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