MachineBlockPlacement.cpp 118 KB

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