MachineBlockPlacement.cpp 121 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979
  1. //===- MachineBlockPlacement.cpp - Basic Block Code Layout optimization ---===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements basic block placement transformations using the CFG
  10. // structure and branch probability estimates.
  11. //
  12. // The pass strives to preserve the structure of the CFG (that is, retain
  13. // a topological ordering of basic blocks) in the absence of a *strong* signal
  14. // to the contrary from probabilities. However, within the CFG structure, it
  15. // attempts to choose an ordering which favors placing more likely sequences of
  16. // blocks adjacent to each other.
  17. //
  18. // The algorithm works from the inner-most loop within a function outward, and
  19. // at each stage walks through the basic blocks, trying to coalesce them into
  20. // sequential chains where allowed by the CFG (or demanded by heavy
  21. // probabilities). Finally, it walks the blocks in topological order, and the
  22. // first time it reaches a chain of basic blocks, it schedules them in the
  23. // function in-order.
  24. //
  25. //===----------------------------------------------------------------------===//
  26. #include "BranchFolding.h"
  27. #include "llvm/ADT/ArrayRef.h"
  28. #include "llvm/ADT/DenseMap.h"
  29. #include "llvm/ADT/STLExtras.h"
  30. #include "llvm/ADT/SetVector.h"
  31. #include "llvm/ADT/SmallPtrSet.h"
  32. #include "llvm/ADT/SmallVector.h"
  33. #include "llvm/ADT/Statistic.h"
  34. #include "llvm/Analysis/BlockFrequencyInfoImpl.h"
  35. #include "llvm/CodeGen/MachineBasicBlock.h"
  36. #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
  37. #include "llvm/CodeGen/MachineBranchProbabilityInfo.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/MachinePostDominators.h"
  43. #include "llvm/CodeGen/TailDuplicator.h"
  44. #include "llvm/CodeGen/TargetInstrInfo.h"
  45. #include "llvm/CodeGen/TargetLowering.h"
  46. #include "llvm/CodeGen/TargetPassConfig.h"
  47. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  48. #include "llvm/IR/DebugLoc.h"
  49. #include "llvm/IR/Function.h"
  50. #include "llvm/Pass.h"
  51. #include "llvm/Support/Allocator.h"
  52. #include "llvm/Support/BlockFrequency.h"
  53. #include "llvm/Support/BranchProbability.h"
  54. #include "llvm/Support/CodeGen.h"
  55. #include "llvm/Support/CommandLine.h"
  56. #include "llvm/Support/Compiler.h"
  57. #include "llvm/Support/Debug.h"
  58. #include "llvm/Support/raw_ostream.h"
  59. #include "llvm/Target/TargetMachine.h"
  60. #include <algorithm>
  61. #include <cassert>
  62. #include <cstdint>
  63. #include <iterator>
  64. #include <memory>
  65. #include <string>
  66. #include <tuple>
  67. #include <utility>
  68. #include <vector>
  69. using namespace llvm;
  70. #define DEBUG_TYPE "block-placement"
  71. STATISTIC(NumCondBranches, "Number of conditional branches");
  72. STATISTIC(NumUncondBranches, "Number of unconditional branches");
  73. STATISTIC(CondBranchTakenFreq,
  74. "Potential frequency of taking conditional branches");
  75. STATISTIC(UncondBranchTakenFreq,
  76. "Potential frequency of taking unconditional branches");
  77. static cl::opt<unsigned> AlignAllBlock("align-all-blocks",
  78. cl::desc("Force the alignment of all "
  79. "blocks in the function."),
  80. cl::init(0), cl::Hidden);
  81. static cl::opt<unsigned> AlignAllNonFallThruBlocks(
  82. "align-all-nofallthru-blocks",
  83. cl::desc("Force the alignment of all "
  84. "blocks that have no fall-through predecessors (i.e. don't add "
  85. "nops that are executed)."),
  86. cl::init(0), cl::Hidden);
  87. // FIXME: Find a good default for this flag and remove the flag.
  88. static cl::opt<unsigned> ExitBlockBias(
  89. "block-placement-exit-block-bias",
  90. cl::desc("Block frequency percentage a loop exit block needs "
  91. "over the original exit to be considered the new exit."),
  92. cl::init(0), cl::Hidden);
  93. // Definition:
  94. // - Outlining: placement of a basic block outside the chain or hot path.
  95. static cl::opt<unsigned> LoopToColdBlockRatio(
  96. "loop-to-cold-block-ratio",
  97. cl::desc("Outline loop blocks from loop chain if (frequency of loop) / "
  98. "(frequency of block) is greater than this ratio"),
  99. cl::init(5), cl::Hidden);
  100. static cl::opt<bool> ForceLoopColdBlock(
  101. "force-loop-cold-block",
  102. cl::desc("Force outlining cold blocks from loops."),
  103. cl::init(false), cl::Hidden);
  104. static cl::opt<bool>
  105. PreciseRotationCost("precise-rotation-cost",
  106. cl::desc("Model the cost of loop rotation more "
  107. "precisely by using profile data."),
  108. cl::init(false), cl::Hidden);
  109. static cl::opt<bool>
  110. ForcePreciseRotationCost("force-precise-rotation-cost",
  111. cl::desc("Force the use of precise cost "
  112. "loop rotation strategy."),
  113. cl::init(false), cl::Hidden);
  114. static cl::opt<unsigned> MisfetchCost(
  115. "misfetch-cost",
  116. cl::desc("Cost that models the probabilistic risk of an instruction "
  117. "misfetch due to a jump comparing to falling through, whose cost "
  118. "is zero."),
  119. cl::init(1), cl::Hidden);
  120. static cl::opt<unsigned> JumpInstCost("jump-inst-cost",
  121. cl::desc("Cost of jump instructions."),
  122. cl::init(1), cl::Hidden);
  123. static cl::opt<bool>
  124. TailDupPlacement("tail-dup-placement",
  125. cl::desc("Perform tail duplication during placement. "
  126. "Creates more fallthrough opportunites in "
  127. "outline branches."),
  128. cl::init(true), cl::Hidden);
  129. static cl::opt<bool>
  130. BranchFoldPlacement("branch-fold-placement",
  131. cl::desc("Perform branch folding during placement. "
  132. "Reduces code size."),
  133. cl::init(true), cl::Hidden);
  134. // Heuristic for tail duplication.
  135. static cl::opt<unsigned> TailDupPlacementThreshold(
  136. "tail-dup-placement-threshold",
  137. cl::desc("Instruction cutoff for tail duplication during layout. "
  138. "Tail merging during layout is forced to have a threshold "
  139. "that won't conflict."), cl::init(2),
  140. cl::Hidden);
  141. // Heuristic for aggressive tail duplication.
  142. static cl::opt<unsigned> TailDupPlacementAggressiveThreshold(
  143. "tail-dup-placement-aggressive-threshold",
  144. cl::desc("Instruction cutoff for aggressive tail duplication during "
  145. "layout. Used at -O3. Tail merging during layout is forced to "
  146. "have a threshold that won't conflict."), cl::init(4),
  147. cl::Hidden);
  148. // Heuristic for tail duplication.
  149. static cl::opt<unsigned> TailDupPlacementPenalty(
  150. "tail-dup-placement-penalty",
  151. cl::desc("Cost penalty for blocks that can avoid breaking CFG by copying. "
  152. "Copying can increase fallthrough, but it also increases icache "
  153. "pressure. This parameter controls the penalty to account for that. "
  154. "Percent as integer."),
  155. cl::init(2),
  156. cl::Hidden);
  157. // Heuristic for triangle chains.
  158. static cl::opt<unsigned> TriangleChainCount(
  159. "triangle-chain-count",
  160. cl::desc("Number of triangle-shaped-CFG's that need to be in a row for the "
  161. "triangle tail duplication heuristic to kick in. 0 to disable."),
  162. cl::init(2),
  163. cl::Hidden);
  164. extern cl::opt<unsigned> StaticLikelyProb;
  165. extern cl::opt<unsigned> ProfileLikelyProb;
  166. // Internal option used to control BFI display only after MBP pass.
  167. // Defined in CodeGen/MachineBlockFrequencyInfo.cpp:
  168. // -view-block-layout-with-bfi=
  169. extern cl::opt<GVDAGType> ViewBlockLayoutWithBFI;
  170. // Command line option to specify the name of the function for CFG dump
  171. // Defined in Analysis/BlockFrequencyInfo.cpp: -view-bfi-func-name=
  172. extern cl::opt<std::string> ViewBlockFreqFuncName;
  173. namespace {
  174. class BlockChain;
  175. /// Type for our function-wide basic block -> block chain mapping.
  176. using BlockToChainMapType = DenseMap<const MachineBasicBlock *, BlockChain *>;
  177. /// A chain of blocks which will be laid out contiguously.
  178. ///
  179. /// This is the datastructure representing a chain of consecutive blocks that
  180. /// are profitable to layout together in order to maximize fallthrough
  181. /// probabilities and code locality. We also can use a block chain to represent
  182. /// a sequence of basic blocks which have some external (correctness)
  183. /// requirement for sequential layout.
  184. ///
  185. /// Chains can be built around a single basic block and can be merged to grow
  186. /// them. They participate in a block-to-chain mapping, which is updated
  187. /// automatically as chains are merged together.
  188. class BlockChain {
  189. /// The sequence of blocks belonging to this chain.
  190. ///
  191. /// This is the sequence of blocks for a particular chain. These will be laid
  192. /// out in-order within the function.
  193. SmallVector<MachineBasicBlock *, 4> Blocks;
  194. /// A handle to the function-wide basic block to block chain mapping.
  195. ///
  196. /// This is retained in each block chain to simplify the computation of child
  197. /// block chains for SCC-formation and iteration. We store the edges to child
  198. /// basic blocks, and map them back to their associated chains using this
  199. /// structure.
  200. BlockToChainMapType &BlockToChain;
  201. public:
  202. /// Construct a new BlockChain.
  203. ///
  204. /// This builds a new block chain representing a single basic block in the
  205. /// function. It also registers itself as the chain that block participates
  206. /// in with the BlockToChain mapping.
  207. BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
  208. : Blocks(1, BB), BlockToChain(BlockToChain) {
  209. assert(BB && "Cannot create a chain with a null basic block");
  210. BlockToChain[BB] = this;
  211. }
  212. /// Iterator over blocks within the chain.
  213. using iterator = SmallVectorImpl<MachineBasicBlock *>::iterator;
  214. using const_iterator = SmallVectorImpl<MachineBasicBlock *>::const_iterator;
  215. /// Beginning of blocks within the chain.
  216. iterator begin() { return Blocks.begin(); }
  217. const_iterator begin() const { return Blocks.begin(); }
  218. /// End of blocks within the chain.
  219. iterator end() { return Blocks.end(); }
  220. const_iterator end() const { return Blocks.end(); }
  221. bool remove(MachineBasicBlock* BB) {
  222. for(iterator i = begin(); i != end(); ++i) {
  223. if (*i == BB) {
  224. Blocks.erase(i);
  225. return true;
  226. }
  227. }
  228. return false;
  229. }
  230. /// Merge a block chain into this one.
  231. ///
  232. /// This routine merges a block chain into this one. It takes care of forming
  233. /// a contiguous sequence of basic blocks, updating the edge list, and
  234. /// updating the block -> chain mapping. It does not free or tear down the
  235. /// old chain, but the old chain's block list is no longer valid.
  236. void merge(MachineBasicBlock *BB, BlockChain *Chain) {
  237. assert(BB && "Can't merge a null block.");
  238. assert(!Blocks.empty() && "Can't merge into an empty chain.");
  239. // Fast path in case we don't have a chain already.
  240. if (!Chain) {
  241. assert(!BlockToChain[BB] &&
  242. "Passed chain is null, but BB has entry in BlockToChain.");
  243. Blocks.push_back(BB);
  244. BlockToChain[BB] = this;
  245. return;
  246. }
  247. assert(BB == *Chain->begin() && "Passed BB is not head of Chain.");
  248. assert(Chain->begin() != Chain->end());
  249. // Update the incoming blocks to point to this chain, and add them to the
  250. // chain structure.
  251. for (MachineBasicBlock *ChainBB : *Chain) {
  252. Blocks.push_back(ChainBB);
  253. assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain.");
  254. BlockToChain[ChainBB] = this;
  255. }
  256. }
  257. #ifndef NDEBUG
  258. /// Dump the blocks in this chain.
  259. LLVM_DUMP_METHOD void dump() {
  260. for (MachineBasicBlock *MBB : *this)
  261. MBB->dump();
  262. }
  263. #endif // NDEBUG
  264. /// Count of predecessors of any block within the chain which have not
  265. /// yet been scheduled. In general, we will delay scheduling this chain
  266. /// until those predecessors are scheduled (or we find a sufficiently good
  267. /// reason to override this heuristic.) Note that when forming loop chains,
  268. /// blocks outside the loop are ignored and treated as if they were already
  269. /// scheduled.
  270. ///
  271. /// Note: This field is reinitialized multiple times - once for each loop,
  272. /// and then once for the function as a whole.
  273. unsigned UnscheduledPredecessors = 0;
  274. };
  275. class MachineBlockPlacement : public MachineFunctionPass {
  276. /// A type for a block filter set.
  277. using BlockFilterSet = SmallSetVector<const MachineBasicBlock *, 16>;
  278. /// Pair struct containing basic block and taildup profitability
  279. struct BlockAndTailDupResult {
  280. MachineBasicBlock *BB;
  281. bool ShouldTailDup;
  282. };
  283. /// Triple struct containing edge weight and the edge.
  284. struct WeightedEdge {
  285. BlockFrequency Weight;
  286. MachineBasicBlock *Src;
  287. MachineBasicBlock *Dest;
  288. };
  289. /// work lists of blocks that are ready to be laid out
  290. SmallVector<MachineBasicBlock *, 16> BlockWorkList;
  291. SmallVector<MachineBasicBlock *, 16> EHPadWorkList;
  292. /// Edges that have already been computed as optimal.
  293. DenseMap<const MachineBasicBlock *, BlockAndTailDupResult> ComputedEdges;
  294. /// Machine Function
  295. MachineFunction *F;
  296. /// A handle to the branch probability pass.
  297. const MachineBranchProbabilityInfo *MBPI;
  298. /// A handle to the function-wide block frequency pass.
  299. std::unique_ptr<BranchFolder::MBFIWrapper> MBFI;
  300. /// A handle to the loop info.
  301. MachineLoopInfo *MLI;
  302. /// Preferred loop exit.
  303. /// Member variable for convenience. It may be removed by duplication deep
  304. /// in the call stack.
  305. MachineBasicBlock *PreferredLoopExit;
  306. /// A handle to the target's instruction info.
  307. const TargetInstrInfo *TII;
  308. /// A handle to the target's lowering info.
  309. const TargetLoweringBase *TLI;
  310. /// A handle to the post dominator tree.
  311. MachinePostDominatorTree *MPDT;
  312. /// Duplicator used to duplicate tails during placement.
  313. ///
  314. /// Placement decisions can open up new tail duplication opportunities, but
  315. /// since tail duplication affects placement decisions of later blocks, it
  316. /// must be done inline.
  317. TailDuplicator TailDup;
  318. /// Allocator and owner of BlockChain structures.
  319. ///
  320. /// We build BlockChains lazily while processing the loop structure of
  321. /// a function. To reduce malloc traffic, we allocate them using this
  322. /// slab-like allocator, and destroy them after the pass completes. An
  323. /// important guarantee is that this allocator produces stable pointers to
  324. /// the chains.
  325. SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
  326. /// Function wide BasicBlock to BlockChain mapping.
  327. ///
  328. /// This mapping allows efficiently moving from any given basic block to the
  329. /// BlockChain it participates in, if any. We use it to, among other things,
  330. /// allow implicitly defining edges between chains as the existing edges
  331. /// between basic blocks.
  332. DenseMap<const MachineBasicBlock *, BlockChain *> BlockToChain;
  333. #ifndef NDEBUG
  334. /// The set of basic blocks that have terminators that cannot be fully
  335. /// analyzed. These basic blocks cannot be re-ordered safely by
  336. /// MachineBlockPlacement, and we must preserve physical layout of these
  337. /// blocks and their successors through the pass.
  338. SmallPtrSet<MachineBasicBlock *, 4> BlocksWithUnanalyzableExits;
  339. #endif
  340. /// Decrease the UnscheduledPredecessors count for all blocks in chain, and
  341. /// if the count goes to 0, add them to the appropriate work list.
  342. void markChainSuccessors(
  343. const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB,
  344. const BlockFilterSet *BlockFilter = nullptr);
  345. /// Decrease the UnscheduledPredecessors count for a single block, and
  346. /// if the count goes to 0, add them to the appropriate work list.
  347. void markBlockSuccessors(
  348. const BlockChain &Chain, const MachineBasicBlock *BB,
  349. const MachineBasicBlock *LoopHeaderBB,
  350. const BlockFilterSet *BlockFilter = nullptr);
  351. BranchProbability
  352. collectViableSuccessors(
  353. const MachineBasicBlock *BB, const BlockChain &Chain,
  354. const BlockFilterSet *BlockFilter,
  355. SmallVector<MachineBasicBlock *, 4> &Successors);
  356. bool shouldPredBlockBeOutlined(
  357. const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
  358. const BlockChain &Chain, const BlockFilterSet *BlockFilter,
  359. BranchProbability SuccProb, BranchProbability HotProb);
  360. bool repeatedlyTailDuplicateBlock(
  361. MachineBasicBlock *BB, MachineBasicBlock *&LPred,
  362. const MachineBasicBlock *LoopHeaderBB,
  363. BlockChain &Chain, BlockFilterSet *BlockFilter,
  364. MachineFunction::iterator &PrevUnplacedBlockIt);
  365. bool maybeTailDuplicateBlock(
  366. MachineBasicBlock *BB, MachineBasicBlock *LPred,
  367. BlockChain &Chain, BlockFilterSet *BlockFilter,
  368. MachineFunction::iterator &PrevUnplacedBlockIt,
  369. bool &DuplicatedToLPred);
  370. bool hasBetterLayoutPredecessor(
  371. const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
  372. const BlockChain &SuccChain, BranchProbability SuccProb,
  373. BranchProbability RealSuccProb, const BlockChain &Chain,
  374. const BlockFilterSet *BlockFilter);
  375. BlockAndTailDupResult selectBestSuccessor(
  376. const MachineBasicBlock *BB, const BlockChain &Chain,
  377. const BlockFilterSet *BlockFilter);
  378. MachineBasicBlock *selectBestCandidateBlock(
  379. const BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList);
  380. MachineBasicBlock *getFirstUnplacedBlock(
  381. const BlockChain &PlacedChain,
  382. MachineFunction::iterator &PrevUnplacedBlockIt,
  383. const BlockFilterSet *BlockFilter);
  384. /// Add a basic block to the work list if it is appropriate.
  385. ///
  386. /// If the optional parameter BlockFilter is provided, only MBB
  387. /// present in the set will be added to the worklist. If nullptr
  388. /// is provided, no filtering occurs.
  389. void fillWorkLists(const MachineBasicBlock *MBB,
  390. SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
  391. const BlockFilterSet *BlockFilter);
  392. void buildChain(const MachineBasicBlock *BB, BlockChain &Chain,
  393. BlockFilterSet *BlockFilter = nullptr);
  394. bool canMoveBottomBlockToTop(const MachineBasicBlock *BottomBlock,
  395. const MachineBasicBlock *OldTop);
  396. bool hasViableTopFallthrough(const MachineBasicBlock *Top,
  397. const BlockFilterSet &LoopBlockSet);
  398. MachineBasicBlock *findBestLoopTop(
  399. const MachineLoop &L, const BlockFilterSet &LoopBlockSet);
  400. MachineBasicBlock *findBestLoopExit(
  401. const MachineLoop &L, const BlockFilterSet &LoopBlockSet);
  402. BlockFilterSet collectLoopBlockSet(const MachineLoop &L);
  403. void buildLoopChains(const MachineLoop &L);
  404. void rotateLoop(
  405. BlockChain &LoopChain, const MachineBasicBlock *ExitingBB,
  406. const BlockFilterSet &LoopBlockSet);
  407. void rotateLoopWithProfile(
  408. BlockChain &LoopChain, const MachineLoop &L,
  409. const BlockFilterSet &LoopBlockSet);
  410. void buildCFGChains();
  411. void optimizeBranches();
  412. void alignBlocks();
  413. /// Returns true if a block should be tail-duplicated to increase fallthrough
  414. /// opportunities.
  415. bool shouldTailDuplicate(MachineBasicBlock *BB);
  416. /// Check the edge frequencies to see if tail duplication will increase
  417. /// fallthroughs.
  418. bool isProfitableToTailDup(
  419. const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
  420. BranchProbability QProb,
  421. const BlockChain &Chain, const BlockFilterSet *BlockFilter);
  422. /// Check for a trellis layout.
  423. bool isTrellis(const MachineBasicBlock *BB,
  424. const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
  425. const BlockChain &Chain, const BlockFilterSet *BlockFilter);
  426. /// Get the best successor given a trellis layout.
  427. BlockAndTailDupResult getBestTrellisSuccessor(
  428. const MachineBasicBlock *BB,
  429. const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
  430. BranchProbability AdjustedSumProb, const BlockChain &Chain,
  431. const BlockFilterSet *BlockFilter);
  432. /// Get the best pair of non-conflicting edges.
  433. static std::pair<WeightedEdge, WeightedEdge> getBestNonConflictingEdges(
  434. const MachineBasicBlock *BB,
  435. MutableArrayRef<SmallVector<WeightedEdge, 8>> Edges);
  436. /// Returns true if a block can tail duplicate into all unplaced
  437. /// predecessors. Filters based on loop.
  438. bool canTailDuplicateUnplacedPreds(
  439. const MachineBasicBlock *BB, MachineBasicBlock *Succ,
  440. const BlockChain &Chain, const BlockFilterSet *BlockFilter);
  441. /// Find chains of triangles to tail-duplicate where a global analysis works,
  442. /// but a local analysis would not find them.
  443. void precomputeTriangleChains();
  444. public:
  445. static char ID; // Pass identification, replacement for typeid
  446. MachineBlockPlacement() : MachineFunctionPass(ID) {
  447. initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
  448. }
  449. bool runOnMachineFunction(MachineFunction &F) override;
  450. bool allowTailDupPlacement() const {
  451. assert(F);
  452. return TailDupPlacement && !F->getTarget().requiresStructuredCFG();
  453. }
  454. void getAnalysisUsage(AnalysisUsage &AU) const override {
  455. AU.addRequired<MachineBranchProbabilityInfo>();
  456. AU.addRequired<MachineBlockFrequencyInfo>();
  457. if (TailDupPlacement)
  458. AU.addRequired<MachinePostDominatorTree>();
  459. AU.addRequired<MachineLoopInfo>();
  460. AU.addRequired<TargetPassConfig>();
  461. MachineFunctionPass::getAnalysisUsage(AU);
  462. }
  463. };
  464. } // end anonymous namespace
  465. char MachineBlockPlacement::ID = 0;
  466. char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
  467. INITIALIZE_PASS_BEGIN(MachineBlockPlacement, DEBUG_TYPE,
  468. "Branch Probability Basic Block Placement", false, false)
  469. INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
  470. INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
  471. INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree)
  472. INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
  473. INITIALIZE_PASS_END(MachineBlockPlacement, DEBUG_TYPE,
  474. "Branch Probability Basic Block Placement", false, false)
  475. #ifndef NDEBUG
  476. /// Helper to print the name of a MBB.
  477. ///
  478. /// Only used by debug logging.
  479. static std::string getBlockName(const MachineBasicBlock *BB) {
  480. std::string Result;
  481. raw_string_ostream OS(Result);
  482. OS << printMBBReference(*BB);
  483. OS << " ('" << BB->getName() << "')";
  484. OS.flush();
  485. return Result;
  486. }
  487. #endif
  488. /// Mark a chain's successors as having one fewer preds.
  489. ///
  490. /// When a chain is being merged into the "placed" chain, this routine will
  491. /// quickly walk the successors of each block in the chain and mark them as
  492. /// having one fewer active predecessor. It also adds any successors of this
  493. /// chain which reach the zero-predecessor state to the appropriate worklist.
  494. void MachineBlockPlacement::markChainSuccessors(
  495. const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB,
  496. const BlockFilterSet *BlockFilter) {
  497. // Walk all the blocks in this chain, marking their successors as having
  498. // a predecessor placed.
  499. for (MachineBasicBlock *MBB : Chain) {
  500. markBlockSuccessors(Chain, MBB, LoopHeaderBB, BlockFilter);
  501. }
  502. }
  503. /// Mark a single block's successors as having one fewer preds.
  504. ///
  505. /// Under normal circumstances, this is only called by markChainSuccessors,
  506. /// but if a block that was to be placed is completely tail-duplicated away,
  507. /// and was duplicated into the chain end, we need to redo markBlockSuccessors
  508. /// for just that block.
  509. void MachineBlockPlacement::markBlockSuccessors(
  510. const BlockChain &Chain, const MachineBasicBlock *MBB,
  511. const MachineBasicBlock *LoopHeaderBB, const BlockFilterSet *BlockFilter) {
  512. // Add any successors for which this is the only un-placed in-loop
  513. // predecessor to the worklist as a viable candidate for CFG-neutral
  514. // placement. No subsequent placement of this block will violate the CFG
  515. // shape, so we get to use heuristics to choose a favorable placement.
  516. for (MachineBasicBlock *Succ : MBB->successors()) {
  517. if (BlockFilter && !BlockFilter->count(Succ))
  518. continue;
  519. BlockChain &SuccChain = *BlockToChain[Succ];
  520. // Disregard edges within a fixed chain, or edges to the loop header.
  521. if (&Chain == &SuccChain || Succ == LoopHeaderBB)
  522. continue;
  523. // This is a cross-chain edge that is within the loop, so decrement the
  524. // loop predecessor count of the destination chain.
  525. if (SuccChain.UnscheduledPredecessors == 0 ||
  526. --SuccChain.UnscheduledPredecessors > 0)
  527. continue;
  528. auto *NewBB = *SuccChain.begin();
  529. if (NewBB->isEHPad())
  530. EHPadWorkList.push_back(NewBB);
  531. else
  532. BlockWorkList.push_back(NewBB);
  533. }
  534. }
  535. /// This helper function collects the set of successors of block
  536. /// \p BB that are allowed to be its layout successors, and return
  537. /// the total branch probability of edges from \p BB to those
  538. /// blocks.
  539. BranchProbability MachineBlockPlacement::collectViableSuccessors(
  540. const MachineBasicBlock *BB, const BlockChain &Chain,
  541. const BlockFilterSet *BlockFilter,
  542. SmallVector<MachineBasicBlock *, 4> &Successors) {
  543. // Adjust edge probabilities by excluding edges pointing to blocks that is
  544. // either not in BlockFilter or is already in the current chain. Consider the
  545. // following CFG:
  546. //
  547. // --->A
  548. // | / \
  549. // | B C
  550. // | \ / \
  551. // ----D E
  552. //
  553. // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after
  554. // A->C is chosen as a fall-through, D won't be selected as a successor of C
  555. // due to CFG constraint (the probability of C->D is not greater than
  556. // HotProb to break topo-order). If we exclude E that is not in BlockFilter
  557. // when calculating the probability of C->D, D will be selected and we
  558. // will get A C D B as the layout of this loop.
  559. auto AdjustedSumProb = BranchProbability::getOne();
  560. for (MachineBasicBlock *Succ : BB->successors()) {
  561. bool SkipSucc = false;
  562. if (Succ->isEHPad() || (BlockFilter && !BlockFilter->count(Succ))) {
  563. SkipSucc = true;
  564. } else {
  565. BlockChain *SuccChain = BlockToChain[Succ];
  566. if (SuccChain == &Chain) {
  567. SkipSucc = true;
  568. } else if (Succ != *SuccChain->begin()) {
  569. LLVM_DEBUG(dbgs() << " " << getBlockName(Succ)
  570. << " -> Mid chain!\n");
  571. continue;
  572. }
  573. }
  574. if (SkipSucc)
  575. AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ);
  576. else
  577. Successors.push_back(Succ);
  578. }
  579. return AdjustedSumProb;
  580. }
  581. /// The helper function returns the branch probability that is adjusted
  582. /// or normalized over the new total \p AdjustedSumProb.
  583. static BranchProbability
  584. getAdjustedProbability(BranchProbability OrigProb,
  585. BranchProbability AdjustedSumProb) {
  586. BranchProbability SuccProb;
  587. uint32_t SuccProbN = OrigProb.getNumerator();
  588. uint32_t SuccProbD = AdjustedSumProb.getNumerator();
  589. if (SuccProbN >= SuccProbD)
  590. SuccProb = BranchProbability::getOne();
  591. else
  592. SuccProb = BranchProbability(SuccProbN, SuccProbD);
  593. return SuccProb;
  594. }
  595. /// Check if \p BB has exactly the successors in \p Successors.
  596. static bool
  597. hasSameSuccessors(MachineBasicBlock &BB,
  598. SmallPtrSetImpl<const MachineBasicBlock *> &Successors) {
  599. if (BB.succ_size() != Successors.size())
  600. return false;
  601. // We don't want to count self-loops
  602. if (Successors.count(&BB))
  603. return false;
  604. for (MachineBasicBlock *Succ : BB.successors())
  605. if (!Successors.count(Succ))
  606. return false;
  607. return true;
  608. }
  609. /// Check if a block should be tail duplicated to increase fallthrough
  610. /// opportunities.
  611. /// \p BB Block to check.
  612. bool MachineBlockPlacement::shouldTailDuplicate(MachineBasicBlock *BB) {
  613. // Blocks with single successors don't create additional fallthrough
  614. // opportunities. Don't duplicate them. TODO: When conditional exits are
  615. // analyzable, allow them to be duplicated.
  616. bool IsSimple = TailDup.isSimpleBB(BB);
  617. if (BB->succ_size() == 1)
  618. return false;
  619. return TailDup.shouldTailDuplicate(IsSimple, *BB);
  620. }
  621. /// Compare 2 BlockFrequency's with a small penalty for \p A.
  622. /// In order to be conservative, we apply a X% penalty to account for
  623. /// increased icache pressure and static heuristics. For small frequencies
  624. /// we use only the numerators to improve accuracy. For simplicity, we assume the
  625. /// penalty is less than 100%
  626. /// TODO(iteratee): Use 64-bit fixed point edge frequencies everywhere.
  627. static bool greaterWithBias(BlockFrequency A, BlockFrequency B,
  628. uint64_t EntryFreq) {
  629. BranchProbability ThresholdProb(TailDupPlacementPenalty, 100);
  630. BlockFrequency Gain = A - B;
  631. return (Gain / ThresholdProb).getFrequency() >= EntryFreq;
  632. }
  633. /// Check the edge frequencies to see if tail duplication will increase
  634. /// fallthroughs. It only makes sense to call this function when
  635. /// \p Succ would not be chosen otherwise. Tail duplication of \p Succ is
  636. /// always locally profitable if we would have picked \p Succ without
  637. /// considering duplication.
  638. bool MachineBlockPlacement::isProfitableToTailDup(
  639. const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
  640. BranchProbability QProb,
  641. const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
  642. // We need to do a probability calculation to make sure this is profitable.
  643. // First: does succ have a successor that post-dominates? This affects the
  644. // calculation. The 2 relevant cases are:
  645. // BB BB
  646. // | \Qout | \Qout
  647. // P| C |P C
  648. // = C' = C'
  649. // | /Qin | /Qin
  650. // | / | /
  651. // Succ Succ
  652. // / \ | \ V
  653. // U/ =V |U \
  654. // / \ = D
  655. // D E | /
  656. // | /
  657. // |/
  658. // PDom
  659. // '=' : Branch taken for that CFG edge
  660. // In the second case, Placing Succ while duplicating it into C prevents the
  661. // fallthrough of Succ into either D or PDom, because they now have C as an
  662. // unplaced predecessor
  663. // Start by figuring out which case we fall into
  664. MachineBasicBlock *PDom = nullptr;
  665. SmallVector<MachineBasicBlock *, 4> SuccSuccs;
  666. // Only scan the relevant successors
  667. auto AdjustedSuccSumProb =
  668. collectViableSuccessors(Succ, Chain, BlockFilter, SuccSuccs);
  669. BranchProbability PProb = MBPI->getEdgeProbability(BB, Succ);
  670. auto BBFreq = MBFI->getBlockFreq(BB);
  671. auto SuccFreq = MBFI->getBlockFreq(Succ);
  672. BlockFrequency P = BBFreq * PProb;
  673. BlockFrequency Qout = BBFreq * QProb;
  674. uint64_t EntryFreq = MBFI->getEntryFreq();
  675. // If there are no more successors, it is profitable to copy, as it strictly
  676. // increases fallthrough.
  677. if (SuccSuccs.size() == 0)
  678. return greaterWithBias(P, Qout, EntryFreq);
  679. auto BestSuccSucc = BranchProbability::getZero();
  680. // Find the PDom or the best Succ if no PDom exists.
  681. for (MachineBasicBlock *SuccSucc : SuccSuccs) {
  682. auto Prob = MBPI->getEdgeProbability(Succ, SuccSucc);
  683. if (Prob > BestSuccSucc)
  684. BestSuccSucc = Prob;
  685. if (PDom == nullptr)
  686. if (MPDT->dominates(SuccSucc, Succ)) {
  687. PDom = SuccSucc;
  688. break;
  689. }
  690. }
  691. // For the comparisons, we need to know Succ's best incoming edge that isn't
  692. // from BB.
  693. auto SuccBestPred = BlockFrequency(0);
  694. for (MachineBasicBlock *SuccPred : Succ->predecessors()) {
  695. if (SuccPred == Succ || SuccPred == BB
  696. || BlockToChain[SuccPred] == &Chain
  697. || (BlockFilter && !BlockFilter->count(SuccPred)))
  698. continue;
  699. auto Freq = MBFI->getBlockFreq(SuccPred)
  700. * MBPI->getEdgeProbability(SuccPred, Succ);
  701. if (Freq > SuccBestPred)
  702. SuccBestPred = Freq;
  703. }
  704. // Qin is Succ's best unplaced incoming edge that isn't BB
  705. BlockFrequency Qin = SuccBestPred;
  706. // If it doesn't have a post-dominating successor, here is the calculation:
  707. // BB BB
  708. // | \Qout | \
  709. // P| C | =
  710. // = C' | C
  711. // | /Qin | |
  712. // | / | C' (+Succ)
  713. // Succ Succ /|
  714. // / \ | \/ |
  715. // U/ =V | == |
  716. // / \ | / \|
  717. // D E D E
  718. // '=' : Branch taken for that CFG edge
  719. // Cost in the first case is: P + V
  720. // For this calculation, we always assume P > Qout. If Qout > P
  721. // The result of this function will be ignored at the caller.
  722. // Let F = SuccFreq - Qin
  723. // Cost in the second case is: Qout + min(Qin, F) * U + max(Qin, F) * V
  724. if (PDom == nullptr || !Succ->isSuccessor(PDom)) {
  725. BranchProbability UProb = BestSuccSucc;
  726. BranchProbability VProb = AdjustedSuccSumProb - UProb;
  727. BlockFrequency F = SuccFreq - Qin;
  728. BlockFrequency V = SuccFreq * VProb;
  729. BlockFrequency QinU = std::min(Qin, F) * UProb;
  730. BlockFrequency BaseCost = P + V;
  731. BlockFrequency DupCost = Qout + QinU + std::max(Qin, F) * VProb;
  732. return greaterWithBias(BaseCost, DupCost, EntryFreq);
  733. }
  734. BranchProbability UProb = MBPI->getEdgeProbability(Succ, PDom);
  735. BranchProbability VProb = AdjustedSuccSumProb - UProb;
  736. BlockFrequency U = SuccFreq * UProb;
  737. BlockFrequency V = SuccFreq * VProb;
  738. BlockFrequency F = SuccFreq - Qin;
  739. // If there is a post-dominating successor, here is the calculation:
  740. // BB BB BB BB
  741. // | \Qout | \ | \Qout | \
  742. // |P C | = |P C | =
  743. // = C' |P C = C' |P C
  744. // | /Qin | | | /Qin | |
  745. // | / | C' (+Succ) | / | C' (+Succ)
  746. // Succ Succ /| Succ Succ /|
  747. // | \ V | \/ | | \ V | \/ |
  748. // |U \ |U /\ =? |U = |U /\ |
  749. // = D = = =?| | D | = =|
  750. // | / |/ D | / |/ D
  751. // | / | / | = | /
  752. // |/ | / |/ | =
  753. // Dom Dom Dom Dom
  754. // '=' : Branch taken for that CFG edge
  755. // The cost for taken branches in the first case is P + U
  756. // Let F = SuccFreq - Qin
  757. // The cost in the second case (assuming independence), given the layout:
  758. // BB, Succ, (C+Succ), D, Dom or the layout:
  759. // BB, Succ, D, Dom, (C+Succ)
  760. // is Qout + max(F, Qin) * U + min(F, Qin)
  761. // compare P + U vs Qout + P * U + Qin.
  762. //
  763. // The 3rd and 4th cases cover when Dom would be chosen to follow Succ.
  764. //
  765. // For the 3rd case, the cost is P + 2 * V
  766. // For the 4th case, the cost is Qout + min(Qin, F) * U + max(Qin, F) * V + V
  767. // We choose 4 over 3 when (P + V) > Qout + min(Qin, F) * U + max(Qin, F) * V
  768. if (UProb > AdjustedSuccSumProb / 2 &&
  769. !hasBetterLayoutPredecessor(Succ, PDom, *BlockToChain[PDom], UProb, UProb,
  770. Chain, BlockFilter))
  771. // Cases 3 & 4
  772. return greaterWithBias(
  773. (P + V), (Qout + std::max(Qin, F) * VProb + std::min(Qin, F) * UProb),
  774. EntryFreq);
  775. // Cases 1 & 2
  776. return greaterWithBias((P + U),
  777. (Qout + std::min(Qin, F) * AdjustedSuccSumProb +
  778. std::max(Qin, F) * UProb),
  779. EntryFreq);
  780. }
  781. /// Check for a trellis layout. \p BB is the upper part of a trellis if its
  782. /// successors form the lower part of a trellis. A successor set S forms the
  783. /// lower part of a trellis if all of the predecessors of S are either in S or
  784. /// have all of S as successors. We ignore trellises where BB doesn't have 2
  785. /// successors because for fewer than 2, it's trivial, and for 3 or greater they
  786. /// are very uncommon and complex to compute optimally. Allowing edges within S
  787. /// is not strictly a trellis, but the same algorithm works, so we allow it.
  788. bool MachineBlockPlacement::isTrellis(
  789. const MachineBasicBlock *BB,
  790. const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
  791. const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
  792. // Technically BB could form a trellis with branching factor higher than 2.
  793. // But that's extremely uncommon.
  794. if (BB->succ_size() != 2 || ViableSuccs.size() != 2)
  795. return false;
  796. SmallPtrSet<const MachineBasicBlock *, 2> Successors(BB->succ_begin(),
  797. BB->succ_end());
  798. // To avoid reviewing the same predecessors twice.
  799. SmallPtrSet<const MachineBasicBlock *, 8> SeenPreds;
  800. for (MachineBasicBlock *Succ : ViableSuccs) {
  801. int PredCount = 0;
  802. for (auto SuccPred : Succ->predecessors()) {
  803. // Allow triangle successors, but don't count them.
  804. if (Successors.count(SuccPred)) {
  805. // Make sure that it is actually a triangle.
  806. for (MachineBasicBlock *CheckSucc : SuccPred->successors())
  807. if (!Successors.count(CheckSucc))
  808. return false;
  809. continue;
  810. }
  811. const BlockChain *PredChain = BlockToChain[SuccPred];
  812. if (SuccPred == BB || (BlockFilter && !BlockFilter->count(SuccPred)) ||
  813. PredChain == &Chain || PredChain == BlockToChain[Succ])
  814. continue;
  815. ++PredCount;
  816. // Perform the successor check only once.
  817. if (!SeenPreds.insert(SuccPred).second)
  818. continue;
  819. if (!hasSameSuccessors(*SuccPred, Successors))
  820. return false;
  821. }
  822. // If one of the successors has only BB as a predecessor, it is not a
  823. // trellis.
  824. if (PredCount < 1)
  825. return false;
  826. }
  827. return true;
  828. }
  829. /// Pick the highest total weight pair of edges that can both be laid out.
  830. /// The edges in \p Edges[0] are assumed to have a different destination than
  831. /// the edges in \p Edges[1]. Simple counting shows that the best pair is either
  832. /// the individual highest weight edges to the 2 different destinations, or in
  833. /// case of a conflict, one of them should be replaced with a 2nd best edge.
  834. std::pair<MachineBlockPlacement::WeightedEdge,
  835. MachineBlockPlacement::WeightedEdge>
  836. MachineBlockPlacement::getBestNonConflictingEdges(
  837. const MachineBasicBlock *BB,
  838. MutableArrayRef<SmallVector<MachineBlockPlacement::WeightedEdge, 8>>
  839. Edges) {
  840. // Sort the edges, and then for each successor, find the best incoming
  841. // predecessor. If the best incoming predecessors aren't the same,
  842. // then that is clearly the best layout. If there is a conflict, one of the
  843. // successors will have to fallthrough from the second best predecessor. We
  844. // compare which combination is better overall.
  845. // Sort for highest frequency.
  846. auto Cmp = [](WeightedEdge A, WeightedEdge B) { return A.Weight > B.Weight; };
  847. std::stable_sort(Edges[0].begin(), Edges[0].end(), Cmp);
  848. std::stable_sort(Edges[1].begin(), Edges[1].end(), Cmp);
  849. auto BestA = Edges[0].begin();
  850. auto BestB = Edges[1].begin();
  851. // Arrange for the correct answer to be in BestA and BestB
  852. // If the 2 best edges don't conflict, the answer is already there.
  853. if (BestA->Src == BestB->Src) {
  854. // Compare the total fallthrough of (Best + Second Best) for both pairs
  855. auto SecondBestA = std::next(BestA);
  856. auto SecondBestB = std::next(BestB);
  857. BlockFrequency BestAScore = BestA->Weight + SecondBestB->Weight;
  858. BlockFrequency BestBScore = BestB->Weight + SecondBestA->Weight;
  859. if (BestAScore < BestBScore)
  860. BestA = SecondBestA;
  861. else
  862. BestB = SecondBestB;
  863. }
  864. // Arrange for the BB edge to be in BestA if it exists.
  865. if (BestB->Src == BB)
  866. std::swap(BestA, BestB);
  867. return std::make_pair(*BestA, *BestB);
  868. }
  869. /// Get the best successor from \p BB based on \p BB being part of a trellis.
  870. /// We only handle trellises with 2 successors, so the algorithm is
  871. /// straightforward: Find the best pair of edges that don't conflict. We find
  872. /// the best incoming edge for each successor in the trellis. If those conflict,
  873. /// we consider which of them should be replaced with the second best.
  874. /// Upon return the two best edges will be in \p BestEdges. If one of the edges
  875. /// comes from \p BB, it will be in \p BestEdges[0]
  876. MachineBlockPlacement::BlockAndTailDupResult
  877. MachineBlockPlacement::getBestTrellisSuccessor(
  878. const MachineBasicBlock *BB,
  879. const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
  880. BranchProbability AdjustedSumProb, const BlockChain &Chain,
  881. const BlockFilterSet *BlockFilter) {
  882. BlockAndTailDupResult Result = {nullptr, false};
  883. SmallPtrSet<const MachineBasicBlock *, 4> Successors(BB->succ_begin(),
  884. BB->succ_end());
  885. // We assume size 2 because it's common. For general n, we would have to do
  886. // the Hungarian algorithm, but it's not worth the complexity because more
  887. // than 2 successors is fairly uncommon, and a trellis even more so.
  888. if (Successors.size() != 2 || ViableSuccs.size() != 2)
  889. return Result;
  890. // Collect the edge frequencies of all edges that form the trellis.
  891. SmallVector<WeightedEdge, 8> Edges[2];
  892. int SuccIndex = 0;
  893. for (auto Succ : ViableSuccs) {
  894. for (MachineBasicBlock *SuccPred : Succ->predecessors()) {
  895. // Skip any placed predecessors that are not BB
  896. if (SuccPred != BB)
  897. if ((BlockFilter && !BlockFilter->count(SuccPred)) ||
  898. BlockToChain[SuccPred] == &Chain ||
  899. BlockToChain[SuccPred] == BlockToChain[Succ])
  900. continue;
  901. BlockFrequency EdgeFreq = MBFI->getBlockFreq(SuccPred) *
  902. MBPI->getEdgeProbability(SuccPred, Succ);
  903. Edges[SuccIndex].push_back({EdgeFreq, SuccPred, Succ});
  904. }
  905. ++SuccIndex;
  906. }
  907. // Pick the best combination of 2 edges from all the edges in the trellis.
  908. WeightedEdge BestA, BestB;
  909. std::tie(BestA, BestB) = getBestNonConflictingEdges(BB, Edges);
  910. if (BestA.Src != BB) {
  911. // If we have a trellis, and BB doesn't have the best fallthrough edges,
  912. // we shouldn't choose any successor. We've already looked and there's a
  913. // better fallthrough edge for all the successors.
  914. LLVM_DEBUG(dbgs() << "Trellis, but not one of the chosen edges.\n");
  915. return Result;
  916. }
  917. // Did we pick the triangle edge? If tail-duplication is profitable, do
  918. // that instead. Otherwise merge the triangle edge now while we know it is
  919. // optimal.
  920. if (BestA.Dest == BestB.Src) {
  921. // The edges are BB->Succ1->Succ2, and we're looking to see if BB->Succ2
  922. // would be better.
  923. MachineBasicBlock *Succ1 = BestA.Dest;
  924. MachineBasicBlock *Succ2 = BestB.Dest;
  925. // Check to see if tail-duplication would be profitable.
  926. if (allowTailDupPlacement() && shouldTailDuplicate(Succ2) &&
  927. canTailDuplicateUnplacedPreds(BB, Succ2, Chain, BlockFilter) &&
  928. isProfitableToTailDup(BB, Succ2, MBPI->getEdgeProbability(BB, Succ1),
  929. Chain, BlockFilter)) {
  930. LLVM_DEBUG(BranchProbability Succ2Prob = getAdjustedProbability(
  931. MBPI->getEdgeProbability(BB, Succ2), AdjustedSumProb);
  932. dbgs() << " Selected: " << getBlockName(Succ2)
  933. << ", probability: " << Succ2Prob
  934. << " (Tail Duplicate)\n");
  935. Result.BB = Succ2;
  936. Result.ShouldTailDup = true;
  937. return Result;
  938. }
  939. }
  940. // We have already computed the optimal edge for the other side of the
  941. // trellis.
  942. ComputedEdges[BestB.Src] = { BestB.Dest, false };
  943. auto TrellisSucc = BestA.Dest;
  944. LLVM_DEBUG(BranchProbability SuccProb = getAdjustedProbability(
  945. MBPI->getEdgeProbability(BB, TrellisSucc), AdjustedSumProb);
  946. dbgs() << " Selected: " << getBlockName(TrellisSucc)
  947. << ", probability: " << SuccProb << " (Trellis)\n");
  948. Result.BB = TrellisSucc;
  949. return Result;
  950. }
  951. /// When the option allowTailDupPlacement() is on, this method checks if the
  952. /// fallthrough candidate block \p Succ (of block \p BB) can be tail-duplicated
  953. /// into all of its unplaced, unfiltered predecessors, that are not BB.
  954. bool MachineBlockPlacement::canTailDuplicateUnplacedPreds(
  955. const MachineBasicBlock *BB, MachineBasicBlock *Succ,
  956. const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
  957. if (!shouldTailDuplicate(Succ))
  958. return false;
  959. // For CFG checking.
  960. SmallPtrSet<const MachineBasicBlock *, 4> Successors(BB->succ_begin(),
  961. BB->succ_end());
  962. for (MachineBasicBlock *Pred : Succ->predecessors()) {
  963. // Make sure all unplaced and unfiltered predecessors can be
  964. // tail-duplicated into.
  965. // Skip any blocks that are already placed or not in this loop.
  966. if (Pred == BB || (BlockFilter && !BlockFilter->count(Pred))
  967. || BlockToChain[Pred] == &Chain)
  968. continue;
  969. if (!TailDup.canTailDuplicate(Succ, Pred)) {
  970. if (Successors.size() > 1 && hasSameSuccessors(*Pred, Successors))
  971. // This will result in a trellis after tail duplication, so we don't
  972. // need to copy Succ into this predecessor. In the presence
  973. // of a trellis tail duplication can continue to be profitable.
  974. // For example:
  975. // A A
  976. // |\ |\
  977. // | \ | \
  978. // | C | C+BB
  979. // | / | |
  980. // |/ | |
  981. // BB => BB |
  982. // |\ |\/|
  983. // | \ |/\|
  984. // | D | D
  985. // | / | /
  986. // |/ |/
  987. // Succ Succ
  988. //
  989. // After BB was duplicated into C, the layout looks like the one on the
  990. // right. BB and C now have the same successors. When considering
  991. // whether Succ can be duplicated into all its unplaced predecessors, we
  992. // ignore C.
  993. // We can do this because C already has a profitable fallthrough, namely
  994. // D. TODO(iteratee): ignore sufficiently cold predecessors for
  995. // duplication and for this test.
  996. //
  997. // This allows trellises to be laid out in 2 separate chains
  998. // (A,B,Succ,...) and later (C,D,...) This is a reasonable heuristic
  999. // because it allows the creation of 2 fallthrough paths with links
  1000. // between them, and we correctly identify the best layout for these
  1001. // CFGs. We want to extend trellises that the user created in addition
  1002. // to trellises created by tail-duplication, so we just look for the
  1003. // CFG.
  1004. continue;
  1005. return false;
  1006. }
  1007. }
  1008. return true;
  1009. }
  1010. /// Find chains of triangles where we believe it would be profitable to
  1011. /// tail-duplicate them all, but a local analysis would not find them.
  1012. /// There are 3 ways this can be profitable:
  1013. /// 1) The post-dominators marked 50% are actually taken 55% (This shrinks with
  1014. /// longer chains)
  1015. /// 2) The chains are statically correlated. Branch probabilities have a very
  1016. /// U-shaped distribution.
  1017. /// [http://nrs.harvard.edu/urn-3:HUL.InstRepos:24015805]
  1018. /// If the branches in a chain are likely to be from the same side of the
  1019. /// distribution as their predecessor, but are independent at runtime, this
  1020. /// transformation is profitable. (Because the cost of being wrong is a small
  1021. /// fixed cost, unlike the standard triangle layout where the cost of being
  1022. /// wrong scales with the # of triangles.)
  1023. /// 3) The chains are dynamically correlated. If the probability that a previous
  1024. /// branch was taken positively influences whether the next branch will be
  1025. /// taken
  1026. /// We believe that 2 and 3 are common enough to justify the small margin in 1.
  1027. void MachineBlockPlacement::precomputeTriangleChains() {
  1028. struct TriangleChain {
  1029. std::vector<MachineBasicBlock *> Edges;
  1030. TriangleChain(MachineBasicBlock *src, MachineBasicBlock *dst)
  1031. : Edges({src, dst}) {}
  1032. void append(MachineBasicBlock *dst) {
  1033. assert(getKey()->isSuccessor(dst) &&
  1034. "Attempting to append a block that is not a successor.");
  1035. Edges.push_back(dst);
  1036. }
  1037. unsigned count() const { return Edges.size() - 1; }
  1038. MachineBasicBlock *getKey() const {
  1039. return Edges.back();
  1040. }
  1041. };
  1042. if (TriangleChainCount == 0)
  1043. return;
  1044. LLVM_DEBUG(dbgs() << "Pre-computing triangle chains.\n");
  1045. // Map from last block to the chain that contains it. This allows us to extend
  1046. // chains as we find new triangles.
  1047. DenseMap<const MachineBasicBlock *, TriangleChain> TriangleChainMap;
  1048. for (MachineBasicBlock &BB : *F) {
  1049. // If BB doesn't have 2 successors, it doesn't start a triangle.
  1050. if (BB.succ_size() != 2)
  1051. continue;
  1052. MachineBasicBlock *PDom = nullptr;
  1053. for (MachineBasicBlock *Succ : BB.successors()) {
  1054. if (!MPDT->dominates(Succ, &BB))
  1055. continue;
  1056. PDom = Succ;
  1057. break;
  1058. }
  1059. // If BB doesn't have a post-dominating successor, it doesn't form a
  1060. // triangle.
  1061. if (PDom == nullptr)
  1062. continue;
  1063. // If PDom has a hint that it is low probability, skip this triangle.
  1064. if (MBPI->getEdgeProbability(&BB, PDom) < BranchProbability(50, 100))
  1065. continue;
  1066. // If PDom isn't eligible for duplication, this isn't the kind of triangle
  1067. // we're looking for.
  1068. if (!shouldTailDuplicate(PDom))
  1069. continue;
  1070. bool CanTailDuplicate = true;
  1071. // If PDom can't tail-duplicate into it's non-BB predecessors, then this
  1072. // isn't the kind of triangle we're looking for.
  1073. for (MachineBasicBlock* Pred : PDom->predecessors()) {
  1074. if (Pred == &BB)
  1075. continue;
  1076. if (!TailDup.canTailDuplicate(PDom, Pred)) {
  1077. CanTailDuplicate = false;
  1078. break;
  1079. }
  1080. }
  1081. // If we can't tail-duplicate PDom to its predecessors, then skip this
  1082. // triangle.
  1083. if (!CanTailDuplicate)
  1084. continue;
  1085. // Now we have an interesting triangle. Insert it if it's not part of an
  1086. // existing chain.
  1087. // Note: This cannot be replaced with a call insert() or emplace() because
  1088. // the find key is BB, but the insert/emplace key is PDom.
  1089. auto Found = TriangleChainMap.find(&BB);
  1090. // If it is, remove the chain from the map, grow it, and put it back in the
  1091. // map with the end as the new key.
  1092. if (Found != TriangleChainMap.end()) {
  1093. TriangleChain Chain = std::move(Found->second);
  1094. TriangleChainMap.erase(Found);
  1095. Chain.append(PDom);
  1096. TriangleChainMap.insert(std::make_pair(Chain.getKey(), std::move(Chain)));
  1097. } else {
  1098. auto InsertResult = TriangleChainMap.try_emplace(PDom, &BB, PDom);
  1099. assert(InsertResult.second && "Block seen twice.");
  1100. (void)InsertResult;
  1101. }
  1102. }
  1103. // Iterating over a DenseMap is safe here, because the only thing in the body
  1104. // of the loop is inserting into another DenseMap (ComputedEdges).
  1105. // ComputedEdges is never iterated, so this doesn't lead to non-determinism.
  1106. for (auto &ChainPair : TriangleChainMap) {
  1107. TriangleChain &Chain = ChainPair.second;
  1108. // Benchmarking has shown that due to branch correlation duplicating 2 or
  1109. // more triangles is profitable, despite the calculations assuming
  1110. // independence.
  1111. if (Chain.count() < TriangleChainCount)
  1112. continue;
  1113. MachineBasicBlock *dst = Chain.Edges.back();
  1114. Chain.Edges.pop_back();
  1115. for (MachineBasicBlock *src : reverse(Chain.Edges)) {
  1116. LLVM_DEBUG(dbgs() << "Marking edge: " << getBlockName(src) << "->"
  1117. << getBlockName(dst)
  1118. << " as pre-computed based on triangles.\n");
  1119. auto InsertResult = ComputedEdges.insert({src, {dst, true}});
  1120. assert(InsertResult.second && "Block seen twice.");
  1121. (void)InsertResult;
  1122. dst = src;
  1123. }
  1124. }
  1125. }
  1126. // When profile is not present, return the StaticLikelyProb.
  1127. // When profile is available, we need to handle the triangle-shape CFG.
  1128. static BranchProbability getLayoutSuccessorProbThreshold(
  1129. const MachineBasicBlock *BB) {
  1130. if (!BB->getParent()->getFunction().hasProfileData())
  1131. return BranchProbability(StaticLikelyProb, 100);
  1132. if (BB->succ_size() == 2) {
  1133. const MachineBasicBlock *Succ1 = *BB->succ_begin();
  1134. const MachineBasicBlock *Succ2 = *(BB->succ_begin() + 1);
  1135. if (Succ1->isSuccessor(Succ2) || Succ2->isSuccessor(Succ1)) {
  1136. /* See case 1 below for the cost analysis. For BB->Succ to
  1137. * be taken with smaller cost, the following needs to hold:
  1138. * Prob(BB->Succ) > 2 * Prob(BB->Pred)
  1139. * So the threshold T in the calculation below
  1140. * (1-T) * Prob(BB->Succ) > T * Prob(BB->Pred)
  1141. * So T / (1 - T) = 2, Yielding T = 2/3
  1142. * Also adding user specified branch bias, we have
  1143. * T = (2/3)*(ProfileLikelyProb/50)
  1144. * = (2*ProfileLikelyProb)/150)
  1145. */
  1146. return BranchProbability(2 * ProfileLikelyProb, 150);
  1147. }
  1148. }
  1149. return BranchProbability(ProfileLikelyProb, 100);
  1150. }
  1151. /// Checks to see if the layout candidate block \p Succ has a better layout
  1152. /// predecessor than \c BB. If yes, returns true.
  1153. /// \p SuccProb: The probability adjusted for only remaining blocks.
  1154. /// Only used for logging
  1155. /// \p RealSuccProb: The un-adjusted probability.
  1156. /// \p Chain: The chain that BB belongs to and Succ is being considered for.
  1157. /// \p BlockFilter: if non-null, the set of blocks that make up the loop being
  1158. /// considered
  1159. bool MachineBlockPlacement::hasBetterLayoutPredecessor(
  1160. const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
  1161. const BlockChain &SuccChain, BranchProbability SuccProb,
  1162. BranchProbability RealSuccProb, const BlockChain &Chain,
  1163. const BlockFilterSet *BlockFilter) {
  1164. // There isn't a better layout when there are no unscheduled predecessors.
  1165. if (SuccChain.UnscheduledPredecessors == 0)
  1166. return false;
  1167. // There are two basic scenarios here:
  1168. // -------------------------------------
  1169. // Case 1: triangular shape CFG (if-then):
  1170. // BB
  1171. // | \
  1172. // | \
  1173. // | Pred
  1174. // | /
  1175. // Succ
  1176. // In this case, we are evaluating whether to select edge -> Succ, e.g.
  1177. // set Succ as the layout successor of BB. Picking Succ as BB's
  1178. // successor breaks the CFG constraints (FIXME: define these constraints).
  1179. // With this layout, Pred BB
  1180. // is forced to be outlined, so the overall cost will be cost of the
  1181. // branch taken from BB to Pred, plus the cost of back taken branch
  1182. // from Pred to Succ, as well as the additional cost associated
  1183. // with the needed unconditional jump instruction from Pred To Succ.
  1184. // The cost of the topological order layout is the taken branch cost
  1185. // from BB to Succ, so to make BB->Succ a viable candidate, the following
  1186. // must hold:
  1187. // 2 * freq(BB->Pred) * taken_branch_cost + unconditional_jump_cost
  1188. // < freq(BB->Succ) * taken_branch_cost.
  1189. // Ignoring unconditional jump cost, we get
  1190. // freq(BB->Succ) > 2 * freq(BB->Pred), i.e.,
  1191. // prob(BB->Succ) > 2 * prob(BB->Pred)
  1192. //
  1193. // When real profile data is available, we can precisely compute the
  1194. // probability threshold that is needed for edge BB->Succ to be considered.
  1195. // Without profile data, the heuristic requires the branch bias to be
  1196. // a lot larger to make sure the signal is very strong (e.g. 80% default).
  1197. // -----------------------------------------------------------------
  1198. // Case 2: diamond like CFG (if-then-else):
  1199. // S
  1200. // / \
  1201. // | \
  1202. // BB Pred
  1203. // \ /
  1204. // Succ
  1205. // ..
  1206. //
  1207. // The current block is BB and edge BB->Succ is now being evaluated.
  1208. // Note that edge S->BB was previously already selected because
  1209. // prob(S->BB) > prob(S->Pred).
  1210. // At this point, 2 blocks can be placed after BB: Pred or Succ. If we
  1211. // choose Pred, we will have a topological ordering as shown on the left
  1212. // in the picture below. If we choose Succ, we have the solution as shown
  1213. // on the right:
  1214. //
  1215. // topo-order:
  1216. //
  1217. // S----- ---S
  1218. // | | | |
  1219. // ---BB | | BB
  1220. // | | | |
  1221. // | Pred-- | Succ--
  1222. // | | | |
  1223. // ---Succ ---Pred--
  1224. //
  1225. // cost = freq(S->Pred) + freq(BB->Succ) cost = 2 * freq (S->Pred)
  1226. // = freq(S->Pred) + freq(S->BB)
  1227. //
  1228. // If we have profile data (i.e, branch probabilities can be trusted), the
  1229. // cost (number of taken branches) with layout S->BB->Succ->Pred is 2 *
  1230. // freq(S->Pred) while the cost of topo order is freq(S->Pred) + freq(S->BB).
  1231. // We know Prob(S->BB) > Prob(S->Pred), so freq(S->BB) > freq(S->Pred), which
  1232. // means the cost of topological order is greater.
  1233. // When profile data is not available, however, we need to be more
  1234. // conservative. If the branch prediction is wrong, breaking the topo-order
  1235. // will actually yield a layout with large cost. For this reason, we need
  1236. // strong biased branch at block S with Prob(S->BB) in order to select
  1237. // BB->Succ. This is equivalent to looking the CFG backward with backward
  1238. // edge: Prob(Succ->BB) needs to >= HotProb in order to be selected (without
  1239. // profile data).
  1240. // --------------------------------------------------------------------------
  1241. // Case 3: forked diamond
  1242. // S
  1243. // / \
  1244. // / \
  1245. // BB Pred
  1246. // | \ / |
  1247. // | \ / |
  1248. // | X |
  1249. // | / \ |
  1250. // | / \ |
  1251. // S1 S2
  1252. //
  1253. // The current block is BB and edge BB->S1 is now being evaluated.
  1254. // As above S->BB was already selected because
  1255. // prob(S->BB) > prob(S->Pred). Assume that prob(BB->S1) >= prob(BB->S2).
  1256. //
  1257. // topo-order:
  1258. //
  1259. // S-------| ---S
  1260. // | | | |
  1261. // ---BB | | BB
  1262. // | | | |
  1263. // | Pred----| | S1----
  1264. // | | | |
  1265. // --(S1 or S2) ---Pred--
  1266. // |
  1267. // S2
  1268. //
  1269. // topo-cost = freq(S->Pred) + freq(BB->S1) + freq(BB->S2)
  1270. // + min(freq(Pred->S1), freq(Pred->S2))
  1271. // Non-topo-order cost:
  1272. // non-topo-cost = 2 * freq(S->Pred) + freq(BB->S2).
  1273. // To be conservative, we can assume that min(freq(Pred->S1), freq(Pred->S2))
  1274. // is 0. Then the non topo layout is better when
  1275. // freq(S->Pred) < freq(BB->S1).
  1276. // This is exactly what is checked below.
  1277. // Note there are other shapes that apply (Pred may not be a single block,
  1278. // but they all fit this general pattern.)
  1279. BranchProbability HotProb = getLayoutSuccessorProbThreshold(BB);
  1280. // Make sure that a hot successor doesn't have a globally more
  1281. // important predecessor.
  1282. BlockFrequency CandidateEdgeFreq = MBFI->getBlockFreq(BB) * RealSuccProb;
  1283. bool BadCFGConflict = false;
  1284. for (MachineBasicBlock *Pred : Succ->predecessors()) {
  1285. if (Pred == Succ || BlockToChain[Pred] == &SuccChain ||
  1286. (BlockFilter && !BlockFilter->count(Pred)) ||
  1287. BlockToChain[Pred] == &Chain ||
  1288. // This check is redundant except for look ahead. This function is
  1289. // called for lookahead by isProfitableToTailDup when BB hasn't been
  1290. // placed yet.
  1291. (Pred == BB))
  1292. continue;
  1293. // Do backward checking.
  1294. // For all cases above, we need a backward checking to filter out edges that
  1295. // are not 'strongly' biased.
  1296. // BB Pred
  1297. // \ /
  1298. // Succ
  1299. // We select edge BB->Succ if
  1300. // freq(BB->Succ) > freq(Succ) * HotProb
  1301. // i.e. freq(BB->Succ) > freq(BB->Succ) * HotProb + freq(Pred->Succ) *
  1302. // HotProb
  1303. // i.e. freq((BB->Succ) * (1 - HotProb) > freq(Pred->Succ) * HotProb
  1304. // Case 1 is covered too, because the first equation reduces to:
  1305. // prob(BB->Succ) > HotProb. (freq(Succ) = freq(BB) for a triangle)
  1306. BlockFrequency PredEdgeFreq =
  1307. MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
  1308. if (PredEdgeFreq * HotProb >= CandidateEdgeFreq * HotProb.getCompl()) {
  1309. BadCFGConflict = true;
  1310. break;
  1311. }
  1312. }
  1313. if (BadCFGConflict) {
  1314. LLVM_DEBUG(dbgs() << " Not a candidate: " << getBlockName(Succ) << " -> "
  1315. << SuccProb << " (prob) (non-cold CFG conflict)\n");
  1316. return true;
  1317. }
  1318. return false;
  1319. }
  1320. /// Select the best successor for a block.
  1321. ///
  1322. /// This looks across all successors of a particular block and attempts to
  1323. /// select the "best" one to be the layout successor. It only considers direct
  1324. /// successors which also pass the block filter. It will attempt to avoid
  1325. /// breaking CFG structure, but cave and break such structures in the case of
  1326. /// very hot successor edges.
  1327. ///
  1328. /// \returns The best successor block found, or null if none are viable, along
  1329. /// with a boolean indicating if tail duplication is necessary.
  1330. MachineBlockPlacement::BlockAndTailDupResult
  1331. MachineBlockPlacement::selectBestSuccessor(
  1332. const MachineBasicBlock *BB, const BlockChain &Chain,
  1333. const BlockFilterSet *BlockFilter) {
  1334. const BranchProbability HotProb(StaticLikelyProb, 100);
  1335. BlockAndTailDupResult BestSucc = { nullptr, false };
  1336. auto BestProb = BranchProbability::getZero();
  1337. SmallVector<MachineBasicBlock *, 4> Successors;
  1338. auto AdjustedSumProb =
  1339. collectViableSuccessors(BB, Chain, BlockFilter, Successors);
  1340. LLVM_DEBUG(dbgs() << "Selecting best successor for: " << getBlockName(BB)
  1341. << "\n");
  1342. // if we already precomputed the best successor for BB, return that if still
  1343. // applicable.
  1344. auto FoundEdge = ComputedEdges.find(BB);
  1345. if (FoundEdge != ComputedEdges.end()) {
  1346. MachineBasicBlock *Succ = FoundEdge->second.BB;
  1347. ComputedEdges.erase(FoundEdge);
  1348. BlockChain *SuccChain = BlockToChain[Succ];
  1349. if (BB->isSuccessor(Succ) && (!BlockFilter || BlockFilter->count(Succ)) &&
  1350. SuccChain != &Chain && Succ == *SuccChain->begin())
  1351. return FoundEdge->second;
  1352. }
  1353. // if BB is part of a trellis, Use the trellis to determine the optimal
  1354. // fallthrough edges
  1355. if (isTrellis(BB, Successors, Chain, BlockFilter))
  1356. return getBestTrellisSuccessor(BB, Successors, AdjustedSumProb, Chain,
  1357. BlockFilter);
  1358. // For blocks with CFG violations, we may be able to lay them out anyway with
  1359. // tail-duplication. We keep this vector so we can perform the probability
  1360. // calculations the minimum number of times.
  1361. SmallVector<std::tuple<BranchProbability, MachineBasicBlock *>, 4>
  1362. DupCandidates;
  1363. for (MachineBasicBlock *Succ : Successors) {
  1364. auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ);
  1365. BranchProbability SuccProb =
  1366. getAdjustedProbability(RealSuccProb, AdjustedSumProb);
  1367. BlockChain &SuccChain = *BlockToChain[Succ];
  1368. // Skip the edge \c BB->Succ if block \c Succ has a better layout
  1369. // predecessor that yields lower global cost.
  1370. if (hasBetterLayoutPredecessor(BB, Succ, SuccChain, SuccProb, RealSuccProb,
  1371. Chain, BlockFilter)) {
  1372. // If tail duplication would make Succ profitable, place it.
  1373. if (allowTailDupPlacement() && shouldTailDuplicate(Succ))
  1374. DupCandidates.push_back(std::make_tuple(SuccProb, Succ));
  1375. continue;
  1376. }
  1377. LLVM_DEBUG(
  1378. dbgs() << " Candidate: " << getBlockName(Succ)
  1379. << ", probability: " << SuccProb
  1380. << (SuccChain.UnscheduledPredecessors != 0 ? " (CFG break)" : "")
  1381. << "\n");
  1382. if (BestSucc.BB && BestProb >= SuccProb) {
  1383. LLVM_DEBUG(dbgs() << " Not the best candidate, continuing\n");
  1384. continue;
  1385. }
  1386. LLVM_DEBUG(dbgs() << " Setting it as best candidate\n");
  1387. BestSucc.BB = Succ;
  1388. BestProb = SuccProb;
  1389. }
  1390. // Handle the tail duplication candidates in order of decreasing probability.
  1391. // Stop at the first one that is profitable. Also stop if they are less
  1392. // profitable than BestSucc. Position is important because we preserve it and
  1393. // prefer first best match. Here we aren't comparing in order, so we capture
  1394. // the position instead.
  1395. if (DupCandidates.size() != 0) {
  1396. auto cmp =
  1397. [](const std::tuple<BranchProbability, MachineBasicBlock *> &a,
  1398. const std::tuple<BranchProbability, MachineBasicBlock *> &b) {
  1399. return std::get<0>(a) > std::get<0>(b);
  1400. };
  1401. std::stable_sort(DupCandidates.begin(), DupCandidates.end(), cmp);
  1402. }
  1403. for(auto &Tup : DupCandidates) {
  1404. BranchProbability DupProb;
  1405. MachineBasicBlock *Succ;
  1406. std::tie(DupProb, Succ) = Tup;
  1407. if (DupProb < BestProb)
  1408. break;
  1409. if (canTailDuplicateUnplacedPreds(BB, Succ, Chain, BlockFilter)
  1410. && (isProfitableToTailDup(BB, Succ, BestProb, Chain, BlockFilter))) {
  1411. LLVM_DEBUG(dbgs() << " Candidate: " << getBlockName(Succ)
  1412. << ", probability: " << DupProb
  1413. << " (Tail Duplicate)\n");
  1414. BestSucc.BB = Succ;
  1415. BestSucc.ShouldTailDup = true;
  1416. break;
  1417. }
  1418. }
  1419. if (BestSucc.BB)
  1420. LLVM_DEBUG(dbgs() << " Selected: " << getBlockName(BestSucc.BB) << "\n");
  1421. return BestSucc;
  1422. }
  1423. /// Select the best block from a worklist.
  1424. ///
  1425. /// This looks through the provided worklist as a list of candidate basic
  1426. /// blocks and select the most profitable one to place. The definition of
  1427. /// profitable only really makes sense in the context of a loop. This returns
  1428. /// the most frequently visited block in the worklist, which in the case of
  1429. /// a loop, is the one most desirable to be physically close to the rest of the
  1430. /// loop body in order to improve i-cache behavior.
  1431. ///
  1432. /// \returns The best block found, or null if none are viable.
  1433. MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
  1434. const BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList) {
  1435. // Once we need to walk the worklist looking for a candidate, cleanup the
  1436. // worklist of already placed entries.
  1437. // FIXME: If this shows up on profiles, it could be folded (at the cost of
  1438. // some code complexity) into the loop below.
  1439. WorkList.erase(llvm::remove_if(WorkList,
  1440. [&](MachineBasicBlock *BB) {
  1441. return BlockToChain.lookup(BB) == &Chain;
  1442. }),
  1443. WorkList.end());
  1444. if (WorkList.empty())
  1445. return nullptr;
  1446. bool IsEHPad = WorkList[0]->isEHPad();
  1447. MachineBasicBlock *BestBlock = nullptr;
  1448. BlockFrequency BestFreq;
  1449. for (MachineBasicBlock *MBB : WorkList) {
  1450. assert(MBB->isEHPad() == IsEHPad &&
  1451. "EHPad mismatch between block and work list.");
  1452. BlockChain &SuccChain = *BlockToChain[MBB];
  1453. if (&SuccChain == &Chain)
  1454. continue;
  1455. assert(SuccChain.UnscheduledPredecessors == 0 &&
  1456. "Found CFG-violating block");
  1457. BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
  1458. LLVM_DEBUG(dbgs() << " " << getBlockName(MBB) << " -> ";
  1459. MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
  1460. // For ehpad, we layout the least probable first as to avoid jumping back
  1461. // from least probable landingpads to more probable ones.
  1462. //
  1463. // FIXME: Using probability is probably (!) not the best way to achieve
  1464. // this. We should probably have a more principled approach to layout
  1465. // cleanup code.
  1466. //
  1467. // The goal is to get:
  1468. //
  1469. // +--------------------------+
  1470. // | V
  1471. // InnerLp -> InnerCleanup OuterLp -> OuterCleanup -> Resume
  1472. //
  1473. // Rather than:
  1474. //
  1475. // +-------------------------------------+
  1476. // V |
  1477. // OuterLp -> OuterCleanup -> Resume InnerLp -> InnerCleanup
  1478. if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq)))
  1479. continue;
  1480. BestBlock = MBB;
  1481. BestFreq = CandidateFreq;
  1482. }
  1483. return BestBlock;
  1484. }
  1485. /// Retrieve the first unplaced basic block.
  1486. ///
  1487. /// This routine is called when we are unable to use the CFG to walk through
  1488. /// all of the basic blocks and form a chain due to unnatural loops in the CFG.
  1489. /// We walk through the function's blocks in order, starting from the
  1490. /// LastUnplacedBlockIt. We update this iterator on each call to avoid
  1491. /// re-scanning the entire sequence on repeated calls to this routine.
  1492. MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
  1493. const BlockChain &PlacedChain,
  1494. MachineFunction::iterator &PrevUnplacedBlockIt,
  1495. const BlockFilterSet *BlockFilter) {
  1496. for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F->end(); I != E;
  1497. ++I) {
  1498. if (BlockFilter && !BlockFilter->count(&*I))
  1499. continue;
  1500. if (BlockToChain[&*I] != &PlacedChain) {
  1501. PrevUnplacedBlockIt = I;
  1502. // Now select the head of the chain to which the unplaced block belongs
  1503. // as the block to place. This will force the entire chain to be placed,
  1504. // and satisfies the requirements of merging chains.
  1505. return *BlockToChain[&*I]->begin();
  1506. }
  1507. }
  1508. return nullptr;
  1509. }
  1510. void MachineBlockPlacement::fillWorkLists(
  1511. const MachineBasicBlock *MBB,
  1512. SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
  1513. const BlockFilterSet *BlockFilter = nullptr) {
  1514. BlockChain &Chain = *BlockToChain[MBB];
  1515. if (!UpdatedPreds.insert(&Chain).second)
  1516. return;
  1517. assert(
  1518. Chain.UnscheduledPredecessors == 0 &&
  1519. "Attempting to place block with unscheduled predecessors in worklist.");
  1520. for (MachineBasicBlock *ChainBB : Chain) {
  1521. assert(BlockToChain[ChainBB] == &Chain &&
  1522. "Block in chain doesn't match BlockToChain map.");
  1523. for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
  1524. if (BlockFilter && !BlockFilter->count(Pred))
  1525. continue;
  1526. if (BlockToChain[Pred] == &Chain)
  1527. continue;
  1528. ++Chain.UnscheduledPredecessors;
  1529. }
  1530. }
  1531. if (Chain.UnscheduledPredecessors != 0)
  1532. return;
  1533. MachineBasicBlock *BB = *Chain.begin();
  1534. if (BB->isEHPad())
  1535. EHPadWorkList.push_back(BB);
  1536. else
  1537. BlockWorkList.push_back(BB);
  1538. }
  1539. void MachineBlockPlacement::buildChain(
  1540. const MachineBasicBlock *HeadBB, BlockChain &Chain,
  1541. BlockFilterSet *BlockFilter) {
  1542. assert(HeadBB && "BB must not be null.\n");
  1543. assert(BlockToChain[HeadBB] == &Chain && "BlockToChainMap mis-match.\n");
  1544. MachineFunction::iterator PrevUnplacedBlockIt = F->begin();
  1545. const MachineBasicBlock *LoopHeaderBB = HeadBB;
  1546. markChainSuccessors(Chain, LoopHeaderBB, BlockFilter);
  1547. MachineBasicBlock *BB = *std::prev(Chain.end());
  1548. while (true) {
  1549. assert(BB && "null block found at end of chain in loop.");
  1550. assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match in loop.");
  1551. assert(*std::prev(Chain.end()) == BB && "BB Not found at end of chain.");
  1552. // Look for the best viable successor if there is one to place immediately
  1553. // after this block.
  1554. auto Result = selectBestSuccessor(BB, Chain, BlockFilter);
  1555. MachineBasicBlock* BestSucc = Result.BB;
  1556. bool ShouldTailDup = Result.ShouldTailDup;
  1557. if (allowTailDupPlacement())
  1558. ShouldTailDup |= (BestSucc && shouldTailDuplicate(BestSucc));
  1559. // If an immediate successor isn't available, look for the best viable
  1560. // block among those we've identified as not violating the loop's CFG at
  1561. // this point. This won't be a fallthrough, but it will increase locality.
  1562. if (!BestSucc)
  1563. BestSucc = selectBestCandidateBlock(Chain, BlockWorkList);
  1564. if (!BestSucc)
  1565. BestSucc = selectBestCandidateBlock(Chain, EHPadWorkList);
  1566. if (!BestSucc) {
  1567. BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockIt, BlockFilter);
  1568. if (!BestSucc)
  1569. break;
  1570. LLVM_DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
  1571. "layout successor until the CFG reduces\n");
  1572. }
  1573. // Placement may have changed tail duplication opportunities.
  1574. // Check for that now.
  1575. if (allowTailDupPlacement() && BestSucc && ShouldTailDup) {
  1576. // If the chosen successor was duplicated into all its predecessors,
  1577. // don't bother laying it out, just go round the loop again with BB as
  1578. // the chain end.
  1579. if (repeatedlyTailDuplicateBlock(BestSucc, BB, LoopHeaderBB, Chain,
  1580. BlockFilter, PrevUnplacedBlockIt))
  1581. continue;
  1582. }
  1583. // Place this block, updating the datastructures to reflect its placement.
  1584. BlockChain &SuccChain = *BlockToChain[BestSucc];
  1585. // Zero out UnscheduledPredecessors for the successor we're about to merge in case
  1586. // we selected a successor that didn't fit naturally into the CFG.
  1587. SuccChain.UnscheduledPredecessors = 0;
  1588. LLVM_DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to "
  1589. << getBlockName(BestSucc) << "\n");
  1590. markChainSuccessors(SuccChain, LoopHeaderBB, BlockFilter);
  1591. Chain.merge(BestSucc, &SuccChain);
  1592. BB = *std::prev(Chain.end());
  1593. }
  1594. LLVM_DEBUG(dbgs() << "Finished forming chain for header block "
  1595. << getBlockName(*Chain.begin()) << "\n");
  1596. }
  1597. // If bottom of block BB has only one successor OldTop, in most cases it is
  1598. // profitable to move it before OldTop, except the following case:
  1599. //
  1600. // -->OldTop<-
  1601. // | . |
  1602. // | . |
  1603. // | . |
  1604. // ---Pred |
  1605. // | |
  1606. // BB-----
  1607. //
  1608. // If BB is moved before OldTop, Pred needs a taken branch to BB, and it can't
  1609. // layout the other successor below it, so it can't reduce taken branch.
  1610. // In this case we keep its original layout.
  1611. bool
  1612. MachineBlockPlacement::canMoveBottomBlockToTop(
  1613. const MachineBasicBlock *BottomBlock,
  1614. const MachineBasicBlock *OldTop) {
  1615. if (BottomBlock->pred_size() != 1)
  1616. return true;
  1617. MachineBasicBlock *Pred = *BottomBlock->pred_begin();
  1618. if (Pred->succ_size() != 2)
  1619. return true;
  1620. MachineBasicBlock *OtherBB = *Pred->succ_begin();
  1621. if (OtherBB == BottomBlock)
  1622. OtherBB = *Pred->succ_rbegin();
  1623. if (OtherBB == OldTop)
  1624. return false;
  1625. return true;
  1626. }
  1627. /// Find the best loop top block for layout.
  1628. ///
  1629. /// Look for a block which is strictly better than the loop header for laying
  1630. /// out at the top of the loop. This looks for one and only one pattern:
  1631. /// a latch block with no conditional exit. This block will cause a conditional
  1632. /// jump around it or will be the bottom of the loop if we lay it out in place,
  1633. /// but if it it doesn't end up at the bottom of the loop for any reason,
  1634. /// rotation alone won't fix it. Because such a block will always result in an
  1635. /// unconditional jump (for the backedge) rotating it in front of the loop
  1636. /// header is always profitable.
  1637. MachineBasicBlock *
  1638. MachineBlockPlacement::findBestLoopTop(const MachineLoop &L,
  1639. const BlockFilterSet &LoopBlockSet) {
  1640. // Placing the latch block before the header may introduce an extra branch
  1641. // that skips this block the first time the loop is executed, which we want
  1642. // to avoid when optimising for size.
  1643. // FIXME: in theory there is a case that does not introduce a new branch,
  1644. // i.e. when the layout predecessor does not fallthrough to the loop header.
  1645. // In practice this never happens though: there always seems to be a preheader
  1646. // that can fallthrough and that is also placed before the header.
  1647. if (F->getFunction().hasOptSize())
  1648. return L.getHeader();
  1649. // Check that the header hasn't been fused with a preheader block due to
  1650. // crazy branches. If it has, we need to start with the header at the top to
  1651. // prevent pulling the preheader into the loop body.
  1652. BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
  1653. if (!LoopBlockSet.count(*HeaderChain.begin()))
  1654. return L.getHeader();
  1655. LLVM_DEBUG(dbgs() << "Finding best loop top for: "
  1656. << getBlockName(L.getHeader()) << "\n");
  1657. BlockFrequency BestPredFreq;
  1658. MachineBasicBlock *BestPred = nullptr;
  1659. for (MachineBasicBlock *Pred : L.getHeader()->predecessors()) {
  1660. if (!LoopBlockSet.count(Pred))
  1661. continue;
  1662. LLVM_DEBUG(dbgs() << " header pred: " << getBlockName(Pred) << ", has "
  1663. << Pred->succ_size() << " successors, ";
  1664. MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
  1665. if (Pred->succ_size() > 1)
  1666. continue;
  1667. if (!canMoveBottomBlockToTop(Pred, L.getHeader()))
  1668. continue;
  1669. BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
  1670. if (!BestPred || PredFreq > BestPredFreq ||
  1671. (!(PredFreq < BestPredFreq) &&
  1672. Pred->isLayoutSuccessor(L.getHeader()))) {
  1673. BestPred = Pred;
  1674. BestPredFreq = PredFreq;
  1675. }
  1676. }
  1677. // If no direct predecessor is fine, just use the loop header.
  1678. if (!BestPred) {
  1679. LLVM_DEBUG(dbgs() << " final top unchanged\n");
  1680. return L.getHeader();
  1681. }
  1682. // Walk backwards through any straight line of predecessors.
  1683. while (BestPred->pred_size() == 1 &&
  1684. (*BestPred->pred_begin())->succ_size() == 1 &&
  1685. *BestPred->pred_begin() != L.getHeader())
  1686. BestPred = *BestPred->pred_begin();
  1687. LLVM_DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n");
  1688. return BestPred;
  1689. }
  1690. /// Find the best loop exiting block for layout.
  1691. ///
  1692. /// This routine implements the logic to analyze the loop looking for the best
  1693. /// block to layout at the top of the loop. Typically this is done to maximize
  1694. /// fallthrough opportunities.
  1695. MachineBasicBlock *
  1696. MachineBlockPlacement::findBestLoopExit(const MachineLoop &L,
  1697. const BlockFilterSet &LoopBlockSet) {
  1698. // We don't want to layout the loop linearly in all cases. If the loop header
  1699. // is just a normal basic block in the loop, we want to look for what block
  1700. // within the loop is the best one to layout at the top. However, if the loop
  1701. // header has be pre-merged into a chain due to predecessors not having
  1702. // analyzable branches, *and* the predecessor it is merged with is *not* part
  1703. // of the loop, rotating the header into the middle of the loop will create
  1704. // a non-contiguous range of blocks which is Very Bad. So start with the
  1705. // header and only rotate if safe.
  1706. BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
  1707. if (!LoopBlockSet.count(*HeaderChain.begin()))
  1708. return nullptr;
  1709. BlockFrequency BestExitEdgeFreq;
  1710. unsigned BestExitLoopDepth = 0;
  1711. MachineBasicBlock *ExitingBB = nullptr;
  1712. // If there are exits to outer loops, loop rotation can severely limit
  1713. // fallthrough opportunities unless it selects such an exit. Keep a set of
  1714. // blocks where rotating to exit with that block will reach an outer loop.
  1715. SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
  1716. LLVM_DEBUG(dbgs() << "Finding best loop exit for: "
  1717. << getBlockName(L.getHeader()) << "\n");
  1718. for (MachineBasicBlock *MBB : L.getBlocks()) {
  1719. BlockChain &Chain = *BlockToChain[MBB];
  1720. // Ensure that this block is at the end of a chain; otherwise it could be
  1721. // mid-way through an inner loop or a successor of an unanalyzable branch.
  1722. if (MBB != *std::prev(Chain.end()))
  1723. continue;
  1724. // Now walk the successors. We need to establish whether this has a viable
  1725. // exiting successor and whether it has a viable non-exiting successor.
  1726. // We store the old exiting state and restore it if a viable looping
  1727. // successor isn't found.
  1728. MachineBasicBlock *OldExitingBB = ExitingBB;
  1729. BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
  1730. bool HasLoopingSucc = false;
  1731. for (MachineBasicBlock *Succ : MBB->successors()) {
  1732. if (Succ->isEHPad())
  1733. continue;
  1734. if (Succ == MBB)
  1735. continue;
  1736. BlockChain &SuccChain = *BlockToChain[Succ];
  1737. // Don't split chains, either this chain or the successor's chain.
  1738. if (&Chain == &SuccChain) {
  1739. LLVM_DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
  1740. << getBlockName(Succ) << " (chain conflict)\n");
  1741. continue;
  1742. }
  1743. auto SuccProb = MBPI->getEdgeProbability(MBB, Succ);
  1744. if (LoopBlockSet.count(Succ)) {
  1745. LLVM_DEBUG(dbgs() << " looping: " << getBlockName(MBB) << " -> "
  1746. << getBlockName(Succ) << " (" << SuccProb << ")\n");
  1747. HasLoopingSucc = true;
  1748. continue;
  1749. }
  1750. unsigned SuccLoopDepth = 0;
  1751. if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
  1752. SuccLoopDepth = ExitLoop->getLoopDepth();
  1753. if (ExitLoop->contains(&L))
  1754. BlocksExitingToOuterLoop.insert(MBB);
  1755. }
  1756. BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
  1757. LLVM_DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
  1758. << getBlockName(Succ) << " [L:" << SuccLoopDepth
  1759. << "] (";
  1760. MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
  1761. // Note that we bias this toward an existing layout successor to retain
  1762. // incoming order in the absence of better information. The exit must have
  1763. // a frequency higher than the current exit before we consider breaking
  1764. // the layout.
  1765. BranchProbability Bias(100 - ExitBlockBias, 100);
  1766. if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
  1767. ExitEdgeFreq > BestExitEdgeFreq ||
  1768. (MBB->isLayoutSuccessor(Succ) &&
  1769. !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
  1770. BestExitEdgeFreq = ExitEdgeFreq;
  1771. ExitingBB = MBB;
  1772. }
  1773. }
  1774. if (!HasLoopingSucc) {
  1775. // Restore the old exiting state, no viable looping successor was found.
  1776. ExitingBB = OldExitingBB;
  1777. BestExitEdgeFreq = OldBestExitEdgeFreq;
  1778. }
  1779. }
  1780. // Without a candidate exiting block or with only a single block in the
  1781. // loop, just use the loop header to layout the loop.
  1782. if (!ExitingBB) {
  1783. LLVM_DEBUG(
  1784. dbgs() << " No other candidate exit blocks, using loop header\n");
  1785. return nullptr;
  1786. }
  1787. if (L.getNumBlocks() == 1) {
  1788. LLVM_DEBUG(dbgs() << " Loop has 1 block, using loop header as exit\n");
  1789. return nullptr;
  1790. }
  1791. // Also, if we have exit blocks which lead to outer loops but didn't select
  1792. // one of them as the exiting block we are rotating toward, disable loop
  1793. // rotation altogether.
  1794. if (!BlocksExitingToOuterLoop.empty() &&
  1795. !BlocksExitingToOuterLoop.count(ExitingBB))
  1796. return nullptr;
  1797. LLVM_DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB)
  1798. << "\n");
  1799. return ExitingBB;
  1800. }
  1801. /// Check if there is a fallthrough to loop header Top.
  1802. ///
  1803. /// 1. Look for a Pred that can be layout before Top.
  1804. /// 2. Check if Top is the most possible successor of Pred.
  1805. bool
  1806. MachineBlockPlacement::hasViableTopFallthrough(
  1807. const MachineBasicBlock *Top,
  1808. const BlockFilterSet &LoopBlockSet) {
  1809. for (MachineBasicBlock *Pred : Top->predecessors()) {
  1810. BlockChain *PredChain = BlockToChain[Pred];
  1811. if (!LoopBlockSet.count(Pred) &&
  1812. (!PredChain || Pred == *std::prev(PredChain->end()))) {
  1813. // Found a Pred block can be placed before Top.
  1814. // Check if Top is the best successor of Pred.
  1815. auto TopProb = MBPI->getEdgeProbability(Pred, Top);
  1816. bool TopOK = true;
  1817. for (MachineBasicBlock *Succ : Pred->successors()) {
  1818. auto SuccProb = MBPI->getEdgeProbability(Pred, Succ);
  1819. BlockChain *SuccChain = BlockToChain[Succ];
  1820. // Check if Succ can be placed after Pred.
  1821. // Succ should not be in any chain, or it is the head of some chain.
  1822. if ((!SuccChain || Succ == *SuccChain->begin()) && SuccProb > TopProb) {
  1823. TopOK = false;
  1824. break;
  1825. }
  1826. }
  1827. if (TopOK)
  1828. return true;
  1829. }
  1830. }
  1831. return false;
  1832. }
  1833. /// Attempt to rotate an exiting block to the bottom of the loop.
  1834. ///
  1835. /// Once we have built a chain, try to rotate it to line up the hot exit block
  1836. /// with fallthrough out of the loop if doing so doesn't introduce unnecessary
  1837. /// branches. For example, if the loop has fallthrough into its header and out
  1838. /// of its bottom already, don't rotate it.
  1839. void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
  1840. const MachineBasicBlock *ExitingBB,
  1841. const BlockFilterSet &LoopBlockSet) {
  1842. if (!ExitingBB)
  1843. return;
  1844. MachineBasicBlock *Top = *LoopChain.begin();
  1845. MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
  1846. // If ExitingBB is already the last one in a chain then nothing to do.
  1847. if (Bottom == ExitingBB)
  1848. return;
  1849. bool ViableTopFallthrough = hasViableTopFallthrough(Top, LoopBlockSet);
  1850. // If the header has viable fallthrough, check whether the current loop
  1851. // bottom is a viable exiting block. If so, bail out as rotating will
  1852. // introduce an unnecessary branch.
  1853. if (ViableTopFallthrough) {
  1854. for (MachineBasicBlock *Succ : Bottom->successors()) {
  1855. BlockChain *SuccChain = BlockToChain[Succ];
  1856. if (!LoopBlockSet.count(Succ) &&
  1857. (!SuccChain || Succ == *SuccChain->begin()))
  1858. return;
  1859. }
  1860. }
  1861. BlockChain::iterator ExitIt = llvm::find(LoopChain, ExitingBB);
  1862. if (ExitIt == LoopChain.end())
  1863. return;
  1864. // Rotating a loop exit to the bottom when there is a fallthrough to top
  1865. // trades the entry fallthrough for an exit fallthrough.
  1866. // If there is no bottom->top edge, but the chosen exit block does have
  1867. // a fallthrough, we break that fallthrough for nothing in return.
  1868. // Let's consider an example. We have a built chain of basic blocks
  1869. // B1, B2, ..., Bn, where Bk is a ExitingBB - chosen exit block.
  1870. // By doing a rotation we get
  1871. // Bk+1, ..., Bn, B1, ..., Bk
  1872. // Break of fallthrough to B1 is compensated by a fallthrough from Bk.
  1873. // If we had a fallthrough Bk -> Bk+1 it is broken now.
  1874. // It might be compensated by fallthrough Bn -> B1.
  1875. // So we have a condition to avoid creation of extra branch by loop rotation.
  1876. // All below must be true to avoid loop rotation:
  1877. // If there is a fallthrough to top (B1)
  1878. // There was fallthrough from chosen exit block (Bk) to next one (Bk+1)
  1879. // There is no fallthrough from bottom (Bn) to top (B1).
  1880. // Please note that there is no exit fallthrough from Bn because we checked it
  1881. // above.
  1882. if (ViableTopFallthrough) {
  1883. assert(std::next(ExitIt) != LoopChain.end() &&
  1884. "Exit should not be last BB");
  1885. MachineBasicBlock *NextBlockInChain = *std::next(ExitIt);
  1886. if (ExitingBB->isSuccessor(NextBlockInChain))
  1887. if (!Bottom->isSuccessor(Top))
  1888. return;
  1889. }
  1890. LLVM_DEBUG(dbgs() << "Rotating loop to put exit " << getBlockName(ExitingBB)
  1891. << " at bottom\n");
  1892. std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
  1893. }
  1894. /// Attempt to rotate a loop based on profile data to reduce branch cost.
  1895. ///
  1896. /// With profile data, we can determine the cost in terms of missed fall through
  1897. /// opportunities when rotating a loop chain and select the best rotation.
  1898. /// Basically, there are three kinds of cost to consider for each rotation:
  1899. /// 1. The possibly missed fall through edge (if it exists) from BB out of
  1900. /// the loop to the loop header.
  1901. /// 2. The possibly missed fall through edges (if they exist) from the loop
  1902. /// exits to BB out of the loop.
  1903. /// 3. The missed fall through edge (if it exists) from the last BB to the
  1904. /// first BB in the loop chain.
  1905. /// Therefore, the cost for a given rotation is the sum of costs listed above.
  1906. /// We select the best rotation with the smallest cost.
  1907. void MachineBlockPlacement::rotateLoopWithProfile(
  1908. BlockChain &LoopChain, const MachineLoop &L,
  1909. const BlockFilterSet &LoopBlockSet) {
  1910. auto HeaderBB = L.getHeader();
  1911. auto HeaderIter = llvm::find(LoopChain, HeaderBB);
  1912. auto RotationPos = LoopChain.end();
  1913. BlockFrequency SmallestRotationCost = BlockFrequency::getMaxFrequency();
  1914. // A utility lambda that scales up a block frequency by dividing it by a
  1915. // branch probability which is the reciprocal of the scale.
  1916. auto ScaleBlockFrequency = [](BlockFrequency Freq,
  1917. unsigned Scale) -> BlockFrequency {
  1918. if (Scale == 0)
  1919. return 0;
  1920. // Use operator / between BlockFrequency and BranchProbability to implement
  1921. // saturating multiplication.
  1922. return Freq / BranchProbability(1, Scale);
  1923. };
  1924. // Compute the cost of the missed fall-through edge to the loop header if the
  1925. // chain head is not the loop header. As we only consider natural loops with
  1926. // single header, this computation can be done only once.
  1927. BlockFrequency HeaderFallThroughCost(0);
  1928. for (auto *Pred : HeaderBB->predecessors()) {
  1929. BlockChain *PredChain = BlockToChain[Pred];
  1930. if (!LoopBlockSet.count(Pred) &&
  1931. (!PredChain || Pred == *std::prev(PredChain->end()))) {
  1932. auto EdgeFreq =
  1933. MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, HeaderBB);
  1934. auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost);
  1935. // If the predecessor has only an unconditional jump to the header, we
  1936. // need to consider the cost of this jump.
  1937. if (Pred->succ_size() == 1)
  1938. FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost);
  1939. HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost);
  1940. }
  1941. }
  1942. // Here we collect all exit blocks in the loop, and for each exit we find out
  1943. // its hottest exit edge. For each loop rotation, we define the loop exit cost
  1944. // as the sum of frequencies of exit edges we collect here, excluding the exit
  1945. // edge from the tail of the loop chain.
  1946. SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq;
  1947. for (auto BB : LoopChain) {
  1948. auto LargestExitEdgeProb = BranchProbability::getZero();
  1949. for (auto *Succ : BB->successors()) {
  1950. BlockChain *SuccChain = BlockToChain[Succ];
  1951. if (!LoopBlockSet.count(Succ) &&
  1952. (!SuccChain || Succ == *SuccChain->begin())) {
  1953. auto SuccProb = MBPI->getEdgeProbability(BB, Succ);
  1954. LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb);
  1955. }
  1956. }
  1957. if (LargestExitEdgeProb > BranchProbability::getZero()) {
  1958. auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb;
  1959. ExitsWithFreq.emplace_back(BB, ExitFreq);
  1960. }
  1961. }
  1962. // In this loop we iterate every block in the loop chain and calculate the
  1963. // cost assuming the block is the head of the loop chain. When the loop ends,
  1964. // we should have found the best candidate as the loop chain's head.
  1965. for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()),
  1966. EndIter = LoopChain.end();
  1967. Iter != EndIter; Iter++, TailIter++) {
  1968. // TailIter is used to track the tail of the loop chain if the block we are
  1969. // checking (pointed by Iter) is the head of the chain.
  1970. if (TailIter == LoopChain.end())
  1971. TailIter = LoopChain.begin();
  1972. auto TailBB = *TailIter;
  1973. // Calculate the cost by putting this BB to the top.
  1974. BlockFrequency Cost = 0;
  1975. // If the current BB is the loop header, we need to take into account the
  1976. // cost of the missed fall through edge from outside of the loop to the
  1977. // header.
  1978. if (Iter != HeaderIter)
  1979. Cost += HeaderFallThroughCost;
  1980. // Collect the loop exit cost by summing up frequencies of all exit edges
  1981. // except the one from the chain tail.
  1982. for (auto &ExitWithFreq : ExitsWithFreq)
  1983. if (TailBB != ExitWithFreq.first)
  1984. Cost += ExitWithFreq.second;
  1985. // The cost of breaking the once fall-through edge from the tail to the top
  1986. // of the loop chain. Here we need to consider three cases:
  1987. // 1. If the tail node has only one successor, then we will get an
  1988. // additional jmp instruction. So the cost here is (MisfetchCost +
  1989. // JumpInstCost) * tail node frequency.
  1990. // 2. If the tail node has two successors, then we may still get an
  1991. // additional jmp instruction if the layout successor after the loop
  1992. // chain is not its CFG successor. Note that the more frequently executed
  1993. // jmp instruction will be put ahead of the other one. Assume the
  1994. // frequency of those two branches are x and y, where x is the frequency
  1995. // of the edge to the chain head, then the cost will be
  1996. // (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency.
  1997. // 3. If the tail node has more than two successors (this rarely happens),
  1998. // we won't consider any additional cost.
  1999. if (TailBB->isSuccessor(*Iter)) {
  2000. auto TailBBFreq = MBFI->getBlockFreq(TailBB);
  2001. if (TailBB->succ_size() == 1)
  2002. Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(),
  2003. MisfetchCost + JumpInstCost);
  2004. else if (TailBB->succ_size() == 2) {
  2005. auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter);
  2006. auto TailToHeadFreq = TailBBFreq * TailToHeadProb;
  2007. auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2)
  2008. ? TailBBFreq * TailToHeadProb.getCompl()
  2009. : TailToHeadFreq;
  2010. Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) +
  2011. ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost);
  2012. }
  2013. }
  2014. LLVM_DEBUG(dbgs() << "The cost of loop rotation by making "
  2015. << getBlockName(*Iter)
  2016. << " to the top: " << Cost.getFrequency() << "\n");
  2017. if (Cost < SmallestRotationCost) {
  2018. SmallestRotationCost = Cost;
  2019. RotationPos = Iter;
  2020. }
  2021. }
  2022. if (RotationPos != LoopChain.end()) {
  2023. LLVM_DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos)
  2024. << " to the top\n");
  2025. std::rotate(LoopChain.begin(), RotationPos, LoopChain.end());
  2026. }
  2027. }
  2028. /// Collect blocks in the given loop that are to be placed.
  2029. ///
  2030. /// When profile data is available, exclude cold blocks from the returned set;
  2031. /// otherwise, collect all blocks in the loop.
  2032. MachineBlockPlacement::BlockFilterSet
  2033. MachineBlockPlacement::collectLoopBlockSet(const MachineLoop &L) {
  2034. BlockFilterSet LoopBlockSet;
  2035. // Filter cold blocks off from LoopBlockSet when profile data is available.
  2036. // Collect the sum of frequencies of incoming edges to the loop header from
  2037. // outside. If we treat the loop as a super block, this is the frequency of
  2038. // the loop. Then for each block in the loop, we calculate the ratio between
  2039. // its frequency and the frequency of the loop block. When it is too small,
  2040. // don't add it to the loop chain. If there are outer loops, then this block
  2041. // will be merged into the first outer loop chain for which this block is not
  2042. // cold anymore. This needs precise profile data and we only do this when
  2043. // profile data is available.
  2044. if (F->getFunction().hasProfileData() || ForceLoopColdBlock) {
  2045. BlockFrequency LoopFreq(0);
  2046. for (auto LoopPred : L.getHeader()->predecessors())
  2047. if (!L.contains(LoopPred))
  2048. LoopFreq += MBFI->getBlockFreq(LoopPred) *
  2049. MBPI->getEdgeProbability(LoopPred, L.getHeader());
  2050. for (MachineBasicBlock *LoopBB : L.getBlocks()) {
  2051. auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency();
  2052. if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio)
  2053. continue;
  2054. LoopBlockSet.insert(LoopBB);
  2055. }
  2056. } else
  2057. LoopBlockSet.insert(L.block_begin(), L.block_end());
  2058. return LoopBlockSet;
  2059. }
  2060. /// Forms basic block chains from the natural loop structures.
  2061. ///
  2062. /// These chains are designed to preserve the existing *structure* of the code
  2063. /// as much as possible. We can then stitch the chains together in a way which
  2064. /// both preserves the topological structure and minimizes taken conditional
  2065. /// branches.
  2066. void MachineBlockPlacement::buildLoopChains(const MachineLoop &L) {
  2067. // First recurse through any nested loops, building chains for those inner
  2068. // loops.
  2069. for (const MachineLoop *InnerLoop : L)
  2070. buildLoopChains(*InnerLoop);
  2071. assert(BlockWorkList.empty() &&
  2072. "BlockWorkList not empty when starting to build loop chains.");
  2073. assert(EHPadWorkList.empty() &&
  2074. "EHPadWorkList not empty when starting to build loop chains.");
  2075. BlockFilterSet LoopBlockSet = collectLoopBlockSet(L);
  2076. // Check if we have profile data for this function. If yes, we will rotate
  2077. // this loop by modeling costs more precisely which requires the profile data
  2078. // for better layout.
  2079. bool RotateLoopWithProfile =
  2080. ForcePreciseRotationCost ||
  2081. (PreciseRotationCost && F->getFunction().hasProfileData());
  2082. // First check to see if there is an obviously preferable top block for the
  2083. // loop. This will default to the header, but may end up as one of the
  2084. // predecessors to the header if there is one which will result in strictly
  2085. // fewer branches in the loop body.
  2086. // When we use profile data to rotate the loop, this is unnecessary.
  2087. MachineBasicBlock *LoopTop =
  2088. RotateLoopWithProfile ? L.getHeader() : findBestLoopTop(L, LoopBlockSet);
  2089. // If we selected just the header for the loop top, look for a potentially
  2090. // profitable exit block in the event that rotating the loop can eliminate
  2091. // branches by placing an exit edge at the bottom.
  2092. //
  2093. // Loops are processed innermost to uttermost, make sure we clear
  2094. // PreferredLoopExit before processing a new loop.
  2095. PreferredLoopExit = nullptr;
  2096. if (!RotateLoopWithProfile && LoopTop == L.getHeader())
  2097. PreferredLoopExit = findBestLoopExit(L, LoopBlockSet);
  2098. BlockChain &LoopChain = *BlockToChain[LoopTop];
  2099. // FIXME: This is a really lame way of walking the chains in the loop: we
  2100. // walk the blocks, and use a set to prevent visiting a particular chain
  2101. // twice.
  2102. SmallPtrSet<BlockChain *, 4> UpdatedPreds;
  2103. assert(LoopChain.UnscheduledPredecessors == 0 &&
  2104. "LoopChain should not have unscheduled predecessors.");
  2105. UpdatedPreds.insert(&LoopChain);
  2106. for (const MachineBasicBlock *LoopBB : LoopBlockSet)
  2107. fillWorkLists(LoopBB, UpdatedPreds, &LoopBlockSet);
  2108. buildChain(LoopTop, LoopChain, &LoopBlockSet);
  2109. if (RotateLoopWithProfile)
  2110. rotateLoopWithProfile(LoopChain, L, LoopBlockSet);
  2111. else
  2112. rotateLoop(LoopChain, PreferredLoopExit, LoopBlockSet);
  2113. LLVM_DEBUG({
  2114. // Crash at the end so we get all of the debugging output first.
  2115. bool BadLoop = false;
  2116. if (LoopChain.UnscheduledPredecessors) {
  2117. BadLoop = true;
  2118. dbgs() << "Loop chain contains a block without its preds placed!\n"
  2119. << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
  2120. << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
  2121. }
  2122. for (MachineBasicBlock *ChainBB : LoopChain) {
  2123. dbgs() << " ... " << getBlockName(ChainBB) << "\n";
  2124. if (!LoopBlockSet.remove(ChainBB)) {
  2125. // We don't mark the loop as bad here because there are real situations
  2126. // where this can occur. For example, with an unanalyzable fallthrough
  2127. // from a loop block to a non-loop block or vice versa.
  2128. dbgs() << "Loop chain contains a block not contained by the loop!\n"
  2129. << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
  2130. << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
  2131. << " Bad block: " << getBlockName(ChainBB) << "\n";
  2132. }
  2133. }
  2134. if (!LoopBlockSet.empty()) {
  2135. BadLoop = true;
  2136. for (const MachineBasicBlock *LoopBB : LoopBlockSet)
  2137. dbgs() << "Loop contains blocks never placed into a chain!\n"
  2138. << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
  2139. << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
  2140. << " Bad block: " << getBlockName(LoopBB) << "\n";
  2141. }
  2142. assert(!BadLoop && "Detected problems with the placement of this loop.");
  2143. });
  2144. BlockWorkList.clear();
  2145. EHPadWorkList.clear();
  2146. }
  2147. void MachineBlockPlacement::buildCFGChains() {
  2148. // Ensure that every BB in the function has an associated chain to simplify
  2149. // the assumptions of the remaining algorithm.
  2150. SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
  2151. for (MachineFunction::iterator FI = F->begin(), FE = F->end(); FI != FE;
  2152. ++FI) {
  2153. MachineBasicBlock *BB = &*FI;
  2154. BlockChain *Chain =
  2155. new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
  2156. // Also, merge any blocks which we cannot reason about and must preserve
  2157. // the exact fallthrough behavior for.
  2158. while (true) {
  2159. Cond.clear();
  2160. MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
  2161. if (!TII->analyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
  2162. break;
  2163. MachineFunction::iterator NextFI = std::next(FI);
  2164. MachineBasicBlock *NextBB = &*NextFI;
  2165. // Ensure that the layout successor is a viable block, as we know that
  2166. // fallthrough is a possibility.
  2167. assert(NextFI != FE && "Can't fallthrough past the last block.");
  2168. LLVM_DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
  2169. << getBlockName(BB) << " -> " << getBlockName(NextBB)
  2170. << "\n");
  2171. Chain->merge(NextBB, nullptr);
  2172. #ifndef NDEBUG
  2173. BlocksWithUnanalyzableExits.insert(&*BB);
  2174. #endif
  2175. FI = NextFI;
  2176. BB = NextBB;
  2177. }
  2178. }
  2179. // Build any loop-based chains.
  2180. PreferredLoopExit = nullptr;
  2181. for (MachineLoop *L : *MLI)
  2182. buildLoopChains(*L);
  2183. assert(BlockWorkList.empty() &&
  2184. "BlockWorkList should be empty before building final chain.");
  2185. assert(EHPadWorkList.empty() &&
  2186. "EHPadWorkList should be empty before building final chain.");
  2187. SmallPtrSet<BlockChain *, 4> UpdatedPreds;
  2188. for (MachineBasicBlock &MBB : *F)
  2189. fillWorkLists(&MBB, UpdatedPreds);
  2190. BlockChain &FunctionChain = *BlockToChain[&F->front()];
  2191. buildChain(&F->front(), FunctionChain);
  2192. #ifndef NDEBUG
  2193. using FunctionBlockSetType = SmallPtrSet<MachineBasicBlock *, 16>;
  2194. #endif
  2195. LLVM_DEBUG({
  2196. // Crash at the end so we get all of the debugging output first.
  2197. bool BadFunc = false;
  2198. FunctionBlockSetType FunctionBlockSet;
  2199. for (MachineBasicBlock &MBB : *F)
  2200. FunctionBlockSet.insert(&MBB);
  2201. for (MachineBasicBlock *ChainBB : FunctionChain)
  2202. if (!FunctionBlockSet.erase(ChainBB)) {
  2203. BadFunc = true;
  2204. dbgs() << "Function chain contains a block not in the function!\n"
  2205. << " Bad block: " << getBlockName(ChainBB) << "\n";
  2206. }
  2207. if (!FunctionBlockSet.empty()) {
  2208. BadFunc = true;
  2209. for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
  2210. dbgs() << "Function contains blocks never placed into a chain!\n"
  2211. << " Bad block: " << getBlockName(RemainingBB) << "\n";
  2212. }
  2213. assert(!BadFunc && "Detected problems with the block placement.");
  2214. });
  2215. // Splice the blocks into place.
  2216. MachineFunction::iterator InsertPos = F->begin();
  2217. LLVM_DEBUG(dbgs() << "[MBP] Function: " << F->getName() << "\n");
  2218. for (MachineBasicBlock *ChainBB : FunctionChain) {
  2219. LLVM_DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
  2220. : " ... ")
  2221. << getBlockName(ChainBB) << "\n");
  2222. if (InsertPos != MachineFunction::iterator(ChainBB))
  2223. F->splice(InsertPos, ChainBB);
  2224. else
  2225. ++InsertPos;
  2226. // Update the terminator of the previous block.
  2227. if (ChainBB == *FunctionChain.begin())
  2228. continue;
  2229. MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB));
  2230. // FIXME: It would be awesome of updateTerminator would just return rather
  2231. // than assert when the branch cannot be analyzed in order to remove this
  2232. // boiler plate.
  2233. Cond.clear();
  2234. MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
  2235. #ifndef NDEBUG
  2236. if (!BlocksWithUnanalyzableExits.count(PrevBB)) {
  2237. // Given the exact block placement we chose, we may actually not _need_ to
  2238. // be able to edit PrevBB's terminator sequence, but not being _able_ to
  2239. // do that at this point is a bug.
  2240. assert((!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond) ||
  2241. !PrevBB->canFallThrough()) &&
  2242. "Unexpected block with un-analyzable fallthrough!");
  2243. Cond.clear();
  2244. TBB = FBB = nullptr;
  2245. }
  2246. #endif
  2247. // The "PrevBB" is not yet updated to reflect current code layout, so,
  2248. // o. it may fall-through to a block without explicit "goto" instruction
  2249. // before layout, and no longer fall-through it after layout; or
  2250. // o. just opposite.
  2251. //
  2252. // analyzeBranch() may return erroneous value for FBB when these two
  2253. // situations take place. For the first scenario FBB is mistakenly set NULL;
  2254. // for the 2nd scenario, the FBB, which is expected to be NULL, is
  2255. // mistakenly pointing to "*BI".
  2256. // Thus, if the future change needs to use FBB before the layout is set, it
  2257. // has to correct FBB first by using the code similar to the following:
  2258. //
  2259. // if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
  2260. // PrevBB->updateTerminator();
  2261. // Cond.clear();
  2262. // TBB = FBB = nullptr;
  2263. // if (TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) {
  2264. // // FIXME: This should never take place.
  2265. // TBB = FBB = nullptr;
  2266. // }
  2267. // }
  2268. if (!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond))
  2269. PrevBB->updateTerminator();
  2270. }
  2271. // Fixup the last block.
  2272. Cond.clear();
  2273. MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
  2274. if (!TII->analyzeBranch(F->back(), TBB, FBB, Cond))
  2275. F->back().updateTerminator();
  2276. BlockWorkList.clear();
  2277. EHPadWorkList.clear();
  2278. }
  2279. void MachineBlockPlacement::optimizeBranches() {
  2280. BlockChain &FunctionChain = *BlockToChain[&F->front()];
  2281. SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
  2282. // Now that all the basic blocks in the chain have the proper layout,
  2283. // make a final call to AnalyzeBranch with AllowModify set.
  2284. // Indeed, the target may be able to optimize the branches in a way we
  2285. // cannot because all branches may not be analyzable.
  2286. // E.g., the target may be able to remove an unconditional branch to
  2287. // a fallthrough when it occurs after predicated terminators.
  2288. for (MachineBasicBlock *ChainBB : FunctionChain) {
  2289. Cond.clear();
  2290. MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
  2291. if (!TII->analyzeBranch(*ChainBB, TBB, FBB, Cond, /*AllowModify*/ true)) {
  2292. // If PrevBB has a two-way branch, try to re-order the branches
  2293. // such that we branch to the successor with higher probability first.
  2294. if (TBB && !Cond.empty() && FBB &&
  2295. MBPI->getEdgeProbability(ChainBB, FBB) >
  2296. MBPI->getEdgeProbability(ChainBB, TBB) &&
  2297. !TII->reverseBranchCondition(Cond)) {
  2298. LLVM_DEBUG(dbgs() << "Reverse order of the two branches: "
  2299. << getBlockName(ChainBB) << "\n");
  2300. LLVM_DEBUG(dbgs() << " Edge probability: "
  2301. << MBPI->getEdgeProbability(ChainBB, FBB) << " vs "
  2302. << MBPI->getEdgeProbability(ChainBB, TBB) << "\n");
  2303. DebugLoc dl; // FIXME: this is nowhere
  2304. TII->removeBranch(*ChainBB);
  2305. TII->insertBranch(*ChainBB, FBB, TBB, Cond, dl);
  2306. ChainBB->updateTerminator();
  2307. }
  2308. }
  2309. }
  2310. }
  2311. void MachineBlockPlacement::alignBlocks() {
  2312. // Walk through the backedges of the function now that we have fully laid out
  2313. // the basic blocks and align the destination of each backedge. We don't rely
  2314. // exclusively on the loop info here so that we can align backedges in
  2315. // unnatural CFGs and backedges that were introduced purely because of the
  2316. // loop rotations done during this layout pass.
  2317. if (F->getFunction().hasMinSize() ||
  2318. (F->getFunction().hasOptSize() && !TLI->alignLoopsWithOptSize()))
  2319. return;
  2320. BlockChain &FunctionChain = *BlockToChain[&F->front()];
  2321. if (FunctionChain.begin() == FunctionChain.end())
  2322. return; // Empty chain.
  2323. const BranchProbability ColdProb(1, 5); // 20%
  2324. BlockFrequency EntryFreq = MBFI->getBlockFreq(&F->front());
  2325. BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
  2326. for (MachineBasicBlock *ChainBB : FunctionChain) {
  2327. if (ChainBB == *FunctionChain.begin())
  2328. continue;
  2329. // Don't align non-looping basic blocks. These are unlikely to execute
  2330. // enough times to matter in practice. Note that we'll still handle
  2331. // unnatural CFGs inside of a natural outer loop (the common case) and
  2332. // rotated loops.
  2333. MachineLoop *L = MLI->getLoopFor(ChainBB);
  2334. if (!L)
  2335. continue;
  2336. unsigned Align = TLI->getPrefLoopAlignment(L);
  2337. if (!Align)
  2338. continue; // Don't care about loop alignment.
  2339. // If the block is cold relative to the function entry don't waste space
  2340. // aligning it.
  2341. BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
  2342. if (Freq < WeightedEntryFreq)
  2343. continue;
  2344. // If the block is cold relative to its loop header, don't align it
  2345. // regardless of what edges into the block exist.
  2346. MachineBasicBlock *LoopHeader = L->getHeader();
  2347. BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
  2348. if (Freq < (LoopHeaderFreq * ColdProb))
  2349. continue;
  2350. // Check for the existence of a non-layout predecessor which would benefit
  2351. // from aligning this block.
  2352. MachineBasicBlock *LayoutPred =
  2353. &*std::prev(MachineFunction::iterator(ChainBB));
  2354. // Force alignment if all the predecessors are jumps. We already checked
  2355. // that the block isn't cold above.
  2356. if (!LayoutPred->isSuccessor(ChainBB)) {
  2357. ChainBB->setAlignment(Align);
  2358. continue;
  2359. }
  2360. // Align this block if the layout predecessor's edge into this block is
  2361. // cold relative to the block. When this is true, other predecessors make up
  2362. // all of the hot entries into the block and thus alignment is likely to be
  2363. // important.
  2364. BranchProbability LayoutProb =
  2365. MBPI->getEdgeProbability(LayoutPred, ChainBB);
  2366. BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
  2367. if (LayoutEdgeFreq <= (Freq * ColdProb))
  2368. ChainBB->setAlignment(Align);
  2369. }
  2370. }
  2371. /// Tail duplicate \p BB into (some) predecessors if profitable, repeating if
  2372. /// it was duplicated into its chain predecessor and removed.
  2373. /// \p BB - Basic block that may be duplicated.
  2374. ///
  2375. /// \p LPred - Chosen layout predecessor of \p BB.
  2376. /// Updated to be the chain end if LPred is removed.
  2377. /// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
  2378. /// \p BlockFilter - Set of blocks that belong to the loop being laid out.
  2379. /// Used to identify which blocks to update predecessor
  2380. /// counts.
  2381. /// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
  2382. /// chosen in the given order due to unnatural CFG
  2383. /// only needed if \p BB is removed and
  2384. /// \p PrevUnplacedBlockIt pointed to \p BB.
  2385. /// @return true if \p BB was removed.
  2386. bool MachineBlockPlacement::repeatedlyTailDuplicateBlock(
  2387. MachineBasicBlock *BB, MachineBasicBlock *&LPred,
  2388. const MachineBasicBlock *LoopHeaderBB,
  2389. BlockChain &Chain, BlockFilterSet *BlockFilter,
  2390. MachineFunction::iterator &PrevUnplacedBlockIt) {
  2391. bool Removed, DuplicatedToLPred;
  2392. bool DuplicatedToOriginalLPred;
  2393. Removed = maybeTailDuplicateBlock(BB, LPred, Chain, BlockFilter,
  2394. PrevUnplacedBlockIt,
  2395. DuplicatedToLPred);
  2396. if (!Removed)
  2397. return false;
  2398. DuplicatedToOriginalLPred = DuplicatedToLPred;
  2399. // Iteratively try to duplicate again. It can happen that a block that is
  2400. // duplicated into is still small enough to be duplicated again.
  2401. // No need to call markBlockSuccessors in this case, as the blocks being
  2402. // duplicated from here on are already scheduled.
  2403. // Note that DuplicatedToLPred always implies Removed.
  2404. while (DuplicatedToLPred) {
  2405. assert(Removed && "Block must have been removed to be duplicated into its "
  2406. "layout predecessor.");
  2407. MachineBasicBlock *DupBB, *DupPred;
  2408. // The removal callback causes Chain.end() to be updated when a block is
  2409. // removed. On the first pass through the loop, the chain end should be the
  2410. // same as it was on function entry. On subsequent passes, because we are
  2411. // duplicating the block at the end of the chain, if it is removed the
  2412. // chain will have shrunk by one block.
  2413. BlockChain::iterator ChainEnd = Chain.end();
  2414. DupBB = *(--ChainEnd);
  2415. // Now try to duplicate again.
  2416. if (ChainEnd == Chain.begin())
  2417. break;
  2418. DupPred = *std::prev(ChainEnd);
  2419. Removed = maybeTailDuplicateBlock(DupBB, DupPred, Chain, BlockFilter,
  2420. PrevUnplacedBlockIt,
  2421. DuplicatedToLPred);
  2422. }
  2423. // If BB was duplicated into LPred, it is now scheduled. But because it was
  2424. // removed, markChainSuccessors won't be called for its chain. Instead we
  2425. // call markBlockSuccessors for LPred to achieve the same effect. This must go
  2426. // at the end because repeating the tail duplication can increase the number
  2427. // of unscheduled predecessors.
  2428. LPred = *std::prev(Chain.end());
  2429. if (DuplicatedToOriginalLPred)
  2430. markBlockSuccessors(Chain, LPred, LoopHeaderBB, BlockFilter);
  2431. return true;
  2432. }
  2433. /// Tail duplicate \p BB into (some) predecessors if profitable.
  2434. /// \p BB - Basic block that may be duplicated
  2435. /// \p LPred - Chosen layout predecessor of \p BB
  2436. /// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
  2437. /// \p BlockFilter - Set of blocks that belong to the loop being laid out.
  2438. /// Used to identify which blocks to update predecessor
  2439. /// counts.
  2440. /// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
  2441. /// chosen in the given order due to unnatural CFG
  2442. /// only needed if \p BB is removed and
  2443. /// \p PrevUnplacedBlockIt pointed to \p BB.
  2444. /// \p DuplicatedToLPred - True if the block was duplicated into LPred. Will
  2445. /// only be true if the block was removed.
  2446. /// \return - True if the block was duplicated into all preds and removed.
  2447. bool MachineBlockPlacement::maybeTailDuplicateBlock(
  2448. MachineBasicBlock *BB, MachineBasicBlock *LPred,
  2449. BlockChain &Chain, BlockFilterSet *BlockFilter,
  2450. MachineFunction::iterator &PrevUnplacedBlockIt,
  2451. bool &DuplicatedToLPred) {
  2452. DuplicatedToLPred = false;
  2453. if (!shouldTailDuplicate(BB))
  2454. return false;
  2455. LLVM_DEBUG(dbgs() << "Redoing tail duplication for Succ#" << BB->getNumber()
  2456. << "\n");
  2457. // This has to be a callback because none of it can be done after
  2458. // BB is deleted.
  2459. bool Removed = false;
  2460. auto RemovalCallback =
  2461. [&](MachineBasicBlock *RemBB) {
  2462. // Signal to outer function
  2463. Removed = true;
  2464. // Conservative default.
  2465. bool InWorkList = true;
  2466. // Remove from the Chain and Chain Map
  2467. if (BlockToChain.count(RemBB)) {
  2468. BlockChain *Chain = BlockToChain[RemBB];
  2469. InWorkList = Chain->UnscheduledPredecessors == 0;
  2470. Chain->remove(RemBB);
  2471. BlockToChain.erase(RemBB);
  2472. }
  2473. // Handle the unplaced block iterator
  2474. if (&(*PrevUnplacedBlockIt) == RemBB) {
  2475. PrevUnplacedBlockIt++;
  2476. }
  2477. // Handle the Work Lists
  2478. if (InWorkList) {
  2479. SmallVectorImpl<MachineBasicBlock *> &RemoveList = BlockWorkList;
  2480. if (RemBB->isEHPad())
  2481. RemoveList = EHPadWorkList;
  2482. RemoveList.erase(
  2483. llvm::remove_if(RemoveList,
  2484. [RemBB](MachineBasicBlock *BB) {
  2485. return BB == RemBB;
  2486. }),
  2487. RemoveList.end());
  2488. }
  2489. // Handle the filter set
  2490. if (BlockFilter) {
  2491. BlockFilter->remove(RemBB);
  2492. }
  2493. // Remove the block from loop info.
  2494. MLI->removeBlock(RemBB);
  2495. if (RemBB == PreferredLoopExit)
  2496. PreferredLoopExit = nullptr;
  2497. LLVM_DEBUG(dbgs() << "TailDuplicator deleted block: "
  2498. << getBlockName(RemBB) << "\n");
  2499. };
  2500. auto RemovalCallbackRef =
  2501. function_ref<void(MachineBasicBlock*)>(RemovalCallback);
  2502. SmallVector<MachineBasicBlock *, 8> DuplicatedPreds;
  2503. bool IsSimple = TailDup.isSimpleBB(BB);
  2504. TailDup.tailDuplicateAndUpdate(IsSimple, BB, LPred,
  2505. &DuplicatedPreds, &RemovalCallbackRef);
  2506. // Update UnscheduledPredecessors to reflect tail-duplication.
  2507. DuplicatedToLPred = false;
  2508. for (MachineBasicBlock *Pred : DuplicatedPreds) {
  2509. // We're only looking for unscheduled predecessors that match the filter.
  2510. BlockChain* PredChain = BlockToChain[Pred];
  2511. if (Pred == LPred)
  2512. DuplicatedToLPred = true;
  2513. if (Pred == LPred || (BlockFilter && !BlockFilter->count(Pred))
  2514. || PredChain == &Chain)
  2515. continue;
  2516. for (MachineBasicBlock *NewSucc : Pred->successors()) {
  2517. if (BlockFilter && !BlockFilter->count(NewSucc))
  2518. continue;
  2519. BlockChain *NewChain = BlockToChain[NewSucc];
  2520. if (NewChain != &Chain && NewChain != PredChain)
  2521. NewChain->UnscheduledPredecessors++;
  2522. }
  2523. }
  2524. return Removed;
  2525. }
  2526. bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &MF) {
  2527. if (skipFunction(MF.getFunction()))
  2528. return false;
  2529. // Check for single-block functions and skip them.
  2530. if (std::next(MF.begin()) == MF.end())
  2531. return false;
  2532. F = &MF;
  2533. MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
  2534. MBFI = llvm::make_unique<BranchFolder::MBFIWrapper>(
  2535. getAnalysis<MachineBlockFrequencyInfo>());
  2536. MLI = &getAnalysis<MachineLoopInfo>();
  2537. TII = MF.getSubtarget().getInstrInfo();
  2538. TLI = MF.getSubtarget().getTargetLowering();
  2539. MPDT = nullptr;
  2540. // Initialize PreferredLoopExit to nullptr here since it may never be set if
  2541. // there are no MachineLoops.
  2542. PreferredLoopExit = nullptr;
  2543. assert(BlockToChain.empty() &&
  2544. "BlockToChain map should be empty before starting placement.");
  2545. assert(ComputedEdges.empty() &&
  2546. "Computed Edge map should be empty before starting placement.");
  2547. unsigned TailDupSize = TailDupPlacementThreshold;
  2548. // If only the aggressive threshold is explicitly set, use it.
  2549. if (TailDupPlacementAggressiveThreshold.getNumOccurrences() != 0 &&
  2550. TailDupPlacementThreshold.getNumOccurrences() == 0)
  2551. TailDupSize = TailDupPlacementAggressiveThreshold;
  2552. TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
  2553. // For aggressive optimization, we can adjust some thresholds to be less
  2554. // conservative.
  2555. if (PassConfig->getOptLevel() >= CodeGenOpt::Aggressive) {
  2556. // At O3 we should be more willing to copy blocks for tail duplication. This
  2557. // increases size pressure, so we only do it at O3
  2558. // Do this unless only the regular threshold is explicitly set.
  2559. if (TailDupPlacementThreshold.getNumOccurrences() == 0 ||
  2560. TailDupPlacementAggressiveThreshold.getNumOccurrences() != 0)
  2561. TailDupSize = TailDupPlacementAggressiveThreshold;
  2562. }
  2563. if (allowTailDupPlacement()) {
  2564. MPDT = &getAnalysis<MachinePostDominatorTree>();
  2565. if (MF.getFunction().hasOptSize())
  2566. TailDupSize = 1;
  2567. bool PreRegAlloc = false;
  2568. TailDup.initMF(MF, PreRegAlloc, MBPI, /* LayoutMode */ true, TailDupSize);
  2569. precomputeTriangleChains();
  2570. }
  2571. buildCFGChains();
  2572. // Changing the layout can create new tail merging opportunities.
  2573. // TailMerge can create jump into if branches that make CFG irreducible for
  2574. // HW that requires structured CFG.
  2575. bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&
  2576. PassConfig->getEnableTailMerge() &&
  2577. BranchFoldPlacement;
  2578. // No tail merging opportunities if the block number is less than four.
  2579. if (MF.size() > 3 && EnableTailMerge) {
  2580. unsigned TailMergeSize = TailDupSize + 1;
  2581. BranchFolder BF(/*EnableTailMerge=*/true, /*CommonHoist=*/false, *MBFI,
  2582. *MBPI, TailMergeSize);
  2583. if (BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
  2584. getAnalysisIfAvailable<MachineModuleInfo>(), MLI,
  2585. /*AfterBlockPlacement=*/true)) {
  2586. // Redo the layout if tail merging creates/removes/moves blocks.
  2587. BlockToChain.clear();
  2588. ComputedEdges.clear();
  2589. // Must redo the post-dominator tree if blocks were changed.
  2590. if (MPDT)
  2591. MPDT->runOnMachineFunction(MF);
  2592. ChainAllocator.DestroyAll();
  2593. buildCFGChains();
  2594. }
  2595. }
  2596. optimizeBranches();
  2597. alignBlocks();
  2598. BlockToChain.clear();
  2599. ComputedEdges.clear();
  2600. ChainAllocator.DestroyAll();
  2601. if (AlignAllBlock)
  2602. // Align all of the blocks in the function to a specific alignment.
  2603. for (MachineBasicBlock &MBB : MF)
  2604. MBB.setAlignment(AlignAllBlock);
  2605. else if (AlignAllNonFallThruBlocks) {
  2606. // Align all of the blocks that have no fall-through predecessors to a
  2607. // specific alignment.
  2608. for (auto MBI = std::next(MF.begin()), MBE = MF.end(); MBI != MBE; ++MBI) {
  2609. auto LayoutPred = std::prev(MBI);
  2610. if (!LayoutPred->isSuccessor(&*MBI))
  2611. MBI->setAlignment(AlignAllNonFallThruBlocks);
  2612. }
  2613. }
  2614. if (ViewBlockLayoutWithBFI != GVDT_None &&
  2615. (ViewBlockFreqFuncName.empty() ||
  2616. F->getFunction().getName().equals(ViewBlockFreqFuncName))) {
  2617. MBFI->view("MBP." + MF.getName(), false);
  2618. }
  2619. // We always return true as we have no way to track whether the final order
  2620. // differs from the original order.
  2621. return true;
  2622. }
  2623. namespace {
  2624. /// A pass to compute block placement statistics.
  2625. ///
  2626. /// A separate pass to compute interesting statistics for evaluating block
  2627. /// placement. This is separate from the actual placement pass so that they can
  2628. /// be computed in the absence of any placement transformations or when using
  2629. /// alternative placement strategies.
  2630. class MachineBlockPlacementStats : public MachineFunctionPass {
  2631. /// A handle to the branch probability pass.
  2632. const MachineBranchProbabilityInfo *MBPI;
  2633. /// A handle to the function-wide block frequency pass.
  2634. const MachineBlockFrequencyInfo *MBFI;
  2635. public:
  2636. static char ID; // Pass identification, replacement for typeid
  2637. MachineBlockPlacementStats() : MachineFunctionPass(ID) {
  2638. initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
  2639. }
  2640. bool runOnMachineFunction(MachineFunction &F) override;
  2641. void getAnalysisUsage(AnalysisUsage &AU) const override {
  2642. AU.addRequired<MachineBranchProbabilityInfo>();
  2643. AU.addRequired<MachineBlockFrequencyInfo>();
  2644. AU.setPreservesAll();
  2645. MachineFunctionPass::getAnalysisUsage(AU);
  2646. }
  2647. };
  2648. } // end anonymous namespace
  2649. char MachineBlockPlacementStats::ID = 0;
  2650. char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
  2651. INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
  2652. "Basic Block Placement Stats", false, false)
  2653. INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
  2654. INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
  2655. INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
  2656. "Basic Block Placement Stats", false, false)
  2657. bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
  2658. // Check for single-block functions and skip them.
  2659. if (std::next(F.begin()) == F.end())
  2660. return false;
  2661. MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
  2662. MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
  2663. for (MachineBasicBlock &MBB : F) {
  2664. BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
  2665. Statistic &NumBranches =
  2666. (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
  2667. Statistic &BranchTakenFreq =
  2668. (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
  2669. for (MachineBasicBlock *Succ : MBB.successors()) {
  2670. // Skip if this successor is a fallthrough.
  2671. if (MBB.isLayoutSuccessor(Succ))
  2672. continue;
  2673. BlockFrequency EdgeFreq =
  2674. BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
  2675. ++NumBranches;
  2676. BranchTakenFreq += EdgeFreq.getFrequency();
  2677. }
  2678. }
  2679. return false;
  2680. }