MustExecute.h 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. //===- MustExecute.h - Is an instruction known to execute--------*- 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. /// \file
  9. /// Contains a collection of routines for determining if a given instruction is
  10. /// guaranteed to execute if a given point in control flow is reached. The most
  11. /// common example is an instruction within a loop being provably executed if we
  12. /// branch to the header of it's containing loop.
  13. ///
  14. /// There are two interfaces available to determine if an instruction is
  15. /// executed once a given point in the control flow is reached:
  16. /// 1) A loop-centric one derived from LoopSafetyInfo.
  17. /// 2) A "must be executed context"-based one implemented in the
  18. /// MustBeExecutedContextExplorer.
  19. /// Please refer to the class comments for more information.
  20. ///
  21. //===----------------------------------------------------------------------===//
  22. #ifndef LLVM_ANALYSIS_MUSTEXECUTE_H
  23. #define LLVM_ANALYSIS_MUSTEXECUTE_H
  24. #include "llvm/ADT/DenseMap.h"
  25. #include "llvm/ADT/DenseSet.h"
  26. #include "llvm/Analysis/EHPersonalities.h"
  27. #include "llvm/Analysis/InstructionPrecedenceTracking.h"
  28. #include "llvm/IR/PassManager.h"
  29. #include "llvm/Support/raw_ostream.h"
  30. namespace llvm {
  31. namespace {
  32. template <typename T> using GetterTy = std::function<T *(const Function &F)>;
  33. }
  34. class BasicBlock;
  35. class DominatorTree;
  36. class Instruction;
  37. class Loop;
  38. class LoopInfo;
  39. class PostDominatorTree;
  40. /// Captures loop safety information.
  41. /// It keep information for loop blocks may throw exception or otherwise
  42. /// exit abnormally on any iteration of the loop which might actually execute
  43. /// at runtime. The primary way to consume this information is via
  44. /// isGuaranteedToExecute below, but some callers bailout or fallback to
  45. /// alternate reasoning if a loop contains any implicit control flow.
  46. /// NOTE: LoopSafetyInfo contains cached information regarding loops and their
  47. /// particular blocks. This information is only dropped on invocation of
  48. /// computeLoopSafetyInfo. If the loop or any of its block is deleted, or if
  49. /// any thrower instructions have been added or removed from them, or if the
  50. /// control flow has changed, or in case of other meaningful modifications, the
  51. /// LoopSafetyInfo needs to be recomputed. If a meaningful modifications to the
  52. /// loop were made and the info wasn't recomputed properly, the behavior of all
  53. /// methods except for computeLoopSafetyInfo is undefined.
  54. class LoopSafetyInfo {
  55. // Used to update funclet bundle operands.
  56. DenseMap<BasicBlock *, ColorVector> BlockColors;
  57. protected:
  58. /// Computes block colors.
  59. void computeBlockColors(const Loop *CurLoop);
  60. public:
  61. /// Returns block colors map that is used to update funclet operand bundles.
  62. const DenseMap<BasicBlock *, ColorVector> &getBlockColors() const;
  63. /// Copy colors of block \p Old into the block \p New.
  64. void copyColors(BasicBlock *New, BasicBlock *Old);
  65. /// Returns true iff the block \p BB potentially may throw exception. It can
  66. /// be false-positive in cases when we want to avoid complex analysis.
  67. virtual bool blockMayThrow(const BasicBlock *BB) const = 0;
  68. /// Returns true iff any block of the loop for which this info is contains an
  69. /// instruction that may throw or otherwise exit abnormally.
  70. virtual bool anyBlockMayThrow() const = 0;
  71. /// Return true if we must reach the block \p BB under assumption that the
  72. /// loop \p CurLoop is entered.
  73. bool allLoopPathsLeadToBlock(const Loop *CurLoop, const BasicBlock *BB,
  74. const DominatorTree *DT) const;
  75. /// Computes safety information for a loop checks loop body & header for
  76. /// the possibility of may throw exception, it takes LoopSafetyInfo and loop
  77. /// as argument. Updates safety information in LoopSafetyInfo argument.
  78. /// Note: This is defined to clear and reinitialize an already initialized
  79. /// LoopSafetyInfo. Some callers rely on this fact.
  80. virtual void computeLoopSafetyInfo(const Loop *CurLoop) = 0;
  81. /// Returns true if the instruction in a loop is guaranteed to execute at
  82. /// least once (under the assumption that the loop is entered).
  83. virtual bool isGuaranteedToExecute(const Instruction &Inst,
  84. const DominatorTree *DT,
  85. const Loop *CurLoop) const = 0;
  86. LoopSafetyInfo() = default;
  87. virtual ~LoopSafetyInfo() = default;
  88. };
  89. /// Simple and conservative implementation of LoopSafetyInfo that can give
  90. /// false-positive answers to its queries in order to avoid complicated
  91. /// analysis.
  92. class SimpleLoopSafetyInfo: public LoopSafetyInfo {
  93. bool MayThrow = false; // The current loop contains an instruction which
  94. // may throw.
  95. bool HeaderMayThrow = false; // Same as previous, but specific to loop header
  96. public:
  97. bool blockMayThrow(const BasicBlock *BB) const override;
  98. bool anyBlockMayThrow() const override;
  99. void computeLoopSafetyInfo(const Loop *CurLoop) override;
  100. bool isGuaranteedToExecute(const Instruction &Inst,
  101. const DominatorTree *DT,
  102. const Loop *CurLoop) const override;
  103. };
  104. /// This implementation of LoopSafetyInfo use ImplicitControlFlowTracking to
  105. /// give precise answers on "may throw" queries. This implementation uses cache
  106. /// that should be invalidated by calling the methods insertInstructionTo and
  107. /// removeInstruction whenever we modify a basic block's contents by adding or
  108. /// removing instructions.
  109. class ICFLoopSafetyInfo: public LoopSafetyInfo {
  110. bool MayThrow = false; // The current loop contains an instruction which
  111. // may throw.
  112. // Contains information about implicit control flow in this loop's blocks.
  113. mutable ImplicitControlFlowTracking ICF;
  114. // Contains information about instruction that may possibly write memory.
  115. mutable MemoryWriteTracking MW;
  116. public:
  117. bool blockMayThrow(const BasicBlock *BB) const override;
  118. bool anyBlockMayThrow() const override;
  119. void computeLoopSafetyInfo(const Loop *CurLoop) override;
  120. bool isGuaranteedToExecute(const Instruction &Inst,
  121. const DominatorTree *DT,
  122. const Loop *CurLoop) const override;
  123. /// Returns true if we could not execute a memory-modifying instruction before
  124. /// we enter \p BB under assumption that \p CurLoop is entered.
  125. bool doesNotWriteMemoryBefore(const BasicBlock *BB, const Loop *CurLoop)
  126. const;
  127. /// Returns true if we could not execute a memory-modifying instruction before
  128. /// we execute \p I under assumption that \p CurLoop is entered.
  129. bool doesNotWriteMemoryBefore(const Instruction &I, const Loop *CurLoop)
  130. const;
  131. /// Inform the safety info that we are planning to insert a new instruction
  132. /// \p Inst into the basic block \p BB. It will make all cache updates to keep
  133. /// it correct after this insertion.
  134. void insertInstructionTo(const Instruction *Inst, const BasicBlock *BB);
  135. /// Inform safety info that we are planning to remove the instruction \p Inst
  136. /// from its block. It will make all cache updates to keep it correct after
  137. /// this removal.
  138. void removeInstruction(const Instruction *Inst);
  139. };
  140. bool mayContainIrreducibleControl(const Function &F, const LoopInfo *LI);
  141. struct MustBeExecutedContextExplorer;
  142. /// Enum that allows us to spell out the direction.
  143. enum class ExplorationDirection {
  144. BACKWARD = 0,
  145. FORWARD = 1,
  146. };
  147. /// Must be executed iterators visit stretches of instructions that are
  148. /// guaranteed to be executed together, potentially with other instruction
  149. /// executed in-between.
  150. ///
  151. /// Given the following code, and assuming all statements are single
  152. /// instructions which transfer execution to the successor (see
  153. /// isGuaranteedToTransferExecutionToSuccessor), there are two possible
  154. /// outcomes. If we start the iterator at A, B, or E, we will visit only A, B,
  155. /// and E. If we start at C or D, we will visit all instructions A-E.
  156. ///
  157. /// \code
  158. /// A;
  159. /// B;
  160. /// if (...) {
  161. /// C;
  162. /// D;
  163. /// }
  164. /// E;
  165. /// \endcode
  166. ///
  167. ///
  168. /// Below is the example extneded with instructions F and G. Now we assume F
  169. /// might not transfer execution to it's successor G. As a result we get the
  170. /// following visit sets:
  171. ///
  172. /// Start Instruction | Visit Set
  173. /// A | A, B, E, F
  174. /// B | A, B, E, F
  175. /// C | A, B, C, D, E, F
  176. /// D | A, B, C, D, E, F
  177. /// E | A, B, E, F
  178. /// F | A, B, E, F
  179. /// G | A, B, E, F, G
  180. ///
  181. ///
  182. /// \code
  183. /// A;
  184. /// B;
  185. /// if (...) {
  186. /// C;
  187. /// D;
  188. /// }
  189. /// E;
  190. /// F; // Might not transfer execution to its successor G.
  191. /// G;
  192. /// \endcode
  193. ///
  194. ///
  195. /// A more complex example involving conditionals, loops, break, and continue
  196. /// is shown below. We again assume all instructions will transmit control to
  197. /// the successor and we assume we can prove the inner loop to be finite. We
  198. /// omit non-trivial branch conditions as the exploration is oblivious to them.
  199. /// Constant branches are assumed to be unconditional in the CFG. The resulting
  200. /// visist sets are shown in the table below.
  201. ///
  202. /// \code
  203. /// A;
  204. /// while (true) {
  205. /// B;
  206. /// if (...)
  207. /// C;
  208. /// if (...)
  209. /// continue;
  210. /// D;
  211. /// if (...)
  212. /// break;
  213. /// do {
  214. /// if (...)
  215. /// continue;
  216. /// E;
  217. /// } while (...);
  218. /// F;
  219. /// }
  220. /// G;
  221. /// \endcode
  222. ///
  223. /// Start Instruction | Visit Set
  224. /// A | A, B
  225. /// B | A, B
  226. /// C | A, B, C
  227. /// D | A, B, D
  228. /// E | A, B, D, E, F
  229. /// F | A, B, D, F
  230. /// G | A, B, D, G
  231. ///
  232. ///
  233. /// Note that the examples show optimal visist sets but not necessarily the ones
  234. /// derived by the explorer depending on the available CFG analyses (see
  235. /// MustBeExecutedContextExplorer). Also note that we, depending on the options,
  236. /// the visit set can contain instructions from other functions.
  237. struct MustBeExecutedIterator {
  238. /// Type declarations that make his class an input iterator.
  239. ///{
  240. typedef const Instruction *value_type;
  241. typedef std::ptrdiff_t difference_type;
  242. typedef const Instruction **pointer;
  243. typedef const Instruction *&reference;
  244. typedef std::input_iterator_tag iterator_category;
  245. ///}
  246. using ExplorerTy = MustBeExecutedContextExplorer;
  247. MustBeExecutedIterator(const MustBeExecutedIterator &Other)
  248. : Visited(Other.Visited), Explorer(Other.Explorer),
  249. CurInst(Other.CurInst), Head(Other.Head), Tail(Other.Tail) {}
  250. MustBeExecutedIterator(MustBeExecutedIterator &&Other)
  251. : Visited(std::move(Other.Visited)), Explorer(Other.Explorer),
  252. CurInst(Other.CurInst), Head(Other.Head), Tail(Other.Tail) {}
  253. MustBeExecutedIterator &operator=(MustBeExecutedIterator &&Other) {
  254. if (this != &Other) {
  255. std::swap(Visited, Other.Visited);
  256. std::swap(CurInst, Other.CurInst);
  257. std::swap(Head, Other.Head);
  258. std::swap(Tail, Other.Tail);
  259. }
  260. return *this;
  261. }
  262. ~MustBeExecutedIterator() {}
  263. /// Pre- and post-increment operators.
  264. ///{
  265. MustBeExecutedIterator &operator++() {
  266. CurInst = advance();
  267. return *this;
  268. }
  269. MustBeExecutedIterator operator++(int) {
  270. MustBeExecutedIterator tmp(*this);
  271. operator++();
  272. return tmp;
  273. }
  274. ///}
  275. /// Equality and inequality operators. Note that we ignore the history here.
  276. ///{
  277. bool operator==(const MustBeExecutedIterator &Other) const {
  278. return CurInst == Other.CurInst && Head == Other.Head && Tail == Other.Tail;
  279. }
  280. bool operator!=(const MustBeExecutedIterator &Other) const {
  281. return !(*this == Other);
  282. }
  283. ///}
  284. /// Return the underlying instruction.
  285. const Instruction *&operator*() { return CurInst; }
  286. const Instruction *getCurrentInst() const { return CurInst; }
  287. /// Return true if \p I was encountered by this iterator already.
  288. bool count(const Instruction *I) const {
  289. return Visited.count({I, ExplorationDirection::FORWARD}) ||
  290. Visited.count({I, ExplorationDirection::BACKWARD});
  291. }
  292. private:
  293. using VisitedSetTy =
  294. DenseSet<PointerIntPair<const Instruction *, 1, ExplorationDirection>>;
  295. /// Private constructors.
  296. MustBeExecutedIterator(ExplorerTy &Explorer, const Instruction *I);
  297. /// Reset the iterator to its initial state pointing at \p I.
  298. void reset(const Instruction *I);
  299. /// Reset the iterator to point at \p I, keep cached state.
  300. void resetInstruction(const Instruction *I);
  301. /// Try to advance one of the underlying positions (Head or Tail).
  302. ///
  303. /// \return The next instruction in the must be executed context, or nullptr
  304. /// if none was found.
  305. const Instruction *advance();
  306. /// A set to track the visited instructions in order to deal with endless
  307. /// loops and recursion.
  308. VisitedSetTy Visited;
  309. /// A reference to the explorer that created this iterator.
  310. ExplorerTy &Explorer;
  311. /// The instruction we are currently exposing to the user. There is always an
  312. /// instruction that we know is executed with the given program point,
  313. /// initially the program point itself.
  314. const Instruction *CurInst;
  315. /// Two positions that mark the program points where this iterator will look
  316. /// for the next instruction. Note that the current instruction is either the
  317. /// one pointed to by Head, Tail, or both.
  318. const Instruction *Head, *Tail;
  319. friend struct MustBeExecutedContextExplorer;
  320. };
  321. /// A "must be executed context" for a given program point PP is the set of
  322. /// instructions, potentially before and after PP, that are executed always when
  323. /// PP is reached. The MustBeExecutedContextExplorer an interface to explore
  324. /// "must be executed contexts" in a module through the use of
  325. /// MustBeExecutedIterator.
  326. ///
  327. /// The explorer exposes "must be executed iterators" that traverse the must be
  328. /// executed context. There is little information sharing between iterators as
  329. /// the expected use case involves few iterators for "far apart" instructions.
  330. /// If that changes, we should consider caching more intermediate results.
  331. struct MustBeExecutedContextExplorer {
  332. /// In the description of the parameters we use PP to denote a program point
  333. /// for which the must be executed context is explored, or put differently,
  334. /// for which the MustBeExecutedIterator is created.
  335. ///
  336. /// \param ExploreInterBlock Flag to indicate if instructions in blocks
  337. /// other than the parent of PP should be
  338. /// explored.
  339. /// \param ExploreCFGForward Flag to indicate if instructions located after
  340. /// PP in the CFG, e.g., post-dominating PP,
  341. /// should be explored.
  342. /// \param ExploreCFGBackward Flag to indicate if instructions located
  343. /// before PP in the CFG, e.g., dominating PP,
  344. /// should be explored.
  345. MustBeExecutedContextExplorer(
  346. bool ExploreInterBlock, bool ExploreCFGForward, bool ExploreCFGBackward,
  347. GetterTy<const LoopInfo> LIGetter =
  348. [](const Function &) { return nullptr; },
  349. GetterTy<const DominatorTree> DTGetter =
  350. [](const Function &) { return nullptr; },
  351. GetterTy<const PostDominatorTree> PDTGetter =
  352. [](const Function &) { return nullptr; })
  353. : ExploreInterBlock(ExploreInterBlock),
  354. ExploreCFGForward(ExploreCFGForward),
  355. ExploreCFGBackward(ExploreCFGBackward), LIGetter(LIGetter),
  356. DTGetter(DTGetter), PDTGetter(PDTGetter), EndIterator(*this, nullptr) {}
  357. /// Iterator-based interface. \see MustBeExecutedIterator.
  358. ///{
  359. using iterator = MustBeExecutedIterator;
  360. using const_iterator = const MustBeExecutedIterator;
  361. /// Return an iterator to explore the context around \p PP.
  362. iterator &begin(const Instruction *PP) {
  363. auto &It = InstructionIteratorMap[PP];
  364. if (!It)
  365. It.reset(new iterator(*this, PP));
  366. return *It;
  367. }
  368. /// Return an iterator to explore the cached context around \p PP.
  369. const_iterator &begin(const Instruction *PP) const {
  370. return *InstructionIteratorMap.find(PP)->second;
  371. }
  372. /// Return an universal end iterator.
  373. ///{
  374. iterator &end() { return EndIterator; }
  375. iterator &end(const Instruction *) { return EndIterator; }
  376. const_iterator &end() const { return EndIterator; }
  377. const_iterator &end(const Instruction *) const { return EndIterator; }
  378. ///}
  379. /// Return an iterator range to explore the context around \p PP.
  380. llvm::iterator_range<iterator> range(const Instruction *PP) {
  381. return llvm::make_range(begin(PP), end(PP));
  382. }
  383. /// Return an iterator range to explore the cached context around \p PP.
  384. llvm::iterator_range<const_iterator> range(const Instruction *PP) const {
  385. return llvm::make_range(begin(PP), end(PP));
  386. }
  387. ///}
  388. /// Check \p Pred on all instructions in the context.
  389. ///
  390. /// This method will evaluate \p Pred and return
  391. /// true if \p Pred holds in every instruction.
  392. bool checkForAllContext(const Instruction *PP,
  393. function_ref<bool(const Instruction *)> Pred) {
  394. for (auto EIt = begin(PP), EEnd = end(PP); EIt != EEnd; ++EIt)
  395. if (!Pred(*EIt))
  396. return false;
  397. return true;
  398. }
  399. /// Helper to look for \p I in the context of \p PP.
  400. ///
  401. /// The context is expanded until \p I was found or no more expansion is
  402. /// possible.
  403. ///
  404. /// \returns True, iff \p I was found.
  405. bool findInContextOf(const Instruction *I, const Instruction *PP) {
  406. auto EIt = begin(PP), EEnd = end(PP);
  407. return findInContextOf(I, EIt, EEnd);
  408. }
  409. /// Helper to look for \p I in the context defined by \p EIt and \p EEnd.
  410. ///
  411. /// The context is expanded until \p I was found or no more expansion is
  412. /// possible.
  413. ///
  414. /// \returns True, iff \p I was found.
  415. bool findInContextOf(const Instruction *I, iterator &EIt, iterator &EEnd) {
  416. bool Found = EIt.count(I);
  417. while (!Found && EIt != EEnd)
  418. Found = (++EIt).getCurrentInst() == I;
  419. return Found;
  420. }
  421. /// Return the next instruction that is guaranteed to be executed after \p PP.
  422. ///
  423. /// \param It The iterator that is used to traverse the must be
  424. /// executed context.
  425. /// \param PP The program point for which the next instruction
  426. /// that is guaranteed to execute is determined.
  427. const Instruction *
  428. getMustBeExecutedNextInstruction(MustBeExecutedIterator &It,
  429. const Instruction *PP);
  430. /// Return the previous instr. that is guaranteed to be executed before \p PP.
  431. ///
  432. /// \param It The iterator that is used to traverse the must be
  433. /// executed context.
  434. /// \param PP The program point for which the previous instr.
  435. /// that is guaranteed to execute is determined.
  436. const Instruction *
  437. getMustBeExecutedPrevInstruction(MustBeExecutedIterator &It,
  438. const Instruction *PP);
  439. /// Find the next join point from \p InitBB in forward direction.
  440. const BasicBlock *findForwardJoinPoint(const BasicBlock *InitBB);
  441. /// Find the next join point from \p InitBB in backward direction.
  442. const BasicBlock *findBackwardJoinPoint(const BasicBlock *InitBB);
  443. /// Parameter that limit the performed exploration. See the constructor for
  444. /// their meaning.
  445. ///{
  446. const bool ExploreInterBlock;
  447. const bool ExploreCFGForward;
  448. const bool ExploreCFGBackward;
  449. ///}
  450. private:
  451. /// Getters for common CFG analyses: LoopInfo, DominatorTree, and
  452. /// PostDominatorTree.
  453. ///{
  454. GetterTy<const LoopInfo> LIGetter;
  455. GetterTy<const DominatorTree> DTGetter;
  456. GetterTy<const PostDominatorTree> PDTGetter;
  457. ///}
  458. /// Map to cache isGuaranteedToTransferExecutionToSuccessor results.
  459. DenseMap<const BasicBlock *, Optional<bool>> BlockTransferMap;
  460. /// Map to cache containsIrreducibleCFG results.
  461. DenseMap<const Function*, Optional<bool>> IrreducibleControlMap;
  462. /// Map from instructions to associated must be executed iterators.
  463. DenseMap<const Instruction *, std::unique_ptr<MustBeExecutedIterator>>
  464. InstructionIteratorMap;
  465. /// A unique end iterator.
  466. MustBeExecutedIterator EndIterator;
  467. };
  468. class MustExecutePrinterPass : public PassInfoMixin<MustExecutePrinterPass> {
  469. raw_ostream &OS;
  470. public:
  471. MustExecutePrinterPass(raw_ostream &OS) : OS(OS) {}
  472. PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
  473. };
  474. class MustBeExecutedContextPrinterPass
  475. : public PassInfoMixin<MustBeExecutedContextPrinterPass> {
  476. raw_ostream &OS;
  477. public:
  478. MustBeExecutedContextPrinterPass(raw_ostream &OS) : OS(OS) {}
  479. PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM);
  480. };
  481. } // namespace llvm
  482. #endif