MachineBlockPlacement.cpp 62 KB

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