MachineBlockPlacement.cpp 130 KB

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