MemCpyOptimizer.cpp 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746
  1. //===- MemCpyOptimizer.cpp - Optimize use of memcpy and friends -----------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This pass performs various transformations related to eliminating memcpy
  10. // calls, or transforming sets of stores into memset's.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
  14. #include "llvm/ADT/DenseSet.h"
  15. #include "llvm/ADT/STLExtras.h"
  16. #include "llvm/ADT/SmallVector.h"
  17. #include "llvm/ADT/Statistic.h"
  18. #include "llvm/ADT/iterator_range.h"
  19. #include "llvm/Analysis/AliasAnalysis.h"
  20. #include "llvm/Analysis/AssumptionCache.h"
  21. #include "llvm/Analysis/CaptureTracking.h"
  22. #include "llvm/Analysis/GlobalsModRef.h"
  23. #include "llvm/Analysis/Loads.h"
  24. #include "llvm/Analysis/MemoryLocation.h"
  25. #include "llvm/Analysis/MemorySSA.h"
  26. #include "llvm/Analysis/MemorySSAUpdater.h"
  27. #include "llvm/Analysis/TargetLibraryInfo.h"
  28. #include "llvm/Analysis/ValueTracking.h"
  29. #include "llvm/IR/BasicBlock.h"
  30. #include "llvm/IR/Constants.h"
  31. #include "llvm/IR/DataLayout.h"
  32. #include "llvm/IR/DerivedTypes.h"
  33. #include "llvm/IR/Dominators.h"
  34. #include "llvm/IR/Function.h"
  35. #include "llvm/IR/GlobalVariable.h"
  36. #include "llvm/IR/IRBuilder.h"
  37. #include "llvm/IR/InstrTypes.h"
  38. #include "llvm/IR/Instruction.h"
  39. #include "llvm/IR/Instructions.h"
  40. #include "llvm/IR/IntrinsicInst.h"
  41. #include "llvm/IR/Intrinsics.h"
  42. #include "llvm/IR/LLVMContext.h"
  43. #include "llvm/IR/Module.h"
  44. #include "llvm/IR/PassManager.h"
  45. #include "llvm/IR/Type.h"
  46. #include "llvm/IR/User.h"
  47. #include "llvm/IR/Value.h"
  48. #include "llvm/InitializePasses.h"
  49. #include "llvm/Pass.h"
  50. #include "llvm/Support/Casting.h"
  51. #include "llvm/Support/Debug.h"
  52. #include "llvm/Support/MathExtras.h"
  53. #include "llvm/Support/raw_ostream.h"
  54. #include "llvm/Transforms/Scalar.h"
  55. #include "llvm/Transforms/Utils/Local.h"
  56. #include <algorithm>
  57. #include <cassert>
  58. #include <cstdint>
  59. #include <optional>
  60. using namespace llvm;
  61. #define DEBUG_TYPE "memcpyopt"
  62. static cl::opt<bool> EnableMemCpyOptWithoutLibcalls(
  63. "enable-memcpyopt-without-libcalls", cl::Hidden,
  64. cl::desc("Enable memcpyopt even when libcalls are disabled"));
  65. STATISTIC(NumMemCpyInstr, "Number of memcpy instructions deleted");
  66. STATISTIC(NumMemSetInfer, "Number of memsets inferred");
  67. STATISTIC(NumMoveToCpy, "Number of memmoves converted to memcpy");
  68. STATISTIC(NumCpyToSet, "Number of memcpys converted to memset");
  69. STATISTIC(NumCallSlot, "Number of call slot optimizations performed");
  70. namespace {
  71. /// Represents a range of memset'd bytes with the ByteVal value.
  72. /// This allows us to analyze stores like:
  73. /// store 0 -> P+1
  74. /// store 0 -> P+0
  75. /// store 0 -> P+3
  76. /// store 0 -> P+2
  77. /// which sometimes happens with stores to arrays of structs etc. When we see
  78. /// the first store, we make a range [1, 2). The second store extends the range
  79. /// to [0, 2). The third makes a new range [2, 3). The fourth store joins the
  80. /// two ranges into [0, 3) which is memset'able.
  81. struct MemsetRange {
  82. // Start/End - A semi range that describes the span that this range covers.
  83. // The range is closed at the start and open at the end: [Start, End).
  84. int64_t Start, End;
  85. /// StartPtr - The getelementptr instruction that points to the start of the
  86. /// range.
  87. Value *StartPtr;
  88. /// Alignment - The known alignment of the first store.
  89. MaybeAlign Alignment;
  90. /// TheStores - The actual stores that make up this range.
  91. SmallVector<Instruction*, 16> TheStores;
  92. bool isProfitableToUseMemset(const DataLayout &DL) const;
  93. };
  94. } // end anonymous namespace
  95. bool MemsetRange::isProfitableToUseMemset(const DataLayout &DL) const {
  96. // If we found more than 4 stores to merge or 16 bytes, use memset.
  97. if (TheStores.size() >= 4 || End-Start >= 16) return true;
  98. // If there is nothing to merge, don't do anything.
  99. if (TheStores.size() < 2) return false;
  100. // If any of the stores are a memset, then it is always good to extend the
  101. // memset.
  102. for (Instruction *SI : TheStores)
  103. if (!isa<StoreInst>(SI))
  104. return true;
  105. // Assume that the code generator is capable of merging pairs of stores
  106. // together if it wants to.
  107. if (TheStores.size() == 2) return false;
  108. // If we have fewer than 8 stores, it can still be worthwhile to do this.
  109. // For example, merging 4 i8 stores into an i32 store is useful almost always.
  110. // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the
  111. // memset will be split into 2 32-bit stores anyway) and doing so can
  112. // pessimize the llvm optimizer.
  113. //
  114. // Since we don't have perfect knowledge here, make some assumptions: assume
  115. // the maximum GPR width is the same size as the largest legal integer
  116. // size. If so, check to see whether we will end up actually reducing the
  117. // number of stores used.
  118. unsigned Bytes = unsigned(End-Start);
  119. unsigned MaxIntSize = DL.getLargestLegalIntTypeSizeInBits() / 8;
  120. if (MaxIntSize == 0)
  121. MaxIntSize = 1;
  122. unsigned NumPointerStores = Bytes / MaxIntSize;
  123. // Assume the remaining bytes if any are done a byte at a time.
  124. unsigned NumByteStores = Bytes % MaxIntSize;
  125. // If we will reduce the # stores (according to this heuristic), do the
  126. // transformation. This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32
  127. // etc.
  128. return TheStores.size() > NumPointerStores+NumByteStores;
  129. }
  130. namespace {
  131. class MemsetRanges {
  132. using range_iterator = SmallVectorImpl<MemsetRange>::iterator;
  133. /// A sorted list of the memset ranges.
  134. SmallVector<MemsetRange, 8> Ranges;
  135. const DataLayout &DL;
  136. public:
  137. MemsetRanges(const DataLayout &DL) : DL(DL) {}
  138. using const_iterator = SmallVectorImpl<MemsetRange>::const_iterator;
  139. const_iterator begin() const { return Ranges.begin(); }
  140. const_iterator end() const { return Ranges.end(); }
  141. bool empty() const { return Ranges.empty(); }
  142. void addInst(int64_t OffsetFromFirst, Instruction *Inst) {
  143. if (auto *SI = dyn_cast<StoreInst>(Inst))
  144. addStore(OffsetFromFirst, SI);
  145. else
  146. addMemSet(OffsetFromFirst, cast<MemSetInst>(Inst));
  147. }
  148. void addStore(int64_t OffsetFromFirst, StoreInst *SI) {
  149. TypeSize StoreSize = DL.getTypeStoreSize(SI->getOperand(0)->getType());
  150. assert(!StoreSize.isScalable() && "Can't track scalable-typed stores");
  151. addRange(OffsetFromFirst, StoreSize.getFixedValue(),
  152. SI->getPointerOperand(), SI->getAlign(), SI);
  153. }
  154. void addMemSet(int64_t OffsetFromFirst, MemSetInst *MSI) {
  155. int64_t Size = cast<ConstantInt>(MSI->getLength())->getZExtValue();
  156. addRange(OffsetFromFirst, Size, MSI->getDest(), MSI->getDestAlign(), MSI);
  157. }
  158. void addRange(int64_t Start, int64_t Size, Value *Ptr, MaybeAlign Alignment,
  159. Instruction *Inst);
  160. };
  161. } // end anonymous namespace
  162. /// Add a new store to the MemsetRanges data structure. This adds a
  163. /// new range for the specified store at the specified offset, merging into
  164. /// existing ranges as appropriate.
  165. void MemsetRanges::addRange(int64_t Start, int64_t Size, Value *Ptr,
  166. MaybeAlign Alignment, Instruction *Inst) {
  167. int64_t End = Start+Size;
  168. range_iterator I = partition_point(
  169. Ranges, [=](const MemsetRange &O) { return O.End < Start; });
  170. // We now know that I == E, in which case we didn't find anything to merge
  171. // with, or that Start <= I->End. If End < I->Start or I == E, then we need
  172. // to insert a new range. Handle this now.
  173. if (I == Ranges.end() || End < I->Start) {
  174. MemsetRange &R = *Ranges.insert(I, MemsetRange());
  175. R.Start = Start;
  176. R.End = End;
  177. R.StartPtr = Ptr;
  178. R.Alignment = Alignment;
  179. R.TheStores.push_back(Inst);
  180. return;
  181. }
  182. // This store overlaps with I, add it.
  183. I->TheStores.push_back(Inst);
  184. // At this point, we may have an interval that completely contains our store.
  185. // If so, just add it to the interval and return.
  186. if (I->Start <= Start && I->End >= End)
  187. return;
  188. // Now we know that Start <= I->End and End >= I->Start so the range overlaps
  189. // but is not entirely contained within the range.
  190. // See if the range extends the start of the range. In this case, it couldn't
  191. // possibly cause it to join the prior range, because otherwise we would have
  192. // stopped on *it*.
  193. if (Start < I->Start) {
  194. I->Start = Start;
  195. I->StartPtr = Ptr;
  196. I->Alignment = Alignment;
  197. }
  198. // Now we know that Start <= I->End and Start >= I->Start (so the startpoint
  199. // is in or right at the end of I), and that End >= I->Start. Extend I out to
  200. // End.
  201. if (End > I->End) {
  202. I->End = End;
  203. range_iterator NextI = I;
  204. while (++NextI != Ranges.end() && End >= NextI->Start) {
  205. // Merge the range in.
  206. I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
  207. if (NextI->End > I->End)
  208. I->End = NextI->End;
  209. Ranges.erase(NextI);
  210. NextI = I;
  211. }
  212. }
  213. }
  214. //===----------------------------------------------------------------------===//
  215. // MemCpyOptLegacyPass Pass
  216. //===----------------------------------------------------------------------===//
  217. namespace {
  218. class MemCpyOptLegacyPass : public FunctionPass {
  219. MemCpyOptPass Impl;
  220. public:
  221. static char ID; // Pass identification, replacement for typeid
  222. MemCpyOptLegacyPass() : FunctionPass(ID) {
  223. initializeMemCpyOptLegacyPassPass(*PassRegistry::getPassRegistry());
  224. }
  225. bool runOnFunction(Function &F) override;
  226. private:
  227. // This transformation requires dominator postdominator info
  228. void getAnalysisUsage(AnalysisUsage &AU) const override {
  229. AU.setPreservesCFG();
  230. AU.addRequired<AssumptionCacheTracker>();
  231. AU.addRequired<DominatorTreeWrapperPass>();
  232. AU.addPreserved<DominatorTreeWrapperPass>();
  233. AU.addPreserved<GlobalsAAWrapperPass>();
  234. AU.addRequired<TargetLibraryInfoWrapperPass>();
  235. AU.addRequired<AAResultsWrapperPass>();
  236. AU.addPreserved<AAResultsWrapperPass>();
  237. AU.addRequired<MemorySSAWrapperPass>();
  238. AU.addPreserved<MemorySSAWrapperPass>();
  239. }
  240. };
  241. } // end anonymous namespace
  242. char MemCpyOptLegacyPass::ID = 0;
  243. /// The public interface to this file...
  244. FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOptLegacyPass(); }
  245. INITIALIZE_PASS_BEGIN(MemCpyOptLegacyPass, "memcpyopt", "MemCpy Optimization",
  246. false, false)
  247. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  248. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  249. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  250. INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
  251. INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
  252. INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
  253. INITIALIZE_PASS_END(MemCpyOptLegacyPass, "memcpyopt", "MemCpy Optimization",
  254. false, false)
  255. // Check that V is either not accessible by the caller, or unwinding cannot
  256. // occur between Start and End.
  257. static bool mayBeVisibleThroughUnwinding(Value *V, Instruction *Start,
  258. Instruction *End) {
  259. assert(Start->getParent() == End->getParent() && "Must be in same block");
  260. // Function can't unwind, so it also can't be visible through unwinding.
  261. if (Start->getFunction()->doesNotThrow())
  262. return false;
  263. // Object is not visible on unwind.
  264. // TODO: Support RequiresNoCaptureBeforeUnwind case.
  265. bool RequiresNoCaptureBeforeUnwind;
  266. if (isNotVisibleOnUnwind(getUnderlyingObject(V),
  267. RequiresNoCaptureBeforeUnwind) &&
  268. !RequiresNoCaptureBeforeUnwind)
  269. return false;
  270. // Check whether there are any unwinding instructions in the range.
  271. return any_of(make_range(Start->getIterator(), End->getIterator()),
  272. [](const Instruction &I) { return I.mayThrow(); });
  273. }
  274. void MemCpyOptPass::eraseInstruction(Instruction *I) {
  275. MSSAU->removeMemoryAccess(I);
  276. I->eraseFromParent();
  277. }
  278. // Check for mod or ref of Loc between Start and End, excluding both boundaries.
  279. // Start and End must be in the same block.
  280. // If SkippedLifetimeStart is provided, skip over one clobbering lifetime.start
  281. // intrinsic and store it inside SkippedLifetimeStart.
  282. static bool accessedBetween(BatchAAResults &AA, MemoryLocation Loc,
  283. const MemoryUseOrDef *Start,
  284. const MemoryUseOrDef *End,
  285. Instruction **SkippedLifetimeStart = nullptr) {
  286. assert(Start->getBlock() == End->getBlock() && "Only local supported");
  287. for (const MemoryAccess &MA :
  288. make_range(++Start->getIterator(), End->getIterator())) {
  289. Instruction *I = cast<MemoryUseOrDef>(MA).getMemoryInst();
  290. if (isModOrRefSet(AA.getModRefInfo(I, Loc))) {
  291. auto *II = dyn_cast<IntrinsicInst>(I);
  292. if (II && II->getIntrinsicID() == Intrinsic::lifetime_start &&
  293. SkippedLifetimeStart && !*SkippedLifetimeStart) {
  294. *SkippedLifetimeStart = I;
  295. continue;
  296. }
  297. return true;
  298. }
  299. }
  300. return false;
  301. }
  302. // Check for mod of Loc between Start and End, excluding both boundaries.
  303. // Start and End can be in different blocks.
  304. static bool writtenBetween(MemorySSA *MSSA, BatchAAResults &AA,
  305. MemoryLocation Loc, const MemoryUseOrDef *Start,
  306. const MemoryUseOrDef *End) {
  307. if (isa<MemoryUse>(End)) {
  308. // For MemoryUses, getClobberingMemoryAccess may skip non-clobbering writes.
  309. // Manually check read accesses between Start and End, if they are in the
  310. // same block, for clobbers. Otherwise assume Loc is clobbered.
  311. return Start->getBlock() != End->getBlock() ||
  312. any_of(
  313. make_range(std::next(Start->getIterator()), End->getIterator()),
  314. [&AA, Loc](const MemoryAccess &Acc) {
  315. if (isa<MemoryUse>(&Acc))
  316. return false;
  317. Instruction *AccInst =
  318. cast<MemoryUseOrDef>(&Acc)->getMemoryInst();
  319. return isModSet(AA.getModRefInfo(AccInst, Loc));
  320. });
  321. }
  322. // TODO: Only walk until we hit Start.
  323. MemoryAccess *Clobber = MSSA->getWalker()->getClobberingMemoryAccess(
  324. End->getDefiningAccess(), Loc, AA);
  325. return !MSSA->dominates(Clobber, Start);
  326. }
  327. /// When scanning forward over instructions, we look for some other patterns to
  328. /// fold away. In particular, this looks for stores to neighboring locations of
  329. /// memory. If it sees enough consecutive ones, it attempts to merge them
  330. /// together into a memcpy/memset.
  331. Instruction *MemCpyOptPass::tryMergingIntoMemset(Instruction *StartInst,
  332. Value *StartPtr,
  333. Value *ByteVal) {
  334. const DataLayout &DL = StartInst->getModule()->getDataLayout();
  335. // We can't track scalable types
  336. if (auto *SI = dyn_cast<StoreInst>(StartInst))
  337. if (DL.getTypeStoreSize(SI->getOperand(0)->getType()).isScalable())
  338. return nullptr;
  339. // Okay, so we now have a single store that can be splatable. Scan to find
  340. // all subsequent stores of the same value to offset from the same pointer.
  341. // Join these together into ranges, so we can decide whether contiguous blocks
  342. // are stored.
  343. MemsetRanges Ranges(DL);
  344. BasicBlock::iterator BI(StartInst);
  345. // Keeps track of the last memory use or def before the insertion point for
  346. // the new memset. The new MemoryDef for the inserted memsets will be inserted
  347. // after MemInsertPoint. It points to either LastMemDef or to the last user
  348. // before the insertion point of the memset, if there are any such users.
  349. MemoryUseOrDef *MemInsertPoint = nullptr;
  350. // Keeps track of the last MemoryDef between StartInst and the insertion point
  351. // for the new memset. This will become the defining access of the inserted
  352. // memsets.
  353. MemoryDef *LastMemDef = nullptr;
  354. for (++BI; !BI->isTerminator(); ++BI) {
  355. auto *CurrentAcc = cast_or_null<MemoryUseOrDef>(
  356. MSSAU->getMemorySSA()->getMemoryAccess(&*BI));
  357. if (CurrentAcc) {
  358. MemInsertPoint = CurrentAcc;
  359. if (auto *CurrentDef = dyn_cast<MemoryDef>(CurrentAcc))
  360. LastMemDef = CurrentDef;
  361. }
  362. // Calls that only access inaccessible memory do not block merging
  363. // accessible stores.
  364. if (auto *CB = dyn_cast<CallBase>(BI)) {
  365. if (CB->onlyAccessesInaccessibleMemory())
  366. continue;
  367. }
  368. if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
  369. // If the instruction is readnone, ignore it, otherwise bail out. We
  370. // don't even allow readonly here because we don't want something like:
  371. // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
  372. if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
  373. break;
  374. continue;
  375. }
  376. if (auto *NextStore = dyn_cast<StoreInst>(BI)) {
  377. // If this is a store, see if we can merge it in.
  378. if (!NextStore->isSimple()) break;
  379. Value *StoredVal = NextStore->getValueOperand();
  380. // Don't convert stores of non-integral pointer types to memsets (which
  381. // stores integers).
  382. if (DL.isNonIntegralPointerType(StoredVal->getType()->getScalarType()))
  383. break;
  384. // We can't track ranges involving scalable types.
  385. if (DL.getTypeStoreSize(StoredVal->getType()).isScalable())
  386. break;
  387. // Check to see if this stored value is of the same byte-splattable value.
  388. Value *StoredByte = isBytewiseValue(StoredVal, DL);
  389. if (isa<UndefValue>(ByteVal) && StoredByte)
  390. ByteVal = StoredByte;
  391. if (ByteVal != StoredByte)
  392. break;
  393. // Check to see if this store is to a constant offset from the start ptr.
  394. std::optional<int64_t> Offset =
  395. isPointerOffset(StartPtr, NextStore->getPointerOperand(), DL);
  396. if (!Offset)
  397. break;
  398. Ranges.addStore(*Offset, NextStore);
  399. } else {
  400. auto *MSI = cast<MemSetInst>(BI);
  401. if (MSI->isVolatile() || ByteVal != MSI->getValue() ||
  402. !isa<ConstantInt>(MSI->getLength()))
  403. break;
  404. // Check to see if this store is to a constant offset from the start ptr.
  405. std::optional<int64_t> Offset =
  406. isPointerOffset(StartPtr, MSI->getDest(), DL);
  407. if (!Offset)
  408. break;
  409. Ranges.addMemSet(*Offset, MSI);
  410. }
  411. }
  412. // If we have no ranges, then we just had a single store with nothing that
  413. // could be merged in. This is a very common case of course.
  414. if (Ranges.empty())
  415. return nullptr;
  416. // If we had at least one store that could be merged in, add the starting
  417. // store as well. We try to avoid this unless there is at least something
  418. // interesting as a small compile-time optimization.
  419. Ranges.addInst(0, StartInst);
  420. // If we create any memsets, we put it right before the first instruction that
  421. // isn't part of the memset block. This ensure that the memset is dominated
  422. // by any addressing instruction needed by the start of the block.
  423. IRBuilder<> Builder(&*BI);
  424. // Now that we have full information about ranges, loop over the ranges and
  425. // emit memset's for anything big enough to be worthwhile.
  426. Instruction *AMemSet = nullptr;
  427. for (const MemsetRange &Range : Ranges) {
  428. if (Range.TheStores.size() == 1) continue;
  429. // If it is profitable to lower this range to memset, do so now.
  430. if (!Range.isProfitableToUseMemset(DL))
  431. continue;
  432. // Otherwise, we do want to transform this! Create a new memset.
  433. // Get the starting pointer of the block.
  434. StartPtr = Range.StartPtr;
  435. AMemSet = Builder.CreateMemSet(StartPtr, ByteVal, Range.End - Range.Start,
  436. Range.Alignment);
  437. AMemSet->mergeDIAssignID(Range.TheStores);
  438. LLVM_DEBUG(dbgs() << "Replace stores:\n"; for (Instruction *SI
  439. : Range.TheStores) dbgs()
  440. << *SI << '\n';
  441. dbgs() << "With: " << *AMemSet << '\n');
  442. if (!Range.TheStores.empty())
  443. AMemSet->setDebugLoc(Range.TheStores[0]->getDebugLoc());
  444. assert(LastMemDef && MemInsertPoint &&
  445. "Both LastMemDef and MemInsertPoint need to be set");
  446. auto *NewDef =
  447. cast<MemoryDef>(MemInsertPoint->getMemoryInst() == &*BI
  448. ? MSSAU->createMemoryAccessBefore(
  449. AMemSet, LastMemDef, MemInsertPoint)
  450. : MSSAU->createMemoryAccessAfter(
  451. AMemSet, LastMemDef, MemInsertPoint));
  452. MSSAU->insertDef(NewDef, /*RenameUses=*/true);
  453. LastMemDef = NewDef;
  454. MemInsertPoint = NewDef;
  455. // Zap all the stores.
  456. for (Instruction *SI : Range.TheStores)
  457. eraseInstruction(SI);
  458. ++NumMemSetInfer;
  459. }
  460. return AMemSet;
  461. }
  462. // This method try to lift a store instruction before position P.
  463. // It will lift the store and its argument + that anything that
  464. // may alias with these.
  465. // The method returns true if it was successful.
  466. bool MemCpyOptPass::moveUp(StoreInst *SI, Instruction *P, const LoadInst *LI) {
  467. // If the store alias this position, early bail out.
  468. MemoryLocation StoreLoc = MemoryLocation::get(SI);
  469. if (isModOrRefSet(AA->getModRefInfo(P, StoreLoc)))
  470. return false;
  471. // Keep track of the arguments of all instruction we plan to lift
  472. // so we can make sure to lift them as well if appropriate.
  473. DenseSet<Instruction*> Args;
  474. auto AddArg = [&](Value *Arg) {
  475. auto *I = dyn_cast<Instruction>(Arg);
  476. if (I && I->getParent() == SI->getParent()) {
  477. // Cannot hoist user of P above P
  478. if (I == P) return false;
  479. Args.insert(I);
  480. }
  481. return true;
  482. };
  483. if (!AddArg(SI->getPointerOperand()))
  484. return false;
  485. // Instruction to lift before P.
  486. SmallVector<Instruction *, 8> ToLift{SI};
  487. // Memory locations of lifted instructions.
  488. SmallVector<MemoryLocation, 8> MemLocs{StoreLoc};
  489. // Lifted calls.
  490. SmallVector<const CallBase *, 8> Calls;
  491. const MemoryLocation LoadLoc = MemoryLocation::get(LI);
  492. for (auto I = --SI->getIterator(), E = P->getIterator(); I != E; --I) {
  493. auto *C = &*I;
  494. // Make sure hoisting does not perform a store that was not guaranteed to
  495. // happen.
  496. if (!isGuaranteedToTransferExecutionToSuccessor(C))
  497. return false;
  498. bool MayAlias = isModOrRefSet(AA->getModRefInfo(C, std::nullopt));
  499. bool NeedLift = false;
  500. if (Args.erase(C))
  501. NeedLift = true;
  502. else if (MayAlias) {
  503. NeedLift = llvm::any_of(MemLocs, [C, this](const MemoryLocation &ML) {
  504. return isModOrRefSet(AA->getModRefInfo(C, ML));
  505. });
  506. if (!NeedLift)
  507. NeedLift = llvm::any_of(Calls, [C, this](const CallBase *Call) {
  508. return isModOrRefSet(AA->getModRefInfo(C, Call));
  509. });
  510. }
  511. if (!NeedLift)
  512. continue;
  513. if (MayAlias) {
  514. // Since LI is implicitly moved downwards past the lifted instructions,
  515. // none of them may modify its source.
  516. if (isModSet(AA->getModRefInfo(C, LoadLoc)))
  517. return false;
  518. else if (const auto *Call = dyn_cast<CallBase>(C)) {
  519. // If we can't lift this before P, it's game over.
  520. if (isModOrRefSet(AA->getModRefInfo(P, Call)))
  521. return false;
  522. Calls.push_back(Call);
  523. } else if (isa<LoadInst>(C) || isa<StoreInst>(C) || isa<VAArgInst>(C)) {
  524. // If we can't lift this before P, it's game over.
  525. auto ML = MemoryLocation::get(C);
  526. if (isModOrRefSet(AA->getModRefInfo(P, ML)))
  527. return false;
  528. MemLocs.push_back(ML);
  529. } else
  530. // We don't know how to lift this instruction.
  531. return false;
  532. }
  533. ToLift.push_back(C);
  534. for (Value *Op : C->operands())
  535. if (!AddArg(Op))
  536. return false;
  537. }
  538. // Find MSSA insertion point. Normally P will always have a corresponding
  539. // memory access before which we can insert. However, with non-standard AA
  540. // pipelines, there may be a mismatch between AA and MSSA, in which case we
  541. // will scan for a memory access before P. In either case, we know for sure
  542. // that at least the load will have a memory access.
  543. // TODO: Simplify this once P will be determined by MSSA, in which case the
  544. // discrepancy can no longer occur.
  545. MemoryUseOrDef *MemInsertPoint = nullptr;
  546. if (MemoryUseOrDef *MA = MSSAU->getMemorySSA()->getMemoryAccess(P)) {
  547. MemInsertPoint = cast<MemoryUseOrDef>(--MA->getIterator());
  548. } else {
  549. const Instruction *ConstP = P;
  550. for (const Instruction &I : make_range(++ConstP->getReverseIterator(),
  551. ++LI->getReverseIterator())) {
  552. if (MemoryUseOrDef *MA = MSSAU->getMemorySSA()->getMemoryAccess(&I)) {
  553. MemInsertPoint = MA;
  554. break;
  555. }
  556. }
  557. }
  558. // We made it, we need to lift.
  559. for (auto *I : llvm::reverse(ToLift)) {
  560. LLVM_DEBUG(dbgs() << "Lifting " << *I << " before " << *P << "\n");
  561. I->moveBefore(P);
  562. assert(MemInsertPoint && "Must have found insert point");
  563. if (MemoryUseOrDef *MA = MSSAU->getMemorySSA()->getMemoryAccess(I)) {
  564. MSSAU->moveAfter(MA, MemInsertPoint);
  565. MemInsertPoint = MA;
  566. }
  567. }
  568. return true;
  569. }
  570. bool MemCpyOptPass::processStoreOfLoad(StoreInst *SI, LoadInst *LI,
  571. const DataLayout &DL,
  572. BasicBlock::iterator &BBI) {
  573. if (!LI->isSimple() || !LI->hasOneUse() ||
  574. LI->getParent() != SI->getParent())
  575. return false;
  576. auto *T = LI->getType();
  577. // Don't introduce calls to memcpy/memmove intrinsics out of thin air if
  578. // the corresponding libcalls are not available.
  579. // TODO: We should really distinguish between libcall availability and
  580. // our ability to introduce intrinsics.
  581. if (T->isAggregateType() &&
  582. (EnableMemCpyOptWithoutLibcalls ||
  583. (TLI->has(LibFunc_memcpy) && TLI->has(LibFunc_memmove)))) {
  584. MemoryLocation LoadLoc = MemoryLocation::get(LI);
  585. // We use alias analysis to check if an instruction may store to
  586. // the memory we load from in between the load and the store. If
  587. // such an instruction is found, we try to promote there instead
  588. // of at the store position.
  589. // TODO: Can use MSSA for this.
  590. Instruction *P = SI;
  591. for (auto &I : make_range(++LI->getIterator(), SI->getIterator())) {
  592. if (isModSet(AA->getModRefInfo(&I, LoadLoc))) {
  593. P = &I;
  594. break;
  595. }
  596. }
  597. // We found an instruction that may write to the loaded memory.
  598. // We can try to promote at this position instead of the store
  599. // position if nothing aliases the store memory after this and the store
  600. // destination is not in the range.
  601. if (P && P != SI) {
  602. if (!moveUp(SI, P, LI))
  603. P = nullptr;
  604. }
  605. // If a valid insertion position is found, then we can promote
  606. // the load/store pair to a memcpy.
  607. if (P) {
  608. // If we load from memory that may alias the memory we store to,
  609. // memmove must be used to preserve semantic. If not, memcpy can
  610. // be used. Also, if we load from constant memory, memcpy can be used
  611. // as the constant memory won't be modified.
  612. bool UseMemMove = false;
  613. if (isModSet(AA->getModRefInfo(SI, LoadLoc)))
  614. UseMemMove = true;
  615. uint64_t Size = DL.getTypeStoreSize(T);
  616. IRBuilder<> Builder(P);
  617. Instruction *M;
  618. if (UseMemMove)
  619. M = Builder.CreateMemMove(
  620. SI->getPointerOperand(), SI->getAlign(),
  621. LI->getPointerOperand(), LI->getAlign(), Size);
  622. else
  623. M = Builder.CreateMemCpy(
  624. SI->getPointerOperand(), SI->getAlign(),
  625. LI->getPointerOperand(), LI->getAlign(), Size);
  626. M->copyMetadata(*SI, LLVMContext::MD_DIAssignID);
  627. LLVM_DEBUG(dbgs() << "Promoting " << *LI << " to " << *SI << " => "
  628. << *M << "\n");
  629. auto *LastDef =
  630. cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(SI));
  631. auto *NewAccess = MSSAU->createMemoryAccessAfter(M, LastDef, LastDef);
  632. MSSAU->insertDef(cast<MemoryDef>(NewAccess), /*RenameUses=*/true);
  633. eraseInstruction(SI);
  634. eraseInstruction(LI);
  635. ++NumMemCpyInstr;
  636. // Make sure we do not invalidate the iterator.
  637. BBI = M->getIterator();
  638. return true;
  639. }
  640. }
  641. // Detect cases where we're performing call slot forwarding, but
  642. // happen to be using a load-store pair to implement it, rather than
  643. // a memcpy.
  644. BatchAAResults BAA(*AA);
  645. auto GetCall = [&]() -> CallInst * {
  646. // We defer this expensive clobber walk until the cheap checks
  647. // have been done on the source inside performCallSlotOptzn.
  648. if (auto *LoadClobber = dyn_cast<MemoryUseOrDef>(
  649. MSSA->getWalker()->getClobberingMemoryAccess(LI, BAA)))
  650. return dyn_cast_or_null<CallInst>(LoadClobber->getMemoryInst());
  651. return nullptr;
  652. };
  653. bool Changed = performCallSlotOptzn(
  654. LI, SI, SI->getPointerOperand()->stripPointerCasts(),
  655. LI->getPointerOperand()->stripPointerCasts(),
  656. DL.getTypeStoreSize(SI->getOperand(0)->getType()),
  657. std::min(SI->getAlign(), LI->getAlign()), BAA, GetCall);
  658. if (Changed) {
  659. eraseInstruction(SI);
  660. eraseInstruction(LI);
  661. ++NumMemCpyInstr;
  662. return true;
  663. }
  664. return false;
  665. }
  666. bool MemCpyOptPass::processStore(StoreInst *SI, BasicBlock::iterator &BBI) {
  667. if (!SI->isSimple()) return false;
  668. // Avoid merging nontemporal stores since the resulting
  669. // memcpy/memset would not be able to preserve the nontemporal hint.
  670. // In theory we could teach how to propagate the !nontemporal metadata to
  671. // memset calls. However, that change would force the backend to
  672. // conservatively expand !nontemporal memset calls back to sequences of
  673. // store instructions (effectively undoing the merging).
  674. if (SI->getMetadata(LLVMContext::MD_nontemporal))
  675. return false;
  676. const DataLayout &DL = SI->getModule()->getDataLayout();
  677. Value *StoredVal = SI->getValueOperand();
  678. // Not all the transforms below are correct for non-integral pointers, bail
  679. // until we've audited the individual pieces.
  680. if (DL.isNonIntegralPointerType(StoredVal->getType()->getScalarType()))
  681. return false;
  682. // Load to store forwarding can be interpreted as memcpy.
  683. if (auto *LI = dyn_cast<LoadInst>(StoredVal))
  684. return processStoreOfLoad(SI, LI, DL, BBI);
  685. // The following code creates memset intrinsics out of thin air. Don't do
  686. // this if the corresponding libfunc is not available.
  687. // TODO: We should really distinguish between libcall availability and
  688. // our ability to introduce intrinsics.
  689. if (!(TLI->has(LibFunc_memset) || EnableMemCpyOptWithoutLibcalls))
  690. return false;
  691. // There are two cases that are interesting for this code to handle: memcpy
  692. // and memset. Right now we only handle memset.
  693. // Ensure that the value being stored is something that can be memset'able a
  694. // byte at a time like "0" or "-1" or any width, as well as things like
  695. // 0xA0A0A0A0 and 0.0.
  696. auto *V = SI->getOperand(0);
  697. if (Value *ByteVal = isBytewiseValue(V, DL)) {
  698. if (Instruction *I = tryMergingIntoMemset(SI, SI->getPointerOperand(),
  699. ByteVal)) {
  700. BBI = I->getIterator(); // Don't invalidate iterator.
  701. return true;
  702. }
  703. // If we have an aggregate, we try to promote it to memset regardless
  704. // of opportunity for merging as it can expose optimization opportunities
  705. // in subsequent passes.
  706. auto *T = V->getType();
  707. if (T->isAggregateType()) {
  708. uint64_t Size = DL.getTypeStoreSize(T);
  709. IRBuilder<> Builder(SI);
  710. auto *M = Builder.CreateMemSet(SI->getPointerOperand(), ByteVal, Size,
  711. SI->getAlign());
  712. M->copyMetadata(*SI, LLVMContext::MD_DIAssignID);
  713. LLVM_DEBUG(dbgs() << "Promoting " << *SI << " to " << *M << "\n");
  714. // The newly inserted memset is immediately overwritten by the original
  715. // store, so we do not need to rename uses.
  716. auto *StoreDef = cast<MemoryDef>(MSSA->getMemoryAccess(SI));
  717. auto *NewAccess = MSSAU->createMemoryAccessBefore(
  718. M, StoreDef->getDefiningAccess(), StoreDef);
  719. MSSAU->insertDef(cast<MemoryDef>(NewAccess), /*RenameUses=*/false);
  720. eraseInstruction(SI);
  721. NumMemSetInfer++;
  722. // Make sure we do not invalidate the iterator.
  723. BBI = M->getIterator();
  724. return true;
  725. }
  726. }
  727. return false;
  728. }
  729. bool MemCpyOptPass::processMemSet(MemSetInst *MSI, BasicBlock::iterator &BBI) {
  730. // See if there is another memset or store neighboring this memset which
  731. // allows us to widen out the memset to do a single larger store.
  732. if (isa<ConstantInt>(MSI->getLength()) && !MSI->isVolatile())
  733. if (Instruction *I = tryMergingIntoMemset(MSI, MSI->getDest(),
  734. MSI->getValue())) {
  735. BBI = I->getIterator(); // Don't invalidate iterator.
  736. return true;
  737. }
  738. return false;
  739. }
  740. /// Takes a memcpy and a call that it depends on,
  741. /// and checks for the possibility of a call slot optimization by having
  742. /// the call write its result directly into the destination of the memcpy.
  743. bool MemCpyOptPass::performCallSlotOptzn(Instruction *cpyLoad,
  744. Instruction *cpyStore, Value *cpyDest,
  745. Value *cpySrc, TypeSize cpySize,
  746. Align cpyDestAlign, BatchAAResults &BAA,
  747. std::function<CallInst *()> GetC) {
  748. // The general transformation to keep in mind is
  749. //
  750. // call @func(..., src, ...)
  751. // memcpy(dest, src, ...)
  752. //
  753. // ->
  754. //
  755. // memcpy(dest, src, ...)
  756. // call @func(..., dest, ...)
  757. //
  758. // Since moving the memcpy is technically awkward, we additionally check that
  759. // src only holds uninitialized values at the moment of the call, meaning that
  760. // the memcpy can be discarded rather than moved.
  761. // We can't optimize scalable types.
  762. if (cpySize.isScalable())
  763. return false;
  764. // Require that src be an alloca. This simplifies the reasoning considerably.
  765. auto *srcAlloca = dyn_cast<AllocaInst>(cpySrc);
  766. if (!srcAlloca)
  767. return false;
  768. ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
  769. if (!srcArraySize)
  770. return false;
  771. const DataLayout &DL = cpyLoad->getModule()->getDataLayout();
  772. uint64_t srcSize = DL.getTypeAllocSize(srcAlloca->getAllocatedType()) *
  773. srcArraySize->getZExtValue();
  774. if (cpySize < srcSize)
  775. return false;
  776. CallInst *C = GetC();
  777. if (!C)
  778. return false;
  779. // Lifetime marks shouldn't be operated on.
  780. if (Function *F = C->getCalledFunction())
  781. if (F->isIntrinsic() && F->getIntrinsicID() == Intrinsic::lifetime_start)
  782. return false;
  783. if (C->getParent() != cpyStore->getParent()) {
  784. LLVM_DEBUG(dbgs() << "Call Slot: block local restriction\n");
  785. return false;
  786. }
  787. MemoryLocation DestLoc = isa<StoreInst>(cpyStore) ?
  788. MemoryLocation::get(cpyStore) :
  789. MemoryLocation::getForDest(cast<MemCpyInst>(cpyStore));
  790. // Check that nothing touches the dest of the copy between
  791. // the call and the store/memcpy.
  792. Instruction *SkippedLifetimeStart = nullptr;
  793. if (accessedBetween(BAA, DestLoc, MSSA->getMemoryAccess(C),
  794. MSSA->getMemoryAccess(cpyStore), &SkippedLifetimeStart)) {
  795. LLVM_DEBUG(dbgs() << "Call Slot: Dest pointer modified after call\n");
  796. return false;
  797. }
  798. // If we need to move a lifetime.start above the call, make sure that we can
  799. // actually do so. If the argument is bitcasted for example, we would have to
  800. // move the bitcast as well, which we don't handle.
  801. if (SkippedLifetimeStart) {
  802. auto *LifetimeArg =
  803. dyn_cast<Instruction>(SkippedLifetimeStart->getOperand(1));
  804. if (LifetimeArg && LifetimeArg->getParent() == C->getParent() &&
  805. C->comesBefore(LifetimeArg))
  806. return false;
  807. }
  808. // Check that accessing the first srcSize bytes of dest will not cause a
  809. // trap. Otherwise the transform is invalid since it might cause a trap
  810. // to occur earlier than it otherwise would.
  811. if (!isDereferenceableAndAlignedPointer(cpyDest, Align(1), APInt(64, cpySize),
  812. DL, C, AC, DT)) {
  813. LLVM_DEBUG(dbgs() << "Call Slot: Dest pointer not dereferenceable\n");
  814. return false;
  815. }
  816. // Make sure that nothing can observe cpyDest being written early. There are
  817. // a number of cases to consider:
  818. // 1. cpyDest cannot be accessed between C and cpyStore as a precondition of
  819. // the transform.
  820. // 2. C itself may not access cpyDest (prior to the transform). This is
  821. // checked further below.
  822. // 3. If cpyDest is accessible to the caller of this function (potentially
  823. // captured and not based on an alloca), we need to ensure that we cannot
  824. // unwind between C and cpyStore. This is checked here.
  825. // 4. If cpyDest is potentially captured, there may be accesses to it from
  826. // another thread. In this case, we need to check that cpyStore is
  827. // guaranteed to be executed if C is. As it is a non-atomic access, it
  828. // renders accesses from other threads undefined.
  829. // TODO: This is currently not checked.
  830. if (mayBeVisibleThroughUnwinding(cpyDest, C, cpyStore)) {
  831. LLVM_DEBUG(dbgs() << "Call Slot: Dest may be visible through unwinding\n");
  832. return false;
  833. }
  834. // Check that dest points to memory that is at least as aligned as src.
  835. Align srcAlign = srcAlloca->getAlign();
  836. bool isDestSufficientlyAligned = srcAlign <= cpyDestAlign;
  837. // If dest is not aligned enough and we can't increase its alignment then
  838. // bail out.
  839. if (!isDestSufficientlyAligned && !isa<AllocaInst>(cpyDest)) {
  840. LLVM_DEBUG(dbgs() << "Call Slot: Dest not sufficiently aligned\n");
  841. return false;
  842. }
  843. // Check that src is not accessed except via the call and the memcpy. This
  844. // guarantees that it holds only undefined values when passed in (so the final
  845. // memcpy can be dropped), that it is not read or written between the call and
  846. // the memcpy, and that writing beyond the end of it is undefined.
  847. SmallVector<User *, 8> srcUseList(srcAlloca->users());
  848. while (!srcUseList.empty()) {
  849. User *U = srcUseList.pop_back_val();
  850. if (isa<BitCastInst>(U) || isa<AddrSpaceCastInst>(U)) {
  851. append_range(srcUseList, U->users());
  852. continue;
  853. }
  854. if (const auto *G = dyn_cast<GetElementPtrInst>(U)) {
  855. if (!G->hasAllZeroIndices())
  856. return false;
  857. append_range(srcUseList, U->users());
  858. continue;
  859. }
  860. if (const auto *IT = dyn_cast<IntrinsicInst>(U))
  861. if (IT->isLifetimeStartOrEnd())
  862. continue;
  863. if (U != C && U != cpyLoad)
  864. return false;
  865. }
  866. // Check whether src is captured by the called function, in which case there
  867. // may be further indirect uses of src.
  868. bool SrcIsCaptured = any_of(C->args(), [&](Use &U) {
  869. return U->stripPointerCasts() == cpySrc &&
  870. !C->doesNotCapture(C->getArgOperandNo(&U));
  871. });
  872. // If src is captured, then check whether there are any potential uses of
  873. // src through the captured pointer before the lifetime of src ends, either
  874. // due to a lifetime.end or a return from the function.
  875. if (SrcIsCaptured) {
  876. // Check that dest is not captured before/at the call. We have already
  877. // checked that src is not captured before it. If either had been captured,
  878. // then the call might be comparing the argument against the captured dest
  879. // or src pointer.
  880. Value *DestObj = getUnderlyingObject(cpyDest);
  881. if (!isIdentifiedFunctionLocal(DestObj) ||
  882. PointerMayBeCapturedBefore(DestObj, /* ReturnCaptures */ true,
  883. /* StoreCaptures */ true, C, DT,
  884. /* IncludeI */ true))
  885. return false;
  886. MemoryLocation SrcLoc =
  887. MemoryLocation(srcAlloca, LocationSize::precise(srcSize));
  888. for (Instruction &I :
  889. make_range(++C->getIterator(), C->getParent()->end())) {
  890. // Lifetime of srcAlloca ends at lifetime.end.
  891. if (auto *II = dyn_cast<IntrinsicInst>(&I)) {
  892. if (II->getIntrinsicID() == Intrinsic::lifetime_end &&
  893. II->getArgOperand(1)->stripPointerCasts() == srcAlloca &&
  894. cast<ConstantInt>(II->getArgOperand(0))->uge(srcSize))
  895. break;
  896. }
  897. // Lifetime of srcAlloca ends at return.
  898. if (isa<ReturnInst>(&I))
  899. break;
  900. // Ignore the direct read of src in the load.
  901. if (&I == cpyLoad)
  902. continue;
  903. // Check whether this instruction may mod/ref src through the captured
  904. // pointer (we have already any direct mod/refs in the loop above).
  905. // Also bail if we hit a terminator, as we don't want to scan into other
  906. // blocks.
  907. if (isModOrRefSet(BAA.getModRefInfo(&I, SrcLoc)) || I.isTerminator())
  908. return false;
  909. }
  910. }
  911. // Since we're changing the parameter to the callsite, we need to make sure
  912. // that what would be the new parameter dominates the callsite.
  913. if (!DT->dominates(cpyDest, C)) {
  914. // Support moving a constant index GEP before the call.
  915. auto *GEP = dyn_cast<GetElementPtrInst>(cpyDest);
  916. if (GEP && GEP->hasAllConstantIndices() &&
  917. DT->dominates(GEP->getPointerOperand(), C))
  918. GEP->moveBefore(C);
  919. else
  920. return false;
  921. }
  922. // In addition to knowing that the call does not access src in some
  923. // unexpected manner, for example via a global, which we deduce from
  924. // the use analysis, we also need to know that it does not sneakily
  925. // access dest. We rely on AA to figure this out for us.
  926. MemoryLocation DestWithSrcSize(cpyDest, LocationSize::precise(srcSize));
  927. ModRefInfo MR = BAA.getModRefInfo(C, DestWithSrcSize);
  928. // If necessary, perform additional analysis.
  929. if (isModOrRefSet(MR))
  930. MR = BAA.callCapturesBefore(C, DestWithSrcSize, DT);
  931. if (isModOrRefSet(MR))
  932. return false;
  933. // We can't create address space casts here because we don't know if they're
  934. // safe for the target.
  935. if (cpySrc->getType()->getPointerAddressSpace() !=
  936. cpyDest->getType()->getPointerAddressSpace())
  937. return false;
  938. for (unsigned ArgI = 0; ArgI < C->arg_size(); ++ArgI)
  939. if (C->getArgOperand(ArgI)->stripPointerCasts() == cpySrc &&
  940. cpySrc->getType()->getPointerAddressSpace() !=
  941. C->getArgOperand(ArgI)->getType()->getPointerAddressSpace())
  942. return false;
  943. // All the checks have passed, so do the transformation.
  944. bool changedArgument = false;
  945. for (unsigned ArgI = 0; ArgI < C->arg_size(); ++ArgI)
  946. if (C->getArgOperand(ArgI)->stripPointerCasts() == cpySrc) {
  947. Value *Dest = cpySrc->getType() == cpyDest->getType() ? cpyDest
  948. : CastInst::CreatePointerCast(cpyDest, cpySrc->getType(),
  949. cpyDest->getName(), C);
  950. changedArgument = true;
  951. if (C->getArgOperand(ArgI)->getType() == Dest->getType())
  952. C->setArgOperand(ArgI, Dest);
  953. else
  954. C->setArgOperand(ArgI, CastInst::CreatePointerCast(
  955. Dest, C->getArgOperand(ArgI)->getType(),
  956. Dest->getName(), C));
  957. }
  958. if (!changedArgument)
  959. return false;
  960. // If the destination wasn't sufficiently aligned then increase its alignment.
  961. if (!isDestSufficientlyAligned) {
  962. assert(isa<AllocaInst>(cpyDest) && "Can only increase alloca alignment!");
  963. cast<AllocaInst>(cpyDest)->setAlignment(srcAlign);
  964. }
  965. if (SkippedLifetimeStart) {
  966. SkippedLifetimeStart->moveBefore(C);
  967. MSSAU->moveBefore(MSSA->getMemoryAccess(SkippedLifetimeStart),
  968. MSSA->getMemoryAccess(C));
  969. }
  970. // Update AA metadata
  971. // FIXME: MD_tbaa_struct and MD_mem_parallel_loop_access should also be
  972. // handled here, but combineMetadata doesn't support them yet
  973. unsigned KnownIDs[] = {LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
  974. LLVMContext::MD_noalias,
  975. LLVMContext::MD_invariant_group,
  976. LLVMContext::MD_access_group};
  977. combineMetadata(C, cpyLoad, KnownIDs, true);
  978. if (cpyLoad != cpyStore)
  979. combineMetadata(C, cpyStore, KnownIDs, true);
  980. ++NumCallSlot;
  981. return true;
  982. }
  983. /// We've found that the (upward scanning) memory dependence of memcpy 'M' is
  984. /// the memcpy 'MDep'. Try to simplify M to copy from MDep's input if we can.
  985. bool MemCpyOptPass::processMemCpyMemCpyDependence(MemCpyInst *M,
  986. MemCpyInst *MDep,
  987. BatchAAResults &BAA) {
  988. // We can only transforms memcpy's where the dest of one is the source of the
  989. // other.
  990. if (M->getSource() != MDep->getDest() || MDep->isVolatile())
  991. return false;
  992. // If dep instruction is reading from our current input, then it is a noop
  993. // transfer and substituting the input won't change this instruction. Just
  994. // ignore the input and let someone else zap MDep. This handles cases like:
  995. // memcpy(a <- a)
  996. // memcpy(b <- a)
  997. if (M->getSource() == MDep->getSource())
  998. return false;
  999. // Second, the length of the memcpy's must be the same, or the preceding one
  1000. // must be larger than the following one.
  1001. if (MDep->getLength() != M->getLength()) {
  1002. auto *MDepLen = dyn_cast<ConstantInt>(MDep->getLength());
  1003. auto *MLen = dyn_cast<ConstantInt>(M->getLength());
  1004. if (!MDepLen || !MLen || MDepLen->getZExtValue() < MLen->getZExtValue())
  1005. return false;
  1006. }
  1007. // Verify that the copied-from memory doesn't change in between the two
  1008. // transfers. For example, in:
  1009. // memcpy(a <- b)
  1010. // *b = 42;
  1011. // memcpy(c <- a)
  1012. // It would be invalid to transform the second memcpy into memcpy(c <- b).
  1013. //
  1014. // TODO: If the code between M and MDep is transparent to the destination "c",
  1015. // then we could still perform the xform by moving M up to the first memcpy.
  1016. // TODO: It would be sufficient to check the MDep source up to the memcpy
  1017. // size of M, rather than MDep.
  1018. if (writtenBetween(MSSA, BAA, MemoryLocation::getForSource(MDep),
  1019. MSSA->getMemoryAccess(MDep), MSSA->getMemoryAccess(M)))
  1020. return false;
  1021. // If the dest of the second might alias the source of the first, then the
  1022. // source and dest might overlap. In addition, if the source of the first
  1023. // points to constant memory, they won't overlap by definition. Otherwise, we
  1024. // still want to eliminate the intermediate value, but we have to generate a
  1025. // memmove instead of memcpy.
  1026. bool UseMemMove = false;
  1027. if (isModSet(BAA.getModRefInfo(M, MemoryLocation::getForSource(MDep))))
  1028. UseMemMove = true;
  1029. // If all checks passed, then we can transform M.
  1030. LLVM_DEBUG(dbgs() << "MemCpyOptPass: Forwarding memcpy->memcpy src:\n"
  1031. << *MDep << '\n' << *M << '\n');
  1032. // TODO: Is this worth it if we're creating a less aligned memcpy? For
  1033. // example we could be moving from movaps -> movq on x86.
  1034. IRBuilder<> Builder(M);
  1035. Instruction *NewM;
  1036. if (UseMemMove)
  1037. NewM = Builder.CreateMemMove(M->getRawDest(), M->getDestAlign(),
  1038. MDep->getRawSource(), MDep->getSourceAlign(),
  1039. M->getLength(), M->isVolatile());
  1040. else if (isa<MemCpyInlineInst>(M)) {
  1041. // llvm.memcpy may be promoted to llvm.memcpy.inline, but the converse is
  1042. // never allowed since that would allow the latter to be lowered as a call
  1043. // to an external function.
  1044. NewM = Builder.CreateMemCpyInline(
  1045. M->getRawDest(), M->getDestAlign(), MDep->getRawSource(),
  1046. MDep->getSourceAlign(), M->getLength(), M->isVolatile());
  1047. } else
  1048. NewM = Builder.CreateMemCpy(M->getRawDest(), M->getDestAlign(),
  1049. MDep->getRawSource(), MDep->getSourceAlign(),
  1050. M->getLength(), M->isVolatile());
  1051. NewM->copyMetadata(*M, LLVMContext::MD_DIAssignID);
  1052. assert(isa<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(M)));
  1053. auto *LastDef = cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(M));
  1054. auto *NewAccess = MSSAU->createMemoryAccessAfter(NewM, LastDef, LastDef);
  1055. MSSAU->insertDef(cast<MemoryDef>(NewAccess), /*RenameUses=*/true);
  1056. // Remove the instruction we're replacing.
  1057. eraseInstruction(M);
  1058. ++NumMemCpyInstr;
  1059. return true;
  1060. }
  1061. /// We've found that the (upward scanning) memory dependence of \p MemCpy is
  1062. /// \p MemSet. Try to simplify \p MemSet to only set the trailing bytes that
  1063. /// weren't copied over by \p MemCpy.
  1064. ///
  1065. /// In other words, transform:
  1066. /// \code
  1067. /// memset(dst, c, dst_size);
  1068. /// memcpy(dst, src, src_size);
  1069. /// \endcode
  1070. /// into:
  1071. /// \code
  1072. /// memcpy(dst, src, src_size);
  1073. /// memset(dst + src_size, c, dst_size <= src_size ? 0 : dst_size - src_size);
  1074. /// \endcode
  1075. bool MemCpyOptPass::processMemSetMemCpyDependence(MemCpyInst *MemCpy,
  1076. MemSetInst *MemSet,
  1077. BatchAAResults &BAA) {
  1078. // We can only transform memset/memcpy with the same destination.
  1079. if (!BAA.isMustAlias(MemSet->getDest(), MemCpy->getDest()))
  1080. return false;
  1081. // Check that src and dst of the memcpy aren't the same. While memcpy
  1082. // operands cannot partially overlap, exact equality is allowed.
  1083. if (isModSet(BAA.getModRefInfo(MemCpy, MemoryLocation::getForSource(MemCpy))))
  1084. return false;
  1085. // We know that dst up to src_size is not written. We now need to make sure
  1086. // that dst up to dst_size is not accessed. (If we did not move the memset,
  1087. // checking for reads would be sufficient.)
  1088. if (accessedBetween(BAA, MemoryLocation::getForDest(MemSet),
  1089. MSSA->getMemoryAccess(MemSet),
  1090. MSSA->getMemoryAccess(MemCpy)))
  1091. return false;
  1092. // Use the same i8* dest as the memcpy, killing the memset dest if different.
  1093. Value *Dest = MemCpy->getRawDest();
  1094. Value *DestSize = MemSet->getLength();
  1095. Value *SrcSize = MemCpy->getLength();
  1096. if (mayBeVisibleThroughUnwinding(Dest, MemSet, MemCpy))
  1097. return false;
  1098. // If the sizes are the same, simply drop the memset instead of generating
  1099. // a replacement with zero size.
  1100. if (DestSize == SrcSize) {
  1101. eraseInstruction(MemSet);
  1102. return true;
  1103. }
  1104. // By default, create an unaligned memset.
  1105. Align Alignment = Align(1);
  1106. // If Dest is aligned, and SrcSize is constant, use the minimum alignment
  1107. // of the sum.
  1108. const Align DestAlign = std::max(MemSet->getDestAlign().valueOrOne(),
  1109. MemCpy->getDestAlign().valueOrOne());
  1110. if (DestAlign > 1)
  1111. if (auto *SrcSizeC = dyn_cast<ConstantInt>(SrcSize))
  1112. Alignment = commonAlignment(DestAlign, SrcSizeC->getZExtValue());
  1113. IRBuilder<> Builder(MemCpy);
  1114. // If the sizes have different types, zext the smaller one.
  1115. if (DestSize->getType() != SrcSize->getType()) {
  1116. if (DestSize->getType()->getIntegerBitWidth() >
  1117. SrcSize->getType()->getIntegerBitWidth())
  1118. SrcSize = Builder.CreateZExt(SrcSize, DestSize->getType());
  1119. else
  1120. DestSize = Builder.CreateZExt(DestSize, SrcSize->getType());
  1121. }
  1122. Value *Ule = Builder.CreateICmpULE(DestSize, SrcSize);
  1123. Value *SizeDiff = Builder.CreateSub(DestSize, SrcSize);
  1124. Value *MemsetLen = Builder.CreateSelect(
  1125. Ule, ConstantInt::getNullValue(DestSize->getType()), SizeDiff);
  1126. unsigned DestAS = Dest->getType()->getPointerAddressSpace();
  1127. Instruction *NewMemSet = Builder.CreateMemSet(
  1128. Builder.CreateGEP(
  1129. Builder.getInt8Ty(),
  1130. Builder.CreatePointerCast(Dest, Builder.getInt8PtrTy(DestAS)),
  1131. SrcSize),
  1132. MemSet->getOperand(1), MemsetLen, Alignment);
  1133. assert(isa<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(MemCpy)) &&
  1134. "MemCpy must be a MemoryDef");
  1135. // The new memset is inserted after the memcpy, but it is known that its
  1136. // defining access is the memset about to be removed which immediately
  1137. // precedes the memcpy.
  1138. auto *LastDef =
  1139. cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(MemCpy));
  1140. auto *NewAccess = MSSAU->createMemoryAccessBefore(
  1141. NewMemSet, LastDef->getDefiningAccess(), LastDef);
  1142. MSSAU->insertDef(cast<MemoryDef>(NewAccess), /*RenameUses=*/true);
  1143. eraseInstruction(MemSet);
  1144. return true;
  1145. }
  1146. /// Determine whether the instruction has undefined content for the given Size,
  1147. /// either because it was freshly alloca'd or started its lifetime.
  1148. static bool hasUndefContents(MemorySSA *MSSA, BatchAAResults &AA, Value *V,
  1149. MemoryDef *Def, Value *Size) {
  1150. if (MSSA->isLiveOnEntryDef(Def))
  1151. return isa<AllocaInst>(getUnderlyingObject(V));
  1152. if (auto *II = dyn_cast_or_null<IntrinsicInst>(Def->getMemoryInst())) {
  1153. if (II->getIntrinsicID() == Intrinsic::lifetime_start) {
  1154. auto *LTSize = cast<ConstantInt>(II->getArgOperand(0));
  1155. if (auto *CSize = dyn_cast<ConstantInt>(Size)) {
  1156. if (AA.isMustAlias(V, II->getArgOperand(1)) &&
  1157. LTSize->getZExtValue() >= CSize->getZExtValue())
  1158. return true;
  1159. }
  1160. // If the lifetime.start covers a whole alloca (as it almost always
  1161. // does) and we're querying a pointer based on that alloca, then we know
  1162. // the memory is definitely undef, regardless of how exactly we alias.
  1163. // The size also doesn't matter, as an out-of-bounds access would be UB.
  1164. if (auto *Alloca = dyn_cast<AllocaInst>(getUnderlyingObject(V))) {
  1165. if (getUnderlyingObject(II->getArgOperand(1)) == Alloca) {
  1166. const DataLayout &DL = Alloca->getModule()->getDataLayout();
  1167. if (std::optional<TypeSize> AllocaSize =
  1168. Alloca->getAllocationSize(DL))
  1169. if (*AllocaSize == LTSize->getValue())
  1170. return true;
  1171. }
  1172. }
  1173. }
  1174. }
  1175. return false;
  1176. }
  1177. /// Transform memcpy to memset when its source was just memset.
  1178. /// In other words, turn:
  1179. /// \code
  1180. /// memset(dst1, c, dst1_size);
  1181. /// memcpy(dst2, dst1, dst2_size);
  1182. /// \endcode
  1183. /// into:
  1184. /// \code
  1185. /// memset(dst1, c, dst1_size);
  1186. /// memset(dst2, c, dst2_size);
  1187. /// \endcode
  1188. /// When dst2_size <= dst1_size.
  1189. bool MemCpyOptPass::performMemCpyToMemSetOptzn(MemCpyInst *MemCpy,
  1190. MemSetInst *MemSet,
  1191. BatchAAResults &BAA) {
  1192. // Make sure that memcpy(..., memset(...), ...), that is we are memsetting and
  1193. // memcpying from the same address. Otherwise it is hard to reason about.
  1194. if (!BAA.isMustAlias(MemSet->getRawDest(), MemCpy->getRawSource()))
  1195. return false;
  1196. Value *MemSetSize = MemSet->getLength();
  1197. Value *CopySize = MemCpy->getLength();
  1198. if (MemSetSize != CopySize) {
  1199. // Make sure the memcpy doesn't read any more than what the memset wrote.
  1200. // Don't worry about sizes larger than i64.
  1201. // A known memset size is required.
  1202. auto *CMemSetSize = dyn_cast<ConstantInt>(MemSetSize);
  1203. if (!CMemSetSize)
  1204. return false;
  1205. // A known memcpy size is also required.
  1206. auto *CCopySize = dyn_cast<ConstantInt>(CopySize);
  1207. if (!CCopySize)
  1208. return false;
  1209. if (CCopySize->getZExtValue() > CMemSetSize->getZExtValue()) {
  1210. // If the memcpy is larger than the memset, but the memory was undef prior
  1211. // to the memset, we can just ignore the tail. Technically we're only
  1212. // interested in the bytes from MemSetSize..CopySize here, but as we can't
  1213. // easily represent this location, we use the full 0..CopySize range.
  1214. MemoryLocation MemCpyLoc = MemoryLocation::getForSource(MemCpy);
  1215. bool CanReduceSize = false;
  1216. MemoryUseOrDef *MemSetAccess = MSSA->getMemoryAccess(MemSet);
  1217. MemoryAccess *Clobber = MSSA->getWalker()->getClobberingMemoryAccess(
  1218. MemSetAccess->getDefiningAccess(), MemCpyLoc, BAA);
  1219. if (auto *MD = dyn_cast<MemoryDef>(Clobber))
  1220. if (hasUndefContents(MSSA, BAA, MemCpy->getSource(), MD, CopySize))
  1221. CanReduceSize = true;
  1222. if (!CanReduceSize)
  1223. return false;
  1224. CopySize = MemSetSize;
  1225. }
  1226. }
  1227. IRBuilder<> Builder(MemCpy);
  1228. Instruction *NewM =
  1229. Builder.CreateMemSet(MemCpy->getRawDest(), MemSet->getOperand(1),
  1230. CopySize, MemCpy->getDestAlign());
  1231. auto *LastDef =
  1232. cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(MemCpy));
  1233. auto *NewAccess = MSSAU->createMemoryAccessAfter(NewM, LastDef, LastDef);
  1234. MSSAU->insertDef(cast<MemoryDef>(NewAccess), /*RenameUses=*/true);
  1235. return true;
  1236. }
  1237. /// Perform simplification of memcpy's. If we have memcpy A
  1238. /// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite
  1239. /// B to be a memcpy from X to Z (or potentially a memmove, depending on
  1240. /// circumstances). This allows later passes to remove the first memcpy
  1241. /// altogether.
  1242. bool MemCpyOptPass::processMemCpy(MemCpyInst *M, BasicBlock::iterator &BBI) {
  1243. // We can only optimize non-volatile memcpy's.
  1244. if (M->isVolatile()) return false;
  1245. // If the source and destination of the memcpy are the same, then zap it.
  1246. if (M->getSource() == M->getDest()) {
  1247. ++BBI;
  1248. eraseInstruction(M);
  1249. return true;
  1250. }
  1251. // If copying from a constant, try to turn the memcpy into a memset.
  1252. if (auto *GV = dyn_cast<GlobalVariable>(M->getSource()))
  1253. if (GV->isConstant() && GV->hasDefinitiveInitializer())
  1254. if (Value *ByteVal = isBytewiseValue(GV->getInitializer(),
  1255. M->getModule()->getDataLayout())) {
  1256. IRBuilder<> Builder(M);
  1257. Instruction *NewM = Builder.CreateMemSet(
  1258. M->getRawDest(), ByteVal, M->getLength(), M->getDestAlign(), false);
  1259. auto *LastDef =
  1260. cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(M));
  1261. auto *NewAccess =
  1262. MSSAU->createMemoryAccessAfter(NewM, LastDef, LastDef);
  1263. MSSAU->insertDef(cast<MemoryDef>(NewAccess), /*RenameUses=*/true);
  1264. eraseInstruction(M);
  1265. ++NumCpyToSet;
  1266. return true;
  1267. }
  1268. BatchAAResults BAA(*AA);
  1269. MemoryUseOrDef *MA = MSSA->getMemoryAccess(M);
  1270. // FIXME: Not using getClobberingMemoryAccess() here due to PR54682.
  1271. MemoryAccess *AnyClobber = MA->getDefiningAccess();
  1272. MemoryLocation DestLoc = MemoryLocation::getForDest(M);
  1273. const MemoryAccess *DestClobber =
  1274. MSSA->getWalker()->getClobberingMemoryAccess(AnyClobber, DestLoc, BAA);
  1275. // Try to turn a partially redundant memset + memcpy into
  1276. // memcpy + smaller memset. We don't need the memcpy size for this.
  1277. // The memcpy most post-dom the memset, so limit this to the same basic
  1278. // block. A non-local generalization is likely not worthwhile.
  1279. if (auto *MD = dyn_cast<MemoryDef>(DestClobber))
  1280. if (auto *MDep = dyn_cast_or_null<MemSetInst>(MD->getMemoryInst()))
  1281. if (DestClobber->getBlock() == M->getParent())
  1282. if (processMemSetMemCpyDependence(M, MDep, BAA))
  1283. return true;
  1284. MemoryAccess *SrcClobber = MSSA->getWalker()->getClobberingMemoryAccess(
  1285. AnyClobber, MemoryLocation::getForSource(M), BAA);
  1286. // There are four possible optimizations we can do for memcpy:
  1287. // a) memcpy-memcpy xform which exposes redundance for DSE.
  1288. // b) call-memcpy xform for return slot optimization.
  1289. // c) memcpy from freshly alloca'd space or space that has just started
  1290. // its lifetime copies undefined data, and we can therefore eliminate
  1291. // the memcpy in favor of the data that was already at the destination.
  1292. // d) memcpy from a just-memset'd source can be turned into memset.
  1293. if (auto *MD = dyn_cast<MemoryDef>(SrcClobber)) {
  1294. if (Instruction *MI = MD->getMemoryInst()) {
  1295. if (auto *CopySize = dyn_cast<ConstantInt>(M->getLength())) {
  1296. if (auto *C = dyn_cast<CallInst>(MI)) {
  1297. if (performCallSlotOptzn(M, M, M->getDest(), M->getSource(),
  1298. TypeSize::getFixed(CopySize->getZExtValue()),
  1299. M->getDestAlign().valueOrOne(), BAA,
  1300. [C]() -> CallInst * { return C; })) {
  1301. LLVM_DEBUG(dbgs() << "Performed call slot optimization:\n"
  1302. << " call: " << *C << "\n"
  1303. << " memcpy: " << *M << "\n");
  1304. eraseInstruction(M);
  1305. ++NumMemCpyInstr;
  1306. return true;
  1307. }
  1308. }
  1309. }
  1310. if (auto *MDep = dyn_cast<MemCpyInst>(MI))
  1311. return processMemCpyMemCpyDependence(M, MDep, BAA);
  1312. if (auto *MDep = dyn_cast<MemSetInst>(MI)) {
  1313. if (performMemCpyToMemSetOptzn(M, MDep, BAA)) {
  1314. LLVM_DEBUG(dbgs() << "Converted memcpy to memset\n");
  1315. eraseInstruction(M);
  1316. ++NumCpyToSet;
  1317. return true;
  1318. }
  1319. }
  1320. }
  1321. if (hasUndefContents(MSSA, BAA, M->getSource(), MD, M->getLength())) {
  1322. LLVM_DEBUG(dbgs() << "Removed memcpy from undef\n");
  1323. eraseInstruction(M);
  1324. ++NumMemCpyInstr;
  1325. return true;
  1326. }
  1327. }
  1328. return false;
  1329. }
  1330. /// Transforms memmove calls to memcpy calls when the src/dst are guaranteed
  1331. /// not to alias.
  1332. bool MemCpyOptPass::processMemMove(MemMoveInst *M) {
  1333. // See if the source could be modified by this memmove potentially.
  1334. if (isModSet(AA->getModRefInfo(M, MemoryLocation::getForSource(M))))
  1335. return false;
  1336. LLVM_DEBUG(dbgs() << "MemCpyOptPass: Optimizing memmove -> memcpy: " << *M
  1337. << "\n");
  1338. // If not, then we know we can transform this.
  1339. Type *ArgTys[3] = { M->getRawDest()->getType(),
  1340. M->getRawSource()->getType(),
  1341. M->getLength()->getType() };
  1342. M->setCalledFunction(Intrinsic::getDeclaration(M->getModule(),
  1343. Intrinsic::memcpy, ArgTys));
  1344. // For MemorySSA nothing really changes (except that memcpy may imply stricter
  1345. // aliasing guarantees).
  1346. ++NumMoveToCpy;
  1347. return true;
  1348. }
  1349. /// This is called on every byval argument in call sites.
  1350. bool MemCpyOptPass::processByValArgument(CallBase &CB, unsigned ArgNo) {
  1351. const DataLayout &DL = CB.getCaller()->getParent()->getDataLayout();
  1352. // Find out what feeds this byval argument.
  1353. Value *ByValArg = CB.getArgOperand(ArgNo);
  1354. Type *ByValTy = CB.getParamByValType(ArgNo);
  1355. TypeSize ByValSize = DL.getTypeAllocSize(ByValTy);
  1356. MemoryLocation Loc(ByValArg, LocationSize::precise(ByValSize));
  1357. MemoryUseOrDef *CallAccess = MSSA->getMemoryAccess(&CB);
  1358. if (!CallAccess)
  1359. return false;
  1360. MemCpyInst *MDep = nullptr;
  1361. BatchAAResults BAA(*AA);
  1362. MemoryAccess *Clobber = MSSA->getWalker()->getClobberingMemoryAccess(
  1363. CallAccess->getDefiningAccess(), Loc, BAA);
  1364. if (auto *MD = dyn_cast<MemoryDef>(Clobber))
  1365. MDep = dyn_cast_or_null<MemCpyInst>(MD->getMemoryInst());
  1366. // If the byval argument isn't fed by a memcpy, ignore it. If it is fed by
  1367. // a memcpy, see if we can byval from the source of the memcpy instead of the
  1368. // result.
  1369. if (!MDep || MDep->isVolatile() ||
  1370. ByValArg->stripPointerCasts() != MDep->getDest())
  1371. return false;
  1372. // The length of the memcpy must be larger or equal to the size of the byval.
  1373. auto *C1 = dyn_cast<ConstantInt>(MDep->getLength());
  1374. if (!C1 || !TypeSize::isKnownGE(
  1375. TypeSize::getFixed(C1->getValue().getZExtValue()), ByValSize))
  1376. return false;
  1377. // Get the alignment of the byval. If the call doesn't specify the alignment,
  1378. // then it is some target specific value that we can't know.
  1379. MaybeAlign ByValAlign = CB.getParamAlign(ArgNo);
  1380. if (!ByValAlign) return false;
  1381. // If it is greater than the memcpy, then we check to see if we can force the
  1382. // source of the memcpy to the alignment we need. If we fail, we bail out.
  1383. MaybeAlign MemDepAlign = MDep->getSourceAlign();
  1384. if ((!MemDepAlign || *MemDepAlign < *ByValAlign) &&
  1385. getOrEnforceKnownAlignment(MDep->getSource(), ByValAlign, DL, &CB, AC,
  1386. DT) < *ByValAlign)
  1387. return false;
  1388. // The address space of the memcpy source must match the byval argument
  1389. if (MDep->getSource()->getType()->getPointerAddressSpace() !=
  1390. ByValArg->getType()->getPointerAddressSpace())
  1391. return false;
  1392. // Verify that the copied-from memory doesn't change in between the memcpy and
  1393. // the byval call.
  1394. // memcpy(a <- b)
  1395. // *b = 42;
  1396. // foo(*a)
  1397. // It would be invalid to transform the second memcpy into foo(*b).
  1398. if (writtenBetween(MSSA, BAA, MemoryLocation::getForSource(MDep),
  1399. MSSA->getMemoryAccess(MDep), MSSA->getMemoryAccess(&CB)))
  1400. return false;
  1401. Value *TmpCast = MDep->getSource();
  1402. if (MDep->getSource()->getType() != ByValArg->getType()) {
  1403. BitCastInst *TmpBitCast = new BitCastInst(MDep->getSource(), ByValArg->getType(),
  1404. "tmpcast", &CB);
  1405. // Set the tmpcast's DebugLoc to MDep's
  1406. TmpBitCast->setDebugLoc(MDep->getDebugLoc());
  1407. TmpCast = TmpBitCast;
  1408. }
  1409. LLVM_DEBUG(dbgs() << "MemCpyOptPass: Forwarding memcpy to byval:\n"
  1410. << " " << *MDep << "\n"
  1411. << " " << CB << "\n");
  1412. // Otherwise we're good! Update the byval argument.
  1413. CB.setArgOperand(ArgNo, TmpCast);
  1414. ++NumMemCpyInstr;
  1415. return true;
  1416. }
  1417. /// Executes one iteration of MemCpyOptPass.
  1418. bool MemCpyOptPass::iterateOnFunction(Function &F) {
  1419. bool MadeChange = false;
  1420. // Walk all instruction in the function.
  1421. for (BasicBlock &BB : F) {
  1422. // Skip unreachable blocks. For example processStore assumes that an
  1423. // instruction in a BB can't be dominated by a later instruction in the
  1424. // same BB (which is a scenario that can happen for an unreachable BB that
  1425. // has itself as a predecessor).
  1426. if (!DT->isReachableFromEntry(&BB))
  1427. continue;
  1428. for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
  1429. // Avoid invalidating the iterator.
  1430. Instruction *I = &*BI++;
  1431. bool RepeatInstruction = false;
  1432. if (auto *SI = dyn_cast<StoreInst>(I))
  1433. MadeChange |= processStore(SI, BI);
  1434. else if (auto *M = dyn_cast<MemSetInst>(I))
  1435. RepeatInstruction = processMemSet(M, BI);
  1436. else if (auto *M = dyn_cast<MemCpyInst>(I))
  1437. RepeatInstruction = processMemCpy(M, BI);
  1438. else if (auto *M = dyn_cast<MemMoveInst>(I))
  1439. RepeatInstruction = processMemMove(M);
  1440. else if (auto *CB = dyn_cast<CallBase>(I)) {
  1441. for (unsigned i = 0, e = CB->arg_size(); i != e; ++i)
  1442. if (CB->isByValArgument(i))
  1443. MadeChange |= processByValArgument(*CB, i);
  1444. }
  1445. // Reprocess the instruction if desired.
  1446. if (RepeatInstruction) {
  1447. if (BI != BB.begin())
  1448. --BI;
  1449. MadeChange = true;
  1450. }
  1451. }
  1452. }
  1453. return MadeChange;
  1454. }
  1455. PreservedAnalyses MemCpyOptPass::run(Function &F, FunctionAnalysisManager &AM) {
  1456. auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
  1457. auto *AA = &AM.getResult<AAManager>(F);
  1458. auto *AC = &AM.getResult<AssumptionAnalysis>(F);
  1459. auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
  1460. auto *MSSA = &AM.getResult<MemorySSAAnalysis>(F);
  1461. bool MadeChange = runImpl(F, &TLI, AA, AC, DT, &MSSA->getMSSA());
  1462. if (!MadeChange)
  1463. return PreservedAnalyses::all();
  1464. PreservedAnalyses PA;
  1465. PA.preserveSet<CFGAnalyses>();
  1466. PA.preserve<MemorySSAAnalysis>();
  1467. return PA;
  1468. }
  1469. bool MemCpyOptPass::runImpl(Function &F, TargetLibraryInfo *TLI_,
  1470. AliasAnalysis *AA_, AssumptionCache *AC_,
  1471. DominatorTree *DT_, MemorySSA *MSSA_) {
  1472. bool MadeChange = false;
  1473. TLI = TLI_;
  1474. AA = AA_;
  1475. AC = AC_;
  1476. DT = DT_;
  1477. MSSA = MSSA_;
  1478. MemorySSAUpdater MSSAU_(MSSA_);
  1479. MSSAU = &MSSAU_;
  1480. while (true) {
  1481. if (!iterateOnFunction(F))
  1482. break;
  1483. MadeChange = true;
  1484. }
  1485. if (VerifyMemorySSA)
  1486. MSSA_->verifyMemorySSA();
  1487. return MadeChange;
  1488. }
  1489. /// This is the main transformation entry point for a function.
  1490. bool MemCpyOptLegacyPass::runOnFunction(Function &F) {
  1491. if (skipFunction(F))
  1492. return false;
  1493. auto *TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
  1494. auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
  1495. auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  1496. auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  1497. auto *MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
  1498. return Impl.runImpl(F, TLI, AA, AC, DT, MSSA);
  1499. }