MachineBlockPlacement.cpp 118 KB

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