MachineBlockPlacement.cpp 128 KB

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