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