1//===- MemCpyOptimizer.cpp - Optimize use of memcpy and friends -----------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This pass performs various transformations related to eliminating memcpy
10// calls, or transforming sets of stores into memset's.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
15#include "llvm/ADT/DenseSet.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/ScopeExit.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/Statistic.h"
20#include "llvm/ADT/iterator_range.h"
21#include "llvm/Analysis/AliasAnalysis.h"
22#include "llvm/Analysis/AssumptionCache.h"
23#include "llvm/Analysis/CFG.h"
24#include "llvm/Analysis/CaptureTracking.h"
25#include "llvm/Analysis/GlobalsModRef.h"
26#include "llvm/Analysis/InstructionSimplify.h"
27#include "llvm/Analysis/Loads.h"
28#include "llvm/Analysis/MemoryLocation.h"
29#include "llvm/Analysis/MemorySSA.h"
30#include "llvm/Analysis/MemorySSAUpdater.h"
31#include "llvm/Analysis/PostDominators.h"
32#include "llvm/Analysis/TargetLibraryInfo.h"
33#include "llvm/Analysis/ValueTracking.h"
34#include "llvm/IR/BasicBlock.h"
35#include "llvm/IR/Constants.h"
36#include "llvm/IR/DataLayout.h"
37#include "llvm/IR/DerivedTypes.h"
38#include "llvm/IR/Dominators.h"
39#include "llvm/IR/Function.h"
40#include "llvm/IR/GlobalVariable.h"
41#include "llvm/IR/IRBuilder.h"
42#include "llvm/IR/InstrTypes.h"
43#include "llvm/IR/Instruction.h"
44#include "llvm/IR/Instructions.h"
45#include "llvm/IR/IntrinsicInst.h"
46#include "llvm/IR/Intrinsics.h"
47#include "llvm/IR/LLVMContext.h"
48#include "llvm/IR/Module.h"
49#include "llvm/IR/PassManager.h"
50#include "llvm/IR/ProfDataUtils.h"
51#include "llvm/IR/Type.h"
52#include "llvm/IR/User.h"
53#include "llvm/IR/Value.h"
54#include "llvm/Support/Casting.h"
55#include "llvm/Support/Debug.h"
56#include "llvm/Support/raw_ostream.h"
57#include "llvm/Transforms/Utils/Local.h"
58#include <algorithm>
59#include <cassert>
60#include <cstdint>
61#include <optional>
62
63using namespace llvm;
64
65#define DEBUG_TYPE "memcpyopt"
66
67static cl::opt<bool> EnableMemCpyOptWithoutLibcalls(
68 "enable-memcpyopt-without-libcalls", cl::Hidden,
69 cl::desc("Enable memcpyopt even when libcalls are disabled"));
70
71STATISTIC(NumMemCpyInstr, "Number of memcpy instructions deleted");
72STATISTIC(NumMemMoveInstr, "Number of memmove instructions deleted");
73STATISTIC(NumMemSetInfer, "Number of memsets inferred");
74STATISTIC(NumMoveToCpy, "Number of memmoves converted to memcpy");
75STATISTIC(NumCpyToSet, "Number of memcpys converted to memset");
76STATISTIC(NumCallSlot, "Number of call slot optimizations performed");
77STATISTIC(NumStackMove, "Number of stack-move optimizations performed");
78
79namespace {
80
81/// Represents a range of memset'd bytes with the ByteVal value.
82/// This allows us to analyze stores like:
83/// store 0 -> P+1
84/// store 0 -> P+0
85/// store 0 -> P+3
86/// store 0 -> P+2
87/// which sometimes happens with stores to arrays of structs etc. When we see
88/// the first store, we make a range [1, 2). The second store extends the range
89/// to [0, 2). The third makes a new range [2, 3). The fourth store joins the
90/// two ranges into [0, 3) which is memset'able.
91struct MemsetRange {
92 // Start/End - A semi range that describes the span that this range covers.
93 // The range is closed at the start and open at the end: [Start, End).
94 int64_t Start, End;
95
96 /// StartPtr - The getelementptr instruction that points to the start of the
97 /// range.
98 Value *StartPtr;
99
100 /// Alignment - The known alignment of the first store.
101 MaybeAlign Alignment;
102
103 /// TheStores - The actual stores that make up this range.
104 SmallVector<Instruction *, 16> TheStores;
105
106 bool isProfitableToUseMemset(const DataLayout &DL) const;
107};
108
109} // end anonymous namespace
110
111static bool overreadUndefContents(MemorySSA *MSSA, MemCpyInst *MemCpy,
112 MemIntrinsic *MemSrc, BatchAAResults &BAA);
113
114bool MemsetRange::isProfitableToUseMemset(const DataLayout &DL) const {
115 // If we found more than 4 stores to merge or 16 bytes, use memset.
116 if (TheStores.size() >= 4 || End - Start >= 16)
117 return true;
118
119 // If there is nothing to merge, don't do anything.
120 if (TheStores.size() < 2)
121 return false;
122
123 // If any of the stores are a memset, then it is always good to extend the
124 // memset.
125 for (Instruction *SI : TheStores)
126 if (!isa<StoreInst>(Val: SI))
127 return true;
128
129 // Assume that the code generator is capable of merging pairs of stores
130 // together if it wants to.
131 if (TheStores.size() == 2)
132 return false;
133
134 // If we have fewer than 8 stores, it can still be worthwhile to do this.
135 // For example, merging 4 i8 stores into an i32 store is useful almost always.
136 // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the
137 // memset will be split into 2 32-bit stores anyway) and doing so can
138 // pessimize the llvm optimizer.
139 //
140 // Since we don't have perfect knowledge here, make some assumptions: assume
141 // the maximum GPR width is the same size as the largest legal integer
142 // size. If so, check to see whether we will end up actually reducing the
143 // number of stores used.
144 unsigned Bytes = unsigned(End - Start);
145 unsigned MaxIntSize = DL.getLargestLegalIntTypeSizeInBits() / 8;
146 if (MaxIntSize == 0)
147 MaxIntSize = 1;
148 unsigned NumPointerStores = Bytes / MaxIntSize;
149
150 // Assume the remaining bytes if any are done a byte at a time.
151 unsigned NumByteStores = Bytes % MaxIntSize;
152
153 // If we will reduce the # stores (according to this heuristic), do the
154 // transformation. This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32
155 // etc.
156 return TheStores.size() > NumPointerStores + NumByteStores;
157}
158
159namespace {
160
161class MemsetRanges {
162 using range_iterator = SmallVectorImpl<MemsetRange>::iterator;
163
164 /// A sorted list of the memset ranges.
165 SmallVector<MemsetRange, 8> Ranges;
166
167 const DataLayout &DL;
168
169public:
170 MemsetRanges(const DataLayout &DL) : DL(DL) {}
171
172 using const_iterator = SmallVectorImpl<MemsetRange>::const_iterator;
173
174 const_iterator begin() const { return Ranges.begin(); }
175 const_iterator end() const { return Ranges.end(); }
176 bool empty() const { return Ranges.empty(); }
177
178 void addInst(int64_t OffsetFromFirst, Instruction *Inst) {
179 if (auto *SI = dyn_cast<StoreInst>(Val: Inst))
180 addStore(OffsetFromFirst, SI);
181 else
182 addMemSet(OffsetFromFirst, MSI: cast<MemSetInst>(Val: Inst));
183 }
184
185 void addStore(int64_t OffsetFromFirst, StoreInst *SI) {
186 TypeSize StoreSize = DL.getTypeStoreSize(Ty: SI->getOperand(i_nocapture: 0)->getType());
187 assert(!StoreSize.isScalable() && "Can't track scalable-typed stores");
188 addRange(Start: OffsetFromFirst, Size: StoreSize.getFixedValue(),
189 Ptr: SI->getPointerOperand(), Alignment: SI->getAlign(), Inst: SI);
190 }
191
192 void addMemSet(int64_t OffsetFromFirst, MemSetInst *MSI) {
193 int64_t Size = cast<ConstantInt>(Val: MSI->getLength())->getZExtValue();
194 addRange(Start: OffsetFromFirst, Size, Ptr: MSI->getDest(), Alignment: MSI->getDestAlign(), Inst: MSI);
195 }
196
197 void addRange(int64_t Start, int64_t Size, Value *Ptr, MaybeAlign Alignment,
198 Instruction *Inst);
199};
200
201} // end anonymous namespace
202
203/// Add a new store to the MemsetRanges data structure. This adds a
204/// new range for the specified store at the specified offset, merging into
205/// existing ranges as appropriate.
206void MemsetRanges::addRange(int64_t Start, int64_t Size, Value *Ptr,
207 MaybeAlign Alignment, Instruction *Inst) {
208 int64_t End = Start + Size;
209
210 range_iterator I = partition_point(
211 Range&: Ranges, P: [=](const MemsetRange &O) { return O.End < Start; });
212
213 // We now know that I == E, in which case we didn't find anything to merge
214 // with, or that Start <= I->End. If End < I->Start or I == E, then we need
215 // to insert a new range. Handle this now.
216 if (I == Ranges.end() || End < I->Start) {
217 MemsetRange &R = *Ranges.insert(I, Elt: MemsetRange());
218 R.Start = Start;
219 R.End = End;
220 R.StartPtr = Ptr;
221 R.Alignment = Alignment;
222 R.TheStores.push_back(Elt: Inst);
223 return;
224 }
225
226 // This store overlaps with I, add it.
227 I->TheStores.push_back(Elt: Inst);
228
229 // At this point, we may have an interval that completely contains our store.
230 // If so, just add it to the interval and return.
231 if (I->Start <= Start && I->End >= End)
232 return;
233
234 // Now we know that Start <= I->End and End >= I->Start so the range overlaps
235 // but is not entirely contained within the range.
236
237 // See if the range extends the start of the range. In this case, it couldn't
238 // possibly cause it to join the prior range, because otherwise we would have
239 // stopped on *it*.
240 if (Start < I->Start) {
241 I->Start = Start;
242 I->StartPtr = Ptr;
243 I->Alignment = Alignment;
244 }
245
246 // Now we know that Start <= I->End and Start >= I->Start (so the startpoint
247 // is in or right at the end of I), and that End >= I->Start. Extend I out to
248 // End.
249 if (End > I->End) {
250 I->End = End;
251 range_iterator NextI = I;
252 while (++NextI != Ranges.end() && End >= NextI->Start) {
253 // Merge the range in.
254 I->TheStores.append(in_start: NextI->TheStores.begin(), in_end: NextI->TheStores.end());
255 if (NextI->End > I->End)
256 I->End = NextI->End;
257 Ranges.erase(CI: NextI);
258 NextI = I;
259 }
260 }
261}
262
263//===----------------------------------------------------------------------===//
264// MemCpyOptLegacyPass Pass
265//===----------------------------------------------------------------------===//
266
267// Check that V is either not accessible by the caller, or unwinding cannot
268// occur between Start and End.
269static bool mayBeVisibleThroughUnwinding(Value *V, Instruction *Start,
270 Instruction *End) {
271 assert(Start->getParent() == End->getParent() && "Must be in same block");
272 // Function can't unwind, so it also can't be visible through unwinding.
273 if (Start->getFunction()->doesNotThrow())
274 return false;
275
276 // Object is not visible on unwind.
277 // TODO: Support RequiresNoCaptureBeforeUnwind case.
278 bool RequiresNoCaptureBeforeUnwind;
279 if (isNotVisibleOnUnwind(Object: getUnderlyingObject(V),
280 RequiresNoCaptureBeforeUnwind) &&
281 !RequiresNoCaptureBeforeUnwind)
282 return false;
283
284 // Check whether there are any unwinding instructions in the range.
285 return any_of(Range: make_range(x: Start->getIterator(), y: End->getIterator()),
286 P: [](const Instruction &I) { return I.mayThrow(); });
287}
288
289void MemCpyOptPass::eraseInstruction(Instruction *I) {
290 MSSAU->removeMemoryAccess(I);
291 EEA->removeInstruction(I);
292 I->eraseFromParent();
293}
294
295// Check for mod or ref of Loc between Start and End, excluding both boundaries.
296// Start and End must be in the same block.
297// If SkippedLifetimeStart is provided, skip over one clobbering lifetime.start
298// intrinsic and store it inside SkippedLifetimeStart.
299static bool accessedBetween(BatchAAResults &AA, MemoryLocation Loc,
300 const MemoryUseOrDef *Start,
301 const MemoryUseOrDef *End,
302 Instruction **SkippedLifetimeStart = nullptr) {
303 assert(Start->getBlock() == End->getBlock() && "Only local supported");
304 for (const MemoryAccess &MA :
305 make_range(x: ++Start->getIterator(), y: End->getIterator())) {
306 Instruction *I = cast<MemoryUseOrDef>(Val: MA).getMemoryInst();
307 if (isModOrRefSet(MRI: AA.getModRefInfo(I, OptLoc: Loc))) {
308 auto *II = dyn_cast<IntrinsicInst>(Val: I);
309 if (II && II->getIntrinsicID() == Intrinsic::lifetime_start &&
310 SkippedLifetimeStart && !*SkippedLifetimeStart) {
311 *SkippedLifetimeStart = I;
312 continue;
313 }
314
315 return true;
316 }
317 }
318 return false;
319}
320
321// Check for mod of Loc between Start and End, excluding both boundaries.
322// Start and End can be in different blocks.
323static bool writtenBetween(MemorySSA *MSSA, BatchAAResults &AA,
324 MemoryLocation Loc, const MemoryUseOrDef *Start,
325 const MemoryUseOrDef *End) {
326 if (isa<MemoryUse>(Val: End)) {
327 // For MemoryUses, getClobberingMemoryAccess may skip non-clobbering writes.
328 // Manually check read accesses between Start and End, if they are in the
329 // same block, for clobbers. Otherwise assume Loc is clobbered.
330 return Start->getBlock() != End->getBlock() ||
331 any_of(
332 Range: make_range(x: std::next(x: Start->getIterator()), y: End->getIterator()),
333 P: [&AA, Loc](const MemoryAccess &Acc) {
334 if (isa<MemoryUse>(Val: &Acc))
335 return false;
336 Instruction *AccInst =
337 cast<MemoryUseOrDef>(Val: &Acc)->getMemoryInst();
338 return isModSet(MRI: AA.getModRefInfo(I: AccInst, OptLoc: Loc));
339 });
340 }
341
342 // TODO: Only walk until we hit Start.
343 MemoryAccess *Clobber = MSSA->getWalker()->getClobberingMemoryAccess(
344 End->getDefiningAccess(), Loc, AA);
345 return !MSSA->dominates(A: Clobber, B: Start);
346}
347
348/// When scanning forward over instructions, we look for some other patterns to
349/// fold away. In particular, this looks for stores to neighboring locations of
350/// memory. If it sees enough consecutive ones, it attempts to merge them
351/// together into a memcpy/memset.
352Instruction *MemCpyOptPass::tryMergingIntoMemset(Instruction *StartInst,
353 Value *StartPtr,
354 Value *ByteVal) {
355 const DataLayout &DL = StartInst->getDataLayout();
356
357 // We can't track scalable types
358 if (auto *SI = dyn_cast<StoreInst>(Val: StartInst))
359 if (DL.getTypeStoreSize(Ty: SI->getOperand(i_nocapture: 0)->getType()).isScalable())
360 return nullptr;
361
362 // Okay, so we now have a single store that can be splatable. Scan to find
363 // all subsequent stores of the same value to offset from the same pointer.
364 // Join these together into ranges, so we can decide whether contiguous blocks
365 // are stored.
366 MemsetRanges Ranges(DL);
367
368 BasicBlock::iterator BI(StartInst);
369
370 // Keeps track of the last memory use or def before the insertion point for
371 // the new memset. The new MemoryDef for the inserted memsets will be inserted
372 // after MemInsertPoint.
373 MemoryUseOrDef *MemInsertPoint = nullptr;
374 for (++BI; !BI->isTerminator(); ++BI) {
375 auto *CurrentAcc =
376 cast_or_null<MemoryUseOrDef>(Val: MSSA->getMemoryAccess(I: &*BI));
377 if (CurrentAcc)
378 MemInsertPoint = CurrentAcc;
379
380 // Calls that only access inaccessible memory do not block merging
381 // accessible stores.
382 if (auto *CB = dyn_cast<CallBase>(Val&: BI)) {
383 if (CB->onlyAccessesInaccessibleMemory())
384 continue;
385 }
386
387 if (!isa<StoreInst>(Val: BI) && !isa<MemSetInst>(Val: BI)) {
388 // If the instruction is readnone, ignore it, otherwise bail out. We
389 // don't even allow readonly here because we don't want something like:
390 // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
391 if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
392 break;
393 continue;
394 }
395
396 if (auto *NextStore = dyn_cast<StoreInst>(Val&: BI)) {
397 // If this is a store, see if we can merge it in.
398 if (!NextStore->isSimple())
399 break;
400
401 Value *StoredVal = NextStore->getValueOperand();
402
403 // Don't convert stores of non-integral pointer types to memsets (which
404 // stores integers).
405 if (DL.isNonIntegralPointerType(Ty: StoredVal->getType()->getScalarType()))
406 break;
407
408 // We can't track ranges involving scalable types.
409 if (DL.getTypeStoreSize(Ty: StoredVal->getType()).isScalable())
410 break;
411
412 // Check to see if this stored value is of the same byte-splattable value.
413 Value *StoredByte = isBytewiseValue(V: StoredVal, DL);
414 if (isa<UndefValue>(Val: ByteVal) && StoredByte)
415 ByteVal = StoredByte;
416 if (ByteVal != StoredByte)
417 break;
418
419 // Check to see if this store is to a constant offset from the start ptr.
420 std::optional<int64_t> Offset =
421 NextStore->getPointerOperand()->getPointerOffsetFrom(Other: StartPtr, DL);
422 if (!Offset)
423 break;
424
425 Ranges.addStore(OffsetFromFirst: *Offset, SI: NextStore);
426 } else {
427 auto *MSI = cast<MemSetInst>(Val&: BI);
428
429 if (MSI->isVolatile() || ByteVal != MSI->getValue() ||
430 !isa<ConstantInt>(Val: MSI->getLength()))
431 break;
432
433 // Check to see if this store is to a constant offset from the start ptr.
434 std::optional<int64_t> Offset =
435 MSI->getDest()->getPointerOffsetFrom(Other: StartPtr, DL);
436 if (!Offset)
437 break;
438
439 Ranges.addMemSet(OffsetFromFirst: *Offset, MSI);
440 }
441 }
442
443 // If we have no ranges, then we just had a single store with nothing that
444 // could be merged in. This is a very common case of course.
445 if (Ranges.empty())
446 return nullptr;
447
448 // If we had at least one store that could be merged in, add the starting
449 // store as well. We try to avoid this unless there is at least something
450 // interesting as a small compile-time optimization.
451 Ranges.addInst(OffsetFromFirst: 0, Inst: StartInst);
452
453 // If we create any memsets, we put it right before the first instruction that
454 // isn't part of the memset block. This ensure that the memset is dominated
455 // by any addressing instruction needed by the start of the block.
456 IRBuilder<> Builder(&*BI);
457
458 // Now that we have full information about ranges, loop over the ranges and
459 // emit memset's for anything big enough to be worthwhile.
460 Instruction *AMemSet = nullptr;
461 for (const MemsetRange &Range : Ranges) {
462 if (Range.TheStores.size() == 1)
463 continue;
464
465 // If it is profitable to lower this range to memset, do so now.
466 if (!Range.isProfitableToUseMemset(DL))
467 continue;
468
469 // Otherwise, we do want to transform this! Create a new memset.
470 // Get the starting pointer of the block.
471 StartPtr = Range.StartPtr;
472
473 AMemSet = Builder.CreateMemSet(Ptr: StartPtr, Val: ByteVal, Size: Range.End - Range.Start,
474 Align: Range.Alignment);
475 AMemSet->mergeDIAssignID(SourceInstructions: Range.TheStores);
476
477 LLVM_DEBUG(dbgs() << "Replace stores:\n"; for (Instruction *SI
478 : Range.TheStores) dbgs()
479 << *SI << '\n';
480 dbgs() << "With: " << *AMemSet << '\n');
481 if (!Range.TheStores.empty())
482 AMemSet->setDebugLoc(Range.TheStores[0]->getDebugLoc());
483
484 auto *NewDef = cast<MemoryDef>(
485 Val: MemInsertPoint->getMemoryInst() == &*BI
486 ? MSSAU->createMemoryAccessBefore(I: AMemSet, Definition: nullptr, InsertPt: MemInsertPoint)
487 : MSSAU->createMemoryAccessAfter(I: AMemSet, Definition: nullptr, InsertPt: MemInsertPoint));
488 MSSAU->insertDef(Def: NewDef, /*RenameUses=*/true);
489 MemInsertPoint = NewDef;
490
491 // Zap all the stores.
492 for (Instruction *SI : Range.TheStores)
493 eraseInstruction(I: SI);
494
495 ++NumMemSetInfer;
496 }
497
498 return AMemSet;
499}
500
501// This method try to lift a store instruction before position P.
502// It will lift the store and its argument + that anything that
503// may alias with these.
504// The method returns true if it was successful.
505bool MemCpyOptPass::moveUp(StoreInst *SI, Instruction *P, const LoadInst *LI) {
506 // If the store alias this position, early bail out.
507 MemoryLocation StoreLoc = MemoryLocation::get(SI);
508 if (isModOrRefSet(MRI: AA->getModRefInfo(I: P, OptLoc: StoreLoc)))
509 return false;
510
511 // Keep track of the arguments of all instruction we plan to lift
512 // so we can make sure to lift them as well if appropriate.
513 DenseSet<Instruction *> Args;
514 auto AddArg = [&](Value *Arg) {
515 auto *I = dyn_cast<Instruction>(Val: Arg);
516 if (I && I->getParent() == SI->getParent()) {
517 // Cannot hoist user of P above P
518 if (I == P)
519 return false;
520 Args.insert(V: I);
521 }
522 return true;
523 };
524 if (!AddArg(SI->getPointerOperand()))
525 return false;
526
527 // Instruction to lift before P.
528 SmallVector<Instruction *, 8> ToLift{SI};
529
530 // Memory locations of lifted instructions.
531 SmallVector<MemoryLocation, 8> MemLocs{StoreLoc};
532
533 // Lifted calls.
534 SmallVector<const CallBase *, 8> Calls;
535
536 const MemoryLocation LoadLoc = MemoryLocation::get(LI);
537
538 for (auto I = --SI->getIterator(), E = P->getIterator(); I != E; --I) {
539 auto *C = &*I;
540
541 // Make sure hoisting does not perform a store that was not guaranteed to
542 // happen.
543 if (!isGuaranteedToTransferExecutionToSuccessor(I: C))
544 return false;
545
546 bool MayAlias = isModOrRefSet(MRI: AA->getModRefInfo(I: C, OptLoc: std::nullopt));
547
548 bool NeedLift = false;
549 if (Args.erase(V: C))
550 NeedLift = true;
551 else if (MayAlias) {
552 NeedLift = llvm::any_of(Range&: MemLocs, P: [C, this](const MemoryLocation &ML) {
553 return isModOrRefSet(MRI: AA->getModRefInfo(I: C, OptLoc: ML));
554 });
555
556 if (!NeedLift)
557 NeedLift = llvm::any_of(Range&: Calls, P: [C, this](const CallBase *Call) {
558 return isModOrRefSet(MRI: AA->getModRefInfo(I: C, Call));
559 });
560 }
561
562 if (!NeedLift)
563 continue;
564
565 if (MayAlias) {
566 // Since LI is implicitly moved downwards past the lifted instructions,
567 // none of them may modify its source.
568 if (isModSet(MRI: AA->getModRefInfo(I: C, OptLoc: LoadLoc)))
569 return false;
570 else if (const auto *Call = dyn_cast<CallBase>(Val: C)) {
571 // If we can't lift this before P, it's game over.
572 if (isModOrRefSet(MRI: AA->getModRefInfo(I: P, Call)))
573 return false;
574
575 Calls.push_back(Elt: Call);
576 } else if (isa<LoadInst>(Val: C) || isa<StoreInst>(Val: C) || isa<VAArgInst>(Val: C)) {
577 // If we can't lift this before P, it's game over.
578 auto ML = MemoryLocation::get(Inst: C);
579 if (isModOrRefSet(MRI: AA->getModRefInfo(I: P, OptLoc: ML)))
580 return false;
581
582 MemLocs.push_back(Elt: ML);
583 } else
584 // We don't know how to lift this instruction.
585 return false;
586 }
587
588 ToLift.push_back(Elt: C);
589 for (Value *Op : C->operands())
590 if (!AddArg(Op))
591 return false;
592 }
593
594 // Find MSSA insertion point. Normally P will always have a corresponding
595 // memory access before which we can insert. However, with non-standard AA
596 // pipelines, there may be a mismatch between AA and MSSA, in which case we
597 // will scan for a memory access before P. In either case, we know for sure
598 // that at least the load will have a memory access.
599 // TODO: Simplify this once P will be determined by MSSA, in which case the
600 // discrepancy can no longer occur.
601 MemoryUseOrDef *MemInsertPoint = nullptr;
602 if (MemoryUseOrDef *MA = MSSA->getMemoryAccess(I: P)) {
603 MemInsertPoint = cast<MemoryUseOrDef>(Val&: --MA->getIterator());
604 } else {
605 const Instruction *ConstP = P;
606 for (const Instruction &I : make_range(x: ++ConstP->getReverseIterator(),
607 y: ++LI->getReverseIterator())) {
608 if (MemoryUseOrDef *MA = MSSA->getMemoryAccess(I: &I)) {
609 MemInsertPoint = MA;
610 break;
611 }
612 }
613 }
614
615 // We made it, we need to lift.
616 for (auto *I : llvm::reverse(C&: ToLift)) {
617 LLVM_DEBUG(dbgs() << "Lifting " << *I << " before " << *P << "\n");
618 I->moveBefore(InsertPos: P->getIterator());
619 assert(MemInsertPoint && "Must have found insert point");
620 if (MemoryUseOrDef *MA = MSSA->getMemoryAccess(I)) {
621 MSSAU->moveAfter(What: MA, Where: MemInsertPoint);
622 MemInsertPoint = MA;
623 }
624 }
625
626 return true;
627}
628
629bool MemCpyOptPass::processStoreOfLoad(StoreInst *SI, LoadInst *LI,
630 const DataLayout &DL,
631 BasicBlock::iterator &BBI) {
632 if (!LI->isSimple() || !LI->hasOneUse() || LI->getParent() != SI->getParent())
633 return false;
634
635 BatchAAResults BAA(*AA, EEA);
636 auto *T = LI->getType();
637 // Don't introduce calls to memcpy/memmove intrinsics out of thin air if
638 // the corresponding libcalls are not available.
639 // TODO: We should really distinguish between libcall availability and
640 // our ability to introduce intrinsics.
641 if (T->isAggregateType() &&
642 (EnableMemCpyOptWithoutLibcalls ||
643 (TLI->has(F: LibFunc_memcpy) && TLI->has(F: LibFunc_memmove)))) {
644 MemoryLocation LoadLoc = MemoryLocation::get(LI);
645
646 // We use alias analysis to check if an instruction may store to
647 // the memory we load from in between the load and the store. If
648 // such an instruction is found, we try to promote there instead
649 // of at the store position.
650 // TODO: Can use MSSA for this.
651 Instruction *P = SI;
652 for (auto &I : make_range(x: ++LI->getIterator(), y: SI->getIterator())) {
653 if (isModSet(MRI: BAA.getModRefInfo(I: &I, OptLoc: LoadLoc))) {
654 P = &I;
655 break;
656 }
657 }
658
659 // If we found an instruction that may write to the loaded memory,
660 // we can try to promote at this position instead of the store
661 // position if nothing aliases the store memory after this and the store
662 // destination is not in the range.
663 if (P == SI || moveUp(SI, P, LI)) {
664 // If we load from memory that may alias the memory we store to,
665 // memmove must be used to preserve semantic. If not, memcpy can
666 // be used. Also, if we load from constant memory, memcpy can be used
667 // as the constant memory won't be modified.
668 bool UseMemMove = false;
669 if (isModSet(MRI: AA->getModRefInfo(I: SI, OptLoc: LoadLoc)))
670 UseMemMove = true;
671
672 IRBuilder<> Builder(P);
673 Value *Size =
674 Builder.CreateTypeSize(Ty: Builder.getInt64Ty(), Size: DL.getTypeStoreSize(Ty: T));
675 Instruction *M;
676 if (UseMemMove)
677 M = Builder.CreateMemMove(Dst: SI->getPointerOperand(), DstAlign: SI->getAlign(),
678 Src: LI->getPointerOperand(), SrcAlign: LI->getAlign(),
679 Size);
680 else
681 M = Builder.CreateMemCpy(Dst: SI->getPointerOperand(), DstAlign: SI->getAlign(),
682 Src: LI->getPointerOperand(), SrcAlign: LI->getAlign(), Size);
683 M->copyMetadata(SrcInst: *SI, WL: LLVMContext::MD_DIAssignID);
684
685 LLVM_DEBUG(dbgs() << "Promoting " << *LI << " to " << *SI << " => " << *M
686 << "\n");
687
688 auto *LastDef = cast<MemoryDef>(Val: MSSA->getMemoryAccess(I: SI));
689 auto *NewAccess = MSSAU->createMemoryAccessAfter(I: M, Definition: nullptr, InsertPt: LastDef);
690 MSSAU->insertDef(Def: cast<MemoryDef>(Val: NewAccess), /*RenameUses=*/true);
691
692 eraseInstruction(I: SI);
693 eraseInstruction(I: LI);
694 ++NumMemCpyInstr;
695
696 // Make sure we do not invalidate the iterator.
697 BBI = M->getIterator();
698 return true;
699 }
700 }
701
702 // Detect cases where we're performing call slot forwarding, but
703 // happen to be using a load-store pair to implement it, rather than
704 // a memcpy.
705 auto GetCall = [&]() -> CallInst * {
706 // We defer this expensive clobber walk until the cheap checks
707 // have been done on the source inside performCallSlotOptzn.
708 if (auto *LoadClobber = dyn_cast<MemoryUseOrDef>(
709 Val: MSSA->getWalker()->getClobberingMemoryAccess(I: LI, AA&: BAA)))
710 return dyn_cast_or_null<CallInst>(Val: LoadClobber->getMemoryInst());
711 return nullptr;
712 };
713
714 bool Changed = performCallSlotOptzn(
715 cpyLoad: LI, cpyStore: SI, cpyDst: SI->getPointerOperand()->stripPointerCasts(),
716 cpySrc: LI->getPointerOperand()->stripPointerCasts(),
717 cpyLen: DL.getTypeStoreSize(Ty: SI->getOperand(i_nocapture: 0)->getType()),
718 cpyAlign: std::min(a: SI->getAlign(), b: LI->getAlign()), BAA, GetC: GetCall);
719 if (Changed) {
720 eraseInstruction(I: SI);
721 eraseInstruction(I: LI);
722 ++NumMemCpyInstr;
723 return true;
724 }
725
726 // If this is a load-store pair from a stack slot to a stack slot, we
727 // might be able to perform the stack-move optimization just as we do for
728 // memcpys from an alloca to an alloca.
729 if (auto *DestAlloca = dyn_cast<AllocaInst>(Val: SI->getPointerOperand())) {
730 if (auto *SrcAlloca = dyn_cast<AllocaInst>(Val: LI->getPointerOperand())) {
731 if (performStackMoveOptzn(Load: LI, Store: SI, DestAlloca, SrcAlloca,
732 Size: DL.getTypeStoreSize(Ty: T), BAA)) {
733 // Avoid invalidating the iterator.
734 BBI = SI->getNextNode()->getIterator();
735 eraseInstruction(I: SI);
736 eraseInstruction(I: LI);
737 ++NumMemCpyInstr;
738 return true;
739 }
740 }
741 }
742
743 return false;
744}
745
746bool MemCpyOptPass::processStore(StoreInst *SI, BasicBlock::iterator &BBI) {
747 if (!SI->isSimple())
748 return false;
749
750 // Avoid merging nontemporal stores since the resulting
751 // memcpy/memset would not be able to preserve the nontemporal hint.
752 // In theory we could teach how to propagate the !nontemporal metadata to
753 // memset calls. However, that change would force the backend to
754 // conservatively expand !nontemporal memset calls back to sequences of
755 // store instructions (effectively undoing the merging).
756 if (SI->getMetadata(KindID: LLVMContext::MD_nontemporal))
757 return false;
758
759 const DataLayout &DL = SI->getDataLayout();
760
761 Value *StoredVal = SI->getValueOperand();
762
763 // Not all the transforms below are correct for non-integral pointers, bail
764 // until we've audited the individual pieces.
765 if (DL.isNonIntegralPointerType(Ty: StoredVal->getType()->getScalarType()))
766 return false;
767
768 // Load to store forwarding can be interpreted as memcpy.
769 if (auto *LI = dyn_cast<LoadInst>(Val: StoredVal))
770 return processStoreOfLoad(SI, LI, DL, BBI);
771
772 // The following code creates memset intrinsics out of thin air. Don't do
773 // this if the corresponding libfunc is not available.
774 // TODO: We should really distinguish between libcall availability and
775 // our ability to introduce intrinsics.
776 if (!(TLI->has(F: LibFunc_memset) || EnableMemCpyOptWithoutLibcalls))
777 return false;
778
779 // There are two cases that are interesting for this code to handle: memcpy
780 // and memset. Right now we only handle memset.
781
782 // Ensure that the value being stored is something that can be memset'able a
783 // byte at a time like "0" or "-1" or any width, as well as things like
784 // 0xA0A0A0A0 and 0.0.
785 Value *V = SI->getOperand(i_nocapture: 0);
786 Value *ByteVal = isBytewiseValue(V, DL);
787 if (!ByteVal)
788 return false;
789
790 if (Instruction *I =
791 tryMergingIntoMemset(StartInst: SI, StartPtr: SI->getPointerOperand(), ByteVal)) {
792 BBI = I->getIterator(); // Don't invalidate iterator.
793 return true;
794 }
795
796 // If we have an aggregate, we try to promote it to memset regardless
797 // of opportunity for merging as it can expose optimization opportunities
798 // in subsequent passes.
799 auto *T = V->getType();
800 if (!T->isAggregateType())
801 return false;
802
803 TypeSize Size = DL.getTypeStoreSize(Ty: T);
804 if (Size.isScalable())
805 return false;
806
807 IRBuilder<> Builder(SI);
808 auto *M = Builder.CreateMemSet(Ptr: SI->getPointerOperand(), Val: ByteVal, Size,
809 Align: SI->getAlign());
810 M->copyMetadata(SrcInst: *SI, WL: LLVMContext::MD_DIAssignID);
811
812 LLVM_DEBUG(dbgs() << "Promoting " << *SI << " to " << *M << "\n");
813
814 // The newly inserted memset is immediately overwritten by the original
815 // store, so we do not need to rename uses.
816 auto *StoreDef = cast<MemoryDef>(Val: MSSA->getMemoryAccess(I: SI));
817 auto *NewAccess = MSSAU->createMemoryAccessBefore(I: M, Definition: nullptr, InsertPt: StoreDef);
818 MSSAU->insertDef(Def: cast<MemoryDef>(Val: NewAccess), /*RenameUses=*/false);
819
820 eraseInstruction(I: SI);
821 NumMemSetInfer++;
822
823 // Make sure we do not invalidate the iterator.
824 BBI = M->getIterator();
825 return true;
826}
827
828bool MemCpyOptPass::processMemSet(MemSetInst *MSI, BasicBlock::iterator &BBI) {
829 // See if there is another memset or store neighboring this memset which
830 // allows us to widen out the memset to do a single larger store.
831 if (isa<ConstantInt>(Val: MSI->getLength()) && !MSI->isVolatile())
832 if (Instruction *I =
833 tryMergingIntoMemset(StartInst: MSI, StartPtr: MSI->getDest(), ByteVal: MSI->getValue())) {
834 BBI = I->getIterator(); // Don't invalidate iterator.
835 return true;
836 }
837 return false;
838}
839
840/// Takes a memcpy and a call that it depends on,
841/// and checks for the possibility of a call slot optimization by having
842/// the call write its result directly into the destination of the memcpy.
843bool MemCpyOptPass::performCallSlotOptzn(Instruction *cpyLoad,
844 Instruction *cpyStore, Value *cpyDest,
845 Value *cpySrc, TypeSize cpySize,
846 Align cpyDestAlign,
847 BatchAAResults &BAA,
848 std::function<CallInst *()> GetC) {
849 // The general transformation to keep in mind is
850 //
851 // call @func(..., src, ...)
852 // memcpy(dest, src, ...)
853 //
854 // ->
855 //
856 // memcpy(dest, src, ...)
857 // call @func(..., dest, ...)
858 //
859 // Since moving the memcpy is technically awkward, we additionally check that
860 // src only holds uninitialized values at the moment of the call, meaning that
861 // the memcpy can be discarded rather than moved.
862
863 // We can't optimize scalable types.
864 if (cpySize.isScalable())
865 return false;
866
867 // Require that src be an alloca. This simplifies the reasoning considerably.
868 auto *srcAlloca = dyn_cast<AllocaInst>(Val: cpySrc);
869 if (!srcAlloca)
870 return false;
871
872 const DataLayout &DL = cpyLoad->getDataLayout();
873 // We can't optimize scalable types or variable-length allocas.
874 std::optional<TypeSize> SrcAllocaSize = srcAlloca->getAllocationSize(DL);
875 if (!SrcAllocaSize || SrcAllocaSize->isScalable())
876 return false;
877 uint64_t srcSize = SrcAllocaSize->getFixedValue();
878
879 if (cpySize < srcSize)
880 return false;
881
882 CallInst *C = GetC();
883 if (!C)
884 return false;
885
886 // Lifetime marks shouldn't be operated on.
887 if (Function *F = C->getCalledFunction())
888 if (F->isIntrinsic() && F->getIntrinsicID() == Intrinsic::lifetime_start)
889 return false;
890
891 if (C->getParent() != cpyStore->getParent()) {
892 LLVM_DEBUG(dbgs() << "Call Slot: block local restriction\n");
893 return false;
894 }
895
896 MemoryLocation DestLoc =
897 isa<StoreInst>(Val: cpyStore)
898 ? MemoryLocation::get(Inst: cpyStore)
899 : MemoryLocation::getForDest(MI: cast<MemCpyInst>(Val: cpyStore));
900
901 // Check that nothing touches the dest of the copy between
902 // the call and the store/memcpy.
903 Instruction *SkippedLifetimeStart = nullptr;
904 if (accessedBetween(AA&: BAA, Loc: DestLoc, Start: MSSA->getMemoryAccess(I: C),
905 End: MSSA->getMemoryAccess(I: cpyStore), SkippedLifetimeStart: &SkippedLifetimeStart)) {
906 LLVM_DEBUG(dbgs() << "Call Slot: Dest pointer modified after call\n");
907 return false;
908 }
909
910 // If we need to move a lifetime.start above the call, make sure that we can
911 // actually do so. If the argument is bitcasted for example, we would have to
912 // move the bitcast as well, which we don't handle.
913 if (SkippedLifetimeStart) {
914 auto *LifetimeArg =
915 dyn_cast<Instruction>(Val: SkippedLifetimeStart->getOperand(i: 0));
916 if (LifetimeArg && LifetimeArg->getParent() == C->getParent() &&
917 C->comesBefore(Other: LifetimeArg))
918 return false;
919 }
920
921 // Check that storing to the first srcSize bytes of dest will not cause a
922 // trap or data race.
923 bool ExplicitlyDereferenceableOnly;
924 if (!isWritableObject(Object: getUnderlyingObject(V: cpyDest),
925 ExplicitlyDereferenceableOnly) ||
926 !isDereferenceableAndAlignedPointer(V: cpyDest, Alignment: Align(1), Size: APInt(64, cpySize),
927 DL, CtxI: C, AC, DT)) {
928 LLVM_DEBUG(dbgs() << "Call Slot: Dest pointer not dereferenceable\n");
929 return false;
930 }
931
932 // Make sure that nothing can observe cpyDest being written early. There are
933 // a number of cases to consider:
934 // 1. cpyDest cannot be accessed between C and cpyStore as a precondition of
935 // the transform.
936 // 2. C itself may not access cpyDest (prior to the transform). This is
937 // checked further below.
938 // 3. If cpyDest is accessible to the caller of this function (potentially
939 // captured and not based on an alloca), we need to ensure that we cannot
940 // unwind between C and cpyStore. This is checked here.
941 // 4. If cpyDest is potentially captured, there may be accesses to it from
942 // another thread. In this case, we need to check that cpyStore is
943 // guaranteed to be executed if C is. As it is a non-atomic access, it
944 // renders accesses from other threads undefined.
945 // TODO: This is currently not checked.
946 if (mayBeVisibleThroughUnwinding(V: cpyDest, Start: C, End: cpyStore)) {
947 LLVM_DEBUG(dbgs() << "Call Slot: Dest may be visible through unwinding\n");
948 return false;
949 }
950
951 // Check that dest points to memory that is at least as aligned as src.
952 Align srcAlign = srcAlloca->getAlign();
953 bool isDestSufficientlyAligned = srcAlign <= cpyDestAlign;
954 // If dest is not aligned enough and we can't increase its alignment then
955 // bail out.
956 if (!isDestSufficientlyAligned && !isa<AllocaInst>(Val: cpyDest)) {
957 LLVM_DEBUG(dbgs() << "Call Slot: Dest not sufficiently aligned\n");
958 return false;
959 }
960
961 // Check that src is not accessed except via the call and the memcpy. This
962 // guarantees that it holds only undefined values when passed in (so the final
963 // memcpy can be dropped), that it is not read or written between the call and
964 // the memcpy, and that writing beyond the end of it is undefined.
965 SmallVector<User *, 8> srcUseList(srcAlloca->users());
966 while (!srcUseList.empty()) {
967 User *U = srcUseList.pop_back_val();
968
969 if (isa<AddrSpaceCastInst>(Val: U)) {
970 append_range(C&: srcUseList, R: U->users());
971 continue;
972 }
973 if (isa<LifetimeIntrinsic>(Val: U))
974 continue;
975
976 if (U != C && U != cpyLoad) {
977 LLVM_DEBUG(dbgs() << "Call slot: Source accessed by " << *U << "\n");
978 return false;
979 }
980 }
981
982 // Check whether src is captured by the called function, in which case there
983 // may be further indirect uses of src.
984 bool SrcIsCaptured = any_of(Range: C->args(), P: [&](Use &U) {
985 return U->stripPointerCasts() == cpySrc &&
986 !C->doesNotCapture(OpNo: C->getArgOperandNo(U: &U));
987 });
988
989 // If src is captured, then check whether there are any potential uses of
990 // src through the captured pointer before the lifetime of src ends, either
991 // due to a lifetime.end or a return from the function.
992 if (SrcIsCaptured) {
993 // Check that dest is not captured before/at the call. We have already
994 // checked that src is not captured before it. If either had been captured,
995 // then the call might be comparing the argument against the captured dest
996 // or src pointer.
997 Value *DestObj = getUnderlyingObject(V: cpyDest);
998 if (!isIdentifiedFunctionLocal(V: DestObj) ||
999 PointerMayBeCapturedBefore(V: DestObj, /* ReturnCaptures */ true, I: C, DT,
1000 /* IncludeI */ true))
1001 return false;
1002
1003 MemoryLocation SrcLoc =
1004 MemoryLocation(srcAlloca, LocationSize::precise(Value: srcSize));
1005 for (Instruction &I :
1006 make_range(x: ++C->getIterator(), y: C->getParent()->end())) {
1007 // Lifetime of srcAlloca ends at lifetime.end.
1008 if (auto *II = dyn_cast<IntrinsicInst>(Val: &I)) {
1009 if (II->getIntrinsicID() == Intrinsic::lifetime_end &&
1010 II->getArgOperand(i: 0) == srcAlloca)
1011 break;
1012 }
1013
1014 // Lifetime of srcAlloca ends at return.
1015 if (isa<ReturnInst>(Val: &I))
1016 break;
1017
1018 // Ignore the direct read of src in the load.
1019 if (&I == cpyLoad)
1020 continue;
1021
1022 // Check whether this instruction may mod/ref src through the captured
1023 // pointer (we have already any direct mod/refs in the loop above).
1024 // Also bail if we hit a terminator, as we don't want to scan into other
1025 // blocks.
1026 if (isModOrRefSet(MRI: BAA.getModRefInfo(I: &I, OptLoc: SrcLoc)) || I.isTerminator())
1027 return false;
1028 }
1029 }
1030
1031 // Since we're changing the parameter to the callsite, we need to make sure
1032 // that what would be the new parameter dominates the callsite.
1033 bool NeedMoveGEP = false;
1034 if (!DT->dominates(Def: cpyDest, User: C)) {
1035 // Support moving a constant index GEP before the call.
1036 auto *GEP = dyn_cast<GetElementPtrInst>(Val: cpyDest);
1037 if (GEP && GEP->hasAllConstantIndices() &&
1038 DT->dominates(Def: GEP->getPointerOperand(), User: C))
1039 NeedMoveGEP = true;
1040 else
1041 return false;
1042 }
1043
1044 // In addition to knowing that the call does not access src in some
1045 // unexpected manner, for example via a global, which we deduce from
1046 // the use analysis, we also need to know that it does not sneakily
1047 // access dest. We rely on AA to figure this out for us.
1048 MemoryLocation DestWithSrcSize(cpyDest, LocationSize::precise(Value: srcSize));
1049 ModRefInfo MR = BAA.getModRefInfo(I: C, OptLoc: DestWithSrcSize);
1050 // If necessary, perform additional analysis.
1051 if (isModOrRefSet(MRI: MR))
1052 MR = BAA.callCapturesBefore(I: C, MemLoc: DestWithSrcSize, DT);
1053 if (isModOrRefSet(MRI: MR))
1054 return false;
1055
1056 // We can't create address space casts here because we don't know if they're
1057 // safe for the target.
1058 if (cpySrc->getType() != cpyDest->getType())
1059 return false;
1060 for (unsigned ArgI = 0; ArgI < C->arg_size(); ++ArgI)
1061 if (C->getArgOperand(i: ArgI)->stripPointerCasts() == cpySrc &&
1062 cpySrc->getType() != C->getArgOperand(i: ArgI)->getType())
1063 return false;
1064
1065 // All the checks have passed, so do the transformation.
1066 bool changedArgument = false;
1067 for (unsigned ArgI = 0; ArgI < C->arg_size(); ++ArgI)
1068 if (C->getArgOperand(i: ArgI)->stripPointerCasts() == cpySrc) {
1069 changedArgument = true;
1070 C->setArgOperand(i: ArgI, v: cpyDest);
1071 }
1072
1073 if (!changedArgument)
1074 return false;
1075
1076 // If the destination wasn't sufficiently aligned then increase its alignment.
1077 if (!isDestSufficientlyAligned) {
1078 assert(isa<AllocaInst>(cpyDest) && "Can only increase alloca alignment!");
1079 cast<AllocaInst>(Val: cpyDest)->setAlignment(srcAlign);
1080 }
1081
1082 if (NeedMoveGEP) {
1083 auto *GEP = dyn_cast<GetElementPtrInst>(Val: cpyDest);
1084 GEP->moveBefore(InsertPos: C->getIterator());
1085 }
1086
1087 if (SkippedLifetimeStart) {
1088 SkippedLifetimeStart->moveBefore(InsertPos: C->getIterator());
1089 MSSAU->moveBefore(What: MSSA->getMemoryAccess(I: SkippedLifetimeStart),
1090 Where: MSSA->getMemoryAccess(I: C));
1091 }
1092
1093 combineAAMetadata(K: C, J: cpyLoad);
1094 if (cpyLoad != cpyStore)
1095 combineAAMetadata(K: C, J: cpyStore);
1096
1097 ++NumCallSlot;
1098 return true;
1099}
1100
1101/// We've found that the (upward scanning) memory dependence of memcpy 'M' is
1102/// the memcpy 'MDep'. Try to simplify M to copy from MDep's input if we can.
1103bool MemCpyOptPass::processMemCpyMemCpyDependence(MemCpyInst *M,
1104 MemCpyInst *MDep,
1105 BatchAAResults &BAA) {
1106 // We can only optimize non-volatile memcpy's.
1107 if (MDep->isVolatile())
1108 return false;
1109
1110 // If dep instruction is reading from our current input, then it is a noop
1111 // transfer and substituting the input won't change this instruction. Just
1112 // ignore the input and let someone else zap MDep. This handles cases like:
1113 // memcpy(a <- a)
1114 // memcpy(b <- a)
1115 // This also avoids infinite loops.
1116 if (BAA.isMustAlias(V1: MDep->getDest(), V2: MDep->getSource()))
1117 return false;
1118
1119 int64_t MForwardOffset = 0;
1120 const DataLayout &DL = M->getModule()->getDataLayout();
1121 // We can only transforms memcpy's where the dest of one is the source of the
1122 // other, or they have an offset in a range.
1123 if (M->getSource() != MDep->getDest()) {
1124 std::optional<int64_t> Offset =
1125 M->getSource()->getPointerOffsetFrom(Other: MDep->getDest(), DL);
1126 if (!Offset || *Offset < 0)
1127 return false;
1128 MForwardOffset = *Offset;
1129 }
1130
1131 Value *CopyLength = M->getLength();
1132
1133 // The length of the memcpy's must be the same, or the preceding one must be
1134 // larger than the following one, or the contents of the overread must be
1135 // undefined bytes of a defined size.
1136 if (MForwardOffset != 0 || MDep->getLength() != CopyLength) {
1137 auto *MDepLen = dyn_cast<ConstantInt>(Val: MDep->getLength());
1138 auto *MLen = dyn_cast<ConstantInt>(Val: CopyLength);
1139 // This could be converted to a runtime test (%CopyLength =
1140 // min(max(0, MDepLen - MForwardOffset), MLen)), but it is
1141 // unclear if that is useful
1142 if (!MDepLen || !MLen)
1143 return false;
1144 if (MDepLen->getZExtValue() < MLen->getZExtValue() + MForwardOffset) {
1145 if (!overreadUndefContents(MSSA, MemCpy: M, MemSrc: MDep, BAA))
1146 return false;
1147 if (MDepLen->getZExtValue() <= (uint64_t)MForwardOffset)
1148 return false; // Should not reach here (there is obviously no aliasing
1149 // with MDep), so just bail in case it had incomplete info
1150 // somehow
1151 CopyLength = ConstantInt::get(Ty: CopyLength->getType(),
1152 V: MDepLen->getZExtValue() - MForwardOffset);
1153 }
1154 }
1155
1156 IRBuilder<> Builder(M);
1157 auto *CopySource = MDep->getSource();
1158 Instruction *NewCopySource = nullptr;
1159 llvm::scope_exit CleanupOnRet([&] {
1160 if (NewCopySource && NewCopySource->use_empty())
1161 // Safety: It's safe here because we will only allocate more instructions
1162 // after finishing all BatchAA queries, but we have to be careful if we
1163 // want to do something like this in another place. Then we'd probably
1164 // have to delay instruction removal until all transforms on an
1165 // instruction finished.
1166 eraseInstruction(I: NewCopySource);
1167 });
1168 MaybeAlign CopySourceAlign = MDep->getSourceAlign();
1169 auto MCopyLoc = MemoryLocation::getForSource(MTI: MDep);
1170 // Truncate the size of the MDep access to just the bytes read
1171 if (MDep->getLength() != CopyLength) {
1172 auto *ConstLength = cast<ConstantInt>(Val: CopyLength);
1173 MCopyLoc = MCopyLoc.getWithNewSize(
1174 NewSize: LocationSize::precise(Value: ConstLength->getZExtValue()));
1175 }
1176
1177 // When the forwarding offset is greater than 0, we transform
1178 // memcpy(d1 <- s1)
1179 // memcpy(d2 <- d1+o)
1180 // to
1181 // memcpy(d2 <- s1+o)
1182 if (MForwardOffset > 0) {
1183 // The copy destination of `M` maybe can serve as the source of copying.
1184 std::optional<int64_t> MDestOffset =
1185 M->getRawDest()->getPointerOffsetFrom(Other: MDep->getRawSource(), DL);
1186 if (MDestOffset == MForwardOffset)
1187 CopySource = M->getDest();
1188 else {
1189 CopySource = Builder.CreateInBoundsPtrAdd(
1190 Ptr: CopySource, Offset: Builder.getInt64(C: MForwardOffset));
1191 NewCopySource = dyn_cast<Instruction>(Val: CopySource);
1192 }
1193 // We need to update `MCopyLoc` if an offset exists.
1194 MCopyLoc = MCopyLoc.getWithNewPtr(NewPtr: CopySource);
1195 if (CopySourceAlign)
1196 CopySourceAlign = commonAlignment(A: *CopySourceAlign, Offset: MForwardOffset);
1197 }
1198
1199 // Verify that the copied-from memory doesn't change in between the two
1200 // transfers. For example, in:
1201 // memcpy(a <- b)
1202 // *b = 42;
1203 // memcpy(c <- a)
1204 // It would be invalid to transform the second memcpy into memcpy(c <- b).
1205 //
1206 // TODO: If the code between M and MDep is transparent to the destination "c",
1207 // then we could still perform the xform by moving M up to the first memcpy.
1208 if (writtenBetween(MSSA, AA&: BAA, Loc: MCopyLoc, Start: MSSA->getMemoryAccess(I: MDep),
1209 End: MSSA->getMemoryAccess(I: M)))
1210 return false;
1211
1212 // No need to create `memcpy(a <- a)`.
1213 if (BAA.isMustAlias(V1: M->getDest(), V2: CopySource)) {
1214 // Remove the instruction we're replacing.
1215 eraseInstruction(I: M);
1216 ++NumMemCpyInstr;
1217 return true;
1218 }
1219
1220 // If the dest of the second might alias the source of the first, then the
1221 // source and dest might overlap. In addition, if the source of the first
1222 // points to constant memory, they won't overlap by definition. Otherwise, we
1223 // still want to eliminate the intermediate value, but we have to generate a
1224 // memmove instead of memcpy.
1225 bool UseMemMove = false;
1226 if (isModSet(MRI: BAA.getModRefInfo(I: M, OptLoc: MemoryLocation::getForSource(MTI: MDep)))) {
1227 // Don't convert llvm.memcpy.inline into memmove because memmove can be
1228 // lowered as a call, and that is not allowed for llvm.memcpy.inline (and
1229 // there is no inline version of llvm.memmove)
1230 if (M->isForceInlined())
1231 return false;
1232 UseMemMove = true;
1233 }
1234
1235 // If all checks passed, then we can transform M.
1236 LLVM_DEBUG(dbgs() << "MemCpyOptPass: Forwarding memcpy->memcpy src:\n"
1237 << *MDep << '\n'
1238 << *M << '\n');
1239
1240 // TODO: Is this worth it if we're creating a less aligned memcpy? For
1241 // example we could be moving from movaps -> movq on x86.
1242 Instruction *NewM;
1243 if (UseMemMove)
1244 NewM = Builder.CreateMemMove(Dst: M->getDest(), DstAlign: M->getDestAlign(), Src: CopySource,
1245 SrcAlign: CopySourceAlign, Size: CopyLength, isVolatile: M->isVolatile());
1246 else if (M->isForceInlined())
1247 // llvm.memcpy may be promoted to llvm.memcpy.inline, but the converse is
1248 // never allowed since that would allow the latter to be lowered as a call
1249 // to an external function.
1250 NewM = Builder.CreateMemCpyInline(Dst: M->getDest(), DstAlign: M->getDestAlign(),
1251 Src: CopySource, SrcAlign: CopySourceAlign, Size: CopyLength,
1252 isVolatile: M->isVolatile());
1253 else
1254 NewM = Builder.CreateMemCpy(Dst: M->getDest(), DstAlign: M->getDestAlign(), Src: CopySource,
1255 SrcAlign: CopySourceAlign, Size: CopyLength, isVolatile: M->isVolatile());
1256
1257 NewM->copyMetadata(SrcInst: *M, WL: LLVMContext::MD_DIAssignID);
1258
1259 assert(isa<MemoryDef>(MSSA->getMemoryAccess(M)));
1260 auto *LastDef = cast<MemoryDef>(Val: MSSA->getMemoryAccess(I: M));
1261 auto *NewAccess = MSSAU->createMemoryAccessAfter(I: NewM, Definition: nullptr, InsertPt: LastDef);
1262 MSSAU->insertDef(Def: cast<MemoryDef>(Val: NewAccess), /*RenameUses=*/true);
1263
1264 // Remove the instruction we're replacing.
1265 eraseInstruction(I: M);
1266 ++NumMemCpyInstr;
1267 return true;
1268}
1269
1270/// We've found that the (upward scanning) memory dependence of \p MemCpy is
1271/// \p MemSet. Try to simplify \p MemSet to only set the trailing bytes that
1272/// weren't copied over by \p MemCpy.
1273///
1274/// In other words, transform:
1275/// \code
1276/// memset(dst, c, dst_size);
1277/// ...
1278/// memcpy(dst, src, src_size);
1279/// \endcode
1280/// into:
1281/// \code
1282/// ...
1283/// memset(dst + src_size, c, dst_size <= src_size ? 0 : dst_size - src_size);
1284/// memcpy(dst, src, src_size);
1285/// \endcode
1286///
1287/// The memset is sunk to just before the memcpy to ensure that src_size is
1288/// present when emitting the simplified memset.
1289bool MemCpyOptPass::processMemSetMemCpyDependence(MemCpyInst *MemCpy,
1290 MemSetInst *MemSet,
1291 BatchAAResults &BAA) {
1292 // We can only transform memset/memcpy with the same destination.
1293 if (!BAA.isMustAlias(V1: MemSet->getDest(), V2: MemCpy->getDest()))
1294 return false;
1295
1296 // Don't perform the transform if src_size may be zero. In that case, the
1297 // transform is essentially a complex no-op and may lead to an infinite
1298 // loop if BasicAA is smart enough to understand that dst and dst + src_size
1299 // are still MustAlias after the transform.
1300 Value *SrcSize = MemCpy->getLength();
1301 if (!isKnownNonZero(V: SrcSize,
1302 Q: SimplifyQuery(MemCpy->getDataLayout(), DT, AC, MemCpy)))
1303 return false;
1304
1305 // Check that src and dst of the memcpy aren't the same. While memcpy
1306 // operands cannot partially overlap, exact equality is allowed.
1307 if (isModSet(MRI: BAA.getModRefInfo(I: MemCpy, OptLoc: MemoryLocation::getForSource(MTI: MemCpy))))
1308 return false;
1309
1310 // We know that dst up to src_size is not written. We now need to make sure
1311 // that dst up to dst_size is not accessed. (If we did not move the memset,
1312 // checking for reads would be sufficient.)
1313 if (accessedBetween(AA&: BAA, Loc: MemoryLocation::getForDest(MI: MemSet),
1314 Start: MSSA->getMemoryAccess(I: MemSet),
1315 End: MSSA->getMemoryAccess(I: MemCpy)))
1316 return false;
1317
1318 // Use the same i8* dest as the memcpy, killing the memset dest if different.
1319 Value *Dest = MemCpy->getRawDest();
1320 Value *DestSize = MemSet->getLength();
1321
1322 if (mayBeVisibleThroughUnwinding(V: Dest, Start: MemSet, End: MemCpy))
1323 return false;
1324
1325 // If the sizes are the same, simply drop the memset instead of generating
1326 // a replacement with zero size.
1327 if (DestSize == SrcSize) {
1328 eraseInstruction(I: MemSet);
1329 return true;
1330 }
1331
1332 // By default, create an unaligned memset.
1333 Align Alignment = Align(1);
1334 // If Dest is aligned, and SrcSize is constant, use the minimum alignment
1335 // of the sum.
1336 const Align DestAlign = std::max(a: MemSet->getDestAlign().valueOrOne(),
1337 b: MemCpy->getDestAlign().valueOrOne());
1338 if (DestAlign > 1)
1339 if (auto *SrcSizeC = dyn_cast<ConstantInt>(Val: SrcSize))
1340 Alignment = commonAlignment(A: DestAlign, Offset: SrcSizeC->getZExtValue());
1341
1342 IRBuilder<> Builder(MemCpy);
1343
1344 // Preserve the debug location of the old memset for the code emitted here
1345 // related to the new memset. This is correct according to the rules in
1346 // https://llvm.org/docs/HowToUpdateDebugInfo.html about "when to preserve an
1347 // instruction location", given that we move the memset within the basic
1348 // block.
1349 assert(MemSet->getParent() == MemCpy->getParent() &&
1350 "Preserving debug location based on moving memset within BB.");
1351 Builder.SetCurrentDebugLocation(MemSet->getDebugLoc());
1352
1353 // If the sizes have different types, zext the smaller one.
1354 if (DestSize->getType() != SrcSize->getType()) {
1355 if (DestSize->getType()->getIntegerBitWidth() >
1356 SrcSize->getType()->getIntegerBitWidth())
1357 SrcSize = Builder.CreateZExt(V: SrcSize, DestTy: DestSize->getType());
1358 else
1359 DestSize = Builder.CreateZExt(V: DestSize, DestTy: SrcSize->getType());
1360 }
1361
1362 Value *Ule = Builder.CreateICmpULE(LHS: DestSize, RHS: SrcSize);
1363 Value *SizeDiff = Builder.CreateSub(LHS: DestSize, RHS: SrcSize);
1364 Value *MemsetLen = Builder.CreateSelect(
1365 C: Ule, True: ConstantInt::getNullValue(Ty: DestSize->getType()), False: SizeDiff);
1366 // FIXME (#167968): we could explore estimating the branch_weights based on
1367 // value profiling data about the 2 sizes.
1368 if (auto *SI = dyn_cast<SelectInst>(Val: MemsetLen))
1369 setExplicitlyUnknownBranchWeightsIfProfiled(I&: *SI, DEBUG_TYPE);
1370 Instruction *NewMemSet =
1371 Builder.CreateMemSet(Ptr: Builder.CreatePtrAdd(Ptr: Dest, Offset: SrcSize),
1372 Val: MemSet->getOperand(i_nocapture: 1), Size: MemsetLen, Align: Alignment);
1373
1374 assert(isa<MemoryDef>(MSSA->getMemoryAccess(MemCpy)) &&
1375 "MemCpy must be a MemoryDef");
1376 // The new memset is inserted before the memcpy, and it is known that the
1377 // memcpy's defining access is the memset about to be removed.
1378 auto *LastDef = cast<MemoryDef>(Val: MSSA->getMemoryAccess(I: MemCpy));
1379 auto *NewAccess =
1380 MSSAU->createMemoryAccessBefore(I: NewMemSet, Definition: nullptr, InsertPt: LastDef);
1381 MSSAU->insertDef(Def: cast<MemoryDef>(Val: NewAccess), /*RenameUses=*/true);
1382
1383 eraseInstruction(I: MemSet);
1384 return true;
1385}
1386
1387/// Determine whether the pointer V had only undefined content (due to Def),
1388/// either because it was freshly alloca'd or started its lifetime.
1389static bool hasUndefContents(MemorySSA *MSSA, BatchAAResults &AA, Value *V,
1390 MemoryDef *Def) {
1391 if (MSSA->isLiveOnEntryDef(MA: Def))
1392 return isa<AllocaInst>(Val: getUnderlyingObject(V));
1393
1394 if (auto *II = dyn_cast_or_null<IntrinsicInst>(Val: Def->getMemoryInst()))
1395 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
1396 if (auto *Alloca = dyn_cast<AllocaInst>(Val: getUnderlyingObject(V)))
1397 return II->getArgOperand(i: 0) == Alloca;
1398
1399 return false;
1400}
1401
1402// If the memcpy is larger than the previous, but the memory was undef prior to
1403// that, we can just ignore the tail. Technically we're only interested in the
1404// bytes from 0..MemSrcOffset and MemSrcLength+MemSrcOffset..CopySize here, but
1405// as we can't easily represent this location (hasUndefContents uses mustAlias
1406// which cannot deal with offsets), we use the full 0..CopySize range.
1407static bool overreadUndefContents(MemorySSA *MSSA, MemCpyInst *MemCpy,
1408 MemIntrinsic *MemSrc, BatchAAResults &BAA) {
1409 MemoryLocation MemCpyLoc = MemoryLocation::getForSource(MTI: MemCpy);
1410 MemoryUseOrDef *MemSrcAccess = MSSA->getMemoryAccess(I: MemSrc);
1411 MemoryAccess *Clobber = MSSA->getWalker()->getClobberingMemoryAccess(
1412 MemSrcAccess->getDefiningAccess(), MemCpyLoc, AA&: BAA);
1413 if (auto *MD = dyn_cast<MemoryDef>(Val: Clobber))
1414 if (hasUndefContents(MSSA, AA&: BAA, V: MemCpy->getSource(), Def: MD))
1415 return true;
1416 return false;
1417}
1418
1419/// Transform memcpy to memset when its source was just memset.
1420/// In other words, turn:
1421/// \code
1422/// memset(dst1, c, dst1_size);
1423/// memcpy(dst2, dst1, dst2_size);
1424/// \endcode
1425/// into:
1426/// \code
1427/// memset(dst1, c, dst1_size);
1428/// memset(dst2, c, dst2_size);
1429/// \endcode
1430bool MemCpyOptPass::performMemCpyToMemSetOptzn(MemCpyInst *MemCpy,
1431 MemSetInst *MemSet,
1432 BatchAAResults &BAA) {
1433 Value *MemSetSize = MemSet->getLength();
1434 Value *CopySize = MemCpy->getLength();
1435
1436 int64_t MOffset = 0;
1437 const DataLayout &DL = MemCpy->getModule()->getDataLayout();
1438 // We can only transforms memcpy's where the dest of one is the source of the
1439 // other, or they have a known offset.
1440 if (MemCpy->getSource() != MemSet->getDest()) {
1441 std::optional<int64_t> Offset =
1442 MemCpy->getSource()->getPointerOffsetFrom(Other: MemSet->getDest(), DL);
1443 if (!Offset)
1444 return false;
1445 // On positive offsets, the memcpy source is at a offset into the memset'd
1446 // region. On negative offsets, the copy starts at a offset prior to the
1447 // previously memset'd area, namely, we memcpy from a partially initialized
1448 // region.
1449 MOffset = *Offset;
1450 }
1451
1452 if (MOffset != 0 || MemSetSize != CopySize) {
1453 // Make sure the memcpy doesn't read any more than what the memset wrote,
1454 // other than undef. Likewise, the memcpy should not read from an area not
1455 // covered by the memset unless undef bytes. Don't worry about sizes larger
1456 // than i64.
1457 auto *CMemSetSize = dyn_cast<ConstantInt>(Val: MemSetSize);
1458 auto *CCopySize = dyn_cast<ConstantInt>(Val: CopySize);
1459 if (!CMemSetSize || !CCopySize || MOffset < 0 ||
1460 CCopySize->getZExtValue() + MOffset > CMemSetSize->getZExtValue()) {
1461 if (!overreadUndefContents(MSSA, MemCpy, MemSrc: MemSet, BAA))
1462 return false;
1463
1464 if (CMemSetSize && CCopySize) {
1465 uint64_t MemSetSizeVal = CMemSetSize->getZExtValue();
1466 uint64_t MemCpySizeVal = CCopySize->getZExtValue();
1467 uint64_t NewSize;
1468
1469 if (MOffset < 0) {
1470 // Offset from beginning of the initialized region.
1471 uint64_t Offset = -MOffset;
1472 NewSize = MemCpySizeVal <= Offset ? 0 : MemCpySizeVal - Offset;
1473 } else if (MOffset == 0) {
1474 NewSize = MemSetSizeVal;
1475 } else {
1476 NewSize =
1477 MemSetSizeVal <= (uint64_t)MOffset ? 0 : MemSetSizeVal - MOffset;
1478 }
1479 CopySize = ConstantInt::get(Ty: CopySize->getType(), V: NewSize);
1480 } else {
1481 if (MOffset < 0)
1482 return false;
1483 }
1484 }
1485 }
1486
1487 IRBuilder<> Builder(MemCpy);
1488 Value *DestPtr = MemCpy->getRawDest();
1489 MaybeAlign Align = MemCpy->getDestAlign();
1490 if (MOffset < 0) {
1491 DestPtr = Builder.CreatePtrAdd(Ptr: DestPtr, Offset: Builder.getInt64(C: -MOffset));
1492 if (Align)
1493 Align = commonAlignment(A: *Align, Offset: -MOffset);
1494 }
1495
1496 Instruction *NewM =
1497 Builder.CreateMemSet(Ptr: DestPtr, Val: MemSet->getOperand(i_nocapture: 1), Size: CopySize, Align);
1498 auto *LastDef = cast<MemoryDef>(Val: MSSA->getMemoryAccess(I: MemCpy));
1499 auto *NewAccess = MSSAU->createMemoryAccessAfter(I: NewM, Definition: nullptr, InsertPt: LastDef);
1500 MSSAU->insertDef(Def: cast<MemoryDef>(Val: NewAccess), /*RenameUses=*/true);
1501
1502 return true;
1503}
1504
1505// Attempts to optimize the pattern whereby memory is copied from an alloca to
1506// another alloca, where the two allocas don't have conflicting mod/ref. If
1507// successful, the two allocas can be merged into one and the transfer can be
1508// deleted. This pattern is generated frequently in Rust, due to the ubiquity of
1509// move operations in that language.
1510//
1511// Once we determine that the optimization is safe to perform, we replace all
1512// uses of the destination alloca with the source alloca. We also "shrink wrap"
1513// the lifetime markers of the single merged alloca to before the first use
1514// and after the last use. Note that the "shrink wrapping" procedure is a safe
1515// transformation only because we restrict the scope of this optimization to
1516// allocas that aren't captured.
1517bool MemCpyOptPass::performStackMoveOptzn(Instruction *Load, Instruction *Store,
1518 AllocaInst *DestAlloca,
1519 AllocaInst *SrcAlloca, TypeSize Size,
1520 BatchAAResults &BAA) {
1521 LLVM_DEBUG(dbgs() << "Stack Move: Attempting to optimize:\n"
1522 << *Store << "\n");
1523
1524 // Make sure the two allocas are in the same address space.
1525 if (SrcAlloca->getAddressSpace() != DestAlloca->getAddressSpace()) {
1526 LLVM_DEBUG(dbgs() << "Stack Move: Address space mismatch\n");
1527 return false;
1528 }
1529
1530 // Check that copy is full with static size.
1531 const DataLayout &DL = DestAlloca->getDataLayout();
1532 std::optional<TypeSize> SrcSize = SrcAlloca->getAllocationSize(DL);
1533 std::optional<TypeSize> DestSize = DestAlloca->getAllocationSize(DL);
1534 if (!SrcSize || !DestSize)
1535 return false;
1536 if (*SrcSize != *DestSize)
1537 if (!SrcSize->isFixed() || !DestSize->isFixed())
1538 return false;
1539 if (Size != *DestSize) {
1540 LLVM_DEBUG(dbgs() << "Stack Move: Destination alloca size mismatch\n");
1541 return false;
1542 }
1543
1544 if (!SrcAlloca->isStaticAlloca() || !DestAlloca->isStaticAlloca())
1545 return false;
1546
1547 // Check if it will be legal to combine allocas without breaking dominator.
1548 bool MoveSrc = !DT->dominates(Def: SrcAlloca, User: DestAlloca);
1549 if (MoveSrc) {
1550 if (!DT->dominates(Def: DestAlloca, User: SrcAlloca))
1551 return false;
1552 }
1553
1554 // Check that src and dest are never captured, unescaped allocas. Also
1555 // find the nearest common dominator and postdominator for all users in
1556 // order to shrink wrap the lifetimes, and instructions with noalias metadata
1557 // to remove them.
1558
1559 SmallVector<Instruction *, 4> LifetimeMarkers;
1560 SmallPtrSet<Instruction *, 4> AAMetadataInstrs;
1561
1562 auto CaptureTrackingWithModRef =
1563 [&](Instruction *AI, function_ref<bool(Instruction *)> ModRefCallback,
1564 bool &AddressCaptured) -> bool {
1565 SmallVector<Instruction *, 8> Worklist;
1566 Worklist.push_back(Elt: AI);
1567 unsigned MaxUsesToExplore = getDefaultMaxUsesToExploreForCaptureTracking();
1568 Worklist.reserve(N: MaxUsesToExplore);
1569 SmallPtrSet<const Use *, 20> Visited;
1570 while (!Worklist.empty()) {
1571 Instruction *I = Worklist.pop_back_val();
1572 for (const Use &U : I->uses()) {
1573 auto *UI = cast<Instruction>(Val: U.getUser());
1574
1575 if (Visited.size() >= MaxUsesToExplore) {
1576 LLVM_DEBUG(
1577 dbgs()
1578 << "Stack Move: Exceeded max uses to see ModRef, bailing\n");
1579 return false;
1580 }
1581 if (!Visited.insert(Ptr: &U).second)
1582 continue;
1583 UseCaptureInfo CI = DetermineUseCaptureKind(U, Base: AI);
1584 if (capturesAnyProvenance(CC: CI.UseCC))
1585 return false;
1586 AddressCaptured |= capturesAddress(CC: CI.UseCC);
1587
1588 if (UI->mayReadOrWriteMemory()) {
1589 if (UI->isLifetimeStartOrEnd()) {
1590 // We note the locations of these intrinsic calls so that we can
1591 // delete them later if the optimization succeeds, this is safe
1592 // since both llvm.lifetime.start and llvm.lifetime.end intrinsics
1593 // practically fill all the bytes of the alloca with an undefined
1594 // value, although conceptually marked as alive/dead.
1595 LifetimeMarkers.push_back(Elt: UI);
1596 continue;
1597 }
1598 AAMetadataInstrs.insert(Ptr: UI);
1599
1600 if (!ModRefCallback(UI))
1601 return false;
1602 }
1603
1604 if (capturesAnything(CC: CI.ResultCC)) {
1605 Worklist.push_back(Elt: UI);
1606 continue;
1607 }
1608 }
1609 }
1610 return true;
1611 };
1612
1613 // Check that dest has no Mod/Ref, from the alloca to the Store. And collect
1614 // modref inst for the reachability check.
1615 ModRefInfo DestModRef = ModRefInfo::NoModRef;
1616 MemoryLocation DestLoc(DestAlloca, LocationSize::precise(Value: Size));
1617 SmallVector<BasicBlock *, 8> ReachabilityWorklist;
1618 auto DestModRefCallback = [&](Instruction *UI) -> bool {
1619 // We don't care about the store itself.
1620 if (UI == Store)
1621 return true;
1622 ModRefInfo Res = BAA.getModRefInfo(I: UI, OptLoc: DestLoc);
1623 DestModRef |= Res;
1624 if (isModOrRefSet(MRI: Res)) {
1625 // Instructions reachability checks.
1626 // FIXME: adding the Instruction version isPotentiallyReachableFromMany on
1627 // lib/Analysis/CFG.cpp (currently only for BasicBlocks) might be helpful.
1628 if (UI->getParent() == Store->getParent()) {
1629 // The same block case is special because it's the only time we're
1630 // looking within a single block to see which instruction comes first.
1631 // Once we start looking at multiple blocks, the first instruction of
1632 // the block is reachable, so we only need to determine reachability
1633 // between whole blocks.
1634 BasicBlock *BB = UI->getParent();
1635
1636 // If A comes before B, then B is definitively reachable from A.
1637 if (UI->comesBefore(Other: Store))
1638 return false;
1639
1640 // If the user's parent block is entry, no predecessor exists.
1641 if (BB->isEntryBlock())
1642 return true;
1643
1644 // Otherwise, continue doing the normal per-BB CFG walk.
1645 ReachabilityWorklist.append(in_start: succ_begin(BB), in_end: succ_end(BB));
1646 } else {
1647 ReachabilityWorklist.push_back(Elt: UI->getParent());
1648 }
1649 }
1650 return true;
1651 };
1652
1653 bool DestAddressCaptured = false;
1654 if (!CaptureTrackingWithModRef(DestAlloca, DestModRefCallback,
1655 DestAddressCaptured))
1656 return false;
1657 // Bailout if Dest may have any ModRef before Store.
1658 if (!ReachabilityWorklist.empty() &&
1659 isPotentiallyReachableFromMany(Worklist&: ReachabilityWorklist, StopBB: Store->getParent(),
1660 ExclusionSet: nullptr, DT, LI: nullptr))
1661 return false;
1662
1663 // Check that, from after the Load to the end of the BB,
1664 // - if the dest has any Mod, src has no Ref, and
1665 // - if the dest has any Ref, src has no Mod except full-sized lifetimes.
1666 MemoryLocation SrcLoc(SrcAlloca, LocationSize::precise(Value: Size));
1667
1668 auto SrcModRefCallback = [&](Instruction *UI) -> bool {
1669 // Any ModRef post-dominated by Load doesn't matter, also Load and Store
1670 // themselves can be ignored.
1671 if (PDT->dominates(I1: Load, I2: UI) || UI == Load || UI == Store)
1672 return true;
1673 ModRefInfo Res = BAA.getModRefInfo(I: UI, OptLoc: SrcLoc);
1674 if ((isModSet(MRI: DestModRef) && isRefSet(MRI: Res)) ||
1675 (isRefSet(MRI: DestModRef) && isModSet(MRI: Res)))
1676 return false;
1677
1678 return true;
1679 };
1680
1681 bool SrcAddressCaptured = false;
1682 if (!CaptureTrackingWithModRef(SrcAlloca, SrcModRefCallback,
1683 SrcAddressCaptured))
1684 return false;
1685
1686 // If both the source and destination address are captured, the fact that they
1687 // are no longer two separate allocations may be observed.
1688 if (DestAddressCaptured && SrcAddressCaptured)
1689 return false;
1690
1691 // We can now do the transformation. First move the Src if it was after Dest.
1692 if (MoveSrc)
1693 SrcAlloca->moveBefore(InsertPos: DestAlloca->getIterator());
1694
1695 // Align the allocas appropriately.
1696 SrcAlloca->setAlignment(
1697 std::max(a: SrcAlloca->getAlign(), b: DestAlloca->getAlign()));
1698
1699 // Size the allocas appropriately.
1700 if (*SrcSize != *DestSize) {
1701 // Only possible if both sizes are fixed (due to earlier check)
1702 // Set Src to the type and array size of Dest if Dest was larger
1703 if (DestSize->getFixedValue() > SrcSize->getFixedValue()) {
1704 SrcAlloca->setAllocatedType(DestAlloca->getAllocatedType());
1705 SrcAlloca->setOperand(i_nocapture: 0, Val_nocapture: DestAlloca->getArraySize());
1706 }
1707 }
1708
1709 // Merge the two allocas.
1710 DestAlloca->replaceAllUsesWith(V: SrcAlloca);
1711 eraseInstruction(I: DestAlloca);
1712
1713 // Drop metadata on the source alloca.
1714 SrcAlloca->dropUnknownNonDebugMetadata();
1715
1716 // TODO: Reconstruct merged lifetime markers.
1717 // Remove all other lifetime markers. if the original lifetime intrinsics
1718 // exists.
1719 if (!LifetimeMarkers.empty()) {
1720 for (Instruction *I : LifetimeMarkers)
1721 eraseInstruction(I);
1722 }
1723
1724 // As this transformation can cause memory accesses that didn't previously
1725 // alias to begin to alias one another, we remove !alias.scope, !noalias,
1726 // !tbaa and !tbaa_struct metadata from any uses of either alloca.
1727 // This is conservative, but more precision doesn't seem worthwhile
1728 // right now.
1729 for (Instruction *I : AAMetadataInstrs) {
1730 I->setMetadata(KindID: LLVMContext::MD_alias_scope, Node: nullptr);
1731 I->setMetadata(KindID: LLVMContext::MD_noalias, Node: nullptr);
1732 I->setMetadata(KindID: LLVMContext::MD_tbaa, Node: nullptr);
1733 I->setMetadata(KindID: LLVMContext::MD_tbaa_struct, Node: nullptr);
1734 }
1735
1736 LLVM_DEBUG(dbgs() << "Stack Move: Performed stack-move optimization\n");
1737 NumStackMove++;
1738 return true;
1739}
1740
1741static bool isZeroSize(Value *Size) {
1742 if (auto *I = dyn_cast<Instruction>(Val: Size))
1743 if (auto *Res = simplifyInstruction(I, Q: I->getDataLayout()))
1744 Size = Res;
1745 // Treat undef/poison size like zero.
1746 if (auto *C = dyn_cast<Constant>(Val: Size))
1747 return isa<UndefValue>(Val: C) || C->isNullValue();
1748 return false;
1749}
1750
1751/// Perform simplification of memcpy's. If we have memcpy A
1752/// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite
1753/// B to be a memcpy from X to Z (or potentially a memmove, depending on
1754/// circumstances). This allows later passes to remove the first memcpy
1755/// altogether.
1756bool MemCpyOptPass::processMemCpy(MemCpyInst *M, BasicBlock::iterator &BBI) {
1757 // We can only optimize non-volatile memcpy's.
1758 if (M->isVolatile())
1759 return false;
1760
1761 // If the source and destination of the memcpy are the same, then zap it.
1762 if (M->getSource() == M->getDest()) {
1763 ++BBI;
1764 eraseInstruction(I: M);
1765 return true;
1766 }
1767
1768 // If the size is zero, remove the memcpy.
1769 if (isZeroSize(Size: M->getLength())) {
1770 ++BBI;
1771 eraseInstruction(I: M);
1772 return true;
1773 }
1774
1775 MemoryUseOrDef *MA = MSSA->getMemoryAccess(I: M);
1776 if (!MA)
1777 // Degenerate case: memcpy marked as not accessing memory.
1778 return false;
1779
1780 // If copying from a constant, try to turn the memcpy into a memset.
1781 if (auto *GV = dyn_cast<GlobalVariable>(Val: M->getSource()))
1782 if (GV->isConstant() && GV->hasDefinitiveInitializer())
1783 if (Value *ByteVal = isBytewiseValue(V: GV->getInitializer(),
1784 DL: M->getDataLayout())) {
1785 IRBuilder<> Builder(M);
1786 Instruction *NewM = Builder.CreateMemSet(
1787 Ptr: M->getRawDest(), Val: ByteVal, Size: M->getLength(), Align: M->getDestAlign(), isVolatile: false);
1788 auto *LastDef = cast<MemoryDef>(Val: MA);
1789 auto *NewAccess =
1790 MSSAU->createMemoryAccessAfter(I: NewM, Definition: nullptr, InsertPt: LastDef);
1791 MSSAU->insertDef(Def: cast<MemoryDef>(Val: NewAccess), /*RenameUses=*/true);
1792
1793 eraseInstruction(I: M);
1794 ++NumCpyToSet;
1795 return true;
1796 }
1797
1798 BatchAAResults BAA(*AA, EEA);
1799 // FIXME: Not using getClobberingMemoryAccess() here due to PR54682.
1800 MemoryAccess *AnyClobber = MA->getDefiningAccess();
1801 MemoryLocation DestLoc = MemoryLocation::getForDest(MI: M);
1802 const MemoryAccess *DestClobber =
1803 MSSA->getWalker()->getClobberingMemoryAccess(AnyClobber, DestLoc, AA&: BAA);
1804
1805 // Try to turn a partially redundant memset + memcpy into
1806 // smaller memset + memcpy. We don't need the memcpy size for this.
1807 // The memcpy must post-dom the memset, so limit this to the same basic
1808 // block. A non-local generalization is likely not worthwhile.
1809 if (auto *MD = dyn_cast<MemoryDef>(Val: DestClobber))
1810 if (auto *MDep = dyn_cast_or_null<MemSetInst>(Val: MD->getMemoryInst()))
1811 if (DestClobber->getBlock() == M->getParent())
1812 if (processMemSetMemCpyDependence(MemCpy: M, MemSet: MDep, BAA))
1813 return true;
1814
1815 MemoryAccess *SrcClobber = MSSA->getWalker()->getClobberingMemoryAccess(
1816 AnyClobber, MemoryLocation::getForSource(MTI: M), AA&: BAA);
1817
1818 // There are five possible optimizations we can do for memcpy:
1819 // a) memcpy-memcpy xform which exposes redundance for DSE.
1820 // b) call-memcpy xform for return slot optimization.
1821 // c) memcpy from freshly alloca'd space or space that has just started
1822 // its lifetime copies undefined data, and we can therefore eliminate
1823 // the memcpy in favor of the data that was already at the destination.
1824 // d) memcpy from a just-memset'd source can be turned into memset.
1825 // e) elimination of memcpy via stack-move optimization.
1826 if (auto *MD = dyn_cast<MemoryDef>(Val: SrcClobber)) {
1827 if (Instruction *MI = MD->getMemoryInst()) {
1828 if (auto *CopySize = dyn_cast<ConstantInt>(Val: M->getLength())) {
1829 if (auto *C = dyn_cast<CallInst>(Val: MI)) {
1830 if (performCallSlotOptzn(cpyLoad: M, cpyStore: M, cpyDest: M->getDest(), cpySrc: M->getSource(),
1831 cpySize: TypeSize::getFixed(ExactSize: CopySize->getZExtValue()),
1832 cpyDestAlign: M->getDestAlign().valueOrOne(), BAA,
1833 GetC: [C]() -> CallInst * { return C; })) {
1834 LLVM_DEBUG(dbgs() << "Performed call slot optimization:\n"
1835 << " call: " << *C << "\n"
1836 << " memcpy: " << *M << "\n");
1837 eraseInstruction(I: M);
1838 ++NumMemCpyInstr;
1839 return true;
1840 }
1841 }
1842 }
1843 if (auto *MDep = dyn_cast<MemCpyInst>(Val: MI))
1844 if (processMemCpyMemCpyDependence(M, MDep, BAA))
1845 return true;
1846 if (auto *MDep = dyn_cast<MemSetInst>(Val: MI)) {
1847 if (performMemCpyToMemSetOptzn(MemCpy: M, MemSet: MDep, BAA)) {
1848 LLVM_DEBUG(dbgs() << "Converted memcpy to memset\n");
1849 eraseInstruction(I: M);
1850 ++NumCpyToSet;
1851 return true;
1852 }
1853 }
1854 }
1855
1856 if (hasUndefContents(MSSA, AA&: BAA, V: M->getSource(), Def: MD)) {
1857 LLVM_DEBUG(dbgs() << "Removed memcpy from undef\n");
1858 eraseInstruction(I: M);
1859 ++NumMemCpyInstr;
1860 return true;
1861 }
1862 }
1863
1864 // If the transfer is from a stack slot to a stack slot, then we may be able
1865 // to perform the stack-move optimization. See the comments in
1866 // performStackMoveOptzn() for more details.
1867 auto *DestAlloca = dyn_cast<AllocaInst>(Val: M->getDest());
1868 if (!DestAlloca)
1869 return false;
1870 auto *SrcAlloca = dyn_cast<AllocaInst>(Val: M->getSource());
1871 if (!SrcAlloca)
1872 return false;
1873 ConstantInt *Len = dyn_cast<ConstantInt>(Val: M->getLength());
1874 if (Len == nullptr)
1875 return false;
1876 if (performStackMoveOptzn(Load: M, Store: M, DestAlloca, SrcAlloca,
1877 Size: TypeSize::getFixed(ExactSize: Len->getZExtValue()), BAA)) {
1878 // Avoid invalidating the iterator.
1879 BBI = M->getNextNode()->getIterator();
1880 eraseInstruction(I: M);
1881 ++NumMemCpyInstr;
1882 return true;
1883 }
1884
1885 return false;
1886}
1887
1888/// Memmove calls with overlapping src/dest buffers that come after a memset may
1889/// be removed.
1890bool MemCpyOptPass::isMemMoveMemSetDependency(MemMoveInst *M) {
1891 const auto &DL = M->getDataLayout();
1892 MemoryUseOrDef *MemMoveAccess = MSSA->getMemoryAccess(I: M);
1893 if (!MemMoveAccess)
1894 return false;
1895
1896 // The memmove is of form memmove(x, x + A, B).
1897 MemoryLocation SourceLoc = MemoryLocation::getForSource(MTI: M);
1898 auto *MemMoveSourceOp = M->getSource();
1899 auto *Source = dyn_cast<GEPOperator>(Val: MemMoveSourceOp);
1900 if (!Source)
1901 return false;
1902
1903 APInt Offset(DL.getIndexTypeSizeInBits(Ty: Source->getType()), 0);
1904 LocationSize MemMoveLocSize = SourceLoc.Size;
1905 if (Source->getPointerOperand() != M->getDest() ||
1906 !MemMoveLocSize.hasValue() ||
1907 !Source->accumulateConstantOffset(DL, Offset) || Offset.isNegative()) {
1908 return false;
1909 }
1910
1911 uint64_t MemMoveSize = MemMoveLocSize.getValue();
1912 LocationSize TotalSize =
1913 LocationSize::precise(Value: Offset.getZExtValue() + MemMoveSize);
1914 MemoryLocation CombinedLoc(M->getDest(), TotalSize);
1915
1916 // The first dominating clobbering MemoryAccess for the combined location
1917 // needs to be a memset.
1918 BatchAAResults BAA(*AA);
1919 MemoryAccess *FirstDef = MemMoveAccess->getDefiningAccess();
1920 auto *DestClobber = dyn_cast<MemoryDef>(
1921 Val: MSSA->getWalker()->getClobberingMemoryAccess(FirstDef, CombinedLoc, AA&: BAA));
1922 if (!DestClobber)
1923 return false;
1924
1925 auto *MS = dyn_cast_or_null<MemSetInst>(Val: DestClobber->getMemoryInst());
1926 if (!MS)
1927 return false;
1928
1929 // Memset length must be sufficiently large.
1930 auto *MemSetLength = dyn_cast<ConstantInt>(Val: MS->getLength());
1931 if (!MemSetLength || MemSetLength->getZExtValue() < MemMoveSize)
1932 return false;
1933
1934 // The destination buffer must have been memset'd.
1935 if (!BAA.isMustAlias(V1: MS->getDest(), V2: M->getDest()))
1936 return false;
1937
1938 return true;
1939}
1940
1941/// Transforms memmove calls to memcpy calls when the src/dst are guaranteed
1942/// not to alias.
1943bool MemCpyOptPass::processMemMove(MemMoveInst *M, BasicBlock::iterator &BBI) {
1944 // See if the source could be modified by this memmove potentially.
1945 if (isModSet(MRI: AA->getModRefInfo(I: M, OptLoc: MemoryLocation::getForSource(MTI: M)))) {
1946 // On the off-chance the memmove clobbers src with previously memset'd
1947 // bytes, the memmove may be redundant.
1948 if (!M->isVolatile() && isMemMoveMemSetDependency(M)) {
1949 LLVM_DEBUG(dbgs() << "Removed redundant memmove.\n");
1950 ++BBI;
1951 eraseInstruction(I: M);
1952 ++NumMemMoveInstr;
1953 return true;
1954 }
1955 return false;
1956 }
1957
1958 LLVM_DEBUG(dbgs() << "MemCpyOptPass: Optimizing memmove -> memcpy: " << *M
1959 << "\n");
1960
1961 // If not, then we know we can transform this.
1962 Type *ArgTys[3] = {M->getRawDest()->getType(), M->getRawSource()->getType(),
1963 M->getLength()->getType()};
1964 M->setCalledFunction(Intrinsic::getOrInsertDeclaration(
1965 M: M->getModule(), id: Intrinsic::memcpy, Tys: ArgTys));
1966
1967 // For MemorySSA nothing really changes (except that memcpy may imply stricter
1968 // aliasing guarantees).
1969
1970 ++NumMoveToCpy;
1971 return true;
1972}
1973
1974/// This is called on every byval argument in call sites.
1975bool MemCpyOptPass::processByValArgument(CallBase &CB, unsigned ArgNo) {
1976 const DataLayout &DL = CB.getDataLayout();
1977 // Find out what feeds this byval argument.
1978 Value *ByValArg = CB.getArgOperand(i: ArgNo);
1979 Type *ByValTy = CB.getParamByValType(ArgNo);
1980 TypeSize ByValSize = DL.getTypeAllocSize(Ty: ByValTy);
1981 MemoryLocation Loc(ByValArg, LocationSize::precise(Value: ByValSize));
1982 MemoryUseOrDef *CallAccess = MSSA->getMemoryAccess(I: &CB);
1983 if (!CallAccess)
1984 return false;
1985 MemCpyInst *MDep = nullptr;
1986 BatchAAResults BAA(*AA, EEA);
1987 MemoryAccess *Clobber = MSSA->getWalker()->getClobberingMemoryAccess(
1988 CallAccess->getDefiningAccess(), Loc, AA&: BAA);
1989 if (auto *MD = dyn_cast<MemoryDef>(Val: Clobber))
1990 MDep = dyn_cast_or_null<MemCpyInst>(Val: MD->getMemoryInst());
1991
1992 // If the byval argument isn't fed by a memcpy, ignore it. If it is fed by
1993 // a memcpy, see if we can byval from the source of the memcpy instead of the
1994 // result.
1995 if (!MDep || MDep->isVolatile() ||
1996 ByValArg->stripPointerCasts() != MDep->getDest())
1997 return false;
1998
1999 // The length of the memcpy must be larger or equal to the size of the byval.
2000 auto *C1 = dyn_cast<ConstantInt>(Val: MDep->getLength());
2001 if (!C1 || !TypeSize::isKnownGE(
2002 LHS: TypeSize::getFixed(ExactSize: C1->getValue().getZExtValue()), RHS: ByValSize))
2003 return false;
2004
2005 // Get the alignment of the byval. If the call doesn't specify the alignment,
2006 // then it is some target specific value that we can't know.
2007 MaybeAlign ByValAlign = CB.getParamAlign(ArgNo);
2008 if (!ByValAlign)
2009 return false;
2010
2011 // If it is greater than the memcpy, then we check to see if we can force the
2012 // source of the memcpy to the alignment we need. If we fail, we bail out.
2013 MaybeAlign MemDepAlign = MDep->getSourceAlign();
2014 if ((!MemDepAlign || *MemDepAlign < *ByValAlign) &&
2015 getOrEnforceKnownAlignment(V: MDep->getSource(), PrefAlign: ByValAlign, DL, CxtI: &CB, AC,
2016 DT) < *ByValAlign)
2017 return false;
2018
2019 // The type of the memcpy source must match the byval argument
2020 if (MDep->getSource()->getType() != ByValArg->getType())
2021 return false;
2022
2023 // Verify that the copied-from memory doesn't change in between the memcpy and
2024 // the byval call.
2025 // memcpy(a <- b)
2026 // *b = 42;
2027 // foo(*a)
2028 // It would be invalid to transform the second memcpy into foo(*b).
2029 if (writtenBetween(MSSA, AA&: BAA, Loc: MemoryLocation::getForSource(MTI: MDep),
2030 Start: MSSA->getMemoryAccess(I: MDep), End: CallAccess))
2031 return false;
2032
2033 LLVM_DEBUG(dbgs() << "MemCpyOptPass: Forwarding memcpy to byval:\n"
2034 << " " << *MDep << "\n"
2035 << " " << CB << "\n");
2036
2037 // Otherwise we're good! Update the byval argument.
2038 combineAAMetadata(K: &CB, J: MDep);
2039 CB.setArgOperand(i: ArgNo, v: MDep->getSource());
2040 ++NumMemCpyInstr;
2041 return true;
2042}
2043
2044/// This is called on memcpy dest pointer arguments attributed as immutable
2045/// during call. Try to use memcpy source directly if all of the following
2046/// conditions are satisfied.
2047/// 1. The memcpy dst is neither modified during the call nor captured by the
2048/// call.
2049/// 2. The memcpy dst is an alloca with known alignment & size.
2050/// 2-1. The memcpy length == the alloca size which ensures that the new
2051/// pointer is dereferenceable for the required range
2052/// 2-2. The src pointer has alignment >= the alloca alignment or can be
2053/// enforced so.
2054/// 3. The memcpy dst and src is not modified between the memcpy and the call.
2055/// (if MSSA clobber check is safe.)
2056/// 4. The memcpy src is not modified during the call. (ModRef check shows no
2057/// Mod.)
2058bool MemCpyOptPass::processImmutArgument(CallBase &CB, unsigned ArgNo) {
2059 BatchAAResults BAA(*AA, EEA);
2060 Value *ImmutArg = CB.getArgOperand(i: ArgNo);
2061
2062 // 1. Ensure passed argument is immutable during call.
2063 if (!CB.doesNotCapture(OpNo: ArgNo))
2064 return false;
2065
2066 // We know that the argument is readonly at this point, but the function
2067 // might still modify the same memory through a different pointer. Exclude
2068 // this either via noalias, or alias analysis.
2069 if (!CB.paramHasAttr(ArgNo, Kind: Attribute::NoAlias) &&
2070 isModSet(
2071 MRI: BAA.getModRefInfo(I: &CB, OptLoc: MemoryLocation::getBeforeOrAfter(Ptr: ImmutArg))))
2072 return false;
2073
2074 const DataLayout &DL = CB.getDataLayout();
2075
2076 // 2. Check that arg is alloca
2077 // TODO: Even if the arg gets back to branches, we can remove memcpy if all
2078 // the alloca alignments can be enforced to source alignment.
2079 auto *AI = dyn_cast<AllocaInst>(Val: ImmutArg->stripPointerCasts());
2080 if (!AI)
2081 return false;
2082
2083 std::optional<TypeSize> AllocaSize = AI->getAllocationSize(DL);
2084 // Can't handle unknown size alloca.
2085 // (e.g. Variable Length Array, Scalable Vector)
2086 if (!AllocaSize || AllocaSize->isScalable())
2087 return false;
2088 MemoryLocation Loc(ImmutArg, LocationSize::precise(Value: *AllocaSize));
2089 MemoryUseOrDef *CallAccess = MSSA->getMemoryAccess(I: &CB);
2090 if (!CallAccess)
2091 return false;
2092
2093 MemCpyInst *MDep = nullptr;
2094 MemoryAccess *Clobber = MSSA->getWalker()->getClobberingMemoryAccess(
2095 CallAccess->getDefiningAccess(), Loc, AA&: BAA);
2096 if (auto *MD = dyn_cast<MemoryDef>(Val: Clobber))
2097 MDep = dyn_cast_or_null<MemCpyInst>(Val: MD->getMemoryInst());
2098
2099 // If the immut argument isn't fed by a memcpy, ignore it. If it is fed by
2100 // a memcpy, check that the arg equals the memcpy dest.
2101 if (!MDep || MDep->isVolatile() || AI != MDep->getDest())
2102 return false;
2103
2104 // The type of the memcpy source must match the immut argument
2105 if (MDep->getSource()->getType() != ImmutArg->getType())
2106 return false;
2107
2108 // 2-1. The length of the memcpy must be equal to the size of the alloca.
2109 auto *MDepLen = dyn_cast<ConstantInt>(Val: MDep->getLength());
2110 if (!MDepLen || AllocaSize != MDepLen->getValue())
2111 return false;
2112
2113 // 2-2. the memcpy source align must be larger than or equal the alloca's
2114 // align. If not so, we check to see if we can force the source of the memcpy
2115 // to the alignment we need. If we fail, we bail out.
2116 Align MemDepAlign = MDep->getSourceAlign().valueOrOne();
2117 Align AllocaAlign = AI->getAlign();
2118 if (MemDepAlign < AllocaAlign &&
2119 getOrEnforceKnownAlignment(V: MDep->getSource(), PrefAlign: AllocaAlign, DL, CxtI: &CB, AC,
2120 DT) < AllocaAlign)
2121 return false;
2122
2123 // 3. Verify that the source doesn't change in between the memcpy and
2124 // the call.
2125 // memcpy(a <- b)
2126 // *b = 42;
2127 // foo(*a)
2128 // It would be invalid to transform the second memcpy into foo(*b).
2129 if (writtenBetween(MSSA, AA&: BAA, Loc: MemoryLocation::getForSource(MTI: MDep),
2130 Start: MSSA->getMemoryAccess(I: MDep), End: CallAccess))
2131 return false;
2132
2133 // 4. The memcpy src must not be modified during the call.
2134 if (isModSet(MRI: BAA.getModRefInfo(I: &CB, OptLoc: MemoryLocation::getForSource(MTI: MDep))))
2135 return false;
2136
2137 LLVM_DEBUG(dbgs() << "MemCpyOptPass: Forwarding memcpy to Immut src:\n"
2138 << " " << *MDep << "\n"
2139 << " " << CB << "\n");
2140
2141 // Otherwise we're good! Update the immut argument.
2142 combineAAMetadata(K: &CB, J: MDep);
2143 CB.setArgOperand(i: ArgNo, v: MDep->getSource());
2144 ++NumMemCpyInstr;
2145 return true;
2146}
2147
2148/// Executes one iteration of MemCpyOptPass.
2149bool MemCpyOptPass::iterateOnFunction(Function &F) {
2150 bool MadeChange = false;
2151
2152 // Walk all instruction in the function.
2153 for (BasicBlock &BB : F) {
2154 // Skip unreachable blocks. For example processStore assumes that an
2155 // instruction in a BB can't be dominated by a later instruction in the
2156 // same BB (which is a scenario that can happen for an unreachable BB that
2157 // has itself as a predecessor).
2158 if (!DT->isReachableFromEntry(A: &BB))
2159 continue;
2160
2161 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
2162 // Avoid invalidating the iterator.
2163 Instruction *I = &*BI++;
2164
2165 bool RepeatInstruction = false;
2166
2167 if (auto *SI = dyn_cast<StoreInst>(Val: I))
2168 MadeChange |= processStore(SI, BBI&: BI);
2169 else if (auto *M = dyn_cast<MemSetInst>(Val: I))
2170 RepeatInstruction = processMemSet(MSI: M, BBI&: BI);
2171 else if (auto *M = dyn_cast<MemCpyInst>(Val: I))
2172 RepeatInstruction = processMemCpy(M, BBI&: BI);
2173 else if (auto *M = dyn_cast<MemMoveInst>(Val: I))
2174 RepeatInstruction = processMemMove(M, BBI&: BI);
2175 else if (auto *CB = dyn_cast<CallBase>(Val: I)) {
2176 for (unsigned i = 0, e = CB->arg_size(); i != e; ++i) {
2177 if (CB->isByValArgument(ArgNo: i))
2178 MadeChange |= processByValArgument(CB&: *CB, ArgNo: i);
2179 else if (CB->onlyReadsMemory(OpNo: i))
2180 MadeChange |= processImmutArgument(CB&: *CB, ArgNo: i);
2181 }
2182 }
2183
2184 // Reprocess the instruction if desired.
2185 if (RepeatInstruction) {
2186 if (BI != BB.begin())
2187 --BI;
2188 MadeChange = true;
2189 }
2190 }
2191 }
2192
2193 return MadeChange;
2194}
2195
2196PreservedAnalyses MemCpyOptPass::run(Function &F, FunctionAnalysisManager &AM) {
2197 auto &TLI = AM.getResult<TargetLibraryAnalysis>(IR&: F);
2198 auto *AA = &AM.getResult<AAManager>(IR&: F);
2199 auto *AC = &AM.getResult<AssumptionAnalysis>(IR&: F);
2200 auto *DT = &AM.getResult<DominatorTreeAnalysis>(IR&: F);
2201 auto *PDT = &AM.getResult<PostDominatorTreeAnalysis>(IR&: F);
2202 auto *MSSA = &AM.getResult<MemorySSAAnalysis>(IR&: F);
2203
2204 bool MadeChange = runImpl(F, TLI: &TLI, AA, AC, DT, PDT, MSSA: &MSSA->getMSSA());
2205 if (!MadeChange)
2206 return PreservedAnalyses::all();
2207
2208 PreservedAnalyses PA;
2209 PA.preserveSet<CFGAnalyses>();
2210 PA.preserve<MemorySSAAnalysis>();
2211 return PA;
2212}
2213
2214bool MemCpyOptPass::runImpl(Function &F, TargetLibraryInfo *TLI_,
2215 AliasAnalysis *AA_, AssumptionCache *AC_,
2216 DominatorTree *DT_, PostDominatorTree *PDT_,
2217 MemorySSA *MSSA_) {
2218 bool MadeChange = false;
2219 TLI = TLI_;
2220 AA = AA_;
2221 AC = AC_;
2222 DT = DT_;
2223 PDT = PDT_;
2224 MSSA = MSSA_;
2225 MemorySSAUpdater MSSAU_(MSSA_);
2226 MSSAU = &MSSAU_;
2227 EarliestEscapeAnalysis EEA_(*DT);
2228 EEA = &EEA_;
2229
2230 while (true) {
2231 if (!iterateOnFunction(F))
2232 break;
2233 MadeChange = true;
2234 }
2235
2236 if (VerifyMemorySSA)
2237 MSSA_->verifyMemorySSA();
2238
2239 return MadeChange;
2240}
2241