MemCpyOptimizer.cpp 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533
  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. #include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
  15. #include "llvm/ADT/DenseSet.h"
  16. #include "llvm/ADT/None.h"
  17. #include "llvm/ADT/STLExtras.h"
  18. #include "llvm/ADT/SmallVector.h"
  19. #include "llvm/ADT/Statistic.h"
  20. #include "llvm/ADT/iterator_range.h"
  21. #include "llvm/Analysis/AliasAnalysis.h"
  22. #include "llvm/Analysis/AssumptionCache.h"
  23. #include "llvm/Analysis/GlobalsModRef.h"
  24. #include "llvm/Analysis/MemoryDependenceAnalysis.h"
  25. #include "llvm/Analysis/MemoryLocation.h"
  26. #include "llvm/Analysis/TargetLibraryInfo.h"
  27. #include "llvm/Transforms/Utils/Local.h"
  28. #include "llvm/Analysis/ValueTracking.h"
  29. #include "llvm/IR/Argument.h"
  30. #include "llvm/IR/BasicBlock.h"
  31. #include "llvm/IR/CallSite.h"
  32. #include "llvm/IR/Constants.h"
  33. #include "llvm/IR/DataLayout.h"
  34. #include "llvm/IR/DerivedTypes.h"
  35. #include "llvm/IR/Dominators.h"
  36. #include "llvm/IR/Function.h"
  37. #include "llvm/IR/GetElementPtrTypeIterator.h"
  38. #include "llvm/IR/GlobalVariable.h"
  39. #include "llvm/IR/IRBuilder.h"
  40. #include "llvm/IR/InstrTypes.h"
  41. #include "llvm/IR/Instruction.h"
  42. #include "llvm/IR/Instructions.h"
  43. #include "llvm/IR/IntrinsicInst.h"
  44. #include "llvm/IR/Intrinsics.h"
  45. #include "llvm/IR/LLVMContext.h"
  46. #include "llvm/IR/Module.h"
  47. #include "llvm/IR/Operator.h"
  48. #include "llvm/IR/PassManager.h"
  49. #include "llvm/IR/Type.h"
  50. #include "llvm/IR/User.h"
  51. #include "llvm/IR/Value.h"
  52. #include "llvm/Pass.h"
  53. #include "llvm/Support/Casting.h"
  54. #include "llvm/Support/Debug.h"
  55. #include "llvm/Support/MathExtras.h"
  56. #include "llvm/Support/raw_ostream.h"
  57. #include "llvm/Transforms/Scalar.h"
  58. #include <algorithm>
  59. #include <cassert>
  60. #include <cstdint>
  61. #include <utility>
  62. using namespace llvm;
  63. #define DEBUG_TYPE "memcpyopt"
  64. STATISTIC(NumMemCpyInstr, "Number of memcpy instructions deleted");
  65. STATISTIC(NumMemSetInfer, "Number of memsets inferred");
  66. STATISTIC(NumMoveToCpy, "Number of memmoves converted to memcpy");
  67. STATISTIC(NumCpyToSet, "Number of memcpys converted to memset");
  68. static int64_t GetOffsetFromIndex(const GEPOperator *GEP, unsigned Idx,
  69. bool &VariableIdxFound,
  70. const DataLayout &DL) {
  71. // Skip over the first indices.
  72. gep_type_iterator GTI = gep_type_begin(GEP);
  73. for (unsigned i = 1; i != Idx; ++i, ++GTI)
  74. /*skip along*/;
  75. // Compute the offset implied by the rest of the indices.
  76. int64_t Offset = 0;
  77. for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
  78. ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
  79. if (!OpC)
  80. return VariableIdxFound = true;
  81. if (OpC->isZero()) continue; // No offset.
  82. // Handle struct indices, which add their field offset to the pointer.
  83. if (StructType *STy = GTI.getStructTypeOrNull()) {
  84. Offset += DL.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
  85. continue;
  86. }
  87. // Otherwise, we have a sequential type like an array or vector. Multiply
  88. // the index by the ElementSize.
  89. uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
  90. Offset += Size*OpC->getSExtValue();
  91. }
  92. return Offset;
  93. }
  94. /// Return true if Ptr1 is provably equal to Ptr2 plus a constant offset, and
  95. /// return that constant offset. For example, Ptr1 might be &A[42], and Ptr2
  96. /// might be &A[40]. In this case offset would be -8.
  97. static bool IsPointerOffset(Value *Ptr1, Value *Ptr2, int64_t &Offset,
  98. const DataLayout &DL) {
  99. Ptr1 = Ptr1->stripPointerCasts();
  100. Ptr2 = Ptr2->stripPointerCasts();
  101. // Handle the trivial case first.
  102. if (Ptr1 == Ptr2) {
  103. Offset = 0;
  104. return true;
  105. }
  106. GEPOperator *GEP1 = dyn_cast<GEPOperator>(Ptr1);
  107. GEPOperator *GEP2 = dyn_cast<GEPOperator>(Ptr2);
  108. bool VariableIdxFound = false;
  109. // If one pointer is a GEP and the other isn't, then see if the GEP is a
  110. // constant offset from the base, as in "P" and "gep P, 1".
  111. if (GEP1 && !GEP2 && GEP1->getOperand(0)->stripPointerCasts() == Ptr2) {
  112. Offset = -GetOffsetFromIndex(GEP1, 1, VariableIdxFound, DL);
  113. return !VariableIdxFound;
  114. }
  115. if (GEP2 && !GEP1 && GEP2->getOperand(0)->stripPointerCasts() == Ptr1) {
  116. Offset = GetOffsetFromIndex(GEP2, 1, VariableIdxFound, DL);
  117. return !VariableIdxFound;
  118. }
  119. // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
  120. // base. After that base, they may have some number of common (and
  121. // potentially variable) indices. After that they handle some constant
  122. // offset, which determines their offset from each other. At this point, we
  123. // handle no other case.
  124. if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0))
  125. return false;
  126. // Skip any common indices and track the GEP types.
  127. unsigned Idx = 1;
  128. for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
  129. if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
  130. break;
  131. int64_t Offset1 = GetOffsetFromIndex(GEP1, Idx, VariableIdxFound, DL);
  132. int64_t Offset2 = GetOffsetFromIndex(GEP2, Idx, VariableIdxFound, DL);
  133. if (VariableIdxFound) return false;
  134. Offset = Offset2-Offset1;
  135. return true;
  136. }
  137. namespace {
  138. /// Represents a range of memset'd bytes with the ByteVal value.
  139. /// This allows us to analyze stores like:
  140. /// store 0 -> P+1
  141. /// store 0 -> P+0
  142. /// store 0 -> P+3
  143. /// store 0 -> P+2
  144. /// which sometimes happens with stores to arrays of structs etc. When we see
  145. /// the first store, we make a range [1, 2). The second store extends the range
  146. /// to [0, 2). The third makes a new range [2, 3). The fourth store joins the
  147. /// two ranges into [0, 3) which is memset'able.
  148. struct MemsetRange {
  149. // Start/End - A semi range that describes the span that this range covers.
  150. // The range is closed at the start and open at the end: [Start, End).
  151. int64_t Start, End;
  152. /// StartPtr - The getelementptr instruction that points to the start of the
  153. /// range.
  154. Value *StartPtr;
  155. /// Alignment - The known alignment of the first store.
  156. unsigned Alignment;
  157. /// TheStores - The actual stores that make up this range.
  158. SmallVector<Instruction*, 16> TheStores;
  159. bool isProfitableToUseMemset(const DataLayout &DL) const;
  160. };
  161. } // end anonymous namespace
  162. bool MemsetRange::isProfitableToUseMemset(const DataLayout &DL) const {
  163. // If we found more than 4 stores to merge or 16 bytes, use memset.
  164. if (TheStores.size() >= 4 || End-Start >= 16) return true;
  165. // If there is nothing to merge, don't do anything.
  166. if (TheStores.size() < 2) return false;
  167. // If any of the stores are a memset, then it is always good to extend the
  168. // memset.
  169. for (Instruction *SI : TheStores)
  170. if (!isa<StoreInst>(SI))
  171. return true;
  172. // Assume that the code generator is capable of merging pairs of stores
  173. // together if it wants to.
  174. if (TheStores.size() == 2) return false;
  175. // If we have fewer than 8 stores, it can still be worthwhile to do this.
  176. // For example, merging 4 i8 stores into an i32 store is useful almost always.
  177. // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the
  178. // memset will be split into 2 32-bit stores anyway) and doing so can
  179. // pessimize the llvm optimizer.
  180. //
  181. // Since we don't have perfect knowledge here, make some assumptions: assume
  182. // the maximum GPR width is the same size as the largest legal integer
  183. // size. If so, check to see whether we will end up actually reducing the
  184. // number of stores used.
  185. unsigned Bytes = unsigned(End-Start);
  186. unsigned MaxIntSize = DL.getLargestLegalIntTypeSizeInBits() / 8;
  187. if (MaxIntSize == 0)
  188. MaxIntSize = 1;
  189. unsigned NumPointerStores = Bytes / MaxIntSize;
  190. // Assume the remaining bytes if any are done a byte at a time.
  191. unsigned NumByteStores = Bytes % MaxIntSize;
  192. // If we will reduce the # stores (according to this heuristic), do the
  193. // transformation. This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32
  194. // etc.
  195. return TheStores.size() > NumPointerStores+NumByteStores;
  196. }
  197. namespace {
  198. class MemsetRanges {
  199. using range_iterator = SmallVectorImpl<MemsetRange>::iterator;
  200. /// A sorted list of the memset ranges.
  201. SmallVector<MemsetRange, 8> Ranges;
  202. const DataLayout &DL;
  203. public:
  204. MemsetRanges(const DataLayout &DL) : DL(DL) {}
  205. using const_iterator = SmallVectorImpl<MemsetRange>::const_iterator;
  206. const_iterator begin() const { return Ranges.begin(); }
  207. const_iterator end() const { return Ranges.end(); }
  208. bool empty() const { return Ranges.empty(); }
  209. void addInst(int64_t OffsetFromFirst, Instruction *Inst) {
  210. if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
  211. addStore(OffsetFromFirst, SI);
  212. else
  213. addMemSet(OffsetFromFirst, cast<MemSetInst>(Inst));
  214. }
  215. void addStore(int64_t OffsetFromFirst, StoreInst *SI) {
  216. int64_t StoreSize = DL.getTypeStoreSize(SI->getOperand(0)->getType());
  217. addRange(OffsetFromFirst, StoreSize,
  218. SI->getPointerOperand(), SI->getAlignment(), SI);
  219. }
  220. void addMemSet(int64_t OffsetFromFirst, MemSetInst *MSI) {
  221. int64_t Size = cast<ConstantInt>(MSI->getLength())->getZExtValue();
  222. addRange(OffsetFromFirst, Size, MSI->getDest(), MSI->getDestAlignment(), MSI);
  223. }
  224. void addRange(int64_t Start, int64_t Size, Value *Ptr,
  225. unsigned Alignment, Instruction *Inst);
  226. };
  227. } // end anonymous namespace
  228. /// Add a new store to the MemsetRanges data structure. This adds a
  229. /// new range for the specified store at the specified offset, merging into
  230. /// existing ranges as appropriate.
  231. void MemsetRanges::addRange(int64_t Start, int64_t Size, Value *Ptr,
  232. unsigned Alignment, Instruction *Inst) {
  233. int64_t End = Start+Size;
  234. range_iterator I = std::lower_bound(Ranges.begin(), Ranges.end(), Start,
  235. [](const MemsetRange &LHS, int64_t RHS) { return LHS.End < RHS; });
  236. // We now know that I == E, in which case we didn't find anything to merge
  237. // with, or that Start <= I->End. If End < I->Start or I == E, then we need
  238. // to insert a new range. Handle this now.
  239. if (I == Ranges.end() || End < I->Start) {
  240. MemsetRange &R = *Ranges.insert(I, MemsetRange());
  241. R.Start = Start;
  242. R.End = End;
  243. R.StartPtr = Ptr;
  244. R.Alignment = Alignment;
  245. R.TheStores.push_back(Inst);
  246. return;
  247. }
  248. // This store overlaps with I, add it.
  249. I->TheStores.push_back(Inst);
  250. // At this point, we may have an interval that completely contains our store.
  251. // If so, just add it to the interval and return.
  252. if (I->Start <= Start && I->End >= End)
  253. return;
  254. // Now we know that Start <= I->End and End >= I->Start so the range overlaps
  255. // but is not entirely contained within the range.
  256. // See if the range extends the start of the range. In this case, it couldn't
  257. // possibly cause it to join the prior range, because otherwise we would have
  258. // stopped on *it*.
  259. if (Start < I->Start) {
  260. I->Start = Start;
  261. I->StartPtr = Ptr;
  262. I->Alignment = Alignment;
  263. }
  264. // Now we know that Start <= I->End and Start >= I->Start (so the startpoint
  265. // is in or right at the end of I), and that End >= I->Start. Extend I out to
  266. // End.
  267. if (End > I->End) {
  268. I->End = End;
  269. range_iterator NextI = I;
  270. while (++NextI != Ranges.end() && End >= NextI->Start) {
  271. // Merge the range in.
  272. I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
  273. if (NextI->End > I->End)
  274. I->End = NextI->End;
  275. Ranges.erase(NextI);
  276. NextI = I;
  277. }
  278. }
  279. }
  280. //===----------------------------------------------------------------------===//
  281. // MemCpyOptLegacyPass Pass
  282. //===----------------------------------------------------------------------===//
  283. namespace {
  284. class MemCpyOptLegacyPass : public FunctionPass {
  285. MemCpyOptPass Impl;
  286. public:
  287. static char ID; // Pass identification, replacement for typeid
  288. MemCpyOptLegacyPass() : FunctionPass(ID) {
  289. initializeMemCpyOptLegacyPassPass(*PassRegistry::getPassRegistry());
  290. }
  291. bool runOnFunction(Function &F) override;
  292. private:
  293. // This transformation requires dominator postdominator info
  294. void getAnalysisUsage(AnalysisUsage &AU) const override {
  295. AU.setPreservesCFG();
  296. AU.addRequired<AssumptionCacheTracker>();
  297. AU.addRequired<DominatorTreeWrapperPass>();
  298. AU.addRequired<MemoryDependenceWrapperPass>();
  299. AU.addRequired<AAResultsWrapperPass>();
  300. AU.addRequired<TargetLibraryInfoWrapperPass>();
  301. AU.addPreserved<GlobalsAAWrapperPass>();
  302. AU.addPreserved<MemoryDependenceWrapperPass>();
  303. }
  304. };
  305. } // end anonymous namespace
  306. char MemCpyOptLegacyPass::ID = 0;
  307. /// The public interface to this file...
  308. FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOptLegacyPass(); }
  309. INITIALIZE_PASS_BEGIN(MemCpyOptLegacyPass, "memcpyopt", "MemCpy Optimization",
  310. false, false)
  311. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  312. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  313. INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)
  314. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  315. INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
  316. INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
  317. INITIALIZE_PASS_END(MemCpyOptLegacyPass, "memcpyopt", "MemCpy Optimization",
  318. false, false)
  319. /// When scanning forward over instructions, we look for some other patterns to
  320. /// fold away. In particular, this looks for stores to neighboring locations of
  321. /// memory. If it sees enough consecutive ones, it attempts to merge them
  322. /// together into a memcpy/memset.
  323. Instruction *MemCpyOptPass::tryMergingIntoMemset(Instruction *StartInst,
  324. Value *StartPtr,
  325. Value *ByteVal) {
  326. const DataLayout &DL = StartInst->getModule()->getDataLayout();
  327. // Okay, so we now have a single store that can be splatable. Scan to find
  328. // all subsequent stores of the same value to offset from the same pointer.
  329. // Join these together into ranges, so we can decide whether contiguous blocks
  330. // are stored.
  331. MemsetRanges Ranges(DL);
  332. BasicBlock::iterator BI(StartInst);
  333. for (++BI; !BI->isTerminator(); ++BI) {
  334. if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
  335. // If the instruction is readnone, ignore it, otherwise bail out. We
  336. // don't even allow readonly here because we don't want something like:
  337. // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
  338. if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
  339. break;
  340. continue;
  341. }
  342. if (StoreInst *NextStore = dyn_cast<StoreInst>(BI)) {
  343. // If this is a store, see if we can merge it in.
  344. if (!NextStore->isSimple()) break;
  345. // Check to see if this stored value is of the same byte-splattable value.
  346. Value *StoredByte = isBytewiseValue(NextStore->getOperand(0));
  347. if (isa<UndefValue>(ByteVal) && StoredByte)
  348. ByteVal = StoredByte;
  349. if (ByteVal != StoredByte)
  350. break;
  351. // Check to see if this store is to a constant offset from the start ptr.
  352. int64_t Offset;
  353. if (!IsPointerOffset(StartPtr, NextStore->getPointerOperand(), Offset,
  354. DL))
  355. break;
  356. Ranges.addStore(Offset, NextStore);
  357. } else {
  358. MemSetInst *MSI = cast<MemSetInst>(BI);
  359. if (MSI->isVolatile() || ByteVal != MSI->getValue() ||
  360. !isa<ConstantInt>(MSI->getLength()))
  361. break;
  362. // Check to see if this store is to a constant offset from the start ptr.
  363. int64_t Offset;
  364. if (!IsPointerOffset(StartPtr, MSI->getDest(), Offset, DL))
  365. break;
  366. Ranges.addMemSet(Offset, MSI);
  367. }
  368. }
  369. // If we have no ranges, then we just had a single store with nothing that
  370. // could be merged in. This is a very common case of course.
  371. if (Ranges.empty())
  372. return nullptr;
  373. // If we had at least one store that could be merged in, add the starting
  374. // store as well. We try to avoid this unless there is at least something
  375. // interesting as a small compile-time optimization.
  376. Ranges.addInst(0, StartInst);
  377. // If we create any memsets, we put it right before the first instruction that
  378. // isn't part of the memset block. This ensure that the memset is dominated
  379. // by any addressing instruction needed by the start of the block.
  380. IRBuilder<> Builder(&*BI);
  381. // Now that we have full information about ranges, loop over the ranges and
  382. // emit memset's for anything big enough to be worthwhile.
  383. Instruction *AMemSet = nullptr;
  384. for (const MemsetRange &Range : Ranges) {
  385. if (Range.TheStores.size() == 1) continue;
  386. // If it is profitable to lower this range to memset, do so now.
  387. if (!Range.isProfitableToUseMemset(DL))
  388. continue;
  389. // Otherwise, we do want to transform this! Create a new memset.
  390. // Get the starting pointer of the block.
  391. StartPtr = Range.StartPtr;
  392. // Determine alignment
  393. unsigned Alignment = Range.Alignment;
  394. if (Alignment == 0) {
  395. Type *EltType =
  396. cast<PointerType>(StartPtr->getType())->getElementType();
  397. Alignment = DL.getABITypeAlignment(EltType);
  398. }
  399. AMemSet =
  400. Builder.CreateMemSet(StartPtr, ByteVal, Range.End-Range.Start, Alignment);
  401. LLVM_DEBUG(dbgs() << "Replace stores:\n"; for (Instruction *SI
  402. : Range.TheStores) dbgs()
  403. << *SI << '\n';
  404. dbgs() << "With: " << *AMemSet << '\n');
  405. if (!Range.TheStores.empty())
  406. AMemSet->setDebugLoc(Range.TheStores[0]->getDebugLoc());
  407. // Zap all the stores.
  408. for (Instruction *SI : Range.TheStores) {
  409. MD->removeInstruction(SI);
  410. SI->eraseFromParent();
  411. }
  412. ++NumMemSetInfer;
  413. }
  414. return AMemSet;
  415. }
  416. static unsigned findStoreAlignment(const DataLayout &DL, const StoreInst *SI) {
  417. unsigned StoreAlign = SI->getAlignment();
  418. if (!StoreAlign)
  419. StoreAlign = DL.getABITypeAlignment(SI->getOperand(0)->getType());
  420. return StoreAlign;
  421. }
  422. static unsigned findLoadAlignment(const DataLayout &DL, const LoadInst *LI) {
  423. unsigned LoadAlign = LI->getAlignment();
  424. if (!LoadAlign)
  425. LoadAlign = DL.getABITypeAlignment(LI->getType());
  426. return LoadAlign;
  427. }
  428. static unsigned findCommonAlignment(const DataLayout &DL, const StoreInst *SI,
  429. const LoadInst *LI) {
  430. unsigned StoreAlign = findStoreAlignment(DL, SI);
  431. unsigned LoadAlign = findLoadAlignment(DL, LI);
  432. return MinAlign(StoreAlign, LoadAlign);
  433. }
  434. // This method try to lift a store instruction before position P.
  435. // It will lift the store and its argument + that anything that
  436. // may alias with these.
  437. // The method returns true if it was successful.
  438. static bool moveUp(AliasAnalysis &AA, StoreInst *SI, Instruction *P,
  439. const LoadInst *LI) {
  440. // If the store alias this position, early bail out.
  441. MemoryLocation StoreLoc = MemoryLocation::get(SI);
  442. if (isModOrRefSet(AA.getModRefInfo(P, StoreLoc)))
  443. return false;
  444. // Keep track of the arguments of all instruction we plan to lift
  445. // so we can make sure to lift them as well if appropriate.
  446. DenseSet<Instruction*> Args;
  447. if (auto *Ptr = dyn_cast<Instruction>(SI->getPointerOperand()))
  448. if (Ptr->getParent() == SI->getParent())
  449. Args.insert(Ptr);
  450. // Instruction to lift before P.
  451. SmallVector<Instruction*, 8> ToLift;
  452. // Memory locations of lifted instructions.
  453. SmallVector<MemoryLocation, 8> MemLocs{StoreLoc};
  454. // Lifted callsites.
  455. SmallVector<ImmutableCallSite, 8> CallSites;
  456. const MemoryLocation LoadLoc = MemoryLocation::get(LI);
  457. for (auto I = --SI->getIterator(), E = P->getIterator(); I != E; --I) {
  458. auto *C = &*I;
  459. bool MayAlias = isModOrRefSet(AA.getModRefInfo(C, None));
  460. bool NeedLift = false;
  461. if (Args.erase(C))
  462. NeedLift = true;
  463. else if (MayAlias) {
  464. NeedLift = llvm::any_of(MemLocs, [C, &AA](const MemoryLocation &ML) {
  465. return isModOrRefSet(AA.getModRefInfo(C, ML));
  466. });
  467. if (!NeedLift)
  468. NeedLift =
  469. llvm::any_of(CallSites, [C, &AA](const ImmutableCallSite &CS) {
  470. return isModOrRefSet(AA.getModRefInfo(C, CS));
  471. });
  472. }
  473. if (!NeedLift)
  474. continue;
  475. if (MayAlias) {
  476. // Since LI is implicitly moved downwards past the lifted instructions,
  477. // none of them may modify its source.
  478. if (isModSet(AA.getModRefInfo(C, LoadLoc)))
  479. return false;
  480. else if (auto CS = ImmutableCallSite(C)) {
  481. // If we can't lift this before P, it's game over.
  482. if (isModOrRefSet(AA.getModRefInfo(P, CS)))
  483. return false;
  484. CallSites.push_back(CS);
  485. } else if (isa<LoadInst>(C) || isa<StoreInst>(C) || isa<VAArgInst>(C)) {
  486. // If we can't lift this before P, it's game over.
  487. auto ML = MemoryLocation::get(C);
  488. if (isModOrRefSet(AA.getModRefInfo(P, ML)))
  489. return false;
  490. MemLocs.push_back(ML);
  491. } else
  492. // We don't know how to lift this instruction.
  493. return false;
  494. }
  495. ToLift.push_back(C);
  496. for (unsigned k = 0, e = C->getNumOperands(); k != e; ++k)
  497. if (auto *A = dyn_cast<Instruction>(C->getOperand(k)))
  498. if (A->getParent() == SI->getParent())
  499. Args.insert(A);
  500. }
  501. // We made it, we need to lift
  502. for (auto *I : llvm::reverse(ToLift)) {
  503. LLVM_DEBUG(dbgs() << "Lifting " << *I << " before " << *P << "\n");
  504. I->moveBefore(P);
  505. }
  506. return true;
  507. }
  508. bool MemCpyOptPass::processStore(StoreInst *SI, BasicBlock::iterator &BBI) {
  509. if (!SI->isSimple()) return false;
  510. // Avoid merging nontemporal stores since the resulting
  511. // memcpy/memset would not be able to preserve the nontemporal hint.
  512. // In theory we could teach how to propagate the !nontemporal metadata to
  513. // memset calls. However, that change would force the backend to
  514. // conservatively expand !nontemporal memset calls back to sequences of
  515. // store instructions (effectively undoing the merging).
  516. if (SI->getMetadata(LLVMContext::MD_nontemporal))
  517. return false;
  518. const DataLayout &DL = SI->getModule()->getDataLayout();
  519. // Load to store forwarding can be interpreted as memcpy.
  520. if (LoadInst *LI = dyn_cast<LoadInst>(SI->getOperand(0))) {
  521. if (LI->isSimple() && LI->hasOneUse() &&
  522. LI->getParent() == SI->getParent()) {
  523. auto *T = LI->getType();
  524. if (T->isAggregateType()) {
  525. AliasAnalysis &AA = LookupAliasAnalysis();
  526. MemoryLocation LoadLoc = MemoryLocation::get(LI);
  527. // We use alias analysis to check if an instruction may store to
  528. // the memory we load from in between the load and the store. If
  529. // such an instruction is found, we try to promote there instead
  530. // of at the store position.
  531. Instruction *P = SI;
  532. for (auto &I : make_range(++LI->getIterator(), SI->getIterator())) {
  533. if (isModSet(AA.getModRefInfo(&I, LoadLoc))) {
  534. P = &I;
  535. break;
  536. }
  537. }
  538. // We found an instruction that may write to the loaded memory.
  539. // We can try to promote at this position instead of the store
  540. // position if nothing alias the store memory after this and the store
  541. // destination is not in the range.
  542. if (P && P != SI) {
  543. if (!moveUp(AA, SI, P, LI))
  544. P = nullptr;
  545. }
  546. // If a valid insertion position is found, then we can promote
  547. // the load/store pair to a memcpy.
  548. if (P) {
  549. // If we load from memory that may alias the memory we store to,
  550. // memmove must be used to preserve semantic. If not, memcpy can
  551. // be used.
  552. bool UseMemMove = false;
  553. if (!AA.isNoAlias(MemoryLocation::get(SI), LoadLoc))
  554. UseMemMove = true;
  555. uint64_t Size = DL.getTypeStoreSize(T);
  556. IRBuilder<> Builder(P);
  557. Instruction *M;
  558. if (UseMemMove)
  559. M = Builder.CreateMemMove(
  560. SI->getPointerOperand(), findStoreAlignment(DL, SI),
  561. LI->getPointerOperand(), findLoadAlignment(DL, LI), Size,
  562. SI->isVolatile());
  563. else
  564. M = Builder.CreateMemCpy(
  565. SI->getPointerOperand(), findStoreAlignment(DL, SI),
  566. LI->getPointerOperand(), findLoadAlignment(DL, LI), Size,
  567. SI->isVolatile());
  568. LLVM_DEBUG(dbgs() << "Promoting " << *LI << " to " << *SI << " => "
  569. << *M << "\n");
  570. MD->removeInstruction(SI);
  571. SI->eraseFromParent();
  572. MD->removeInstruction(LI);
  573. LI->eraseFromParent();
  574. ++NumMemCpyInstr;
  575. // Make sure we do not invalidate the iterator.
  576. BBI = M->getIterator();
  577. return true;
  578. }
  579. }
  580. // Detect cases where we're performing call slot forwarding, but
  581. // happen to be using a load-store pair to implement it, rather than
  582. // a memcpy.
  583. MemDepResult ldep = MD->getDependency(LI);
  584. CallInst *C = nullptr;
  585. if (ldep.isClobber() && !isa<MemCpyInst>(ldep.getInst()))
  586. C = dyn_cast<CallInst>(ldep.getInst());
  587. if (C) {
  588. // Check that nothing touches the dest of the "copy" between
  589. // the call and the store.
  590. Value *CpyDest = SI->getPointerOperand()->stripPointerCasts();
  591. bool CpyDestIsLocal = isa<AllocaInst>(CpyDest);
  592. AliasAnalysis &AA = LookupAliasAnalysis();
  593. MemoryLocation StoreLoc = MemoryLocation::get(SI);
  594. for (BasicBlock::iterator I = --SI->getIterator(), E = C->getIterator();
  595. I != E; --I) {
  596. if (isModOrRefSet(AA.getModRefInfo(&*I, StoreLoc))) {
  597. C = nullptr;
  598. break;
  599. }
  600. // The store to dest may never happen if an exception can be thrown
  601. // between the load and the store.
  602. if (I->mayThrow() && !CpyDestIsLocal) {
  603. C = nullptr;
  604. break;
  605. }
  606. }
  607. }
  608. if (C) {
  609. bool changed = performCallSlotOptzn(
  610. LI, SI->getPointerOperand()->stripPointerCasts(),
  611. LI->getPointerOperand()->stripPointerCasts(),
  612. DL.getTypeStoreSize(SI->getOperand(0)->getType()),
  613. findCommonAlignment(DL, SI, LI), C);
  614. if (changed) {
  615. MD->removeInstruction(SI);
  616. SI->eraseFromParent();
  617. MD->removeInstruction(LI);
  618. LI->eraseFromParent();
  619. ++NumMemCpyInstr;
  620. return true;
  621. }
  622. }
  623. }
  624. }
  625. // There are two cases that are interesting for this code to handle: memcpy
  626. // and memset. Right now we only handle memset.
  627. // Ensure that the value being stored is something that can be memset'able a
  628. // byte at a time like "0" or "-1" or any width, as well as things like
  629. // 0xA0A0A0A0 and 0.0.
  630. auto *V = SI->getOperand(0);
  631. if (Value *ByteVal = isBytewiseValue(V)) {
  632. if (Instruction *I = tryMergingIntoMemset(SI, SI->getPointerOperand(),
  633. ByteVal)) {
  634. BBI = I->getIterator(); // Don't invalidate iterator.
  635. return true;
  636. }
  637. // If we have an aggregate, we try to promote it to memset regardless
  638. // of opportunity for merging as it can expose optimization opportunities
  639. // in subsequent passes.
  640. auto *T = V->getType();
  641. if (T->isAggregateType()) {
  642. uint64_t Size = DL.getTypeStoreSize(T);
  643. unsigned Align = SI->getAlignment();
  644. if (!Align)
  645. Align = DL.getABITypeAlignment(T);
  646. IRBuilder<> Builder(SI);
  647. auto *M = Builder.CreateMemSet(SI->getPointerOperand(), ByteVal,
  648. Size, Align, SI->isVolatile());
  649. LLVM_DEBUG(dbgs() << "Promoting " << *SI << " to " << *M << "\n");
  650. MD->removeInstruction(SI);
  651. SI->eraseFromParent();
  652. NumMemSetInfer++;
  653. // Make sure we do not invalidate the iterator.
  654. BBI = M->getIterator();
  655. return true;
  656. }
  657. }
  658. return false;
  659. }
  660. bool MemCpyOptPass::processMemSet(MemSetInst *MSI, BasicBlock::iterator &BBI) {
  661. // See if there is another memset or store neighboring this memset which
  662. // allows us to widen out the memset to do a single larger store.
  663. if (isa<ConstantInt>(MSI->getLength()) && !MSI->isVolatile())
  664. if (Instruction *I = tryMergingIntoMemset(MSI, MSI->getDest(),
  665. MSI->getValue())) {
  666. BBI = I->getIterator(); // Don't invalidate iterator.
  667. return true;
  668. }
  669. return false;
  670. }
  671. /// Takes a memcpy and a call that it depends on,
  672. /// and checks for the possibility of a call slot optimization by having
  673. /// the call write its result directly into the destination of the memcpy.
  674. bool MemCpyOptPass::performCallSlotOptzn(Instruction *cpy, Value *cpyDest,
  675. Value *cpySrc, uint64_t cpyLen,
  676. unsigned cpyAlign, CallInst *C) {
  677. // The general transformation to keep in mind is
  678. //
  679. // call @func(..., src, ...)
  680. // memcpy(dest, src, ...)
  681. //
  682. // ->
  683. //
  684. // memcpy(dest, src, ...)
  685. // call @func(..., dest, ...)
  686. //
  687. // Since moving the memcpy is technically awkward, we additionally check that
  688. // src only holds uninitialized values at the moment of the call, meaning that
  689. // the memcpy can be discarded rather than moved.
  690. // Lifetime marks shouldn't be operated on.
  691. if (Function *F = C->getCalledFunction())
  692. if (F->isIntrinsic() && F->getIntrinsicID() == Intrinsic::lifetime_start)
  693. return false;
  694. // Deliberately get the source and destination with bitcasts stripped away,
  695. // because we'll need to do type comparisons based on the underlying type.
  696. CallSite CS(C);
  697. // Require that src be an alloca. This simplifies the reasoning considerably.
  698. AllocaInst *srcAlloca = dyn_cast<AllocaInst>(cpySrc);
  699. if (!srcAlloca)
  700. return false;
  701. ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
  702. if (!srcArraySize)
  703. return false;
  704. const DataLayout &DL = cpy->getModule()->getDataLayout();
  705. uint64_t srcSize = DL.getTypeAllocSize(srcAlloca->getAllocatedType()) *
  706. srcArraySize->getZExtValue();
  707. if (cpyLen < srcSize)
  708. return false;
  709. // Check that accessing the first srcSize bytes of dest will not cause a
  710. // trap. Otherwise the transform is invalid since it might cause a trap
  711. // to occur earlier than it otherwise would.
  712. if (AllocaInst *A = dyn_cast<AllocaInst>(cpyDest)) {
  713. // The destination is an alloca. Check it is larger than srcSize.
  714. ConstantInt *destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
  715. if (!destArraySize)
  716. return false;
  717. uint64_t destSize = DL.getTypeAllocSize(A->getAllocatedType()) *
  718. destArraySize->getZExtValue();
  719. if (destSize < srcSize)
  720. return false;
  721. } else if (Argument *A = dyn_cast<Argument>(cpyDest)) {
  722. // The store to dest may never happen if the call can throw.
  723. if (C->mayThrow())
  724. return false;
  725. if (A->getDereferenceableBytes() < srcSize) {
  726. // If the destination is an sret parameter then only accesses that are
  727. // outside of the returned struct type can trap.
  728. if (!A->hasStructRetAttr())
  729. return false;
  730. Type *StructTy = cast<PointerType>(A->getType())->getElementType();
  731. if (!StructTy->isSized()) {
  732. // The call may never return and hence the copy-instruction may never
  733. // be executed, and therefore it's not safe to say "the destination
  734. // has at least <cpyLen> bytes, as implied by the copy-instruction",
  735. return false;
  736. }
  737. uint64_t destSize = DL.getTypeAllocSize(StructTy);
  738. if (destSize < srcSize)
  739. return false;
  740. }
  741. } else {
  742. return false;
  743. }
  744. // Check that dest points to memory that is at least as aligned as src.
  745. unsigned srcAlign = srcAlloca->getAlignment();
  746. if (!srcAlign)
  747. srcAlign = DL.getABITypeAlignment(srcAlloca->getAllocatedType());
  748. bool isDestSufficientlyAligned = srcAlign <= cpyAlign;
  749. // If dest is not aligned enough and we can't increase its alignment then
  750. // bail out.
  751. if (!isDestSufficientlyAligned && !isa<AllocaInst>(cpyDest))
  752. return false;
  753. // Check that src is not accessed except via the call and the memcpy. This
  754. // guarantees that it holds only undefined values when passed in (so the final
  755. // memcpy can be dropped), that it is not read or written between the call and
  756. // the memcpy, and that writing beyond the end of it is undefined.
  757. SmallVector<User*, 8> srcUseList(srcAlloca->user_begin(),
  758. srcAlloca->user_end());
  759. while (!srcUseList.empty()) {
  760. User *U = srcUseList.pop_back_val();
  761. if (isa<BitCastInst>(U) || isa<AddrSpaceCastInst>(U)) {
  762. for (User *UU : U->users())
  763. srcUseList.push_back(UU);
  764. continue;
  765. }
  766. if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(U)) {
  767. if (!G->hasAllZeroIndices())
  768. return false;
  769. for (User *UU : U->users())
  770. srcUseList.push_back(UU);
  771. continue;
  772. }
  773. if (const IntrinsicInst *IT = dyn_cast<IntrinsicInst>(U))
  774. if (IT->getIntrinsicID() == Intrinsic::lifetime_start ||
  775. IT->getIntrinsicID() == Intrinsic::lifetime_end)
  776. continue;
  777. if (U != C && U != cpy)
  778. return false;
  779. }
  780. // Check that src isn't captured by the called function since the
  781. // transformation can cause aliasing issues in that case.
  782. for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
  783. if (CS.getArgument(i) == cpySrc && !CS.doesNotCapture(i))
  784. return false;
  785. // Since we're changing the parameter to the callsite, we need to make sure
  786. // that what would be the new parameter dominates the callsite.
  787. DominatorTree &DT = LookupDomTree();
  788. if (Instruction *cpyDestInst = dyn_cast<Instruction>(cpyDest))
  789. if (!DT.dominates(cpyDestInst, C))
  790. return false;
  791. // In addition to knowing that the call does not access src in some
  792. // unexpected manner, for example via a global, which we deduce from
  793. // the use analysis, we also need to know that it does not sneakily
  794. // access dest. We rely on AA to figure this out for us.
  795. AliasAnalysis &AA = LookupAliasAnalysis();
  796. ModRefInfo MR = AA.getModRefInfo(C, cpyDest, srcSize);
  797. // If necessary, perform additional analysis.
  798. if (isModOrRefSet(MR))
  799. MR = AA.callCapturesBefore(C, cpyDest, srcSize, &DT);
  800. if (isModOrRefSet(MR))
  801. return false;
  802. // We can't create address space casts here because we don't know if they're
  803. // safe for the target.
  804. if (cpySrc->getType()->getPointerAddressSpace() !=
  805. cpyDest->getType()->getPointerAddressSpace())
  806. return false;
  807. for (unsigned i = 0; i < CS.arg_size(); ++i)
  808. if (CS.getArgument(i)->stripPointerCasts() == cpySrc &&
  809. cpySrc->getType()->getPointerAddressSpace() !=
  810. CS.getArgument(i)->getType()->getPointerAddressSpace())
  811. return false;
  812. // All the checks have passed, so do the transformation.
  813. bool changedArgument = false;
  814. for (unsigned i = 0; i < CS.arg_size(); ++i)
  815. if (CS.getArgument(i)->stripPointerCasts() == cpySrc) {
  816. Value *Dest = cpySrc->getType() == cpyDest->getType() ? cpyDest
  817. : CastInst::CreatePointerCast(cpyDest, cpySrc->getType(),
  818. cpyDest->getName(), C);
  819. changedArgument = true;
  820. if (CS.getArgument(i)->getType() == Dest->getType())
  821. CS.setArgument(i, Dest);
  822. else
  823. CS.setArgument(i, CastInst::CreatePointerCast(Dest,
  824. CS.getArgument(i)->getType(), Dest->getName(), C));
  825. }
  826. if (!changedArgument)
  827. return false;
  828. // If the destination wasn't sufficiently aligned then increase its alignment.
  829. if (!isDestSufficientlyAligned) {
  830. assert(isa<AllocaInst>(cpyDest) && "Can only increase alloca alignment!");
  831. cast<AllocaInst>(cpyDest)->setAlignment(srcAlign);
  832. }
  833. // Drop any cached information about the call, because we may have changed
  834. // its dependence information by changing its parameter.
  835. MD->removeInstruction(C);
  836. // Update AA metadata
  837. // FIXME: MD_tbaa_struct and MD_mem_parallel_loop_access should also be
  838. // handled here, but combineMetadata doesn't support them yet
  839. unsigned KnownIDs[] = {LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
  840. LLVMContext::MD_noalias,
  841. LLVMContext::MD_invariant_group,
  842. LLVMContext::MD_access_group};
  843. combineMetadata(C, cpy, KnownIDs, true);
  844. // Remove the memcpy.
  845. MD->removeInstruction(cpy);
  846. ++NumMemCpyInstr;
  847. return true;
  848. }
  849. /// We've found that the (upward scanning) memory dependence of memcpy 'M' is
  850. /// the memcpy 'MDep'. Try to simplify M to copy from MDep's input if we can.
  851. bool MemCpyOptPass::processMemCpyMemCpyDependence(MemCpyInst *M,
  852. MemCpyInst *MDep) {
  853. // We can only transforms memcpy's where the dest of one is the source of the
  854. // other.
  855. if (M->getSource() != MDep->getDest() || MDep->isVolatile())
  856. return false;
  857. // If dep instruction is reading from our current input, then it is a noop
  858. // transfer and substituting the input won't change this instruction. Just
  859. // ignore the input and let someone else zap MDep. This handles cases like:
  860. // memcpy(a <- a)
  861. // memcpy(b <- a)
  862. if (M->getSource() == MDep->getSource())
  863. return false;
  864. // Second, the length of the memcpy's must be the same, or the preceding one
  865. // must be larger than the following one.
  866. ConstantInt *MDepLen = dyn_cast<ConstantInt>(MDep->getLength());
  867. ConstantInt *MLen = dyn_cast<ConstantInt>(M->getLength());
  868. if (!MDepLen || !MLen || MDepLen->getZExtValue() < MLen->getZExtValue())
  869. return false;
  870. AliasAnalysis &AA = LookupAliasAnalysis();
  871. // Verify that the copied-from memory doesn't change in between the two
  872. // transfers. For example, in:
  873. // memcpy(a <- b)
  874. // *b = 42;
  875. // memcpy(c <- a)
  876. // It would be invalid to transform the second memcpy into memcpy(c <- b).
  877. //
  878. // TODO: If the code between M and MDep is transparent to the destination "c",
  879. // then we could still perform the xform by moving M up to the first memcpy.
  880. //
  881. // NOTE: This is conservative, it will stop on any read from the source loc,
  882. // not just the defining memcpy.
  883. MemDepResult SourceDep =
  884. MD->getPointerDependencyFrom(MemoryLocation::getForSource(MDep), false,
  885. M->getIterator(), M->getParent());
  886. if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
  887. return false;
  888. // If the dest of the second might alias the source of the first, then the
  889. // source and dest might overlap. We still want to eliminate the intermediate
  890. // value, but we have to generate a memmove instead of memcpy.
  891. bool UseMemMove = false;
  892. if (!AA.isNoAlias(MemoryLocation::getForDest(M),
  893. MemoryLocation::getForSource(MDep)))
  894. UseMemMove = true;
  895. // If all checks passed, then we can transform M.
  896. // TODO: Is this worth it if we're creating a less aligned memcpy? For
  897. // example we could be moving from movaps -> movq on x86.
  898. IRBuilder<> Builder(M);
  899. if (UseMemMove)
  900. Builder.CreateMemMove(M->getRawDest(), M->getDestAlignment(),
  901. MDep->getRawSource(), MDep->getSourceAlignment(),
  902. M->getLength(), M->isVolatile());
  903. else
  904. Builder.CreateMemCpy(M->getRawDest(), M->getDestAlignment(),
  905. MDep->getRawSource(), MDep->getSourceAlignment(),
  906. M->getLength(), M->isVolatile());
  907. // Remove the instruction we're replacing.
  908. MD->removeInstruction(M);
  909. M->eraseFromParent();
  910. ++NumMemCpyInstr;
  911. return true;
  912. }
  913. /// We've found that the (upward scanning) memory dependence of \p MemCpy is
  914. /// \p MemSet. Try to simplify \p MemSet to only set the trailing bytes that
  915. /// weren't copied over by \p MemCpy.
  916. ///
  917. /// In other words, transform:
  918. /// \code
  919. /// memset(dst, c, dst_size);
  920. /// memcpy(dst, src, src_size);
  921. /// \endcode
  922. /// into:
  923. /// \code
  924. /// memcpy(dst, src, src_size);
  925. /// memset(dst + src_size, c, dst_size <= src_size ? 0 : dst_size - src_size);
  926. /// \endcode
  927. bool MemCpyOptPass::processMemSetMemCpyDependence(MemCpyInst *MemCpy,
  928. MemSetInst *MemSet) {
  929. // We can only transform memset/memcpy with the same destination.
  930. if (MemSet->getDest() != MemCpy->getDest())
  931. return false;
  932. // Check that there are no other dependencies on the memset destination.
  933. MemDepResult DstDepInfo =
  934. MD->getPointerDependencyFrom(MemoryLocation::getForDest(MemSet), false,
  935. MemCpy->getIterator(), MemCpy->getParent());
  936. if (DstDepInfo.getInst() != MemSet)
  937. return false;
  938. // Use the same i8* dest as the memcpy, killing the memset dest if different.
  939. Value *Dest = MemCpy->getRawDest();
  940. Value *DestSize = MemSet->getLength();
  941. Value *SrcSize = MemCpy->getLength();
  942. // By default, create an unaligned memset.
  943. unsigned Align = 1;
  944. // If Dest is aligned, and SrcSize is constant, use the minimum alignment
  945. // of the sum.
  946. const unsigned DestAlign =
  947. std::max(MemSet->getDestAlignment(), MemCpy->getDestAlignment());
  948. if (DestAlign > 1)
  949. if (ConstantInt *SrcSizeC = dyn_cast<ConstantInt>(SrcSize))
  950. Align = MinAlign(SrcSizeC->getZExtValue(), DestAlign);
  951. IRBuilder<> Builder(MemCpy);
  952. // If the sizes have different types, zext the smaller one.
  953. if (DestSize->getType() != SrcSize->getType()) {
  954. if (DestSize->getType()->getIntegerBitWidth() >
  955. SrcSize->getType()->getIntegerBitWidth())
  956. SrcSize = Builder.CreateZExt(SrcSize, DestSize->getType());
  957. else
  958. DestSize = Builder.CreateZExt(DestSize, SrcSize->getType());
  959. }
  960. Value *Ule = Builder.CreateICmpULE(DestSize, SrcSize);
  961. Value *SizeDiff = Builder.CreateSub(DestSize, SrcSize);
  962. Value *MemsetLen = Builder.CreateSelect(
  963. Ule, ConstantInt::getNullValue(DestSize->getType()), SizeDiff);
  964. Builder.CreateMemSet(Builder.CreateGEP(Dest, SrcSize), MemSet->getOperand(1),
  965. MemsetLen, Align);
  966. MD->removeInstruction(MemSet);
  967. MemSet->eraseFromParent();
  968. return true;
  969. }
  970. /// Determine whether the instruction has undefined content for the given Size,
  971. /// either because it was freshly alloca'd or started its lifetime.
  972. static bool hasUndefContents(Instruction *I, ConstantInt *Size) {
  973. if (isa<AllocaInst>(I))
  974. return true;
  975. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
  976. if (II->getIntrinsicID() == Intrinsic::lifetime_start)
  977. if (ConstantInt *LTSize = dyn_cast<ConstantInt>(II->getArgOperand(0)))
  978. if (LTSize->getZExtValue() >= Size->getZExtValue())
  979. return true;
  980. return false;
  981. }
  982. /// Transform memcpy to memset when its source was just memset.
  983. /// In other words, turn:
  984. /// \code
  985. /// memset(dst1, c, dst1_size);
  986. /// memcpy(dst2, dst1, dst2_size);
  987. /// \endcode
  988. /// into:
  989. /// \code
  990. /// memset(dst1, c, dst1_size);
  991. /// memset(dst2, c, dst2_size);
  992. /// \endcode
  993. /// When dst2_size <= dst1_size.
  994. ///
  995. /// The \p MemCpy must have a Constant length.
  996. bool MemCpyOptPass::performMemCpyToMemSetOptzn(MemCpyInst *MemCpy,
  997. MemSetInst *MemSet) {
  998. AliasAnalysis &AA = LookupAliasAnalysis();
  999. // Make sure that memcpy(..., memset(...), ...), that is we are memsetting and
  1000. // memcpying from the same address. Otherwise it is hard to reason about.
  1001. if (!AA.isMustAlias(MemSet->getRawDest(), MemCpy->getRawSource()))
  1002. return false;
  1003. // A known memset size is required.
  1004. ConstantInt *MemSetSize = dyn_cast<ConstantInt>(MemSet->getLength());
  1005. if (!MemSetSize)
  1006. return false;
  1007. // Make sure the memcpy doesn't read any more than what the memset wrote.
  1008. // Don't worry about sizes larger than i64.
  1009. ConstantInt *CopySize = cast<ConstantInt>(MemCpy->getLength());
  1010. if (CopySize->getZExtValue() > MemSetSize->getZExtValue()) {
  1011. // If the memcpy is larger than the memset, but the memory was undef prior
  1012. // to the memset, we can just ignore the tail. Technically we're only
  1013. // interested in the bytes from MemSetSize..CopySize here, but as we can't
  1014. // easily represent this location, we use the full 0..CopySize range.
  1015. MemoryLocation MemCpyLoc = MemoryLocation::getForSource(MemCpy);
  1016. MemDepResult DepInfo = MD->getPointerDependencyFrom(
  1017. MemCpyLoc, true, MemSet->getIterator(), MemSet->getParent());
  1018. if (DepInfo.isDef() && hasUndefContents(DepInfo.getInst(), CopySize))
  1019. CopySize = MemSetSize;
  1020. else
  1021. return false;
  1022. }
  1023. IRBuilder<> Builder(MemCpy);
  1024. Builder.CreateMemSet(MemCpy->getRawDest(), MemSet->getOperand(1),
  1025. CopySize, MemCpy->getDestAlignment());
  1026. return true;
  1027. }
  1028. /// Perform simplification of memcpy's. If we have memcpy A
  1029. /// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite
  1030. /// B to be a memcpy from X to Z (or potentially a memmove, depending on
  1031. /// circumstances). This allows later passes to remove the first memcpy
  1032. /// altogether.
  1033. bool MemCpyOptPass::processMemCpy(MemCpyInst *M) {
  1034. // We can only optimize non-volatile memcpy's.
  1035. if (M->isVolatile()) return false;
  1036. // If the source and destination of the memcpy are the same, then zap it.
  1037. if (M->getSource() == M->getDest()) {
  1038. MD->removeInstruction(M);
  1039. M->eraseFromParent();
  1040. return false;
  1041. }
  1042. // If copying from a constant, try to turn the memcpy into a memset.
  1043. if (GlobalVariable *GV = dyn_cast<GlobalVariable>(M->getSource()))
  1044. if (GV->isConstant() && GV->hasDefinitiveInitializer())
  1045. if (Value *ByteVal = isBytewiseValue(GV->getInitializer())) {
  1046. IRBuilder<> Builder(M);
  1047. Builder.CreateMemSet(M->getRawDest(), ByteVal, M->getLength(),
  1048. M->getDestAlignment(), false);
  1049. MD->removeInstruction(M);
  1050. M->eraseFromParent();
  1051. ++NumCpyToSet;
  1052. return true;
  1053. }
  1054. MemDepResult DepInfo = MD->getDependency(M);
  1055. // Try to turn a partially redundant memset + memcpy into
  1056. // memcpy + smaller memset. We don't need the memcpy size for this.
  1057. if (DepInfo.isClobber())
  1058. if (MemSetInst *MDep = dyn_cast<MemSetInst>(DepInfo.getInst()))
  1059. if (processMemSetMemCpyDependence(M, MDep))
  1060. return true;
  1061. // The optimizations after this point require the memcpy size.
  1062. ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength());
  1063. if (!CopySize) return false;
  1064. // There are four possible optimizations we can do for memcpy:
  1065. // a) memcpy-memcpy xform which exposes redundance for DSE.
  1066. // b) call-memcpy xform for return slot optimization.
  1067. // c) memcpy from freshly alloca'd space or space that has just started its
  1068. // lifetime copies undefined data, and we can therefore eliminate the
  1069. // memcpy in favor of the data that was already at the destination.
  1070. // d) memcpy from a just-memset'd source can be turned into memset.
  1071. if (DepInfo.isClobber()) {
  1072. if (CallInst *C = dyn_cast<CallInst>(DepInfo.getInst())) {
  1073. // FIXME: Can we pass in either of dest/src alignment here instead
  1074. // of conservatively taking the minimum?
  1075. unsigned Align = MinAlign(M->getDestAlignment(), M->getSourceAlignment());
  1076. if (performCallSlotOptzn(M, M->getDest(), M->getSource(),
  1077. CopySize->getZExtValue(), Align,
  1078. C)) {
  1079. MD->removeInstruction(M);
  1080. M->eraseFromParent();
  1081. return true;
  1082. }
  1083. }
  1084. }
  1085. MemoryLocation SrcLoc = MemoryLocation::getForSource(M);
  1086. MemDepResult SrcDepInfo = MD->getPointerDependencyFrom(
  1087. SrcLoc, true, M->getIterator(), M->getParent());
  1088. if (SrcDepInfo.isClobber()) {
  1089. if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(SrcDepInfo.getInst()))
  1090. return processMemCpyMemCpyDependence(M, MDep);
  1091. } else if (SrcDepInfo.isDef()) {
  1092. if (hasUndefContents(SrcDepInfo.getInst(), CopySize)) {
  1093. MD->removeInstruction(M);
  1094. M->eraseFromParent();
  1095. ++NumMemCpyInstr;
  1096. return true;
  1097. }
  1098. }
  1099. if (SrcDepInfo.isClobber())
  1100. if (MemSetInst *MDep = dyn_cast<MemSetInst>(SrcDepInfo.getInst()))
  1101. if (performMemCpyToMemSetOptzn(M, MDep)) {
  1102. MD->removeInstruction(M);
  1103. M->eraseFromParent();
  1104. ++NumCpyToSet;
  1105. return true;
  1106. }
  1107. return false;
  1108. }
  1109. /// Transforms memmove calls to memcpy calls when the src/dst are guaranteed
  1110. /// not to alias.
  1111. bool MemCpyOptPass::processMemMove(MemMoveInst *M) {
  1112. AliasAnalysis &AA = LookupAliasAnalysis();
  1113. if (!TLI->has(LibFunc_memmove))
  1114. return false;
  1115. // See if the pointers alias.
  1116. if (!AA.isNoAlias(MemoryLocation::getForDest(M),
  1117. MemoryLocation::getForSource(M)))
  1118. return false;
  1119. LLVM_DEBUG(dbgs() << "MemCpyOptPass: Optimizing memmove -> memcpy: " << *M
  1120. << "\n");
  1121. // If not, then we know we can transform this.
  1122. Type *ArgTys[3] = { M->getRawDest()->getType(),
  1123. M->getRawSource()->getType(),
  1124. M->getLength()->getType() };
  1125. M->setCalledFunction(Intrinsic::getDeclaration(M->getModule(),
  1126. Intrinsic::memcpy, ArgTys));
  1127. // MemDep may have over conservative information about this instruction, just
  1128. // conservatively flush it from the cache.
  1129. MD->removeInstruction(M);
  1130. ++NumMoveToCpy;
  1131. return true;
  1132. }
  1133. /// This is called on every byval argument in call sites.
  1134. bool MemCpyOptPass::processByValArgument(CallSite CS, unsigned ArgNo) {
  1135. const DataLayout &DL = CS.getCaller()->getParent()->getDataLayout();
  1136. // Find out what feeds this byval argument.
  1137. Value *ByValArg = CS.getArgument(ArgNo);
  1138. Type *ByValTy = cast<PointerType>(ByValArg->getType())->getElementType();
  1139. uint64_t ByValSize = DL.getTypeAllocSize(ByValTy);
  1140. MemDepResult DepInfo = MD->getPointerDependencyFrom(
  1141. MemoryLocation(ByValArg, ByValSize), true,
  1142. CS.getInstruction()->getIterator(), CS.getInstruction()->getParent());
  1143. if (!DepInfo.isClobber())
  1144. return false;
  1145. // If the byval argument isn't fed by a memcpy, ignore it. If it is fed by
  1146. // a memcpy, see if we can byval from the source of the memcpy instead of the
  1147. // result.
  1148. MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst());
  1149. if (!MDep || MDep->isVolatile() ||
  1150. ByValArg->stripPointerCasts() != MDep->getDest())
  1151. return false;
  1152. // The length of the memcpy must be larger or equal to the size of the byval.
  1153. ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
  1154. if (!C1 || C1->getValue().getZExtValue() < ByValSize)
  1155. return false;
  1156. // Get the alignment of the byval. If the call doesn't specify the alignment,
  1157. // then it is some target specific value that we can't know.
  1158. unsigned ByValAlign = CS.getParamAlignment(ArgNo);
  1159. if (ByValAlign == 0) return false;
  1160. // If it is greater than the memcpy, then we check to see if we can force the
  1161. // source of the memcpy to the alignment we need. If we fail, we bail out.
  1162. AssumptionCache &AC = LookupAssumptionCache();
  1163. DominatorTree &DT = LookupDomTree();
  1164. if (MDep->getSourceAlignment() < ByValAlign &&
  1165. getOrEnforceKnownAlignment(MDep->getSource(), ByValAlign, DL,
  1166. CS.getInstruction(), &AC, &DT) < ByValAlign)
  1167. return false;
  1168. // The address space of the memcpy source must match the byval argument
  1169. if (MDep->getSource()->getType()->getPointerAddressSpace() !=
  1170. ByValArg->getType()->getPointerAddressSpace())
  1171. return false;
  1172. // Verify that the copied-from memory doesn't change in between the memcpy and
  1173. // the byval call.
  1174. // memcpy(a <- b)
  1175. // *b = 42;
  1176. // foo(*a)
  1177. // It would be invalid to transform the second memcpy into foo(*b).
  1178. //
  1179. // NOTE: This is conservative, it will stop on any read from the source loc,
  1180. // not just the defining memcpy.
  1181. MemDepResult SourceDep = MD->getPointerDependencyFrom(
  1182. MemoryLocation::getForSource(MDep), false,
  1183. CS.getInstruction()->getIterator(), MDep->getParent());
  1184. if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
  1185. return false;
  1186. Value *TmpCast = MDep->getSource();
  1187. if (MDep->getSource()->getType() != ByValArg->getType())
  1188. TmpCast = new BitCastInst(MDep->getSource(), ByValArg->getType(),
  1189. "tmpcast", CS.getInstruction());
  1190. LLVM_DEBUG(dbgs() << "MemCpyOptPass: Forwarding memcpy to byval:\n"
  1191. << " " << *MDep << "\n"
  1192. << " " << *CS.getInstruction() << "\n");
  1193. // Otherwise we're good! Update the byval argument.
  1194. CS.setArgument(ArgNo, TmpCast);
  1195. ++NumMemCpyInstr;
  1196. return true;
  1197. }
  1198. /// Executes one iteration of MemCpyOptPass.
  1199. bool MemCpyOptPass::iterateOnFunction(Function &F) {
  1200. bool MadeChange = false;
  1201. DominatorTree &DT = LookupDomTree();
  1202. // Walk all instruction in the function.
  1203. for (BasicBlock &BB : F) {
  1204. // Skip unreachable blocks. For example processStore assumes that an
  1205. // instruction in a BB can't be dominated by a later instruction in the
  1206. // same BB (which is a scenario that can happen for an unreachable BB that
  1207. // has itself as a predecessor).
  1208. if (!DT.isReachableFromEntry(&BB))
  1209. continue;
  1210. for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
  1211. // Avoid invalidating the iterator.
  1212. Instruction *I = &*BI++;
  1213. bool RepeatInstruction = false;
  1214. if (StoreInst *SI = dyn_cast<StoreInst>(I))
  1215. MadeChange |= processStore(SI, BI);
  1216. else if (MemSetInst *M = dyn_cast<MemSetInst>(I))
  1217. RepeatInstruction = processMemSet(M, BI);
  1218. else if (MemCpyInst *M = dyn_cast<MemCpyInst>(I))
  1219. RepeatInstruction = processMemCpy(M);
  1220. else if (MemMoveInst *M = dyn_cast<MemMoveInst>(I))
  1221. RepeatInstruction = processMemMove(M);
  1222. else if (auto CS = CallSite(I)) {
  1223. for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
  1224. if (CS.isByValArgument(i))
  1225. MadeChange |= processByValArgument(CS, i);
  1226. }
  1227. // Reprocess the instruction if desired.
  1228. if (RepeatInstruction) {
  1229. if (BI != BB.begin())
  1230. --BI;
  1231. MadeChange = true;
  1232. }
  1233. }
  1234. }
  1235. return MadeChange;
  1236. }
  1237. PreservedAnalyses MemCpyOptPass::run(Function &F, FunctionAnalysisManager &AM) {
  1238. auto &MD = AM.getResult<MemoryDependenceAnalysis>(F);
  1239. auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
  1240. auto LookupAliasAnalysis = [&]() -> AliasAnalysis & {
  1241. return AM.getResult<AAManager>(F);
  1242. };
  1243. auto LookupAssumptionCache = [&]() -> AssumptionCache & {
  1244. return AM.getResult<AssumptionAnalysis>(F);
  1245. };
  1246. auto LookupDomTree = [&]() -> DominatorTree & {
  1247. return AM.getResult<DominatorTreeAnalysis>(F);
  1248. };
  1249. bool MadeChange = runImpl(F, &MD, &TLI, LookupAliasAnalysis,
  1250. LookupAssumptionCache, LookupDomTree);
  1251. if (!MadeChange)
  1252. return PreservedAnalyses::all();
  1253. PreservedAnalyses PA;
  1254. PA.preserveSet<CFGAnalyses>();
  1255. PA.preserve<GlobalsAA>();
  1256. PA.preserve<MemoryDependenceAnalysis>();
  1257. return PA;
  1258. }
  1259. bool MemCpyOptPass::runImpl(
  1260. Function &F, MemoryDependenceResults *MD_, TargetLibraryInfo *TLI_,
  1261. std::function<AliasAnalysis &()> LookupAliasAnalysis_,
  1262. std::function<AssumptionCache &()> LookupAssumptionCache_,
  1263. std::function<DominatorTree &()> LookupDomTree_) {
  1264. bool MadeChange = false;
  1265. MD = MD_;
  1266. TLI = TLI_;
  1267. LookupAliasAnalysis = std::move(LookupAliasAnalysis_);
  1268. LookupAssumptionCache = std::move(LookupAssumptionCache_);
  1269. LookupDomTree = std::move(LookupDomTree_);
  1270. // If we don't have at least memset and memcpy, there is little point of doing
  1271. // anything here. These are required by a freestanding implementation, so if
  1272. // even they are disabled, there is no point in trying hard.
  1273. if (!TLI->has(LibFunc_memset) || !TLI->has(LibFunc_memcpy))
  1274. return false;
  1275. while (true) {
  1276. if (!iterateOnFunction(F))
  1277. break;
  1278. MadeChange = true;
  1279. }
  1280. MD = nullptr;
  1281. return MadeChange;
  1282. }
  1283. /// This is the main transformation entry point for a function.
  1284. bool MemCpyOptLegacyPass::runOnFunction(Function &F) {
  1285. if (skipFunction(F))
  1286. return false;
  1287. auto *MD = &getAnalysis<MemoryDependenceWrapperPass>().getMemDep();
  1288. auto *TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
  1289. auto LookupAliasAnalysis = [this]() -> AliasAnalysis & {
  1290. return getAnalysis<AAResultsWrapperPass>().getAAResults();
  1291. };
  1292. auto LookupAssumptionCache = [this, &F]() -> AssumptionCache & {
  1293. return getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  1294. };
  1295. auto LookupDomTree = [this]() -> DominatorTree & {
  1296. return getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  1297. };
  1298. return Impl.runImpl(F, MD, TLI, LookupAliasAnalysis, LookupAssumptionCache,
  1299. LookupDomTree);
  1300. }