MemorySSA.cpp 96 KB

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