MachineBlockPlacement.cpp 87 KB

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