MachineBlockPlacement.cpp 119 KB

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