MustExecute.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876
  1. //===- MustExecute.cpp - Printer for isGuaranteedToExecute ----------------===//
  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. #include "llvm/Analysis/MustExecute.h"
  9. #include "llvm/ADT/PostOrderIterator.h"
  10. #include "llvm/ADT/StringExtras.h"
  11. #include "llvm/Analysis/CFG.h"
  12. #include "llvm/Analysis/InstructionSimplify.h"
  13. #include "llvm/Analysis/LoopInfo.h"
  14. #include "llvm/Analysis/Passes.h"
  15. #include "llvm/Analysis/PostDominators.h"
  16. #include "llvm/Analysis/ValueTracking.h"
  17. #include "llvm/IR/AssemblyAnnotationWriter.h"
  18. #include "llvm/IR/DataLayout.h"
  19. #include "llvm/IR/Dominators.h"
  20. #include "llvm/IR/InstIterator.h"
  21. #include "llvm/IR/LLVMContext.h"
  22. #include "llvm/IR/Module.h"
  23. #include "llvm/IR/PassManager.h"
  24. #include "llvm/InitializePasses.h"
  25. #include "llvm/Support/ErrorHandling.h"
  26. #include "llvm/Support/FormattedStream.h"
  27. #include "llvm/Support/raw_ostream.h"
  28. using namespace llvm;
  29. #define DEBUG_TYPE "must-execute"
  30. const DenseMap<BasicBlock *, ColorVector> &
  31. LoopSafetyInfo::getBlockColors() const {
  32. return BlockColors;
  33. }
  34. void LoopSafetyInfo::copyColors(BasicBlock *New, BasicBlock *Old) {
  35. ColorVector &ColorsForNewBlock = BlockColors[New];
  36. ColorVector &ColorsForOldBlock = BlockColors[Old];
  37. ColorsForNewBlock = ColorsForOldBlock;
  38. }
  39. bool SimpleLoopSafetyInfo::blockMayThrow(const BasicBlock *BB) const {
  40. (void)BB;
  41. return anyBlockMayThrow();
  42. }
  43. bool SimpleLoopSafetyInfo::anyBlockMayThrow() const {
  44. return MayThrow;
  45. }
  46. void SimpleLoopSafetyInfo::computeLoopSafetyInfo(const Loop *CurLoop) {
  47. assert(CurLoop != nullptr && "CurLoop can't be null");
  48. BasicBlock *Header = CurLoop->getHeader();
  49. // Iterate over header and compute safety info.
  50. HeaderMayThrow = !isGuaranteedToTransferExecutionToSuccessor(Header);
  51. MayThrow = HeaderMayThrow;
  52. // Iterate over loop instructions and compute safety info.
  53. // Skip header as it has been computed and stored in HeaderMayThrow.
  54. // The first block in loopinfo.Blocks is guaranteed to be the header.
  55. assert(Header == *CurLoop->getBlocks().begin() &&
  56. "First block must be header");
  57. for (Loop::block_iterator BB = std::next(CurLoop->block_begin()),
  58. BBE = CurLoop->block_end();
  59. (BB != BBE) && !MayThrow; ++BB)
  60. MayThrow |= !isGuaranteedToTransferExecutionToSuccessor(*BB);
  61. computeBlockColors(CurLoop);
  62. }
  63. bool ICFLoopSafetyInfo::blockMayThrow(const BasicBlock *BB) const {
  64. return ICF.hasICF(BB);
  65. }
  66. bool ICFLoopSafetyInfo::anyBlockMayThrow() const {
  67. return MayThrow;
  68. }
  69. void ICFLoopSafetyInfo::computeLoopSafetyInfo(const Loop *CurLoop) {
  70. assert(CurLoop != nullptr && "CurLoop can't be null");
  71. ICF.clear();
  72. MW.clear();
  73. MayThrow = false;
  74. // Figure out the fact that at least one block may throw.
  75. for (auto &BB : CurLoop->blocks())
  76. if (ICF.hasICF(&*BB)) {
  77. MayThrow = true;
  78. break;
  79. }
  80. computeBlockColors(CurLoop);
  81. }
  82. void ICFLoopSafetyInfo::insertInstructionTo(const Instruction *Inst,
  83. const BasicBlock *BB) {
  84. ICF.insertInstructionTo(Inst, BB);
  85. MW.insertInstructionTo(Inst, BB);
  86. }
  87. void ICFLoopSafetyInfo::removeInstruction(const Instruction *Inst) {
  88. ICF.removeInstruction(Inst);
  89. MW.removeInstruction(Inst);
  90. }
  91. void LoopSafetyInfo::computeBlockColors(const Loop *CurLoop) {
  92. // Compute funclet colors if we might sink/hoist in a function with a funclet
  93. // personality routine.
  94. Function *Fn = CurLoop->getHeader()->getParent();
  95. if (Fn->hasPersonalityFn())
  96. if (Constant *PersonalityFn = Fn->getPersonalityFn())
  97. if (isScopedEHPersonality(classifyEHPersonality(PersonalityFn)))
  98. BlockColors = colorEHFunclets(*Fn);
  99. }
  100. /// Return true if we can prove that the given ExitBlock is not reached on the
  101. /// first iteration of the given loop. That is, the backedge of the loop must
  102. /// be executed before the ExitBlock is executed in any dynamic execution trace.
  103. static bool CanProveNotTakenFirstIteration(const BasicBlock *ExitBlock,
  104. const DominatorTree *DT,
  105. const Loop *CurLoop) {
  106. auto *CondExitBlock = ExitBlock->getSinglePredecessor();
  107. if (!CondExitBlock)
  108. // expect unique exits
  109. return false;
  110. assert(CurLoop->contains(CondExitBlock) && "meaning of exit block");
  111. auto *BI = dyn_cast<BranchInst>(CondExitBlock->getTerminator());
  112. if (!BI || !BI->isConditional())
  113. return false;
  114. // If condition is constant and false leads to ExitBlock then we always
  115. // execute the true branch.
  116. if (auto *Cond = dyn_cast<ConstantInt>(BI->getCondition()))
  117. return BI->getSuccessor(Cond->getZExtValue() ? 1 : 0) == ExitBlock;
  118. auto *Cond = dyn_cast<CmpInst>(BI->getCondition());
  119. if (!Cond)
  120. return false;
  121. // todo: this would be a lot more powerful if we used scev, but all the
  122. // plumbing is currently missing to pass a pointer in from the pass
  123. // Check for cmp (phi [x, preheader] ...), y where (pred x, y is known
  124. auto *LHS = dyn_cast<PHINode>(Cond->getOperand(0));
  125. auto *RHS = Cond->getOperand(1);
  126. if (!LHS || LHS->getParent() != CurLoop->getHeader())
  127. return false;
  128. auto DL = ExitBlock->getModule()->getDataLayout();
  129. auto *IVStart = LHS->getIncomingValueForBlock(CurLoop->getLoopPreheader());
  130. auto *SimpleValOrNull = SimplifyCmpInst(Cond->getPredicate(),
  131. IVStart, RHS,
  132. {DL, /*TLI*/ nullptr,
  133. DT, /*AC*/ nullptr, BI});
  134. auto *SimpleCst = dyn_cast_or_null<Constant>(SimpleValOrNull);
  135. if (!SimpleCst)
  136. return false;
  137. if (ExitBlock == BI->getSuccessor(0))
  138. return SimpleCst->isZeroValue();
  139. assert(ExitBlock == BI->getSuccessor(1) && "implied by above");
  140. return SimpleCst->isAllOnesValue();
  141. }
  142. /// Collect all blocks from \p CurLoop which lie on all possible paths from
  143. /// the header of \p CurLoop (inclusive) to BB (exclusive) into the set
  144. /// \p Predecessors. If \p BB is the header, \p Predecessors will be empty.
  145. static void collectTransitivePredecessors(
  146. const Loop *CurLoop, const BasicBlock *BB,
  147. SmallPtrSetImpl<const BasicBlock *> &Predecessors) {
  148. assert(Predecessors.empty() && "Garbage in predecessors set?");
  149. assert(CurLoop->contains(BB) && "Should only be called for loop blocks!");
  150. if (BB == CurLoop->getHeader())
  151. return;
  152. SmallVector<const BasicBlock *, 4> WorkList;
  153. for (auto *Pred : predecessors(BB)) {
  154. Predecessors.insert(Pred);
  155. WorkList.push_back(Pred);
  156. }
  157. while (!WorkList.empty()) {
  158. auto *Pred = WorkList.pop_back_val();
  159. assert(CurLoop->contains(Pred) && "Should only reach loop blocks!");
  160. // We are not interested in backedges and we don't want to leave loop.
  161. if (Pred == CurLoop->getHeader())
  162. continue;
  163. // TODO: If BB lies in an inner loop of CurLoop, this will traverse over all
  164. // blocks of this inner loop, even those that are always executed AFTER the
  165. // BB. It may make our analysis more conservative than it could be, see test
  166. // @nested and @nested_no_throw in test/Analysis/MustExecute/loop-header.ll.
  167. // We can ignore backedge of all loops containing BB to get a sligtly more
  168. // optimistic result.
  169. for (auto *PredPred : predecessors(Pred))
  170. if (Predecessors.insert(PredPred).second)
  171. WorkList.push_back(PredPred);
  172. }
  173. }
  174. bool LoopSafetyInfo::allLoopPathsLeadToBlock(const Loop *CurLoop,
  175. const BasicBlock *BB,
  176. const DominatorTree *DT) const {
  177. assert(CurLoop->contains(BB) && "Should only be called for loop blocks!");
  178. // Fast path: header is always reached once the loop is entered.
  179. if (BB == CurLoop->getHeader())
  180. return true;
  181. // Collect all transitive predecessors of BB in the same loop. This set will
  182. // be a subset of the blocks within the loop.
  183. SmallPtrSet<const BasicBlock *, 4> Predecessors;
  184. collectTransitivePredecessors(CurLoop, BB, Predecessors);
  185. // Make sure that all successors of, all predecessors of BB which are not
  186. // dominated by BB, are either:
  187. // 1) BB,
  188. // 2) Also predecessors of BB,
  189. // 3) Exit blocks which are not taken on 1st iteration.
  190. // Memoize blocks we've already checked.
  191. SmallPtrSet<const BasicBlock *, 4> CheckedSuccessors;
  192. for (auto *Pred : Predecessors) {
  193. // Predecessor block may throw, so it has a side exit.
  194. if (blockMayThrow(Pred))
  195. return false;
  196. // BB dominates Pred, so if Pred runs, BB must run.
  197. // This is true when Pred is a loop latch.
  198. if (DT->dominates(BB, Pred))
  199. continue;
  200. for (auto *Succ : successors(Pred))
  201. if (CheckedSuccessors.insert(Succ).second &&
  202. Succ != BB && !Predecessors.count(Succ))
  203. // By discharging conditions that are not executed on the 1st iteration,
  204. // we guarantee that *at least* on the first iteration all paths from
  205. // header that *may* execute will lead us to the block of interest. So
  206. // that if we had virtually peeled one iteration away, in this peeled
  207. // iteration the set of predecessors would contain only paths from
  208. // header to BB without any exiting edges that may execute.
  209. //
  210. // TODO: We only do it for exiting edges currently. We could use the
  211. // same function to skip some of the edges within the loop if we know
  212. // that they will not be taken on the 1st iteration.
  213. //
  214. // TODO: If we somehow know the number of iterations in loop, the same
  215. // check may be done for any arbitrary N-th iteration as long as N is
  216. // not greater than minimum number of iterations in this loop.
  217. if (CurLoop->contains(Succ) ||
  218. !CanProveNotTakenFirstIteration(Succ, DT, CurLoop))
  219. return false;
  220. }
  221. // All predecessors can only lead us to BB.
  222. return true;
  223. }
  224. /// Returns true if the instruction in a loop is guaranteed to execute at least
  225. /// once.
  226. bool SimpleLoopSafetyInfo::isGuaranteedToExecute(const Instruction &Inst,
  227. const DominatorTree *DT,
  228. const Loop *CurLoop) const {
  229. // If the instruction is in the header block for the loop (which is very
  230. // common), it is always guaranteed to dominate the exit blocks. Since this
  231. // is a common case, and can save some work, check it now.
  232. if (Inst.getParent() == CurLoop->getHeader())
  233. // If there's a throw in the header block, we can't guarantee we'll reach
  234. // Inst unless we can prove that Inst comes before the potential implicit
  235. // exit. At the moment, we use a (cheap) hack for the common case where
  236. // the instruction of interest is the first one in the block.
  237. return !HeaderMayThrow ||
  238. Inst.getParent()->getFirstNonPHIOrDbg() == &Inst;
  239. // If there is a path from header to exit or latch that doesn't lead to our
  240. // instruction's block, return false.
  241. return allLoopPathsLeadToBlock(CurLoop, Inst.getParent(), DT);
  242. }
  243. bool ICFLoopSafetyInfo::isGuaranteedToExecute(const Instruction &Inst,
  244. const DominatorTree *DT,
  245. const Loop *CurLoop) const {
  246. return !ICF.isDominatedByICFIFromSameBlock(&Inst) &&
  247. allLoopPathsLeadToBlock(CurLoop, Inst.getParent(), DT);
  248. }
  249. bool ICFLoopSafetyInfo::doesNotWriteMemoryBefore(const BasicBlock *BB,
  250. const Loop *CurLoop) const {
  251. assert(CurLoop->contains(BB) && "Should only be called for loop blocks!");
  252. // Fast path: there are no instructions before header.
  253. if (BB == CurLoop->getHeader())
  254. return true;
  255. // Collect all transitive predecessors of BB in the same loop. This set will
  256. // be a subset of the blocks within the loop.
  257. SmallPtrSet<const BasicBlock *, 4> Predecessors;
  258. collectTransitivePredecessors(CurLoop, BB, Predecessors);
  259. // Find if there any instruction in either predecessor that could write
  260. // to memory.
  261. for (auto *Pred : Predecessors)
  262. if (MW.mayWriteToMemory(Pred))
  263. return false;
  264. return true;
  265. }
  266. bool ICFLoopSafetyInfo::doesNotWriteMemoryBefore(const Instruction &I,
  267. const Loop *CurLoop) const {
  268. auto *BB = I.getParent();
  269. assert(CurLoop->contains(BB) && "Should only be called for loop blocks!");
  270. return !MW.isDominatedByMemoryWriteFromSameBlock(&I) &&
  271. doesNotWriteMemoryBefore(BB, CurLoop);
  272. }
  273. namespace {
  274. struct MustExecutePrinter : public FunctionPass {
  275. static char ID; // Pass identification, replacement for typeid
  276. MustExecutePrinter() : FunctionPass(ID) {
  277. initializeMustExecutePrinterPass(*PassRegistry::getPassRegistry());
  278. }
  279. void getAnalysisUsage(AnalysisUsage &AU) const override {
  280. AU.setPreservesAll();
  281. AU.addRequired<DominatorTreeWrapperPass>();
  282. AU.addRequired<LoopInfoWrapperPass>();
  283. }
  284. bool runOnFunction(Function &F) override;
  285. };
  286. struct MustBeExecutedContextPrinter : public ModulePass {
  287. static char ID;
  288. MustBeExecutedContextPrinter() : ModulePass(ID) {
  289. initializeMustBeExecutedContextPrinterPass(
  290. *PassRegistry::getPassRegistry());
  291. }
  292. void getAnalysisUsage(AnalysisUsage &AU) const override {
  293. AU.setPreservesAll();
  294. }
  295. bool runOnModule(Module &M) override;
  296. };
  297. }
  298. char MustExecutePrinter::ID = 0;
  299. INITIALIZE_PASS_BEGIN(MustExecutePrinter, "print-mustexecute",
  300. "Instructions which execute on loop entry", false, true)
  301. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  302. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  303. INITIALIZE_PASS_END(MustExecutePrinter, "print-mustexecute",
  304. "Instructions which execute on loop entry", false, true)
  305. FunctionPass *llvm::createMustExecutePrinter() {
  306. return new MustExecutePrinter();
  307. }
  308. char MustBeExecutedContextPrinter::ID = 0;
  309. INITIALIZE_PASS_BEGIN(MustBeExecutedContextPrinter,
  310. "print-must-be-executed-contexts",
  311. "print the must-be-executed-context for all instructions",
  312. false, true)
  313. INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
  314. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  315. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  316. INITIALIZE_PASS_END(MustBeExecutedContextPrinter,
  317. "print-must-be-executed-contexts",
  318. "print the must-be-executed-context for all instructions",
  319. false, true)
  320. ModulePass *llvm::createMustBeExecutedContextPrinter() {
  321. return new MustBeExecutedContextPrinter();
  322. }
  323. bool MustBeExecutedContextPrinter::runOnModule(Module &M) {
  324. // We provide non-PM analysis here because the old PM doesn't like to query
  325. // function passes from a module pass.
  326. SmallVector<std::unique_ptr<PostDominatorTree>, 8> PDTs;
  327. SmallVector<std::unique_ptr<DominatorTree>, 8> DTs;
  328. SmallVector<std::unique_ptr<LoopInfo>, 8> LIs;
  329. GetterTy<LoopInfo> LIGetter = [&](const Function &F) {
  330. DTs.push_back(std::make_unique<DominatorTree>(const_cast<Function &>(F)));
  331. LIs.push_back(std::make_unique<LoopInfo>(*DTs.back()));
  332. return LIs.back().get();
  333. };
  334. GetterTy<DominatorTree> DTGetter = [&](const Function &F) {
  335. DTs.push_back(std::make_unique<DominatorTree>(const_cast<Function&>(F)));
  336. return DTs.back().get();
  337. };
  338. GetterTy<PostDominatorTree> PDTGetter = [&](const Function &F) {
  339. PDTs.push_back(
  340. std::make_unique<PostDominatorTree>(const_cast<Function &>(F)));
  341. return PDTs.back().get();
  342. };
  343. MustBeExecutedContextExplorer Explorer(
  344. /* ExploreInterBlock */ true,
  345. /* ExploreCFGForward */ true,
  346. /* ExploreCFGBackward */ true, LIGetter, DTGetter, PDTGetter);
  347. for (Function &F : M) {
  348. for (Instruction &I : instructions(F)) {
  349. dbgs() << "-- Explore context of: " << I << "\n";
  350. for (const Instruction *CI : Explorer.range(&I))
  351. dbgs() << " [F: " << CI->getFunction()->getName() << "] " << *CI
  352. << "\n";
  353. }
  354. }
  355. return false;
  356. }
  357. static bool isMustExecuteIn(const Instruction &I, Loop *L, DominatorTree *DT) {
  358. // TODO: merge these two routines. For the moment, we display the best
  359. // result obtained by *either* implementation. This is a bit unfair since no
  360. // caller actually gets the full power at the moment.
  361. SimpleLoopSafetyInfo LSI;
  362. LSI.computeLoopSafetyInfo(L);
  363. return LSI.isGuaranteedToExecute(I, DT, L) ||
  364. isGuaranteedToExecuteForEveryIteration(&I, L);
  365. }
  366. namespace {
  367. /// An assembly annotator class to print must execute information in
  368. /// comments.
  369. class MustExecuteAnnotatedWriter : public AssemblyAnnotationWriter {
  370. DenseMap<const Value*, SmallVector<Loop*, 4> > MustExec;
  371. public:
  372. MustExecuteAnnotatedWriter(const Function &F,
  373. DominatorTree &DT, LoopInfo &LI) {
  374. for (auto &I: instructions(F)) {
  375. Loop *L = LI.getLoopFor(I.getParent());
  376. while (L) {
  377. if (isMustExecuteIn(I, L, &DT)) {
  378. MustExec[&I].push_back(L);
  379. }
  380. L = L->getParentLoop();
  381. };
  382. }
  383. }
  384. MustExecuteAnnotatedWriter(const Module &M,
  385. DominatorTree &DT, LoopInfo &LI) {
  386. for (auto &F : M)
  387. for (auto &I: instructions(F)) {
  388. Loop *L = LI.getLoopFor(I.getParent());
  389. while (L) {
  390. if (isMustExecuteIn(I, L, &DT)) {
  391. MustExec[&I].push_back(L);
  392. }
  393. L = L->getParentLoop();
  394. };
  395. }
  396. }
  397. void printInfoComment(const Value &V, formatted_raw_ostream &OS) override {
  398. if (!MustExec.count(&V))
  399. return;
  400. const auto &Loops = MustExec.lookup(&V);
  401. const auto NumLoops = Loops.size();
  402. if (NumLoops > 1)
  403. OS << " ; (mustexec in " << NumLoops << " loops: ";
  404. else
  405. OS << " ; (mustexec in: ";
  406. ListSeparator LS;
  407. for (const Loop *L : Loops)
  408. OS << LS << L->getHeader()->getName();
  409. OS << ")";
  410. }
  411. };
  412. } // namespace
  413. bool MustExecutePrinter::runOnFunction(Function &F) {
  414. auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  415. auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  416. MustExecuteAnnotatedWriter Writer(F, DT, LI);
  417. F.print(dbgs(), &Writer);
  418. return false;
  419. }
  420. /// Return true if \p L might be an endless loop.
  421. static bool maybeEndlessLoop(const Loop &L) {
  422. if (L.getHeader()->getParent()->hasFnAttribute(Attribute::WillReturn))
  423. return false;
  424. // TODO: Actually try to prove it is not.
  425. // TODO: If maybeEndlessLoop is going to be expensive, cache it.
  426. return true;
  427. }
  428. bool llvm::mayContainIrreducibleControl(const Function &F, const LoopInfo *LI) {
  429. if (!LI)
  430. return false;
  431. using RPOTraversal = ReversePostOrderTraversal<const Function *>;
  432. RPOTraversal FuncRPOT(&F);
  433. return containsIrreducibleCFG<const BasicBlock *, const RPOTraversal,
  434. const LoopInfo>(FuncRPOT, *LI);
  435. }
  436. /// Lookup \p Key in \p Map and return the result, potentially after
  437. /// initializing the optional through \p Fn(\p args).
  438. template <typename K, typename V, typename FnTy, typename... ArgsTy>
  439. static V getOrCreateCachedOptional(K Key, DenseMap<K, Optional<V>> &Map,
  440. FnTy &&Fn, ArgsTy&&... args) {
  441. Optional<V> &OptVal = Map[Key];
  442. if (!OptVal.hasValue())
  443. OptVal = Fn(std::forward<ArgsTy>(args)...);
  444. return OptVal.getValue();
  445. }
  446. const BasicBlock *
  447. MustBeExecutedContextExplorer::findForwardJoinPoint(const BasicBlock *InitBB) {
  448. const LoopInfo *LI = LIGetter(*InitBB->getParent());
  449. const PostDominatorTree *PDT = PDTGetter(*InitBB->getParent());
  450. LLVM_DEBUG(dbgs() << "\tFind forward join point for " << InitBB->getName()
  451. << (LI ? " [LI]" : "") << (PDT ? " [PDT]" : ""));
  452. const Function &F = *InitBB->getParent();
  453. const Loop *L = LI ? LI->getLoopFor(InitBB) : nullptr;
  454. const BasicBlock *HeaderBB = L ? L->getHeader() : InitBB;
  455. bool WillReturnAndNoThrow = (F.hasFnAttribute(Attribute::WillReturn) ||
  456. (L && !maybeEndlessLoop(*L))) &&
  457. F.doesNotThrow();
  458. LLVM_DEBUG(dbgs() << (L ? " [in loop]" : "")
  459. << (WillReturnAndNoThrow ? " [WillReturn] [NoUnwind]" : "")
  460. << "\n");
  461. // Determine the adjacent blocks in the given direction but exclude (self)
  462. // loops under certain circumstances.
  463. SmallVector<const BasicBlock *, 8> Worklist;
  464. for (const BasicBlock *SuccBB : successors(InitBB)) {
  465. bool IsLatch = SuccBB == HeaderBB;
  466. // Loop latches are ignored in forward propagation if the loop cannot be
  467. // endless and may not throw: control has to go somewhere.
  468. if (!WillReturnAndNoThrow || !IsLatch)
  469. Worklist.push_back(SuccBB);
  470. }
  471. LLVM_DEBUG(dbgs() << "\t\t#Worklist: " << Worklist.size() << "\n");
  472. // If there are no other adjacent blocks, there is no join point.
  473. if (Worklist.empty())
  474. return nullptr;
  475. // If there is one adjacent block, it is the join point.
  476. if (Worklist.size() == 1)
  477. return Worklist[0];
  478. // Try to determine a join block through the help of the post-dominance
  479. // tree. If no tree was provided, we perform simple pattern matching for one
  480. // block conditionals and one block loops only.
  481. const BasicBlock *JoinBB = nullptr;
  482. if (PDT)
  483. if (const auto *InitNode = PDT->getNode(InitBB))
  484. if (const auto *IDomNode = InitNode->getIDom())
  485. JoinBB = IDomNode->getBlock();
  486. if (!JoinBB && Worklist.size() == 2) {
  487. const BasicBlock *Succ0 = Worklist[0];
  488. const BasicBlock *Succ1 = Worklist[1];
  489. const BasicBlock *Succ0UniqueSucc = Succ0->getUniqueSuccessor();
  490. const BasicBlock *Succ1UniqueSucc = Succ1->getUniqueSuccessor();
  491. if (Succ0UniqueSucc == InitBB) {
  492. // InitBB -> Succ0 -> InitBB
  493. // InitBB -> Succ1 = JoinBB
  494. JoinBB = Succ1;
  495. } else if (Succ1UniqueSucc == InitBB) {
  496. // InitBB -> Succ1 -> InitBB
  497. // InitBB -> Succ0 = JoinBB
  498. JoinBB = Succ0;
  499. } else if (Succ0 == Succ1UniqueSucc) {
  500. // InitBB -> Succ0 = JoinBB
  501. // InitBB -> Succ1 -> Succ0 = JoinBB
  502. JoinBB = Succ0;
  503. } else if (Succ1 == Succ0UniqueSucc) {
  504. // InitBB -> Succ0 -> Succ1 = JoinBB
  505. // InitBB -> Succ1 = JoinBB
  506. JoinBB = Succ1;
  507. } else if (Succ0UniqueSucc == Succ1UniqueSucc) {
  508. // InitBB -> Succ0 -> JoinBB
  509. // InitBB -> Succ1 -> JoinBB
  510. JoinBB = Succ0UniqueSucc;
  511. }
  512. }
  513. if (!JoinBB && L)
  514. JoinBB = L->getUniqueExitBlock();
  515. if (!JoinBB)
  516. return nullptr;
  517. LLVM_DEBUG(dbgs() << "\t\tJoin block candidate: " << JoinBB->getName() << "\n");
  518. // In forward direction we check if control will for sure reach JoinBB from
  519. // InitBB, thus it can not be "stopped" along the way. Ways to "stop" control
  520. // are: infinite loops and instructions that do not necessarily transfer
  521. // execution to their successor. To check for them we traverse the CFG from
  522. // the adjacent blocks to the JoinBB, looking at all intermediate blocks.
  523. // If we know the function is "will-return" and "no-throw" there is no need
  524. // for futher checks.
  525. if (!F.hasFnAttribute(Attribute::WillReturn) || !F.doesNotThrow()) {
  526. auto BlockTransfersExecutionToSuccessor = [](const BasicBlock *BB) {
  527. return isGuaranteedToTransferExecutionToSuccessor(BB);
  528. };
  529. SmallPtrSet<const BasicBlock *, 16> Visited;
  530. while (!Worklist.empty()) {
  531. const BasicBlock *ToBB = Worklist.pop_back_val();
  532. if (ToBB == JoinBB)
  533. continue;
  534. // Make sure all loops in-between are finite.
  535. if (!Visited.insert(ToBB).second) {
  536. if (!F.hasFnAttribute(Attribute::WillReturn)) {
  537. if (!LI)
  538. return nullptr;
  539. bool MayContainIrreducibleControl = getOrCreateCachedOptional(
  540. &F, IrreducibleControlMap, mayContainIrreducibleControl, F, LI);
  541. if (MayContainIrreducibleControl)
  542. return nullptr;
  543. const Loop *L = LI->getLoopFor(ToBB);
  544. if (L && maybeEndlessLoop(*L))
  545. return nullptr;
  546. }
  547. continue;
  548. }
  549. // Make sure the block has no instructions that could stop control
  550. // transfer.
  551. bool TransfersExecution = getOrCreateCachedOptional(
  552. ToBB, BlockTransferMap, BlockTransfersExecutionToSuccessor, ToBB);
  553. if (!TransfersExecution)
  554. return nullptr;
  555. append_range(Worklist, successors(ToBB));
  556. }
  557. }
  558. LLVM_DEBUG(dbgs() << "\tJoin block: " << JoinBB->getName() << "\n");
  559. return JoinBB;
  560. }
  561. const BasicBlock *
  562. MustBeExecutedContextExplorer::findBackwardJoinPoint(const BasicBlock *InitBB) {
  563. const LoopInfo *LI = LIGetter(*InitBB->getParent());
  564. const DominatorTree *DT = DTGetter(*InitBB->getParent());
  565. LLVM_DEBUG(dbgs() << "\tFind backward join point for " << InitBB->getName()
  566. << (LI ? " [LI]" : "") << (DT ? " [DT]" : ""));
  567. // Try to determine a join block through the help of the dominance tree. If no
  568. // tree was provided, we perform simple pattern matching for one block
  569. // conditionals only.
  570. if (DT)
  571. if (const auto *InitNode = DT->getNode(InitBB))
  572. if (const auto *IDomNode = InitNode->getIDom())
  573. return IDomNode->getBlock();
  574. const Loop *L = LI ? LI->getLoopFor(InitBB) : nullptr;
  575. const BasicBlock *HeaderBB = L ? L->getHeader() : nullptr;
  576. // Determine the predecessor blocks but ignore backedges.
  577. SmallVector<const BasicBlock *, 8> Worklist;
  578. for (const BasicBlock *PredBB : predecessors(InitBB)) {
  579. bool IsBackedge =
  580. (PredBB == InitBB) || (HeaderBB == InitBB && L->contains(PredBB));
  581. // Loop backedges are ignored in backwards propagation: control has to come
  582. // from somewhere.
  583. if (!IsBackedge)
  584. Worklist.push_back(PredBB);
  585. }
  586. // If there are no other predecessor blocks, there is no join point.
  587. if (Worklist.empty())
  588. return nullptr;
  589. // If there is one predecessor block, it is the join point.
  590. if (Worklist.size() == 1)
  591. return Worklist[0];
  592. const BasicBlock *JoinBB = nullptr;
  593. if (Worklist.size() == 2) {
  594. const BasicBlock *Pred0 = Worklist[0];
  595. const BasicBlock *Pred1 = Worklist[1];
  596. const BasicBlock *Pred0UniquePred = Pred0->getUniquePredecessor();
  597. const BasicBlock *Pred1UniquePred = Pred1->getUniquePredecessor();
  598. if (Pred0 == Pred1UniquePred) {
  599. // InitBB <- Pred0 = JoinBB
  600. // InitBB <- Pred1 <- Pred0 = JoinBB
  601. JoinBB = Pred0;
  602. } else if (Pred1 == Pred0UniquePred) {
  603. // InitBB <- Pred0 <- Pred1 = JoinBB
  604. // InitBB <- Pred1 = JoinBB
  605. JoinBB = Pred1;
  606. } else if (Pred0UniquePred == Pred1UniquePred) {
  607. // InitBB <- Pred0 <- JoinBB
  608. // InitBB <- Pred1 <- JoinBB
  609. JoinBB = Pred0UniquePred;
  610. }
  611. }
  612. if (!JoinBB && L)
  613. JoinBB = L->getHeader();
  614. // In backwards direction there is no need to show termination of previous
  615. // instructions. If they do not terminate, the code afterward is dead, making
  616. // any information/transformation correct anyway.
  617. return JoinBB;
  618. }
  619. const Instruction *
  620. MustBeExecutedContextExplorer::getMustBeExecutedNextInstruction(
  621. MustBeExecutedIterator &It, const Instruction *PP) {
  622. if (!PP)
  623. return PP;
  624. LLVM_DEBUG(dbgs() << "Find next instruction for " << *PP << "\n");
  625. // If we explore only inside a given basic block we stop at terminators.
  626. if (!ExploreInterBlock && PP->isTerminator()) {
  627. LLVM_DEBUG(dbgs() << "\tReached terminator in intra-block mode, done\n");
  628. return nullptr;
  629. }
  630. // If we do not traverse the call graph we check if we can make progress in
  631. // the current function. First, check if the instruction is guaranteed to
  632. // transfer execution to the successor.
  633. bool TransfersExecution = isGuaranteedToTransferExecutionToSuccessor(PP);
  634. if (!TransfersExecution)
  635. return nullptr;
  636. // If this is not a terminator we know that there is a single instruction
  637. // after this one that is executed next if control is transfered. If not,
  638. // we can try to go back to a call site we entered earlier. If none exists, we
  639. // do not know any instruction that has to be executd next.
  640. if (!PP->isTerminator()) {
  641. const Instruction *NextPP = PP->getNextNode();
  642. LLVM_DEBUG(dbgs() << "\tIntermediate instruction does transfer control\n");
  643. return NextPP;
  644. }
  645. // Finally, we have to handle terminators, trivial ones first.
  646. assert(PP->isTerminator() && "Expected a terminator!");
  647. // A terminator without a successor is not handled yet.
  648. if (PP->getNumSuccessors() == 0) {
  649. LLVM_DEBUG(dbgs() << "\tUnhandled terminator\n");
  650. return nullptr;
  651. }
  652. // A terminator with a single successor, we will continue at the beginning of
  653. // that one.
  654. if (PP->getNumSuccessors() == 1) {
  655. LLVM_DEBUG(
  656. dbgs() << "\tUnconditional terminator, continue with successor\n");
  657. return &PP->getSuccessor(0)->front();
  658. }
  659. // Multiple successors mean we need to find the join point where control flow
  660. // converges again. We use the findForwardJoinPoint helper function with
  661. // information about the function and helper analyses, if available.
  662. if (const BasicBlock *JoinBB = findForwardJoinPoint(PP->getParent()))
  663. return &JoinBB->front();
  664. LLVM_DEBUG(dbgs() << "\tNo join point found\n");
  665. return nullptr;
  666. }
  667. const Instruction *
  668. MustBeExecutedContextExplorer::getMustBeExecutedPrevInstruction(
  669. MustBeExecutedIterator &It, const Instruction *PP) {
  670. if (!PP)
  671. return PP;
  672. bool IsFirst = !(PP->getPrevNode());
  673. LLVM_DEBUG(dbgs() << "Find next instruction for " << *PP
  674. << (IsFirst ? " [IsFirst]" : "") << "\n");
  675. // If we explore only inside a given basic block we stop at the first
  676. // instruction.
  677. if (!ExploreInterBlock && IsFirst) {
  678. LLVM_DEBUG(dbgs() << "\tReached block front in intra-block mode, done\n");
  679. return nullptr;
  680. }
  681. // The block and function that contains the current position.
  682. const BasicBlock *PPBlock = PP->getParent();
  683. // If we are inside a block we know what instruction was executed before, the
  684. // previous one.
  685. if (!IsFirst) {
  686. const Instruction *PrevPP = PP->getPrevNode();
  687. LLVM_DEBUG(
  688. dbgs() << "\tIntermediate instruction, continue with previous\n");
  689. // We did not enter a callee so we simply return the previous instruction.
  690. return PrevPP;
  691. }
  692. // Finally, we have to handle the case where the program point is the first in
  693. // a block but not in the function. We use the findBackwardJoinPoint helper
  694. // function with information about the function and helper analyses, if
  695. // available.
  696. if (const BasicBlock *JoinBB = findBackwardJoinPoint(PPBlock))
  697. return &JoinBB->back();
  698. LLVM_DEBUG(dbgs() << "\tNo join point found\n");
  699. return nullptr;
  700. }
  701. MustBeExecutedIterator::MustBeExecutedIterator(
  702. MustBeExecutedContextExplorer &Explorer, const Instruction *I)
  703. : Explorer(Explorer), CurInst(I) {
  704. reset(I);
  705. }
  706. void MustBeExecutedIterator::reset(const Instruction *I) {
  707. Visited.clear();
  708. resetInstruction(I);
  709. }
  710. void MustBeExecutedIterator::resetInstruction(const Instruction *I) {
  711. CurInst = I;
  712. Head = Tail = nullptr;
  713. Visited.insert({I, ExplorationDirection::FORWARD});
  714. Visited.insert({I, ExplorationDirection::BACKWARD});
  715. if (Explorer.ExploreCFGForward)
  716. Head = I;
  717. if (Explorer.ExploreCFGBackward)
  718. Tail = I;
  719. }
  720. const Instruction *MustBeExecutedIterator::advance() {
  721. assert(CurInst && "Cannot advance an end iterator!");
  722. Head = Explorer.getMustBeExecutedNextInstruction(*this, Head);
  723. if (Head && Visited.insert({Head, ExplorationDirection ::FORWARD}).second)
  724. return Head;
  725. Head = nullptr;
  726. Tail = Explorer.getMustBeExecutedPrevInstruction(*this, Tail);
  727. if (Tail && Visited.insert({Tail, ExplorationDirection ::BACKWARD}).second)
  728. return Tail;
  729. Tail = nullptr;
  730. return nullptr;
  731. }
  732. PreservedAnalyses MustExecutePrinterPass::run(Function &F,
  733. FunctionAnalysisManager &AM) {
  734. auto &LI = AM.getResult<LoopAnalysis>(F);
  735. auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
  736. MustExecuteAnnotatedWriter Writer(F, DT, LI);
  737. F.print(OS, &Writer);
  738. return PreservedAnalyses::all();
  739. }
  740. PreservedAnalyses
  741. MustBeExecutedContextPrinterPass::run(Module &M, ModuleAnalysisManager &AM) {
  742. FunctionAnalysisManager &FAM =
  743. AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
  744. GetterTy<const LoopInfo> LIGetter = [&](const Function &F) {
  745. return &FAM.getResult<LoopAnalysis>(const_cast<Function &>(F));
  746. };
  747. GetterTy<const DominatorTree> DTGetter = [&](const Function &F) {
  748. return &FAM.getResult<DominatorTreeAnalysis>(const_cast<Function &>(F));
  749. };
  750. GetterTy<const PostDominatorTree> PDTGetter = [&](const Function &F) {
  751. return &FAM.getResult<PostDominatorTreeAnalysis>(const_cast<Function &>(F));
  752. };
  753. MustBeExecutedContextExplorer Explorer(
  754. /* ExploreInterBlock */ true,
  755. /* ExploreCFGForward */ true,
  756. /* ExploreCFGBackward */ true, LIGetter, DTGetter, PDTGetter);
  757. for (Function &F : M) {
  758. for (Instruction &I : instructions(F)) {
  759. OS << "-- Explore context of: " << I << "\n";
  760. for (const Instruction *CI : Explorer.range(&I))
  761. OS << " [F: " << CI->getFunction()->getName() << "] " << *CI << "\n";
  762. }
  763. }
  764. return PreservedAnalyses::all();
  765. }