LLVM  8.0.0svn
MemCpyOptimizer.cpp
Go to the documentation of this file.
1 //===- MemCpyOptimizer.cpp - Optimize use of memcpy and friends -----------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass performs various transformations related to eliminating memcpy
11 // calls, or transforming sets of stores into memset's.
12 //
13 //===----------------------------------------------------------------------===//
14 
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/None.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/Statistic.h"
30 #include "llvm/IR/Argument.h"
31 #include "llvm/IR/BasicBlock.h"
32 #include "llvm/IR/CallSite.h"
33 #include "llvm/IR/Constants.h"
34 #include "llvm/IR/DataLayout.h"
35 #include "llvm/IR/DerivedTypes.h"
36 #include "llvm/IR/Dominators.h"
37 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GlobalVariable.h"
40 #include "llvm/IR/IRBuilder.h"
41 #include "llvm/IR/InstrTypes.h"
42 #include "llvm/IR/Instruction.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/IntrinsicInst.h"
45 #include "llvm/IR/Intrinsics.h"
46 #include "llvm/IR/LLVMContext.h"
47 #include "llvm/IR/Module.h"
48 #include "llvm/IR/Operator.h"
49 #include "llvm/IR/PassManager.h"
50 #include "llvm/IR/Type.h"
51 #include "llvm/IR/User.h"
52 #include "llvm/IR/Value.h"
53 #include "llvm/Pass.h"
54 #include "llvm/Support/Casting.h"
55 #include "llvm/Support/Debug.h"
58 #include "llvm/Transforms/Scalar.h"
59 #include <algorithm>
60 #include <cassert>
61 #include <cstdint>
62 #include <utility>
63 
64 using namespace llvm;
65 
66 #define DEBUG_TYPE "memcpyopt"
67 
68 STATISTIC(NumMemCpyInstr, "Number of memcpy instructions deleted");
69 STATISTIC(NumMemSetInfer, "Number of memsets inferred");
70 STATISTIC(NumMoveToCpy, "Number of memmoves converted to memcpy");
71 STATISTIC(NumCpyToSet, "Number of memcpys converted to memset");
72 
73 static int64_t GetOffsetFromIndex(const GEPOperator *GEP, unsigned Idx,
74  bool &VariableIdxFound,
75  const DataLayout &DL) {
76  // Skip over the first indices.
78  for (unsigned i = 1; i != Idx; ++i, ++GTI)
79  /*skip along*/;
80 
81  // Compute the offset implied by the rest of the indices.
82  int64_t Offset = 0;
83  for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
84  ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
85  if (!OpC)
86  return VariableIdxFound = true;
87  if (OpC->isZero()) continue; // No offset.
88 
89  // Handle struct indices, which add their field offset to the pointer.
90  if (StructType *STy = GTI.getStructTypeOrNull()) {
91  Offset += DL.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
92  continue;
93  }
94 
95  // Otherwise, we have a sequential type like an array or vector. Multiply
96  // the index by the ElementSize.
97  uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
98  Offset += Size*OpC->getSExtValue();
99  }
100 
101  return Offset;
102 }
103 
104 /// Return true if Ptr1 is provably equal to Ptr2 plus a constant offset, and
105 /// return that constant offset. For example, Ptr1 might be &A[42], and Ptr2
106 /// might be &A[40]. In this case offset would be -8.
107 static bool IsPointerOffset(Value *Ptr1, Value *Ptr2, int64_t &Offset,
108  const DataLayout &DL) {
109  Ptr1 = Ptr1->stripPointerCasts();
110  Ptr2 = Ptr2->stripPointerCasts();
111 
112  // Handle the trivial case first.
113  if (Ptr1 == Ptr2) {
114  Offset = 0;
115  return true;
116  }
117 
118  GEPOperator *GEP1 = dyn_cast<GEPOperator>(Ptr1);
119  GEPOperator *GEP2 = dyn_cast<GEPOperator>(Ptr2);
120 
121  bool VariableIdxFound = false;
122 
123  // If one pointer is a GEP and the other isn't, then see if the GEP is a
124  // constant offset from the base, as in "P" and "gep P, 1".
125  if (GEP1 && !GEP2 && GEP1->getOperand(0)->stripPointerCasts() == Ptr2) {
126  Offset = -GetOffsetFromIndex(GEP1, 1, VariableIdxFound, DL);
127  return !VariableIdxFound;
128  }
129 
130  if (GEP2 && !GEP1 && GEP2->getOperand(0)->stripPointerCasts() == Ptr1) {
131  Offset = GetOffsetFromIndex(GEP2, 1, VariableIdxFound, DL);
132  return !VariableIdxFound;
133  }
134 
135  // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
136  // base. After that base, they may have some number of common (and
137  // potentially variable) indices. After that they handle some constant
138  // offset, which determines their offset from each other. At this point, we
139  // handle no other case.
140  if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0))
141  return false;
142 
143  // Skip any common indices and track the GEP types.
144  unsigned Idx = 1;
145  for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
146  if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
147  break;
148 
149  int64_t Offset1 = GetOffsetFromIndex(GEP1, Idx, VariableIdxFound, DL);
150  int64_t Offset2 = GetOffsetFromIndex(GEP2, Idx, VariableIdxFound, DL);
151  if (VariableIdxFound) return false;
152 
153  Offset = Offset2-Offset1;
154  return true;
155 }
156 
157 namespace {
158 
159 /// Represents a range of memset'd bytes with the ByteVal value.
160 /// This allows us to analyze stores like:
161 /// store 0 -> P+1
162 /// store 0 -> P+0
163 /// store 0 -> P+3
164 /// store 0 -> P+2
165 /// which sometimes happens with stores to arrays of structs etc. When we see
166 /// the first store, we make a range [1, 2). The second store extends the range
167 /// to [0, 2). The third makes a new range [2, 3). The fourth store joins the
168 /// two ranges into [0, 3) which is memset'able.
169 struct MemsetRange {
170  // Start/End - A semi range that describes the span that this range covers.
171  // The range is closed at the start and open at the end: [Start, End).
172  int64_t Start, End;
173 
174  /// StartPtr - The getelementptr instruction that points to the start of the
175  /// range.
176  Value *StartPtr;
177 
178  /// Alignment - The known alignment of the first store.
179  unsigned Alignment;
180 
181  /// TheStores - The actual stores that make up this range.
183 
184  bool isProfitableToUseMemset(const DataLayout &DL) const;
185 };
186 
187 } // end anonymous namespace
188 
189 bool MemsetRange::isProfitableToUseMemset(const DataLayout &DL) const {
190  // If we found more than 4 stores to merge or 16 bytes, use memset.
191  if (TheStores.size() >= 4 || End-Start >= 16) return true;
192 
193  // If there is nothing to merge, don't do anything.
194  if (TheStores.size() < 2) return false;
195 
196  // If any of the stores are a memset, then it is always good to extend the
197  // memset.
198  for (Instruction *SI : TheStores)
199  if (!isa<StoreInst>(SI))
200  return true;
201 
202  // Assume that the code generator is capable of merging pairs of stores
203  // together if it wants to.
204  if (TheStores.size() == 2) return false;
205 
206  // If we have fewer than 8 stores, it can still be worthwhile to do this.
207  // For example, merging 4 i8 stores into an i32 store is useful almost always.
208  // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the
209  // memset will be split into 2 32-bit stores anyway) and doing so can
210  // pessimize the llvm optimizer.
211  //
212  // Since we don't have perfect knowledge here, make some assumptions: assume
213  // the maximum GPR width is the same size as the largest legal integer
214  // size. If so, check to see whether we will end up actually reducing the
215  // number of stores used.
216  unsigned Bytes = unsigned(End-Start);
217  unsigned MaxIntSize = DL.getLargestLegalIntTypeSizeInBits() / 8;
218  if (MaxIntSize == 0)
219  MaxIntSize = 1;
220  unsigned NumPointerStores = Bytes / MaxIntSize;
221 
222  // Assume the remaining bytes if any are done a byte at a time.
223  unsigned NumByteStores = Bytes % MaxIntSize;
224 
225  // If we will reduce the # stores (according to this heuristic), do the
226  // transformation. This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32
227  // etc.
228  return TheStores.size() > NumPointerStores+NumByteStores;
229 }
230 
231 namespace {
232 
233 class MemsetRanges {
234  using range_iterator = SmallVectorImpl<MemsetRange>::iterator;
235 
236  /// A sorted list of the memset ranges.
238 
239  const DataLayout &DL;
240 
241 public:
242  MemsetRanges(const DataLayout &DL) : DL(DL) {}
243 
244  using const_iterator = SmallVectorImpl<MemsetRange>::const_iterator;
245 
246  const_iterator begin() const { return Ranges.begin(); }
247  const_iterator end() const { return Ranges.end(); }
248  bool empty() const { return Ranges.empty(); }
249 
250  void addInst(int64_t OffsetFromFirst, Instruction *Inst) {
251  if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
252  addStore(OffsetFromFirst, SI);
253  else
254  addMemSet(OffsetFromFirst, cast<MemSetInst>(Inst));
255  }
256 
257  void addStore(int64_t OffsetFromFirst, StoreInst *SI) {
258  int64_t StoreSize = DL.getTypeStoreSize(SI->getOperand(0)->getType());
259 
260  addRange(OffsetFromFirst, StoreSize,
261  SI->getPointerOperand(), SI->getAlignment(), SI);
262  }
263 
264  void addMemSet(int64_t OffsetFromFirst, MemSetInst *MSI) {
265  int64_t Size = cast<ConstantInt>(MSI->getLength())->getZExtValue();
266  addRange(OffsetFromFirst, Size, MSI->getDest(), MSI->getDestAlignment(), MSI);
267  }
268 
269  void addRange(int64_t Start, int64_t Size, Value *Ptr,
270  unsigned Alignment, Instruction *Inst);
271 };
272 
273 } // end anonymous namespace
274 
275 /// Add a new store to the MemsetRanges data structure. This adds a
276 /// new range for the specified store at the specified offset, merging into
277 /// existing ranges as appropriate.
278 void MemsetRanges::addRange(int64_t Start, int64_t Size, Value *Ptr,
279  unsigned Alignment, Instruction *Inst) {
280  int64_t End = Start+Size;
281 
282  range_iterator I = std::lower_bound(Ranges.begin(), Ranges.end(), Start,
283  [](const MemsetRange &LHS, int64_t RHS) { return LHS.End < RHS; });
284 
285  // We now know that I == E, in which case we didn't find anything to merge
286  // with, or that Start <= I->End. If End < I->Start or I == E, then we need
287  // to insert a new range. Handle this now.
288  if (I == Ranges.end() || End < I->Start) {
289  MemsetRange &R = *Ranges.insert(I, MemsetRange());
290  R.Start = Start;
291  R.End = End;
292  R.StartPtr = Ptr;
293  R.Alignment = Alignment;
294  R.TheStores.push_back(Inst);
295  return;
296  }
297 
298  // This store overlaps with I, add it.
299  I->TheStores.push_back(Inst);
300 
301  // At this point, we may have an interval that completely contains our store.
302  // If so, just add it to the interval and return.
303  if (I->Start <= Start && I->End >= End)
304  return;
305 
306  // Now we know that Start <= I->End and End >= I->Start so the range overlaps
307  // but is not entirely contained within the range.
308 
309  // See if the range extends the start of the range. In this case, it couldn't
310  // possibly cause it to join the prior range, because otherwise we would have
311  // stopped on *it*.
312  if (Start < I->Start) {
313  I->Start = Start;
314  I->StartPtr = Ptr;
315  I->Alignment = Alignment;
316  }
317 
318  // Now we know that Start <= I->End and Start >= I->Start (so the startpoint
319  // is in or right at the end of I), and that End >= I->Start. Extend I out to
320  // End.
321  if (End > I->End) {
322  I->End = End;
323  range_iterator NextI = I;
324  while (++NextI != Ranges.end() && End >= NextI->Start) {
325  // Merge the range in.
326  I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
327  if (NextI->End > I->End)
328  I->End = NextI->End;
329  Ranges.erase(NextI);
330  NextI = I;
331  }
332  }
333 }
334 
335 //===----------------------------------------------------------------------===//
336 // MemCpyOptLegacyPass Pass
337 //===----------------------------------------------------------------------===//
338 
339 namespace {
340 
341 class MemCpyOptLegacyPass : public FunctionPass {
342  MemCpyOptPass Impl;
343 
344 public:
345  static char ID; // Pass identification, replacement for typeid
346 
347  MemCpyOptLegacyPass() : FunctionPass(ID) {
349  }
350 
351  bool runOnFunction(Function &F) override;
352 
353 private:
354  // This transformation requires dominator postdominator info
355  void getAnalysisUsage(AnalysisUsage &AU) const override {
356  AU.setPreservesCFG();
364  }
365 };
366 
367 } // end anonymous namespace
368 
369 char MemCpyOptLegacyPass::ID = 0;
370 
371 /// The public interface to this file...
372 FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOptLegacyPass(); }
373 
374 INITIALIZE_PASS_BEGIN(MemCpyOptLegacyPass, "memcpyopt", "MemCpy Optimization",
375  false, false)
382 INITIALIZE_PASS_END(MemCpyOptLegacyPass, "memcpyopt", "MemCpy Optimization",
383  false, false)
384 
385 /// When scanning forward over instructions, we look for some other patterns to
386 /// fold away. In particular, this looks for stores to neighboring locations of
387 /// memory. If it sees enough consecutive ones, it attempts to merge them
388 /// together into a memcpy/memset.
389 Instruction *MemCpyOptPass::tryMergingIntoMemset(Instruction *StartInst,
390  Value *StartPtr,
391  Value *ByteVal) {
392  const DataLayout &DL = StartInst->getModule()->getDataLayout();
393 
394  // Okay, so we now have a single store that can be splatable. Scan to find
395  // all subsequent stores of the same value to offset from the same pointer.
396  // Join these together into ranges, so we can decide whether contiguous blocks
397  // are stored.
398  MemsetRanges Ranges(DL);
399 
400  BasicBlock::iterator BI(StartInst);
401  for (++BI; !BI->isTerminator(); ++BI) {
402  if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
403  // If the instruction is readnone, ignore it, otherwise bail out. We
404  // don't even allow readonly here because we don't want something like:
405  // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
406  if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
407  break;
408  continue;
409  }
410 
411  if (StoreInst *NextStore = dyn_cast<StoreInst>(BI)) {
412  // If this is a store, see if we can merge it in.
413  if (!NextStore->isSimple()) break;
414 
415  // Check to see if this stored value is of the same byte-splattable value.
416  Value *StoredByte = isBytewiseValue(NextStore->getOperand(0));
417  if (isa<UndefValue>(ByteVal) && StoredByte)
418  ByteVal = StoredByte;
419  if (ByteVal != StoredByte)
420  break;
421 
422  // Check to see if this store is to a constant offset from the start ptr.
423  int64_t Offset;
424  if (!IsPointerOffset(StartPtr, NextStore->getPointerOperand(), Offset,
425  DL))
426  break;
427 
428  Ranges.addStore(Offset, NextStore);
429  } else {
430  MemSetInst *MSI = cast<MemSetInst>(BI);
431 
432  if (MSI->isVolatile() || ByteVal != MSI->getValue() ||
433  !isa<ConstantInt>(MSI->getLength()))
434  break;
435 
436  // Check to see if this store is to a constant offset from the start ptr.
437  int64_t Offset;
438  if (!IsPointerOffset(StartPtr, MSI->getDest(), Offset, DL))
439  break;
440 
441  Ranges.addMemSet(Offset, MSI);
442  }
443  }
444 
445  // If we have no ranges, then we just had a single store with nothing that
446  // could be merged in. This is a very common case of course.
447  if (Ranges.empty())
448  return nullptr;
449 
450  // If we had at least one store that could be merged in, add the starting
451  // store as well. We try to avoid this unless there is at least something
452  // interesting as a small compile-time optimization.
453  Ranges.addInst(0, StartInst);
454 
455  // If we create any memsets, we put it right before the first instruction that
456  // isn't part of the memset block. This ensure that the memset is dominated
457  // by any addressing instruction needed by the start of the block.
458  IRBuilder<> Builder(&*BI);
459 
460  // Now that we have full information about ranges, loop over the ranges and
461  // emit memset's for anything big enough to be worthwhile.
462  Instruction *AMemSet = nullptr;
463  for (const MemsetRange &Range : Ranges) {
464  if (Range.TheStores.size() == 1) continue;
465 
466  // If it is profitable to lower this range to memset, do so now.
467  if (!Range.isProfitableToUseMemset(DL))
468  continue;
469 
470  // Otherwise, we do want to transform this! Create a new memset.
471  // Get the starting pointer of the block.
472  StartPtr = Range.StartPtr;
473 
474  // Determine alignment
475  unsigned Alignment = Range.Alignment;
476  if (Alignment == 0) {
477  Type *EltType =
478  cast<PointerType>(StartPtr->getType())->getElementType();
479  Alignment = DL.getABITypeAlignment(EltType);
480  }
481 
482  AMemSet =
483  Builder.CreateMemSet(StartPtr, ByteVal, Range.End-Range.Start, Alignment);
484 
485  LLVM_DEBUG(dbgs() << "Replace stores:\n"; for (Instruction *SI
486  : Range.TheStores) dbgs()
487  << *SI << '\n';
488  dbgs() << "With: " << *AMemSet << '\n');
489 
490  if (!Range.TheStores.empty())
491  AMemSet->setDebugLoc(Range.TheStores[0]->getDebugLoc());
492 
493  // Zap all the stores.
494  for (Instruction *SI : Range.TheStores) {
495  MD->removeInstruction(SI);
496  SI->eraseFromParent();
497  }
498  ++NumMemSetInfer;
499  }
500 
501  return AMemSet;
502 }
503 
504 static unsigned findStoreAlignment(const DataLayout &DL, const StoreInst *SI) {
505  unsigned StoreAlign = SI->getAlignment();
506  if (!StoreAlign)
507  StoreAlign = DL.getABITypeAlignment(SI->getOperand(0)->getType());
508  return StoreAlign;
509 }
510 
511 static unsigned findLoadAlignment(const DataLayout &DL, const LoadInst *LI) {
512  unsigned LoadAlign = LI->getAlignment();
513  if (!LoadAlign)
514  LoadAlign = DL.getABITypeAlignment(LI->getType());
515  return LoadAlign;
516 }
517 
518 static unsigned findCommonAlignment(const DataLayout &DL, const StoreInst *SI,
519  const LoadInst *LI) {
520  unsigned StoreAlign = findStoreAlignment(DL, SI);
521  unsigned LoadAlign = findLoadAlignment(DL, LI);
522  return MinAlign(StoreAlign, LoadAlign);
523 }
524 
525 // This method try to lift a store instruction before position P.
526 // It will lift the store and its argument + that anything that
527 // may alias with these.
528 // The method returns true if it was successful.
530  const LoadInst *LI) {
531  // If the store alias this position, early bail out.
532  MemoryLocation StoreLoc = MemoryLocation::get(SI);
533  if (isModOrRefSet(AA.getModRefInfo(P, StoreLoc)))
534  return false;
535 
536  // Keep track of the arguments of all instruction we plan to lift
537  // so we can make sure to lift them as well if appropriate.
539  if (auto *Ptr = dyn_cast<Instruction>(SI->getPointerOperand()))
540  if (Ptr->getParent() == SI->getParent())
541  Args.insert(Ptr);
542 
543  // Instruction to lift before P.
545 
546  // Memory locations of lifted instructions.
547  SmallVector<MemoryLocation, 8> MemLocs{StoreLoc};
548 
549  // Lifted callsites.
551 
552  const MemoryLocation LoadLoc = MemoryLocation::get(LI);
553 
554  for (auto I = --SI->getIterator(), E = P->getIterator(); I != E; --I) {
555  auto *C = &*I;
556 
558 
559  bool NeedLift = false;
560  if (Args.erase(C))
561  NeedLift = true;
562  else if (MayAlias) {
563  NeedLift = llvm::any_of(MemLocs, [C, &AA](const MemoryLocation &ML) {
564  return isModOrRefSet(AA.getModRefInfo(C, ML));
565  });
566 
567  if (!NeedLift)
568  NeedLift =
569  llvm::any_of(CallSites, [C, &AA](const ImmutableCallSite &CS) {
570  return isModOrRefSet(AA.getModRefInfo(C, CS));
571  });
572  }
573 
574  if (!NeedLift)
575  continue;
576 
577  if (MayAlias) {
578  // Since LI is implicitly moved downwards past the lifted instructions,
579  // none of them may modify its source.
580  if (isModSet(AA.getModRefInfo(C, LoadLoc)))
581  return false;
582  else if (auto CS = ImmutableCallSite(C)) {
583  // If we can't lift this before P, it's game over.
584  if (isModOrRefSet(AA.getModRefInfo(P, CS)))
585  return false;
586 
587  CallSites.push_back(CS);
588  } else if (isa<LoadInst>(C) || isa<StoreInst>(C) || isa<VAArgInst>(C)) {
589  // If we can't lift this before P, it's game over.
590  auto ML = MemoryLocation::get(C);
591  if (isModOrRefSet(AA.getModRefInfo(P, ML)))
592  return false;
593 
594  MemLocs.push_back(ML);
595  } else
596  // We don't know how to lift this instruction.
597  return false;
598  }
599 
600  ToLift.push_back(C);
601  for (unsigned k = 0, e = C->getNumOperands(); k != e; ++k)
602  if (auto *A = dyn_cast<Instruction>(C->getOperand(k)))
603  if (A->getParent() == SI->getParent())
604  Args.insert(A);
605  }
606 
607  // We made it, we need to lift
608  for (auto *I : llvm::reverse(ToLift)) {
609  LLVM_DEBUG(dbgs() << "Lifting " << *I << " before " << *P << "\n");
610  I->moveBefore(P);
611  }
612 
613  return true;
614 }
615 
616 bool MemCpyOptPass::processStore(StoreInst *SI, BasicBlock::iterator &BBI) {
617  if (!SI->isSimple()) return false;
618 
619  // Avoid merging nontemporal stores since the resulting
620  // memcpy/memset would not be able to preserve the nontemporal hint.
621  // In theory we could teach how to propagate the !nontemporal metadata to
622  // memset calls. However, that change would force the backend to
623  // conservatively expand !nontemporal memset calls back to sequences of
624  // store instructions (effectively undoing the merging).
626  return false;
627 
628  const DataLayout &DL = SI->getModule()->getDataLayout();
629 
630  // Load to store forwarding can be interpreted as memcpy.
631  if (LoadInst *LI = dyn_cast<LoadInst>(SI->getOperand(0))) {
632  if (LI->isSimple() && LI->hasOneUse() &&
633  LI->getParent() == SI->getParent()) {
634 
635  auto *T = LI->getType();
636  if (T->isAggregateType()) {
637  AliasAnalysis &AA = LookupAliasAnalysis();
638  MemoryLocation LoadLoc = MemoryLocation::get(LI);
639 
640  // We use alias analysis to check if an instruction may store to
641  // the memory we load from in between the load and the store. If
642  // such an instruction is found, we try to promote there instead
643  // of at the store position.
644  Instruction *P = SI;
645  for (auto &I : make_range(++LI->getIterator(), SI->getIterator())) {
646  if (isModSet(AA.getModRefInfo(&I, LoadLoc))) {
647  P = &I;
648  break;
649  }
650  }
651 
652  // We found an instruction that may write to the loaded memory.
653  // We can try to promote at this position instead of the store
654  // position if nothing alias the store memory after this and the store
655  // destination is not in the range.
656  if (P && P != SI) {
657  if (!moveUp(AA, SI, P, LI))
658  P = nullptr;
659  }
660 
661  // If a valid insertion position is found, then we can promote
662  // the load/store pair to a memcpy.
663  if (P) {
664  // If we load from memory that may alias the memory we store to,
665  // memmove must be used to preserve semantic. If not, memcpy can
666  // be used.
667  bool UseMemMove = false;
668  if (!AA.isNoAlias(MemoryLocation::get(SI), LoadLoc))
669  UseMemMove = true;
670 
671  uint64_t Size = DL.getTypeStoreSize(T);
672 
673  IRBuilder<> Builder(P);
674  Instruction *M;
675  if (UseMemMove)
676  M = Builder.CreateMemMove(
677  SI->getPointerOperand(), findStoreAlignment(DL, SI),
678  LI->getPointerOperand(), findLoadAlignment(DL, LI), Size,
679  SI->isVolatile());
680  else
681  M = Builder.CreateMemCpy(
682  SI->getPointerOperand(), findStoreAlignment(DL, SI),
683  LI->getPointerOperand(), findLoadAlignment(DL, LI), Size,
684  SI->isVolatile());
685 
686  LLVM_DEBUG(dbgs() << "Promoting " << *LI << " to " << *SI << " => "
687  << *M << "\n");
688 
689  MD->removeInstruction(SI);
690  SI->eraseFromParent();
691  MD->removeInstruction(LI);
692  LI->eraseFromParent();
693  ++NumMemCpyInstr;
694 
695  // Make sure we do not invalidate the iterator.
696  BBI = M->getIterator();
697  return true;
698  }
699  }
700 
701  // Detect cases where we're performing call slot forwarding, but
702  // happen to be using a load-store pair to implement it, rather than
703  // a memcpy.
704  MemDepResult ldep = MD->getDependency(LI);
705  CallInst *C = nullptr;
706  if (ldep.isClobber() && !isa<MemCpyInst>(ldep.getInst()))
707  C = dyn_cast<CallInst>(ldep.getInst());
708 
709  if (C) {
710  // Check that nothing touches the dest of the "copy" between
711  // the call and the store.
712  Value *CpyDest = SI->getPointerOperand()->stripPointerCasts();
713  bool CpyDestIsLocal = isa<AllocaInst>(CpyDest);
714  AliasAnalysis &AA = LookupAliasAnalysis();
715  MemoryLocation StoreLoc = MemoryLocation::get(SI);
716  for (BasicBlock::iterator I = --SI->getIterator(), E = C->getIterator();
717  I != E; --I) {
718  if (isModOrRefSet(AA.getModRefInfo(&*I, StoreLoc))) {
719  C = nullptr;
720  break;
721  }
722  // The store to dest may never happen if an exception can be thrown
723  // between the load and the store.
724  if (I->mayThrow() && !CpyDestIsLocal) {
725  C = nullptr;
726  break;
727  }
728  }
729  }
730 
731  if (C) {
732  bool changed = performCallSlotOptzn(
734  LI->getPointerOperand()->stripPointerCasts(),
735  DL.getTypeStoreSize(SI->getOperand(0)->getType()),
736  findCommonAlignment(DL, SI, LI), C);
737  if (changed) {
738  MD->removeInstruction(SI);
739  SI->eraseFromParent();
740  MD->removeInstruction(LI);
741  LI->eraseFromParent();
742  ++NumMemCpyInstr;
743  return true;
744  }
745  }
746  }
747  }
748 
749  // There are two cases that are interesting for this code to handle: memcpy
750  // and memset. Right now we only handle memset.
751 
752  // Ensure that the value being stored is something that can be memset'able a
753  // byte at a time like "0" or "-1" or any width, as well as things like
754  // 0xA0A0A0A0 and 0.0.
755  auto *V = SI->getOperand(0);
756  if (Value *ByteVal = isBytewiseValue(V)) {
757  if (Instruction *I = tryMergingIntoMemset(SI, SI->getPointerOperand(),
758  ByteVal)) {
759  BBI = I->getIterator(); // Don't invalidate iterator.
760  return true;
761  }
762 
763  // If we have an aggregate, we try to promote it to memset regardless
764  // of opportunity for merging as it can expose optimization opportunities
765  // in subsequent passes.
766  auto *T = V->getType();
767  if (T->isAggregateType()) {
768  uint64_t Size = DL.getTypeStoreSize(T);
769  unsigned Align = SI->getAlignment();
770  if (!Align)
771  Align = DL.getABITypeAlignment(T);
772  IRBuilder<> Builder(SI);
773  auto *M = Builder.CreateMemSet(SI->getPointerOperand(), ByteVal,
774  Size, Align, SI->isVolatile());
775 
776  LLVM_DEBUG(dbgs() << "Promoting " << *SI << " to " << *M << "\n");
777 
778  MD->removeInstruction(SI);
779  SI->eraseFromParent();
780  NumMemSetInfer++;
781 
782  // Make sure we do not invalidate the iterator.
783  BBI = M->getIterator();
784  return true;
785  }
786  }
787 
788  return false;
789 }
790 
791 bool MemCpyOptPass::processMemSet(MemSetInst *MSI, BasicBlock::iterator &BBI) {
792  // See if there is another memset or store neighboring this memset which
793  // allows us to widen out the memset to do a single larger store.
794  if (isa<ConstantInt>(MSI->getLength()) && !MSI->isVolatile())
795  if (Instruction *I = tryMergingIntoMemset(MSI, MSI->getDest(),
796  MSI->getValue())) {
797  BBI = I->getIterator(); // Don't invalidate iterator.
798  return true;
799  }
800  return false;
801 }
802 
803 /// Takes a memcpy and a call that it depends on,
804 /// and checks for the possibility of a call slot optimization by having
805 /// the call write its result directly into the destination of the memcpy.
806 bool MemCpyOptPass::performCallSlotOptzn(Instruction *cpy, Value *cpyDest,
807  Value *cpySrc, uint64_t cpyLen,
808  unsigned cpyAlign, CallInst *C) {
809  // The general transformation to keep in mind is
810  //
811  // call @func(..., src, ...)
812  // memcpy(dest, src, ...)
813  //
814  // ->
815  //
816  // memcpy(dest, src, ...)
817  // call @func(..., dest, ...)
818  //
819  // Since moving the memcpy is technically awkward, we additionally check that
820  // src only holds uninitialized values at the moment of the call, meaning that
821  // the memcpy can be discarded rather than moved.
822 
823  // Lifetime marks shouldn't be operated on.
824  if (Function *F = C->getCalledFunction())
825  if (F->isIntrinsic() && F->getIntrinsicID() == Intrinsic::lifetime_start)
826  return false;
827 
828  // Deliberately get the source and destination with bitcasts stripped away,
829  // because we'll need to do type comparisons based on the underlying type.
830  CallSite CS(C);
831 
832  // Require that src be an alloca. This simplifies the reasoning considerably.
833  AllocaInst *srcAlloca = dyn_cast<AllocaInst>(cpySrc);
834  if (!srcAlloca)
835  return false;
836 
837  ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
838  if (!srcArraySize)
839  return false;
840 
841  const DataLayout &DL = cpy->getModule()->getDataLayout();
842  uint64_t srcSize = DL.getTypeAllocSize(srcAlloca->getAllocatedType()) *
843  srcArraySize->getZExtValue();
844 
845  if (cpyLen < srcSize)
846  return false;
847 
848  // Check that accessing the first srcSize bytes of dest will not cause a
849  // trap. Otherwise the transform is invalid since it might cause a trap
850  // to occur earlier than it otherwise would.
851  if (AllocaInst *A = dyn_cast<AllocaInst>(cpyDest)) {
852  // The destination is an alloca. Check it is larger than srcSize.
853  ConstantInt *destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
854  if (!destArraySize)
855  return false;
856 
857  uint64_t destSize = DL.getTypeAllocSize(A->getAllocatedType()) *
858  destArraySize->getZExtValue();
859 
860  if (destSize < srcSize)
861  return false;
862  } else if (Argument *A = dyn_cast<Argument>(cpyDest)) {
863  // The store to dest may never happen if the call can throw.
864  if (C->mayThrow())
865  return false;
866 
867  if (A->getDereferenceableBytes() < srcSize) {
868  // If the destination is an sret parameter then only accesses that are
869  // outside of the returned struct type can trap.
870  if (!A->hasStructRetAttr())
871  return false;
872 
873  Type *StructTy = cast<PointerType>(A->getType())->getElementType();
874  if (!StructTy->isSized()) {
875  // The call may never return and hence the copy-instruction may never
876  // be executed, and therefore it's not safe to say "the destination
877  // has at least <cpyLen> bytes, as implied by the copy-instruction",
878  return false;
879  }
880 
881  uint64_t destSize = DL.getTypeAllocSize(StructTy);
882  if (destSize < srcSize)
883  return false;
884  }
885  } else {
886  return false;
887  }
888 
889  // Check that dest points to memory that is at least as aligned as src.
890  unsigned srcAlign = srcAlloca->getAlignment();
891  if (!srcAlign)
892  srcAlign = DL.getABITypeAlignment(srcAlloca->getAllocatedType());
893  bool isDestSufficientlyAligned = srcAlign <= cpyAlign;
894  // If dest is not aligned enough and we can't increase its alignment then
895  // bail out.
896  if (!isDestSufficientlyAligned && !isa<AllocaInst>(cpyDest))
897  return false;
898 
899  // Check that src is not accessed except via the call and the memcpy. This
900  // guarantees that it holds only undefined values when passed in (so the final
901  // memcpy can be dropped), that it is not read or written between the call and
902  // the memcpy, and that writing beyond the end of it is undefined.
903  SmallVector<User*, 8> srcUseList(srcAlloca->user_begin(),
904  srcAlloca->user_end());
905  while (!srcUseList.empty()) {
906  User *U = srcUseList.pop_back_val();
907 
908  if (isa<BitCastInst>(U) || isa<AddrSpaceCastInst>(U)) {
909  for (User *UU : U->users())
910  srcUseList.push_back(UU);
911  continue;
912  }
913  if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(U)) {
914  if (!G->hasAllZeroIndices())
915  return false;
916 
917  for (User *UU : U->users())
918  srcUseList.push_back(UU);
919  continue;
920  }
921  if (const IntrinsicInst *IT = dyn_cast<IntrinsicInst>(U))
922  if (IT->getIntrinsicID() == Intrinsic::lifetime_start ||
923  IT->getIntrinsicID() == Intrinsic::lifetime_end)
924  continue;
925 
926  if (U != C && U != cpy)
927  return false;
928  }
929 
930  // Check that src isn't captured by the called function since the
931  // transformation can cause aliasing issues in that case.
932  for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
933  if (CS.getArgument(i) == cpySrc && !CS.doesNotCapture(i))
934  return false;
935 
936  // Since we're changing the parameter to the callsite, we need to make sure
937  // that what would be the new parameter dominates the callsite.
938  DominatorTree &DT = LookupDomTree();
939  if (Instruction *cpyDestInst = dyn_cast<Instruction>(cpyDest))
940  if (!DT.dominates(cpyDestInst, C))
941  return false;
942 
943  // In addition to knowing that the call does not access src in some
944  // unexpected manner, for example via a global, which we deduce from
945  // the use analysis, we also need to know that it does not sneakily
946  // access dest. We rely on AA to figure this out for us.
947  AliasAnalysis &AA = LookupAliasAnalysis();
948  ModRefInfo MR = AA.getModRefInfo(C, cpyDest, srcSize);
949  // If necessary, perform additional analysis.
950  if (isModOrRefSet(MR))
951  MR = AA.callCapturesBefore(C, cpyDest, srcSize, &DT);
952  if (isModOrRefSet(MR))
953  return false;
954 
955  // We can't create address space casts here because we don't know if they're
956  // safe for the target.
957  if (cpySrc->getType()->getPointerAddressSpace() !=
958  cpyDest->getType()->getPointerAddressSpace())
959  return false;
960  for (unsigned i = 0; i < CS.arg_size(); ++i)
961  if (CS.getArgument(i)->stripPointerCasts() == cpySrc &&
962  cpySrc->getType()->getPointerAddressSpace() !=
964  return false;
965 
966  // All the checks have passed, so do the transformation.
967  bool changedArgument = false;
968  for (unsigned i = 0; i < CS.arg_size(); ++i)
969  if (CS.getArgument(i)->stripPointerCasts() == cpySrc) {
970  Value *Dest = cpySrc->getType() == cpyDest->getType() ? cpyDest
971  : CastInst::CreatePointerCast(cpyDest, cpySrc->getType(),
972  cpyDest->getName(), C);
973  changedArgument = true;
974  if (CS.getArgument(i)->getType() == Dest->getType())
975  CS.setArgument(i, Dest);
976  else
978  CS.getArgument(i)->getType(), Dest->getName(), C));
979  }
980 
981  if (!changedArgument)
982  return false;
983 
984  // If the destination wasn't sufficiently aligned then increase its alignment.
985  if (!isDestSufficientlyAligned) {
986  assert(isa<AllocaInst>(cpyDest) && "Can only increase alloca alignment!");
987  cast<AllocaInst>(cpyDest)->setAlignment(srcAlign);
988  }
989 
990  // Drop any cached information about the call, because we may have changed
991  // its dependence information by changing its parameter.
992  MD->removeInstruction(C);
993 
994  // Update AA metadata
995  // FIXME: MD_tbaa_struct and MD_mem_parallel_loop_access should also be
996  // handled here, but combineMetadata doesn't support them yet
997  unsigned KnownIDs[] = {LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
1000  combineMetadata(C, cpy, KnownIDs, true);
1001 
1002  // Remove the memcpy.
1003  MD->removeInstruction(cpy);
1004  ++NumMemCpyInstr;
1005 
1006  return true;
1007 }
1008 
1009 /// We've found that the (upward scanning) memory dependence of memcpy 'M' is
1010 /// the memcpy 'MDep'. Try to simplify M to copy from MDep's input if we can.
1011 bool MemCpyOptPass::processMemCpyMemCpyDependence(MemCpyInst *M,
1012  MemCpyInst *MDep) {
1013  // We can only transforms memcpy's where the dest of one is the source of the
1014  // other.
1015  if (M->getSource() != MDep->getDest() || MDep->isVolatile())
1016  return false;
1017 
1018  // If dep instruction is reading from our current input, then it is a noop
1019  // transfer and substituting the input won't change this instruction. Just
1020  // ignore the input and let someone else zap MDep. This handles cases like:
1021  // memcpy(a <- a)
1022  // memcpy(b <- a)
1023  if (M->getSource() == MDep->getSource())
1024  return false;
1025 
1026  // Second, the length of the memcpy's must be the same, or the preceding one
1027  // must be larger than the following one.
1028  ConstantInt *MDepLen = dyn_cast<ConstantInt>(MDep->getLength());
1029  ConstantInt *MLen = dyn_cast<ConstantInt>(M->getLength());
1030  if (!MDepLen || !MLen || MDepLen->getZExtValue() < MLen->getZExtValue())
1031  return false;
1032 
1033  AliasAnalysis &AA = LookupAliasAnalysis();
1034 
1035  // Verify that the copied-from memory doesn't change in between the two
1036  // transfers. For example, in:
1037  // memcpy(a <- b)
1038  // *b = 42;
1039  // memcpy(c <- a)
1040  // It would be invalid to transform the second memcpy into memcpy(c <- b).
1041  //
1042  // TODO: If the code between M and MDep is transparent to the destination "c",
1043  // then we could still perform the xform by moving M up to the first memcpy.
1044  //
1045  // NOTE: This is conservative, it will stop on any read from the source loc,
1046  // not just the defining memcpy.
1047  MemDepResult SourceDep =
1048  MD->getPointerDependencyFrom(MemoryLocation::getForSource(MDep), false,
1049  M->getIterator(), M->getParent());
1050  if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
1051  return false;
1052 
1053  // If the dest of the second might alias the source of the first, then the
1054  // source and dest might overlap. We still want to eliminate the intermediate
1055  // value, but we have to generate a memmove instead of memcpy.
1056  bool UseMemMove = false;
1059  UseMemMove = true;
1060 
1061  // If all checks passed, then we can transform M.
1062 
1063  // TODO: Is this worth it if we're creating a less aligned memcpy? For
1064  // example we could be moving from movaps -> movq on x86.
1065  IRBuilder<> Builder(M);
1066  if (UseMemMove)
1067  Builder.CreateMemMove(M->getRawDest(), M->getDestAlignment(),
1068  MDep->getRawSource(), MDep->getSourceAlignment(),
1069  M->getLength(), M->isVolatile());
1070  else
1071  Builder.CreateMemCpy(M->getRawDest(), M->getDestAlignment(),
1072  MDep->getRawSource(), MDep->getSourceAlignment(),
1073  M->getLength(), M->isVolatile());
1074 
1075  // Remove the instruction we're replacing.
1076  MD->removeInstruction(M);
1077  M->eraseFromParent();
1078  ++NumMemCpyInstr;
1079  return true;
1080 }
1081 
1082 /// We've found that the (upward scanning) memory dependence of \p MemCpy is
1083 /// \p MemSet. Try to simplify \p MemSet to only set the trailing bytes that
1084 /// weren't copied over by \p MemCpy.
1085 ///
1086 /// In other words, transform:
1087 /// \code
1088 /// memset(dst, c, dst_size);
1089 /// memcpy(dst, src, src_size);
1090 /// \endcode
1091 /// into:
1092 /// \code
1093 /// memcpy(dst, src, src_size);
1094 /// memset(dst + src_size, c, dst_size <= src_size ? 0 : dst_size - src_size);
1095 /// \endcode
1096 bool MemCpyOptPass::processMemSetMemCpyDependence(MemCpyInst *MemCpy,
1097  MemSetInst *MemSet) {
1098  // We can only transform memset/memcpy with the same destination.
1099  if (MemSet->getDest() != MemCpy->getDest())
1100  return false;
1101 
1102  // Check that there are no other dependencies on the memset destination.
1103  MemDepResult DstDepInfo =
1104  MD->getPointerDependencyFrom(MemoryLocation::getForDest(MemSet), false,
1105  MemCpy->getIterator(), MemCpy->getParent());
1106  if (DstDepInfo.getInst() != MemSet)
1107  return false;
1108 
1109  // Use the same i8* dest as the memcpy, killing the memset dest if different.
1110  Value *Dest = MemCpy->getRawDest();
1111  Value *DestSize = MemSet->getLength();
1112  Value *SrcSize = MemCpy->getLength();
1113 
1114  // By default, create an unaligned memset.
1115  unsigned Align = 1;
1116  // If Dest is aligned, and SrcSize is constant, use the minimum alignment
1117  // of the sum.
1118  const unsigned DestAlign =
1119  std::max(MemSet->getDestAlignment(), MemCpy->getDestAlignment());
1120  if (DestAlign > 1)
1121  if (ConstantInt *SrcSizeC = dyn_cast<ConstantInt>(SrcSize))
1122  Align = MinAlign(SrcSizeC->getZExtValue(), DestAlign);
1123 
1124  IRBuilder<> Builder(MemCpy);
1125 
1126  // If the sizes have different types, zext the smaller one.
1127  if (DestSize->getType() != SrcSize->getType()) {
1128  if (DestSize->getType()->getIntegerBitWidth() >
1129  SrcSize->getType()->getIntegerBitWidth())
1130  SrcSize = Builder.CreateZExt(SrcSize, DestSize->getType());
1131  else
1132  DestSize = Builder.CreateZExt(DestSize, SrcSize->getType());
1133  }
1134 
1135  Value *Ule = Builder.CreateICmpULE(DestSize, SrcSize);
1136  Value *SizeDiff = Builder.CreateSub(DestSize, SrcSize);
1137  Value *MemsetLen = Builder.CreateSelect(
1138  Ule, ConstantInt::getNullValue(DestSize->getType()), SizeDiff);
1139  Builder.CreateMemSet(Builder.CreateGEP(Dest, SrcSize), MemSet->getOperand(1),
1140  MemsetLen, Align);
1141 
1142  MD->removeInstruction(MemSet);
1143  MemSet->eraseFromParent();
1144  return true;
1145 }
1146 
1147 /// Determine whether the instruction has undefined content for the given Size,
1148 /// either because it was freshly alloca'd or started its lifetime.
1150  if (isa<AllocaInst>(I))
1151  return true;
1152 
1153  if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1154  if (II->getIntrinsicID() == Intrinsic::lifetime_start)
1155  if (ConstantInt *LTSize = dyn_cast<ConstantInt>(II->getArgOperand(0)))
1156  if (LTSize->getZExtValue() >= Size->getZExtValue())
1157  return true;
1158 
1159  return false;
1160 }
1161 
1162 /// Transform memcpy to memset when its source was just memset.
1163 /// In other words, turn:
1164 /// \code
1165 /// memset(dst1, c, dst1_size);
1166 /// memcpy(dst2, dst1, dst2_size);
1167 /// \endcode
1168 /// into:
1169 /// \code
1170 /// memset(dst1, c, dst1_size);
1171 /// memset(dst2, c, dst2_size);
1172 /// \endcode
1173 /// When dst2_size <= dst1_size.
1174 ///
1175 /// The \p MemCpy must have a Constant length.
1176 bool MemCpyOptPass::performMemCpyToMemSetOptzn(MemCpyInst *MemCpy,
1177  MemSetInst *MemSet) {
1178  AliasAnalysis &AA = LookupAliasAnalysis();
1179 
1180  // Make sure that memcpy(..., memset(...), ...), that is we are memsetting and
1181  // memcpying from the same address. Otherwise it is hard to reason about.
1182  if (!AA.isMustAlias(MemSet->getRawDest(), MemCpy->getRawSource()))
1183  return false;
1184 
1185  // A known memset size is required.
1186  ConstantInt *MemSetSize = dyn_cast<ConstantInt>(MemSet->getLength());
1187  if (!MemSetSize)
1188  return false;
1189 
1190  // Make sure the memcpy doesn't read any more than what the memset wrote.
1191  // Don't worry about sizes larger than i64.
1192  ConstantInt *CopySize = cast<ConstantInt>(MemCpy->getLength());
1193  if (CopySize->getZExtValue() > MemSetSize->getZExtValue()) {
1194  // If the memcpy is larger than the memset, but the memory was undef prior
1195  // to the memset, we can just ignore the tail. Technically we're only
1196  // interested in the bytes from MemSetSize..CopySize here, but as we can't
1197  // easily represent this location, we use the full 0..CopySize range.
1198  MemoryLocation MemCpyLoc = MemoryLocation::getForSource(MemCpy);
1199  MemDepResult DepInfo = MD->getPointerDependencyFrom(
1200  MemCpyLoc, true, MemSet->getIterator(), MemSet->getParent());
1201  if (DepInfo.isDef() && hasUndefContents(DepInfo.getInst(), CopySize))
1202  CopySize = MemSetSize;
1203  else
1204  return false;
1205  }
1206 
1207  IRBuilder<> Builder(MemCpy);
1208  Builder.CreateMemSet(MemCpy->getRawDest(), MemSet->getOperand(1),
1209  CopySize, MemCpy->getDestAlignment());
1210  return true;
1211 }
1212 
1213 /// Perform simplification of memcpy's. If we have memcpy A
1214 /// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite
1215 /// B to be a memcpy from X to Z (or potentially a memmove, depending on
1216 /// circumstances). This allows later passes to remove the first memcpy
1217 /// altogether.
1218 bool MemCpyOptPass::processMemCpy(MemCpyInst *M) {
1219  // We can only optimize non-volatile memcpy's.
1220  if (M->isVolatile()) return false;
1221 
1222  // If the source and destination of the memcpy are the same, then zap it.
1223  if (M->getSource() == M->getDest()) {
1224  MD->removeInstruction(M);
1225  M->eraseFromParent();
1226  return false;
1227  }
1228 
1229  // If copying from a constant, try to turn the memcpy into a memset.
1230  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(M->getSource()))
1231  if (GV->isConstant() && GV->hasDefinitiveInitializer())
1232  if (Value *ByteVal = isBytewiseValue(GV->getInitializer())) {
1233  IRBuilder<> Builder(M);
1234  Builder.CreateMemSet(M->getRawDest(), ByteVal, M->getLength(),
1235  M->getDestAlignment(), false);
1236  MD->removeInstruction(M);
1237  M->eraseFromParent();
1238  ++NumCpyToSet;
1239  return true;
1240  }
1241 
1242  MemDepResult DepInfo = MD->getDependency(M);
1243 
1244  // Try to turn a partially redundant memset + memcpy into
1245  // memcpy + smaller memset. We don't need the memcpy size for this.
1246  if (DepInfo.isClobber())
1247  if (MemSetInst *MDep = dyn_cast<MemSetInst>(DepInfo.getInst()))
1248  if (processMemSetMemCpyDependence(M, MDep))
1249  return true;
1250 
1251  // The optimizations after this point require the memcpy size.
1252  ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength());
1253  if (!CopySize) return false;
1254 
1255  // There are four possible optimizations we can do for memcpy:
1256  // a) memcpy-memcpy xform which exposes redundance for DSE.
1257  // b) call-memcpy xform for return slot optimization.
1258  // c) memcpy from freshly alloca'd space or space that has just started its
1259  // lifetime copies undefined data, and we can therefore eliminate the
1260  // memcpy in favor of the data that was already at the destination.
1261  // d) memcpy from a just-memset'd source can be turned into memset.
1262  if (DepInfo.isClobber()) {
1263  if (CallInst *C = dyn_cast<CallInst>(DepInfo.getInst())) {
1264  // FIXME: Can we pass in either of dest/src alignment here instead
1265  // of conservatively taking the minimum?
1266  unsigned Align = MinAlign(M->getDestAlignment(), M->getSourceAlignment());
1267  if (performCallSlotOptzn(M, M->getDest(), M->getSource(),
1268  CopySize->getZExtValue(), Align,
1269  C)) {
1270  MD->removeInstruction(M);
1271  M->eraseFromParent();
1272  return true;
1273  }
1274  }
1275  }
1276 
1278  MemDepResult SrcDepInfo = MD->getPointerDependencyFrom(
1279  SrcLoc, true, M->getIterator(), M->getParent());
1280 
1281  if (SrcDepInfo.isClobber()) {
1282  if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(SrcDepInfo.getInst()))
1283  return processMemCpyMemCpyDependence(M, MDep);
1284  } else if (SrcDepInfo.isDef()) {
1285  if (hasUndefContents(SrcDepInfo.getInst(), CopySize)) {
1286  MD->removeInstruction(M);
1287  M->eraseFromParent();
1288  ++NumMemCpyInstr;
1289  return true;
1290  }
1291  }
1292 
1293  if (SrcDepInfo.isClobber())
1294  if (MemSetInst *MDep = dyn_cast<MemSetInst>(SrcDepInfo.getInst()))
1295  if (performMemCpyToMemSetOptzn(M, MDep)) {
1296  MD->removeInstruction(M);
1297  M->eraseFromParent();
1298  ++NumCpyToSet;
1299  return true;
1300  }
1301 
1302  return false;
1303 }
1304 
1305 /// Transforms memmove calls to memcpy calls when the src/dst are guaranteed
1306 /// not to alias.
1307 bool MemCpyOptPass::processMemMove(MemMoveInst *M) {
1308  AliasAnalysis &AA = LookupAliasAnalysis();
1309 
1310  if (!TLI->has(LibFunc_memmove))
1311  return false;
1312 
1313  // See if the pointers alias.
1316  return false;
1317 
1318  LLVM_DEBUG(dbgs() << "MemCpyOptPass: Optimizing memmove -> memcpy: " << *M
1319  << "\n");
1320 
1321  // If not, then we know we can transform this.
1322  Type *ArgTys[3] = { M->getRawDest()->getType(),
1323  M->getRawSource()->getType(),
1324  M->getLength()->getType() };
1326  Intrinsic::memcpy, ArgTys));
1327 
1328  // MemDep may have over conservative information about this instruction, just
1329  // conservatively flush it from the cache.
1330  MD->removeInstruction(M);
1331 
1332  ++NumMoveToCpy;
1333  return true;
1334 }
1335 
1336 /// This is called on every byval argument in call sites.
1337 bool MemCpyOptPass::processByValArgument(CallSite CS, unsigned ArgNo) {
1338  const DataLayout &DL = CS.getCaller()->getParent()->getDataLayout();
1339  // Find out what feeds this byval argument.
1340  Value *ByValArg = CS.getArgument(ArgNo);
1341  Type *ByValTy = cast<PointerType>(ByValArg->getType())->getElementType();
1342  uint64_t ByValSize = DL.getTypeAllocSize(ByValTy);
1343  MemDepResult DepInfo = MD->getPointerDependencyFrom(
1344  MemoryLocation(ByValArg, ByValSize), true,
1346  if (!DepInfo.isClobber())
1347  return false;
1348 
1349  // If the byval argument isn't fed by a memcpy, ignore it. If it is fed by
1350  // a memcpy, see if we can byval from the source of the memcpy instead of the
1351  // result.
1352  MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst());
1353  if (!MDep || MDep->isVolatile() ||
1354  ByValArg->stripPointerCasts() != MDep->getDest())
1355  return false;
1356 
1357  // The length of the memcpy must be larger or equal to the size of the byval.
1358  ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
1359  if (!C1 || C1->getValue().getZExtValue() < ByValSize)
1360  return false;
1361 
1362  // Get the alignment of the byval. If the call doesn't specify the alignment,
1363  // then it is some target specific value that we can't know.
1364  unsigned ByValAlign = CS.getParamAlignment(ArgNo);
1365  if (ByValAlign == 0) return false;
1366 
1367  // If it is greater than the memcpy, then we check to see if we can force the
1368  // source of the memcpy to the alignment we need. If we fail, we bail out.
1369  AssumptionCache &AC = LookupAssumptionCache();
1370  DominatorTree &DT = LookupDomTree();
1371  if (MDep->getSourceAlignment() < ByValAlign &&
1372  getOrEnforceKnownAlignment(MDep->getSource(), ByValAlign, DL,
1373  CS.getInstruction(), &AC, &DT) < ByValAlign)
1374  return false;
1375 
1376  // The address space of the memcpy source must match the byval argument
1377  if (MDep->getSource()->getType()->getPointerAddressSpace() !=
1378  ByValArg->getType()->getPointerAddressSpace())
1379  return false;
1380 
1381  // Verify that the copied-from memory doesn't change in between the memcpy and
1382  // the byval call.
1383  // memcpy(a <- b)
1384  // *b = 42;
1385  // foo(*a)
1386  // It would be invalid to transform the second memcpy into foo(*b).
1387  //
1388  // NOTE: This is conservative, it will stop on any read from the source loc,
1389  // not just the defining memcpy.
1390  MemDepResult SourceDep = MD->getPointerDependencyFrom(
1391  MemoryLocation::getForSource(MDep), false,
1392  CS.getInstruction()->getIterator(), MDep->getParent());
1393  if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
1394  return false;
1395 
1396  Value *TmpCast = MDep->getSource();
1397  if (MDep->getSource()->getType() != ByValArg->getType())
1398  TmpCast = new BitCastInst(MDep->getSource(), ByValArg->getType(),
1399  "tmpcast", CS.getInstruction());
1400 
1401  LLVM_DEBUG(dbgs() << "MemCpyOptPass: Forwarding memcpy to byval:\n"
1402  << " " << *MDep << "\n"
1403  << " " << *CS.getInstruction() << "\n");
1404 
1405  // Otherwise we're good! Update the byval argument.
1406  CS.setArgument(ArgNo, TmpCast);
1407  ++NumMemCpyInstr;
1408  return true;
1409 }
1410 
1411 /// Executes one iteration of MemCpyOptPass.
1412 bool MemCpyOptPass::iterateOnFunction(Function &F) {
1413  bool MadeChange = false;
1414 
1415  DominatorTree &DT = LookupDomTree();
1416 
1417  // Walk all instruction in the function.
1418  for (BasicBlock &BB : F) {
1419  // Skip unreachable blocks. For example processStore assumes that an
1420  // instruction in a BB can't be dominated by a later instruction in the
1421  // same BB (which is a scenario that can happen for an unreachable BB that
1422  // has itself as a predecessor).
1423  if (!DT.isReachableFromEntry(&BB))
1424  continue;
1425 
1426  for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
1427  // Avoid invalidating the iterator.
1428  Instruction *I = &*BI++;
1429 
1430  bool RepeatInstruction = false;
1431 
1432  if (StoreInst *SI = dyn_cast<StoreInst>(I))
1433  MadeChange |= processStore(SI, BI);
1434  else if (MemSetInst *M = dyn_cast<MemSetInst>(I))
1435  RepeatInstruction = processMemSet(M, BI);
1436  else if (MemCpyInst *M = dyn_cast<MemCpyInst>(I))
1437  RepeatInstruction = processMemCpy(M);
1438  else if (MemMoveInst *M = dyn_cast<MemMoveInst>(I))
1439  RepeatInstruction = processMemMove(M);
1440  else if (auto CS = CallSite(I)) {
1441  for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
1442  if (CS.isByValArgument(i))
1443  MadeChange |= processByValArgument(CS, i);
1444  }
1445 
1446  // Reprocess the instruction if desired.
1447  if (RepeatInstruction) {
1448  if (BI != BB.begin())
1449  --BI;
1450  MadeChange = true;
1451  }
1452  }
1453  }
1454 
1455  return MadeChange;
1456 }
1457 
1459  auto &MD = AM.getResult<MemoryDependenceAnalysis>(F);
1460  auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1461 
1462  auto LookupAliasAnalysis = [&]() -> AliasAnalysis & {
1463  return AM.getResult<AAManager>(F);
1464  };
1465  auto LookupAssumptionCache = [&]() -> AssumptionCache & {
1466  return AM.getResult<AssumptionAnalysis>(F);
1467  };
1468  auto LookupDomTree = [&]() -> DominatorTree & {
1469  return AM.getResult<DominatorTreeAnalysis>(F);
1470  };
1471 
1472  bool MadeChange = runImpl(F, &MD, &TLI, LookupAliasAnalysis,
1473  LookupAssumptionCache, LookupDomTree);
1474  if (!MadeChange)
1475  return PreservedAnalyses::all();
1476 
1477  PreservedAnalyses PA;
1478  PA.preserveSet<CFGAnalyses>();
1479  PA.preserve<GlobalsAA>();
1481  return PA;
1482 }
1483 
1486  std::function<AliasAnalysis &()> LookupAliasAnalysis_,
1487  std::function<AssumptionCache &()> LookupAssumptionCache_,
1488  std::function<DominatorTree &()> LookupDomTree_) {
1489  bool MadeChange = false;
1490  MD = MD_;
1491  TLI = TLI_;
1492  LookupAliasAnalysis = std::move(LookupAliasAnalysis_);
1493  LookupAssumptionCache = std::move(LookupAssumptionCache_);
1494  LookupDomTree = std::move(LookupDomTree_);
1495 
1496  // If we don't have at least memset and memcpy, there is little point of doing
1497  // anything here. These are required by a freestanding implementation, so if
1498  // even they are disabled, there is no point in trying hard.
1499  if (!TLI->has(LibFunc_memset) || !TLI->has(LibFunc_memcpy))
1500  return false;
1501 
1502  while (true) {
1503  if (!iterateOnFunction(F))
1504  break;
1505  MadeChange = true;
1506  }
1507 
1508  MD = nullptr;
1509  return MadeChange;
1510 }
1511 
1512 /// This is the main transformation entry point for a function.
1514  if (skipFunction(F))
1515  return false;
1516 
1517  auto *MD = &getAnalysis<MemoryDependenceWrapperPass>().getMemDep();
1518  auto *TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1519 
1520  auto LookupAliasAnalysis = [this]() -> AliasAnalysis & {
1521  return getAnalysis<AAResultsWrapperPass>().getAAResults();
1522  };
1523  auto LookupAssumptionCache = [this, &F]() -> AssumptionCache & {
1524  return getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1525  };
1526  auto LookupDomTree = [this]() -> DominatorTree & {
1527  return getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1528  };
1529 
1530  return Impl.runImpl(F, MD, TLI, LookupAliasAnalysis, LookupAssumptionCache,
1531  LookupDomTree);
1532 }
Legacy wrapper pass to provide the GlobalsAAResult object.
uint64_t CallInst * C
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks &#39;this&#39; from the containing basic block and deletes it.
Definition: Instruction.cpp:68
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:111
const_iterator end(StringRef path)
Get end iterator over path.
Definition: Path.cpp:259
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
static bool runImpl(Function &F, TargetLibraryInfo &TLI, DominatorTree &DT)
This is the entry point for all transforms.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
Provides a lazy, caching interface for making common memory aliasing information queries, backed by LLVM&#39;s alias analysis passes.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1563
unsigned getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign, const DataLayout &DL, const Instruction *CxtI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr)
Try to ensure that the alignment of V is at least PrefAlign bytes.
Definition: Local.cpp:1184
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
This class represents an incoming formal argument to a Function.
Definition: Argument.h:30
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
Definition: Path.cpp:250
unsigned arg_size() const
Definition: CallSite.h:219
typename SuperClass::const_iterator const_iterator
Definition: SmallVector.h:328
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:770
This class represents lattice values for constants.
Definition: AllocatorList.h:24
unsigned getParamAlignment(unsigned ArgNo) const
Extract the alignment for a call or parameter (0=unknown).
Definition: CallSite.h:406
Value * isBytewiseValue(Value *V)
If the specified value can be set by repeating the same byte in memory, return the i8 value that it i...
INITIALIZE_PASS_BEGIN(MemCpyOptLegacyPass, "memcpyopt", "MemCpy Optimization", false, false) INITIALIZE_PASS_END(MemCpyOptLegacyPass
This is the interface for a simple mod/ref and alias analysis over globals.
bool isSized(SmallPtrSetImpl< Type *> *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition: Type.h:265
Implements a dense probed hash-table based set.
Definition: DenseSet.h:250
const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
Definition: DataLayout.cpp:588
bool isNoAlias(const MemoryLocation &LocA, const MemoryLocation &LocB)
A trivial helper function to check to see if the specified pointers are no-alias. ...
This provides a very simple, boring adaptor for a begin and end iterator into a range type...
This class represents a function call, abstracting a target machine&#39;s calling convention.
An immutable pass that tracks lazily created AssumptionCache objects.
unsigned getSourceAlignment() const
Value * getValue() const
A cache of @llvm.assume calls within a function.
static bool IsPointerOffset(Value *Ptr1, Value *Ptr2, int64_t &Offset, const DataLayout &DL)
Return true if Ptr1 is provably equal to Ptr2 plus a constant offset, and return that constant offset...
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
This class wraps the llvm.memset intrinsic.
STATISTIC(NumFunctions, "Total number of functions")
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:231
F(f)
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
Definition: DerivedTypes.h:503
CallInst * CreateMemSet(Value *Ptr, Value *Val, uint64_t Size, unsigned Align, bool isVolatile=false, MDNode *TBAATag=nullptr, MDNode *ScopeTag=nullptr, MDNode *NoAliasTag=nullptr)
Create and insert a memset to the specified pointer and the specified value.
Definition: IRBuilder.h:404
An instruction for reading from memory.
Definition: Instructions.h:168
Hexagon Common GEP
Value * CreateICmpULE(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1768
Value * getLength() const
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
Definition: Dominators.cpp:300
static Constant * getNullValue(Type *Ty)
Constructor to create a &#39;0&#39; constant of arbitrary type.
Definition: Constants.cpp:265
Value * getDest() const
This is just like getRawDest, but it strips off any cast instructions (including addrspacecast) that ...
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:51
bool isDef() const
Tests if this MemDepResult represents a query that is an instruction definition dependency.
static int64_t GetOffsetFromIndex(const GEPOperator *GEP, unsigned Idx, bool &VariableIdxFound, const DataLayout &DL)
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:365
unsigned getAlignment() const
Return the alignment of the memory that is being allocated by the instruction.
Definition: Instructions.h:113
static unsigned findStoreAlignment(const DataLayout &DL, const StoreInst *SI)
bool isClobber() const
Tests if this MemDepResult represents a query that is an instruction clobber dependency.
This class wraps the llvm.memmove intrinsic.
Class to represent struct types.
Definition: DerivedTypes.h:201
static bool hasUndefContents(Instruction *I, ConstantInt *Size)
Determine whether the instruction has undefined content for the given Size, either because it was fre...
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:743
void setCalledFunction(Value *Fn)
Sets the function called, including updating the function type.
Definition: InstrTypes.h:1119
InstrTy * getInstruction() const
Definition: CallSite.h:92
An analysis that produces MemoryDependenceResults for a function.
CallInst * CreateMemMove(Value *Dst, unsigned DstAlign, Value *Src, unsigned SrcAlign, uint64_t Size, bool isVolatile=false, MDNode *TBAATag=nullptr, MDNode *ScopeTag=nullptr, MDNode *NoAliasTag=nullptr)
Create and insert a memmove between the specified pointers.
Definition: IRBuilder.h:494
unsigned getDestAlignment() const
void setArgument(unsigned ArgNo, Value *newVal)
Definition: CallSite.h:191
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
Definition: STLExtras.h:261
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:245
static MemoryLocation getForDest(const MemIntrinsic *MI)
Return a location representing the destination of a memory set or transfer.
This class represents a no-op cast from one type to another.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
Definition: Instruction.h:221
void combineMetadata(Instruction *K, const Instruction *J, ArrayRef< unsigned > KnownIDs, bool DoesKMove)
Combine the metadata of two instructions so that K can replace J.
Definition: Local.cpp:2274
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition: Constants.h:138
auto lower_bound(R &&Range, ForwardIt I) -> decltype(adl_begin(Range))
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1276
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:991
An instruction for storing to memory.
Definition: Instructions.h:310
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1568
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:145
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Definition: Function.cpp:1021
Value * getOperand(unsigned i) const
Definition: User.h:170
constexpr uint64_t MinAlign(uint64_t A, uint64_t B)
A and B are either alignments or offsets.
Definition: MathExtras.h:610
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
Definition: Instructions.h:843
static bool runOnFunction(Function &F, bool PostInlining)
#define P(N)
static MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition: Constants.h:149
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:154
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
Definition: Instruction.h:308
LLVM Basic Block Representation.
Definition: BasicBlock.h:58
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
Definition: SmallVector.h:129
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition: IRBuilder.h:1913
A manager for alias analyses.
bool mayThrow() const
Return true if this instruction may throw an exception.
Represent the analysis usage information of a pass.
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:1187
Analysis pass providing a never-invalidated alias analysis result.
unsigned getLargestLegalIntTypeSizeInBits() const
Returns the size of largest legal integer type size, or 0 if none are set.
Definition: DataLayout.cpp:764
FunctionPass * createMemCpyOptPass()
The public interface to this file...
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:285
self_iterator getIterator()
Definition: ilist_node.h:82
static CastInst * CreatePointerCast(Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd)
Create a BitCast AddrSpaceCast, or a PtrToInt cast instruction.
bool doesNotCapture(unsigned OpNo) const
Determine whether this data operand is not captured.
Definition: CallSite.h:593
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs, and aliases.
Definition: Value.cpp:530
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:160
void initializeMemCpyOptLegacyPassPass(PassRegistry &)
const Value * getArraySize() const
Get the number of elements allocated.
Definition: Instructions.h:93
A wrapper analysis pass for the legacy pass manager that exposes a MemoryDepnedenceResults instance...
bool isVolatile() const
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
Definition: Instructions.h:106
A memory dependence query can return one of three different answers.
bool runImpl(Function &F, MemoryDependenceResults *MD_, TargetLibraryInfo *TLI_, std::function< AliasAnalysis &()> LookupAliasAnalysis_, std::function< AssumptionCache &()> LookupAssumptionCache_, std::function< DominatorTree &()> LookupDomTree_)
constexpr bool empty(const T &RangeOrContainer)
Test whether RangeOrContainer is empty. Similar to C++17 std::empty.
Definition: STLExtras.h:204
The two locations may or may not alias. This is the least precise result.
Definition: AliasAnalysis.h:87
Value * CreateGEP(Value *Ptr, ArrayRef< Value *> IdxList, const Twine &Name="")
Definition: IRBuilder.h:1386
Representation for a specific memory location.
A function analysis which provides an AssumptionCache.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
Iterator for intrusive lists based on ilist_node.
unsigned getNumOperands() const
Definition: User.h:192
This is the shared class of boolean and integer constants.
Definition: Constants.h:84
ValTy * getArgument(unsigned ArgNo) const
Definition: CallSite.h:186
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:847
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Definition: Dominators.cpp:249
Module.h This file contains the declarations for the Module class.
Provides information about what library functions are available for the current target.
unsigned getABITypeAlignment(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
Definition: DataLayout.cpp:722
const DataFlowGraph & G
Definition: RDFGraph.cpp:211
static unsigned findLoadAlignment(const DataLayout &DL, const LoadInst *LI)
CallInst * CreateMemCpy(Value *Dst, unsigned DstAlign, Value *Src, unsigned SrcAlign, uint64_t Size, bool isVolatile=false, MDNode *TBAATag=nullptr, MDNode *TBAAStructTag=nullptr, MDNode *ScopeTag=nullptr, MDNode *NoAliasTag=nullptr)
Create and insert a memcpy between the specified pointers.
Definition: IRBuilder.h:446
This class wraps the llvm.memcpy intrinsic.
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:286
Value * getRawSource() const
Return the arguments to the instruction.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:133
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:56
ModRefInfo callCapturesBefore(const Instruction *I, const MemoryLocation &MemLoc, DominatorTree *DT, OrderedBasicBlock *OBB=nullptr)
Return information about whether a particular call site modifies or reads the specified memory locati...
ModRefInfo getModRefInfo(ImmutableCallSite CS, const MemoryLocation &Loc)
getModRefInfo (for call sites) - Return information about whether a particular call site modifies or ...
typename SuperClass::iterator iterator
Definition: SmallVector.h:327
iterator_range< user_iterator > users()
Definition: Value.h:400
bool isMustAlias(const MemoryLocation &LocA, const MemoryLocation &LocB)
A trivial helper function to check to see if the specified pointers are must-alias.
MemCpy Optimization
Represents analyses that only rely on functions&#39; control flow.
Definition: PassManager.h:115
static cl::opt< ITMode > IT(cl::desc("IT block support"), cl::Hidden, cl::init(DefaultIT), cl::ZeroOrMore, cl::values(clEnumValN(DefaultIT, "arm-default-it", "Generate IT block based on arch"), clEnumValN(RestrictedIT, "arm-restrict-it", "Disallow deprecated IT based on ARMv8"), clEnumValN(NoRestrictedIT, "arm-no-restrict-it", "Allow IT blocks based on ARMv7")))
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Definition: DataLayout.h:428
LLVM_NODISCARD bool isModSet(const ModRefInfo MRI)
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Definition: SmallVector.h:133
FunTy * getCaller() const
Return the caller function for this call site.
Definition: CallSite.h:267
bool isVolatile() const
Return true if this is a store to a volatile memory location.
Definition: Instructions.h:343
uint64_t getElementOffset(unsigned Idx) const
Definition: DataLayout.h:543
unsigned getAlignment() const
Return the alignment of the access that is being performed.
Definition: Instructions.h:230
Instruction * getInst() const
If this is a normal dependency, returns the instruction that is depended on.
unsigned getIntegerBitWidth() const
Definition: DerivedTypes.h:97
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:56
This file provides utility analysis objects describing memory locations.
void preserveSet()
Mark an analysis set as preserved.
Definition: PassManager.h:190
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:215
Establish a view to a call site for examination.
Definition: CallSite.h:711
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation.
Definition: InstrTypes.h:1112
#define I(x, y, z)
Definition: MD5.cpp:58
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition: Constants.h:193
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:323
uint32_t Size
Definition: Profile.cpp:47
void preserve()
Mark an analysis as preserved.
Definition: PassManager.h:175
unsigned getAlignment() const
Return the alignment of the access that is being performed.
Definition: Instructions.h:355
static void addRange(SmallVectorImpl< ConstantInt *> &EndPoints, ConstantInt *Low, ConstantInt *High)
Definition: Metadata.cpp:968
bool isByValArgument(unsigned ArgNo) const
Determine whether this argument is passed by value.
Definition: CallSite.h:598
Analysis pass providing the TargetLibraryInfo.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
Definition: Value.h:376
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:566
LLVM Value Representation.
Definition: Value.h:73
uint64_t getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type...
Definition: DataLayout.h:411
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
Value * getSource() const
This is just like getRawSource, but it strips off any cast instructions that feed it...
print Print MemDeps of function
A container for analyses that lazily runs them and caches their results.
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:260
LLVM_NODISCARD bool isModOrRefSet(const ModRefInfo MRI)
static bool moveUp(AliasAnalysis &AA, StoreInst *SI, Instruction *P, const LoadInst *LI)
static unsigned findCommonAlignment(const DataLayout &DL, const StoreInst *SI, const LoadInst *LI)
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
bool isSimple() const
Definition: Instructions.h:391
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
Definition: Constants.h:157
This header defines various interfaces for pass management in LLVM.
#define LLVM_DEBUG(X)
Definition: Debug.h:123
Value * getPointerOperand()
Definition: Instructions.h:402
Value * getRawDest() const
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:44
const BasicBlock * getParent() const
Definition: Instruction.h:67
an instruction to allocate memory on the stack
Definition: Instructions.h:60
gep_type_iterator gep_type_begin(const User *GEP)
static MemoryLocation getForSource(const MemTransferInst *MTI)
Return a location representing the source of a memory transfer.
user_iterator user_end()
Definition: Value.h:384