MemorySSA.cpp 98 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685
  1. //===- MemorySSA.cpp - Memory SSA Builder ---------------------------------===//
  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 file implements the MemorySSA class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/Analysis/MemorySSA.h"
  13. #include "llvm/ADT/DenseMap.h"
  14. #include "llvm/ADT/DenseMapInfo.h"
  15. #include "llvm/ADT/DenseSet.h"
  16. #include "llvm/ADT/DepthFirstIterator.h"
  17. #include "llvm/ADT/Hashing.h"
  18. #include "llvm/ADT/None.h"
  19. #include "llvm/ADT/Optional.h"
  20. #include "llvm/ADT/STLExtras.h"
  21. #include "llvm/ADT/SmallPtrSet.h"
  22. #include "llvm/ADT/SmallVector.h"
  23. #include "llvm/ADT/StringExtras.h"
  24. #include "llvm/ADT/iterator.h"
  25. #include "llvm/ADT/iterator_range.h"
  26. #include "llvm/Analysis/AliasAnalysis.h"
  27. #include "llvm/Analysis/CFGPrinter.h"
  28. #include "llvm/Analysis/IteratedDominanceFrontier.h"
  29. #include "llvm/Analysis/MemoryLocation.h"
  30. #include "llvm/Config/llvm-config.h"
  31. #include "llvm/IR/AssemblyAnnotationWriter.h"
  32. #include "llvm/IR/BasicBlock.h"
  33. #include "llvm/IR/Dominators.h"
  34. #include "llvm/IR/Function.h"
  35. #include "llvm/IR/Instruction.h"
  36. #include "llvm/IR/Instructions.h"
  37. #include "llvm/IR/IntrinsicInst.h"
  38. #include "llvm/IR/Intrinsics.h"
  39. #include "llvm/IR/LLVMContext.h"
  40. #include "llvm/IR/PassManager.h"
  41. #include "llvm/IR/Use.h"
  42. #include "llvm/InitializePasses.h"
  43. #include "llvm/Pass.h"
  44. #include "llvm/Support/AtomicOrdering.h"
  45. #include "llvm/Support/Casting.h"
  46. #include "llvm/Support/CommandLine.h"
  47. #include "llvm/Support/Compiler.h"
  48. #include "llvm/Support/Debug.h"
  49. #include "llvm/Support/ErrorHandling.h"
  50. #include "llvm/Support/FormattedStream.h"
  51. #include "llvm/Support/raw_ostream.h"
  52. #include <algorithm>
  53. #include <cassert>
  54. #include <cstdlib>
  55. #include <iterator>
  56. #include <memory>
  57. #include <utility>
  58. using namespace llvm;
  59. #define DEBUG_TYPE "memoryssa"
  60. static cl::opt<std::string>
  61. DotCFGMSSA("dot-cfg-mssa",
  62. cl::value_desc("file name for generated dot file"),
  63. cl::desc("file name for generated dot file"), cl::init(""));
  64. INITIALIZE_PASS_BEGIN(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false,
  65. true)
  66. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  67. INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
  68. INITIALIZE_PASS_END(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false,
  69. true)
  70. INITIALIZE_PASS_BEGIN(MemorySSAPrinterLegacyPass, "print-memoryssa",
  71. "Memory SSA Printer", false, false)
  72. INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
  73. INITIALIZE_PASS_END(MemorySSAPrinterLegacyPass, "print-memoryssa",
  74. "Memory SSA Printer", false, false)
  75. static cl::opt<unsigned> MaxCheckLimit(
  76. "memssa-check-limit", cl::Hidden, cl::init(100),
  77. cl::desc("The maximum number of stores/phis MemorySSA"
  78. "will consider trying to walk past (default = 100)"));
  79. // Always verify MemorySSA if expensive checking is enabled.
  80. #ifdef EXPENSIVE_CHECKS
  81. bool llvm::VerifyMemorySSA = true;
  82. #else
  83. bool llvm::VerifyMemorySSA = false;
  84. #endif
  85. static cl::opt<bool, true>
  86. VerifyMemorySSAX("verify-memoryssa", cl::location(VerifyMemorySSA),
  87. cl::Hidden, cl::desc("Enable verification of MemorySSA."));
  88. const static char LiveOnEntryStr[] = "liveOnEntry";
  89. namespace {
  90. /// An assembly annotator class to print Memory SSA information in
  91. /// comments.
  92. class MemorySSAAnnotatedWriter : public AssemblyAnnotationWriter {
  93. const MemorySSA *MSSA;
  94. public:
  95. MemorySSAAnnotatedWriter(const MemorySSA *M) : MSSA(M) {}
  96. void emitBasicBlockStartAnnot(const BasicBlock *BB,
  97. formatted_raw_ostream &OS) override {
  98. if (MemoryAccess *MA = MSSA->getMemoryAccess(BB))
  99. OS << "; " << *MA << "\n";
  100. }
  101. void emitInstructionAnnot(const Instruction *I,
  102. formatted_raw_ostream &OS) override {
  103. if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
  104. OS << "; " << *MA << "\n";
  105. }
  106. };
  107. /// An assembly annotator class to print Memory SSA information in
  108. /// comments.
  109. class MemorySSAWalkerAnnotatedWriter : public AssemblyAnnotationWriter {
  110. MemorySSA *MSSA;
  111. MemorySSAWalker *Walker;
  112. public:
  113. MemorySSAWalkerAnnotatedWriter(MemorySSA *M)
  114. : MSSA(M), Walker(M->getWalker()) {}
  115. void emitInstructionAnnot(const Instruction *I,
  116. formatted_raw_ostream &OS) override {
  117. if (MemoryAccess *MA = MSSA->getMemoryAccess(I)) {
  118. MemoryAccess *Clobber = Walker->getClobberingMemoryAccess(MA);
  119. OS << "; " << *MA;
  120. if (Clobber) {
  121. OS << " - clobbered by ";
  122. if (MSSA->isLiveOnEntryDef(Clobber))
  123. OS << LiveOnEntryStr;
  124. else
  125. OS << *Clobber;
  126. }
  127. OS << "\n";
  128. }
  129. }
  130. };
  131. } // namespace
  132. namespace {
  133. /// Our current alias analysis API differentiates heavily between calls and
  134. /// non-calls, and functions called on one usually assert on the other.
  135. /// This class encapsulates the distinction to simplify other code that wants
  136. /// "Memory affecting instructions and related data" to use as a key.
  137. /// For example, this class is used as a densemap key in the use optimizer.
  138. class MemoryLocOrCall {
  139. public:
  140. bool IsCall = false;
  141. MemoryLocOrCall(MemoryUseOrDef *MUD)
  142. : MemoryLocOrCall(MUD->getMemoryInst()) {}
  143. MemoryLocOrCall(const MemoryUseOrDef *MUD)
  144. : MemoryLocOrCall(MUD->getMemoryInst()) {}
  145. MemoryLocOrCall(Instruction *Inst) {
  146. if (auto *C = dyn_cast<CallBase>(Inst)) {
  147. IsCall = true;
  148. Call = C;
  149. } else {
  150. IsCall = false;
  151. // There is no such thing as a memorylocation for a fence inst, and it is
  152. // unique in that regard.
  153. if (!isa<FenceInst>(Inst))
  154. Loc = MemoryLocation::get(Inst);
  155. }
  156. }
  157. explicit MemoryLocOrCall(const MemoryLocation &Loc) : Loc(Loc) {}
  158. const CallBase *getCall() const {
  159. assert(IsCall);
  160. return Call;
  161. }
  162. MemoryLocation getLoc() const {
  163. assert(!IsCall);
  164. return Loc;
  165. }
  166. bool operator==(const MemoryLocOrCall &Other) const {
  167. if (IsCall != Other.IsCall)
  168. return false;
  169. if (!IsCall)
  170. return Loc == Other.Loc;
  171. if (Call->getCalledOperand() != Other.Call->getCalledOperand())
  172. return false;
  173. return Call->arg_size() == Other.Call->arg_size() &&
  174. std::equal(Call->arg_begin(), Call->arg_end(),
  175. Other.Call->arg_begin());
  176. }
  177. private:
  178. union {
  179. const CallBase *Call;
  180. MemoryLocation Loc;
  181. };
  182. };
  183. } // end anonymous namespace
  184. namespace llvm {
  185. template <> struct DenseMapInfo<MemoryLocOrCall> {
  186. static inline MemoryLocOrCall getEmptyKey() {
  187. return MemoryLocOrCall(DenseMapInfo<MemoryLocation>::getEmptyKey());
  188. }
  189. static inline MemoryLocOrCall getTombstoneKey() {
  190. return MemoryLocOrCall(DenseMapInfo<MemoryLocation>::getTombstoneKey());
  191. }
  192. static unsigned getHashValue(const MemoryLocOrCall &MLOC) {
  193. if (!MLOC.IsCall)
  194. return hash_combine(
  195. MLOC.IsCall,
  196. DenseMapInfo<MemoryLocation>::getHashValue(MLOC.getLoc()));
  197. hash_code hash =
  198. hash_combine(MLOC.IsCall, DenseMapInfo<const Value *>::getHashValue(
  199. MLOC.getCall()->getCalledOperand()));
  200. for (const Value *Arg : MLOC.getCall()->args())
  201. hash = hash_combine(hash, DenseMapInfo<const Value *>::getHashValue(Arg));
  202. return hash;
  203. }
  204. static bool isEqual(const MemoryLocOrCall &LHS, const MemoryLocOrCall &RHS) {
  205. return LHS == RHS;
  206. }
  207. };
  208. } // end namespace llvm
  209. /// This does one-way checks to see if Use could theoretically be hoisted above
  210. /// MayClobber. This will not check the other way around.
  211. ///
  212. /// This assumes that, for the purposes of MemorySSA, Use comes directly after
  213. /// MayClobber, with no potentially clobbering operations in between them.
  214. /// (Where potentially clobbering ops are memory barriers, aliased stores, etc.)
  215. static bool areLoadsReorderable(const LoadInst *Use,
  216. const LoadInst *MayClobber) {
  217. bool VolatileUse = Use->isVolatile();
  218. bool VolatileClobber = MayClobber->isVolatile();
  219. // Volatile operations may never be reordered with other volatile operations.
  220. if (VolatileUse && VolatileClobber)
  221. return false;
  222. // Otherwise, volatile doesn't matter here. From the language reference:
  223. // 'optimizers may change the order of volatile operations relative to
  224. // non-volatile operations.'"
  225. // If a load is seq_cst, it cannot be moved above other loads. If its ordering
  226. // is weaker, it can be moved above other loads. We just need to be sure that
  227. // MayClobber isn't an acquire load, because loads can't be moved above
  228. // acquire loads.
  229. //
  230. // Note that this explicitly *does* allow the free reordering of monotonic (or
  231. // weaker) loads of the same address.
  232. bool SeqCstUse = Use->getOrdering() == AtomicOrdering::SequentiallyConsistent;
  233. bool MayClobberIsAcquire = isAtLeastOrStrongerThan(MayClobber->getOrdering(),
  234. AtomicOrdering::Acquire);
  235. return !(SeqCstUse || MayClobberIsAcquire);
  236. }
  237. namespace {
  238. struct ClobberAlias {
  239. bool IsClobber;
  240. Optional<AliasResult> AR;
  241. };
  242. } // end anonymous namespace
  243. // Return a pair of {IsClobber (bool), AR (AliasResult)}. It relies on AR being
  244. // ignored if IsClobber = false.
  245. template <typename AliasAnalysisType>
  246. static ClobberAlias
  247. instructionClobbersQuery(const MemoryDef *MD, const MemoryLocation &UseLoc,
  248. const Instruction *UseInst, AliasAnalysisType &AA) {
  249. Instruction *DefInst = MD->getMemoryInst();
  250. assert(DefInst && "Defining instruction not actually an instruction");
  251. Optional<AliasResult> AR;
  252. if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(DefInst)) {
  253. // These intrinsics will show up as affecting memory, but they are just
  254. // markers, mostly.
  255. //
  256. // FIXME: We probably don't actually want MemorySSA to model these at all
  257. // (including creating MemoryAccesses for them): we just end up inventing
  258. // clobbers where they don't really exist at all. Please see D43269 for
  259. // context.
  260. switch (II->getIntrinsicID()) {
  261. case Intrinsic::invariant_start:
  262. case Intrinsic::invariant_end:
  263. case Intrinsic::assume:
  264. case Intrinsic::experimental_noalias_scope_decl:
  265. case Intrinsic::pseudoprobe:
  266. return {false, AliasResult(AliasResult::NoAlias)};
  267. case Intrinsic::dbg_addr:
  268. case Intrinsic::dbg_declare:
  269. case Intrinsic::dbg_label:
  270. case Intrinsic::dbg_value:
  271. llvm_unreachable("debuginfo shouldn't have associated defs!");
  272. default:
  273. break;
  274. }
  275. }
  276. if (auto *CB = dyn_cast_or_null<CallBase>(UseInst)) {
  277. ModRefInfo I = AA.getModRefInfo(DefInst, CB);
  278. AR = isMustSet(I) ? AliasResult::MustAlias : AliasResult::MayAlias;
  279. return {isModOrRefSet(I), AR};
  280. }
  281. if (auto *DefLoad = dyn_cast<LoadInst>(DefInst))
  282. if (auto *UseLoad = dyn_cast_or_null<LoadInst>(UseInst))
  283. return {!areLoadsReorderable(UseLoad, DefLoad),
  284. AliasResult(AliasResult::MayAlias)};
  285. ModRefInfo I = AA.getModRefInfo(DefInst, UseLoc);
  286. AR = isMustSet(I) ? AliasResult::MustAlias : AliasResult::MayAlias;
  287. return {isModSet(I), AR};
  288. }
  289. template <typename AliasAnalysisType>
  290. static ClobberAlias instructionClobbersQuery(MemoryDef *MD,
  291. const MemoryUseOrDef *MU,
  292. const MemoryLocOrCall &UseMLOC,
  293. AliasAnalysisType &AA) {
  294. // FIXME: This is a temporary hack to allow a single instructionClobbersQuery
  295. // to exist while MemoryLocOrCall is pushed through places.
  296. if (UseMLOC.IsCall)
  297. return instructionClobbersQuery(MD, MemoryLocation(), MU->getMemoryInst(),
  298. AA);
  299. return instructionClobbersQuery(MD, UseMLOC.getLoc(), MU->getMemoryInst(),
  300. AA);
  301. }
  302. // Return true when MD may alias MU, return false otherwise.
  303. bool MemorySSAUtil::defClobbersUseOrDef(MemoryDef *MD, const MemoryUseOrDef *MU,
  304. AliasAnalysis &AA) {
  305. return instructionClobbersQuery(MD, MU, MemoryLocOrCall(MU), AA).IsClobber;
  306. }
  307. namespace {
  308. struct UpwardsMemoryQuery {
  309. // True if our original query started off as a call
  310. bool IsCall = false;
  311. // The pointer location we started the query with. This will be empty if
  312. // IsCall is true.
  313. MemoryLocation StartingLoc;
  314. // This is the instruction we were querying about.
  315. const Instruction *Inst = nullptr;
  316. // The MemoryAccess we actually got called with, used to test local domination
  317. const MemoryAccess *OriginalAccess = nullptr;
  318. Optional<AliasResult> AR = AliasResult(AliasResult::MayAlias);
  319. bool SkipSelfAccess = false;
  320. UpwardsMemoryQuery() = default;
  321. UpwardsMemoryQuery(const Instruction *Inst, const MemoryAccess *Access)
  322. : IsCall(isa<CallBase>(Inst)), Inst(Inst), OriginalAccess(Access) {
  323. if (!IsCall)
  324. StartingLoc = MemoryLocation::get(Inst);
  325. }
  326. };
  327. } // end anonymous namespace
  328. template <typename AliasAnalysisType>
  329. static bool isUseTriviallyOptimizableToLiveOnEntry(AliasAnalysisType &AA,
  330. const Instruction *I) {
  331. // If the memory can't be changed, then loads of the memory can't be
  332. // clobbered.
  333. if (auto *LI = dyn_cast<LoadInst>(I))
  334. return I->hasMetadata(LLVMContext::MD_invariant_load) ||
  335. AA.pointsToConstantMemory(MemoryLocation::get(LI));
  336. return false;
  337. }
  338. /// Verifies that `Start` is clobbered by `ClobberAt`, and that nothing
  339. /// inbetween `Start` and `ClobberAt` can clobbers `Start`.
  340. ///
  341. /// This is meant to be as simple and self-contained as possible. Because it
  342. /// uses no cache, etc., it can be relatively expensive.
  343. ///
  344. /// \param Start The MemoryAccess that we want to walk from.
  345. /// \param ClobberAt A clobber for Start.
  346. /// \param StartLoc The MemoryLocation for Start.
  347. /// \param MSSA The MemorySSA instance that Start and ClobberAt belong to.
  348. /// \param Query The UpwardsMemoryQuery we used for our search.
  349. /// \param AA The AliasAnalysis we used for our search.
  350. /// \param AllowImpreciseClobber Always false, unless we do relaxed verify.
  351. template <typename AliasAnalysisType>
  352. LLVM_ATTRIBUTE_UNUSED static void
  353. checkClobberSanity(const MemoryAccess *Start, MemoryAccess *ClobberAt,
  354. const MemoryLocation &StartLoc, const MemorySSA &MSSA,
  355. const UpwardsMemoryQuery &Query, AliasAnalysisType &AA,
  356. bool AllowImpreciseClobber = false) {
  357. assert(MSSA.dominates(ClobberAt, Start) && "Clobber doesn't dominate start?");
  358. if (MSSA.isLiveOnEntryDef(Start)) {
  359. assert(MSSA.isLiveOnEntryDef(ClobberAt) &&
  360. "liveOnEntry must clobber itself");
  361. return;
  362. }
  363. bool FoundClobber = false;
  364. DenseSet<ConstMemoryAccessPair> VisitedPhis;
  365. SmallVector<ConstMemoryAccessPair, 8> Worklist;
  366. Worklist.emplace_back(Start, StartLoc);
  367. // Walk all paths from Start to ClobberAt, while looking for clobbers. If one
  368. // is found, complain.
  369. while (!Worklist.empty()) {
  370. auto MAP = Worklist.pop_back_val();
  371. // All we care about is that nothing from Start to ClobberAt clobbers Start.
  372. // We learn nothing from revisiting nodes.
  373. if (!VisitedPhis.insert(MAP).second)
  374. continue;
  375. for (const auto *MA : def_chain(MAP.first)) {
  376. if (MA == ClobberAt) {
  377. if (const auto *MD = dyn_cast<MemoryDef>(MA)) {
  378. // instructionClobbersQuery isn't essentially free, so don't use `|=`,
  379. // since it won't let us short-circuit.
  380. //
  381. // Also, note that this can't be hoisted out of the `Worklist` loop,
  382. // since MD may only act as a clobber for 1 of N MemoryLocations.
  383. FoundClobber = FoundClobber || MSSA.isLiveOnEntryDef(MD);
  384. if (!FoundClobber) {
  385. ClobberAlias CA =
  386. instructionClobbersQuery(MD, MAP.second, Query.Inst, AA);
  387. if (CA.IsClobber) {
  388. FoundClobber = true;
  389. // Not used: CA.AR;
  390. }
  391. }
  392. }
  393. break;
  394. }
  395. // We should never hit liveOnEntry, unless it's the clobber.
  396. assert(!MSSA.isLiveOnEntryDef(MA) && "Hit liveOnEntry before clobber?");
  397. if (const auto *MD = dyn_cast<MemoryDef>(MA)) {
  398. // If Start is a Def, skip self.
  399. if (MD == Start)
  400. continue;
  401. assert(!instructionClobbersQuery(MD, MAP.second, Query.Inst, AA)
  402. .IsClobber &&
  403. "Found clobber before reaching ClobberAt!");
  404. continue;
  405. }
  406. if (const auto *MU = dyn_cast<MemoryUse>(MA)) {
  407. (void)MU;
  408. assert (MU == Start &&
  409. "Can only find use in def chain if Start is a use");
  410. continue;
  411. }
  412. assert(isa<MemoryPhi>(MA));
  413. // Add reachable phi predecessors
  414. for (auto ItB = upward_defs_begin(
  415. {const_cast<MemoryAccess *>(MA), MAP.second},
  416. MSSA.getDomTree()),
  417. ItE = upward_defs_end();
  418. ItB != ItE; ++ItB)
  419. if (MSSA.getDomTree().isReachableFromEntry(ItB.getPhiArgBlock()))
  420. Worklist.emplace_back(*ItB);
  421. }
  422. }
  423. // If the verify is done following an optimization, it's possible that
  424. // ClobberAt was a conservative clobbering, that we can now infer is not a
  425. // true clobbering access. Don't fail the verify if that's the case.
  426. // We do have accesses that claim they're optimized, but could be optimized
  427. // further. Updating all these can be expensive, so allow it for now (FIXME).
  428. if (AllowImpreciseClobber)
  429. return;
  430. // If ClobberAt is a MemoryPhi, we can assume something above it acted as a
  431. // clobber. Otherwise, `ClobberAt` should've acted as a clobber at some point.
  432. assert((isa<MemoryPhi>(ClobberAt) || FoundClobber) &&
  433. "ClobberAt never acted as a clobber");
  434. }
  435. namespace {
  436. /// Our algorithm for walking (and trying to optimize) clobbers, all wrapped up
  437. /// in one class.
  438. template <class AliasAnalysisType> class ClobberWalker {
  439. /// Save a few bytes by using unsigned instead of size_t.
  440. using ListIndex = unsigned;
  441. /// Represents a span of contiguous MemoryDefs, potentially ending in a
  442. /// MemoryPhi.
  443. struct DefPath {
  444. MemoryLocation Loc;
  445. // Note that, because we always walk in reverse, Last will always dominate
  446. // First. Also note that First and Last are inclusive.
  447. MemoryAccess *First;
  448. MemoryAccess *Last;
  449. Optional<ListIndex> Previous;
  450. DefPath(const MemoryLocation &Loc, MemoryAccess *First, MemoryAccess *Last,
  451. Optional<ListIndex> Previous)
  452. : Loc(Loc), First(First), Last(Last), Previous(Previous) {}
  453. DefPath(const MemoryLocation &Loc, MemoryAccess *Init,
  454. Optional<ListIndex> Previous)
  455. : DefPath(Loc, Init, Init, Previous) {}
  456. };
  457. const MemorySSA &MSSA;
  458. AliasAnalysisType &AA;
  459. DominatorTree &DT;
  460. UpwardsMemoryQuery *Query;
  461. unsigned *UpwardWalkLimit;
  462. // Phi optimization bookkeeping:
  463. // List of DefPath to process during the current phi optimization walk.
  464. SmallVector<DefPath, 32> Paths;
  465. // List of visited <Access, Location> pairs; we can skip paths already
  466. // visited with the same memory location.
  467. DenseSet<ConstMemoryAccessPair> VisitedPhis;
  468. // Record if phi translation has been performed during the current phi
  469. // optimization walk, as merging alias results after phi translation can
  470. // yield incorrect results. Context in PR46156.
  471. bool PerformedPhiTranslation = false;
  472. /// Find the nearest def or phi that `From` can legally be optimized to.
  473. const MemoryAccess *getWalkTarget(const MemoryPhi *From) const {
  474. assert(From->getNumOperands() && "Phi with no operands?");
  475. BasicBlock *BB = From->getBlock();
  476. MemoryAccess *Result = MSSA.getLiveOnEntryDef();
  477. DomTreeNode *Node = DT.getNode(BB);
  478. while ((Node = Node->getIDom())) {
  479. auto *Defs = MSSA.getBlockDefs(Node->getBlock());
  480. if (Defs)
  481. return &*Defs->rbegin();
  482. }
  483. return Result;
  484. }
  485. /// Result of calling walkToPhiOrClobber.
  486. struct UpwardsWalkResult {
  487. /// The "Result" of the walk. Either a clobber, the last thing we walked, or
  488. /// both. Include alias info when clobber found.
  489. MemoryAccess *Result;
  490. bool IsKnownClobber;
  491. Optional<AliasResult> AR;
  492. };
  493. /// Walk to the next Phi or Clobber in the def chain starting at Desc.Last.
  494. /// This will update Desc.Last as it walks. It will (optionally) also stop at
  495. /// StopAt.
  496. ///
  497. /// This does not test for whether StopAt is a clobber
  498. UpwardsWalkResult
  499. walkToPhiOrClobber(DefPath &Desc, const MemoryAccess *StopAt = nullptr,
  500. const MemoryAccess *SkipStopAt = nullptr) const {
  501. assert(!isa<MemoryUse>(Desc.Last) && "Uses don't exist in my world");
  502. assert(UpwardWalkLimit && "Need a valid walk limit");
  503. bool LimitAlreadyReached = false;
  504. // (*UpwardWalkLimit) may be 0 here, due to the loop in tryOptimizePhi. Set
  505. // it to 1. This will not do any alias() calls. It either returns in the
  506. // first iteration in the loop below, or is set back to 0 if all def chains
  507. // are free of MemoryDefs.
  508. if (!*UpwardWalkLimit) {
  509. *UpwardWalkLimit = 1;
  510. LimitAlreadyReached = true;
  511. }
  512. for (MemoryAccess *Current : def_chain(Desc.Last)) {
  513. Desc.Last = Current;
  514. if (Current == StopAt || Current == SkipStopAt)
  515. return {Current, false, AliasResult(AliasResult::MayAlias)};
  516. if (auto *MD = dyn_cast<MemoryDef>(Current)) {
  517. if (MSSA.isLiveOnEntryDef(MD))
  518. return {MD, true, AliasResult(AliasResult::MustAlias)};
  519. if (!--*UpwardWalkLimit)
  520. return {Current, true, AliasResult(AliasResult::MayAlias)};
  521. ClobberAlias CA =
  522. instructionClobbersQuery(MD, Desc.Loc, Query->Inst, AA);
  523. if (CA.IsClobber)
  524. return {MD, true, CA.AR};
  525. }
  526. }
  527. if (LimitAlreadyReached)
  528. *UpwardWalkLimit = 0;
  529. assert(isa<MemoryPhi>(Desc.Last) &&
  530. "Ended at a non-clobber that's not a phi?");
  531. return {Desc.Last, false, AliasResult(AliasResult::MayAlias)};
  532. }
  533. void addSearches(MemoryPhi *Phi, SmallVectorImpl<ListIndex> &PausedSearches,
  534. ListIndex PriorNode) {
  535. auto UpwardDefsBegin = upward_defs_begin({Phi, Paths[PriorNode].Loc}, DT,
  536. &PerformedPhiTranslation);
  537. auto UpwardDefs = make_range(UpwardDefsBegin, upward_defs_end());
  538. for (const MemoryAccessPair &P : UpwardDefs) {
  539. PausedSearches.push_back(Paths.size());
  540. Paths.emplace_back(P.second, P.first, PriorNode);
  541. }
  542. }
  543. /// Represents a search that terminated after finding a clobber. This clobber
  544. /// may or may not be present in the path of defs from LastNode..SearchStart,
  545. /// since it may have been retrieved from cache.
  546. struct TerminatedPath {
  547. MemoryAccess *Clobber;
  548. ListIndex LastNode;
  549. };
  550. /// Get an access that keeps us from optimizing to the given phi.
  551. ///
  552. /// PausedSearches is an array of indices into the Paths array. Its incoming
  553. /// value is the indices of searches that stopped at the last phi optimization
  554. /// target. It's left in an unspecified state.
  555. ///
  556. /// If this returns None, NewPaused is a vector of searches that terminated
  557. /// at StopWhere. Otherwise, NewPaused is left in an unspecified state.
  558. Optional<TerminatedPath>
  559. getBlockingAccess(const MemoryAccess *StopWhere,
  560. SmallVectorImpl<ListIndex> &PausedSearches,
  561. SmallVectorImpl<ListIndex> &NewPaused,
  562. SmallVectorImpl<TerminatedPath> &Terminated) {
  563. assert(!PausedSearches.empty() && "No searches to continue?");
  564. // BFS vs DFS really doesn't make a difference here, so just do a DFS with
  565. // PausedSearches as our stack.
  566. while (!PausedSearches.empty()) {
  567. ListIndex PathIndex = PausedSearches.pop_back_val();
  568. DefPath &Node = Paths[PathIndex];
  569. // If we've already visited this path with this MemoryLocation, we don't
  570. // need to do so again.
  571. //
  572. // NOTE: That we just drop these paths on the ground makes caching
  573. // behavior sporadic. e.g. given a diamond:
  574. // A
  575. // B C
  576. // D
  577. //
  578. // ...If we walk D, B, A, C, we'll only cache the result of phi
  579. // optimization for A, B, and D; C will be skipped because it dies here.
  580. // This arguably isn't the worst thing ever, since:
  581. // - We generally query things in a top-down order, so if we got below D
  582. // without needing cache entries for {C, MemLoc}, then chances are
  583. // that those cache entries would end up ultimately unused.
  584. // - We still cache things for A, so C only needs to walk up a bit.
  585. // If this behavior becomes problematic, we can fix without a ton of extra
  586. // work.
  587. if (!VisitedPhis.insert({Node.Last, Node.Loc}).second) {
  588. if (PerformedPhiTranslation) {
  589. // If visiting this path performed Phi translation, don't continue,
  590. // since it may not be correct to merge results from two paths if one
  591. // relies on the phi translation.
  592. TerminatedPath Term{Node.Last, PathIndex};
  593. return Term;
  594. }
  595. continue;
  596. }
  597. const MemoryAccess *SkipStopWhere = nullptr;
  598. if (Query->SkipSelfAccess && Node.Loc == Query->StartingLoc) {
  599. assert(isa<MemoryDef>(Query->OriginalAccess));
  600. SkipStopWhere = Query->OriginalAccess;
  601. }
  602. UpwardsWalkResult Res = walkToPhiOrClobber(Node,
  603. /*StopAt=*/StopWhere,
  604. /*SkipStopAt=*/SkipStopWhere);
  605. if (Res.IsKnownClobber) {
  606. assert(Res.Result != StopWhere && Res.Result != SkipStopWhere);
  607. // If this wasn't a cache hit, we hit a clobber when walking. That's a
  608. // failure.
  609. TerminatedPath Term{Res.Result, PathIndex};
  610. if (!MSSA.dominates(Res.Result, StopWhere))
  611. return Term;
  612. // Otherwise, it's a valid thing to potentially optimize to.
  613. Terminated.push_back(Term);
  614. continue;
  615. }
  616. if (Res.Result == StopWhere || Res.Result == SkipStopWhere) {
  617. // We've hit our target. Save this path off for if we want to continue
  618. // walking. If we are in the mode of skipping the OriginalAccess, and
  619. // we've reached back to the OriginalAccess, do not save path, we've
  620. // just looped back to self.
  621. if (Res.Result != SkipStopWhere)
  622. NewPaused.push_back(PathIndex);
  623. continue;
  624. }
  625. assert(!MSSA.isLiveOnEntryDef(Res.Result) && "liveOnEntry is a clobber");
  626. addSearches(cast<MemoryPhi>(Res.Result), PausedSearches, PathIndex);
  627. }
  628. return None;
  629. }
  630. template <typename T, typename Walker>
  631. struct generic_def_path_iterator
  632. : public iterator_facade_base<generic_def_path_iterator<T, Walker>,
  633. std::forward_iterator_tag, T *> {
  634. generic_def_path_iterator() {}
  635. generic_def_path_iterator(Walker *W, ListIndex N) : W(W), N(N) {}
  636. T &operator*() const { return curNode(); }
  637. generic_def_path_iterator &operator++() {
  638. N = curNode().Previous;
  639. return *this;
  640. }
  641. bool operator==(const generic_def_path_iterator &O) const {
  642. if (N.hasValue() != O.N.hasValue())
  643. return false;
  644. return !N.hasValue() || *N == *O.N;
  645. }
  646. private:
  647. T &curNode() const { return W->Paths[*N]; }
  648. Walker *W = nullptr;
  649. Optional<ListIndex> N = None;
  650. };
  651. using def_path_iterator = generic_def_path_iterator<DefPath, ClobberWalker>;
  652. using const_def_path_iterator =
  653. generic_def_path_iterator<const DefPath, const ClobberWalker>;
  654. iterator_range<def_path_iterator> def_path(ListIndex From) {
  655. return make_range(def_path_iterator(this, From), def_path_iterator());
  656. }
  657. iterator_range<const_def_path_iterator> const_def_path(ListIndex From) const {
  658. return make_range(const_def_path_iterator(this, From),
  659. const_def_path_iterator());
  660. }
  661. struct OptznResult {
  662. /// The path that contains our result.
  663. TerminatedPath PrimaryClobber;
  664. /// The paths that we can legally cache back from, but that aren't
  665. /// necessarily the result of the Phi optimization.
  666. SmallVector<TerminatedPath, 4> OtherClobbers;
  667. };
  668. ListIndex defPathIndex(const DefPath &N) const {
  669. // The assert looks nicer if we don't need to do &N
  670. const DefPath *NP = &N;
  671. assert(!Paths.empty() && NP >= &Paths.front() && NP <= &Paths.back() &&
  672. "Out of bounds DefPath!");
  673. return NP - &Paths.front();
  674. }
  675. /// Try to optimize a phi as best as we can. Returns a SmallVector of Paths
  676. /// that act as legal clobbers. Note that this won't return *all* clobbers.
  677. ///
  678. /// Phi optimization algorithm tl;dr:
  679. /// - Find the earliest def/phi, A, we can optimize to
  680. /// - Find if all paths from the starting memory access ultimately reach A
  681. /// - If not, optimization isn't possible.
  682. /// - Otherwise, walk from A to another clobber or phi, A'.
  683. /// - If A' is a def, we're done.
  684. /// - If A' is a phi, try to optimize it.
  685. ///
  686. /// A path is a series of {MemoryAccess, MemoryLocation} pairs. A path
  687. /// terminates when a MemoryAccess that clobbers said MemoryLocation is found.
  688. OptznResult tryOptimizePhi(MemoryPhi *Phi, MemoryAccess *Start,
  689. const MemoryLocation &Loc) {
  690. assert(Paths.empty() && VisitedPhis.empty() && !PerformedPhiTranslation &&
  691. "Reset the optimization state.");
  692. Paths.emplace_back(Loc, Start, Phi, None);
  693. // Stores how many "valid" optimization nodes we had prior to calling
  694. // addSearches/getBlockingAccess. Necessary for caching if we had a blocker.
  695. auto PriorPathsSize = Paths.size();
  696. SmallVector<ListIndex, 16> PausedSearches;
  697. SmallVector<ListIndex, 8> NewPaused;
  698. SmallVector<TerminatedPath, 4> TerminatedPaths;
  699. addSearches(Phi, PausedSearches, 0);
  700. // Moves the TerminatedPath with the "most dominated" Clobber to the end of
  701. // Paths.
  702. auto MoveDominatedPathToEnd = [&](SmallVectorImpl<TerminatedPath> &Paths) {
  703. assert(!Paths.empty() && "Need a path to move");
  704. auto Dom = Paths.begin();
  705. for (auto I = std::next(Dom), E = Paths.end(); I != E; ++I)
  706. if (!MSSA.dominates(I->Clobber, Dom->Clobber))
  707. Dom = I;
  708. auto Last = Paths.end() - 1;
  709. if (Last != Dom)
  710. std::iter_swap(Last, Dom);
  711. };
  712. MemoryPhi *Current = Phi;
  713. while (true) {
  714. assert(!MSSA.isLiveOnEntryDef(Current) &&
  715. "liveOnEntry wasn't treated as a clobber?");
  716. const auto *Target = getWalkTarget(Current);
  717. // If a TerminatedPath doesn't dominate Target, then it wasn't a legal
  718. // optimization for the prior phi.
  719. assert(all_of(TerminatedPaths, [&](const TerminatedPath &P) {
  720. return MSSA.dominates(P.Clobber, Target);
  721. }));
  722. // FIXME: This is broken, because the Blocker may be reported to be
  723. // liveOnEntry, and we'll happily wait for that to disappear (read: never)
  724. // For the moment, this is fine, since we do nothing with blocker info.
  725. if (Optional<TerminatedPath> Blocker = getBlockingAccess(
  726. Target, PausedSearches, NewPaused, TerminatedPaths)) {
  727. // Find the node we started at. We can't search based on N->Last, since
  728. // we may have gone around a loop with a different MemoryLocation.
  729. auto Iter = find_if(def_path(Blocker->LastNode), [&](const DefPath &N) {
  730. return defPathIndex(N) < PriorPathsSize;
  731. });
  732. assert(Iter != def_path_iterator());
  733. DefPath &CurNode = *Iter;
  734. assert(CurNode.Last == Current);
  735. // Two things:
  736. // A. We can't reliably cache all of NewPaused back. Consider a case
  737. // where we have two paths in NewPaused; one of which can't optimize
  738. // above this phi, whereas the other can. If we cache the second path
  739. // back, we'll end up with suboptimal cache entries. We can handle
  740. // cases like this a bit better when we either try to find all
  741. // clobbers that block phi optimization, or when our cache starts
  742. // supporting unfinished searches.
  743. // B. We can't reliably cache TerminatedPaths back here without doing
  744. // extra checks; consider a case like:
  745. // T
  746. // / \
  747. // D C
  748. // \ /
  749. // S
  750. // Where T is our target, C is a node with a clobber on it, D is a
  751. // diamond (with a clobber *only* on the left or right node, N), and
  752. // S is our start. Say we walk to D, through the node opposite N
  753. // (read: ignoring the clobber), and see a cache entry in the top
  754. // node of D. That cache entry gets put into TerminatedPaths. We then
  755. // walk up to C (N is later in our worklist), find the clobber, and
  756. // quit. If we append TerminatedPaths to OtherClobbers, we'll cache
  757. // the bottom part of D to the cached clobber, ignoring the clobber
  758. // in N. Again, this problem goes away if we start tracking all
  759. // blockers for a given phi optimization.
  760. TerminatedPath Result{CurNode.Last, defPathIndex(CurNode)};
  761. return {Result, {}};
  762. }
  763. // If there's nothing left to search, then all paths led to valid clobbers
  764. // that we got from our cache; pick the nearest to the start, and allow
  765. // the rest to be cached back.
  766. if (NewPaused.empty()) {
  767. MoveDominatedPathToEnd(TerminatedPaths);
  768. TerminatedPath Result = TerminatedPaths.pop_back_val();
  769. return {Result, std::move(TerminatedPaths)};
  770. }
  771. MemoryAccess *DefChainEnd = nullptr;
  772. SmallVector<TerminatedPath, 4> Clobbers;
  773. for (ListIndex Paused : NewPaused) {
  774. UpwardsWalkResult WR = walkToPhiOrClobber(Paths[Paused]);
  775. if (WR.IsKnownClobber)
  776. Clobbers.push_back({WR.Result, Paused});
  777. else
  778. // Micro-opt: If we hit the end of the chain, save it.
  779. DefChainEnd = WR.Result;
  780. }
  781. if (!TerminatedPaths.empty()) {
  782. // If we couldn't find the dominating phi/liveOnEntry in the above loop,
  783. // do it now.
  784. if (!DefChainEnd)
  785. for (auto *MA : def_chain(const_cast<MemoryAccess *>(Target)))
  786. DefChainEnd = MA;
  787. assert(DefChainEnd && "Failed to find dominating phi/liveOnEntry");
  788. // If any of the terminated paths don't dominate the phi we'll try to
  789. // optimize, we need to figure out what they are and quit.
  790. const BasicBlock *ChainBB = DefChainEnd->getBlock();
  791. for (const TerminatedPath &TP : TerminatedPaths) {
  792. // Because we know that DefChainEnd is as "high" as we can go, we
  793. // don't need local dominance checks; BB dominance is sufficient.
  794. if (DT.dominates(ChainBB, TP.Clobber->getBlock()))
  795. Clobbers.push_back(TP);
  796. }
  797. }
  798. // If we have clobbers in the def chain, find the one closest to Current
  799. // and quit.
  800. if (!Clobbers.empty()) {
  801. MoveDominatedPathToEnd(Clobbers);
  802. TerminatedPath Result = Clobbers.pop_back_val();
  803. return {Result, std::move(Clobbers)};
  804. }
  805. assert(all_of(NewPaused,
  806. [&](ListIndex I) { return Paths[I].Last == DefChainEnd; }));
  807. // Because liveOnEntry is a clobber, this must be a phi.
  808. auto *DefChainPhi = cast<MemoryPhi>(DefChainEnd);
  809. PriorPathsSize = Paths.size();
  810. PausedSearches.clear();
  811. for (ListIndex I : NewPaused)
  812. addSearches(DefChainPhi, PausedSearches, I);
  813. NewPaused.clear();
  814. Current = DefChainPhi;
  815. }
  816. }
  817. void verifyOptResult(const OptznResult &R) const {
  818. assert(all_of(R.OtherClobbers, [&](const TerminatedPath &P) {
  819. return MSSA.dominates(P.Clobber, R.PrimaryClobber.Clobber);
  820. }));
  821. }
  822. void resetPhiOptznState() {
  823. Paths.clear();
  824. VisitedPhis.clear();
  825. PerformedPhiTranslation = false;
  826. }
  827. public:
  828. ClobberWalker(const MemorySSA &MSSA, AliasAnalysisType &AA, DominatorTree &DT)
  829. : MSSA(MSSA), AA(AA), DT(DT) {}
  830. AliasAnalysisType *getAA() { return &AA; }
  831. /// Finds the nearest clobber for the given query, optimizing phis if
  832. /// possible.
  833. MemoryAccess *findClobber(MemoryAccess *Start, UpwardsMemoryQuery &Q,
  834. unsigned &UpWalkLimit) {
  835. Query = &Q;
  836. UpwardWalkLimit = &UpWalkLimit;
  837. // Starting limit must be > 0.
  838. if (!UpWalkLimit)
  839. UpWalkLimit++;
  840. MemoryAccess *Current = Start;
  841. // This walker pretends uses don't exist. If we're handed one, silently grab
  842. // its def. (This has the nice side-effect of ensuring we never cache uses)
  843. if (auto *MU = dyn_cast<MemoryUse>(Start))
  844. Current = MU->getDefiningAccess();
  845. DefPath FirstDesc(Q.StartingLoc, Current, Current, None);
  846. // Fast path for the overly-common case (no crazy phi optimization
  847. // necessary)
  848. UpwardsWalkResult WalkResult = walkToPhiOrClobber(FirstDesc);
  849. MemoryAccess *Result;
  850. if (WalkResult.IsKnownClobber) {
  851. Result = WalkResult.Result;
  852. Q.AR = WalkResult.AR;
  853. } else {
  854. OptznResult OptRes = tryOptimizePhi(cast<MemoryPhi>(FirstDesc.Last),
  855. Current, Q.StartingLoc);
  856. verifyOptResult(OptRes);
  857. resetPhiOptznState();
  858. Result = OptRes.PrimaryClobber.Clobber;
  859. }
  860. #ifdef EXPENSIVE_CHECKS
  861. if (!Q.SkipSelfAccess && *UpwardWalkLimit > 0)
  862. checkClobberSanity(Current, Result, Q.StartingLoc, MSSA, Q, AA);
  863. #endif
  864. return Result;
  865. }
  866. };
  867. struct RenamePassData {
  868. DomTreeNode *DTN;
  869. DomTreeNode::const_iterator ChildIt;
  870. MemoryAccess *IncomingVal;
  871. RenamePassData(DomTreeNode *D, DomTreeNode::const_iterator It,
  872. MemoryAccess *M)
  873. : DTN(D), ChildIt(It), IncomingVal(M) {}
  874. void swap(RenamePassData &RHS) {
  875. std::swap(DTN, RHS.DTN);
  876. std::swap(ChildIt, RHS.ChildIt);
  877. std::swap(IncomingVal, RHS.IncomingVal);
  878. }
  879. };
  880. } // end anonymous namespace
  881. namespace llvm {
  882. template <class AliasAnalysisType> class MemorySSA::ClobberWalkerBase {
  883. ClobberWalker<AliasAnalysisType> Walker;
  884. MemorySSA *MSSA;
  885. public:
  886. ClobberWalkerBase(MemorySSA *M, AliasAnalysisType *A, DominatorTree *D)
  887. : Walker(*M, *A, *D), MSSA(M) {}
  888. MemoryAccess *getClobberingMemoryAccessBase(MemoryAccess *,
  889. const MemoryLocation &,
  890. unsigned &);
  891. // Third argument (bool), defines whether the clobber search should skip the
  892. // original queried access. If true, there will be a follow-up query searching
  893. // for a clobber access past "self". Note that the Optimized access is not
  894. // updated if a new clobber is found by this SkipSelf search. If this
  895. // additional query becomes heavily used we may decide to cache the result.
  896. // Walker instantiations will decide how to set the SkipSelf bool.
  897. MemoryAccess *getClobberingMemoryAccessBase(MemoryAccess *, unsigned &, bool,
  898. bool UseInvariantGroup = true);
  899. };
  900. /// A MemorySSAWalker that does AA walks to disambiguate accesses. It no
  901. /// longer does caching on its own, but the name has been retained for the
  902. /// moment.
  903. template <class AliasAnalysisType>
  904. class MemorySSA::CachingWalker final : public MemorySSAWalker {
  905. ClobberWalkerBase<AliasAnalysisType> *Walker;
  906. public:
  907. CachingWalker(MemorySSA *M, ClobberWalkerBase<AliasAnalysisType> *W)
  908. : MemorySSAWalker(M), Walker(W) {}
  909. ~CachingWalker() override = default;
  910. using MemorySSAWalker::getClobberingMemoryAccess;
  911. MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA, unsigned &UWL) {
  912. return Walker->getClobberingMemoryAccessBase(MA, UWL, false);
  913. }
  914. MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA,
  915. const MemoryLocation &Loc,
  916. unsigned &UWL) {
  917. return Walker->getClobberingMemoryAccessBase(MA, Loc, UWL);
  918. }
  919. // This method is not accessible outside of this file.
  920. MemoryAccess *getClobberingMemoryAccessWithoutInvariantGroup(MemoryAccess *MA,
  921. unsigned &UWL) {
  922. return Walker->getClobberingMemoryAccessBase(MA, UWL, false, false);
  923. }
  924. MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA) override {
  925. unsigned UpwardWalkLimit = MaxCheckLimit;
  926. return getClobberingMemoryAccess(MA, UpwardWalkLimit);
  927. }
  928. MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA,
  929. const MemoryLocation &Loc) override {
  930. unsigned UpwardWalkLimit = MaxCheckLimit;
  931. return getClobberingMemoryAccess(MA, Loc, UpwardWalkLimit);
  932. }
  933. void invalidateInfo(MemoryAccess *MA) override {
  934. if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
  935. MUD->resetOptimized();
  936. }
  937. };
  938. template <class AliasAnalysisType>
  939. class MemorySSA::SkipSelfWalker final : public MemorySSAWalker {
  940. ClobberWalkerBase<AliasAnalysisType> *Walker;
  941. public:
  942. SkipSelfWalker(MemorySSA *M, ClobberWalkerBase<AliasAnalysisType> *W)
  943. : MemorySSAWalker(M), Walker(W) {}
  944. ~SkipSelfWalker() override = default;
  945. using MemorySSAWalker::getClobberingMemoryAccess;
  946. MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA, unsigned &UWL) {
  947. return Walker->getClobberingMemoryAccessBase(MA, UWL, true);
  948. }
  949. MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA,
  950. const MemoryLocation &Loc,
  951. unsigned &UWL) {
  952. return Walker->getClobberingMemoryAccessBase(MA, Loc, UWL);
  953. }
  954. MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA) override {
  955. unsigned UpwardWalkLimit = MaxCheckLimit;
  956. return getClobberingMemoryAccess(MA, UpwardWalkLimit);
  957. }
  958. MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA,
  959. const MemoryLocation &Loc) override {
  960. unsigned UpwardWalkLimit = MaxCheckLimit;
  961. return getClobberingMemoryAccess(MA, Loc, UpwardWalkLimit);
  962. }
  963. void invalidateInfo(MemoryAccess *MA) override {
  964. if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
  965. MUD->resetOptimized();
  966. }
  967. };
  968. } // end namespace llvm
  969. void MemorySSA::renameSuccessorPhis(BasicBlock *BB, MemoryAccess *IncomingVal,
  970. bool RenameAllUses) {
  971. // Pass through values to our successors
  972. for (const BasicBlock *S : successors(BB)) {
  973. auto It = PerBlockAccesses.find(S);
  974. // Rename the phi nodes in our successor block
  975. if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
  976. continue;
  977. AccessList *Accesses = It->second.get();
  978. auto *Phi = cast<MemoryPhi>(&Accesses->front());
  979. if (RenameAllUses) {
  980. bool ReplacementDone = false;
  981. for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I)
  982. if (Phi->getIncomingBlock(I) == BB) {
  983. Phi->setIncomingValue(I, IncomingVal);
  984. ReplacementDone = true;
  985. }
  986. (void) ReplacementDone;
  987. assert(ReplacementDone && "Incomplete phi during partial rename");
  988. } else
  989. Phi->addIncoming(IncomingVal, BB);
  990. }
  991. }
  992. /// Rename a single basic block into MemorySSA form.
  993. /// Uses the standard SSA renaming algorithm.
  994. /// \returns The new incoming value.
  995. MemoryAccess *MemorySSA::renameBlock(BasicBlock *BB, MemoryAccess *IncomingVal,
  996. bool RenameAllUses) {
  997. auto It = PerBlockAccesses.find(BB);
  998. // Skip most processing if the list is empty.
  999. if (It != PerBlockAccesses.end()) {
  1000. AccessList *Accesses = It->second.get();
  1001. for (MemoryAccess &L : *Accesses) {
  1002. if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(&L)) {
  1003. if (MUD->getDefiningAccess() == nullptr || RenameAllUses)
  1004. MUD->setDefiningAccess(IncomingVal);
  1005. if (isa<MemoryDef>(&L))
  1006. IncomingVal = &L;
  1007. } else {
  1008. IncomingVal = &L;
  1009. }
  1010. }
  1011. }
  1012. return IncomingVal;
  1013. }
  1014. /// This is the standard SSA renaming algorithm.
  1015. ///
  1016. /// We walk the dominator tree in preorder, renaming accesses, and then filling
  1017. /// in phi nodes in our successors.
  1018. void MemorySSA::renamePass(DomTreeNode *Root, MemoryAccess *IncomingVal,
  1019. SmallPtrSetImpl<BasicBlock *> &Visited,
  1020. bool SkipVisited, bool RenameAllUses) {
  1021. assert(Root && "Trying to rename accesses in an unreachable block");
  1022. SmallVector<RenamePassData, 32> WorkStack;
  1023. // Skip everything if we already renamed this block and we are skipping.
  1024. // Note: You can't sink this into the if, because we need it to occur
  1025. // regardless of whether we skip blocks or not.
  1026. bool AlreadyVisited = !Visited.insert(Root->getBlock()).second;
  1027. if (SkipVisited && AlreadyVisited)
  1028. return;
  1029. IncomingVal = renameBlock(Root->getBlock(), IncomingVal, RenameAllUses);
  1030. renameSuccessorPhis(Root->getBlock(), IncomingVal, RenameAllUses);
  1031. WorkStack.push_back({Root, Root->begin(), IncomingVal});
  1032. while (!WorkStack.empty()) {
  1033. DomTreeNode *Node = WorkStack.back().DTN;
  1034. DomTreeNode::const_iterator ChildIt = WorkStack.back().ChildIt;
  1035. IncomingVal = WorkStack.back().IncomingVal;
  1036. if (ChildIt == Node->end()) {
  1037. WorkStack.pop_back();
  1038. } else {
  1039. DomTreeNode *Child = *ChildIt;
  1040. ++WorkStack.back().ChildIt;
  1041. BasicBlock *BB = Child->getBlock();
  1042. // Note: You can't sink this into the if, because we need it to occur
  1043. // regardless of whether we skip blocks or not.
  1044. AlreadyVisited = !Visited.insert(BB).second;
  1045. if (SkipVisited && AlreadyVisited) {
  1046. // We already visited this during our renaming, which can happen when
  1047. // being asked to rename multiple blocks. Figure out the incoming val,
  1048. // which is the last def.
  1049. // Incoming value can only change if there is a block def, and in that
  1050. // case, it's the last block def in the list.
  1051. if (auto *BlockDefs = getWritableBlockDefs(BB))
  1052. IncomingVal = &*BlockDefs->rbegin();
  1053. } else
  1054. IncomingVal = renameBlock(BB, IncomingVal, RenameAllUses);
  1055. renameSuccessorPhis(BB, IncomingVal, RenameAllUses);
  1056. WorkStack.push_back({Child, Child->begin(), IncomingVal});
  1057. }
  1058. }
  1059. }
  1060. /// This handles unreachable block accesses by deleting phi nodes in
  1061. /// unreachable blocks, and marking all other unreachable MemoryAccess's as
  1062. /// being uses of the live on entry definition.
  1063. void MemorySSA::markUnreachableAsLiveOnEntry(BasicBlock *BB) {
  1064. assert(!DT->isReachableFromEntry(BB) &&
  1065. "Reachable block found while handling unreachable blocks");
  1066. // Make sure phi nodes in our reachable successors end up with a
  1067. // LiveOnEntryDef for our incoming edge, even though our block is forward
  1068. // unreachable. We could just disconnect these blocks from the CFG fully,
  1069. // but we do not right now.
  1070. for (const BasicBlock *S : successors(BB)) {
  1071. if (!DT->isReachableFromEntry(S))
  1072. continue;
  1073. auto It = PerBlockAccesses.find(S);
  1074. // Rename the phi nodes in our successor block
  1075. if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
  1076. continue;
  1077. AccessList *Accesses = It->second.get();
  1078. auto *Phi = cast<MemoryPhi>(&Accesses->front());
  1079. Phi->addIncoming(LiveOnEntryDef.get(), BB);
  1080. }
  1081. auto It = PerBlockAccesses.find(BB);
  1082. if (It == PerBlockAccesses.end())
  1083. return;
  1084. auto &Accesses = It->second;
  1085. for (auto AI = Accesses->begin(), AE = Accesses->end(); AI != AE;) {
  1086. auto Next = std::next(AI);
  1087. // If we have a phi, just remove it. We are going to replace all
  1088. // users with live on entry.
  1089. if (auto *UseOrDef = dyn_cast<MemoryUseOrDef>(AI))
  1090. UseOrDef->setDefiningAccess(LiveOnEntryDef.get());
  1091. else
  1092. Accesses->erase(AI);
  1093. AI = Next;
  1094. }
  1095. }
  1096. MemorySSA::MemorySSA(Function &Func, AliasAnalysis *AA, DominatorTree *DT)
  1097. : DT(DT), F(Func), LiveOnEntryDef(nullptr), Walker(nullptr),
  1098. SkipWalker(nullptr) {
  1099. // Build MemorySSA using a batch alias analysis. This reuses the internal
  1100. // state that AA collects during an alias()/getModRefInfo() call. This is
  1101. // safe because there are no CFG changes while building MemorySSA and can
  1102. // significantly reduce the time spent by the compiler in AA, because we will
  1103. // make queries about all the instructions in the Function.
  1104. assert(AA && "No alias analysis?");
  1105. BatchAAResults BatchAA(*AA);
  1106. buildMemorySSA(BatchAA);
  1107. // Intentionally leave AA to nullptr while building so we don't accidently
  1108. // use non-batch AliasAnalysis.
  1109. this->AA = AA;
  1110. // Also create the walker here.
  1111. getWalker();
  1112. }
  1113. MemorySSA::~MemorySSA() {
  1114. // Drop all our references
  1115. for (const auto &Pair : PerBlockAccesses)
  1116. for (MemoryAccess &MA : *Pair.second)
  1117. MA.dropAllReferences();
  1118. }
  1119. MemorySSA::AccessList *MemorySSA::getOrCreateAccessList(const BasicBlock *BB) {
  1120. auto Res = PerBlockAccesses.insert(std::make_pair(BB, nullptr));
  1121. if (Res.second)
  1122. Res.first->second = std::make_unique<AccessList>();
  1123. return Res.first->second.get();
  1124. }
  1125. MemorySSA::DefsList *MemorySSA::getOrCreateDefsList(const BasicBlock *BB) {
  1126. auto Res = PerBlockDefs.insert(std::make_pair(BB, nullptr));
  1127. if (Res.second)
  1128. Res.first->second = std::make_unique<DefsList>();
  1129. return Res.first->second.get();
  1130. }
  1131. namespace llvm {
  1132. /// This class is a batch walker of all MemoryUse's in the program, and points
  1133. /// their defining access at the thing that actually clobbers them. Because it
  1134. /// is a batch walker that touches everything, it does not operate like the
  1135. /// other walkers. This walker is basically performing a top-down SSA renaming
  1136. /// pass, where the version stack is used as the cache. This enables it to be
  1137. /// significantly more time and memory efficient than using the regular walker,
  1138. /// which is walking bottom-up.
  1139. class MemorySSA::OptimizeUses {
  1140. public:
  1141. OptimizeUses(MemorySSA *MSSA, CachingWalker<BatchAAResults> *Walker,
  1142. BatchAAResults *BAA, DominatorTree *DT)
  1143. : MSSA(MSSA), Walker(Walker), AA(BAA), DT(DT) {}
  1144. void optimizeUses();
  1145. private:
  1146. /// This represents where a given memorylocation is in the stack.
  1147. struct MemlocStackInfo {
  1148. // This essentially is keeping track of versions of the stack. Whenever
  1149. // the stack changes due to pushes or pops, these versions increase.
  1150. unsigned long StackEpoch;
  1151. unsigned long PopEpoch;
  1152. // This is the lower bound of places on the stack to check. It is equal to
  1153. // the place the last stack walk ended.
  1154. // Note: Correctness depends on this being initialized to 0, which densemap
  1155. // does
  1156. unsigned long LowerBound;
  1157. const BasicBlock *LowerBoundBlock;
  1158. // This is where the last walk for this memory location ended.
  1159. unsigned long LastKill;
  1160. bool LastKillValid;
  1161. Optional<AliasResult> AR;
  1162. };
  1163. void optimizeUsesInBlock(const BasicBlock *, unsigned long &, unsigned long &,
  1164. SmallVectorImpl<MemoryAccess *> &,
  1165. DenseMap<MemoryLocOrCall, MemlocStackInfo> &);
  1166. MemorySSA *MSSA;
  1167. CachingWalker<BatchAAResults> *Walker;
  1168. BatchAAResults *AA;
  1169. DominatorTree *DT;
  1170. };
  1171. } // end namespace llvm
  1172. /// Optimize the uses in a given block This is basically the SSA renaming
  1173. /// algorithm, with one caveat: We are able to use a single stack for all
  1174. /// MemoryUses. This is because the set of *possible* reaching MemoryDefs is
  1175. /// the same for every MemoryUse. The *actual* clobbering MemoryDef is just
  1176. /// going to be some position in that stack of possible ones.
  1177. ///
  1178. /// We track the stack positions that each MemoryLocation needs
  1179. /// to check, and last ended at. This is because we only want to check the
  1180. /// things that changed since last time. The same MemoryLocation should
  1181. /// get clobbered by the same store (getModRefInfo does not use invariantness or
  1182. /// things like this, and if they start, we can modify MemoryLocOrCall to
  1183. /// include relevant data)
  1184. void MemorySSA::OptimizeUses::optimizeUsesInBlock(
  1185. const BasicBlock *BB, unsigned long &StackEpoch, unsigned long &PopEpoch,
  1186. SmallVectorImpl<MemoryAccess *> &VersionStack,
  1187. DenseMap<MemoryLocOrCall, MemlocStackInfo> &LocStackInfo) {
  1188. /// If no accesses, nothing to do.
  1189. MemorySSA::AccessList *Accesses = MSSA->getWritableBlockAccesses(BB);
  1190. if (Accesses == nullptr)
  1191. return;
  1192. // Pop everything that doesn't dominate the current block off the stack,
  1193. // increment the PopEpoch to account for this.
  1194. while (true) {
  1195. assert(
  1196. !VersionStack.empty() &&
  1197. "Version stack should have liveOnEntry sentinel dominating everything");
  1198. BasicBlock *BackBlock = VersionStack.back()->getBlock();
  1199. if (DT->dominates(BackBlock, BB))
  1200. break;
  1201. while (VersionStack.back()->getBlock() == BackBlock)
  1202. VersionStack.pop_back();
  1203. ++PopEpoch;
  1204. }
  1205. for (MemoryAccess &MA : *Accesses) {
  1206. auto *MU = dyn_cast<MemoryUse>(&MA);
  1207. if (!MU) {
  1208. VersionStack.push_back(&MA);
  1209. ++StackEpoch;
  1210. continue;
  1211. }
  1212. if (isUseTriviallyOptimizableToLiveOnEntry(*AA, MU->getMemoryInst())) {
  1213. MU->setDefiningAccess(MSSA->getLiveOnEntryDef(), true, None);
  1214. continue;
  1215. }
  1216. MemoryLocOrCall UseMLOC(MU);
  1217. auto &LocInfo = LocStackInfo[UseMLOC];
  1218. // If the pop epoch changed, it means we've removed stuff from top of
  1219. // stack due to changing blocks. We may have to reset the lower bound or
  1220. // last kill info.
  1221. if (LocInfo.PopEpoch != PopEpoch) {
  1222. LocInfo.PopEpoch = PopEpoch;
  1223. LocInfo.StackEpoch = StackEpoch;
  1224. // If the lower bound was in something that no longer dominates us, we
  1225. // have to reset it.
  1226. // We can't simply track stack size, because the stack may have had
  1227. // pushes/pops in the meantime.
  1228. // XXX: This is non-optimal, but only is slower cases with heavily
  1229. // branching dominator trees. To get the optimal number of queries would
  1230. // be to make lowerbound and lastkill a per-loc stack, and pop it until
  1231. // the top of that stack dominates us. This does not seem worth it ATM.
  1232. // A much cheaper optimization would be to always explore the deepest
  1233. // branch of the dominator tree first. This will guarantee this resets on
  1234. // the smallest set of blocks.
  1235. if (LocInfo.LowerBoundBlock && LocInfo.LowerBoundBlock != BB &&
  1236. !DT->dominates(LocInfo.LowerBoundBlock, BB)) {
  1237. // Reset the lower bound of things to check.
  1238. // TODO: Some day we should be able to reset to last kill, rather than
  1239. // 0.
  1240. LocInfo.LowerBound = 0;
  1241. LocInfo.LowerBoundBlock = VersionStack[0]->getBlock();
  1242. LocInfo.LastKillValid = false;
  1243. }
  1244. } else if (LocInfo.StackEpoch != StackEpoch) {
  1245. // If all that has changed is the StackEpoch, we only have to check the
  1246. // new things on the stack, because we've checked everything before. In
  1247. // this case, the lower bound of things to check remains the same.
  1248. LocInfo.PopEpoch = PopEpoch;
  1249. LocInfo.StackEpoch = StackEpoch;
  1250. }
  1251. if (!LocInfo.LastKillValid) {
  1252. LocInfo.LastKill = VersionStack.size() - 1;
  1253. LocInfo.LastKillValid = true;
  1254. LocInfo.AR = AliasResult::MayAlias;
  1255. }
  1256. // At this point, we should have corrected last kill and LowerBound to be
  1257. // in bounds.
  1258. assert(LocInfo.LowerBound < VersionStack.size() &&
  1259. "Lower bound out of range");
  1260. assert(LocInfo.LastKill < VersionStack.size() &&
  1261. "Last kill info out of range");
  1262. // In any case, the new upper bound is the top of the stack.
  1263. unsigned long UpperBound = VersionStack.size() - 1;
  1264. if (UpperBound - LocInfo.LowerBound > MaxCheckLimit) {
  1265. LLVM_DEBUG(dbgs() << "MemorySSA skipping optimization of " << *MU << " ("
  1266. << *(MU->getMemoryInst()) << ")"
  1267. << " because there are "
  1268. << UpperBound - LocInfo.LowerBound
  1269. << " stores to disambiguate\n");
  1270. // Because we did not walk, LastKill is no longer valid, as this may
  1271. // have been a kill.
  1272. LocInfo.LastKillValid = false;
  1273. continue;
  1274. }
  1275. bool FoundClobberResult = false;
  1276. unsigned UpwardWalkLimit = MaxCheckLimit;
  1277. while (UpperBound > LocInfo.LowerBound) {
  1278. if (isa<MemoryPhi>(VersionStack[UpperBound])) {
  1279. // For phis, use the walker, see where we ended up, go there.
  1280. // The invariant.group handling in MemorySSA is ad-hoc and doesn't
  1281. // support updates, so don't use it to optimize uses.
  1282. MemoryAccess *Result =
  1283. Walker->getClobberingMemoryAccessWithoutInvariantGroup(
  1284. MU, UpwardWalkLimit);
  1285. // We are guaranteed to find it or something is wrong.
  1286. while (VersionStack[UpperBound] != Result) {
  1287. assert(UpperBound != 0);
  1288. --UpperBound;
  1289. }
  1290. FoundClobberResult = true;
  1291. break;
  1292. }
  1293. MemoryDef *MD = cast<MemoryDef>(VersionStack[UpperBound]);
  1294. ClobberAlias CA = instructionClobbersQuery(MD, MU, UseMLOC, *AA);
  1295. if (CA.IsClobber) {
  1296. FoundClobberResult = true;
  1297. LocInfo.AR = CA.AR;
  1298. break;
  1299. }
  1300. --UpperBound;
  1301. }
  1302. // Note: Phis always have AliasResult AR set to MayAlias ATM.
  1303. // At the end of this loop, UpperBound is either a clobber, or lower bound
  1304. // PHI walking may cause it to be < LowerBound, and in fact, < LastKill.
  1305. if (FoundClobberResult || UpperBound < LocInfo.LastKill) {
  1306. // We were last killed now by where we got to
  1307. if (MSSA->isLiveOnEntryDef(VersionStack[UpperBound]))
  1308. LocInfo.AR = None;
  1309. MU->setDefiningAccess(VersionStack[UpperBound], true, LocInfo.AR);
  1310. LocInfo.LastKill = UpperBound;
  1311. } else {
  1312. // Otherwise, we checked all the new ones, and now we know we can get to
  1313. // LastKill.
  1314. MU->setDefiningAccess(VersionStack[LocInfo.LastKill], true, LocInfo.AR);
  1315. }
  1316. LocInfo.LowerBound = VersionStack.size() - 1;
  1317. LocInfo.LowerBoundBlock = BB;
  1318. }
  1319. }
  1320. /// Optimize uses to point to their actual clobbering definitions.
  1321. void MemorySSA::OptimizeUses::optimizeUses() {
  1322. SmallVector<MemoryAccess *, 16> VersionStack;
  1323. DenseMap<MemoryLocOrCall, MemlocStackInfo> LocStackInfo;
  1324. VersionStack.push_back(MSSA->getLiveOnEntryDef());
  1325. unsigned long StackEpoch = 1;
  1326. unsigned long PopEpoch = 1;
  1327. // We perform a non-recursive top-down dominator tree walk.
  1328. for (const auto *DomNode : depth_first(DT->getRootNode()))
  1329. optimizeUsesInBlock(DomNode->getBlock(), StackEpoch, PopEpoch, VersionStack,
  1330. LocStackInfo);
  1331. }
  1332. void MemorySSA::placePHINodes(
  1333. const SmallPtrSetImpl<BasicBlock *> &DefiningBlocks) {
  1334. // Determine where our MemoryPhi's should go
  1335. ForwardIDFCalculator IDFs(*DT);
  1336. IDFs.setDefiningBlocks(DefiningBlocks);
  1337. SmallVector<BasicBlock *, 32> IDFBlocks;
  1338. IDFs.calculate(IDFBlocks);
  1339. // Now place MemoryPhi nodes.
  1340. for (auto &BB : IDFBlocks)
  1341. createMemoryPhi(BB);
  1342. }
  1343. void MemorySSA::buildMemorySSA(BatchAAResults &BAA) {
  1344. // We create an access to represent "live on entry", for things like
  1345. // arguments or users of globals, where the memory they use is defined before
  1346. // the beginning of the function. We do not actually insert it into the IR.
  1347. // We do not define a live on exit for the immediate uses, and thus our
  1348. // semantics do *not* imply that something with no immediate uses can simply
  1349. // be removed.
  1350. BasicBlock &StartingPoint = F.getEntryBlock();
  1351. LiveOnEntryDef.reset(new MemoryDef(F.getContext(), nullptr, nullptr,
  1352. &StartingPoint, NextID++));
  1353. // We maintain lists of memory accesses per-block, trading memory for time. We
  1354. // could just look up the memory access for every possible instruction in the
  1355. // stream.
  1356. SmallPtrSet<BasicBlock *, 32> DefiningBlocks;
  1357. // Go through each block, figure out where defs occur, and chain together all
  1358. // the accesses.
  1359. for (BasicBlock &B : F) {
  1360. bool InsertIntoDef = false;
  1361. AccessList *Accesses = nullptr;
  1362. DefsList *Defs = nullptr;
  1363. for (Instruction &I : B) {
  1364. MemoryUseOrDef *MUD = createNewAccess(&I, &BAA);
  1365. if (!MUD)
  1366. continue;
  1367. if (!Accesses)
  1368. Accesses = getOrCreateAccessList(&B);
  1369. Accesses->push_back(MUD);
  1370. if (isa<MemoryDef>(MUD)) {
  1371. InsertIntoDef = true;
  1372. if (!Defs)
  1373. Defs = getOrCreateDefsList(&B);
  1374. Defs->push_back(*MUD);
  1375. }
  1376. }
  1377. if (InsertIntoDef)
  1378. DefiningBlocks.insert(&B);
  1379. }
  1380. placePHINodes(DefiningBlocks);
  1381. // Now do regular SSA renaming on the MemoryDef/MemoryUse. Visited will get
  1382. // filled in with all blocks.
  1383. SmallPtrSet<BasicBlock *, 16> Visited;
  1384. renamePass(DT->getRootNode(), LiveOnEntryDef.get(), Visited);
  1385. ClobberWalkerBase<BatchAAResults> WalkerBase(this, &BAA, DT);
  1386. CachingWalker<BatchAAResults> WalkerLocal(this, &WalkerBase);
  1387. OptimizeUses(this, &WalkerLocal, &BAA, DT).optimizeUses();
  1388. // Mark the uses in unreachable blocks as live on entry, so that they go
  1389. // somewhere.
  1390. for (auto &BB : F)
  1391. if (!Visited.count(&BB))
  1392. markUnreachableAsLiveOnEntry(&BB);
  1393. }
  1394. MemorySSAWalker *MemorySSA::getWalker() { return getWalkerImpl(); }
  1395. MemorySSA::CachingWalker<AliasAnalysis> *MemorySSA::getWalkerImpl() {
  1396. if (Walker)
  1397. return Walker.get();
  1398. if (!WalkerBase)
  1399. WalkerBase =
  1400. std::make_unique<ClobberWalkerBase<AliasAnalysis>>(this, AA, DT);
  1401. Walker =
  1402. std::make_unique<CachingWalker<AliasAnalysis>>(this, WalkerBase.get());
  1403. return Walker.get();
  1404. }
  1405. MemorySSAWalker *MemorySSA::getSkipSelfWalker() {
  1406. if (SkipWalker)
  1407. return SkipWalker.get();
  1408. if (!WalkerBase)
  1409. WalkerBase =
  1410. std::make_unique<ClobberWalkerBase<AliasAnalysis>>(this, AA, DT);
  1411. SkipWalker =
  1412. std::make_unique<SkipSelfWalker<AliasAnalysis>>(this, WalkerBase.get());
  1413. return SkipWalker.get();
  1414. }
  1415. // This is a helper function used by the creation routines. It places NewAccess
  1416. // into the access and defs lists for a given basic block, at the given
  1417. // insertion point.
  1418. void MemorySSA::insertIntoListsForBlock(MemoryAccess *NewAccess,
  1419. const BasicBlock *BB,
  1420. InsertionPlace Point) {
  1421. auto *Accesses = getOrCreateAccessList(BB);
  1422. if (Point == Beginning) {
  1423. // If it's a phi node, it goes first, otherwise, it goes after any phi
  1424. // nodes.
  1425. if (isa<MemoryPhi>(NewAccess)) {
  1426. Accesses->push_front(NewAccess);
  1427. auto *Defs = getOrCreateDefsList(BB);
  1428. Defs->push_front(*NewAccess);
  1429. } else {
  1430. auto AI = find_if_not(
  1431. *Accesses, [](const MemoryAccess &MA) { return isa<MemoryPhi>(MA); });
  1432. Accesses->insert(AI, NewAccess);
  1433. if (!isa<MemoryUse>(NewAccess)) {
  1434. auto *Defs = getOrCreateDefsList(BB);
  1435. auto DI = find_if_not(
  1436. *Defs, [](const MemoryAccess &MA) { return isa<MemoryPhi>(MA); });
  1437. Defs->insert(DI, *NewAccess);
  1438. }
  1439. }
  1440. } else {
  1441. Accesses->push_back(NewAccess);
  1442. if (!isa<MemoryUse>(NewAccess)) {
  1443. auto *Defs = getOrCreateDefsList(BB);
  1444. Defs->push_back(*NewAccess);
  1445. }
  1446. }
  1447. BlockNumberingValid.erase(BB);
  1448. }
  1449. void MemorySSA::insertIntoListsBefore(MemoryAccess *What, const BasicBlock *BB,
  1450. AccessList::iterator InsertPt) {
  1451. auto *Accesses = getWritableBlockAccesses(BB);
  1452. bool WasEnd = InsertPt == Accesses->end();
  1453. Accesses->insert(AccessList::iterator(InsertPt), What);
  1454. if (!isa<MemoryUse>(What)) {
  1455. auto *Defs = getOrCreateDefsList(BB);
  1456. // If we got asked to insert at the end, we have an easy job, just shove it
  1457. // at the end. If we got asked to insert before an existing def, we also get
  1458. // an iterator. If we got asked to insert before a use, we have to hunt for
  1459. // the next def.
  1460. if (WasEnd) {
  1461. Defs->push_back(*What);
  1462. } else if (isa<MemoryDef>(InsertPt)) {
  1463. Defs->insert(InsertPt->getDefsIterator(), *What);
  1464. } else {
  1465. while (InsertPt != Accesses->end() && !isa<MemoryDef>(InsertPt))
  1466. ++InsertPt;
  1467. // Either we found a def, or we are inserting at the end
  1468. if (InsertPt == Accesses->end())
  1469. Defs->push_back(*What);
  1470. else
  1471. Defs->insert(InsertPt->getDefsIterator(), *What);
  1472. }
  1473. }
  1474. BlockNumberingValid.erase(BB);
  1475. }
  1476. void MemorySSA::prepareForMoveTo(MemoryAccess *What, BasicBlock *BB) {
  1477. // Keep it in the lookup tables, remove from the lists
  1478. removeFromLists(What, false);
  1479. // Note that moving should implicitly invalidate the optimized state of a
  1480. // MemoryUse (and Phis can't be optimized). However, it doesn't do so for a
  1481. // MemoryDef.
  1482. if (auto *MD = dyn_cast<MemoryDef>(What))
  1483. MD->resetOptimized();
  1484. What->setBlock(BB);
  1485. }
  1486. // Move What before Where in the IR. The end result is that What will belong to
  1487. // the right lists and have the right Block set, but will not otherwise be
  1488. // correct. It will not have the right defining access, and if it is a def,
  1489. // things below it will not properly be updated.
  1490. void MemorySSA::moveTo(MemoryUseOrDef *What, BasicBlock *BB,
  1491. AccessList::iterator Where) {
  1492. prepareForMoveTo(What, BB);
  1493. insertIntoListsBefore(What, BB, Where);
  1494. }
  1495. void MemorySSA::moveTo(MemoryAccess *What, BasicBlock *BB,
  1496. InsertionPlace Point) {
  1497. if (isa<MemoryPhi>(What)) {
  1498. assert(Point == Beginning &&
  1499. "Can only move a Phi at the beginning of the block");
  1500. // Update lookup table entry
  1501. ValueToMemoryAccess.erase(What->getBlock());
  1502. bool Inserted = ValueToMemoryAccess.insert({BB, What}).second;
  1503. (void)Inserted;
  1504. assert(Inserted && "Cannot move a Phi to a block that already has one");
  1505. }
  1506. prepareForMoveTo(What, BB);
  1507. insertIntoListsForBlock(What, BB, Point);
  1508. }
  1509. MemoryPhi *MemorySSA::createMemoryPhi(BasicBlock *BB) {
  1510. assert(!getMemoryAccess(BB) && "MemoryPhi already exists for this BB");
  1511. MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
  1512. // Phi's always are placed at the front of the block.
  1513. insertIntoListsForBlock(Phi, BB, Beginning);
  1514. ValueToMemoryAccess[BB] = Phi;
  1515. return Phi;
  1516. }
  1517. MemoryUseOrDef *MemorySSA::createDefinedAccess(Instruction *I,
  1518. MemoryAccess *Definition,
  1519. const MemoryUseOrDef *Template,
  1520. bool CreationMustSucceed) {
  1521. assert(!isa<PHINode>(I) && "Cannot create a defined access for a PHI");
  1522. MemoryUseOrDef *NewAccess = createNewAccess(I, AA, Template);
  1523. if (CreationMustSucceed)
  1524. assert(NewAccess != nullptr && "Tried to create a memory access for a "
  1525. "non-memory touching instruction");
  1526. if (NewAccess) {
  1527. assert((!Definition || !isa<MemoryUse>(Definition)) &&
  1528. "A use cannot be a defining access");
  1529. NewAccess->setDefiningAccess(Definition);
  1530. }
  1531. return NewAccess;
  1532. }
  1533. // Return true if the instruction has ordering constraints.
  1534. // Note specifically that this only considers stores and loads
  1535. // because others are still considered ModRef by getModRefInfo.
  1536. static inline bool isOrdered(const Instruction *I) {
  1537. if (auto *SI = dyn_cast<StoreInst>(I)) {
  1538. if (!SI->isUnordered())
  1539. return true;
  1540. } else if (auto *LI = dyn_cast<LoadInst>(I)) {
  1541. if (!LI->isUnordered())
  1542. return true;
  1543. }
  1544. return false;
  1545. }
  1546. /// Helper function to create new memory accesses
  1547. template <typename AliasAnalysisType>
  1548. MemoryUseOrDef *MemorySSA::createNewAccess(Instruction *I,
  1549. AliasAnalysisType *AAP,
  1550. const MemoryUseOrDef *Template) {
  1551. // The assume intrinsic has a control dependency which we model by claiming
  1552. // that it writes arbitrarily. Debuginfo intrinsics may be considered
  1553. // clobbers when we have a nonstandard AA pipeline. Ignore these fake memory
  1554. // dependencies here.
  1555. // FIXME: Replace this special casing with a more accurate modelling of
  1556. // assume's control dependency.
  1557. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
  1558. switch (II->getIntrinsicID()) {
  1559. default:
  1560. break;
  1561. case Intrinsic::assume:
  1562. case Intrinsic::experimental_noalias_scope_decl:
  1563. case Intrinsic::pseudoprobe:
  1564. return nullptr;
  1565. }
  1566. }
  1567. // Using a nonstandard AA pipelines might leave us with unexpected modref
  1568. // results for I, so add a check to not model instructions that may not read
  1569. // from or write to memory. This is necessary for correctness.
  1570. if (!I->mayReadFromMemory() && !I->mayWriteToMemory())
  1571. return nullptr;
  1572. bool Def, Use;
  1573. if (Template) {
  1574. Def = isa<MemoryDef>(Template);
  1575. Use = isa<MemoryUse>(Template);
  1576. #if !defined(NDEBUG)
  1577. ModRefInfo ModRef = AAP->getModRefInfo(I, None);
  1578. bool DefCheck, UseCheck;
  1579. DefCheck = isModSet(ModRef) || isOrdered(I);
  1580. UseCheck = isRefSet(ModRef);
  1581. assert(Def == DefCheck && (Def || Use == UseCheck) && "Invalid template");
  1582. #endif
  1583. } else {
  1584. // Find out what affect this instruction has on memory.
  1585. ModRefInfo ModRef = AAP->getModRefInfo(I, None);
  1586. // The isOrdered check is used to ensure that volatiles end up as defs
  1587. // (atomics end up as ModRef right now anyway). Until we separate the
  1588. // ordering chain from the memory chain, this enables people to see at least
  1589. // some relative ordering to volatiles. Note that getClobberingMemoryAccess
  1590. // will still give an answer that bypasses other volatile loads. TODO:
  1591. // Separate memory aliasing and ordering into two different chains so that
  1592. // we can precisely represent both "what memory will this read/write/is
  1593. // clobbered by" and "what instructions can I move this past".
  1594. Def = isModSet(ModRef) || isOrdered(I);
  1595. Use = isRefSet(ModRef);
  1596. }
  1597. // It's possible for an instruction to not modify memory at all. During
  1598. // construction, we ignore them.
  1599. if (!Def && !Use)
  1600. return nullptr;
  1601. MemoryUseOrDef *MUD;
  1602. if (Def)
  1603. MUD = new MemoryDef(I->getContext(), nullptr, I, I->getParent(), NextID++);
  1604. else
  1605. MUD = new MemoryUse(I->getContext(), nullptr, I, I->getParent());
  1606. ValueToMemoryAccess[I] = MUD;
  1607. return MUD;
  1608. }
  1609. /// Properly remove \p MA from all of MemorySSA's lookup tables.
  1610. void MemorySSA::removeFromLookups(MemoryAccess *MA) {
  1611. assert(MA->use_empty() &&
  1612. "Trying to remove memory access that still has uses");
  1613. BlockNumbering.erase(MA);
  1614. if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
  1615. MUD->setDefiningAccess(nullptr);
  1616. // Invalidate our walker's cache if necessary
  1617. if (!isa<MemoryUse>(MA))
  1618. getWalker()->invalidateInfo(MA);
  1619. Value *MemoryInst;
  1620. if (const auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
  1621. MemoryInst = MUD->getMemoryInst();
  1622. else
  1623. MemoryInst = MA->getBlock();
  1624. auto VMA = ValueToMemoryAccess.find(MemoryInst);
  1625. if (VMA->second == MA)
  1626. ValueToMemoryAccess.erase(VMA);
  1627. }
  1628. /// Properly remove \p MA from all of MemorySSA's lists.
  1629. ///
  1630. /// Because of the way the intrusive list and use lists work, it is important to
  1631. /// do removal in the right order.
  1632. /// ShouldDelete defaults to true, and will cause the memory access to also be
  1633. /// deleted, not just removed.
  1634. void MemorySSA::removeFromLists(MemoryAccess *MA, bool ShouldDelete) {
  1635. BasicBlock *BB = MA->getBlock();
  1636. // The access list owns the reference, so we erase it from the non-owning list
  1637. // first.
  1638. if (!isa<MemoryUse>(MA)) {
  1639. auto DefsIt = PerBlockDefs.find(BB);
  1640. std::unique_ptr<DefsList> &Defs = DefsIt->second;
  1641. Defs->remove(*MA);
  1642. if (Defs->empty())
  1643. PerBlockDefs.erase(DefsIt);
  1644. }
  1645. // The erase call here will delete it. If we don't want it deleted, we call
  1646. // remove instead.
  1647. auto AccessIt = PerBlockAccesses.find(BB);
  1648. std::unique_ptr<AccessList> &Accesses = AccessIt->second;
  1649. if (ShouldDelete)
  1650. Accesses->erase(MA);
  1651. else
  1652. Accesses->remove(MA);
  1653. if (Accesses->empty()) {
  1654. PerBlockAccesses.erase(AccessIt);
  1655. BlockNumberingValid.erase(BB);
  1656. }
  1657. }
  1658. void MemorySSA::print(raw_ostream &OS) const {
  1659. MemorySSAAnnotatedWriter Writer(this);
  1660. F.print(OS, &Writer);
  1661. }
  1662. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1663. LLVM_DUMP_METHOD void MemorySSA::dump() const { print(dbgs()); }
  1664. #endif
  1665. void MemorySSA::verifyMemorySSA(VerificationLevel VL) const {
  1666. #if !defined(NDEBUG) && defined(EXPENSIVE_CHECKS)
  1667. VL = VerificationLevel::Full;
  1668. #endif
  1669. #ifndef NDEBUG
  1670. verifyOrderingDominationAndDefUses(F, VL);
  1671. verifyDominationNumbers(F);
  1672. if (VL == VerificationLevel::Full)
  1673. verifyPrevDefInPhis(F);
  1674. #endif
  1675. // Previously, the verification used to also verify that the clobberingAccess
  1676. // cached by MemorySSA is the same as the clobberingAccess found at a later
  1677. // query to AA. This does not hold true in general due to the current fragility
  1678. // of BasicAA which has arbitrary caps on the things it analyzes before giving
  1679. // up. As a result, transformations that are correct, will lead to BasicAA
  1680. // returning different Alias answers before and after that transformation.
  1681. // Invalidating MemorySSA is not an option, as the results in BasicAA can be so
  1682. // random, in the worst case we'd need to rebuild MemorySSA from scratch after
  1683. // every transformation, which defeats the purpose of using it. For such an
  1684. // example, see test4 added in D51960.
  1685. }
  1686. void MemorySSA::verifyPrevDefInPhis(Function &F) const {
  1687. for (const BasicBlock &BB : F) {
  1688. if (MemoryPhi *Phi = getMemoryAccess(&BB)) {
  1689. for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I) {
  1690. auto *Pred = Phi->getIncomingBlock(I);
  1691. auto *IncAcc = Phi->getIncomingValue(I);
  1692. // If Pred has no unreachable predecessors, get last def looking at
  1693. // IDoms. If, while walkings IDoms, any of these has an unreachable
  1694. // predecessor, then the incoming def can be any access.
  1695. if (auto *DTNode = DT->getNode(Pred)) {
  1696. while (DTNode) {
  1697. if (auto *DefList = getBlockDefs(DTNode->getBlock())) {
  1698. auto *LastAcc = &*(--DefList->end());
  1699. assert(LastAcc == IncAcc &&
  1700. "Incorrect incoming access into phi.");
  1701. (void)IncAcc;
  1702. (void)LastAcc;
  1703. break;
  1704. }
  1705. DTNode = DTNode->getIDom();
  1706. }
  1707. } else {
  1708. // If Pred has unreachable predecessors, but has at least a Def, the
  1709. // incoming access can be the last Def in Pred, or it could have been
  1710. // optimized to LoE. After an update, though, the LoE may have been
  1711. // replaced by another access, so IncAcc may be any access.
  1712. // If Pred has unreachable predecessors and no Defs, incoming access
  1713. // should be LoE; However, after an update, it may be any access.
  1714. }
  1715. }
  1716. }
  1717. }
  1718. }
  1719. /// Verify that all of the blocks we believe to have valid domination numbers
  1720. /// actually have valid domination numbers.
  1721. void MemorySSA::verifyDominationNumbers(const Function &F) const {
  1722. if (BlockNumberingValid.empty())
  1723. return;
  1724. SmallPtrSet<const BasicBlock *, 16> ValidBlocks = BlockNumberingValid;
  1725. for (const BasicBlock &BB : F) {
  1726. if (!ValidBlocks.count(&BB))
  1727. continue;
  1728. ValidBlocks.erase(&BB);
  1729. const AccessList *Accesses = getBlockAccesses(&BB);
  1730. // It's correct to say an empty block has valid numbering.
  1731. if (!Accesses)
  1732. continue;
  1733. // Block numbering starts at 1.
  1734. unsigned long LastNumber = 0;
  1735. for (const MemoryAccess &MA : *Accesses) {
  1736. auto ThisNumberIter = BlockNumbering.find(&MA);
  1737. assert(ThisNumberIter != BlockNumbering.end() &&
  1738. "MemoryAccess has no domination number in a valid block!");
  1739. unsigned long ThisNumber = ThisNumberIter->second;
  1740. assert(ThisNumber > LastNumber &&
  1741. "Domination numbers should be strictly increasing!");
  1742. (void)LastNumber;
  1743. LastNumber = ThisNumber;
  1744. }
  1745. }
  1746. assert(ValidBlocks.empty() &&
  1747. "All valid BasicBlocks should exist in F -- dangling pointers?");
  1748. }
  1749. /// Verify ordering: the order and existence of MemoryAccesses matches the
  1750. /// order and existence of memory affecting instructions.
  1751. /// Verify domination: each definition dominates all of its uses.
  1752. /// Verify def-uses: the immediate use information - walk all the memory
  1753. /// accesses and verifying that, for each use, it appears in the appropriate
  1754. /// def's use list
  1755. void MemorySSA::verifyOrderingDominationAndDefUses(Function &F,
  1756. VerificationLevel VL) const {
  1757. // Walk all the blocks, comparing what the lookups think and what the access
  1758. // lists think, as well as the order in the blocks vs the order in the access
  1759. // lists.
  1760. SmallVector<MemoryAccess *, 32> ActualAccesses;
  1761. SmallVector<MemoryAccess *, 32> ActualDefs;
  1762. for (BasicBlock &B : F) {
  1763. const AccessList *AL = getBlockAccesses(&B);
  1764. const auto *DL = getBlockDefs(&B);
  1765. MemoryPhi *Phi = getMemoryAccess(&B);
  1766. if (Phi) {
  1767. // Verify ordering.
  1768. ActualAccesses.push_back(Phi);
  1769. ActualDefs.push_back(Phi);
  1770. // Verify domination
  1771. for (const Use &U : Phi->uses()) {
  1772. assert(dominates(Phi, U) && "Memory PHI does not dominate it's uses");
  1773. (void)U;
  1774. }
  1775. // Verify def-uses for full verify.
  1776. if (VL == VerificationLevel::Full) {
  1777. assert(Phi->getNumOperands() == static_cast<unsigned>(std::distance(
  1778. pred_begin(&B), pred_end(&B))) &&
  1779. "Incomplete MemoryPhi Node");
  1780. for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I) {
  1781. verifyUseInDefs(Phi->getIncomingValue(I), Phi);
  1782. assert(is_contained(predecessors(&B), Phi->getIncomingBlock(I)) &&
  1783. "Incoming phi block not a block predecessor");
  1784. }
  1785. }
  1786. }
  1787. for (Instruction &I : B) {
  1788. MemoryUseOrDef *MA = getMemoryAccess(&I);
  1789. assert((!MA || (AL && (isa<MemoryUse>(MA) || DL))) &&
  1790. "We have memory affecting instructions "
  1791. "in this block but they are not in the "
  1792. "access list or defs list");
  1793. if (MA) {
  1794. // Verify ordering.
  1795. ActualAccesses.push_back(MA);
  1796. if (MemoryAccess *MD = dyn_cast<MemoryDef>(MA)) {
  1797. // Verify ordering.
  1798. ActualDefs.push_back(MA);
  1799. // Verify domination.
  1800. for (const Use &U : MD->uses()) {
  1801. assert(dominates(MD, U) &&
  1802. "Memory Def does not dominate it's uses");
  1803. (void)U;
  1804. }
  1805. }
  1806. // Verify def-uses for full verify.
  1807. if (VL == VerificationLevel::Full)
  1808. verifyUseInDefs(MA->getDefiningAccess(), MA);
  1809. }
  1810. }
  1811. // Either we hit the assert, really have no accesses, or we have both
  1812. // accesses and an access list. Same with defs.
  1813. if (!AL && !DL)
  1814. continue;
  1815. // Verify ordering.
  1816. assert(AL->size() == ActualAccesses.size() &&
  1817. "We don't have the same number of accesses in the block as on the "
  1818. "access list");
  1819. assert((DL || ActualDefs.size() == 0) &&
  1820. "Either we should have a defs list, or we should have no defs");
  1821. assert((!DL || DL->size() == ActualDefs.size()) &&
  1822. "We don't have the same number of defs in the block as on the "
  1823. "def list");
  1824. auto ALI = AL->begin();
  1825. auto AAI = ActualAccesses.begin();
  1826. while (ALI != AL->end() && AAI != ActualAccesses.end()) {
  1827. assert(&*ALI == *AAI && "Not the same accesses in the same order");
  1828. ++ALI;
  1829. ++AAI;
  1830. }
  1831. ActualAccesses.clear();
  1832. if (DL) {
  1833. auto DLI = DL->begin();
  1834. auto ADI = ActualDefs.begin();
  1835. while (DLI != DL->end() && ADI != ActualDefs.end()) {
  1836. assert(&*DLI == *ADI && "Not the same defs in the same order");
  1837. ++DLI;
  1838. ++ADI;
  1839. }
  1840. }
  1841. ActualDefs.clear();
  1842. }
  1843. }
  1844. /// Verify the def-use lists in MemorySSA, by verifying that \p Use
  1845. /// appears in the use list of \p Def.
  1846. void MemorySSA::verifyUseInDefs(MemoryAccess *Def, MemoryAccess *Use) const {
  1847. // The live on entry use may cause us to get a NULL def here
  1848. if (!Def)
  1849. assert(isLiveOnEntryDef(Use) &&
  1850. "Null def but use not point to live on entry def");
  1851. else
  1852. assert(is_contained(Def->users(), Use) &&
  1853. "Did not find use in def's use list");
  1854. }
  1855. /// Perform a local numbering on blocks so that instruction ordering can be
  1856. /// determined in constant time.
  1857. /// TODO: We currently just number in order. If we numbered by N, we could
  1858. /// allow at least N-1 sequences of insertBefore or insertAfter (and at least
  1859. /// log2(N) sequences of mixed before and after) without needing to invalidate
  1860. /// the numbering.
  1861. void MemorySSA::renumberBlock(const BasicBlock *B) const {
  1862. // The pre-increment ensures the numbers really start at 1.
  1863. unsigned long CurrentNumber = 0;
  1864. const AccessList *AL = getBlockAccesses(B);
  1865. assert(AL != nullptr && "Asking to renumber an empty block");
  1866. for (const auto &I : *AL)
  1867. BlockNumbering[&I] = ++CurrentNumber;
  1868. BlockNumberingValid.insert(B);
  1869. }
  1870. /// Determine, for two memory accesses in the same block,
  1871. /// whether \p Dominator dominates \p Dominatee.
  1872. /// \returns True if \p Dominator dominates \p Dominatee.
  1873. bool MemorySSA::locallyDominates(const MemoryAccess *Dominator,
  1874. const MemoryAccess *Dominatee) const {
  1875. const BasicBlock *DominatorBlock = Dominator->getBlock();
  1876. assert((DominatorBlock == Dominatee->getBlock()) &&
  1877. "Asking for local domination when accesses are in different blocks!");
  1878. // A node dominates itself.
  1879. if (Dominatee == Dominator)
  1880. return true;
  1881. // When Dominatee is defined on function entry, it is not dominated by another
  1882. // memory access.
  1883. if (isLiveOnEntryDef(Dominatee))
  1884. return false;
  1885. // When Dominator is defined on function entry, it dominates the other memory
  1886. // access.
  1887. if (isLiveOnEntryDef(Dominator))
  1888. return true;
  1889. if (!BlockNumberingValid.count(DominatorBlock))
  1890. renumberBlock(DominatorBlock);
  1891. unsigned long DominatorNum = BlockNumbering.lookup(Dominator);
  1892. // All numbers start with 1
  1893. assert(DominatorNum != 0 && "Block was not numbered properly");
  1894. unsigned long DominateeNum = BlockNumbering.lookup(Dominatee);
  1895. assert(DominateeNum != 0 && "Block was not numbered properly");
  1896. return DominatorNum < DominateeNum;
  1897. }
  1898. bool MemorySSA::dominates(const MemoryAccess *Dominator,
  1899. const MemoryAccess *Dominatee) const {
  1900. if (Dominator == Dominatee)
  1901. return true;
  1902. if (isLiveOnEntryDef(Dominatee))
  1903. return false;
  1904. if (Dominator->getBlock() != Dominatee->getBlock())
  1905. return DT->dominates(Dominator->getBlock(), Dominatee->getBlock());
  1906. return locallyDominates(Dominator, Dominatee);
  1907. }
  1908. bool MemorySSA::dominates(const MemoryAccess *Dominator,
  1909. const Use &Dominatee) const {
  1910. if (MemoryPhi *MP = dyn_cast<MemoryPhi>(Dominatee.getUser())) {
  1911. BasicBlock *UseBB = MP->getIncomingBlock(Dominatee);
  1912. // The def must dominate the incoming block of the phi.
  1913. if (UseBB != Dominator->getBlock())
  1914. return DT->dominates(Dominator->getBlock(), UseBB);
  1915. // If the UseBB and the DefBB are the same, compare locally.
  1916. return locallyDominates(Dominator, cast<MemoryAccess>(Dominatee));
  1917. }
  1918. // If it's not a PHI node use, the normal dominates can already handle it.
  1919. return dominates(Dominator, cast<MemoryAccess>(Dominatee.getUser()));
  1920. }
  1921. void MemoryAccess::print(raw_ostream &OS) const {
  1922. switch (getValueID()) {
  1923. case MemoryPhiVal: return static_cast<const MemoryPhi *>(this)->print(OS);
  1924. case MemoryDefVal: return static_cast<const MemoryDef *>(this)->print(OS);
  1925. case MemoryUseVal: return static_cast<const MemoryUse *>(this)->print(OS);
  1926. }
  1927. llvm_unreachable("invalid value id");
  1928. }
  1929. void MemoryDef::print(raw_ostream &OS) const {
  1930. MemoryAccess *UO = getDefiningAccess();
  1931. auto printID = [&OS](MemoryAccess *A) {
  1932. if (A && A->getID())
  1933. OS << A->getID();
  1934. else
  1935. OS << LiveOnEntryStr;
  1936. };
  1937. OS << getID() << " = MemoryDef(";
  1938. printID(UO);
  1939. OS << ")";
  1940. if (isOptimized()) {
  1941. OS << "->";
  1942. printID(getOptimized());
  1943. if (Optional<AliasResult> AR = getOptimizedAccessType())
  1944. OS << " " << *AR;
  1945. }
  1946. }
  1947. void MemoryPhi::print(raw_ostream &OS) const {
  1948. ListSeparator LS(",");
  1949. OS << getID() << " = MemoryPhi(";
  1950. for (const auto &Op : operands()) {
  1951. BasicBlock *BB = getIncomingBlock(Op);
  1952. MemoryAccess *MA = cast<MemoryAccess>(Op);
  1953. OS << LS << '{';
  1954. if (BB->hasName())
  1955. OS << BB->getName();
  1956. else
  1957. BB->printAsOperand(OS, false);
  1958. OS << ',';
  1959. if (unsigned ID = MA->getID())
  1960. OS << ID;
  1961. else
  1962. OS << LiveOnEntryStr;
  1963. OS << '}';
  1964. }
  1965. OS << ')';
  1966. }
  1967. void MemoryUse::print(raw_ostream &OS) const {
  1968. MemoryAccess *UO = getDefiningAccess();
  1969. OS << "MemoryUse(";
  1970. if (UO && UO->getID())
  1971. OS << UO->getID();
  1972. else
  1973. OS << LiveOnEntryStr;
  1974. OS << ')';
  1975. if (Optional<AliasResult> AR = getOptimizedAccessType())
  1976. OS << " " << *AR;
  1977. }
  1978. void MemoryAccess::dump() const {
  1979. // Cannot completely remove virtual function even in release mode.
  1980. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1981. print(dbgs());
  1982. dbgs() << "\n";
  1983. #endif
  1984. }
  1985. char MemorySSAPrinterLegacyPass::ID = 0;
  1986. MemorySSAPrinterLegacyPass::MemorySSAPrinterLegacyPass() : FunctionPass(ID) {
  1987. initializeMemorySSAPrinterLegacyPassPass(*PassRegistry::getPassRegistry());
  1988. }
  1989. void MemorySSAPrinterLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
  1990. AU.setPreservesAll();
  1991. AU.addRequired<MemorySSAWrapperPass>();
  1992. }
  1993. class DOTFuncMSSAInfo {
  1994. private:
  1995. const Function &F;
  1996. MemorySSAAnnotatedWriter MSSAWriter;
  1997. public:
  1998. DOTFuncMSSAInfo(const Function &F, MemorySSA &MSSA)
  1999. : F(F), MSSAWriter(&MSSA) {}
  2000. const Function *getFunction() { return &F; }
  2001. MemorySSAAnnotatedWriter &getWriter() { return MSSAWriter; }
  2002. };
  2003. namespace llvm {
  2004. template <>
  2005. struct GraphTraits<DOTFuncMSSAInfo *> : public GraphTraits<const BasicBlock *> {
  2006. static NodeRef getEntryNode(DOTFuncMSSAInfo *CFGInfo) {
  2007. return &(CFGInfo->getFunction()->getEntryBlock());
  2008. }
  2009. // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
  2010. using nodes_iterator = pointer_iterator<Function::const_iterator>;
  2011. static nodes_iterator nodes_begin(DOTFuncMSSAInfo *CFGInfo) {
  2012. return nodes_iterator(CFGInfo->getFunction()->begin());
  2013. }
  2014. static nodes_iterator nodes_end(DOTFuncMSSAInfo *CFGInfo) {
  2015. return nodes_iterator(CFGInfo->getFunction()->end());
  2016. }
  2017. static size_t size(DOTFuncMSSAInfo *CFGInfo) {
  2018. return CFGInfo->getFunction()->size();
  2019. }
  2020. };
  2021. template <>
  2022. struct DOTGraphTraits<DOTFuncMSSAInfo *> : public DefaultDOTGraphTraits {
  2023. DOTGraphTraits(bool IsSimple = false) : DefaultDOTGraphTraits(IsSimple) {}
  2024. static std::string getGraphName(DOTFuncMSSAInfo *CFGInfo) {
  2025. return "MSSA CFG for '" + CFGInfo->getFunction()->getName().str() +
  2026. "' function";
  2027. }
  2028. std::string getNodeLabel(const BasicBlock *Node, DOTFuncMSSAInfo *CFGInfo) {
  2029. return DOTGraphTraits<DOTFuncInfo *>::getCompleteNodeLabel(
  2030. Node, nullptr,
  2031. [CFGInfo](raw_string_ostream &OS, const BasicBlock &BB) -> void {
  2032. BB.print(OS, &CFGInfo->getWriter(), true, true);
  2033. },
  2034. [](std::string &S, unsigned &I, unsigned Idx) -> void {
  2035. std::string Str = S.substr(I, Idx - I);
  2036. StringRef SR = Str;
  2037. if (SR.count(" = MemoryDef(") || SR.count(" = MemoryPhi(") ||
  2038. SR.count("MemoryUse("))
  2039. return;
  2040. DOTGraphTraits<DOTFuncInfo *>::eraseComment(S, I, Idx);
  2041. });
  2042. }
  2043. static std::string getEdgeSourceLabel(const BasicBlock *Node,
  2044. const_succ_iterator I) {
  2045. return DOTGraphTraits<DOTFuncInfo *>::getEdgeSourceLabel(Node, I);
  2046. }
  2047. /// Display the raw branch weights from PGO.
  2048. std::string getEdgeAttributes(const BasicBlock *Node, const_succ_iterator I,
  2049. DOTFuncMSSAInfo *CFGInfo) {
  2050. return "";
  2051. }
  2052. std::string getNodeAttributes(const BasicBlock *Node,
  2053. DOTFuncMSSAInfo *CFGInfo) {
  2054. return getNodeLabel(Node, CFGInfo).find(';') != std::string::npos
  2055. ? "style=filled, fillcolor=lightpink"
  2056. : "";
  2057. }
  2058. };
  2059. } // namespace llvm
  2060. bool MemorySSAPrinterLegacyPass::runOnFunction(Function &F) {
  2061. auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
  2062. if (DotCFGMSSA != "") {
  2063. DOTFuncMSSAInfo CFGInfo(F, MSSA);
  2064. WriteGraph(&CFGInfo, "", false, "MSSA", DotCFGMSSA);
  2065. } else
  2066. MSSA.print(dbgs());
  2067. if (VerifyMemorySSA)
  2068. MSSA.verifyMemorySSA();
  2069. return false;
  2070. }
  2071. AnalysisKey MemorySSAAnalysis::Key;
  2072. MemorySSAAnalysis::Result MemorySSAAnalysis::run(Function &F,
  2073. FunctionAnalysisManager &AM) {
  2074. auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
  2075. auto &AA = AM.getResult<AAManager>(F);
  2076. return MemorySSAAnalysis::Result(std::make_unique<MemorySSA>(F, &AA, &DT));
  2077. }
  2078. bool MemorySSAAnalysis::Result::invalidate(
  2079. Function &F, const PreservedAnalyses &PA,
  2080. FunctionAnalysisManager::Invalidator &Inv) {
  2081. auto PAC = PA.getChecker<MemorySSAAnalysis>();
  2082. return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
  2083. Inv.invalidate<AAManager>(F, PA) ||
  2084. Inv.invalidate<DominatorTreeAnalysis>(F, PA);
  2085. }
  2086. PreservedAnalyses MemorySSAPrinterPass::run(Function &F,
  2087. FunctionAnalysisManager &AM) {
  2088. auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
  2089. if (DotCFGMSSA != "") {
  2090. DOTFuncMSSAInfo CFGInfo(F, MSSA);
  2091. WriteGraph(&CFGInfo, "", false, "MSSA", DotCFGMSSA);
  2092. } else {
  2093. OS << "MemorySSA for function: " << F.getName() << "\n";
  2094. MSSA.print(OS);
  2095. }
  2096. return PreservedAnalyses::all();
  2097. }
  2098. PreservedAnalyses MemorySSAWalkerPrinterPass::run(Function &F,
  2099. FunctionAnalysisManager &AM) {
  2100. auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
  2101. OS << "MemorySSA (walker) for function: " << F.getName() << "\n";
  2102. MemorySSAWalkerAnnotatedWriter Writer(&MSSA);
  2103. F.print(OS, &Writer);
  2104. return PreservedAnalyses::all();
  2105. }
  2106. PreservedAnalyses MemorySSAVerifierPass::run(Function &F,
  2107. FunctionAnalysisManager &AM) {
  2108. AM.getResult<MemorySSAAnalysis>(F).getMSSA().verifyMemorySSA();
  2109. return PreservedAnalyses::all();
  2110. }
  2111. char MemorySSAWrapperPass::ID = 0;
  2112. MemorySSAWrapperPass::MemorySSAWrapperPass() : FunctionPass(ID) {
  2113. initializeMemorySSAWrapperPassPass(*PassRegistry::getPassRegistry());
  2114. }
  2115. void MemorySSAWrapperPass::releaseMemory() { MSSA.reset(); }
  2116. void MemorySSAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
  2117. AU.setPreservesAll();
  2118. AU.addRequiredTransitive<DominatorTreeWrapperPass>();
  2119. AU.addRequiredTransitive<AAResultsWrapperPass>();
  2120. }
  2121. bool MemorySSAWrapperPass::runOnFunction(Function &F) {
  2122. auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  2123. auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
  2124. MSSA.reset(new MemorySSA(F, &AA, &DT));
  2125. return false;
  2126. }
  2127. void MemorySSAWrapperPass::verifyAnalysis() const {
  2128. if (VerifyMemorySSA)
  2129. MSSA->verifyMemorySSA();
  2130. }
  2131. void MemorySSAWrapperPass::print(raw_ostream &OS, const Module *M) const {
  2132. MSSA->print(OS);
  2133. }
  2134. MemorySSAWalker::MemorySSAWalker(MemorySSA *M) : MSSA(M) {}
  2135. /// Walk the use-def chains starting at \p StartingAccess and find
  2136. /// the MemoryAccess that actually clobbers Loc.
  2137. ///
  2138. /// \returns our clobbering memory access
  2139. template <typename AliasAnalysisType>
  2140. MemoryAccess *
  2141. MemorySSA::ClobberWalkerBase<AliasAnalysisType>::getClobberingMemoryAccessBase(
  2142. MemoryAccess *StartingAccess, const MemoryLocation &Loc,
  2143. unsigned &UpwardWalkLimit) {
  2144. assert(!isa<MemoryUse>(StartingAccess) && "Use cannot be defining access");
  2145. Instruction *I = nullptr;
  2146. if (auto *StartingUseOrDef = dyn_cast<MemoryUseOrDef>(StartingAccess)) {
  2147. if (MSSA->isLiveOnEntryDef(StartingUseOrDef))
  2148. return StartingUseOrDef;
  2149. I = StartingUseOrDef->getMemoryInst();
  2150. // Conservatively, fences are always clobbers, so don't perform the walk if
  2151. // we hit a fence.
  2152. if (!isa<CallBase>(I) && I->isFenceLike())
  2153. return StartingUseOrDef;
  2154. }
  2155. UpwardsMemoryQuery Q;
  2156. Q.OriginalAccess = StartingAccess;
  2157. Q.StartingLoc = Loc;
  2158. Q.Inst = nullptr;
  2159. Q.IsCall = false;
  2160. // Unlike the other function, do not walk to the def of a def, because we are
  2161. // handed something we already believe is the clobbering access.
  2162. // We never set SkipSelf to true in Q in this method.
  2163. MemoryAccess *Clobber =
  2164. Walker.findClobber(StartingAccess, Q, UpwardWalkLimit);
  2165. LLVM_DEBUG({
  2166. dbgs() << "Clobber starting at access " << *StartingAccess << "\n";
  2167. if (I)
  2168. dbgs() << " for instruction " << *I << "\n";
  2169. dbgs() << " is " << *Clobber << "\n";
  2170. });
  2171. return Clobber;
  2172. }
  2173. static const Instruction *
  2174. getInvariantGroupClobberingInstruction(Instruction &I, DominatorTree &DT) {
  2175. if (!I.hasMetadata(LLVMContext::MD_invariant_group) || I.isVolatile())
  2176. return nullptr;
  2177. // We consider bitcasts and zero GEPs to be the same pointer value. Start by
  2178. // stripping bitcasts and zero GEPs, then we will recursively look at loads
  2179. // and stores through bitcasts and zero GEPs.
  2180. Value *PointerOperand = getLoadStorePointerOperand(&I)->stripPointerCasts();
  2181. // It's not safe to walk the use list of a global value because function
  2182. // passes aren't allowed to look outside their functions.
  2183. // FIXME: this could be fixed by filtering instructions from outside of
  2184. // current function.
  2185. if (isa<Constant>(PointerOperand))
  2186. return nullptr;
  2187. // Queue to process all pointers that are equivalent to load operand.
  2188. SmallVector<const Value *, 8> PointerUsesQueue;
  2189. PointerUsesQueue.push_back(PointerOperand);
  2190. const Instruction *MostDominatingInstruction = &I;
  2191. // FIXME: This loop is O(n^2) because dominates can be O(n) and in worst case
  2192. // we will see all the instructions. It may not matter in practice. If it
  2193. // does, we will have to support MemorySSA construction and updates.
  2194. while (!PointerUsesQueue.empty()) {
  2195. const Value *Ptr = PointerUsesQueue.pop_back_val();
  2196. assert(Ptr && !isa<GlobalValue>(Ptr) &&
  2197. "Null or GlobalValue should not be inserted");
  2198. for (const User *Us : Ptr->users()) {
  2199. auto *U = dyn_cast<Instruction>(Us);
  2200. if (!U || U == &I || !DT.dominates(U, MostDominatingInstruction))
  2201. continue;
  2202. // Add bitcasts and zero GEPs to queue.
  2203. if (isa<BitCastInst>(U)) {
  2204. PointerUsesQueue.push_back(U);
  2205. continue;
  2206. }
  2207. if (auto *GEP = dyn_cast<GetElementPtrInst>(U)) {
  2208. if (GEP->hasAllZeroIndices())
  2209. PointerUsesQueue.push_back(U);
  2210. continue;
  2211. }
  2212. // If we hit a load/store with an invariant.group metadata and the same
  2213. // pointer operand, we can assume that value pointed to by the pointer
  2214. // operand didn't change.
  2215. if (U->hasMetadata(LLVMContext::MD_invariant_group) &&
  2216. getLoadStorePointerOperand(U) == Ptr && !U->isVolatile()) {
  2217. MostDominatingInstruction = U;
  2218. }
  2219. }
  2220. }
  2221. return MostDominatingInstruction == &I ? nullptr : MostDominatingInstruction;
  2222. }
  2223. template <typename AliasAnalysisType>
  2224. MemoryAccess *
  2225. MemorySSA::ClobberWalkerBase<AliasAnalysisType>::getClobberingMemoryAccessBase(
  2226. MemoryAccess *MA, unsigned &UpwardWalkLimit, bool SkipSelf,
  2227. bool UseInvariantGroup) {
  2228. auto *StartingAccess = dyn_cast<MemoryUseOrDef>(MA);
  2229. // If this is a MemoryPhi, we can't do anything.
  2230. if (!StartingAccess)
  2231. return MA;
  2232. if (UseInvariantGroup) {
  2233. if (auto *I = getInvariantGroupClobberingInstruction(
  2234. *StartingAccess->getMemoryInst(), MSSA->getDomTree())) {
  2235. assert(isa<LoadInst>(I) || isa<StoreInst>(I));
  2236. auto *ClobberMA = MSSA->getMemoryAccess(I);
  2237. assert(ClobberMA);
  2238. if (isa<MemoryUse>(ClobberMA))
  2239. return ClobberMA->getDefiningAccess();
  2240. return ClobberMA;
  2241. }
  2242. }
  2243. bool IsOptimized = false;
  2244. // If this is an already optimized use or def, return the optimized result.
  2245. // Note: Currently, we store the optimized def result in a separate field,
  2246. // since we can't use the defining access.
  2247. if (StartingAccess->isOptimized()) {
  2248. if (!SkipSelf || !isa<MemoryDef>(StartingAccess))
  2249. return StartingAccess->getOptimized();
  2250. IsOptimized = true;
  2251. }
  2252. const Instruction *I = StartingAccess->getMemoryInst();
  2253. // We can't sanely do anything with a fence, since they conservatively clobber
  2254. // all memory, and have no locations to get pointers from to try to
  2255. // disambiguate.
  2256. if (!isa<CallBase>(I) && I->isFenceLike())
  2257. return StartingAccess;
  2258. UpwardsMemoryQuery Q(I, StartingAccess);
  2259. if (isUseTriviallyOptimizableToLiveOnEntry(*Walker.getAA(), I)) {
  2260. MemoryAccess *LiveOnEntry = MSSA->getLiveOnEntryDef();
  2261. StartingAccess->setOptimized(LiveOnEntry);
  2262. StartingAccess->setOptimizedAccessType(None);
  2263. return LiveOnEntry;
  2264. }
  2265. MemoryAccess *OptimizedAccess;
  2266. if (!IsOptimized) {
  2267. // Start with the thing we already think clobbers this location
  2268. MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess();
  2269. // At this point, DefiningAccess may be the live on entry def.
  2270. // If it is, we will not get a better result.
  2271. if (MSSA->isLiveOnEntryDef(DefiningAccess)) {
  2272. StartingAccess->setOptimized(DefiningAccess);
  2273. StartingAccess->setOptimizedAccessType(None);
  2274. return DefiningAccess;
  2275. }
  2276. OptimizedAccess = Walker.findClobber(DefiningAccess, Q, UpwardWalkLimit);
  2277. StartingAccess->setOptimized(OptimizedAccess);
  2278. if (MSSA->isLiveOnEntryDef(OptimizedAccess))
  2279. StartingAccess->setOptimizedAccessType(None);
  2280. else if (Q.AR && *Q.AR == AliasResult::MustAlias)
  2281. StartingAccess->setOptimizedAccessType(
  2282. AliasResult(AliasResult::MustAlias));
  2283. } else
  2284. OptimizedAccess = StartingAccess->getOptimized();
  2285. LLVM_DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
  2286. LLVM_DEBUG(dbgs() << *StartingAccess << "\n");
  2287. LLVM_DEBUG(dbgs() << "Optimized Memory SSA clobber for " << *I << " is ");
  2288. LLVM_DEBUG(dbgs() << *OptimizedAccess << "\n");
  2289. MemoryAccess *Result;
  2290. if (SkipSelf && isa<MemoryPhi>(OptimizedAccess) &&
  2291. isa<MemoryDef>(StartingAccess) && UpwardWalkLimit) {
  2292. assert(isa<MemoryDef>(Q.OriginalAccess));
  2293. Q.SkipSelfAccess = true;
  2294. Result = Walker.findClobber(OptimizedAccess, Q, UpwardWalkLimit);
  2295. } else
  2296. Result = OptimizedAccess;
  2297. LLVM_DEBUG(dbgs() << "Result Memory SSA clobber [SkipSelf = " << SkipSelf);
  2298. LLVM_DEBUG(dbgs() << "] for " << *I << " is " << *Result << "\n");
  2299. return Result;
  2300. }
  2301. MemoryAccess *
  2302. DoNothingMemorySSAWalker::getClobberingMemoryAccess(MemoryAccess *MA) {
  2303. if (auto *Use = dyn_cast<MemoryUseOrDef>(MA))
  2304. return Use->getDefiningAccess();
  2305. return MA;
  2306. }
  2307. MemoryAccess *DoNothingMemorySSAWalker::getClobberingMemoryAccess(
  2308. MemoryAccess *StartingAccess, const MemoryLocation &) {
  2309. if (auto *Use = dyn_cast<MemoryUseOrDef>(StartingAccess))
  2310. return Use->getDefiningAccess();
  2311. return StartingAccess;
  2312. }
  2313. void MemoryPhi::deleteMe(DerivedUser *Self) {
  2314. delete static_cast<MemoryPhi *>(Self);
  2315. }
  2316. void MemoryDef::deleteMe(DerivedUser *Self) {
  2317. delete static_cast<MemoryDef *>(Self);
  2318. }
  2319. void MemoryUse::deleteMe(DerivedUser *Self) {
  2320. delete static_cast<MemoryUse *>(Self);
  2321. }
  2322. bool upward_defs_iterator::IsGuaranteedLoopInvariant(Value *Ptr) const {
  2323. auto IsGuaranteedLoopInvariantBase = [](Value *Ptr) {
  2324. Ptr = Ptr->stripPointerCasts();
  2325. if (!isa<Instruction>(Ptr))
  2326. return true;
  2327. return isa<AllocaInst>(Ptr);
  2328. };
  2329. Ptr = Ptr->stripPointerCasts();
  2330. if (auto *I = dyn_cast<Instruction>(Ptr)) {
  2331. if (I->getParent()->isEntryBlock())
  2332. return true;
  2333. }
  2334. if (auto *GEP = dyn_cast<GEPOperator>(Ptr)) {
  2335. return IsGuaranteedLoopInvariantBase(GEP->getPointerOperand()) &&
  2336. GEP->hasAllConstantIndices();
  2337. }
  2338. return IsGuaranteedLoopInvariantBase(Ptr);
  2339. }