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