MemorySSA.h 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- MemorySSA.h - Build Memory SSA ---------------------------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. /// \file
  15. /// This file exposes an interface to building/using memory SSA to
  16. /// walk memory instructions using a use/def graph.
  17. ///
  18. /// Memory SSA class builds an SSA form that links together memory access
  19. /// instructions such as loads, stores, atomics, and calls. Additionally, it
  20. /// does a trivial form of "heap versioning" Every time the memory state changes
  21. /// in the program, we generate a new heap version. It generates
  22. /// MemoryDef/Uses/Phis that are overlayed on top of the existing instructions.
  23. ///
  24. /// As a trivial example,
  25. /// define i32 @main() #0 {
  26. /// entry:
  27. /// %call = call noalias i8* @_Znwm(i64 4) #2
  28. /// %0 = bitcast i8* %call to i32*
  29. /// %call1 = call noalias i8* @_Znwm(i64 4) #2
  30. /// %1 = bitcast i8* %call1 to i32*
  31. /// store i32 5, i32* %0, align 4
  32. /// store i32 7, i32* %1, align 4
  33. /// %2 = load i32* %0, align 4
  34. /// %3 = load i32* %1, align 4
  35. /// %add = add nsw i32 %2, %3
  36. /// ret i32 %add
  37. /// }
  38. ///
  39. /// Will become
  40. /// define i32 @main() #0 {
  41. /// entry:
  42. /// ; 1 = MemoryDef(0)
  43. /// %call = call noalias i8* @_Znwm(i64 4) #3
  44. /// %2 = bitcast i8* %call to i32*
  45. /// ; 2 = MemoryDef(1)
  46. /// %call1 = call noalias i8* @_Znwm(i64 4) #3
  47. /// %4 = bitcast i8* %call1 to i32*
  48. /// ; 3 = MemoryDef(2)
  49. /// store i32 5, i32* %2, align 4
  50. /// ; 4 = MemoryDef(3)
  51. /// store i32 7, i32* %4, align 4
  52. /// ; MemoryUse(3)
  53. /// %7 = load i32* %2, align 4
  54. /// ; MemoryUse(4)
  55. /// %8 = load i32* %4, align 4
  56. /// %add = add nsw i32 %7, %8
  57. /// ret i32 %add
  58. /// }
  59. ///
  60. /// Given this form, all the stores that could ever effect the load at %8 can be
  61. /// gotten by using the MemoryUse associated with it, and walking from use to
  62. /// def until you hit the top of the function.
  63. ///
  64. /// Each def also has a list of users associated with it, so you can walk from
  65. /// both def to users, and users to defs. Note that we disambiguate MemoryUses,
  66. /// but not the RHS of MemoryDefs. You can see this above at %7, which would
  67. /// otherwise be a MemoryUse(4). Being disambiguated means that for a given
  68. /// store, all the MemoryUses on its use lists are may-aliases of that store
  69. /// (but the MemoryDefs on its use list may not be).
  70. ///
  71. /// MemoryDefs are not disambiguated because it would require multiple reaching
  72. /// definitions, which would require multiple phis, and multiple memoryaccesses
  73. /// per instruction.
  74. //
  75. //===----------------------------------------------------------------------===//
  76. #ifndef LLVM_ANALYSIS_MEMORYSSA_H
  77. #define LLVM_ANALYSIS_MEMORYSSA_H
  78. #include "llvm/ADT/DenseMap.h"
  79. #include "llvm/ADT/GraphTraits.h"
  80. #include "llvm/ADT/SmallPtrSet.h"
  81. #include "llvm/ADT/SmallVector.h"
  82. #include "llvm/ADT/ilist.h"
  83. #include "llvm/ADT/ilist_node.h"
  84. #include "llvm/ADT/iterator.h"
  85. #include "llvm/ADT/iterator_range.h"
  86. #include "llvm/ADT/simple_ilist.h"
  87. #include "llvm/Analysis/AliasAnalysis.h"
  88. #include "llvm/Analysis/MemoryLocation.h"
  89. #include "llvm/Analysis/PHITransAddr.h"
  90. #include "llvm/IR/BasicBlock.h"
  91. #include "llvm/IR/DerivedUser.h"
  92. #include "llvm/IR/Dominators.h"
  93. #include "llvm/IR/Module.h"
  94. #include "llvm/IR/Operator.h"
  95. #include "llvm/IR/Type.h"
  96. #include "llvm/IR/Use.h"
  97. #include "llvm/IR/User.h"
  98. #include "llvm/IR/Value.h"
  99. #include "llvm/IR/ValueHandle.h"
  100. #include "llvm/Pass.h"
  101. #include "llvm/Support/Casting.h"
  102. #include "llvm/Support/CommandLine.h"
  103. #include <algorithm>
  104. #include <cassert>
  105. #include <cstddef>
  106. #include <iterator>
  107. #include <memory>
  108. #include <utility>
  109. namespace llvm {
  110. class Function;
  111. class Instruction;
  112. class MemoryAccess;
  113. class MemorySSAWalker;
  114. class LLVMContext;
  115. class raw_ostream;
  116. namespace MSSAHelpers {
  117. struct AllAccessTag {};
  118. struct DefsOnlyTag {};
  119. } // end namespace MSSAHelpers
  120. enum : unsigned {
  121. // Used to signify what the default invalid ID is for MemoryAccess's
  122. // getID()
  123. INVALID_MEMORYACCESS_ID = -1U
  124. };
  125. template <class T> class memoryaccess_def_iterator_base;
  126. using memoryaccess_def_iterator = memoryaccess_def_iterator_base<MemoryAccess>;
  127. using const_memoryaccess_def_iterator =
  128. memoryaccess_def_iterator_base<const MemoryAccess>;
  129. // The base for all memory accesses. All memory accesses in a block are
  130. // linked together using an intrusive list.
  131. class MemoryAccess
  132. : public DerivedUser,
  133. public ilist_node<MemoryAccess, ilist_tag<MSSAHelpers::AllAccessTag>>,
  134. public ilist_node<MemoryAccess, ilist_tag<MSSAHelpers::DefsOnlyTag>> {
  135. public:
  136. using AllAccessType =
  137. ilist_node<MemoryAccess, ilist_tag<MSSAHelpers::AllAccessTag>>;
  138. using DefsOnlyType =
  139. ilist_node<MemoryAccess, ilist_tag<MSSAHelpers::DefsOnlyTag>>;
  140. MemoryAccess(const MemoryAccess &) = delete;
  141. MemoryAccess &operator=(const MemoryAccess &) = delete;
  142. void *operator new(size_t) = delete;
  143. // Methods for support type inquiry through isa, cast, and
  144. // dyn_cast
  145. static bool classof(const Value *V) {
  146. unsigned ID = V->getValueID();
  147. return ID == MemoryUseVal || ID == MemoryPhiVal || ID == MemoryDefVal;
  148. }
  149. BasicBlock *getBlock() const { return Block; }
  150. void print(raw_ostream &OS) const;
  151. void dump() const;
  152. /// The user iterators for a memory access
  153. using iterator = user_iterator;
  154. using const_iterator = const_user_iterator;
  155. /// This iterator walks over all of the defs in a given
  156. /// MemoryAccess. For MemoryPhi nodes, this walks arguments. For
  157. /// MemoryUse/MemoryDef, this walks the defining access.
  158. memoryaccess_def_iterator defs_begin();
  159. const_memoryaccess_def_iterator defs_begin() const;
  160. memoryaccess_def_iterator defs_end();
  161. const_memoryaccess_def_iterator defs_end() const;
  162. /// Get the iterators for the all access list and the defs only list
  163. /// We default to the all access list.
  164. AllAccessType::self_iterator getIterator() {
  165. return this->AllAccessType::getIterator();
  166. }
  167. AllAccessType::const_self_iterator getIterator() const {
  168. return this->AllAccessType::getIterator();
  169. }
  170. AllAccessType::reverse_self_iterator getReverseIterator() {
  171. return this->AllAccessType::getReverseIterator();
  172. }
  173. AllAccessType::const_reverse_self_iterator getReverseIterator() const {
  174. return this->AllAccessType::getReverseIterator();
  175. }
  176. DefsOnlyType::self_iterator getDefsIterator() {
  177. return this->DefsOnlyType::getIterator();
  178. }
  179. DefsOnlyType::const_self_iterator getDefsIterator() const {
  180. return this->DefsOnlyType::getIterator();
  181. }
  182. DefsOnlyType::reverse_self_iterator getReverseDefsIterator() {
  183. return this->DefsOnlyType::getReverseIterator();
  184. }
  185. DefsOnlyType::const_reverse_self_iterator getReverseDefsIterator() const {
  186. return this->DefsOnlyType::getReverseIterator();
  187. }
  188. protected:
  189. friend class MemoryDef;
  190. friend class MemoryPhi;
  191. friend class MemorySSA;
  192. friend class MemoryUse;
  193. friend class MemoryUseOrDef;
  194. /// Used by MemorySSA to change the block of a MemoryAccess when it is
  195. /// moved.
  196. void setBlock(BasicBlock *BB) { Block = BB; }
  197. /// Used for debugging and tracking things about MemoryAccesses.
  198. /// Guaranteed unique among MemoryAccesses, no guarantees otherwise.
  199. inline unsigned getID() const;
  200. MemoryAccess(LLVMContext &C, unsigned Vty, DeleteValueTy DeleteValue,
  201. BasicBlock *BB, unsigned NumOperands)
  202. : DerivedUser(Type::getVoidTy(C), Vty, nullptr, NumOperands, DeleteValue),
  203. Block(BB) {}
  204. // Use deleteValue() to delete a generic MemoryAccess.
  205. ~MemoryAccess() = default;
  206. private:
  207. BasicBlock *Block;
  208. };
  209. template <>
  210. struct ilist_alloc_traits<MemoryAccess> {
  211. static void deleteNode(MemoryAccess *MA) { MA->deleteValue(); }
  212. };
  213. inline raw_ostream &operator<<(raw_ostream &OS, const MemoryAccess &MA) {
  214. MA.print(OS);
  215. return OS;
  216. }
  217. /// Class that has the common methods + fields of memory uses/defs. It's
  218. /// a little awkward to have, but there are many cases where we want either a
  219. /// use or def, and there are many cases where uses are needed (defs aren't
  220. /// acceptable), and vice-versa.
  221. ///
  222. /// This class should never be instantiated directly; make a MemoryUse or
  223. /// MemoryDef instead.
  224. class MemoryUseOrDef : public MemoryAccess {
  225. public:
  226. void *operator new(size_t) = delete;
  227. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(MemoryAccess);
  228. /// Get the instruction that this MemoryUse represents.
  229. Instruction *getMemoryInst() const { return MemoryInstruction; }
  230. /// Get the access that produces the memory state used by this Use.
  231. MemoryAccess *getDefiningAccess() const { return getOperand(0); }
  232. static bool classof(const Value *MA) {
  233. return MA->getValueID() == MemoryUseVal || MA->getValueID() == MemoryDefVal;
  234. }
  235. // Sadly, these have to be public because they are needed in some of the
  236. // iterators.
  237. inline bool isOptimized() const;
  238. inline MemoryAccess *getOptimized() const;
  239. inline void setOptimized(MemoryAccess *);
  240. // Retrieve AliasResult type of the optimized access. Ideally this would be
  241. // returned by the caching walker and may go away in the future.
  242. Optional<AliasResult> getOptimizedAccessType() const {
  243. return isOptimized() ? OptimizedAccessAlias : None;
  244. }
  245. /// Reset the ID of what this MemoryUse was optimized to, causing it to
  246. /// be rewalked by the walker if necessary.
  247. /// This really should only be called by tests.
  248. inline void resetOptimized();
  249. protected:
  250. friend class MemorySSA;
  251. friend class MemorySSAUpdater;
  252. MemoryUseOrDef(LLVMContext &C, MemoryAccess *DMA, unsigned Vty,
  253. DeleteValueTy DeleteValue, Instruction *MI, BasicBlock *BB,
  254. unsigned NumOperands)
  255. : MemoryAccess(C, Vty, DeleteValue, BB, NumOperands),
  256. MemoryInstruction(MI), OptimizedAccessAlias(AliasResult::MayAlias) {
  257. setDefiningAccess(DMA);
  258. }
  259. // Use deleteValue() to delete a generic MemoryUseOrDef.
  260. ~MemoryUseOrDef() = default;
  261. void setOptimizedAccessType(Optional<AliasResult> AR) {
  262. OptimizedAccessAlias = AR;
  263. }
  264. void setDefiningAccess(
  265. MemoryAccess *DMA, bool Optimized = false,
  266. Optional<AliasResult> AR = AliasResult(AliasResult::MayAlias)) {
  267. if (!Optimized) {
  268. setOperand(0, DMA);
  269. return;
  270. }
  271. setOptimized(DMA);
  272. setOptimizedAccessType(AR);
  273. }
  274. private:
  275. Instruction *MemoryInstruction;
  276. Optional<AliasResult> OptimizedAccessAlias;
  277. };
  278. /// Represents read-only accesses to memory
  279. ///
  280. /// In particular, the set of Instructions that will be represented by
  281. /// MemoryUse's is exactly the set of Instructions for which
  282. /// AliasAnalysis::getModRefInfo returns "Ref".
  283. class MemoryUse final : public MemoryUseOrDef {
  284. public:
  285. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(MemoryAccess);
  286. MemoryUse(LLVMContext &C, MemoryAccess *DMA, Instruction *MI, BasicBlock *BB)
  287. : MemoryUseOrDef(C, DMA, MemoryUseVal, deleteMe, MI, BB,
  288. /*NumOperands=*/1) {}
  289. // allocate space for exactly one operand
  290. void *operator new(size_t S) { return User::operator new(S, 1); }
  291. void operator delete(void *Ptr) { User::operator delete(Ptr); }
  292. static bool classof(const Value *MA) {
  293. return MA->getValueID() == MemoryUseVal;
  294. }
  295. void print(raw_ostream &OS) const;
  296. void setOptimized(MemoryAccess *DMA) {
  297. OptimizedID = DMA->getID();
  298. setOperand(0, DMA);
  299. }
  300. bool isOptimized() const {
  301. return getDefiningAccess() && OptimizedID == getDefiningAccess()->getID();
  302. }
  303. MemoryAccess *getOptimized() const {
  304. return getDefiningAccess();
  305. }
  306. void resetOptimized() {
  307. OptimizedID = INVALID_MEMORYACCESS_ID;
  308. }
  309. protected:
  310. friend class MemorySSA;
  311. private:
  312. static void deleteMe(DerivedUser *Self);
  313. unsigned OptimizedID = INVALID_MEMORYACCESS_ID;
  314. };
  315. template <>
  316. struct OperandTraits<MemoryUse> : public FixedNumOperandTraits<MemoryUse, 1> {};
  317. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(MemoryUse, MemoryAccess)
  318. /// Represents a read-write access to memory, whether it is a must-alias,
  319. /// or a may-alias.
  320. ///
  321. /// In particular, the set of Instructions that will be represented by
  322. /// MemoryDef's is exactly the set of Instructions for which
  323. /// AliasAnalysis::getModRefInfo returns "Mod" or "ModRef".
  324. /// Note that, in order to provide def-def chains, all defs also have a use
  325. /// associated with them. This use points to the nearest reaching
  326. /// MemoryDef/MemoryPhi.
  327. class MemoryDef final : public MemoryUseOrDef {
  328. public:
  329. friend class MemorySSA;
  330. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(MemoryAccess);
  331. MemoryDef(LLVMContext &C, MemoryAccess *DMA, Instruction *MI, BasicBlock *BB,
  332. unsigned Ver)
  333. : MemoryUseOrDef(C, DMA, MemoryDefVal, deleteMe, MI, BB,
  334. /*NumOperands=*/2),
  335. ID(Ver) {}
  336. // allocate space for exactly two operands
  337. void *operator new(size_t S) { return User::operator new(S, 2); }
  338. void operator delete(void *Ptr) { User::operator delete(Ptr); }
  339. static bool classof(const Value *MA) {
  340. return MA->getValueID() == MemoryDefVal;
  341. }
  342. void setOptimized(MemoryAccess *MA) {
  343. setOperand(1, MA);
  344. OptimizedID = MA->getID();
  345. }
  346. MemoryAccess *getOptimized() const {
  347. return cast_or_null<MemoryAccess>(getOperand(1));
  348. }
  349. bool isOptimized() const {
  350. return getOptimized() && OptimizedID == getOptimized()->getID();
  351. }
  352. void resetOptimized() {
  353. OptimizedID = INVALID_MEMORYACCESS_ID;
  354. setOperand(1, nullptr);
  355. }
  356. void print(raw_ostream &OS) const;
  357. unsigned getID() const { return ID; }
  358. private:
  359. static void deleteMe(DerivedUser *Self);
  360. const unsigned ID;
  361. unsigned OptimizedID = INVALID_MEMORYACCESS_ID;
  362. };
  363. template <>
  364. struct OperandTraits<MemoryDef> : public FixedNumOperandTraits<MemoryDef, 2> {};
  365. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(MemoryDef, MemoryAccess)
  366. template <>
  367. struct OperandTraits<MemoryUseOrDef> {
  368. static Use *op_begin(MemoryUseOrDef *MUD) {
  369. if (auto *MU = dyn_cast<MemoryUse>(MUD))
  370. return OperandTraits<MemoryUse>::op_begin(MU);
  371. return OperandTraits<MemoryDef>::op_begin(cast<MemoryDef>(MUD));
  372. }
  373. static Use *op_end(MemoryUseOrDef *MUD) {
  374. if (auto *MU = dyn_cast<MemoryUse>(MUD))
  375. return OperandTraits<MemoryUse>::op_end(MU);
  376. return OperandTraits<MemoryDef>::op_end(cast<MemoryDef>(MUD));
  377. }
  378. static unsigned operands(const MemoryUseOrDef *MUD) {
  379. if (const auto *MU = dyn_cast<MemoryUse>(MUD))
  380. return OperandTraits<MemoryUse>::operands(MU);
  381. return OperandTraits<MemoryDef>::operands(cast<MemoryDef>(MUD));
  382. }
  383. };
  384. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(MemoryUseOrDef, MemoryAccess)
  385. /// Represents phi nodes for memory accesses.
  386. ///
  387. /// These have the same semantic as regular phi nodes, with the exception that
  388. /// only one phi will ever exist in a given basic block.
  389. /// Guaranteeing one phi per block means guaranteeing there is only ever one
  390. /// valid reaching MemoryDef/MemoryPHI along each path to the phi node.
  391. /// This is ensured by not allowing disambiguation of the RHS of a MemoryDef or
  392. /// a MemoryPhi's operands.
  393. /// That is, given
  394. /// if (a) {
  395. /// store %a
  396. /// store %b
  397. /// }
  398. /// it *must* be transformed into
  399. /// if (a) {
  400. /// 1 = MemoryDef(liveOnEntry)
  401. /// store %a
  402. /// 2 = MemoryDef(1)
  403. /// store %b
  404. /// }
  405. /// and *not*
  406. /// if (a) {
  407. /// 1 = MemoryDef(liveOnEntry)
  408. /// store %a
  409. /// 2 = MemoryDef(liveOnEntry)
  410. /// store %b
  411. /// }
  412. /// even if the two stores do not conflict. Otherwise, both 1 and 2 reach the
  413. /// end of the branch, and if there are not two phi nodes, one will be
  414. /// disconnected completely from the SSA graph below that point.
  415. /// Because MemoryUse's do not generate new definitions, they do not have this
  416. /// issue.
  417. class MemoryPhi final : public MemoryAccess {
  418. // allocate space for exactly zero operands
  419. void *operator new(size_t S) { return User::operator new(S); }
  420. public:
  421. void operator delete(void *Ptr) { User::operator delete(Ptr); }
  422. /// Provide fast operand accessors
  423. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(MemoryAccess);
  424. MemoryPhi(LLVMContext &C, BasicBlock *BB, unsigned Ver, unsigned NumPreds = 0)
  425. : MemoryAccess(C, MemoryPhiVal, deleteMe, BB, 0), ID(Ver),
  426. ReservedSpace(NumPreds) {
  427. allocHungoffUses(ReservedSpace);
  428. }
  429. // Block iterator interface. This provides access to the list of incoming
  430. // basic blocks, which parallels the list of incoming values.
  431. using block_iterator = BasicBlock **;
  432. using const_block_iterator = BasicBlock *const *;
  433. block_iterator block_begin() {
  434. return reinterpret_cast<block_iterator>(op_begin() + ReservedSpace);
  435. }
  436. const_block_iterator block_begin() const {
  437. return reinterpret_cast<const_block_iterator>(op_begin() + ReservedSpace);
  438. }
  439. block_iterator block_end() { return block_begin() + getNumOperands(); }
  440. const_block_iterator block_end() const {
  441. return block_begin() + getNumOperands();
  442. }
  443. iterator_range<block_iterator> blocks() {
  444. return make_range(block_begin(), block_end());
  445. }
  446. iterator_range<const_block_iterator> blocks() const {
  447. return make_range(block_begin(), block_end());
  448. }
  449. op_range incoming_values() { return operands(); }
  450. const_op_range incoming_values() const { return operands(); }
  451. /// Return the number of incoming edges
  452. unsigned getNumIncomingValues() const { return getNumOperands(); }
  453. /// Return incoming value number x
  454. MemoryAccess *getIncomingValue(unsigned I) const { return getOperand(I); }
  455. void setIncomingValue(unsigned I, MemoryAccess *V) {
  456. assert(V && "PHI node got a null value!");
  457. setOperand(I, V);
  458. }
  459. static unsigned getOperandNumForIncomingValue(unsigned I) { return I; }
  460. static unsigned getIncomingValueNumForOperand(unsigned I) { return I; }
  461. /// Return incoming basic block number @p i.
  462. BasicBlock *getIncomingBlock(unsigned I) const { return block_begin()[I]; }
  463. /// Return incoming basic block corresponding
  464. /// to an operand of the PHI.
  465. BasicBlock *getIncomingBlock(const Use &U) const {
  466. assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?");
  467. return getIncomingBlock(unsigned(&U - op_begin()));
  468. }
  469. /// Return incoming basic block corresponding
  470. /// to value use iterator.
  471. BasicBlock *getIncomingBlock(MemoryAccess::const_user_iterator I) const {
  472. return getIncomingBlock(I.getUse());
  473. }
  474. void setIncomingBlock(unsigned I, BasicBlock *BB) {
  475. assert(BB && "PHI node got a null basic block!");
  476. block_begin()[I] = BB;
  477. }
  478. /// Add an incoming value to the end of the PHI list
  479. void addIncoming(MemoryAccess *V, BasicBlock *BB) {
  480. if (getNumOperands() == ReservedSpace)
  481. growOperands(); // Get more space!
  482. // Initialize some new operands.
  483. setNumHungOffUseOperands(getNumOperands() + 1);
  484. setIncomingValue(getNumOperands() - 1, V);
  485. setIncomingBlock(getNumOperands() - 1, BB);
  486. }
  487. /// Return the first index of the specified basic
  488. /// block in the value list for this PHI. Returns -1 if no instance.
  489. int getBasicBlockIndex(const BasicBlock *BB) const {
  490. for (unsigned I = 0, E = getNumOperands(); I != E; ++I)
  491. if (block_begin()[I] == BB)
  492. return I;
  493. return -1;
  494. }
  495. MemoryAccess *getIncomingValueForBlock(const BasicBlock *BB) const {
  496. int Idx = getBasicBlockIndex(BB);
  497. assert(Idx >= 0 && "Invalid basic block argument!");
  498. return getIncomingValue(Idx);
  499. }
  500. // After deleting incoming position I, the order of incoming may be changed.
  501. void unorderedDeleteIncoming(unsigned I) {
  502. unsigned E = getNumOperands();
  503. assert(I < E && "Cannot remove out of bounds Phi entry.");
  504. // MemoryPhi must have at least two incoming values, otherwise the MemoryPhi
  505. // itself should be deleted.
  506. assert(E >= 2 && "Cannot only remove incoming values in MemoryPhis with "
  507. "at least 2 values.");
  508. setIncomingValue(I, getIncomingValue(E - 1));
  509. setIncomingBlock(I, block_begin()[E - 1]);
  510. setOperand(E - 1, nullptr);
  511. block_begin()[E - 1] = nullptr;
  512. setNumHungOffUseOperands(getNumOperands() - 1);
  513. }
  514. // After deleting entries that satisfy Pred, remaining entries may have
  515. // changed order.
  516. template <typename Fn> void unorderedDeleteIncomingIf(Fn &&Pred) {
  517. for (unsigned I = 0, E = getNumOperands(); I != E; ++I)
  518. if (Pred(getIncomingValue(I), getIncomingBlock(I))) {
  519. unorderedDeleteIncoming(I);
  520. E = getNumOperands();
  521. --I;
  522. }
  523. assert(getNumOperands() >= 1 &&
  524. "Cannot remove all incoming blocks in a MemoryPhi.");
  525. }
  526. // After deleting incoming block BB, the incoming blocks order may be changed.
  527. void unorderedDeleteIncomingBlock(const BasicBlock *BB) {
  528. unorderedDeleteIncomingIf(
  529. [&](const MemoryAccess *, const BasicBlock *B) { return BB == B; });
  530. }
  531. // After deleting incoming memory access MA, the incoming accesses order may
  532. // be changed.
  533. void unorderedDeleteIncomingValue(const MemoryAccess *MA) {
  534. unorderedDeleteIncomingIf(
  535. [&](const MemoryAccess *M, const BasicBlock *) { return MA == M; });
  536. }
  537. static bool classof(const Value *V) {
  538. return V->getValueID() == MemoryPhiVal;
  539. }
  540. void print(raw_ostream &OS) const;
  541. unsigned getID() const { return ID; }
  542. protected:
  543. friend class MemorySSA;
  544. /// this is more complicated than the generic
  545. /// User::allocHungoffUses, because we have to allocate Uses for the incoming
  546. /// values and pointers to the incoming blocks, all in one allocation.
  547. void allocHungoffUses(unsigned N) {
  548. User::allocHungoffUses(N, /* IsPhi */ true);
  549. }
  550. private:
  551. // For debugging only
  552. const unsigned ID;
  553. unsigned ReservedSpace;
  554. /// This grows the operand list in response to a push_back style of
  555. /// operation. This grows the number of ops by 1.5 times.
  556. void growOperands() {
  557. unsigned E = getNumOperands();
  558. // 2 op PHI nodes are VERY common, so reserve at least enough for that.
  559. ReservedSpace = std::max(E + E / 2, 2u);
  560. growHungoffUses(ReservedSpace, /* IsPhi */ true);
  561. }
  562. static void deleteMe(DerivedUser *Self);
  563. };
  564. inline unsigned MemoryAccess::getID() const {
  565. assert((isa<MemoryDef>(this) || isa<MemoryPhi>(this)) &&
  566. "only memory defs and phis have ids");
  567. if (const auto *MD = dyn_cast<MemoryDef>(this))
  568. return MD->getID();
  569. return cast<MemoryPhi>(this)->getID();
  570. }
  571. inline bool MemoryUseOrDef::isOptimized() const {
  572. if (const auto *MD = dyn_cast<MemoryDef>(this))
  573. return MD->isOptimized();
  574. return cast<MemoryUse>(this)->isOptimized();
  575. }
  576. inline MemoryAccess *MemoryUseOrDef::getOptimized() const {
  577. if (const auto *MD = dyn_cast<MemoryDef>(this))
  578. return MD->getOptimized();
  579. return cast<MemoryUse>(this)->getOptimized();
  580. }
  581. inline void MemoryUseOrDef::setOptimized(MemoryAccess *MA) {
  582. if (auto *MD = dyn_cast<MemoryDef>(this))
  583. MD->setOptimized(MA);
  584. else
  585. cast<MemoryUse>(this)->setOptimized(MA);
  586. }
  587. inline void MemoryUseOrDef::resetOptimized() {
  588. if (auto *MD = dyn_cast<MemoryDef>(this))
  589. MD->resetOptimized();
  590. else
  591. cast<MemoryUse>(this)->resetOptimized();
  592. }
  593. template <> struct OperandTraits<MemoryPhi> : public HungoffOperandTraits<2> {};
  594. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(MemoryPhi, MemoryAccess)
  595. /// Encapsulates MemorySSA, including all data associated with memory
  596. /// accesses.
  597. class MemorySSA {
  598. public:
  599. MemorySSA(Function &, AliasAnalysis *, DominatorTree *);
  600. // MemorySSA must remain where it's constructed; Walkers it creates store
  601. // pointers to it.
  602. MemorySSA(MemorySSA &&) = delete;
  603. ~MemorySSA();
  604. MemorySSAWalker *getWalker();
  605. MemorySSAWalker *getSkipSelfWalker();
  606. /// Given a memory Mod/Ref'ing instruction, get the MemorySSA
  607. /// access associated with it. If passed a basic block gets the memory phi
  608. /// node that exists for that block, if there is one. Otherwise, this will get
  609. /// a MemoryUseOrDef.
  610. MemoryUseOrDef *getMemoryAccess(const Instruction *I) const {
  611. return cast_or_null<MemoryUseOrDef>(ValueToMemoryAccess.lookup(I));
  612. }
  613. MemoryPhi *getMemoryAccess(const BasicBlock *BB) const {
  614. return cast_or_null<MemoryPhi>(ValueToMemoryAccess.lookup(cast<Value>(BB)));
  615. }
  616. DominatorTree &getDomTree() const { return *DT; }
  617. void dump() const;
  618. void print(raw_ostream &) const;
  619. /// Return true if \p MA represents the live on entry value
  620. ///
  621. /// Loads and stores from pointer arguments and other global values may be
  622. /// defined by memory operations that do not occur in the current function, so
  623. /// they may be live on entry to the function. MemorySSA represents such
  624. /// memory state by the live on entry definition, which is guaranteed to occur
  625. /// before any other memory access in the function.
  626. inline bool isLiveOnEntryDef(const MemoryAccess *MA) const {
  627. return MA == LiveOnEntryDef.get();
  628. }
  629. inline MemoryAccess *getLiveOnEntryDef() const {
  630. return LiveOnEntryDef.get();
  631. }
  632. // Sadly, iplists, by default, owns and deletes pointers added to the
  633. // list. It's not currently possible to have two iplists for the same type,
  634. // where one owns the pointers, and one does not. This is because the traits
  635. // are per-type, not per-tag. If this ever changes, we should make the
  636. // DefList an iplist.
  637. using AccessList = iplist<MemoryAccess, ilist_tag<MSSAHelpers::AllAccessTag>>;
  638. using DefsList =
  639. simple_ilist<MemoryAccess, ilist_tag<MSSAHelpers::DefsOnlyTag>>;
  640. /// Return the list of MemoryAccess's for a given basic block.
  641. ///
  642. /// This list is not modifiable by the user.
  643. const AccessList *getBlockAccesses(const BasicBlock *BB) const {
  644. return getWritableBlockAccesses(BB);
  645. }
  646. /// Return the list of MemoryDef's and MemoryPhi's for a given basic
  647. /// block.
  648. ///
  649. /// This list is not modifiable by the user.
  650. const DefsList *getBlockDefs(const BasicBlock *BB) const {
  651. return getWritableBlockDefs(BB);
  652. }
  653. /// Given two memory accesses in the same basic block, determine
  654. /// whether MemoryAccess \p A dominates MemoryAccess \p B.
  655. bool locallyDominates(const MemoryAccess *A, const MemoryAccess *B) const;
  656. /// Given two memory accesses in potentially different blocks,
  657. /// determine whether MemoryAccess \p A dominates MemoryAccess \p B.
  658. bool dominates(const MemoryAccess *A, const MemoryAccess *B) const;
  659. /// Given a MemoryAccess and a Use, determine whether MemoryAccess \p A
  660. /// dominates Use \p B.
  661. bool dominates(const MemoryAccess *A, const Use &B) const;
  662. enum class VerificationLevel { Fast, Full };
  663. /// Verify that MemorySSA is self consistent (IE definitions dominate
  664. /// all uses, uses appear in the right places). This is used by unit tests.
  665. void verifyMemorySSA(VerificationLevel = VerificationLevel::Fast) const;
  666. /// Used in various insertion functions to specify whether we are talking
  667. /// about the beginning or end of a block.
  668. enum InsertionPlace { Beginning, End, BeforeTerminator };
  669. protected:
  670. // Used by Memory SSA dumpers and wrapper pass
  671. friend class MemorySSAPrinterLegacyPass;
  672. friend class MemorySSAUpdater;
  673. void verifyOrderingDominationAndDefUses(
  674. Function &F, VerificationLevel = VerificationLevel::Fast) const;
  675. void verifyDominationNumbers(const Function &F) const;
  676. void verifyPrevDefInPhis(Function &F) const;
  677. // This is used by the use optimizer and updater.
  678. AccessList *getWritableBlockAccesses(const BasicBlock *BB) const {
  679. auto It = PerBlockAccesses.find(BB);
  680. return It == PerBlockAccesses.end() ? nullptr : It->second.get();
  681. }
  682. // This is used by the use optimizer and updater.
  683. DefsList *getWritableBlockDefs(const BasicBlock *BB) const {
  684. auto It = PerBlockDefs.find(BB);
  685. return It == PerBlockDefs.end() ? nullptr : It->second.get();
  686. }
  687. // These is used by the updater to perform various internal MemorySSA
  688. // machinsations. They do not always leave the IR in a correct state, and
  689. // relies on the updater to fixup what it breaks, so it is not public.
  690. void moveTo(MemoryUseOrDef *What, BasicBlock *BB, AccessList::iterator Where);
  691. void moveTo(MemoryAccess *What, BasicBlock *BB, InsertionPlace Point);
  692. // Rename the dominator tree branch rooted at BB.
  693. void renamePass(BasicBlock *BB, MemoryAccess *IncomingVal,
  694. SmallPtrSetImpl<BasicBlock *> &Visited) {
  695. renamePass(DT->getNode(BB), IncomingVal, Visited, true, true);
  696. }
  697. void removeFromLookups(MemoryAccess *);
  698. void removeFromLists(MemoryAccess *, bool ShouldDelete = true);
  699. void insertIntoListsForBlock(MemoryAccess *, const BasicBlock *,
  700. InsertionPlace);
  701. void insertIntoListsBefore(MemoryAccess *, const BasicBlock *,
  702. AccessList::iterator);
  703. MemoryUseOrDef *createDefinedAccess(Instruction *, MemoryAccess *,
  704. const MemoryUseOrDef *Template = nullptr,
  705. bool CreationMustSucceed = true);
  706. private:
  707. template <class AliasAnalysisType> class ClobberWalkerBase;
  708. template <class AliasAnalysisType> class CachingWalker;
  709. template <class AliasAnalysisType> class SkipSelfWalker;
  710. class OptimizeUses;
  711. CachingWalker<AliasAnalysis> *getWalkerImpl();
  712. void buildMemorySSA(BatchAAResults &BAA);
  713. void prepareForMoveTo(MemoryAccess *, BasicBlock *);
  714. void verifyUseInDefs(MemoryAccess *, MemoryAccess *) const;
  715. using AccessMap = DenseMap<const BasicBlock *, std::unique_ptr<AccessList>>;
  716. using DefsMap = DenseMap<const BasicBlock *, std::unique_ptr<DefsList>>;
  717. void markUnreachableAsLiveOnEntry(BasicBlock *BB);
  718. MemoryPhi *createMemoryPhi(BasicBlock *BB);
  719. template <typename AliasAnalysisType>
  720. MemoryUseOrDef *createNewAccess(Instruction *, AliasAnalysisType *,
  721. const MemoryUseOrDef *Template = nullptr);
  722. void placePHINodes(const SmallPtrSetImpl<BasicBlock *> &);
  723. MemoryAccess *renameBlock(BasicBlock *, MemoryAccess *, bool);
  724. void renameSuccessorPhis(BasicBlock *, MemoryAccess *, bool);
  725. void renamePass(DomTreeNode *, MemoryAccess *IncomingVal,
  726. SmallPtrSetImpl<BasicBlock *> &Visited,
  727. bool SkipVisited = false, bool RenameAllUses = false);
  728. AccessList *getOrCreateAccessList(const BasicBlock *);
  729. DefsList *getOrCreateDefsList(const BasicBlock *);
  730. void renumberBlock(const BasicBlock *) const;
  731. AliasAnalysis *AA = nullptr;
  732. DominatorTree *DT;
  733. Function &F;
  734. // Memory SSA mappings
  735. DenseMap<const Value *, MemoryAccess *> ValueToMemoryAccess;
  736. // These two mappings contain the main block to access/def mappings for
  737. // MemorySSA. The list contained in PerBlockAccesses really owns all the
  738. // MemoryAccesses.
  739. // Both maps maintain the invariant that if a block is found in them, the
  740. // corresponding list is not empty, and if a block is not found in them, the
  741. // corresponding list is empty.
  742. AccessMap PerBlockAccesses;
  743. DefsMap PerBlockDefs;
  744. std::unique_ptr<MemoryAccess, ValueDeleter> LiveOnEntryDef;
  745. // Domination mappings
  746. // Note that the numbering is local to a block, even though the map is
  747. // global.
  748. mutable SmallPtrSet<const BasicBlock *, 16> BlockNumberingValid;
  749. mutable DenseMap<const MemoryAccess *, unsigned long> BlockNumbering;
  750. // Memory SSA building info
  751. std::unique_ptr<ClobberWalkerBase<AliasAnalysis>> WalkerBase;
  752. std::unique_ptr<CachingWalker<AliasAnalysis>> Walker;
  753. std::unique_ptr<SkipSelfWalker<AliasAnalysis>> SkipWalker;
  754. unsigned NextID = 0;
  755. };
  756. /// Enables verification of MemorySSA.
  757. ///
  758. /// The checks which this flag enables is exensive and disabled by default
  759. /// unless `EXPENSIVE_CHECKS` is defined. The flag `-verify-memoryssa` can be
  760. /// used to selectively enable the verification without re-compilation.
  761. extern bool VerifyMemorySSA;
  762. // Internal MemorySSA utils, for use by MemorySSA classes and walkers
  763. class MemorySSAUtil {
  764. protected:
  765. friend class GVNHoist;
  766. friend class MemorySSAWalker;
  767. // This function should not be used by new passes.
  768. static bool defClobbersUseOrDef(MemoryDef *MD, const MemoryUseOrDef *MU,
  769. AliasAnalysis &AA);
  770. };
  771. // This pass does eager building and then printing of MemorySSA. It is used by
  772. // the tests to be able to build, dump, and verify Memory SSA.
  773. class MemorySSAPrinterLegacyPass : public FunctionPass {
  774. public:
  775. MemorySSAPrinterLegacyPass();
  776. bool runOnFunction(Function &) override;
  777. void getAnalysisUsage(AnalysisUsage &AU) const override;
  778. static char ID;
  779. };
  780. /// An analysis that produces \c MemorySSA for a function.
  781. ///
  782. class MemorySSAAnalysis : public AnalysisInfoMixin<MemorySSAAnalysis> {
  783. friend AnalysisInfoMixin<MemorySSAAnalysis>;
  784. static AnalysisKey Key;
  785. public:
  786. // Wrap MemorySSA result to ensure address stability of internal MemorySSA
  787. // pointers after construction. Use a wrapper class instead of plain
  788. // unique_ptr<MemorySSA> to avoid build breakage on MSVC.
  789. struct Result {
  790. Result(std::unique_ptr<MemorySSA> &&MSSA) : MSSA(std::move(MSSA)) {}
  791. MemorySSA &getMSSA() { return *MSSA.get(); }
  792. std::unique_ptr<MemorySSA> MSSA;
  793. bool invalidate(Function &F, const PreservedAnalyses &PA,
  794. FunctionAnalysisManager::Invalidator &Inv);
  795. };
  796. Result run(Function &F, FunctionAnalysisManager &AM);
  797. };
  798. /// Printer pass for \c MemorySSA.
  799. class MemorySSAPrinterPass : public PassInfoMixin<MemorySSAPrinterPass> {
  800. raw_ostream &OS;
  801. public:
  802. explicit MemorySSAPrinterPass(raw_ostream &OS) : OS(OS) {}
  803. PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
  804. };
  805. /// Printer pass for \c MemorySSA via the walker.
  806. class MemorySSAWalkerPrinterPass
  807. : public PassInfoMixin<MemorySSAWalkerPrinterPass> {
  808. raw_ostream &OS;
  809. public:
  810. explicit MemorySSAWalkerPrinterPass(raw_ostream &OS) : OS(OS) {}
  811. PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
  812. };
  813. /// Verifier pass for \c MemorySSA.
  814. struct MemorySSAVerifierPass : PassInfoMixin<MemorySSAVerifierPass> {
  815. PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
  816. };
  817. /// Legacy analysis pass which computes \c MemorySSA.
  818. class MemorySSAWrapperPass : public FunctionPass {
  819. public:
  820. MemorySSAWrapperPass();
  821. static char ID;
  822. bool runOnFunction(Function &) override;
  823. void releaseMemory() override;
  824. MemorySSA &getMSSA() { return *MSSA; }
  825. const MemorySSA &getMSSA() const { return *MSSA; }
  826. void getAnalysisUsage(AnalysisUsage &AU) const override;
  827. void verifyAnalysis() const override;
  828. void print(raw_ostream &OS, const Module *M = nullptr) const override;
  829. private:
  830. std::unique_ptr<MemorySSA> MSSA;
  831. };
  832. /// This is the generic walker interface for walkers of MemorySSA.
  833. /// Walkers are used to be able to further disambiguate the def-use chains
  834. /// MemorySSA gives you, or otherwise produce better info than MemorySSA gives
  835. /// you.
  836. /// In particular, while the def-use chains provide basic information, and are
  837. /// guaranteed to give, for example, the nearest may-aliasing MemoryDef for a
  838. /// MemoryUse as AliasAnalysis considers it, a user mant want better or other
  839. /// information. In particular, they may want to use SCEV info to further
  840. /// disambiguate memory accesses, or they may want the nearest dominating
  841. /// may-aliasing MemoryDef for a call or a store. This API enables a
  842. /// standardized interface to getting and using that info.
  843. class MemorySSAWalker {
  844. public:
  845. MemorySSAWalker(MemorySSA *);
  846. virtual ~MemorySSAWalker() = default;
  847. using MemoryAccessSet = SmallVector<MemoryAccess *, 8>;
  848. /// Given a memory Mod/Ref/ModRef'ing instruction, calling this
  849. /// will give you the nearest dominating MemoryAccess that Mod's the location
  850. /// the instruction accesses (by skipping any def which AA can prove does not
  851. /// alias the location(s) accessed by the instruction given).
  852. ///
  853. /// Note that this will return a single access, and it must dominate the
  854. /// Instruction, so if an operand of a MemoryPhi node Mod's the instruction,
  855. /// this will return the MemoryPhi, not the operand. This means that
  856. /// given:
  857. /// if (a) {
  858. /// 1 = MemoryDef(liveOnEntry)
  859. /// store %a
  860. /// } else {
  861. /// 2 = MemoryDef(liveOnEntry)
  862. /// store %b
  863. /// }
  864. /// 3 = MemoryPhi(2, 1)
  865. /// MemoryUse(3)
  866. /// load %a
  867. ///
  868. /// calling this API on load(%a) will return the MemoryPhi, not the MemoryDef
  869. /// in the if (a) branch.
  870. MemoryAccess *getClobberingMemoryAccess(const Instruction *I) {
  871. MemoryAccess *MA = MSSA->getMemoryAccess(I);
  872. assert(MA && "Handed an instruction that MemorySSA doesn't recognize?");
  873. return getClobberingMemoryAccess(MA);
  874. }
  875. /// Does the same thing as getClobberingMemoryAccess(const Instruction *I),
  876. /// but takes a MemoryAccess instead of an Instruction.
  877. virtual MemoryAccess *getClobberingMemoryAccess(MemoryAccess *) = 0;
  878. /// Given a potentially clobbering memory access and a new location,
  879. /// calling this will give you the nearest dominating clobbering MemoryAccess
  880. /// (by skipping non-aliasing def links).
  881. ///
  882. /// This version of the function is mainly used to disambiguate phi translated
  883. /// pointers, where the value of a pointer may have changed from the initial
  884. /// memory access. Note that this expects to be handed either a MemoryUse,
  885. /// or an already potentially clobbering access. Unlike the above API, if
  886. /// given a MemoryDef that clobbers the pointer as the starting access, it
  887. /// will return that MemoryDef, whereas the above would return the clobber
  888. /// starting from the use side of the memory def.
  889. virtual MemoryAccess *getClobberingMemoryAccess(MemoryAccess *,
  890. const MemoryLocation &) = 0;
  891. /// Given a memory access, invalidate anything this walker knows about
  892. /// that access.
  893. /// This API is used by walkers that store information to perform basic cache
  894. /// invalidation. This will be called by MemorySSA at appropriate times for
  895. /// the walker it uses or returns.
  896. virtual void invalidateInfo(MemoryAccess *) {}
  897. protected:
  898. friend class MemorySSA; // For updating MSSA pointer in MemorySSA move
  899. // constructor.
  900. MemorySSA *MSSA;
  901. };
  902. /// A MemorySSAWalker that does no alias queries, or anything else. It
  903. /// simply returns the links as they were constructed by the builder.
  904. class DoNothingMemorySSAWalker final : public MemorySSAWalker {
  905. public:
  906. // Keep the overrides below from hiding the Instruction overload of
  907. // getClobberingMemoryAccess.
  908. using MemorySSAWalker::getClobberingMemoryAccess;
  909. MemoryAccess *getClobberingMemoryAccess(MemoryAccess *) override;
  910. MemoryAccess *getClobberingMemoryAccess(MemoryAccess *,
  911. const MemoryLocation &) override;
  912. };
  913. using MemoryAccessPair = std::pair<MemoryAccess *, MemoryLocation>;
  914. using ConstMemoryAccessPair = std::pair<const MemoryAccess *, MemoryLocation>;
  915. /// Iterator base class used to implement const and non-const iterators
  916. /// over the defining accesses of a MemoryAccess.
  917. template <class T>
  918. class memoryaccess_def_iterator_base
  919. : public iterator_facade_base<memoryaccess_def_iterator_base<T>,
  920. std::forward_iterator_tag, T, ptrdiff_t, T *,
  921. T *> {
  922. using BaseT = typename memoryaccess_def_iterator_base::iterator_facade_base;
  923. public:
  924. memoryaccess_def_iterator_base(T *Start) : Access(Start) {}
  925. memoryaccess_def_iterator_base() = default;
  926. bool operator==(const memoryaccess_def_iterator_base &Other) const {
  927. return Access == Other.Access && (!Access || ArgNo == Other.ArgNo);
  928. }
  929. // This is a bit ugly, but for MemoryPHI's, unlike PHINodes, you can't get the
  930. // block from the operand in constant time (In a PHINode, the uselist has
  931. // both, so it's just subtraction). We provide it as part of the
  932. // iterator to avoid callers having to linear walk to get the block.
  933. // If the operation becomes constant time on MemoryPHI's, this bit of
  934. // abstraction breaking should be removed.
  935. BasicBlock *getPhiArgBlock() const {
  936. MemoryPhi *MP = dyn_cast<MemoryPhi>(Access);
  937. assert(MP && "Tried to get phi arg block when not iterating over a PHI");
  938. return MP->getIncomingBlock(ArgNo);
  939. }
  940. typename std::iterator_traits<BaseT>::pointer operator*() const {
  941. assert(Access && "Tried to access past the end of our iterator");
  942. // Go to the first argument for phis, and the defining access for everything
  943. // else.
  944. if (const MemoryPhi *MP = dyn_cast<MemoryPhi>(Access))
  945. return MP->getIncomingValue(ArgNo);
  946. return cast<MemoryUseOrDef>(Access)->getDefiningAccess();
  947. }
  948. using BaseT::operator++;
  949. memoryaccess_def_iterator_base &operator++() {
  950. assert(Access && "Hit end of iterator");
  951. if (const MemoryPhi *MP = dyn_cast<MemoryPhi>(Access)) {
  952. if (++ArgNo >= MP->getNumIncomingValues()) {
  953. ArgNo = 0;
  954. Access = nullptr;
  955. }
  956. } else {
  957. Access = nullptr;
  958. }
  959. return *this;
  960. }
  961. private:
  962. T *Access = nullptr;
  963. unsigned ArgNo = 0;
  964. };
  965. inline memoryaccess_def_iterator MemoryAccess::defs_begin() {
  966. return memoryaccess_def_iterator(this);
  967. }
  968. inline const_memoryaccess_def_iterator MemoryAccess::defs_begin() const {
  969. return const_memoryaccess_def_iterator(this);
  970. }
  971. inline memoryaccess_def_iterator MemoryAccess::defs_end() {
  972. return memoryaccess_def_iterator();
  973. }
  974. inline const_memoryaccess_def_iterator MemoryAccess::defs_end() const {
  975. return const_memoryaccess_def_iterator();
  976. }
  977. /// GraphTraits for a MemoryAccess, which walks defs in the normal case,
  978. /// and uses in the inverse case.
  979. template <> struct GraphTraits<MemoryAccess *> {
  980. using NodeRef = MemoryAccess *;
  981. using ChildIteratorType = memoryaccess_def_iterator;
  982. static NodeRef getEntryNode(NodeRef N) { return N; }
  983. static ChildIteratorType child_begin(NodeRef N) { return N->defs_begin(); }
  984. static ChildIteratorType child_end(NodeRef N) { return N->defs_end(); }
  985. };
  986. template <> struct GraphTraits<Inverse<MemoryAccess *>> {
  987. using NodeRef = MemoryAccess *;
  988. using ChildIteratorType = MemoryAccess::iterator;
  989. static NodeRef getEntryNode(NodeRef N) { return N; }
  990. static ChildIteratorType child_begin(NodeRef N) { return N->user_begin(); }
  991. static ChildIteratorType child_end(NodeRef N) { return N->user_end(); }
  992. };
  993. /// Provide an iterator that walks defs, giving both the memory access,
  994. /// and the current pointer location, updating the pointer location as it
  995. /// changes due to phi node translation.
  996. ///
  997. /// This iterator, while somewhat specialized, is what most clients actually
  998. /// want when walking upwards through MemorySSA def chains. It takes a pair of
  999. /// <MemoryAccess,MemoryLocation>, and walks defs, properly translating the
  1000. /// memory location through phi nodes for the user.
  1001. class upward_defs_iterator
  1002. : public iterator_facade_base<upward_defs_iterator,
  1003. std::forward_iterator_tag,
  1004. const MemoryAccessPair> {
  1005. using BaseT = upward_defs_iterator::iterator_facade_base;
  1006. public:
  1007. upward_defs_iterator(const MemoryAccessPair &Info, DominatorTree *DT,
  1008. bool *PerformedPhiTranslation = nullptr)
  1009. : DefIterator(Info.first), Location(Info.second),
  1010. OriginalAccess(Info.first), DT(DT),
  1011. PerformedPhiTranslation(PerformedPhiTranslation) {
  1012. CurrentPair.first = nullptr;
  1013. WalkingPhi = Info.first && isa<MemoryPhi>(Info.first);
  1014. fillInCurrentPair();
  1015. }
  1016. upward_defs_iterator() { CurrentPair.first = nullptr; }
  1017. bool operator==(const upward_defs_iterator &Other) const {
  1018. return DefIterator == Other.DefIterator;
  1019. }
  1020. typename std::iterator_traits<BaseT>::reference operator*() const {
  1021. assert(DefIterator != OriginalAccess->defs_end() &&
  1022. "Tried to access past the end of our iterator");
  1023. return CurrentPair;
  1024. }
  1025. using BaseT::operator++;
  1026. upward_defs_iterator &operator++() {
  1027. assert(DefIterator != OriginalAccess->defs_end() &&
  1028. "Tried to access past the end of the iterator");
  1029. ++DefIterator;
  1030. if (DefIterator != OriginalAccess->defs_end())
  1031. fillInCurrentPair();
  1032. return *this;
  1033. }
  1034. BasicBlock *getPhiArgBlock() const { return DefIterator.getPhiArgBlock(); }
  1035. private:
  1036. /// Returns true if \p Ptr is guaranteed to be loop invariant for any possible
  1037. /// loop. In particular, this guarantees that it only references a single
  1038. /// MemoryLocation during execution of the containing function.
  1039. bool IsGuaranteedLoopInvariant(Value *Ptr) const;
  1040. void fillInCurrentPair() {
  1041. CurrentPair.first = *DefIterator;
  1042. CurrentPair.second = Location;
  1043. if (WalkingPhi && Location.Ptr) {
  1044. // Mark size as unknown, if the location is not guaranteed to be
  1045. // loop-invariant for any possible loop in the function. Setting the size
  1046. // to unknown guarantees that any memory accesses that access locations
  1047. // after the pointer are considered as clobbers, which is important to
  1048. // catch loop carried dependences.
  1049. if (Location.Ptr &&
  1050. !IsGuaranteedLoopInvariant(const_cast<Value *>(Location.Ptr)))
  1051. CurrentPair.second =
  1052. Location.getWithNewSize(LocationSize::beforeOrAfterPointer());
  1053. PHITransAddr Translator(
  1054. const_cast<Value *>(Location.Ptr),
  1055. OriginalAccess->getBlock()->getModule()->getDataLayout(), nullptr);
  1056. if (!Translator.PHITranslateValue(OriginalAccess->getBlock(),
  1057. DefIterator.getPhiArgBlock(), DT,
  1058. true)) {
  1059. Value *TransAddr = Translator.getAddr();
  1060. if (TransAddr != Location.Ptr) {
  1061. CurrentPair.second = CurrentPair.second.getWithNewPtr(TransAddr);
  1062. if (TransAddr &&
  1063. !IsGuaranteedLoopInvariant(const_cast<Value *>(TransAddr)))
  1064. CurrentPair.second = CurrentPair.second.getWithNewSize(
  1065. LocationSize::beforeOrAfterPointer());
  1066. if (PerformedPhiTranslation)
  1067. *PerformedPhiTranslation = true;
  1068. }
  1069. }
  1070. }
  1071. }
  1072. MemoryAccessPair CurrentPair;
  1073. memoryaccess_def_iterator DefIterator;
  1074. MemoryLocation Location;
  1075. MemoryAccess *OriginalAccess = nullptr;
  1076. DominatorTree *DT = nullptr;
  1077. bool WalkingPhi = false;
  1078. bool *PerformedPhiTranslation = nullptr;
  1079. };
  1080. inline upward_defs_iterator
  1081. upward_defs_begin(const MemoryAccessPair &Pair, DominatorTree &DT,
  1082. bool *PerformedPhiTranslation = nullptr) {
  1083. return upward_defs_iterator(Pair, &DT, PerformedPhiTranslation);
  1084. }
  1085. inline upward_defs_iterator upward_defs_end() { return upward_defs_iterator(); }
  1086. inline iterator_range<upward_defs_iterator>
  1087. upward_defs(const MemoryAccessPair &Pair, DominatorTree &DT) {
  1088. return make_range(upward_defs_begin(Pair, DT), upward_defs_end());
  1089. }
  1090. /// Walks the defining accesses of MemoryDefs. Stops after we hit something that
  1091. /// has no defining use (e.g. a MemoryPhi or liveOnEntry). Note that, when
  1092. /// comparing against a null def_chain_iterator, this will compare equal only
  1093. /// after walking said Phi/liveOnEntry.
  1094. ///
  1095. /// The UseOptimizedChain flag specifies whether to walk the clobbering
  1096. /// access chain, or all the accesses.
  1097. ///
  1098. /// Normally, MemoryDef are all just def/use linked together, so a def_chain on
  1099. /// a MemoryDef will walk all MemoryDefs above it in the program until it hits
  1100. /// a phi node. The optimized chain walks the clobbering access of a store.
  1101. /// So if you are just trying to find, given a store, what the next
  1102. /// thing that would clobber the same memory is, you want the optimized chain.
  1103. template <class T, bool UseOptimizedChain = false>
  1104. struct def_chain_iterator
  1105. : public iterator_facade_base<def_chain_iterator<T, UseOptimizedChain>,
  1106. std::forward_iterator_tag, MemoryAccess *> {
  1107. def_chain_iterator() : MA(nullptr) {}
  1108. def_chain_iterator(T MA) : MA(MA) {}
  1109. T operator*() const { return MA; }
  1110. def_chain_iterator &operator++() {
  1111. // N.B. liveOnEntry has a null defining access.
  1112. if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA)) {
  1113. if (UseOptimizedChain && MUD->isOptimized())
  1114. MA = MUD->getOptimized();
  1115. else
  1116. MA = MUD->getDefiningAccess();
  1117. } else {
  1118. MA = nullptr;
  1119. }
  1120. return *this;
  1121. }
  1122. bool operator==(const def_chain_iterator &O) const { return MA == O.MA; }
  1123. private:
  1124. T MA;
  1125. };
  1126. template <class T>
  1127. inline iterator_range<def_chain_iterator<T>>
  1128. def_chain(T MA, MemoryAccess *UpTo = nullptr) {
  1129. #ifdef EXPENSIVE_CHECKS
  1130. assert((!UpTo || find(def_chain(MA), UpTo) != def_chain_iterator<T>()) &&
  1131. "UpTo isn't in the def chain!");
  1132. #endif
  1133. return make_range(def_chain_iterator<T>(MA), def_chain_iterator<T>(UpTo));
  1134. }
  1135. template <class T>
  1136. inline iterator_range<def_chain_iterator<T, true>> optimized_def_chain(T MA) {
  1137. return make_range(def_chain_iterator<T, true>(MA),
  1138. def_chain_iterator<T, true>(nullptr));
  1139. }
  1140. } // end namespace llvm
  1141. #endif // LLVM_ANALYSIS_MEMORYSSA_H
  1142. #ifdef __GNUC__
  1143. #pragma GCC diagnostic pop
  1144. #endif