MachineBlockPlacement.cpp 147 KB

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