MachineBlockPlacement.cpp 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164
  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. #define DEBUG_TYPE "block-placement2"
  28. #include "llvm/CodeGen/MachineBasicBlock.h"
  29. #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
  30. #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
  31. #include "llvm/CodeGen/MachineFunction.h"
  32. #include "llvm/CodeGen/MachineFunctionPass.h"
  33. #include "llvm/CodeGen/MachineLoopInfo.h"
  34. #include "llvm/CodeGen/MachineModuleInfo.h"
  35. #include "llvm/CodeGen/Passes.h"
  36. #include "llvm/Support/Allocator.h"
  37. #include "llvm/Support/Debug.h"
  38. #include "llvm/ADT/DenseMap.h"
  39. #include "llvm/ADT/SmallPtrSet.h"
  40. #include "llvm/ADT/SmallVector.h"
  41. #include "llvm/ADT/Statistic.h"
  42. #include "llvm/Target/TargetInstrInfo.h"
  43. #include "llvm/Target/TargetLowering.h"
  44. #include <algorithm>
  45. using namespace llvm;
  46. STATISTIC(NumCondBranches, "Number of conditional branches");
  47. STATISTIC(NumUncondBranches, "Number of uncondittional branches");
  48. STATISTIC(CondBranchTakenFreq,
  49. "Potential frequency of taking conditional branches");
  50. STATISTIC(UncondBranchTakenFreq,
  51. "Potential frequency of taking unconditional branches");
  52. namespace {
  53. class BlockChain;
  54. /// \brief Type for our function-wide basic block -> block chain mapping.
  55. typedef DenseMap<MachineBasicBlock *, BlockChain *> BlockToChainMapType;
  56. }
  57. namespace {
  58. /// \brief A chain of blocks which will be laid out contiguously.
  59. ///
  60. /// This is the datastructure representing a chain of consecutive blocks that
  61. /// are profitable to layout together in order to maximize fallthrough
  62. /// probabilities and code locality. We also can use a block chain to represent
  63. /// a sequence of basic blocks which have some external (correctness)
  64. /// requirement for sequential layout.
  65. ///
  66. /// Chains can be built around a single basic block and can be merged to grow
  67. /// them. They participate in a block-to-chain mapping, which is updated
  68. /// automatically as chains are merged together.
  69. class BlockChain {
  70. /// \brief The sequence of blocks belonging to this chain.
  71. ///
  72. /// This is the sequence of blocks for a particular chain. These will be laid
  73. /// out in-order within the function.
  74. SmallVector<MachineBasicBlock *, 4> Blocks;
  75. /// \brief A handle to the function-wide basic block to block chain mapping.
  76. ///
  77. /// This is retained in each block chain to simplify the computation of child
  78. /// block chains for SCC-formation and iteration. We store the edges to child
  79. /// basic blocks, and map them back to their associated chains using this
  80. /// structure.
  81. BlockToChainMapType &BlockToChain;
  82. public:
  83. /// \brief Construct a new BlockChain.
  84. ///
  85. /// This builds a new block chain representing a single basic block in the
  86. /// function. It also registers itself as the chain that block participates
  87. /// in with the BlockToChain mapping.
  88. BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
  89. : Blocks(1, BB), BlockToChain(BlockToChain), LoopPredecessors(0) {
  90. assert(BB && "Cannot create a chain with a null basic block");
  91. BlockToChain[BB] = this;
  92. }
  93. /// \brief Iterator over blocks within the chain.
  94. typedef SmallVectorImpl<MachineBasicBlock *>::iterator iterator;
  95. /// \brief Beginning of blocks within the chain.
  96. iterator begin() { return Blocks.begin(); }
  97. /// \brief End of blocks within the chain.
  98. iterator end() { return Blocks.end(); }
  99. /// \brief Merge a block chain into this one.
  100. ///
  101. /// This routine merges a block chain into this one. It takes care of forming
  102. /// a contiguous sequence of basic blocks, updating the edge list, and
  103. /// updating the block -> chain mapping. It does not free or tear down the
  104. /// old chain, but the old chain's block list is no longer valid.
  105. void merge(MachineBasicBlock *BB, BlockChain *Chain) {
  106. assert(BB);
  107. assert(!Blocks.empty());
  108. // Fast path in case we don't have a chain already.
  109. if (!Chain) {
  110. assert(!BlockToChain[BB]);
  111. Blocks.push_back(BB);
  112. BlockToChain[BB] = this;
  113. return;
  114. }
  115. assert(BB == *Chain->begin());
  116. assert(Chain->begin() != Chain->end());
  117. // Update the incoming blocks to point to this chain, and add them to the
  118. // chain structure.
  119. for (BlockChain::iterator BI = Chain->begin(), BE = Chain->end();
  120. BI != BE; ++BI) {
  121. Blocks.push_back(*BI);
  122. assert(BlockToChain[*BI] == Chain && "Incoming blocks not in chain");
  123. BlockToChain[*BI] = this;
  124. }
  125. }
  126. #ifndef NDEBUG
  127. /// \brief Dump the blocks in this chain.
  128. void dump() LLVM_ATTRIBUTE_USED {
  129. for (iterator I = begin(), E = end(); I != E; ++I)
  130. (*I)->dump();
  131. }
  132. #endif // NDEBUG
  133. /// \brief Count of predecessors within the loop currently being processed.
  134. ///
  135. /// This count is updated at each loop we process to represent the number of
  136. /// in-loop predecessors of this chain.
  137. unsigned LoopPredecessors;
  138. };
  139. }
  140. namespace {
  141. class MachineBlockPlacement : public MachineFunctionPass {
  142. /// \brief A typedef for a block filter set.
  143. typedef SmallPtrSet<MachineBasicBlock *, 16> BlockFilterSet;
  144. /// \brief A handle to the branch probability pass.
  145. const MachineBranchProbabilityInfo *MBPI;
  146. /// \brief A handle to the function-wide block frequency pass.
  147. const MachineBlockFrequencyInfo *MBFI;
  148. /// \brief A handle to the loop info.
  149. const MachineLoopInfo *MLI;
  150. /// \brief A handle to the target's instruction info.
  151. const TargetInstrInfo *TII;
  152. /// \brief A handle to the target's lowering info.
  153. const TargetLowering *TLI;
  154. /// \brief Allocator and owner of BlockChain structures.
  155. ///
  156. /// We build BlockChains lazily while processing the loop structure of
  157. /// a function. To reduce malloc traffic, we allocate them using this
  158. /// slab-like allocator, and destroy them after the pass completes. An
  159. /// important guarantee is that this allocator produces stable pointers to
  160. /// the chains.
  161. SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
  162. /// \brief Function wide BasicBlock to BlockChain mapping.
  163. ///
  164. /// This mapping allows efficiently moving from any given basic block to the
  165. /// BlockChain it participates in, if any. We use it to, among other things,
  166. /// allow implicitly defining edges between chains as the existing edges
  167. /// between basic blocks.
  168. DenseMap<MachineBasicBlock *, BlockChain *> BlockToChain;
  169. void markChainSuccessors(BlockChain &Chain,
  170. MachineBasicBlock *LoopHeaderBB,
  171. SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
  172. const BlockFilterSet *BlockFilter = 0);
  173. MachineBasicBlock *selectBestSuccessor(MachineBasicBlock *BB,
  174. BlockChain &Chain,
  175. const BlockFilterSet *BlockFilter);
  176. MachineBasicBlock *selectBestCandidateBlock(
  177. BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList,
  178. const BlockFilterSet *BlockFilter);
  179. MachineBasicBlock *getFirstUnplacedBlock(
  180. MachineFunction &F,
  181. const BlockChain &PlacedChain,
  182. MachineFunction::iterator &PrevUnplacedBlockIt,
  183. const BlockFilterSet *BlockFilter);
  184. void buildChain(MachineBasicBlock *BB, BlockChain &Chain,
  185. SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
  186. const BlockFilterSet *BlockFilter = 0);
  187. MachineBasicBlock *findBestLoopTop(MachineLoop &L,
  188. const BlockFilterSet &LoopBlockSet);
  189. MachineBasicBlock *findBestLoopExit(MachineFunction &F,
  190. MachineLoop &L,
  191. const BlockFilterSet &LoopBlockSet);
  192. void buildLoopChains(MachineFunction &F, MachineLoop &L);
  193. void rotateLoop(BlockChain &LoopChain, MachineBasicBlock *ExitingBB,
  194. const BlockFilterSet &LoopBlockSet);
  195. void buildCFGChains(MachineFunction &F);
  196. public:
  197. static char ID; // Pass identification, replacement for typeid
  198. MachineBlockPlacement() : MachineFunctionPass(ID) {
  199. initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
  200. }
  201. bool runOnMachineFunction(MachineFunction &F);
  202. void getAnalysisUsage(AnalysisUsage &AU) const {
  203. AU.addRequired<MachineBranchProbabilityInfo>();
  204. AU.addRequired<MachineBlockFrequencyInfo>();
  205. AU.addRequired<MachineLoopInfo>();
  206. MachineFunctionPass::getAnalysisUsage(AU);
  207. }
  208. };
  209. }
  210. char MachineBlockPlacement::ID = 0;
  211. char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
  212. INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement2",
  213. "Branch Probability Basic Block Placement", false, false)
  214. INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
  215. INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
  216. INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
  217. INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement2",
  218. "Branch Probability Basic Block Placement", false, false)
  219. #ifndef NDEBUG
  220. /// \brief Helper to print the name of a MBB.
  221. ///
  222. /// Only used by debug logging.
  223. static std::string getBlockName(MachineBasicBlock *BB) {
  224. std::string Result;
  225. raw_string_ostream OS(Result);
  226. OS << "BB#" << BB->getNumber()
  227. << " (derived from LLVM BB '" << BB->getName() << "')";
  228. OS.flush();
  229. return Result;
  230. }
  231. /// \brief Helper to print the number of a MBB.
  232. ///
  233. /// Only used by debug logging.
  234. static std::string getBlockNum(MachineBasicBlock *BB) {
  235. std::string Result;
  236. raw_string_ostream OS(Result);
  237. OS << "BB#" << BB->getNumber();
  238. OS.flush();
  239. return Result;
  240. }
  241. #endif
  242. /// \brief Mark a chain's successors as having one fewer preds.
  243. ///
  244. /// When a chain is being merged into the "placed" chain, this routine will
  245. /// quickly walk the successors of each block in the chain and mark them as
  246. /// having one fewer active predecessor. It also adds any successors of this
  247. /// chain which reach the zero-predecessor state to the worklist passed in.
  248. void MachineBlockPlacement::markChainSuccessors(
  249. BlockChain &Chain,
  250. MachineBasicBlock *LoopHeaderBB,
  251. SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
  252. const BlockFilterSet *BlockFilter) {
  253. // Walk all the blocks in this chain, marking their successors as having
  254. // a predecessor placed.
  255. for (BlockChain::iterator CBI = Chain.begin(), CBE = Chain.end();
  256. CBI != CBE; ++CBI) {
  257. // Add any successors for which this is the only un-placed in-loop
  258. // predecessor to the worklist as a viable candidate for CFG-neutral
  259. // placement. No subsequent placement of this block will violate the CFG
  260. // shape, so we get to use heuristics to choose a favorable placement.
  261. for (MachineBasicBlock::succ_iterator SI = (*CBI)->succ_begin(),
  262. SE = (*CBI)->succ_end();
  263. SI != SE; ++SI) {
  264. if (BlockFilter && !BlockFilter->count(*SI))
  265. continue;
  266. BlockChain &SuccChain = *BlockToChain[*SI];
  267. // Disregard edges within a fixed chain, or edges to the loop header.
  268. if (&Chain == &SuccChain || *SI == LoopHeaderBB)
  269. continue;
  270. // This is a cross-chain edge that is within the loop, so decrement the
  271. // loop predecessor count of the destination chain.
  272. if (SuccChain.LoopPredecessors > 0 && --SuccChain.LoopPredecessors == 0)
  273. BlockWorkList.push_back(*SuccChain.begin());
  274. }
  275. }
  276. }
  277. /// \brief Select the best successor for a block.
  278. ///
  279. /// This looks across all successors of a particular block and attempts to
  280. /// select the "best" one to be the layout successor. It only considers direct
  281. /// successors which also pass the block filter. It will attempt to avoid
  282. /// breaking CFG structure, but cave and break such structures in the case of
  283. /// very hot successor edges.
  284. ///
  285. /// \returns The best successor block found, or null if none are viable.
  286. MachineBasicBlock *MachineBlockPlacement::selectBestSuccessor(
  287. MachineBasicBlock *BB, BlockChain &Chain,
  288. const BlockFilterSet *BlockFilter) {
  289. const BranchProbability HotProb(4, 5); // 80%
  290. MachineBasicBlock *BestSucc = 0;
  291. // FIXME: Due to the performance of the probability and weight routines in
  292. // the MBPI analysis, we manually compute probabilities using the edge
  293. // weights. This is suboptimal as it means that the somewhat subtle
  294. // definition of edge weight semantics is encoded here as well. We should
  295. // improve the MBPI interface to efficiently support query patterns such as
  296. // this.
  297. uint32_t BestWeight = 0;
  298. uint32_t WeightScale = 0;
  299. uint32_t SumWeight = MBPI->getSumForBlock(BB, WeightScale);
  300. DEBUG(dbgs() << "Attempting merge from: " << getBlockName(BB) << "\n");
  301. for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
  302. SE = BB->succ_end();
  303. SI != SE; ++SI) {
  304. if (BlockFilter && !BlockFilter->count(*SI))
  305. continue;
  306. BlockChain &SuccChain = *BlockToChain[*SI];
  307. if (&SuccChain == &Chain) {
  308. DEBUG(dbgs() << " " << getBlockName(*SI) << " -> Already merged!\n");
  309. continue;
  310. }
  311. if (*SI != *SuccChain.begin()) {
  312. DEBUG(dbgs() << " " << getBlockName(*SI) << " -> Mid chain!\n");
  313. continue;
  314. }
  315. uint32_t SuccWeight = MBPI->getEdgeWeight(BB, *SI);
  316. BranchProbability SuccProb(SuccWeight / WeightScale, SumWeight);
  317. // Only consider successors which are either "hot", or wouldn't violate
  318. // any CFG constraints.
  319. if (SuccChain.LoopPredecessors != 0) {
  320. if (SuccProb < HotProb) {
  321. DEBUG(dbgs() << " " << getBlockName(*SI) << " -> CFG conflict\n");
  322. continue;
  323. }
  324. // Make sure that a hot successor doesn't have a globally more important
  325. // predecessor.
  326. BlockFrequency CandidateEdgeFreq
  327. = MBFI->getBlockFreq(BB) * SuccProb * HotProb.getCompl();
  328. bool BadCFGConflict = false;
  329. for (MachineBasicBlock::pred_iterator PI = (*SI)->pred_begin(),
  330. PE = (*SI)->pred_end();
  331. PI != PE; ++PI) {
  332. if (*PI == *SI || (BlockFilter && !BlockFilter->count(*PI)) ||
  333. BlockToChain[*PI] == &Chain)
  334. continue;
  335. BlockFrequency PredEdgeFreq
  336. = MBFI->getBlockFreq(*PI) * MBPI->getEdgeProbability(*PI, *SI);
  337. if (PredEdgeFreq >= CandidateEdgeFreq) {
  338. BadCFGConflict = true;
  339. break;
  340. }
  341. }
  342. if (BadCFGConflict) {
  343. DEBUG(dbgs() << " " << getBlockName(*SI)
  344. << " -> non-cold CFG conflict\n");
  345. continue;
  346. }
  347. }
  348. DEBUG(dbgs() << " " << getBlockName(*SI) << " -> " << SuccProb
  349. << " (prob)"
  350. << (SuccChain.LoopPredecessors != 0 ? " (CFG break)" : "")
  351. << "\n");
  352. if (BestSucc && BestWeight >= SuccWeight)
  353. continue;
  354. BestSucc = *SI;
  355. BestWeight = SuccWeight;
  356. }
  357. return BestSucc;
  358. }
  359. namespace {
  360. /// \brief Predicate struct to detect blocks already placed.
  361. class IsBlockPlaced {
  362. const BlockChain &PlacedChain;
  363. const BlockToChainMapType &BlockToChain;
  364. public:
  365. IsBlockPlaced(const BlockChain &PlacedChain,
  366. const BlockToChainMapType &BlockToChain)
  367. : PlacedChain(PlacedChain), BlockToChain(BlockToChain) {}
  368. bool operator()(MachineBasicBlock *BB) const {
  369. return BlockToChain.lookup(BB) == &PlacedChain;
  370. }
  371. };
  372. }
  373. /// \brief Select the best block from a worklist.
  374. ///
  375. /// This looks through the provided worklist as a list of candidate basic
  376. /// blocks and select the most profitable one to place. The definition of
  377. /// profitable only really makes sense in the context of a loop. This returns
  378. /// the most frequently visited block in the worklist, which in the case of
  379. /// a loop, is the one most desirable to be physically close to the rest of the
  380. /// loop body in order to improve icache behavior.
  381. ///
  382. /// \returns The best block found, or null if none are viable.
  383. MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
  384. BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList,
  385. const BlockFilterSet *BlockFilter) {
  386. // Once we need to walk the worklist looking for a candidate, cleanup the
  387. // worklist of already placed entries.
  388. // FIXME: If this shows up on profiles, it could be folded (at the cost of
  389. // some code complexity) into the loop below.
  390. WorkList.erase(std::remove_if(WorkList.begin(), WorkList.end(),
  391. IsBlockPlaced(Chain, BlockToChain)),
  392. WorkList.end());
  393. MachineBasicBlock *BestBlock = 0;
  394. BlockFrequency BestFreq;
  395. for (SmallVectorImpl<MachineBasicBlock *>::iterator WBI = WorkList.begin(),
  396. WBE = WorkList.end();
  397. WBI != WBE; ++WBI) {
  398. BlockChain &SuccChain = *BlockToChain[*WBI];
  399. if (&SuccChain == &Chain) {
  400. DEBUG(dbgs() << " " << getBlockName(*WBI)
  401. << " -> Already merged!\n");
  402. continue;
  403. }
  404. assert(SuccChain.LoopPredecessors == 0 && "Found CFG-violating block");
  405. BlockFrequency CandidateFreq = MBFI->getBlockFreq(*WBI);
  406. DEBUG(dbgs() << " " << getBlockName(*WBI) << " -> " << CandidateFreq
  407. << " (freq)\n");
  408. if (BestBlock && BestFreq >= CandidateFreq)
  409. continue;
  410. BestBlock = *WBI;
  411. BestFreq = CandidateFreq;
  412. }
  413. return BestBlock;
  414. }
  415. /// \brief Retrieve the first unplaced basic block.
  416. ///
  417. /// This routine is called when we are unable to use the CFG to walk through
  418. /// all of the basic blocks and form a chain due to unnatural loops in the CFG.
  419. /// We walk through the function's blocks in order, starting from the
  420. /// LastUnplacedBlockIt. We update this iterator on each call to avoid
  421. /// re-scanning the entire sequence on repeated calls to this routine.
  422. MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
  423. MachineFunction &F, const BlockChain &PlacedChain,
  424. MachineFunction::iterator &PrevUnplacedBlockIt,
  425. const BlockFilterSet *BlockFilter) {
  426. for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F.end(); I != E;
  427. ++I) {
  428. if (BlockFilter && !BlockFilter->count(I))
  429. continue;
  430. if (BlockToChain[I] != &PlacedChain) {
  431. PrevUnplacedBlockIt = I;
  432. // Now select the head of the chain to which the unplaced block belongs
  433. // as the block to place. This will force the entire chain to be placed,
  434. // and satisfies the requirements of merging chains.
  435. return *BlockToChain[I]->begin();
  436. }
  437. }
  438. return 0;
  439. }
  440. void MachineBlockPlacement::buildChain(
  441. MachineBasicBlock *BB,
  442. BlockChain &Chain,
  443. SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
  444. const BlockFilterSet *BlockFilter) {
  445. assert(BB);
  446. assert(BlockToChain[BB] == &Chain);
  447. MachineFunction &F = *BB->getParent();
  448. MachineFunction::iterator PrevUnplacedBlockIt = F.begin();
  449. MachineBasicBlock *LoopHeaderBB = BB;
  450. markChainSuccessors(Chain, LoopHeaderBB, BlockWorkList, BlockFilter);
  451. BB = *llvm::prior(Chain.end());
  452. for (;;) {
  453. assert(BB);
  454. assert(BlockToChain[BB] == &Chain);
  455. assert(*llvm::prior(Chain.end()) == BB);
  456. // Look for the best viable successor if there is one to place immediately
  457. // after this block.
  458. MachineBasicBlock *BestSucc = selectBestSuccessor(BB, Chain, BlockFilter);
  459. // If an immediate successor isn't available, look for the best viable
  460. // block among those we've identified as not violating the loop's CFG at
  461. // this point. This won't be a fallthrough, but it will increase locality.
  462. if (!BestSucc)
  463. BestSucc = selectBestCandidateBlock(Chain, BlockWorkList, BlockFilter);
  464. if (!BestSucc) {
  465. BestSucc = getFirstUnplacedBlock(F, Chain, PrevUnplacedBlockIt,
  466. BlockFilter);
  467. if (!BestSucc)
  468. break;
  469. DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
  470. "layout successor until the CFG reduces\n");
  471. }
  472. // Place this block, updating the datastructures to reflect its placement.
  473. BlockChain &SuccChain = *BlockToChain[BestSucc];
  474. // Zero out LoopPredecessors for the successor we're about to merge in case
  475. // we selected a successor that didn't fit naturally into the CFG.
  476. SuccChain.LoopPredecessors = 0;
  477. DEBUG(dbgs() << "Merging from " << getBlockNum(BB)
  478. << " to " << getBlockNum(BestSucc) << "\n");
  479. markChainSuccessors(SuccChain, LoopHeaderBB, BlockWorkList, BlockFilter);
  480. Chain.merge(BestSucc, &SuccChain);
  481. BB = *llvm::prior(Chain.end());
  482. }
  483. DEBUG(dbgs() << "Finished forming chain for header block "
  484. << getBlockNum(*Chain.begin()) << "\n");
  485. }
  486. /// \brief Find the best loop top block for layout.
  487. ///
  488. /// Look for a block which is strictly better than the loop header for laying
  489. /// out at the top of the loop. This looks for one and only one pattern:
  490. /// a latch block with no conditional exit. This block will cause a conditional
  491. /// jump around it or will be the bottom of the loop if we lay it out in place,
  492. /// but if it it doesn't end up at the bottom of the loop for any reason,
  493. /// rotation alone won't fix it. Because such a block will always result in an
  494. /// unconditional jump (for the backedge) rotating it in front of the loop
  495. /// header is always profitable.
  496. MachineBasicBlock *
  497. MachineBlockPlacement::findBestLoopTop(MachineLoop &L,
  498. const BlockFilterSet &LoopBlockSet) {
  499. // Check that the header hasn't been fused with a preheader block due to
  500. // crazy branches. If it has, we need to start with the header at the top to
  501. // prevent pulling the preheader into the loop body.
  502. BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
  503. if (!LoopBlockSet.count(*HeaderChain.begin()))
  504. return L.getHeader();
  505. DEBUG(dbgs() << "Finding best loop top for: "
  506. << getBlockName(L.getHeader()) << "\n");
  507. BlockFrequency BestPredFreq;
  508. MachineBasicBlock *BestPred = 0;
  509. for (MachineBasicBlock::pred_iterator PI = L.getHeader()->pred_begin(),
  510. PE = L.getHeader()->pred_end();
  511. PI != PE; ++PI) {
  512. MachineBasicBlock *Pred = *PI;
  513. if (!LoopBlockSet.count(Pred))
  514. continue;
  515. DEBUG(dbgs() << " header pred: " << getBlockName(Pred) << ", "
  516. << Pred->succ_size() << " successors, "
  517. << MBFI->getBlockFreq(Pred) << " freq\n");
  518. if (Pred->succ_size() > 1)
  519. continue;
  520. BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
  521. if (!BestPred || PredFreq > BestPredFreq ||
  522. (!(PredFreq < BestPredFreq) &&
  523. Pred->isLayoutSuccessor(L.getHeader()))) {
  524. BestPred = Pred;
  525. BestPredFreq = PredFreq;
  526. }
  527. }
  528. // If no direct predecessor is fine, just use the loop header.
  529. if (!BestPred)
  530. return L.getHeader();
  531. // Walk backwards through any straight line of predecessors.
  532. while (BestPred->pred_size() == 1 &&
  533. (*BestPred->pred_begin())->succ_size() == 1 &&
  534. *BestPred->pred_begin() != L.getHeader())
  535. BestPred = *BestPred->pred_begin();
  536. DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n");
  537. return BestPred;
  538. }
  539. /// \brief Find the best loop exiting block for layout.
  540. ///
  541. /// This routine implements the logic to analyze the loop looking for the best
  542. /// block to layout at the top of the loop. Typically this is done to maximize
  543. /// fallthrough opportunities.
  544. MachineBasicBlock *
  545. MachineBlockPlacement::findBestLoopExit(MachineFunction &F,
  546. MachineLoop &L,
  547. const BlockFilterSet &LoopBlockSet) {
  548. // We don't want to layout the loop linearly in all cases. If the loop header
  549. // is just a normal basic block in the loop, we want to look for what block
  550. // within the loop is the best one to layout at the top. However, if the loop
  551. // header has be pre-merged into a chain due to predecessors not having
  552. // analyzable branches, *and* the predecessor it is merged with is *not* part
  553. // of the loop, rotating the header into the middle of the loop will create
  554. // a non-contiguous range of blocks which is Very Bad. So start with the
  555. // header and only rotate if safe.
  556. BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
  557. if (!LoopBlockSet.count(*HeaderChain.begin()))
  558. return 0;
  559. BlockFrequency BestExitEdgeFreq;
  560. unsigned BestExitLoopDepth = 0;
  561. MachineBasicBlock *ExitingBB = 0;
  562. // If there are exits to outer loops, loop rotation can severely limit
  563. // fallthrough opportunites unless it selects such an exit. Keep a set of
  564. // blocks where rotating to exit with that block will reach an outer loop.
  565. SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
  566. DEBUG(dbgs() << "Finding best loop exit for: "
  567. << getBlockName(L.getHeader()) << "\n");
  568. for (MachineLoop::block_iterator I = L.block_begin(),
  569. E = L.block_end();
  570. I != E; ++I) {
  571. BlockChain &Chain = *BlockToChain[*I];
  572. // Ensure that this block is at the end of a chain; otherwise it could be
  573. // mid-way through an inner loop or a successor of an analyzable branch.
  574. if (*I != *llvm::prior(Chain.end()))
  575. continue;
  576. // Now walk the successors. We need to establish whether this has a viable
  577. // exiting successor and whether it has a viable non-exiting successor.
  578. // We store the old exiting state and restore it if a viable looping
  579. // successor isn't found.
  580. MachineBasicBlock *OldExitingBB = ExitingBB;
  581. BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
  582. bool HasLoopingSucc = false;
  583. // FIXME: Due to the performance of the probability and weight routines in
  584. // the MBPI analysis, we use the internal weights and manually compute the
  585. // probabilities to avoid quadratic behavior.
  586. uint32_t WeightScale = 0;
  587. uint32_t SumWeight = MBPI->getSumForBlock(*I, WeightScale);
  588. for (MachineBasicBlock::succ_iterator SI = (*I)->succ_begin(),
  589. SE = (*I)->succ_end();
  590. SI != SE; ++SI) {
  591. if ((*SI)->isLandingPad())
  592. continue;
  593. if (*SI == *I)
  594. continue;
  595. BlockChain &SuccChain = *BlockToChain[*SI];
  596. // Don't split chains, either this chain or the successor's chain.
  597. if (&Chain == &SuccChain) {
  598. DEBUG(dbgs() << " exiting: " << getBlockName(*I) << " -> "
  599. << getBlockName(*SI) << " (chain conflict)\n");
  600. continue;
  601. }
  602. uint32_t SuccWeight = MBPI->getEdgeWeight(*I, *SI);
  603. if (LoopBlockSet.count(*SI)) {
  604. DEBUG(dbgs() << " looping: " << getBlockName(*I) << " -> "
  605. << getBlockName(*SI) << " (" << SuccWeight << ")\n");
  606. HasLoopingSucc = true;
  607. continue;
  608. }
  609. unsigned SuccLoopDepth = 0;
  610. if (MachineLoop *ExitLoop = MLI->getLoopFor(*SI)) {
  611. SuccLoopDepth = ExitLoop->getLoopDepth();
  612. if (ExitLoop->contains(&L))
  613. BlocksExitingToOuterLoop.insert(*I);
  614. }
  615. BranchProbability SuccProb(SuccWeight / WeightScale, SumWeight);
  616. BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(*I) * SuccProb;
  617. DEBUG(dbgs() << " exiting: " << getBlockName(*I) << " -> "
  618. << getBlockName(*SI) << " [L:" << SuccLoopDepth
  619. << "] (" << ExitEdgeFreq << ")\n");
  620. // Note that we slightly bias this toward an existing layout successor to
  621. // retain incoming order in the absence of better information.
  622. // FIXME: Should we bias this more strongly? It's pretty weak.
  623. if (!ExitingBB || BestExitLoopDepth < SuccLoopDepth ||
  624. ExitEdgeFreq > BestExitEdgeFreq ||
  625. ((*I)->isLayoutSuccessor(*SI) &&
  626. !(ExitEdgeFreq < BestExitEdgeFreq))) {
  627. BestExitEdgeFreq = ExitEdgeFreq;
  628. ExitingBB = *I;
  629. }
  630. }
  631. // Restore the old exiting state, no viable looping successor was found.
  632. if (!HasLoopingSucc) {
  633. ExitingBB = OldExitingBB;
  634. BestExitEdgeFreq = OldBestExitEdgeFreq;
  635. continue;
  636. }
  637. }
  638. // Without a candidate exiting block or with only a single block in the
  639. // loop, just use the loop header to layout the loop.
  640. if (!ExitingBB || L.getNumBlocks() == 1)
  641. return 0;
  642. // Also, if we have exit blocks which lead to outer loops but didn't select
  643. // one of them as the exiting block we are rotating toward, disable loop
  644. // rotation altogether.
  645. if (!BlocksExitingToOuterLoop.empty() &&
  646. !BlocksExitingToOuterLoop.count(ExitingBB))
  647. return 0;
  648. DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB) << "\n");
  649. return ExitingBB;
  650. }
  651. /// \brief Attempt to rotate an exiting block to the bottom of the loop.
  652. ///
  653. /// Once we have built a chain, try to rotate it to line up the hot exit block
  654. /// with fallthrough out of the loop if doing so doesn't introduce unnecessary
  655. /// branches. For example, if the loop has fallthrough into its header and out
  656. /// of its bottom already, don't rotate it.
  657. void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
  658. MachineBasicBlock *ExitingBB,
  659. const BlockFilterSet &LoopBlockSet) {
  660. if (!ExitingBB)
  661. return;
  662. MachineBasicBlock *Top = *LoopChain.begin();
  663. bool ViableTopFallthrough = false;
  664. for (MachineBasicBlock::pred_iterator PI = Top->pred_begin(),
  665. PE = Top->pred_end();
  666. PI != PE; ++PI) {
  667. BlockChain *PredChain = BlockToChain[*PI];
  668. if (!LoopBlockSet.count(*PI) &&
  669. (!PredChain || *PI == *llvm::prior(PredChain->end()))) {
  670. ViableTopFallthrough = true;
  671. break;
  672. }
  673. }
  674. // If the header has viable fallthrough, check whether the current loop
  675. // bottom is a viable exiting block. If so, bail out as rotating will
  676. // introduce an unnecessary branch.
  677. if (ViableTopFallthrough) {
  678. MachineBasicBlock *Bottom = *llvm::prior(LoopChain.end());
  679. for (MachineBasicBlock::succ_iterator SI = Bottom->succ_begin(),
  680. SE = Bottom->succ_end();
  681. SI != SE; ++SI) {
  682. BlockChain *SuccChain = BlockToChain[*SI];
  683. if (!LoopBlockSet.count(*SI) &&
  684. (!SuccChain || *SI == *SuccChain->begin()))
  685. return;
  686. }
  687. }
  688. BlockChain::iterator ExitIt = std::find(LoopChain.begin(), LoopChain.end(),
  689. ExitingBB);
  690. if (ExitIt == LoopChain.end())
  691. return;
  692. std::rotate(LoopChain.begin(), llvm::next(ExitIt), LoopChain.end());
  693. }
  694. /// \brief Forms basic block chains from the natural loop structures.
  695. ///
  696. /// These chains are designed to preserve the existing *structure* of the code
  697. /// as much as possible. We can then stitch the chains together in a way which
  698. /// both preserves the topological structure and minimizes taken conditional
  699. /// branches.
  700. void MachineBlockPlacement::buildLoopChains(MachineFunction &F,
  701. MachineLoop &L) {
  702. // First recurse through any nested loops, building chains for those inner
  703. // loops.
  704. for (MachineLoop::iterator LI = L.begin(), LE = L.end(); LI != LE; ++LI)
  705. buildLoopChains(F, **LI);
  706. SmallVector<MachineBasicBlock *, 16> BlockWorkList;
  707. BlockFilterSet LoopBlockSet(L.block_begin(), L.block_end());
  708. // First check to see if there is an obviously preferable top block for the
  709. // loop. This will default to the header, but may end up as one of the
  710. // predecessors to the header if there is one which will result in strictly
  711. // fewer branches in the loop body.
  712. MachineBasicBlock *LoopTop = findBestLoopTop(L, LoopBlockSet);
  713. // If we selected just the header for the loop top, look for a potentially
  714. // profitable exit block in the event that rotating the loop can eliminate
  715. // branches by placing an exit edge at the bottom.
  716. MachineBasicBlock *ExitingBB = 0;
  717. if (LoopTop == L.getHeader())
  718. ExitingBB = findBestLoopExit(F, L, LoopBlockSet);
  719. BlockChain &LoopChain = *BlockToChain[LoopTop];
  720. // FIXME: This is a really lame way of walking the chains in the loop: we
  721. // walk the blocks, and use a set to prevent visiting a particular chain
  722. // twice.
  723. SmallPtrSet<BlockChain *, 4> UpdatedPreds;
  724. assert(LoopChain.LoopPredecessors == 0);
  725. UpdatedPreds.insert(&LoopChain);
  726. for (MachineLoop::block_iterator BI = L.block_begin(),
  727. BE = L.block_end();
  728. BI != BE; ++BI) {
  729. BlockChain &Chain = *BlockToChain[*BI];
  730. if (!UpdatedPreds.insert(&Chain))
  731. continue;
  732. assert(Chain.LoopPredecessors == 0);
  733. for (BlockChain::iterator BCI = Chain.begin(), BCE = Chain.end();
  734. BCI != BCE; ++BCI) {
  735. assert(BlockToChain[*BCI] == &Chain);
  736. for (MachineBasicBlock::pred_iterator PI = (*BCI)->pred_begin(),
  737. PE = (*BCI)->pred_end();
  738. PI != PE; ++PI) {
  739. if (BlockToChain[*PI] == &Chain || !LoopBlockSet.count(*PI))
  740. continue;
  741. ++Chain.LoopPredecessors;
  742. }
  743. }
  744. if (Chain.LoopPredecessors == 0)
  745. BlockWorkList.push_back(*Chain.begin());
  746. }
  747. buildChain(LoopTop, LoopChain, BlockWorkList, &LoopBlockSet);
  748. rotateLoop(LoopChain, ExitingBB, LoopBlockSet);
  749. DEBUG({
  750. // Crash at the end so we get all of the debugging output first.
  751. bool BadLoop = false;
  752. if (LoopChain.LoopPredecessors) {
  753. BadLoop = true;
  754. dbgs() << "Loop chain contains a block without its preds placed!\n"
  755. << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
  756. << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
  757. }
  758. for (BlockChain::iterator BCI = LoopChain.begin(), BCE = LoopChain.end();
  759. BCI != BCE; ++BCI) {
  760. dbgs() << " ... " << getBlockName(*BCI) << "\n";
  761. if (!LoopBlockSet.erase(*BCI)) {
  762. // We don't mark the loop as bad here because there are real situations
  763. // where this can occur. For example, with an unanalyzable fallthrough
  764. // from a loop block to a non-loop block or vice versa.
  765. dbgs() << "Loop chain contains a block not contained by the loop!\n"
  766. << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
  767. << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
  768. << " Bad block: " << getBlockName(*BCI) << "\n";
  769. }
  770. }
  771. if (!LoopBlockSet.empty()) {
  772. BadLoop = true;
  773. for (BlockFilterSet::iterator LBI = LoopBlockSet.begin(),
  774. LBE = LoopBlockSet.end();
  775. LBI != LBE; ++LBI)
  776. dbgs() << "Loop contains blocks never placed into a chain!\n"
  777. << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
  778. << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
  779. << " Bad block: " << getBlockName(*LBI) << "\n";
  780. }
  781. assert(!BadLoop && "Detected problems with the placement of this loop.");
  782. });
  783. }
  784. void MachineBlockPlacement::buildCFGChains(MachineFunction &F) {
  785. // Ensure that every BB in the function has an associated chain to simplify
  786. // the assumptions of the remaining algorithm.
  787. SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
  788. for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
  789. MachineBasicBlock *BB = FI;
  790. BlockChain *Chain
  791. = new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
  792. // Also, merge any blocks which we cannot reason about and must preserve
  793. // the exact fallthrough behavior for.
  794. for (;;) {
  795. Cond.clear();
  796. MachineBasicBlock *TBB = 0, *FBB = 0; // For AnalyzeBranch.
  797. if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
  798. break;
  799. MachineFunction::iterator NextFI(llvm::next(FI));
  800. MachineBasicBlock *NextBB = NextFI;
  801. // Ensure that the layout successor is a viable block, as we know that
  802. // fallthrough is a possibility.
  803. assert(NextFI != FE && "Can't fallthrough past the last block.");
  804. DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
  805. << getBlockName(BB) << " -> " << getBlockName(NextBB)
  806. << "\n");
  807. Chain->merge(NextBB, 0);
  808. FI = NextFI;
  809. BB = NextBB;
  810. }
  811. }
  812. // Build any loop-based chains.
  813. for (MachineLoopInfo::iterator LI = MLI->begin(), LE = MLI->end(); LI != LE;
  814. ++LI)
  815. buildLoopChains(F, **LI);
  816. SmallVector<MachineBasicBlock *, 16> BlockWorkList;
  817. SmallPtrSet<BlockChain *, 4> UpdatedPreds;
  818. for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
  819. MachineBasicBlock *BB = &*FI;
  820. BlockChain &Chain = *BlockToChain[BB];
  821. if (!UpdatedPreds.insert(&Chain))
  822. continue;
  823. assert(Chain.LoopPredecessors == 0);
  824. for (BlockChain::iterator BCI = Chain.begin(), BCE = Chain.end();
  825. BCI != BCE; ++BCI) {
  826. assert(BlockToChain[*BCI] == &Chain);
  827. for (MachineBasicBlock::pred_iterator PI = (*BCI)->pred_begin(),
  828. PE = (*BCI)->pred_end();
  829. PI != PE; ++PI) {
  830. if (BlockToChain[*PI] == &Chain)
  831. continue;
  832. ++Chain.LoopPredecessors;
  833. }
  834. }
  835. if (Chain.LoopPredecessors == 0)
  836. BlockWorkList.push_back(*Chain.begin());
  837. }
  838. BlockChain &FunctionChain = *BlockToChain[&F.front()];
  839. buildChain(&F.front(), FunctionChain, BlockWorkList);
  840. typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType;
  841. DEBUG({
  842. // Crash at the end so we get all of the debugging output first.
  843. bool BadFunc = false;
  844. FunctionBlockSetType FunctionBlockSet;
  845. for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
  846. FunctionBlockSet.insert(FI);
  847. for (BlockChain::iterator BCI = FunctionChain.begin(),
  848. BCE = FunctionChain.end();
  849. BCI != BCE; ++BCI)
  850. if (!FunctionBlockSet.erase(*BCI)) {
  851. BadFunc = true;
  852. dbgs() << "Function chain contains a block not in the function!\n"
  853. << " Bad block: " << getBlockName(*BCI) << "\n";
  854. }
  855. if (!FunctionBlockSet.empty()) {
  856. BadFunc = true;
  857. for (FunctionBlockSetType::iterator FBI = FunctionBlockSet.begin(),
  858. FBE = FunctionBlockSet.end();
  859. FBI != FBE; ++FBI)
  860. dbgs() << "Function contains blocks never placed into a chain!\n"
  861. << " Bad block: " << getBlockName(*FBI) << "\n";
  862. }
  863. assert(!BadFunc && "Detected problems with the block placement.");
  864. });
  865. // Splice the blocks into place.
  866. MachineFunction::iterator InsertPos = F.begin();
  867. for (BlockChain::iterator BI = FunctionChain.begin(),
  868. BE = FunctionChain.end();
  869. BI != BE; ++BI) {
  870. DEBUG(dbgs() << (BI == FunctionChain.begin() ? "Placing chain "
  871. : " ... ")
  872. << getBlockName(*BI) << "\n");
  873. if (InsertPos != MachineFunction::iterator(*BI))
  874. F.splice(InsertPos, *BI);
  875. else
  876. ++InsertPos;
  877. // Update the terminator of the previous block.
  878. if (BI == FunctionChain.begin())
  879. continue;
  880. MachineBasicBlock *PrevBB = llvm::prior(MachineFunction::iterator(*BI));
  881. // FIXME: It would be awesome of updateTerminator would just return rather
  882. // than assert when the branch cannot be analyzed in order to remove this
  883. // boiler plate.
  884. Cond.clear();
  885. MachineBasicBlock *TBB = 0, *FBB = 0; // For AnalyzeBranch.
  886. if (!TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
  887. // If PrevBB has a two-way branch, try to re-order the branches
  888. // such that we branch to the successor with higher weight first.
  889. if (TBB && !Cond.empty() && FBB &&
  890. MBPI->getEdgeWeight(PrevBB, FBB) > MBPI->getEdgeWeight(PrevBB, TBB) &&
  891. !TII->ReverseBranchCondition(Cond)) {
  892. DEBUG(dbgs() << "Reverse order of the two branches: "
  893. << getBlockName(PrevBB) << "\n");
  894. DEBUG(dbgs() << " Edge weight: " << MBPI->getEdgeWeight(PrevBB, FBB)
  895. << " vs " << MBPI->getEdgeWeight(PrevBB, TBB) << "\n");
  896. DebugLoc dl; // FIXME: this is nowhere
  897. TII->RemoveBranch(*PrevBB);
  898. TII->InsertBranch(*PrevBB, FBB, TBB, Cond, dl);
  899. }
  900. PrevBB->updateTerminator();
  901. }
  902. }
  903. // Fixup the last block.
  904. Cond.clear();
  905. MachineBasicBlock *TBB = 0, *FBB = 0; // For AnalyzeBranch.
  906. if (!TII->AnalyzeBranch(F.back(), TBB, FBB, Cond))
  907. F.back().updateTerminator();
  908. // Walk through the backedges of the function now that we have fully laid out
  909. // the basic blocks and align the destination of each backedge. We don't rely
  910. // exclusively on the loop info here so that we can align backedges in
  911. // unnatural CFGs and backedges that were introduced purely because of the
  912. // loop rotations done during this layout pass.
  913. if (F.getFunction()->getFnAttributes().hasOptimizeForSizeAttr())
  914. return;
  915. unsigned Align = TLI->getPrefLoopAlignment();
  916. if (!Align)
  917. return; // Don't care about loop alignment.
  918. if (FunctionChain.begin() == FunctionChain.end())
  919. return; // Empty chain.
  920. const BranchProbability ColdProb(1, 5); // 20%
  921. BlockFrequency EntryFreq = MBFI->getBlockFreq(F.begin());
  922. BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
  923. for (BlockChain::iterator BI = llvm::next(FunctionChain.begin()),
  924. BE = FunctionChain.end();
  925. BI != BE; ++BI) {
  926. // Don't align non-looping basic blocks. These are unlikely to execute
  927. // enough times to matter in practice. Note that we'll still handle
  928. // unnatural CFGs inside of a natural outer loop (the common case) and
  929. // rotated loops.
  930. MachineLoop *L = MLI->getLoopFor(*BI);
  931. if (!L)
  932. continue;
  933. // If the block is cold relative to the function entry don't waste space
  934. // aligning it.
  935. BlockFrequency Freq = MBFI->getBlockFreq(*BI);
  936. if (Freq < WeightedEntryFreq)
  937. continue;
  938. // If the block is cold relative to its loop header, don't align it
  939. // regardless of what edges into the block exist.
  940. MachineBasicBlock *LoopHeader = L->getHeader();
  941. BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
  942. if (Freq < (LoopHeaderFreq * ColdProb))
  943. continue;
  944. // Check for the existence of a non-layout predecessor which would benefit
  945. // from aligning this block.
  946. MachineBasicBlock *LayoutPred = *llvm::prior(BI);
  947. // Force alignment if all the predecessors are jumps. We already checked
  948. // that the block isn't cold above.
  949. if (!LayoutPred->isSuccessor(*BI)) {
  950. (*BI)->setAlignment(Align);
  951. continue;
  952. }
  953. // Align this block if the layout predecessor's edge into this block is
  954. // cold relative to the block. When this is true, othe predecessors make up
  955. // all of the hot entries into the block and thus alignment is likely to be
  956. // important.
  957. BranchProbability LayoutProb = MBPI->getEdgeProbability(LayoutPred, *BI);
  958. BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
  959. if (LayoutEdgeFreq <= (Freq * ColdProb))
  960. (*BI)->setAlignment(Align);
  961. }
  962. }
  963. bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &F) {
  964. // Check for single-block functions and skip them.
  965. if (llvm::next(F.begin()) == F.end())
  966. return false;
  967. MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
  968. MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
  969. MLI = &getAnalysis<MachineLoopInfo>();
  970. TII = F.getTarget().getInstrInfo();
  971. TLI = F.getTarget().getTargetLowering();
  972. assert(BlockToChain.empty());
  973. buildCFGChains(F);
  974. BlockToChain.clear();
  975. ChainAllocator.DestroyAll();
  976. // We always return true as we have no way to track whether the final order
  977. // differs from the original order.
  978. return true;
  979. }
  980. namespace {
  981. /// \brief A pass to compute block placement statistics.
  982. ///
  983. /// A separate pass to compute interesting statistics for evaluating block
  984. /// placement. This is separate from the actual placement pass so that they can
  985. /// be computed in the absence of any placement transformations or when using
  986. /// alternative placement strategies.
  987. class MachineBlockPlacementStats : public MachineFunctionPass {
  988. /// \brief A handle to the branch probability pass.
  989. const MachineBranchProbabilityInfo *MBPI;
  990. /// \brief A handle to the function-wide block frequency pass.
  991. const MachineBlockFrequencyInfo *MBFI;
  992. public:
  993. static char ID; // Pass identification, replacement for typeid
  994. MachineBlockPlacementStats() : MachineFunctionPass(ID) {
  995. initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
  996. }
  997. bool runOnMachineFunction(MachineFunction &F);
  998. void getAnalysisUsage(AnalysisUsage &AU) const {
  999. AU.addRequired<MachineBranchProbabilityInfo>();
  1000. AU.addRequired<MachineBlockFrequencyInfo>();
  1001. AU.setPreservesAll();
  1002. MachineFunctionPass::getAnalysisUsage(AU);
  1003. }
  1004. };
  1005. }
  1006. char MachineBlockPlacementStats::ID = 0;
  1007. char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
  1008. INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
  1009. "Basic Block Placement Stats", false, false)
  1010. INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
  1011. INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
  1012. INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
  1013. "Basic Block Placement Stats", false, false)
  1014. bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
  1015. // Check for single-block functions and skip them.
  1016. if (llvm::next(F.begin()) == F.end())
  1017. return false;
  1018. MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
  1019. MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
  1020. for (MachineFunction::iterator I = F.begin(), E = F.end(); I != E; ++I) {
  1021. BlockFrequency BlockFreq = MBFI->getBlockFreq(I);
  1022. Statistic &NumBranches = (I->succ_size() > 1) ? NumCondBranches
  1023. : NumUncondBranches;
  1024. Statistic &BranchTakenFreq = (I->succ_size() > 1) ? CondBranchTakenFreq
  1025. : UncondBranchTakenFreq;
  1026. for (MachineBasicBlock::succ_iterator SI = I->succ_begin(),
  1027. SE = I->succ_end();
  1028. SI != SE; ++SI) {
  1029. // Skip if this successor is a fallthrough.
  1030. if (I->isLayoutSuccessor(*SI))
  1031. continue;
  1032. BlockFrequency EdgeFreq = BlockFreq * MBPI->getEdgeProbability(I, *SI);
  1033. ++NumBranches;
  1034. BranchTakenFreq += EdgeFreq.getFrequency();
  1035. }
  1036. }
  1037. return false;
  1038. }