BasicBlockUtils.h 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- Transform/Utils/BasicBlockUtils.h - BasicBlock Utils -----*- 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. // This family of functions perform manipulations on basic blocks, and
  15. // instructions contained within basic blocks.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #ifndef LLVM_TRANSFORMS_UTILS_BASICBLOCKUTILS_H
  19. #define LLVM_TRANSFORMS_UTILS_BASICBLOCKUTILS_H
  20. // FIXME: Move to this file: BasicBlock::removePredecessor, BB::splitBasicBlock
  21. #include "llvm/ADT/ArrayRef.h"
  22. #include "llvm/ADT/SetVector.h"
  23. #include "llvm/IR/BasicBlock.h"
  24. #include "llvm/IR/Dominators.h"
  25. #include <cassert>
  26. namespace llvm {
  27. class BranchInst;
  28. class LandingPadInst;
  29. class Loop;
  30. class PHINode;
  31. template <typename PtrType> class SmallPtrSetImpl;
  32. class BlockFrequencyInfo;
  33. class BranchProbabilityInfo;
  34. class DomTreeUpdater;
  35. class Function;
  36. class LoopInfo;
  37. class MDNode;
  38. class MemoryDependenceResults;
  39. class MemorySSAUpdater;
  40. class PostDominatorTree;
  41. class ReturnInst;
  42. class TargetLibraryInfo;
  43. class Value;
  44. /// Replace contents of every block in \p BBs with single unreachable
  45. /// instruction. If \p Updates is specified, collect all necessary DT updates
  46. /// into this vector. If \p KeepOneInputPHIs is true, one-input Phis in
  47. /// successors of blocks being deleted will be preserved.
  48. void detachDeadBlocks(ArrayRef <BasicBlock *> BBs,
  49. SmallVectorImpl<DominatorTree::UpdateType> *Updates,
  50. bool KeepOneInputPHIs = false);
  51. /// Delete the specified block, which must have no predecessors.
  52. void DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU = nullptr,
  53. bool KeepOneInputPHIs = false);
  54. /// Delete the specified blocks from \p BB. The set of deleted blocks must have
  55. /// no predecessors that are not being deleted themselves. \p BBs must have no
  56. /// duplicating blocks. If there are loops among this set of blocks, all
  57. /// relevant loop info updates should be done before this function is called.
  58. /// If \p KeepOneInputPHIs is true, one-input Phis in successors of blocks
  59. /// being deleted will be preserved.
  60. void DeleteDeadBlocks(ArrayRef <BasicBlock *> BBs,
  61. DomTreeUpdater *DTU = nullptr,
  62. bool KeepOneInputPHIs = false);
  63. /// Delete all basic blocks from \p F that are not reachable from its entry
  64. /// node. If \p KeepOneInputPHIs is true, one-input Phis in successors of
  65. /// blocks being deleted will be preserved.
  66. bool EliminateUnreachableBlocks(Function &F, DomTreeUpdater *DTU = nullptr,
  67. bool KeepOneInputPHIs = false);
  68. /// We know that BB has one predecessor. If there are any single-entry PHI nodes
  69. /// in it, fold them away. This handles the case when all entries to the PHI
  70. /// nodes in a block are guaranteed equal, such as when the block has exactly
  71. /// one predecessor.
  72. bool FoldSingleEntryPHINodes(BasicBlock *BB,
  73. MemoryDependenceResults *MemDep = nullptr);
  74. /// Examine each PHI in the given block and delete it if it is dead. Also
  75. /// recursively delete any operands that become dead as a result. This includes
  76. /// tracing the def-use list from the PHI to see if it is ultimately unused or
  77. /// if it reaches an unused cycle. Return true if any PHIs were deleted.
  78. bool DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI = nullptr,
  79. MemorySSAUpdater *MSSAU = nullptr);
  80. /// Attempts to merge a block into its predecessor, if possible. The return
  81. /// value indicates success or failure.
  82. /// By default do not merge blocks if BB's predecessor has multiple successors.
  83. /// If PredecessorWithTwoSuccessors = true, the blocks can only be merged
  84. /// if BB's Pred has a branch to BB and to AnotherBB, and BB has a single
  85. /// successor Sing. In this case the branch will be updated with Sing instead of
  86. /// BB, and BB will still be merged into its predecessor and removed.
  87. /// If \p DT is not nullptr, update it directly; in that case, DTU must be
  88. /// nullptr.
  89. bool MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU = nullptr,
  90. LoopInfo *LI = nullptr,
  91. MemorySSAUpdater *MSSAU = nullptr,
  92. MemoryDependenceResults *MemDep = nullptr,
  93. bool PredecessorWithTwoSuccessors = false,
  94. DominatorTree *DT = nullptr);
  95. /// Merge block(s) sucessors, if possible. Return true if at least two
  96. /// of the blocks were merged together.
  97. /// In order to merge, each block must be terminated by an unconditional
  98. /// branch. If L is provided, then the blocks merged into their predecessors
  99. /// must be in L. In addition, This utility calls on another utility:
  100. /// MergeBlockIntoPredecessor. Blocks are successfully merged when the call to
  101. /// MergeBlockIntoPredecessor returns true.
  102. bool MergeBlockSuccessorsIntoGivenBlocks(
  103. SmallPtrSetImpl<BasicBlock *> &MergeBlocks, Loop *L = nullptr,
  104. DomTreeUpdater *DTU = nullptr, LoopInfo *LI = nullptr);
  105. /// Try to remove redundant dbg.value instructions from given basic block.
  106. /// Returns true if at least one instruction was removed. Remove redundant
  107. /// pseudo ops when RemovePseudoOp is true.
  108. bool RemoveRedundantDbgInstrs(BasicBlock *BB);
  109. /// Replace all uses of an instruction (specified by BI) with a value, then
  110. /// remove and delete the original instruction.
  111. void ReplaceInstWithValue(BasicBlock::iterator &BI, Value *V);
  112. /// Replace the instruction specified by BI with the instruction specified by I.
  113. /// Copies DebugLoc from BI to I, if I doesn't already have a DebugLoc. The
  114. /// original instruction is deleted and BI is updated to point to the new
  115. /// instruction.
  116. void ReplaceInstWithInst(BasicBlock *BB, BasicBlock::iterator &BI,
  117. Instruction *I);
  118. /// Replace the instruction specified by From with the instruction specified by
  119. /// To. Copies DebugLoc from BI to I, if I doesn't already have a DebugLoc.
  120. void ReplaceInstWithInst(Instruction *From, Instruction *To);
  121. /// Check if we can prove that all paths starting from this block converge
  122. /// to a block that either has a @llvm.experimental.deoptimize call
  123. /// prior to its terminating return instruction or is terminated by unreachable.
  124. /// All blocks in the traversed sequence must have an unique successor, maybe
  125. /// except for the last one.
  126. bool IsBlockFollowedByDeoptOrUnreachable(const BasicBlock *BB);
  127. /// Option class for critical edge splitting.
  128. ///
  129. /// This provides a builder interface for overriding the default options used
  130. /// during critical edge splitting.
  131. struct CriticalEdgeSplittingOptions {
  132. DominatorTree *DT;
  133. PostDominatorTree *PDT;
  134. LoopInfo *LI;
  135. MemorySSAUpdater *MSSAU;
  136. bool MergeIdenticalEdges = false;
  137. bool KeepOneInputPHIs = false;
  138. bool PreserveLCSSA = false;
  139. bool IgnoreUnreachableDests = false;
  140. /// SplitCriticalEdge is guaranteed to preserve loop-simplify form if LI is
  141. /// provided. If it cannot be preserved, no splitting will take place. If it
  142. /// is not set, preserve loop-simplify form if possible.
  143. bool PreserveLoopSimplify = true;
  144. CriticalEdgeSplittingOptions(DominatorTree *DT = nullptr,
  145. LoopInfo *LI = nullptr,
  146. MemorySSAUpdater *MSSAU = nullptr,
  147. PostDominatorTree *PDT = nullptr)
  148. : DT(DT), PDT(PDT), LI(LI), MSSAU(MSSAU) {}
  149. CriticalEdgeSplittingOptions &setMergeIdenticalEdges() {
  150. MergeIdenticalEdges = true;
  151. return *this;
  152. }
  153. CriticalEdgeSplittingOptions &setKeepOneInputPHIs() {
  154. KeepOneInputPHIs = true;
  155. return *this;
  156. }
  157. CriticalEdgeSplittingOptions &setPreserveLCSSA() {
  158. PreserveLCSSA = true;
  159. return *this;
  160. }
  161. CriticalEdgeSplittingOptions &setIgnoreUnreachableDests() {
  162. IgnoreUnreachableDests = true;
  163. return *this;
  164. }
  165. CriticalEdgeSplittingOptions &unsetPreserveLoopSimplify() {
  166. PreserveLoopSimplify = false;
  167. return *this;
  168. }
  169. };
  170. /// When a loop exit edge is split, LCSSA form may require new PHIs in the new
  171. /// exit block. This function inserts the new PHIs, as needed. Preds is a list
  172. /// of preds inside the loop, SplitBB is the new loop exit block, and DestBB is
  173. /// the old loop exit, now the successor of SplitBB.
  174. void createPHIsForSplitLoopExit(ArrayRef<BasicBlock *> Preds,
  175. BasicBlock *SplitBB, BasicBlock *DestBB);
  176. /// If this edge is a critical edge, insert a new node to split the critical
  177. /// edge. This will update the analyses passed in through the option struct.
  178. /// This returns the new block if the edge was split, null otherwise.
  179. ///
  180. /// If MergeIdenticalEdges in the options struct is true (not the default),
  181. /// *all* edges from TI to the specified successor will be merged into the same
  182. /// critical edge block. This is most commonly interesting with switch
  183. /// instructions, which may have many edges to any one destination. This
  184. /// ensures that all edges to that dest go to one block instead of each going
  185. /// to a different block, but isn't the standard definition of a "critical
  186. /// edge".
  187. ///
  188. /// It is invalid to call this function on a critical edge that starts at an
  189. /// IndirectBrInst. Splitting these edges will almost always create an invalid
  190. /// program because the address of the new block won't be the one that is jumped
  191. /// to.
  192. BasicBlock *SplitCriticalEdge(Instruction *TI, unsigned SuccNum,
  193. const CriticalEdgeSplittingOptions &Options =
  194. CriticalEdgeSplittingOptions(),
  195. const Twine &BBName = "");
  196. /// If it is known that an edge is critical, SplitKnownCriticalEdge can be
  197. /// called directly, rather than calling SplitCriticalEdge first.
  198. BasicBlock *SplitKnownCriticalEdge(Instruction *TI, unsigned SuccNum,
  199. const CriticalEdgeSplittingOptions &Options =
  200. CriticalEdgeSplittingOptions(),
  201. const Twine &BBName = "");
  202. /// If an edge from Src to Dst is critical, split the edge and return true,
  203. /// otherwise return false. This method requires that there be an edge between
  204. /// the two blocks. It updates the analyses passed in the options struct
  205. inline BasicBlock *
  206. SplitCriticalEdge(BasicBlock *Src, BasicBlock *Dst,
  207. const CriticalEdgeSplittingOptions &Options =
  208. CriticalEdgeSplittingOptions()) {
  209. Instruction *TI = Src->getTerminator();
  210. unsigned i = 0;
  211. while (true) {
  212. assert(i != TI->getNumSuccessors() && "Edge doesn't exist!");
  213. if (TI->getSuccessor(i) == Dst)
  214. return SplitCriticalEdge(TI, i, Options);
  215. ++i;
  216. }
  217. }
  218. /// Loop over all of the edges in the CFG, breaking critical edges as they are
  219. /// found. Returns the number of broken edges.
  220. unsigned SplitAllCriticalEdges(Function &F,
  221. const CriticalEdgeSplittingOptions &Options =
  222. CriticalEdgeSplittingOptions());
  223. /// Split the edge connecting the specified blocks, and return the newly created
  224. /// basic block between \p From and \p To.
  225. BasicBlock *SplitEdge(BasicBlock *From, BasicBlock *To,
  226. DominatorTree *DT = nullptr, LoopInfo *LI = nullptr,
  227. MemorySSAUpdater *MSSAU = nullptr,
  228. const Twine &BBName = "");
  229. /// Sets the unwind edge of an instruction to a particular successor.
  230. void setUnwindEdgeTo(Instruction *TI, BasicBlock *Succ);
  231. /// Replaces all uses of OldPred with the NewPred block in all PHINodes in a
  232. /// block.
  233. void updatePhiNodes(BasicBlock *DestBB, BasicBlock *OldPred,
  234. BasicBlock *NewPred, PHINode *Until = nullptr);
  235. /// Split the edge connect the specficed blocks in the case that \p Succ is an
  236. /// Exception Handling Block
  237. BasicBlock *ehAwareSplitEdge(BasicBlock *BB, BasicBlock *Succ,
  238. LandingPadInst *OriginalPad = nullptr,
  239. PHINode *LandingPadReplacement = nullptr,
  240. const CriticalEdgeSplittingOptions &Options =
  241. CriticalEdgeSplittingOptions(),
  242. const Twine &BBName = "");
  243. /// Split the specified block at the specified instruction.
  244. ///
  245. /// If \p Before is true, splitBlockBefore handles the block
  246. /// splitting. Otherwise, execution proceeds as described below.
  247. ///
  248. /// Everything before \p SplitPt stays in \p Old and everything starting with \p
  249. /// SplitPt moves to a new block. The two blocks are joined by an unconditional
  250. /// branch. The new block with name \p BBName is returned.
  251. ///
  252. /// FIXME: deprecated, switch to the DomTreeUpdater-based one.
  253. BasicBlock *SplitBlock(BasicBlock *Old, Instruction *SplitPt, DominatorTree *DT,
  254. LoopInfo *LI = nullptr,
  255. MemorySSAUpdater *MSSAU = nullptr,
  256. const Twine &BBName = "", bool Before = false);
  257. /// Split the specified block at the specified instruction.
  258. ///
  259. /// If \p Before is true, splitBlockBefore handles the block
  260. /// splitting. Otherwise, execution proceeds as described below.
  261. ///
  262. /// Everything before \p SplitPt stays in \p Old and everything starting with \p
  263. /// SplitPt moves to a new block. The two blocks are joined by an unconditional
  264. /// branch. The new block with name \p BBName is returned.
  265. BasicBlock *SplitBlock(BasicBlock *Old, Instruction *SplitPt,
  266. DomTreeUpdater *DTU = nullptr, LoopInfo *LI = nullptr,
  267. MemorySSAUpdater *MSSAU = nullptr,
  268. const Twine &BBName = "", bool Before = false);
  269. /// Split the specified block at the specified instruction \p SplitPt.
  270. /// All instructions before \p SplitPt are moved to a new block and all
  271. /// instructions after \p SplitPt stay in the old block. The new block and the
  272. /// old block are joined by inserting an unconditional branch to the end of the
  273. /// new block. The new block with name \p BBName is returned.
  274. BasicBlock *splitBlockBefore(BasicBlock *Old, Instruction *SplitPt,
  275. DomTreeUpdater *DTU, LoopInfo *LI,
  276. MemorySSAUpdater *MSSAU, const Twine &BBName = "");
  277. /// This method introduces at least one new basic block into the function and
  278. /// moves some of the predecessors of BB to be predecessors of the new block.
  279. /// The new predecessors are indicated by the Preds array. The new block is
  280. /// given a suffix of 'Suffix'. Returns new basic block to which predecessors
  281. /// from Preds are now pointing.
  282. ///
  283. /// If BB is a landingpad block then additional basicblock might be introduced.
  284. /// It will have Suffix+".split_lp". See SplitLandingPadPredecessors for more
  285. /// details on this case.
  286. ///
  287. /// This currently updates the LLVM IR, DominatorTree, LoopInfo, and LCCSA but
  288. /// no other analyses. In particular, it does not preserve LoopSimplify
  289. /// (because it's complicated to handle the case where one of the edges being
  290. /// split is an exit of a loop with other exits).
  291. ///
  292. /// FIXME: deprecated, switch to the DomTreeUpdater-based one.
  293. BasicBlock *SplitBlockPredecessors(BasicBlock *BB, ArrayRef<BasicBlock *> Preds,
  294. const char *Suffix, DominatorTree *DT,
  295. LoopInfo *LI = nullptr,
  296. MemorySSAUpdater *MSSAU = nullptr,
  297. bool PreserveLCSSA = false);
  298. /// This method introduces at least one new basic block into the function and
  299. /// moves some of the predecessors of BB to be predecessors of the new block.
  300. /// The new predecessors are indicated by the Preds array. The new block is
  301. /// given a suffix of 'Suffix'. Returns new basic block to which predecessors
  302. /// from Preds are now pointing.
  303. ///
  304. /// If BB is a landingpad block then additional basicblock might be introduced.
  305. /// It will have Suffix+".split_lp". See SplitLandingPadPredecessors for more
  306. /// details on this case.
  307. ///
  308. /// This currently updates the LLVM IR, DominatorTree, LoopInfo, and LCCSA but
  309. /// no other analyses. In particular, it does not preserve LoopSimplify
  310. /// (because it's complicated to handle the case where one of the edges being
  311. /// split is an exit of a loop with other exits).
  312. BasicBlock *SplitBlockPredecessors(BasicBlock *BB, ArrayRef<BasicBlock *> Preds,
  313. const char *Suffix,
  314. DomTreeUpdater *DTU = nullptr,
  315. LoopInfo *LI = nullptr,
  316. MemorySSAUpdater *MSSAU = nullptr,
  317. bool PreserveLCSSA = false);
  318. /// This method transforms the landing pad, OrigBB, by introducing two new basic
  319. /// blocks into the function. One of those new basic blocks gets the
  320. /// predecessors listed in Preds. The other basic block gets the remaining
  321. /// predecessors of OrigBB. The landingpad instruction OrigBB is clone into both
  322. /// of the new basic blocks. The new blocks are given the suffixes 'Suffix1' and
  323. /// 'Suffix2', and are returned in the NewBBs vector.
  324. ///
  325. /// This currently updates the LLVM IR, DominatorTree, LoopInfo, and LCCSA but
  326. /// no other analyses. In particular, it does not preserve LoopSimplify
  327. /// (because it's complicated to handle the case where one of the edges being
  328. /// split is an exit of a loop with other exits).
  329. ///
  330. /// FIXME: deprecated, switch to the DomTreeUpdater-based one.
  331. void SplitLandingPadPredecessors(BasicBlock *OrigBB,
  332. ArrayRef<BasicBlock *> Preds,
  333. const char *Suffix, const char *Suffix2,
  334. SmallVectorImpl<BasicBlock *> &NewBBs,
  335. DominatorTree *DT, LoopInfo *LI = nullptr,
  336. MemorySSAUpdater *MSSAU = nullptr,
  337. bool PreserveLCSSA = false);
  338. /// This method transforms the landing pad, OrigBB, by introducing two new basic
  339. /// blocks into the function. One of those new basic blocks gets the
  340. /// predecessors listed in Preds. The other basic block gets the remaining
  341. /// predecessors of OrigBB. The landingpad instruction OrigBB is clone into both
  342. /// of the new basic blocks. The new blocks are given the suffixes 'Suffix1' and
  343. /// 'Suffix2', and are returned in the NewBBs vector.
  344. ///
  345. /// This currently updates the LLVM IR, DominatorTree, LoopInfo, and LCCSA but
  346. /// no other analyses. In particular, it does not preserve LoopSimplify
  347. /// (because it's complicated to handle the case where one of the edges being
  348. /// split is an exit of a loop with other exits).
  349. void SplitLandingPadPredecessors(
  350. BasicBlock *OrigBB, ArrayRef<BasicBlock *> Preds, const char *Suffix,
  351. const char *Suffix2, SmallVectorImpl<BasicBlock *> &NewBBs,
  352. DomTreeUpdater *DTU = nullptr, LoopInfo *LI = nullptr,
  353. MemorySSAUpdater *MSSAU = nullptr, bool PreserveLCSSA = false);
  354. /// This method duplicates the specified return instruction into a predecessor
  355. /// which ends in an unconditional branch. If the return instruction returns a
  356. /// value defined by a PHI, propagate the right value into the return. It
  357. /// returns the new return instruction in the predecessor.
  358. ReturnInst *FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
  359. BasicBlock *Pred,
  360. DomTreeUpdater *DTU = nullptr);
  361. /// Split the containing block at the specified instruction - everything before
  362. /// SplitBefore stays in the old basic block, and the rest of the instructions
  363. /// in the BB are moved to a new block. The two blocks are connected by a
  364. /// conditional branch (with value of Cmp being the condition).
  365. /// Before:
  366. /// Head
  367. /// SplitBefore
  368. /// Tail
  369. /// After:
  370. /// Head
  371. /// if (Cond)
  372. /// ThenBlock
  373. /// SplitBefore
  374. /// Tail
  375. ///
  376. /// If \p ThenBlock is not specified, a new block will be created for it.
  377. /// If \p Unreachable is true, the newly created block will end with
  378. /// UnreachableInst, otherwise it branches to Tail.
  379. /// Returns the NewBasicBlock's terminator.
  380. ///
  381. /// Updates DT and LI if given.
  382. ///
  383. /// FIXME: deprecated, switch to the DomTreeUpdater-based one.
  384. Instruction *SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore,
  385. bool Unreachable, MDNode *BranchWeights,
  386. DominatorTree *DT,
  387. LoopInfo *LI = nullptr,
  388. BasicBlock *ThenBlock = nullptr);
  389. /// Split the containing block at the specified instruction - everything before
  390. /// SplitBefore stays in the old basic block, and the rest of the instructions
  391. /// in the BB are moved to a new block. The two blocks are connected by a
  392. /// conditional branch (with value of Cmp being the condition).
  393. /// Before:
  394. /// Head
  395. /// SplitBefore
  396. /// Tail
  397. /// After:
  398. /// Head
  399. /// if (Cond)
  400. /// ThenBlock
  401. /// SplitBefore
  402. /// Tail
  403. ///
  404. /// If \p ThenBlock is not specified, a new block will be created for it.
  405. /// If \p Unreachable is true, the newly created block will end with
  406. /// UnreachableInst, otherwise it branches to Tail.
  407. /// Returns the NewBasicBlock's terminator.
  408. ///
  409. /// Updates DT and LI if given.
  410. Instruction *SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore,
  411. bool Unreachable,
  412. MDNode *BranchWeights = nullptr,
  413. DomTreeUpdater *DTU = nullptr,
  414. LoopInfo *LI = nullptr,
  415. BasicBlock *ThenBlock = nullptr);
  416. /// SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen,
  417. /// but also creates the ElseBlock.
  418. /// Before:
  419. /// Head
  420. /// SplitBefore
  421. /// Tail
  422. /// After:
  423. /// Head
  424. /// if (Cond)
  425. /// ThenBlock
  426. /// else
  427. /// ElseBlock
  428. /// SplitBefore
  429. /// Tail
  430. ///
  431. /// Updates DT if given.
  432. void SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore,
  433. Instruction **ThenTerm,
  434. Instruction **ElseTerm,
  435. MDNode *BranchWeights = nullptr,
  436. DomTreeUpdater *DTU = nullptr);
  437. /// Check whether BB is the merge point of a if-region.
  438. /// If so, return the branch instruction that determines which entry into
  439. /// BB will be taken. Also, return by references the block that will be
  440. /// entered from if the condition is true, and the block that will be
  441. /// entered if the condition is false.
  442. ///
  443. /// This does no checking to see if the true/false blocks have large or unsavory
  444. /// instructions in them.
  445. BranchInst *GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
  446. BasicBlock *&IfFalse);
  447. // Split critical edges where the source of the edge is an indirectbr
  448. // instruction. This isn't always possible, but we can handle some easy cases.
  449. // This is useful because MI is unable to split such critical edges,
  450. // which means it will not be able to sink instructions along those edges.
  451. // This is especially painful for indirect branches with many successors, where
  452. // we end up having to prepare all outgoing values in the origin block.
  453. //
  454. // Our normal algorithm for splitting critical edges requires us to update
  455. // the outgoing edges of the edge origin block, but for an indirectbr this
  456. // is hard, since it would require finding and updating the block addresses
  457. // the indirect branch uses. But if a block only has a single indirectbr
  458. // predecessor, with the others being regular branches, we can do it in a
  459. // different way.
  460. // Say we have A -> D, B -> D, I -> D where only I -> D is an indirectbr.
  461. // We can split D into D0 and D1, where D0 contains only the PHIs from D,
  462. // and D1 is the D block body. We can then duplicate D0 as D0A and D0B, and
  463. // create the following structure:
  464. // A -> D0A, B -> D0A, I -> D0B, D0A -> D1, D0B -> D1
  465. // If BPI and BFI aren't non-null, BPI/BFI will be updated accordingly.
  466. // When `IgnoreBlocksWithoutPHI` is set to `true` critical edges leading to a
  467. // block without phi-instructions will not be split.
  468. bool SplitIndirectBrCriticalEdges(Function &F, bool IgnoreBlocksWithoutPHI,
  469. BranchProbabilityInfo *BPI = nullptr,
  470. BlockFrequencyInfo *BFI = nullptr);
  471. /// Given a set of incoming and outgoing blocks, create a "hub" such that every
  472. /// edge from an incoming block InBB to an outgoing block OutBB is now split
  473. /// into two edges, one from InBB to the hub and another from the hub to
  474. /// OutBB. The hub consists of a series of guard blocks, one for each outgoing
  475. /// block. Each guard block conditionally branches to the corresponding outgoing
  476. /// block, or the next guard block in the chain. These guard blocks are returned
  477. /// in the argument vector.
  478. ///
  479. /// Since the control flow edges from InBB to OutBB have now been replaced, the
  480. /// function also updates any PHINodes in OutBB. For each such PHINode, the
  481. /// operands corresponding to incoming blocks are moved to a new PHINode in the
  482. /// hub, and the hub is made an operand of the original PHINode.
  483. ///
  484. /// Input CFG:
  485. /// ----------
  486. ///
  487. /// Def
  488. /// |
  489. /// v
  490. /// In1 In2
  491. /// | |
  492. /// | |
  493. /// v v
  494. /// Foo ---> Out1 Out2
  495. /// |
  496. /// v
  497. /// Use
  498. ///
  499. ///
  500. /// Create hub: Incoming = {In1, In2}, Outgoing = {Out1, Out2}
  501. /// ----------------------------------------------------------
  502. ///
  503. /// Def
  504. /// |
  505. /// v
  506. /// In1 In2 Foo
  507. /// | Hub | |
  508. /// | + - - | - - + |
  509. /// | ' v ' V
  510. /// +------> Guard1 -----> Out1
  511. /// ' | '
  512. /// ' v '
  513. /// ' Guard2 -----> Out2
  514. /// ' ' |
  515. /// + - - - - - + |
  516. /// v
  517. /// Use
  518. ///
  519. /// Limitations:
  520. /// -----------
  521. /// 1. This assumes that all terminators in the CFG are direct branches (the
  522. /// "br" instruction). The presence of any other control flow such as
  523. /// indirectbr, switch or callbr will cause an assert.
  524. ///
  525. /// 2. The updates to the PHINodes are not sufficient to restore SSA
  526. /// form. Consider a definition Def, its use Use, incoming block In2 and
  527. /// outgoing block Out2, such that:
  528. /// a. In2 is reachable from D or contains D.
  529. /// b. U is reachable from Out2 or is contained in Out2.
  530. /// c. U is not a PHINode if U is contained in Out2.
  531. ///
  532. /// Clearly, Def dominates Out2 since the program is valid SSA. But when the
  533. /// hub is introduced, there is a new path through the hub along which Use is
  534. /// reachable from entry without passing through Def, and SSA is no longer
  535. /// valid. To fix this, we need to look at all the blocks post-dominated by
  536. /// the hub on the one hand, and dominated by Out2 on the other. This is left
  537. /// for the caller to accomplish, since each specific use of this function
  538. /// may have additional information which simplifies this fixup. For example,
  539. /// see restoreSSA() in the UnifyLoopExits pass.
  540. BasicBlock *CreateControlFlowHub(
  541. DomTreeUpdater *DTU, SmallVectorImpl<BasicBlock *> &GuardBlocks,
  542. const SetVector<BasicBlock *> &Predecessors,
  543. const SetVector<BasicBlock *> &Successors, const StringRef Prefix,
  544. std::optional<unsigned> MaxControlFlowBooleans = std::nullopt);
  545. } // end namespace llvm
  546. #endif // LLVM_TRANSFORMS_UTILS_BASICBLOCKUTILS_H
  547. #ifdef __GNUC__
  548. #pragma GCC diagnostic pop
  549. #endif