MachineBlockPlacement.cpp 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857
  1. //===-- MachineBlockPlacement.cpp - Basic Block Code Layout optimization --===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements basic block placement transformations using the CFG
  11. // structure and branch probability estimates.
  12. //
  13. // The pass strives to preserve the structure of the CFG (that is, retain
  14. // a topological ordering of basic blocks) in the absence of a *strong* signal
  15. // to the contrary from probabilities. However, within the CFG structure, it
  16. // attempts to choose an ordering which favors placing more likely sequences of
  17. // blocks adjacent to each other.
  18. //
  19. // The algorithm works from the inner-most loop within a function outward, and
  20. // at each stage walks through the basic blocks, trying to coalesce them into
  21. // sequential chains where allowed by the CFG (or demanded by heavy
  22. // probabilities). Finally, it walks the blocks in topological order, and the
  23. // first time it reaches a chain of basic blocks, it schedules them in the
  24. // function in-order.
  25. //
  26. //===----------------------------------------------------------------------===//
  27. #include "llvm/CodeGen/Passes.h"
  28. #include "llvm/CodeGen/TargetPassConfig.h"
  29. #include "BranchFolding.h"
  30. #include "llvm/ADT/DenseMap.h"
  31. #include "llvm/ADT/SmallPtrSet.h"
  32. #include "llvm/ADT/SmallVector.h"
  33. #include "llvm/ADT/Statistic.h"
  34. #include "llvm/CodeGen/MachineBasicBlock.h"
  35. #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
  36. #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
  37. #include "llvm/CodeGen/MachineDominators.h"
  38. #include "llvm/CodeGen/MachineFunction.h"
  39. #include "llvm/CodeGen/MachineFunctionPass.h"
  40. #include "llvm/CodeGen/MachineLoopInfo.h"
  41. #include "llvm/CodeGen/MachineModuleInfo.h"
  42. #include "llvm/Support/Allocator.h"
  43. #include "llvm/Support/CommandLine.h"
  44. #include "llvm/Support/Debug.h"
  45. #include "llvm/Support/raw_ostream.h"
  46. #include "llvm/Target/TargetInstrInfo.h"
  47. #include "llvm/Target/TargetLowering.h"
  48. #include "llvm/Target/TargetSubtargetInfo.h"
  49. #include <algorithm>
  50. using namespace llvm;
  51. #define DEBUG_TYPE "block-placement"
  52. STATISTIC(NumCondBranches, "Number of conditional branches");
  53. STATISTIC(NumUncondBranches, "Number of unconditional branches");
  54. STATISTIC(CondBranchTakenFreq,
  55. "Potential frequency of taking conditional branches");
  56. STATISTIC(UncondBranchTakenFreq,
  57. "Potential frequency of taking unconditional branches");
  58. static cl::opt<unsigned> AlignAllBlock("align-all-blocks",
  59. cl::desc("Force the alignment of all "
  60. "blocks in the function."),
  61. cl::init(0), cl::Hidden);
  62. static cl::opt<unsigned> AlignAllNonFallThruBlocks(
  63. "align-all-nofallthru-blocks",
  64. cl::desc("Force the alignment of all "
  65. "blocks that have no fall-through predecessors (i.e. don't add "
  66. "nops that are executed)."),
  67. cl::init(0), cl::Hidden);
  68. // FIXME: Find a good default for this flag and remove the flag.
  69. static cl::opt<unsigned> ExitBlockBias(
  70. "block-placement-exit-block-bias",
  71. cl::desc("Block frequency percentage a loop exit block needs "
  72. "over the original exit to be considered the new exit."),
  73. cl::init(0), cl::Hidden);
  74. // Definition:
  75. // - Outlining: placement of a basic block outside the chain or hot path.
  76. static cl::opt<bool> OutlineOptionalBranches(
  77. "outline-optional-branches",
  78. cl::desc("Outlining optional branches will place blocks that are optional "
  79. "branches, i.e. branches with a common post dominator, outside "
  80. "the hot path or chain"),
  81. cl::init(false), cl::Hidden);
  82. static cl::opt<unsigned> OutlineOptionalThreshold(
  83. "outline-optional-threshold",
  84. cl::desc("Don't outline optional branches that are a single block with an "
  85. "instruction count below this threshold"),
  86. cl::init(4), cl::Hidden);
  87. static cl::opt<unsigned> LoopToColdBlockRatio(
  88. "loop-to-cold-block-ratio",
  89. cl::desc("Outline loop blocks from loop chain if (frequency of loop) / "
  90. "(frequency of block) is greater than this ratio"),
  91. cl::init(5), cl::Hidden);
  92. static cl::opt<bool>
  93. PreciseRotationCost("precise-rotation-cost",
  94. cl::desc("Model the cost of loop rotation more "
  95. "precisely by using profile data."),
  96. cl::init(false), cl::Hidden);
  97. static cl::opt<bool>
  98. ForcePreciseRotationCost("force-precise-rotation-cost",
  99. cl::desc("Force the use of precise cost "
  100. "loop rotation strategy."),
  101. cl::init(false), cl::Hidden);
  102. static cl::opt<unsigned> MisfetchCost(
  103. "misfetch-cost",
  104. cl::desc("Cost that models the probabilistic risk of an instruction "
  105. "misfetch due to a jump comparing to falling through, whose cost "
  106. "is zero."),
  107. cl::init(1), cl::Hidden);
  108. static cl::opt<unsigned> JumpInstCost("jump-inst-cost",
  109. cl::desc("Cost of jump instructions."),
  110. cl::init(1), cl::Hidden);
  111. static cl::opt<bool>
  112. BranchFoldPlacement("branch-fold-placement",
  113. cl::desc("Perform branch folding during placement. "
  114. "Reduces code size."),
  115. cl::init(true), cl::Hidden);
  116. extern cl::opt<unsigned> StaticLikelyProb;
  117. extern cl::opt<unsigned> ProfileLikelyProb;
  118. namespace {
  119. class BlockChain;
  120. /// \brief Type for our function-wide basic block -> block chain mapping.
  121. typedef DenseMap<MachineBasicBlock *, BlockChain *> BlockToChainMapType;
  122. }
  123. namespace {
  124. /// \brief A chain of blocks which will be laid out contiguously.
  125. ///
  126. /// This is the datastructure representing a chain of consecutive blocks that
  127. /// are profitable to layout together in order to maximize fallthrough
  128. /// probabilities and code locality. We also can use a block chain to represent
  129. /// a sequence of basic blocks which have some external (correctness)
  130. /// requirement for sequential layout.
  131. ///
  132. /// Chains can be built around a single basic block and can be merged to grow
  133. /// them. They participate in a block-to-chain mapping, which is updated
  134. /// automatically as chains are merged together.
  135. class BlockChain {
  136. /// \brief The sequence of blocks belonging to this chain.
  137. ///
  138. /// This is the sequence of blocks for a particular chain. These will be laid
  139. /// out in-order within the function.
  140. SmallVector<MachineBasicBlock *, 4> Blocks;
  141. /// \brief A handle to the function-wide basic block to block chain mapping.
  142. ///
  143. /// This is retained in each block chain to simplify the computation of child
  144. /// block chains for SCC-formation and iteration. We store the edges to child
  145. /// basic blocks, and map them back to their associated chains using this
  146. /// structure.
  147. BlockToChainMapType &BlockToChain;
  148. public:
  149. /// \brief Construct a new BlockChain.
  150. ///
  151. /// This builds a new block chain representing a single basic block in the
  152. /// function. It also registers itself as the chain that block participates
  153. /// in with the BlockToChain mapping.
  154. BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
  155. : Blocks(1, BB), BlockToChain(BlockToChain), UnscheduledPredecessors(0) {
  156. assert(BB && "Cannot create a chain with a null basic block");
  157. BlockToChain[BB] = this;
  158. }
  159. /// \brief Iterator over blocks within the chain.
  160. typedef SmallVectorImpl<MachineBasicBlock *>::iterator iterator;
  161. /// \brief Beginning of blocks within the chain.
  162. iterator begin() { return Blocks.begin(); }
  163. /// \brief End of blocks within the chain.
  164. iterator end() { return Blocks.end(); }
  165. /// \brief Merge a block chain into this one.
  166. ///
  167. /// This routine merges a block chain into this one. It takes care of forming
  168. /// a contiguous sequence of basic blocks, updating the edge list, and
  169. /// updating the block -> chain mapping. It does not free or tear down the
  170. /// old chain, but the old chain's block list is no longer valid.
  171. void merge(MachineBasicBlock *BB, BlockChain *Chain) {
  172. assert(BB);
  173. assert(!Blocks.empty());
  174. // Fast path in case we don't have a chain already.
  175. if (!Chain) {
  176. assert(!BlockToChain[BB]);
  177. Blocks.push_back(BB);
  178. BlockToChain[BB] = this;
  179. return;
  180. }
  181. assert(BB == *Chain->begin());
  182. assert(Chain->begin() != Chain->end());
  183. // Update the incoming blocks to point to this chain, and add them to the
  184. // chain structure.
  185. for (MachineBasicBlock *ChainBB : *Chain) {
  186. Blocks.push_back(ChainBB);
  187. assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain");
  188. BlockToChain[ChainBB] = this;
  189. }
  190. }
  191. #ifndef NDEBUG
  192. /// \brief Dump the blocks in this chain.
  193. LLVM_DUMP_METHOD void dump() {
  194. for (MachineBasicBlock *MBB : *this)
  195. MBB->dump();
  196. }
  197. #endif // NDEBUG
  198. /// \brief Count of predecessors of any block within the chain which have not
  199. /// yet been scheduled. In general, we will delay scheduling this chain
  200. /// until those predecessors are scheduled (or we find a sufficiently good
  201. /// reason to override this heuristic.) Note that when forming loop chains,
  202. /// blocks outside the loop are ignored and treated as if they were already
  203. /// scheduled.
  204. ///
  205. /// Note: This field is reinitialized multiple times - once for each loop,
  206. /// and then once for the function as a whole.
  207. unsigned UnscheduledPredecessors;
  208. };
  209. }
  210. namespace {
  211. class MachineBlockPlacement : public MachineFunctionPass {
  212. /// \brief A typedef for a block filter set.
  213. typedef SmallPtrSet<MachineBasicBlock *, 16> BlockFilterSet;
  214. /// \brief work lists of blocks that are ready to be laid out
  215. SmallVector<MachineBasicBlock *, 16> BlockWorkList;
  216. SmallVector<MachineBasicBlock *, 16> EHPadWorkList;
  217. /// \brief Machine Function
  218. MachineFunction *F;
  219. /// \brief A handle to the branch probability pass.
  220. const MachineBranchProbabilityInfo *MBPI;
  221. /// \brief A handle to the function-wide block frequency pass.
  222. std::unique_ptr<BranchFolder::MBFIWrapper> MBFI;
  223. /// \brief A handle to the loop info.
  224. MachineLoopInfo *MLI;
  225. /// \brief A handle to the target's instruction info.
  226. const TargetInstrInfo *TII;
  227. /// \brief A handle to the target's lowering info.
  228. const TargetLoweringBase *TLI;
  229. /// \brief A handle to the post dominator tree.
  230. MachineDominatorTree *MDT;
  231. /// \brief A set of blocks that are unavoidably execute, i.e. they dominate
  232. /// all terminators of the MachineFunction.
  233. SmallPtrSet<MachineBasicBlock *, 4> UnavoidableBlocks;
  234. /// \brief Allocator and owner of BlockChain structures.
  235. ///
  236. /// We build BlockChains lazily while processing the loop structure of
  237. /// a function. To reduce malloc traffic, we allocate them using this
  238. /// slab-like allocator, and destroy them after the pass completes. An
  239. /// important guarantee is that this allocator produces stable pointers to
  240. /// the chains.
  241. SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
  242. /// \brief Function wide BasicBlock to BlockChain mapping.
  243. ///
  244. /// This mapping allows efficiently moving from any given basic block to the
  245. /// BlockChain it participates in, if any. We use it to, among other things,
  246. /// allow implicitly defining edges between chains as the existing edges
  247. /// between basic blocks.
  248. DenseMap<MachineBasicBlock *, BlockChain *> BlockToChain;
  249. void markChainSuccessors(BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
  250. const BlockFilterSet *BlockFilter = nullptr);
  251. BranchProbability
  252. collectViableSuccessors(MachineBasicBlock *BB, BlockChain &Chain,
  253. const BlockFilterSet *BlockFilter,
  254. SmallVector<MachineBasicBlock *, 4> &Successors);
  255. bool shouldPredBlockBeOutlined(MachineBasicBlock *BB, MachineBasicBlock *Succ,
  256. BlockChain &Chain,
  257. const BlockFilterSet *BlockFilter,
  258. BranchProbability SuccProb,
  259. BranchProbability HotProb);
  260. bool
  261. hasBetterLayoutPredecessor(MachineBasicBlock *BB, MachineBasicBlock *Succ,
  262. BlockChain &SuccChain, BranchProbability SuccProb,
  263. BranchProbability RealSuccProb, BlockChain &Chain,
  264. const BlockFilterSet *BlockFilter);
  265. MachineBasicBlock *selectBestSuccessor(MachineBasicBlock *BB,
  266. BlockChain &Chain,
  267. const BlockFilterSet *BlockFilter);
  268. MachineBasicBlock *
  269. selectBestCandidateBlock(BlockChain &Chain,
  270. SmallVectorImpl<MachineBasicBlock *> &WorkList);
  271. MachineBasicBlock *
  272. getFirstUnplacedBlock(const BlockChain &PlacedChain,
  273. MachineFunction::iterator &PrevUnplacedBlockIt,
  274. const BlockFilterSet *BlockFilter);
  275. /// \brief Add a basic block to the work list if it is appropriate.
  276. ///
  277. /// If the optional parameter BlockFilter is provided, only MBB
  278. /// present in the set will be added to the worklist. If nullptr
  279. /// is provided, no filtering occurs.
  280. void fillWorkLists(MachineBasicBlock *MBB,
  281. SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
  282. const BlockFilterSet *BlockFilter);
  283. void buildChain(MachineBasicBlock *BB, BlockChain &Chain,
  284. const BlockFilterSet *BlockFilter = nullptr);
  285. MachineBasicBlock *findBestLoopTop(MachineLoop &L,
  286. const BlockFilterSet &LoopBlockSet);
  287. MachineBasicBlock *findBestLoopExit(MachineLoop &L,
  288. const BlockFilterSet &LoopBlockSet);
  289. BlockFilterSet collectLoopBlockSet(MachineLoop &L);
  290. void buildLoopChains(MachineLoop &L);
  291. void rotateLoop(BlockChain &LoopChain, MachineBasicBlock *ExitingBB,
  292. const BlockFilterSet &LoopBlockSet);
  293. void rotateLoopWithProfile(BlockChain &LoopChain, MachineLoop &L,
  294. const BlockFilterSet &LoopBlockSet);
  295. void collectMustExecuteBBs();
  296. void buildCFGChains();
  297. void optimizeBranches();
  298. void alignBlocks();
  299. public:
  300. static char ID; // Pass identification, replacement for typeid
  301. MachineBlockPlacement() : MachineFunctionPass(ID) {
  302. initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
  303. }
  304. bool runOnMachineFunction(MachineFunction &F) override;
  305. void getAnalysisUsage(AnalysisUsage &AU) const override {
  306. AU.addRequired<MachineBranchProbabilityInfo>();
  307. AU.addRequired<MachineBlockFrequencyInfo>();
  308. AU.addRequired<MachineDominatorTree>();
  309. AU.addRequired<MachineLoopInfo>();
  310. AU.addRequired<TargetPassConfig>();
  311. MachineFunctionPass::getAnalysisUsage(AU);
  312. }
  313. };
  314. }
  315. char MachineBlockPlacement::ID = 0;
  316. char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
  317. INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement",
  318. "Branch Probability Basic Block Placement", false, false)
  319. INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
  320. INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
  321. INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
  322. INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
  323. INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement",
  324. "Branch Probability Basic Block Placement", false, false)
  325. #ifndef NDEBUG
  326. /// \brief Helper to print the name of a MBB.
  327. ///
  328. /// Only used by debug logging.
  329. static std::string getBlockName(MachineBasicBlock *BB) {
  330. std::string Result;
  331. raw_string_ostream OS(Result);
  332. OS << "BB#" << BB->getNumber();
  333. OS << " ('" << BB->getName() << "')";
  334. OS.flush();
  335. return Result;
  336. }
  337. #endif
  338. /// \brief Mark a chain's successors as having one fewer preds.
  339. ///
  340. /// When a chain is being merged into the "placed" chain, this routine will
  341. /// quickly walk the successors of each block in the chain and mark them as
  342. /// having one fewer active predecessor. It also adds any successors of this
  343. /// chain which reach the zero-predecessor state to the worklist passed in.
  344. void MachineBlockPlacement::markChainSuccessors(
  345. BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
  346. const BlockFilterSet *BlockFilter) {
  347. // Walk all the blocks in this chain, marking their successors as having
  348. // a predecessor placed.
  349. for (MachineBasicBlock *MBB : Chain) {
  350. // Add any successors for which this is the only un-placed in-loop
  351. // predecessor to the worklist as a viable candidate for CFG-neutral
  352. // placement. No subsequent placement of this block will violate the CFG
  353. // shape, so we get to use heuristics to choose a favorable placement.
  354. for (MachineBasicBlock *Succ : MBB->successors()) {
  355. if (BlockFilter && !BlockFilter->count(Succ))
  356. continue;
  357. BlockChain &SuccChain = *BlockToChain[Succ];
  358. // Disregard edges within a fixed chain, or edges to the loop header.
  359. if (&Chain == &SuccChain || Succ == LoopHeaderBB)
  360. continue;
  361. // This is a cross-chain edge that is within the loop, so decrement the
  362. // loop predecessor count of the destination chain.
  363. if (SuccChain.UnscheduledPredecessors == 0 ||
  364. --SuccChain.UnscheduledPredecessors > 0)
  365. continue;
  366. auto *MBB = *SuccChain.begin();
  367. if (MBB->isEHPad())
  368. EHPadWorkList.push_back(MBB);
  369. else
  370. BlockWorkList.push_back(MBB);
  371. }
  372. }
  373. }
  374. /// This helper function collects the set of successors of block
  375. /// \p BB that are allowed to be its layout successors, and return
  376. /// the total branch probability of edges from \p BB to those
  377. /// blocks.
  378. BranchProbability MachineBlockPlacement::collectViableSuccessors(
  379. MachineBasicBlock *BB, BlockChain &Chain, const BlockFilterSet *BlockFilter,
  380. SmallVector<MachineBasicBlock *, 4> &Successors) {
  381. // Adjust edge probabilities by excluding edges pointing to blocks that is
  382. // either not in BlockFilter or is already in the current chain. Consider the
  383. // following CFG:
  384. //
  385. // --->A
  386. // | / \
  387. // | B C
  388. // | \ / \
  389. // ----D E
  390. //
  391. // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after
  392. // A->C is chosen as a fall-through, D won't be selected as a successor of C
  393. // due to CFG constraint (the probability of C->D is not greater than
  394. // HotProb to break top-order). If we exclude E that is not in BlockFilter
  395. // when calculating the probability of C->D, D will be selected and we
  396. // will get A C D B as the layout of this loop.
  397. auto AdjustedSumProb = BranchProbability::getOne();
  398. for (MachineBasicBlock *Succ : BB->successors()) {
  399. bool SkipSucc = false;
  400. if (Succ->isEHPad() || (BlockFilter && !BlockFilter->count(Succ))) {
  401. SkipSucc = true;
  402. } else {
  403. BlockChain *SuccChain = BlockToChain[Succ];
  404. if (SuccChain == &Chain) {
  405. SkipSucc = true;
  406. } else if (Succ != *SuccChain->begin()) {
  407. DEBUG(dbgs() << " " << getBlockName(Succ) << " -> Mid chain!\n");
  408. continue;
  409. }
  410. }
  411. if (SkipSucc)
  412. AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ);
  413. else
  414. Successors.push_back(Succ);
  415. }
  416. return AdjustedSumProb;
  417. }
  418. /// The helper function returns the branch probability that is adjusted
  419. /// or normalized over the new total \p AdjustedSumProb.
  420. static BranchProbability
  421. getAdjustedProbability(BranchProbability OrigProb,
  422. BranchProbability AdjustedSumProb) {
  423. BranchProbability SuccProb;
  424. uint32_t SuccProbN = OrigProb.getNumerator();
  425. uint32_t SuccProbD = AdjustedSumProb.getNumerator();
  426. if (SuccProbN >= SuccProbD)
  427. SuccProb = BranchProbability::getOne();
  428. else
  429. SuccProb = BranchProbability(SuccProbN, SuccProbD);
  430. return SuccProb;
  431. }
  432. /// When the option OutlineOptionalBranches is on, this method
  433. /// checks if the fallthrough candidate block \p Succ (of block
  434. /// \p BB) also has other unscheduled predecessor blocks which
  435. /// are also successors of \p BB (forming triangular shape CFG).
  436. /// If none of such predecessors are small, it returns true.
  437. /// The caller can choose to select \p Succ as the layout successors
  438. /// so that \p Succ's predecessors (optional branches) can be
  439. /// outlined.
  440. /// FIXME: fold this with more general layout cost analysis.
  441. bool MachineBlockPlacement::shouldPredBlockBeOutlined(
  442. MachineBasicBlock *BB, MachineBasicBlock *Succ, BlockChain &Chain,
  443. const BlockFilterSet *BlockFilter, BranchProbability SuccProb,
  444. BranchProbability HotProb) {
  445. if (!OutlineOptionalBranches)
  446. return false;
  447. // If we outline optional branches, look whether Succ is unavoidable, i.e.
  448. // dominates all terminators of the MachineFunction. If it does, other
  449. // successors must be optional. Don't do this for cold branches.
  450. if (SuccProb > HotProb.getCompl() && UnavoidableBlocks.count(Succ) > 0) {
  451. for (MachineBasicBlock *Pred : Succ->predecessors()) {
  452. // Check whether there is an unplaced optional branch.
  453. if (Pred == Succ || (BlockFilter && !BlockFilter->count(Pred)) ||
  454. BlockToChain[Pred] == &Chain)
  455. continue;
  456. // Check whether the optional branch has exactly one BB.
  457. if (Pred->pred_size() > 1 || *Pred->pred_begin() != BB)
  458. continue;
  459. // Check whether the optional branch is small.
  460. if (Pred->size() < OutlineOptionalThreshold)
  461. return false;
  462. }
  463. return true;
  464. } else
  465. return false;
  466. }
  467. // When profile is not present, return the StaticLikelyProb.
  468. // When profile is available, we need to handle the triangle-shape CFG.
  469. static BranchProbability getLayoutSuccessorProbThreshold(
  470. MachineBasicBlock *BB) {
  471. if (!BB->getParent()->getFunction()->getEntryCount())
  472. return BranchProbability(StaticLikelyProb, 100);
  473. if (BB->succ_size() == 2) {
  474. const MachineBasicBlock *Succ1 = *BB->succ_begin();
  475. const MachineBasicBlock *Succ2 = *(BB->succ_begin() + 1);
  476. if (Succ1->isSuccessor(Succ2) || Succ2->isSuccessor(Succ1)) {
  477. /* See case 1 below for the cost analysis. For BB->Succ to
  478. * be taken with smaller cost, the following needs to hold:
  479. * Prob(BB->Succ) > 2* Prob(BB->Pred)
  480. * So the threshold T
  481. * T = 2 * (1-Prob(BB->Pred). Since T + Prob(BB->Pred) == 1,
  482. * We have T + T/2 = 1, i.e. T = 2/3. Also adding user specified
  483. * branch bias, we have
  484. * T = (2/3)*(ProfileLikelyProb/50)
  485. * = (2*ProfileLikelyProb)/150)
  486. */
  487. return BranchProbability(2 * ProfileLikelyProb, 150);
  488. }
  489. }
  490. return BranchProbability(ProfileLikelyProb, 100);
  491. }
  492. /// Checks to see if the layout candidate block \p Succ has a better layout
  493. /// predecessor than \c BB. If yes, returns true.
  494. bool MachineBlockPlacement::hasBetterLayoutPredecessor(
  495. MachineBasicBlock *BB, MachineBasicBlock *Succ, BlockChain &SuccChain,
  496. BranchProbability SuccProb, BranchProbability RealSuccProb,
  497. BlockChain &Chain, const BlockFilterSet *BlockFilter) {
  498. // There isn't a better layout when there are no unscheduled predecessors.
  499. if (SuccChain.UnscheduledPredecessors == 0)
  500. return false;
  501. // There are two basic scenarios here:
  502. // -------------------------------------
  503. // Case 1: triangular shape CFG (if-then):
  504. // BB
  505. // | \
  506. // | \
  507. // | Pred
  508. // | /
  509. // Succ
  510. // In this case, we are evaluating whether to select edge -> Succ, e.g.
  511. // set Succ as the layout successor of BB. Picking Succ as BB's
  512. // successor breaks the CFG constraints (FIXME: define these constraints).
  513. // With this layout, Pred BB
  514. // is forced to be outlined, so the overall cost will be cost of the
  515. // branch taken from BB to Pred, plus the cost of back taken branch
  516. // from Pred to Succ, as well as the additional cost associated
  517. // with the needed unconditional jump instruction from Pred To Succ.
  518. // The cost of the topological order layout is the taken branch cost
  519. // from BB to Succ, so to make BB->Succ a viable candidate, the following
  520. // must hold:
  521. // 2 * freq(BB->Pred) * taken_branch_cost + unconditional_jump_cost
  522. // < freq(BB->Succ) * taken_branch_cost.
  523. // Ignoring unconditional jump cost, we get
  524. // freq(BB->Succ) > 2 * freq(BB->Pred), i.e.,
  525. // prob(BB->Succ) > 2 * prob(BB->Pred)
  526. //
  527. // When real profile data is available, we can precisely compute the
  528. // probability threshold that is needed for edge BB->Succ to be considered.
  529. // Without profile data, the heuristic requires the branch bias to be
  530. // a lot larger to make sure the signal is very strong (e.g. 80% default).
  531. // -----------------------------------------------------------------
  532. // Case 2: diamond like CFG (if-then-else):
  533. // S
  534. // / \
  535. // | \
  536. // BB Pred
  537. // \ /
  538. // Succ
  539. // ..
  540. //
  541. // The current block is BB and edge BB->Succ is now being evaluated.
  542. // Note that edge S->BB was previously already selected because
  543. // prob(S->BB) > prob(S->Pred).
  544. // At this point, 2 blocks can be placed after BB: Pred or Succ. If we
  545. // choose Pred, we will have a topological ordering as shown on the left
  546. // in the picture below. If we choose Succ, we have the solution as shown
  547. // on the right:
  548. //
  549. // topo-order:
  550. //
  551. // S----- ---S
  552. // | | | |
  553. // ---BB | | BB
  554. // | | | |
  555. // | pred-- | Succ--
  556. // | | | |
  557. // ---succ ---pred--
  558. //
  559. // cost = freq(S->Pred) + freq(BB->Succ) cost = 2 * freq (S->Pred)
  560. // = freq(S->Pred) + freq(S->BB)
  561. //
  562. // If we have profile data (i.e, branch probabilities can be trusted), the
  563. // cost (number of taken branches) with layout S->BB->Succ->Pred is 2 *
  564. // freq(S->Pred) while the cost of topo order is freq(S->Pred) + freq(S->BB).
  565. // We know Prob(S->BB) > Prob(S->Pred), so freq(S->BB) > freq(S->Pred), which
  566. // means the cost of topological order is greater.
  567. // When profile data is not available, however, we need to be more
  568. // conservative. If the branch prediction is wrong, breaking the topo-order
  569. // will actually yield a layout with large cost. For this reason, we need
  570. // strong biased branch at block S with Prob(S->BB) in order to select
  571. // BB->Succ. This is equivalent to looking the CFG backward with backward
  572. // edge: Prob(Succ->BB) needs to >= HotProb in order to be selected (without
  573. // profile data).
  574. // --------------------------------------------------------------------------
  575. // Case 3: forked diamond
  576. // S
  577. // / \
  578. // / \
  579. // BB Pred
  580. // | \ / |
  581. // | \ / |
  582. // | X |
  583. // | / \ |
  584. // | / \ |
  585. // S1 S2
  586. //
  587. // The current block is BB and edge BB->S1 is now being evaluated.
  588. // As above S->BB was already selected because
  589. // prob(S->BB) > prob(S->Pred). Assume that prob(BB->S1) >= prob(BB->S2).
  590. //
  591. // topo-order:
  592. //
  593. // S-------| ---S
  594. // | | | |
  595. // ---BB | | BB
  596. // | | | |
  597. // | Pred----| | S1----
  598. // | | | |
  599. // --(S1 or S2) ---Pred--
  600. //
  601. // topo-cost = freq(S->Pred) + freq(BB->S1) + freq(BB->S2)
  602. // + min(freq(Pred->S1), freq(Pred->S2))
  603. // Non-topo-order cost:
  604. // In the worst case, S2 will not get laid out after Pred.
  605. // non-topo-cost = 2 * freq(S->Pred) + freq(BB->S2).
  606. // To be conservative, we can assume that min(freq(Pred->S1), freq(Pred->S2))
  607. // is 0. Then the non topo layout is better when
  608. // freq(S->Pred) < freq(BB->S1).
  609. // This is exactly what is checked below.
  610. // Note there are other shapes that apply (Pred may not be a single block,
  611. // but they all fit this general pattern.)
  612. BranchProbability HotProb = getLayoutSuccessorProbThreshold(BB);
  613. // Make sure that a hot successor doesn't have a globally more
  614. // important predecessor.
  615. BlockFrequency CandidateEdgeFreq = MBFI->getBlockFreq(BB) * RealSuccProb;
  616. bool BadCFGConflict = false;
  617. for (MachineBasicBlock *Pred : Succ->predecessors()) {
  618. if (Pred == Succ || BlockToChain[Pred] == &SuccChain ||
  619. (BlockFilter && !BlockFilter->count(Pred)) ||
  620. BlockToChain[Pred] == &Chain)
  621. continue;
  622. // Do backward checking.
  623. // For all cases above, we need a backward checking to filter out edges that
  624. // are not 'strongly' biased. With profile data available, the check is
  625. // mostly redundant for case 2 (when threshold prob is set at 50%) unless S
  626. // has more than two successors.
  627. // BB Pred
  628. // \ /
  629. // Succ
  630. // We select edge BB->Succ if
  631. // freq(BB->Succ) > freq(Succ) * HotProb
  632. // i.e. freq(BB->Succ) > freq(BB->Succ) * HotProb + freq(Pred->Succ) *
  633. // HotProb
  634. // i.e. freq((BB->Succ) * (1 - HotProb) > freq(Pred->Succ) * HotProb
  635. // Case 1 is covered too, because the first equation reduces to:
  636. // prob(BB->Succ) > HotProb. (freq(Succ) = freq(BB) for a triangle)
  637. BlockFrequency PredEdgeFreq =
  638. MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
  639. if (PredEdgeFreq * HotProb >= CandidateEdgeFreq * HotProb.getCompl()) {
  640. BadCFGConflict = true;
  641. break;
  642. }
  643. }
  644. if (BadCFGConflict) {
  645. DEBUG(dbgs() << " Not a candidate: " << getBlockName(Succ) << " -> " << SuccProb
  646. << " (prob) (non-cold CFG conflict)\n");
  647. return true;
  648. }
  649. return false;
  650. }
  651. /// \brief Select the best successor for a block.
  652. ///
  653. /// This looks across all successors of a particular block and attempts to
  654. /// select the "best" one to be the layout successor. It only considers direct
  655. /// successors which also pass the block filter. It will attempt to avoid
  656. /// breaking CFG structure, but cave and break such structures in the case of
  657. /// very hot successor edges.
  658. ///
  659. /// \returns The best successor block found, or null if none are viable.
  660. MachineBasicBlock *
  661. MachineBlockPlacement::selectBestSuccessor(MachineBasicBlock *BB,
  662. BlockChain &Chain,
  663. const BlockFilterSet *BlockFilter) {
  664. const BranchProbability HotProb(StaticLikelyProb, 100);
  665. MachineBasicBlock *BestSucc = nullptr;
  666. auto BestProb = BranchProbability::getZero();
  667. SmallVector<MachineBasicBlock *, 4> Successors;
  668. auto AdjustedSumProb =
  669. collectViableSuccessors(BB, Chain, BlockFilter, Successors);
  670. DEBUG(dbgs() << "Selecting best successor for: " << getBlockName(BB) << "\n");
  671. for (MachineBasicBlock *Succ : Successors) {
  672. auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ);
  673. BranchProbability SuccProb =
  674. getAdjustedProbability(RealSuccProb, AdjustedSumProb);
  675. // This heuristic is off by default.
  676. if (shouldPredBlockBeOutlined(BB, Succ, Chain, BlockFilter, SuccProb,
  677. HotProb))
  678. return Succ;
  679. BlockChain &SuccChain = *BlockToChain[Succ];
  680. // Skip the edge \c BB->Succ if block \c Succ has a better layout
  681. // predecessor that yields lower global cost.
  682. if (hasBetterLayoutPredecessor(BB, Succ, SuccChain, SuccProb, RealSuccProb,
  683. Chain, BlockFilter))
  684. continue;
  685. DEBUG(
  686. dbgs() << " Candidate: " << getBlockName(Succ) << ", probability: "
  687. << SuccProb
  688. << (SuccChain.UnscheduledPredecessors != 0 ? " (CFG break)" : "")
  689. << "\n");
  690. if (BestSucc && BestProb >= SuccProb) {
  691. DEBUG(dbgs() << " Not the best candidate, continuing\n");
  692. continue;
  693. }
  694. DEBUG(dbgs() << " Setting it as best candidate\n");
  695. BestSucc = Succ;
  696. BestProb = SuccProb;
  697. }
  698. if (BestSucc)
  699. DEBUG(dbgs() << " Selected: " << getBlockName(BestSucc) << "\n");
  700. return BestSucc;
  701. }
  702. /// \brief Select the best block from a worklist.
  703. ///
  704. /// This looks through the provided worklist as a list of candidate basic
  705. /// blocks and select the most profitable one to place. The definition of
  706. /// profitable only really makes sense in the context of a loop. This returns
  707. /// the most frequently visited block in the worklist, which in the case of
  708. /// a loop, is the one most desirable to be physically close to the rest of the
  709. /// loop body in order to improve i-cache behavior.
  710. ///
  711. /// \returns The best block found, or null if none are viable.
  712. MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
  713. BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList) {
  714. // Once we need to walk the worklist looking for a candidate, cleanup the
  715. // worklist of already placed entries.
  716. // FIXME: If this shows up on profiles, it could be folded (at the cost of
  717. // some code complexity) into the loop below.
  718. WorkList.erase(remove_if(WorkList,
  719. [&](MachineBasicBlock *BB) {
  720. return BlockToChain.lookup(BB) == &Chain;
  721. }),
  722. WorkList.end());
  723. if (WorkList.empty())
  724. return nullptr;
  725. bool IsEHPad = WorkList[0]->isEHPad();
  726. MachineBasicBlock *BestBlock = nullptr;
  727. BlockFrequency BestFreq;
  728. for (MachineBasicBlock *MBB : WorkList) {
  729. assert(MBB->isEHPad() == IsEHPad);
  730. BlockChain &SuccChain = *BlockToChain[MBB];
  731. if (&SuccChain == &Chain)
  732. continue;
  733. assert(SuccChain.UnscheduledPredecessors == 0 && "Found CFG-violating block");
  734. BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
  735. DEBUG(dbgs() << " " << getBlockName(MBB) << " -> ";
  736. MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
  737. // For ehpad, we layout the least probable first as to avoid jumping back
  738. // from least probable landingpads to more probable ones.
  739. //
  740. // FIXME: Using probability is probably (!) not the best way to achieve
  741. // this. We should probably have a more principled approach to layout
  742. // cleanup code.
  743. //
  744. // The goal is to get:
  745. //
  746. // +--------------------------+
  747. // | V
  748. // InnerLp -> InnerCleanup OuterLp -> OuterCleanup -> Resume
  749. //
  750. // Rather than:
  751. //
  752. // +-------------------------------------+
  753. // V |
  754. // OuterLp -> OuterCleanup -> Resume InnerLp -> InnerCleanup
  755. if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq)))
  756. continue;
  757. BestBlock = MBB;
  758. BestFreq = CandidateFreq;
  759. }
  760. return BestBlock;
  761. }
  762. /// \brief Retrieve the first unplaced basic block.
  763. ///
  764. /// This routine is called when we are unable to use the CFG to walk through
  765. /// all of the basic blocks and form a chain due to unnatural loops in the CFG.
  766. /// We walk through the function's blocks in order, starting from the
  767. /// LastUnplacedBlockIt. We update this iterator on each call to avoid
  768. /// re-scanning the entire sequence on repeated calls to this routine.
  769. MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
  770. const BlockChain &PlacedChain,
  771. MachineFunction::iterator &PrevUnplacedBlockIt,
  772. const BlockFilterSet *BlockFilter) {
  773. for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F->end(); I != E;
  774. ++I) {
  775. if (BlockFilter && !BlockFilter->count(&*I))
  776. continue;
  777. if (BlockToChain[&*I] != &PlacedChain) {
  778. PrevUnplacedBlockIt = I;
  779. // Now select the head of the chain to which the unplaced block belongs
  780. // as the block to place. This will force the entire chain to be placed,
  781. // and satisfies the requirements of merging chains.
  782. return *BlockToChain[&*I]->begin();
  783. }
  784. }
  785. return nullptr;
  786. }
  787. void MachineBlockPlacement::fillWorkLists(
  788. MachineBasicBlock *MBB,
  789. SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
  790. const BlockFilterSet *BlockFilter = nullptr) {
  791. BlockChain &Chain = *BlockToChain[MBB];
  792. if (!UpdatedPreds.insert(&Chain).second)
  793. return;
  794. assert(Chain.UnscheduledPredecessors == 0);
  795. for (MachineBasicBlock *ChainBB : Chain) {
  796. assert(BlockToChain[ChainBB] == &Chain);
  797. for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
  798. if (BlockFilter && !BlockFilter->count(Pred))
  799. continue;
  800. if (BlockToChain[Pred] == &Chain)
  801. continue;
  802. ++Chain.UnscheduledPredecessors;
  803. }
  804. }
  805. if (Chain.UnscheduledPredecessors != 0)
  806. return;
  807. MBB = *Chain.begin();
  808. if (MBB->isEHPad())
  809. EHPadWorkList.push_back(MBB);
  810. else
  811. BlockWorkList.push_back(MBB);
  812. }
  813. void MachineBlockPlacement::buildChain(
  814. MachineBasicBlock *BB, BlockChain &Chain,
  815. const BlockFilterSet *BlockFilter) {
  816. assert(BB && "BB must not be null.\n");
  817. assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match.\n");
  818. MachineFunction::iterator PrevUnplacedBlockIt = F->begin();
  819. MachineBasicBlock *LoopHeaderBB = BB;
  820. markChainSuccessors(Chain, LoopHeaderBB, BlockFilter);
  821. BB = *std::prev(Chain.end());
  822. for (;;) {
  823. assert(BB && "null block found at end of chain in loop.");
  824. assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match in loop.");
  825. assert(*std::prev(Chain.end()) == BB && "BB Not found at end of chain.");
  826. // Look for the best viable successor if there is one to place immediately
  827. // after this block.
  828. MachineBasicBlock *BestSucc = selectBestSuccessor(BB, Chain, BlockFilter);
  829. // If an immediate successor isn't available, look for the best viable
  830. // block among those we've identified as not violating the loop's CFG at
  831. // this point. This won't be a fallthrough, but it will increase locality.
  832. if (!BestSucc)
  833. BestSucc = selectBestCandidateBlock(Chain, BlockWorkList);
  834. if (!BestSucc)
  835. BestSucc = selectBestCandidateBlock(Chain, EHPadWorkList);
  836. if (!BestSucc) {
  837. BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockIt, BlockFilter);
  838. if (!BestSucc)
  839. break;
  840. DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
  841. "layout successor until the CFG reduces\n");
  842. }
  843. // Place this block, updating the datastructures to reflect its placement.
  844. BlockChain &SuccChain = *BlockToChain[BestSucc];
  845. // Zero out UnscheduledPredecessors for the successor we're about to merge in case
  846. // we selected a successor that didn't fit naturally into the CFG.
  847. SuccChain.UnscheduledPredecessors = 0;
  848. DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to "
  849. << getBlockName(BestSucc) << "\n");
  850. markChainSuccessors(SuccChain, LoopHeaderBB, BlockFilter);
  851. Chain.merge(BestSucc, &SuccChain);
  852. BB = *std::prev(Chain.end());
  853. }
  854. DEBUG(dbgs() << "Finished forming chain for header block "
  855. << getBlockName(*Chain.begin()) << "\n");
  856. }
  857. /// \brief Find the best loop top block for layout.
  858. ///
  859. /// Look for a block which is strictly better than the loop header for laying
  860. /// out at the top of the loop. This looks for one and only one pattern:
  861. /// a latch block with no conditional exit. This block will cause a conditional
  862. /// jump around it or will be the bottom of the loop if we lay it out in place,
  863. /// but if it it doesn't end up at the bottom of the loop for any reason,
  864. /// rotation alone won't fix it. Because such a block will always result in an
  865. /// unconditional jump (for the backedge) rotating it in front of the loop
  866. /// header is always profitable.
  867. MachineBasicBlock *
  868. MachineBlockPlacement::findBestLoopTop(MachineLoop &L,
  869. const BlockFilterSet &LoopBlockSet) {
  870. // Placing the latch block before the header may introduce an extra branch
  871. // that skips this block the first time the loop is executed, which we want
  872. // to avoid when optimising for size.
  873. // FIXME: in theory there is a case that does not introduce a new branch,
  874. // i.e. when the layout predecessor does not fallthrough to the loop header.
  875. // In practice this never happens though: there always seems to be a preheader
  876. // that can fallthrough and that is also placed before the header.
  877. if (F->getFunction()->optForSize())
  878. return L.getHeader();
  879. // Check that the header hasn't been fused with a preheader block due to
  880. // crazy branches. If it has, we need to start with the header at the top to
  881. // prevent pulling the preheader into the loop body.
  882. BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
  883. if (!LoopBlockSet.count(*HeaderChain.begin()))
  884. return L.getHeader();
  885. DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(L.getHeader())
  886. << "\n");
  887. BlockFrequency BestPredFreq;
  888. MachineBasicBlock *BestPred = nullptr;
  889. for (MachineBasicBlock *Pred : L.getHeader()->predecessors()) {
  890. if (!LoopBlockSet.count(Pred))
  891. continue;
  892. DEBUG(dbgs() << " header pred: " << getBlockName(Pred) << ", has "
  893. << Pred->succ_size() << " successors, ";
  894. MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
  895. if (Pred->succ_size() > 1)
  896. continue;
  897. BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
  898. if (!BestPred || PredFreq > BestPredFreq ||
  899. (!(PredFreq < BestPredFreq) &&
  900. Pred->isLayoutSuccessor(L.getHeader()))) {
  901. BestPred = Pred;
  902. BestPredFreq = PredFreq;
  903. }
  904. }
  905. // If no direct predecessor is fine, just use the loop header.
  906. if (!BestPred) {
  907. DEBUG(dbgs() << " final top unchanged\n");
  908. return L.getHeader();
  909. }
  910. // Walk backwards through any straight line of predecessors.
  911. while (BestPred->pred_size() == 1 &&
  912. (*BestPred->pred_begin())->succ_size() == 1 &&
  913. *BestPred->pred_begin() != L.getHeader())
  914. BestPred = *BestPred->pred_begin();
  915. DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n");
  916. return BestPred;
  917. }
  918. /// \brief Find the best loop exiting block for layout.
  919. ///
  920. /// This routine implements the logic to analyze the loop looking for the best
  921. /// block to layout at the top of the loop. Typically this is done to maximize
  922. /// fallthrough opportunities.
  923. MachineBasicBlock *
  924. MachineBlockPlacement::findBestLoopExit(MachineLoop &L,
  925. const BlockFilterSet &LoopBlockSet) {
  926. // We don't want to layout the loop linearly in all cases. If the loop header
  927. // is just a normal basic block in the loop, we want to look for what block
  928. // within the loop is the best one to layout at the top. However, if the loop
  929. // header has be pre-merged into a chain due to predecessors not having
  930. // analyzable branches, *and* the predecessor it is merged with is *not* part
  931. // of the loop, rotating the header into the middle of the loop will create
  932. // a non-contiguous range of blocks which is Very Bad. So start with the
  933. // header and only rotate if safe.
  934. BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
  935. if (!LoopBlockSet.count(*HeaderChain.begin()))
  936. return nullptr;
  937. BlockFrequency BestExitEdgeFreq;
  938. unsigned BestExitLoopDepth = 0;
  939. MachineBasicBlock *ExitingBB = nullptr;
  940. // If there are exits to outer loops, loop rotation can severely limit
  941. // fallthrough opportunities unless it selects such an exit. Keep a set of
  942. // blocks where rotating to exit with that block will reach an outer loop.
  943. SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
  944. DEBUG(dbgs() << "Finding best loop exit for: " << getBlockName(L.getHeader())
  945. << "\n");
  946. for (MachineBasicBlock *MBB : L.getBlocks()) {
  947. BlockChain &Chain = *BlockToChain[MBB];
  948. // Ensure that this block is at the end of a chain; otherwise it could be
  949. // mid-way through an inner loop or a successor of an unanalyzable branch.
  950. if (MBB != *std::prev(Chain.end()))
  951. continue;
  952. // Now walk the successors. We need to establish whether this has a viable
  953. // exiting successor and whether it has a viable non-exiting successor.
  954. // We store the old exiting state and restore it if a viable looping
  955. // successor isn't found.
  956. MachineBasicBlock *OldExitingBB = ExitingBB;
  957. BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
  958. bool HasLoopingSucc = false;
  959. for (MachineBasicBlock *Succ : MBB->successors()) {
  960. if (Succ->isEHPad())
  961. continue;
  962. if (Succ == MBB)
  963. continue;
  964. BlockChain &SuccChain = *BlockToChain[Succ];
  965. // Don't split chains, either this chain or the successor's chain.
  966. if (&Chain == &SuccChain) {
  967. DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
  968. << getBlockName(Succ) << " (chain conflict)\n");
  969. continue;
  970. }
  971. auto SuccProb = MBPI->getEdgeProbability(MBB, Succ);
  972. if (LoopBlockSet.count(Succ)) {
  973. DEBUG(dbgs() << " looping: " << getBlockName(MBB) << " -> "
  974. << getBlockName(Succ) << " (" << SuccProb << ")\n");
  975. HasLoopingSucc = true;
  976. continue;
  977. }
  978. unsigned SuccLoopDepth = 0;
  979. if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
  980. SuccLoopDepth = ExitLoop->getLoopDepth();
  981. if (ExitLoop->contains(&L))
  982. BlocksExitingToOuterLoop.insert(MBB);
  983. }
  984. BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
  985. DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
  986. << getBlockName(Succ) << " [L:" << SuccLoopDepth << "] (";
  987. MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
  988. // Note that we bias this toward an existing layout successor to retain
  989. // incoming order in the absence of better information. The exit must have
  990. // a frequency higher than the current exit before we consider breaking
  991. // the layout.
  992. BranchProbability Bias(100 - ExitBlockBias, 100);
  993. if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
  994. ExitEdgeFreq > BestExitEdgeFreq ||
  995. (MBB->isLayoutSuccessor(Succ) &&
  996. !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
  997. BestExitEdgeFreq = ExitEdgeFreq;
  998. ExitingBB = MBB;
  999. }
  1000. }
  1001. if (!HasLoopingSucc) {
  1002. // Restore the old exiting state, no viable looping successor was found.
  1003. ExitingBB = OldExitingBB;
  1004. BestExitEdgeFreq = OldBestExitEdgeFreq;
  1005. }
  1006. }
  1007. // Without a candidate exiting block or with only a single block in the
  1008. // loop, just use the loop header to layout the loop.
  1009. if (!ExitingBB) {
  1010. DEBUG(dbgs() << " No other candidate exit blocks, using loop header\n");
  1011. return nullptr;
  1012. }
  1013. if (L.getNumBlocks() == 1) {
  1014. DEBUG(dbgs() << " Loop has 1 block, using loop header as exit\n");
  1015. return nullptr;
  1016. }
  1017. // Also, if we have exit blocks which lead to outer loops but didn't select
  1018. // one of them as the exiting block we are rotating toward, disable loop
  1019. // rotation altogether.
  1020. if (!BlocksExitingToOuterLoop.empty() &&
  1021. !BlocksExitingToOuterLoop.count(ExitingBB))
  1022. return nullptr;
  1023. DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB) << "\n");
  1024. return ExitingBB;
  1025. }
  1026. /// \brief Attempt to rotate an exiting block to the bottom of the loop.
  1027. ///
  1028. /// Once we have built a chain, try to rotate it to line up the hot exit block
  1029. /// with fallthrough out of the loop if doing so doesn't introduce unnecessary
  1030. /// branches. For example, if the loop has fallthrough into its header and out
  1031. /// of its bottom already, don't rotate it.
  1032. void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
  1033. MachineBasicBlock *ExitingBB,
  1034. const BlockFilterSet &LoopBlockSet) {
  1035. if (!ExitingBB)
  1036. return;
  1037. MachineBasicBlock *Top = *LoopChain.begin();
  1038. bool ViableTopFallthrough = false;
  1039. for (MachineBasicBlock *Pred : Top->predecessors()) {
  1040. BlockChain *PredChain = BlockToChain[Pred];
  1041. if (!LoopBlockSet.count(Pred) &&
  1042. (!PredChain || Pred == *std::prev(PredChain->end()))) {
  1043. ViableTopFallthrough = true;
  1044. break;
  1045. }
  1046. }
  1047. // If the header has viable fallthrough, check whether the current loop
  1048. // bottom is a viable exiting block. If so, bail out as rotating will
  1049. // introduce an unnecessary branch.
  1050. if (ViableTopFallthrough) {
  1051. MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
  1052. for (MachineBasicBlock *Succ : Bottom->successors()) {
  1053. BlockChain *SuccChain = BlockToChain[Succ];
  1054. if (!LoopBlockSet.count(Succ) &&
  1055. (!SuccChain || Succ == *SuccChain->begin()))
  1056. return;
  1057. }
  1058. }
  1059. BlockChain::iterator ExitIt = find(LoopChain, ExitingBB);
  1060. if (ExitIt == LoopChain.end())
  1061. return;
  1062. std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
  1063. }
  1064. /// \brief Attempt to rotate a loop based on profile data to reduce branch cost.
  1065. ///
  1066. /// With profile data, we can determine the cost in terms of missed fall through
  1067. /// opportunities when rotating a loop chain and select the best rotation.
  1068. /// Basically, there are three kinds of cost to consider for each rotation:
  1069. /// 1. The possibly missed fall through edge (if it exists) from BB out of
  1070. /// the loop to the loop header.
  1071. /// 2. The possibly missed fall through edges (if they exist) from the loop
  1072. /// exits to BB out of the loop.
  1073. /// 3. The missed fall through edge (if it exists) from the last BB to the
  1074. /// first BB in the loop chain.
  1075. /// Therefore, the cost for a given rotation is the sum of costs listed above.
  1076. /// We select the best rotation with the smallest cost.
  1077. void MachineBlockPlacement::rotateLoopWithProfile(
  1078. BlockChain &LoopChain, MachineLoop &L, const BlockFilterSet &LoopBlockSet) {
  1079. auto HeaderBB = L.getHeader();
  1080. auto HeaderIter = find(LoopChain, HeaderBB);
  1081. auto RotationPos = LoopChain.end();
  1082. BlockFrequency SmallestRotationCost = BlockFrequency::getMaxFrequency();
  1083. // A utility lambda that scales up a block frequency by dividing it by a
  1084. // branch probability which is the reciprocal of the scale.
  1085. auto ScaleBlockFrequency = [](BlockFrequency Freq,
  1086. unsigned Scale) -> BlockFrequency {
  1087. if (Scale == 0)
  1088. return 0;
  1089. // Use operator / between BlockFrequency and BranchProbability to implement
  1090. // saturating multiplication.
  1091. return Freq / BranchProbability(1, Scale);
  1092. };
  1093. // Compute the cost of the missed fall-through edge to the loop header if the
  1094. // chain head is not the loop header. As we only consider natural loops with
  1095. // single header, this computation can be done only once.
  1096. BlockFrequency HeaderFallThroughCost(0);
  1097. for (auto *Pred : HeaderBB->predecessors()) {
  1098. BlockChain *PredChain = BlockToChain[Pred];
  1099. if (!LoopBlockSet.count(Pred) &&
  1100. (!PredChain || Pred == *std::prev(PredChain->end()))) {
  1101. auto EdgeFreq =
  1102. MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, HeaderBB);
  1103. auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost);
  1104. // If the predecessor has only an unconditional jump to the header, we
  1105. // need to consider the cost of this jump.
  1106. if (Pred->succ_size() == 1)
  1107. FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost);
  1108. HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost);
  1109. }
  1110. }
  1111. // Here we collect all exit blocks in the loop, and for each exit we find out
  1112. // its hottest exit edge. For each loop rotation, we define the loop exit cost
  1113. // as the sum of frequencies of exit edges we collect here, excluding the exit
  1114. // edge from the tail of the loop chain.
  1115. SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq;
  1116. for (auto BB : LoopChain) {
  1117. auto LargestExitEdgeProb = BranchProbability::getZero();
  1118. for (auto *Succ : BB->successors()) {
  1119. BlockChain *SuccChain = BlockToChain[Succ];
  1120. if (!LoopBlockSet.count(Succ) &&
  1121. (!SuccChain || Succ == *SuccChain->begin())) {
  1122. auto SuccProb = MBPI->getEdgeProbability(BB, Succ);
  1123. LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb);
  1124. }
  1125. }
  1126. if (LargestExitEdgeProb > BranchProbability::getZero()) {
  1127. auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb;
  1128. ExitsWithFreq.emplace_back(BB, ExitFreq);
  1129. }
  1130. }
  1131. // In this loop we iterate every block in the loop chain and calculate the
  1132. // cost assuming the block is the head of the loop chain. When the loop ends,
  1133. // we should have found the best candidate as the loop chain's head.
  1134. for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()),
  1135. EndIter = LoopChain.end();
  1136. Iter != EndIter; Iter++, TailIter++) {
  1137. // TailIter is used to track the tail of the loop chain if the block we are
  1138. // checking (pointed by Iter) is the head of the chain.
  1139. if (TailIter == LoopChain.end())
  1140. TailIter = LoopChain.begin();
  1141. auto TailBB = *TailIter;
  1142. // Calculate the cost by putting this BB to the top.
  1143. BlockFrequency Cost = 0;
  1144. // If the current BB is the loop header, we need to take into account the
  1145. // cost of the missed fall through edge from outside of the loop to the
  1146. // header.
  1147. if (Iter != HeaderIter)
  1148. Cost += HeaderFallThroughCost;
  1149. // Collect the loop exit cost by summing up frequencies of all exit edges
  1150. // except the one from the chain tail.
  1151. for (auto &ExitWithFreq : ExitsWithFreq)
  1152. if (TailBB != ExitWithFreq.first)
  1153. Cost += ExitWithFreq.second;
  1154. // The cost of breaking the once fall-through edge from the tail to the top
  1155. // of the loop chain. Here we need to consider three cases:
  1156. // 1. If the tail node has only one successor, then we will get an
  1157. // additional jmp instruction. So the cost here is (MisfetchCost +
  1158. // JumpInstCost) * tail node frequency.
  1159. // 2. If the tail node has two successors, then we may still get an
  1160. // additional jmp instruction if the layout successor after the loop
  1161. // chain is not its CFG successor. Note that the more frequently executed
  1162. // jmp instruction will be put ahead of the other one. Assume the
  1163. // frequency of those two branches are x and y, where x is the frequency
  1164. // of the edge to the chain head, then the cost will be
  1165. // (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency.
  1166. // 3. If the tail node has more than two successors (this rarely happens),
  1167. // we won't consider any additional cost.
  1168. if (TailBB->isSuccessor(*Iter)) {
  1169. auto TailBBFreq = MBFI->getBlockFreq(TailBB);
  1170. if (TailBB->succ_size() == 1)
  1171. Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(),
  1172. MisfetchCost + JumpInstCost);
  1173. else if (TailBB->succ_size() == 2) {
  1174. auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter);
  1175. auto TailToHeadFreq = TailBBFreq * TailToHeadProb;
  1176. auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2)
  1177. ? TailBBFreq * TailToHeadProb.getCompl()
  1178. : TailToHeadFreq;
  1179. Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) +
  1180. ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost);
  1181. }
  1182. }
  1183. DEBUG(dbgs() << "The cost of loop rotation by making " << getBlockName(*Iter)
  1184. << " to the top: " << Cost.getFrequency() << "\n");
  1185. if (Cost < SmallestRotationCost) {
  1186. SmallestRotationCost = Cost;
  1187. RotationPos = Iter;
  1188. }
  1189. }
  1190. if (RotationPos != LoopChain.end()) {
  1191. DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos)
  1192. << " to the top\n");
  1193. std::rotate(LoopChain.begin(), RotationPos, LoopChain.end());
  1194. }
  1195. }
  1196. /// \brief Collect blocks in the given loop that are to be placed.
  1197. ///
  1198. /// When profile data is available, exclude cold blocks from the returned set;
  1199. /// otherwise, collect all blocks in the loop.
  1200. MachineBlockPlacement::BlockFilterSet
  1201. MachineBlockPlacement::collectLoopBlockSet(MachineLoop &L) {
  1202. BlockFilterSet LoopBlockSet;
  1203. // Filter cold blocks off from LoopBlockSet when profile data is available.
  1204. // Collect the sum of frequencies of incoming edges to the loop header from
  1205. // outside. If we treat the loop as a super block, this is the frequency of
  1206. // the loop. Then for each block in the loop, we calculate the ratio between
  1207. // its frequency and the frequency of the loop block. When it is too small,
  1208. // don't add it to the loop chain. If there are outer loops, then this block
  1209. // will be merged into the first outer loop chain for which this block is not
  1210. // cold anymore. This needs precise profile data and we only do this when
  1211. // profile data is available.
  1212. if (F->getFunction()->getEntryCount()) {
  1213. BlockFrequency LoopFreq(0);
  1214. for (auto LoopPred : L.getHeader()->predecessors())
  1215. if (!L.contains(LoopPred))
  1216. LoopFreq += MBFI->getBlockFreq(LoopPred) *
  1217. MBPI->getEdgeProbability(LoopPred, L.getHeader());
  1218. for (MachineBasicBlock *LoopBB : L.getBlocks()) {
  1219. auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency();
  1220. if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio)
  1221. continue;
  1222. LoopBlockSet.insert(LoopBB);
  1223. }
  1224. } else
  1225. LoopBlockSet.insert(L.block_begin(), L.block_end());
  1226. return LoopBlockSet;
  1227. }
  1228. /// \brief Forms basic block chains from the natural loop structures.
  1229. ///
  1230. /// These chains are designed to preserve the existing *structure* of the code
  1231. /// as much as possible. We can then stitch the chains together in a way which
  1232. /// both preserves the topological structure and minimizes taken conditional
  1233. /// branches.
  1234. void MachineBlockPlacement::buildLoopChains(MachineLoop &L) {
  1235. // First recurse through any nested loops, building chains for those inner
  1236. // loops.
  1237. for (MachineLoop *InnerLoop : L)
  1238. buildLoopChains(*InnerLoop);
  1239. assert(BlockWorkList.empty());
  1240. assert(EHPadWorkList.empty());
  1241. BlockFilterSet LoopBlockSet = collectLoopBlockSet(L);
  1242. // Check if we have profile data for this function. If yes, we will rotate
  1243. // this loop by modeling costs more precisely which requires the profile data
  1244. // for better layout.
  1245. bool RotateLoopWithProfile =
  1246. ForcePreciseRotationCost ||
  1247. (PreciseRotationCost && F->getFunction()->getEntryCount());
  1248. // First check to see if there is an obviously preferable top block for the
  1249. // loop. This will default to the header, but may end up as one of the
  1250. // predecessors to the header if there is one which will result in strictly
  1251. // fewer branches in the loop body.
  1252. // When we use profile data to rotate the loop, this is unnecessary.
  1253. MachineBasicBlock *LoopTop =
  1254. RotateLoopWithProfile ? L.getHeader() : findBestLoopTop(L, LoopBlockSet);
  1255. // If we selected just the header for the loop top, look for a potentially
  1256. // profitable exit block in the event that rotating the loop can eliminate
  1257. // branches by placing an exit edge at the bottom.
  1258. MachineBasicBlock *ExitingBB = nullptr;
  1259. if (!RotateLoopWithProfile && LoopTop == L.getHeader())
  1260. ExitingBB = findBestLoopExit(L, LoopBlockSet);
  1261. BlockChain &LoopChain = *BlockToChain[LoopTop];
  1262. // FIXME: This is a really lame way of walking the chains in the loop: we
  1263. // walk the blocks, and use a set to prevent visiting a particular chain
  1264. // twice.
  1265. SmallPtrSet<BlockChain *, 4> UpdatedPreds;
  1266. assert(LoopChain.UnscheduledPredecessors == 0);
  1267. UpdatedPreds.insert(&LoopChain);
  1268. for (MachineBasicBlock *LoopBB : LoopBlockSet)
  1269. fillWorkLists(LoopBB, UpdatedPreds, &LoopBlockSet);
  1270. buildChain(LoopTop, LoopChain, &LoopBlockSet);
  1271. if (RotateLoopWithProfile)
  1272. rotateLoopWithProfile(LoopChain, L, LoopBlockSet);
  1273. else
  1274. rotateLoop(LoopChain, ExitingBB, LoopBlockSet);
  1275. DEBUG({
  1276. // Crash at the end so we get all of the debugging output first.
  1277. bool BadLoop = false;
  1278. if (LoopChain.UnscheduledPredecessors) {
  1279. BadLoop = true;
  1280. dbgs() << "Loop chain contains a block without its preds placed!\n"
  1281. << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
  1282. << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
  1283. }
  1284. for (MachineBasicBlock *ChainBB : LoopChain) {
  1285. dbgs() << " ... " << getBlockName(ChainBB) << "\n";
  1286. if (!LoopBlockSet.erase(ChainBB)) {
  1287. // We don't mark the loop as bad here because there are real situations
  1288. // where this can occur. For example, with an unanalyzable fallthrough
  1289. // from a loop block to a non-loop block or vice versa.
  1290. dbgs() << "Loop chain contains a block not contained by the loop!\n"
  1291. << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
  1292. << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
  1293. << " Bad block: " << getBlockName(ChainBB) << "\n";
  1294. }
  1295. }
  1296. if (!LoopBlockSet.empty()) {
  1297. BadLoop = true;
  1298. for (MachineBasicBlock *LoopBB : LoopBlockSet)
  1299. dbgs() << "Loop contains blocks never placed into a chain!\n"
  1300. << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
  1301. << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
  1302. << " Bad block: " << getBlockName(LoopBB) << "\n";
  1303. }
  1304. assert(!BadLoop && "Detected problems with the placement of this loop.");
  1305. });
  1306. BlockWorkList.clear();
  1307. EHPadWorkList.clear();
  1308. }
  1309. /// When OutlineOpitonalBranches is on, this method collects BBs that
  1310. /// dominates all terminator blocks of the function \p F.
  1311. void MachineBlockPlacement::collectMustExecuteBBs() {
  1312. if (OutlineOptionalBranches) {
  1313. // Find the nearest common dominator of all of F's terminators.
  1314. MachineBasicBlock *Terminator = nullptr;
  1315. for (MachineBasicBlock &MBB : *F) {
  1316. if (MBB.succ_size() == 0) {
  1317. if (Terminator == nullptr)
  1318. Terminator = &MBB;
  1319. else
  1320. Terminator = MDT->findNearestCommonDominator(Terminator, &MBB);
  1321. }
  1322. }
  1323. // MBBs dominating this common dominator are unavoidable.
  1324. UnavoidableBlocks.clear();
  1325. for (MachineBasicBlock &MBB : *F) {
  1326. if (MDT->dominates(&MBB, Terminator)) {
  1327. UnavoidableBlocks.insert(&MBB);
  1328. }
  1329. }
  1330. }
  1331. }
  1332. void MachineBlockPlacement::buildCFGChains() {
  1333. // Ensure that every BB in the function has an associated chain to simplify
  1334. // the assumptions of the remaining algorithm.
  1335. SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
  1336. for (MachineFunction::iterator FI = F->begin(), FE = F->end(); FI != FE;
  1337. ++FI) {
  1338. MachineBasicBlock *BB = &*FI;
  1339. BlockChain *Chain =
  1340. new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
  1341. // Also, merge any blocks which we cannot reason about and must preserve
  1342. // the exact fallthrough behavior for.
  1343. for (;;) {
  1344. Cond.clear();
  1345. MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
  1346. if (!TII->analyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
  1347. break;
  1348. MachineFunction::iterator NextFI = std::next(FI);
  1349. MachineBasicBlock *NextBB = &*NextFI;
  1350. // Ensure that the layout successor is a viable block, as we know that
  1351. // fallthrough is a possibility.
  1352. assert(NextFI != FE && "Can't fallthrough past the last block.");
  1353. DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
  1354. << getBlockName(BB) << " -> " << getBlockName(NextBB)
  1355. << "\n");
  1356. Chain->merge(NextBB, nullptr);
  1357. FI = NextFI;
  1358. BB = NextBB;
  1359. }
  1360. }
  1361. // Turned on with OutlineOptionalBranches option
  1362. collectMustExecuteBBs();
  1363. // Build any loop-based chains.
  1364. for (MachineLoop *L : *MLI)
  1365. buildLoopChains(*L);
  1366. assert(BlockWorkList.empty());
  1367. assert(EHPadWorkList.empty());
  1368. SmallPtrSet<BlockChain *, 4> UpdatedPreds;
  1369. for (MachineBasicBlock &MBB : *F)
  1370. fillWorkLists(&MBB, UpdatedPreds);
  1371. BlockChain &FunctionChain = *BlockToChain[&F->front()];
  1372. buildChain(&F->front(), FunctionChain);
  1373. #ifndef NDEBUG
  1374. typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType;
  1375. #endif
  1376. DEBUG({
  1377. // Crash at the end so we get all of the debugging output first.
  1378. bool BadFunc = false;
  1379. FunctionBlockSetType FunctionBlockSet;
  1380. for (MachineBasicBlock &MBB : *F)
  1381. FunctionBlockSet.insert(&MBB);
  1382. for (MachineBasicBlock *ChainBB : FunctionChain)
  1383. if (!FunctionBlockSet.erase(ChainBB)) {
  1384. BadFunc = true;
  1385. dbgs() << "Function chain contains a block not in the function!\n"
  1386. << " Bad block: " << getBlockName(ChainBB) << "\n";
  1387. }
  1388. if (!FunctionBlockSet.empty()) {
  1389. BadFunc = true;
  1390. for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
  1391. dbgs() << "Function contains blocks never placed into a chain!\n"
  1392. << " Bad block: " << getBlockName(RemainingBB) << "\n";
  1393. }
  1394. assert(!BadFunc && "Detected problems with the block placement.");
  1395. });
  1396. // Splice the blocks into place.
  1397. MachineFunction::iterator InsertPos = F->begin();
  1398. DEBUG(dbgs() << "[MBP] Function: "<< F->getName() << "\n");
  1399. for (MachineBasicBlock *ChainBB : FunctionChain) {
  1400. DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
  1401. : " ... ")
  1402. << getBlockName(ChainBB) << "\n");
  1403. if (InsertPos != MachineFunction::iterator(ChainBB))
  1404. F->splice(InsertPos, ChainBB);
  1405. else
  1406. ++InsertPos;
  1407. // Update the terminator of the previous block.
  1408. if (ChainBB == *FunctionChain.begin())
  1409. continue;
  1410. MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB));
  1411. // FIXME: It would be awesome of updateTerminator would just return rather
  1412. // than assert when the branch cannot be analyzed in order to remove this
  1413. // boiler plate.
  1414. Cond.clear();
  1415. MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
  1416. // The "PrevBB" is not yet updated to reflect current code layout, so,
  1417. // o. it may fall-through to a block without explicit "goto" instruction
  1418. // before layout, and no longer fall-through it after layout; or
  1419. // o. just opposite.
  1420. //
  1421. // analyzeBranch() may return erroneous value for FBB when these two
  1422. // situations take place. For the first scenario FBB is mistakenly set NULL;
  1423. // for the 2nd scenario, the FBB, which is expected to be NULL, is
  1424. // mistakenly pointing to "*BI".
  1425. // Thus, if the future change needs to use FBB before the layout is set, it
  1426. // has to correct FBB first by using the code similar to the following:
  1427. //
  1428. // if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
  1429. // PrevBB->updateTerminator();
  1430. // Cond.clear();
  1431. // TBB = FBB = nullptr;
  1432. // if (TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) {
  1433. // // FIXME: This should never take place.
  1434. // TBB = FBB = nullptr;
  1435. // }
  1436. // }
  1437. if (!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond))
  1438. PrevBB->updateTerminator();
  1439. }
  1440. // Fixup the last block.
  1441. Cond.clear();
  1442. MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
  1443. if (!TII->analyzeBranch(F->back(), TBB, FBB, Cond))
  1444. F->back().updateTerminator();
  1445. BlockWorkList.clear();
  1446. EHPadWorkList.clear();
  1447. }
  1448. void MachineBlockPlacement::optimizeBranches() {
  1449. BlockChain &FunctionChain = *BlockToChain[&F->front()];
  1450. SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
  1451. // Now that all the basic blocks in the chain have the proper layout,
  1452. // make a final call to AnalyzeBranch with AllowModify set.
  1453. // Indeed, the target may be able to optimize the branches in a way we
  1454. // cannot because all branches may not be analyzable.
  1455. // E.g., the target may be able to remove an unconditional branch to
  1456. // a fallthrough when it occurs after predicated terminators.
  1457. for (MachineBasicBlock *ChainBB : FunctionChain) {
  1458. Cond.clear();
  1459. MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
  1460. if (!TII->analyzeBranch(*ChainBB, TBB, FBB, Cond, /*AllowModify*/ true)) {
  1461. // If PrevBB has a two-way branch, try to re-order the branches
  1462. // such that we branch to the successor with higher probability first.
  1463. if (TBB && !Cond.empty() && FBB &&
  1464. MBPI->getEdgeProbability(ChainBB, FBB) >
  1465. MBPI->getEdgeProbability(ChainBB, TBB) &&
  1466. !TII->ReverseBranchCondition(Cond)) {
  1467. DEBUG(dbgs() << "Reverse order of the two branches: "
  1468. << getBlockName(ChainBB) << "\n");
  1469. DEBUG(dbgs() << " Edge probability: "
  1470. << MBPI->getEdgeProbability(ChainBB, FBB) << " vs "
  1471. << MBPI->getEdgeProbability(ChainBB, TBB) << "\n");
  1472. DebugLoc dl; // FIXME: this is nowhere
  1473. TII->RemoveBranch(*ChainBB);
  1474. TII->insertBranch(*ChainBB, FBB, TBB, Cond, dl);
  1475. ChainBB->updateTerminator();
  1476. }
  1477. }
  1478. }
  1479. }
  1480. void MachineBlockPlacement::alignBlocks() {
  1481. // Walk through the backedges of the function now that we have fully laid out
  1482. // the basic blocks and align the destination of each backedge. We don't rely
  1483. // exclusively on the loop info here so that we can align backedges in
  1484. // unnatural CFGs and backedges that were introduced purely because of the
  1485. // loop rotations done during this layout pass.
  1486. if (F->getFunction()->optForSize())
  1487. return;
  1488. BlockChain &FunctionChain = *BlockToChain[&F->front()];
  1489. if (FunctionChain.begin() == FunctionChain.end())
  1490. return; // Empty chain.
  1491. const BranchProbability ColdProb(1, 5); // 20%
  1492. BlockFrequency EntryFreq = MBFI->getBlockFreq(&F->front());
  1493. BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
  1494. for (MachineBasicBlock *ChainBB : FunctionChain) {
  1495. if (ChainBB == *FunctionChain.begin())
  1496. continue;
  1497. // Don't align non-looping basic blocks. These are unlikely to execute
  1498. // enough times to matter in practice. Note that we'll still handle
  1499. // unnatural CFGs inside of a natural outer loop (the common case) and
  1500. // rotated loops.
  1501. MachineLoop *L = MLI->getLoopFor(ChainBB);
  1502. if (!L)
  1503. continue;
  1504. unsigned Align = TLI->getPrefLoopAlignment(L);
  1505. if (!Align)
  1506. continue; // Don't care about loop alignment.
  1507. // If the block is cold relative to the function entry don't waste space
  1508. // aligning it.
  1509. BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
  1510. if (Freq < WeightedEntryFreq)
  1511. continue;
  1512. // If the block is cold relative to its loop header, don't align it
  1513. // regardless of what edges into the block exist.
  1514. MachineBasicBlock *LoopHeader = L->getHeader();
  1515. BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
  1516. if (Freq < (LoopHeaderFreq * ColdProb))
  1517. continue;
  1518. // Check for the existence of a non-layout predecessor which would benefit
  1519. // from aligning this block.
  1520. MachineBasicBlock *LayoutPred =
  1521. &*std::prev(MachineFunction::iterator(ChainBB));
  1522. // Force alignment if all the predecessors are jumps. We already checked
  1523. // that the block isn't cold above.
  1524. if (!LayoutPred->isSuccessor(ChainBB)) {
  1525. ChainBB->setAlignment(Align);
  1526. continue;
  1527. }
  1528. // Align this block if the layout predecessor's edge into this block is
  1529. // cold relative to the block. When this is true, other predecessors make up
  1530. // all of the hot entries into the block and thus alignment is likely to be
  1531. // important.
  1532. BranchProbability LayoutProb =
  1533. MBPI->getEdgeProbability(LayoutPred, ChainBB);
  1534. BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
  1535. if (LayoutEdgeFreq <= (Freq * ColdProb))
  1536. ChainBB->setAlignment(Align);
  1537. }
  1538. }
  1539. bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &MF) {
  1540. if (skipFunction(*MF.getFunction()))
  1541. return false;
  1542. // Check for single-block functions and skip them.
  1543. if (std::next(MF.begin()) == MF.end())
  1544. return false;
  1545. F = &MF;
  1546. MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
  1547. MBFI = llvm::make_unique<BranchFolder::MBFIWrapper>(
  1548. getAnalysis<MachineBlockFrequencyInfo>());
  1549. MLI = &getAnalysis<MachineLoopInfo>();
  1550. TII = MF.getSubtarget().getInstrInfo();
  1551. TLI = MF.getSubtarget().getTargetLowering();
  1552. MDT = &getAnalysis<MachineDominatorTree>();
  1553. assert(BlockToChain.empty());
  1554. buildCFGChains();
  1555. // Changing the layout can create new tail merging opportunities.
  1556. TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
  1557. // TailMerge can create jump into if branches that make CFG irreducible for
  1558. // HW that requires structured CFG.
  1559. bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&
  1560. PassConfig->getEnableTailMerge() &&
  1561. BranchFoldPlacement;
  1562. // No tail merging opportunities if the block number is less than four.
  1563. if (MF.size() > 3 && EnableTailMerge) {
  1564. // Default to the standard tail-merge-size option.
  1565. unsigned TailMergeSize = 0;
  1566. BranchFolder BF(/*EnableTailMerge=*/true, /*CommonHoist=*/false, *MBFI,
  1567. *MBPI, TailMergeSize);
  1568. if (BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
  1569. getAnalysisIfAvailable<MachineModuleInfo>(), MLI,
  1570. /*AfterBlockPlacement=*/true)) {
  1571. // Redo the layout if tail merging creates/removes/moves blocks.
  1572. BlockToChain.clear();
  1573. ChainAllocator.DestroyAll();
  1574. buildCFGChains();
  1575. }
  1576. }
  1577. optimizeBranches();
  1578. alignBlocks();
  1579. BlockToChain.clear();
  1580. ChainAllocator.DestroyAll();
  1581. if (AlignAllBlock)
  1582. // Align all of the blocks in the function to a specific alignment.
  1583. for (MachineBasicBlock &MBB : MF)
  1584. MBB.setAlignment(AlignAllBlock);
  1585. else if (AlignAllNonFallThruBlocks) {
  1586. // Align all of the blocks that have no fall-through predecessors to a
  1587. // specific alignment.
  1588. for (auto MBI = std::next(MF.begin()), MBE = MF.end(); MBI != MBE; ++MBI) {
  1589. auto LayoutPred = std::prev(MBI);
  1590. if (!LayoutPred->isSuccessor(&*MBI))
  1591. MBI->setAlignment(AlignAllNonFallThruBlocks);
  1592. }
  1593. }
  1594. // We always return true as we have no way to track whether the final order
  1595. // differs from the original order.
  1596. return true;
  1597. }
  1598. namespace {
  1599. /// \brief A pass to compute block placement statistics.
  1600. ///
  1601. /// A separate pass to compute interesting statistics for evaluating block
  1602. /// placement. This is separate from the actual placement pass so that they can
  1603. /// be computed in the absence of any placement transformations or when using
  1604. /// alternative placement strategies.
  1605. class MachineBlockPlacementStats : public MachineFunctionPass {
  1606. /// \brief A handle to the branch probability pass.
  1607. const MachineBranchProbabilityInfo *MBPI;
  1608. /// \brief A handle to the function-wide block frequency pass.
  1609. const MachineBlockFrequencyInfo *MBFI;
  1610. public:
  1611. static char ID; // Pass identification, replacement for typeid
  1612. MachineBlockPlacementStats() : MachineFunctionPass(ID) {
  1613. initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
  1614. }
  1615. bool runOnMachineFunction(MachineFunction &F) override;
  1616. void getAnalysisUsage(AnalysisUsage &AU) const override {
  1617. AU.addRequired<MachineBranchProbabilityInfo>();
  1618. AU.addRequired<MachineBlockFrequencyInfo>();
  1619. AU.setPreservesAll();
  1620. MachineFunctionPass::getAnalysisUsage(AU);
  1621. }
  1622. };
  1623. }
  1624. char MachineBlockPlacementStats::ID = 0;
  1625. char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
  1626. INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
  1627. "Basic Block Placement Stats", false, false)
  1628. INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
  1629. INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
  1630. INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
  1631. "Basic Block Placement Stats", false, false)
  1632. bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
  1633. // Check for single-block functions and skip them.
  1634. if (std::next(F.begin()) == F.end())
  1635. return false;
  1636. MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
  1637. MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
  1638. for (MachineBasicBlock &MBB : F) {
  1639. BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
  1640. Statistic &NumBranches =
  1641. (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
  1642. Statistic &BranchTakenFreq =
  1643. (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
  1644. for (MachineBasicBlock *Succ : MBB.successors()) {
  1645. // Skip if this successor is a fallthrough.
  1646. if (MBB.isLayoutSuccessor(Succ))
  1647. continue;
  1648. BlockFrequency EdgeFreq =
  1649. BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
  1650. ++NumBranches;
  1651. BranchTakenFreq += EdgeFreq.getFrequency();
  1652. }
  1653. }
  1654. return false;
  1655. }