VirtualInstruction.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. //===------ VirtualInstruction.cpp ------------------------------*- C++ -*-===//
  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. // Tools for determining which instructions are within a statement and the
  10. // nature of their operands.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "polly/Support/VirtualInstruction.h"
  14. using namespace polly;
  15. using namespace llvm;
  16. VirtualUse VirtualUse::create(Scop *S, const Use &U, LoopInfo *LI,
  17. bool Virtual) {
  18. auto *UserBB = getUseBlock(U);
  19. Loop *UserScope = LI->getLoopFor(UserBB);
  20. Instruction *UI = dyn_cast<Instruction>(U.getUser());
  21. ScopStmt *UserStmt = S->getStmtFor(UI);
  22. // Uses by PHI nodes are always reading values written by other statements,
  23. // except it is within a region statement.
  24. if (PHINode *PHI = dyn_cast<PHINode>(UI)) {
  25. // Handle PHI in exit block.
  26. if (S->getRegion().getExit() == PHI->getParent())
  27. return VirtualUse(UserStmt, U.get(), Inter, nullptr, nullptr);
  28. if (UserStmt->getEntryBlock() != PHI->getParent())
  29. return VirtualUse(UserStmt, U.get(), Intra, nullptr, nullptr);
  30. // The MemoryAccess is expected to be set if @p Virtual is true.
  31. MemoryAccess *IncomingMA = nullptr;
  32. if (Virtual) {
  33. if (const ScopArrayInfo *SAI =
  34. S->getScopArrayInfoOrNull(PHI, MemoryKind::PHI)) {
  35. IncomingMA = S->getPHIRead(SAI);
  36. assert(IncomingMA->getStatement() == UserStmt);
  37. }
  38. }
  39. return VirtualUse(UserStmt, U.get(), Inter, nullptr, IncomingMA);
  40. }
  41. return create(S, UserStmt, UserScope, U.get(), Virtual);
  42. }
  43. VirtualUse VirtualUse::create(Scop *S, ScopStmt *UserStmt, Loop *UserScope,
  44. Value *Val, bool Virtual) {
  45. assert(!isa<StoreInst>(Val) && "a StoreInst cannot be used");
  46. if (isa<BasicBlock>(Val))
  47. return VirtualUse(UserStmt, Val, Block, nullptr, nullptr);
  48. if (isa<llvm::Constant>(Val) || isa<MetadataAsValue>(Val) ||
  49. isa<InlineAsm>(Val))
  50. return VirtualUse(UserStmt, Val, Constant, nullptr, nullptr);
  51. // Is the value synthesizable? If the user has been pruned
  52. // (UserStmt == nullptr), it is either not used anywhere or is synthesizable.
  53. // We assume synthesizable which practically should have the same effect.
  54. auto *SE = S->getSE();
  55. if (SE->isSCEVable(Val->getType())) {
  56. auto *ScevExpr = SE->getSCEVAtScope(Val, UserScope);
  57. if (!UserStmt || canSynthesize(Val, *UserStmt->getParent(), SE, UserScope))
  58. return VirtualUse(UserStmt, Val, Synthesizable, ScevExpr, nullptr);
  59. }
  60. // FIXME: Inconsistency between lookupInvariantEquivClass and
  61. // getRequiredInvariantLoads. Querying one of them should be enough.
  62. auto &RIL = S->getRequiredInvariantLoads();
  63. if (S->lookupInvariantEquivClass(Val) || RIL.count(dyn_cast<LoadInst>(Val)))
  64. return VirtualUse(UserStmt, Val, Hoisted, nullptr, nullptr);
  65. // ReadOnly uses may have MemoryAccesses that we want to associate with the
  66. // use. This is why we look for a MemoryAccess here already.
  67. MemoryAccess *InputMA = nullptr;
  68. if (UserStmt && Virtual)
  69. InputMA = UserStmt->lookupValueReadOf(Val);
  70. // Uses are read-only if they have been defined before the SCoP, i.e., they
  71. // cannot be written to inside the SCoP. Arguments are defined before any
  72. // instructions, hence also before the SCoP. If the user has been pruned
  73. // (UserStmt == nullptr) and is not SCEVable, assume it is read-only as it is
  74. // neither an intra- nor an inter-use.
  75. if (!UserStmt || isa<Argument>(Val))
  76. return VirtualUse(UserStmt, Val, ReadOnly, nullptr, InputMA);
  77. auto Inst = cast<Instruction>(Val);
  78. if (!S->contains(Inst))
  79. return VirtualUse(UserStmt, Val, ReadOnly, nullptr, InputMA);
  80. // A use is inter-statement if either it is defined in another statement, or
  81. // there is a MemoryAccess that reads its value that has been written by
  82. // another statement.
  83. if (InputMA || (!Virtual && UserStmt != S->getStmtFor(Inst)))
  84. return VirtualUse(UserStmt, Val, Inter, nullptr, InputMA);
  85. return VirtualUse(UserStmt, Val, Intra, nullptr, nullptr);
  86. }
  87. void VirtualUse::print(raw_ostream &OS, bool Reproducible) const {
  88. OS << "User: [" << User->getBaseName() << "] ";
  89. switch (Kind) {
  90. case VirtualUse::Constant:
  91. OS << "Constant Op:";
  92. break;
  93. case VirtualUse::Block:
  94. OS << "BasicBlock Op:";
  95. break;
  96. case VirtualUse::Synthesizable:
  97. OS << "Synthesizable Op:";
  98. break;
  99. case VirtualUse::Hoisted:
  100. OS << "Hoisted load Op:";
  101. break;
  102. case VirtualUse::ReadOnly:
  103. OS << "Read-Only Op:";
  104. break;
  105. case VirtualUse::Intra:
  106. OS << "Intra Op:";
  107. break;
  108. case VirtualUse::Inter:
  109. OS << "Inter Op:";
  110. break;
  111. }
  112. if (Val) {
  113. OS << ' ';
  114. if (Reproducible)
  115. OS << '"' << Val->getName() << '"';
  116. else
  117. Val->print(OS, true);
  118. }
  119. if (ScevExpr) {
  120. OS << ' ';
  121. ScevExpr->print(OS);
  122. }
  123. if (InputMA && !Reproducible)
  124. OS << ' ' << InputMA;
  125. }
  126. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  127. LLVM_DUMP_METHOD void VirtualUse::dump() const {
  128. print(errs(), false);
  129. errs() << '\n';
  130. }
  131. #endif
  132. void VirtualInstruction::print(raw_ostream &OS, bool Reproducible) const {
  133. if (!Stmt || !Inst) {
  134. OS << "[null VirtualInstruction]";
  135. return;
  136. }
  137. OS << "[" << Stmt->getBaseName() << "]";
  138. Inst->print(OS, !Reproducible);
  139. }
  140. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  141. LLVM_DUMP_METHOD void VirtualInstruction::dump() const {
  142. print(errs(), false);
  143. errs() << '\n';
  144. }
  145. #endif
  146. /// Return true if @p Inst cannot be removed, even if it is nowhere referenced.
  147. static bool isRoot(const Instruction *Inst) {
  148. // The store is handled by its MemoryAccess. The load must be reached from the
  149. // roots in order to be marked as used.
  150. if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
  151. return false;
  152. // Terminator instructions (in region statements) are required for control
  153. // flow.
  154. if (Inst->isTerminator())
  155. return true;
  156. // Writes to memory must be honored.
  157. if (Inst->mayWriteToMemory())
  158. return true;
  159. return false;
  160. }
  161. /// Return true for MemoryAccesses that cannot be removed because it represents
  162. /// an llvm::Value that is used after the SCoP.
  163. static bool isEscaping(MemoryAccess *MA) {
  164. assert(MA->isOriginalValueKind());
  165. Scop *S = MA->getStatement()->getParent();
  166. return S->isEscaping(cast<Instruction>(MA->getAccessValue()));
  167. }
  168. /// Add non-removable virtual instructions in @p Stmt to @p RootInsts.
  169. static void
  170. addInstructionRoots(ScopStmt *Stmt,
  171. SmallVectorImpl<VirtualInstruction> &RootInsts) {
  172. if (!Stmt->isBlockStmt()) {
  173. // In region statements the terminator statement and all statements that
  174. // are not in the entry block cannot be eliminated and consequently must
  175. // be roots.
  176. RootInsts.emplace_back(Stmt,
  177. Stmt->getRegion()->getEntry()->getTerminator());
  178. for (BasicBlock *BB : Stmt->getRegion()->blocks())
  179. if (Stmt->getRegion()->getEntry() != BB)
  180. for (Instruction &Inst : *BB)
  181. RootInsts.emplace_back(Stmt, &Inst);
  182. return;
  183. }
  184. for (Instruction *Inst : Stmt->getInstructions())
  185. if (isRoot(Inst))
  186. RootInsts.emplace_back(Stmt, Inst);
  187. }
  188. /// Add non-removable memory accesses in @p Stmt to @p RootInsts.
  189. ///
  190. /// @param Local If true, all writes are assumed to escape. markAndSweep
  191. /// algorithms can use this to be applicable to a single ScopStmt only without
  192. /// the risk of removing definitions required by other statements.
  193. /// If false, only writes for SCoP-escaping values are roots. This
  194. /// is global mode, where such writes must be marked by theirs uses
  195. /// in order to be reachable.
  196. static void addAccessRoots(ScopStmt *Stmt,
  197. SmallVectorImpl<MemoryAccess *> &RootAccs,
  198. bool Local) {
  199. for (auto *MA : *Stmt) {
  200. if (!MA->isWrite())
  201. continue;
  202. // Writes to arrays are always used.
  203. if (MA->isLatestArrayKind())
  204. RootAccs.push_back(MA);
  205. // Values are roots if they are escaping.
  206. else if (MA->isLatestValueKind()) {
  207. if (Local || isEscaping(MA))
  208. RootAccs.push_back(MA);
  209. }
  210. // Exit phis are, by definition, escaping.
  211. else if (MA->isLatestExitPHIKind())
  212. RootAccs.push_back(MA);
  213. // phi writes are only roots if we are not visiting the statement
  214. // containing the PHINode.
  215. else if (Local && MA->isLatestPHIKind())
  216. RootAccs.push_back(MA);
  217. }
  218. }
  219. /// Determine all instruction and access roots.
  220. static void addRoots(ScopStmt *Stmt,
  221. SmallVectorImpl<VirtualInstruction> &RootInsts,
  222. SmallVectorImpl<MemoryAccess *> &RootAccs, bool Local) {
  223. addInstructionRoots(Stmt, RootInsts);
  224. addAccessRoots(Stmt, RootAccs, Local);
  225. }
  226. /// Mark accesses and instructions as used if they are reachable from a root,
  227. /// walking the operand trees.
  228. ///
  229. /// @param S The SCoP to walk.
  230. /// @param LI The LoopInfo Analysis.
  231. /// @param RootInsts List of root instructions.
  232. /// @param RootAccs List of root accesses.
  233. /// @param UsesInsts[out] Receives all reachable instructions, including the
  234. /// roots.
  235. /// @param UsedAccs[out] Receives all reachable accesses, including the roots.
  236. /// @param OnlyLocal If non-nullptr, restricts walking to a single
  237. /// statement.
  238. static void walkReachable(Scop *S, LoopInfo *LI,
  239. ArrayRef<VirtualInstruction> RootInsts,
  240. ArrayRef<MemoryAccess *> RootAccs,
  241. DenseSet<VirtualInstruction> &UsedInsts,
  242. DenseSet<MemoryAccess *> &UsedAccs,
  243. ScopStmt *OnlyLocal = nullptr) {
  244. UsedInsts.clear();
  245. UsedAccs.clear();
  246. SmallVector<VirtualInstruction, 32> WorklistInsts;
  247. SmallVector<MemoryAccess *, 32> WorklistAccs;
  248. WorklistInsts.append(RootInsts.begin(), RootInsts.end());
  249. WorklistAccs.append(RootAccs.begin(), RootAccs.end());
  250. auto AddToWorklist = [&](VirtualUse VUse) {
  251. switch (VUse.getKind()) {
  252. case VirtualUse::Block:
  253. case VirtualUse::Constant:
  254. case VirtualUse::Synthesizable:
  255. case VirtualUse::Hoisted:
  256. break;
  257. case VirtualUse::ReadOnly:
  258. // Read-only scalars only have MemoryAccesses if ModelReadOnlyScalars is
  259. // enabled.
  260. if (!VUse.getMemoryAccess())
  261. break;
  262. [[fallthrough]];
  263. case VirtualUse::Inter:
  264. assert(VUse.getMemoryAccess());
  265. WorklistAccs.push_back(VUse.getMemoryAccess());
  266. break;
  267. case VirtualUse::Intra:
  268. WorklistInsts.emplace_back(VUse.getUser(),
  269. cast<Instruction>(VUse.getValue()));
  270. break;
  271. }
  272. };
  273. while (true) {
  274. // We have two worklists to process: Only when the MemoryAccess worklist is
  275. // empty, we process the instruction worklist.
  276. while (!WorklistAccs.empty()) {
  277. auto *Acc = WorklistAccs.pop_back_val();
  278. ScopStmt *Stmt = Acc->getStatement();
  279. if (OnlyLocal && Stmt != OnlyLocal)
  280. continue;
  281. auto Inserted = UsedAccs.insert(Acc);
  282. if (!Inserted.second)
  283. continue;
  284. if (Acc->isRead()) {
  285. const ScopArrayInfo *SAI = Acc->getScopArrayInfo();
  286. if (Acc->isLatestValueKind()) {
  287. MemoryAccess *DefAcc = S->getValueDef(SAI);
  288. // Accesses to read-only values do not have a definition.
  289. if (DefAcc)
  290. WorklistAccs.push_back(S->getValueDef(SAI));
  291. }
  292. if (Acc->isLatestAnyPHIKind()) {
  293. auto IncomingMAs = S->getPHIIncomings(SAI);
  294. WorklistAccs.append(IncomingMAs.begin(), IncomingMAs.end());
  295. }
  296. }
  297. if (Acc->isWrite()) {
  298. if (Acc->isOriginalValueKind() ||
  299. (Acc->isOriginalArrayKind() && Acc->getAccessValue())) {
  300. Loop *Scope = Stmt->getSurroundingLoop();
  301. VirtualUse VUse =
  302. VirtualUse::create(S, Stmt, Scope, Acc->getAccessValue(), true);
  303. AddToWorklist(VUse);
  304. }
  305. if (Acc->isOriginalAnyPHIKind()) {
  306. for (auto Incoming : Acc->getIncoming()) {
  307. VirtualUse VUse = VirtualUse::create(
  308. S, Stmt, LI->getLoopFor(Incoming.first), Incoming.second, true);
  309. AddToWorklist(VUse);
  310. }
  311. }
  312. if (Acc->isOriginalArrayKind())
  313. WorklistInsts.emplace_back(Stmt, Acc->getAccessInstruction());
  314. }
  315. }
  316. // If both worklists are empty, stop walking.
  317. if (WorklistInsts.empty())
  318. break;
  319. VirtualInstruction VInst = WorklistInsts.pop_back_val();
  320. ScopStmt *Stmt = VInst.getStmt();
  321. Instruction *Inst = VInst.getInstruction();
  322. // Do not process statements other than the local.
  323. if (OnlyLocal && Stmt != OnlyLocal)
  324. continue;
  325. auto InsertResult = UsedInsts.insert(VInst);
  326. if (!InsertResult.second)
  327. continue;
  328. // Add all operands to the worklists.
  329. PHINode *PHI = dyn_cast<PHINode>(Inst);
  330. if (PHI && PHI->getParent() == Stmt->getEntryBlock()) {
  331. if (MemoryAccess *PHIRead = Stmt->lookupPHIReadOf(PHI))
  332. WorklistAccs.push_back(PHIRead);
  333. } else {
  334. for (VirtualUse VUse : VInst.operands())
  335. AddToWorklist(VUse);
  336. }
  337. // If there is an array access, also add its MemoryAccesses to the worklist.
  338. const MemoryAccessList *Accs = Stmt->lookupArrayAccessesFor(Inst);
  339. if (!Accs)
  340. continue;
  341. for (MemoryAccess *Acc : *Accs)
  342. WorklistAccs.push_back(Acc);
  343. }
  344. }
  345. void polly::markReachable(Scop *S, LoopInfo *LI,
  346. DenseSet<VirtualInstruction> &UsedInsts,
  347. DenseSet<MemoryAccess *> &UsedAccs,
  348. ScopStmt *OnlyLocal) {
  349. SmallVector<VirtualInstruction, 32> RootInsts;
  350. SmallVector<MemoryAccess *, 32> RootAccs;
  351. if (OnlyLocal) {
  352. addRoots(OnlyLocal, RootInsts, RootAccs, true);
  353. } else {
  354. for (auto &Stmt : *S)
  355. addRoots(&Stmt, RootInsts, RootAccs, false);
  356. }
  357. walkReachable(S, LI, RootInsts, RootAccs, UsedInsts, UsedAccs, OnlyLocal);
  358. }