MachineBlockPlacement.cpp 128 KB

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