1 //===-- MachineBlockPlacement.cpp - Basic Block Code Layout optimization --===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements basic block placement transformations using the CFG
11 // structure and branch probability estimates.
13 // The pass strives to preserve the structure of the CFG (that is, retain
14 // a topological ordering of basic blocks) in the absence of a *strong* signal
15 // to the contrary from probabilities. However, within the CFG structure, it
16 // attempts to choose an ordering which favors placing more likely sequences of
17 // blocks adjacent to each other.
19 // The algorithm works from the inner-most loop within a function outward, and
20 // at each stage walks through the basic blocks, trying to coalesce them into
21 // sequential chains where allowed by the CFG (or demanded by heavy
22 // probabilities). Finally, it walks the blocks in topological order, and the
23 // first time it reaches a chain of basic blocks, it schedules them in the
26 //===----------------------------------------------------------------------===//
28 #include "llvm/CodeGen/Passes.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/CodeGen/MachineBasicBlock.h"
34 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
35 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
36 #include "llvm/CodeGen/MachineDominators.h"
37 #include "llvm/CodeGen/MachineFunction.h"
38 #include "llvm/CodeGen/MachineFunctionPass.h"
39 #include "llvm/CodeGen/MachineLoopInfo.h"
40 #include "llvm/CodeGen/MachineModuleInfo.h"
41 #include "llvm/Support/Allocator.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/Target/TargetInstrInfo.h"
46 #include "llvm/Target/TargetLowering.h"
47 #include "llvm/Target/TargetSubtargetInfo.h"
51 #define DEBUG_TYPE "block-placement"
53 STATISTIC(NumCondBranches
, "Number of conditional branches");
54 STATISTIC(NumUncondBranches
, "Number of unconditional branches");
55 STATISTIC(CondBranchTakenFreq
,
56 "Potential frequency of taking conditional branches");
57 STATISTIC(UncondBranchTakenFreq
,
58 "Potential frequency of taking unconditional branches");
60 static cl::opt
<unsigned> AlignAllBlock("align-all-blocks",
61 cl::desc("Force the alignment of all "
62 "blocks in the function."),
63 cl::init(0), cl::Hidden
);
65 // FIXME: Find a good default for this flag and remove the flag.
66 static cl::opt
<unsigned> ExitBlockBias(
67 "block-placement-exit-block-bias",
68 cl::desc("Block frequency percentage a loop exit block needs "
69 "over the original exit to be considered the new exit."),
70 cl::init(0), cl::Hidden
);
72 static cl::opt
<bool> OutlineOptionalBranches(
73 "outline-optional-branches",
74 cl::desc("Put completely optional branches, i.e. branches with a common "
75 "post dominator, out of line."),
76 cl::init(false), cl::Hidden
);
78 static cl::opt
<unsigned> OutlineOptionalThreshold(
79 "outline-optional-threshold",
80 cl::desc("Don't outline optional branches that are a single block with an "
81 "instruction count below this threshold"),
82 cl::init(4), cl::Hidden
);
84 static cl::opt
<unsigned> LoopToColdBlockRatio(
85 "loop-to-cold-block-ratio",
86 cl::desc("Outline loop blocks from loop chain if (frequency of loop) / "
87 "(frequency of block) is greater than this ratio"),
88 cl::init(5), cl::Hidden
);
91 PreciseRotationCost("precise-rotation-cost",
92 cl::desc("Model the cost of loop rotation more "
93 "precisely by using profile data."),
94 cl::init(false), cl::Hidden
);
96 static cl::opt
<unsigned> MisfetchCost(
98 cl::desc("Cost that models the probablistic risk of an instruction "
99 "misfetch due to a jump comparing to falling through, whose cost "
101 cl::init(1), cl::Hidden
);
103 static cl::opt
<unsigned> JumpInstCost("jump-inst-cost",
104 cl::desc("Cost of jump instructions."),
105 cl::init(1), cl::Hidden
);
109 /// \brief Type for our function-wide basic block -> block chain mapping.
110 typedef DenseMap
<MachineBasicBlock
*, BlockChain
*> BlockToChainMapType
;
114 /// \brief A chain of blocks which will be laid out contiguously.
116 /// This is the datastructure representing a chain of consecutive blocks that
117 /// are profitable to layout together in order to maximize fallthrough
118 /// probabilities and code locality. We also can use a block chain to represent
119 /// a sequence of basic blocks which have some external (correctness)
120 /// requirement for sequential layout.
122 /// Chains can be built around a single basic block and can be merged to grow
123 /// them. They participate in a block-to-chain mapping, which is updated
124 /// automatically as chains are merged together.
126 /// \brief The sequence of blocks belonging to this chain.
128 /// This is the sequence of blocks for a particular chain. These will be laid
129 /// out in-order within the function.
130 SmallVector
<MachineBasicBlock
*, 4> Blocks
;
132 /// \brief A handle to the function-wide basic block to block chain mapping.
134 /// This is retained in each block chain to simplify the computation of child
135 /// block chains for SCC-formation and iteration. We store the edges to child
136 /// basic blocks, and map them back to their associated chains using this
138 BlockToChainMapType
&BlockToChain
;
141 /// \brief Construct a new BlockChain.
143 /// This builds a new block chain representing a single basic block in the
144 /// function. It also registers itself as the chain that block participates
145 /// in with the BlockToChain mapping.
146 BlockChain(BlockToChainMapType
&BlockToChain
, MachineBasicBlock
*BB
)
147 : Blocks(1, BB
), BlockToChain(BlockToChain
), LoopPredecessors(0) {
148 assert(BB
&& "Cannot create a chain with a null basic block");
149 BlockToChain
[BB
] = this;
152 /// \brief Iterator over blocks within the chain.
153 typedef SmallVectorImpl
<MachineBasicBlock
*>::iterator iterator
;
155 /// \brief Beginning of blocks within the chain.
156 iterator
begin() { return Blocks
.begin(); }
158 /// \brief End of blocks within the chain.
159 iterator
end() { return Blocks
.end(); }
161 /// \brief Merge a block chain into this one.
163 /// This routine merges a block chain into this one. It takes care of forming
164 /// a contiguous sequence of basic blocks, updating the edge list, and
165 /// updating the block -> chain mapping. It does not free or tear down the
166 /// old chain, but the old chain's block list is no longer valid.
167 void merge(MachineBasicBlock
*BB
, BlockChain
*Chain
) {
169 assert(!Blocks
.empty());
171 // Fast path in case we don't have a chain already.
173 assert(!BlockToChain
[BB
]);
174 Blocks
.push_back(BB
);
175 BlockToChain
[BB
] = this;
179 assert(BB
== *Chain
->begin());
180 assert(Chain
->begin() != Chain
->end());
182 // Update the incoming blocks to point to this chain, and add them to the
184 for (MachineBasicBlock
*ChainBB
: *Chain
) {
185 Blocks
.push_back(ChainBB
);
186 assert(BlockToChain
[ChainBB
] == Chain
&& "Incoming blocks not in chain");
187 BlockToChain
[ChainBB
] = this;
192 /// \brief Dump the blocks in this chain.
193 LLVM_DUMP_METHOD
void dump() {
194 for (MachineBasicBlock
*MBB
: *this)
199 /// \brief Count of predecessors within the loop currently being processed.
201 /// This count is updated at each loop we process to represent the number of
202 /// in-loop predecessors of this chain.
203 unsigned LoopPredecessors
;
208 class MachineBlockPlacement
: public MachineFunctionPass
{
209 /// \brief A typedef for a block filter set.
210 typedef SmallPtrSet
<MachineBasicBlock
*, 16> BlockFilterSet
;
212 /// \brief A handle to the branch probability pass.
213 const MachineBranchProbabilityInfo
*MBPI
;
215 /// \brief A handle to the function-wide block frequency pass.
216 const MachineBlockFrequencyInfo
*MBFI
;
218 /// \brief A handle to the loop info.
219 const MachineLoopInfo
*MLI
;
221 /// \brief A handle to the target's instruction info.
222 const TargetInstrInfo
*TII
;
224 /// \brief A handle to the target's lowering info.
225 const TargetLoweringBase
*TLI
;
227 /// \brief A handle to the post dominator tree.
228 MachineDominatorTree
*MDT
;
230 /// \brief A set of blocks that are unavoidably execute, i.e. they dominate
231 /// all terminators of the MachineFunction.
232 SmallPtrSet
<MachineBasicBlock
*, 4> UnavoidableBlocks
;
234 /// \brief Allocator and owner of BlockChain structures.
236 /// We build BlockChains lazily while processing the loop structure of
237 /// a function. To reduce malloc traffic, we allocate them using this
238 /// slab-like allocator, and destroy them after the pass completes. An
239 /// important guarantee is that this allocator produces stable pointers to
241 SpecificBumpPtrAllocator
<BlockChain
> ChainAllocator
;
243 /// \brief Function wide BasicBlock to BlockChain mapping.
245 /// This mapping allows efficiently moving from any given basic block to the
246 /// BlockChain it participates in, if any. We use it to, among other things,
247 /// allow implicitly defining edges between chains as the existing edges
248 /// between basic blocks.
249 DenseMap
<MachineBasicBlock
*, BlockChain
*> BlockToChain
;
251 void markChainSuccessors(BlockChain
&Chain
, MachineBasicBlock
*LoopHeaderBB
,
252 SmallVectorImpl
<MachineBasicBlock
*> &BlockWorkList
,
253 const BlockFilterSet
*BlockFilter
= nullptr);
254 MachineBasicBlock
*selectBestSuccessor(MachineBasicBlock
*BB
,
256 const BlockFilterSet
*BlockFilter
);
258 selectBestCandidateBlock(BlockChain
&Chain
,
259 SmallVectorImpl
<MachineBasicBlock
*> &WorkList
,
260 const BlockFilterSet
*BlockFilter
);
262 getFirstUnplacedBlock(MachineFunction
&F
, const BlockChain
&PlacedChain
,
263 MachineFunction::iterator
&PrevUnplacedBlockIt
,
264 const BlockFilterSet
*BlockFilter
);
265 void buildChain(MachineBasicBlock
*BB
, BlockChain
&Chain
,
266 SmallVectorImpl
<MachineBasicBlock
*> &BlockWorkList
,
267 const BlockFilterSet
*BlockFilter
= nullptr);
268 MachineBasicBlock
*findBestLoopTop(MachineLoop
&L
,
269 const BlockFilterSet
&LoopBlockSet
);
270 MachineBasicBlock
*findBestLoopExit(MachineFunction
&F
, MachineLoop
&L
,
271 const BlockFilterSet
&LoopBlockSet
);
272 BlockFilterSet
collectLoopBlockSet(MachineFunction
&F
, MachineLoop
&L
);
273 void buildLoopChains(MachineFunction
&F
, MachineLoop
&L
);
274 void rotateLoop(BlockChain
&LoopChain
, MachineBasicBlock
*ExitingBB
,
275 const BlockFilterSet
&LoopBlockSet
);
276 void rotateLoopWithProfile(BlockChain
&LoopChain
, MachineLoop
&L
,
277 const BlockFilterSet
&LoopBlockSet
);
278 void buildCFGChains(MachineFunction
&F
);
281 static char ID
; // Pass identification, replacement for typeid
282 MachineBlockPlacement() : MachineFunctionPass(ID
) {
283 initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
286 bool runOnMachineFunction(MachineFunction
&F
) override
;
288 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
289 AU
.addRequired
<MachineBranchProbabilityInfo
>();
290 AU
.addRequired
<MachineBlockFrequencyInfo
>();
291 AU
.addRequired
<MachineDominatorTree
>();
292 AU
.addRequired
<MachineLoopInfo
>();
293 MachineFunctionPass::getAnalysisUsage(AU
);
298 char MachineBlockPlacement::ID
= 0;
299 char &llvm::MachineBlockPlacementID
= MachineBlockPlacement::ID
;
300 INITIALIZE_PASS_BEGIN(MachineBlockPlacement
, "block-placement",
301 "Branch Probability Basic Block Placement", false, false)
302 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo
)
303 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo
)
304 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree
)
305 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo
)
306 INITIALIZE_PASS_END(MachineBlockPlacement
, "block-placement",
307 "Branch Probability Basic Block Placement", false, false)
310 /// \brief Helper to print the name of a MBB.
312 /// Only used by debug logging.
313 static std::string
getBlockName(MachineBasicBlock
*BB
) {
315 raw_string_ostream
OS(Result
);
316 OS
<< "BB#" << BB
->getNumber();
317 OS
<< " (derived from LLVM BB '" << BB
->getName() << "')";
322 /// \brief Helper to print the number of a MBB.
324 /// Only used by debug logging.
325 static std::string
getBlockNum(MachineBasicBlock
*BB
) {
327 raw_string_ostream
OS(Result
);
328 OS
<< "BB#" << BB
->getNumber();
334 /// \brief Mark a chain's successors as having one fewer preds.
336 /// When a chain is being merged into the "placed" chain, this routine will
337 /// quickly walk the successors of each block in the chain and mark them as
338 /// having one fewer active predecessor. It also adds any successors of this
339 /// chain which reach the zero-predecessor state to the worklist passed in.
340 void MachineBlockPlacement::markChainSuccessors(
341 BlockChain
&Chain
, MachineBasicBlock
*LoopHeaderBB
,
342 SmallVectorImpl
<MachineBasicBlock
*> &BlockWorkList
,
343 const BlockFilterSet
*BlockFilter
) {
344 // Walk all the blocks in this chain, marking their successors as having
345 // a predecessor placed.
346 for (MachineBasicBlock
*MBB
: Chain
) {
347 // Add any successors for which this is the only un-placed in-loop
348 // predecessor to the worklist as a viable candidate for CFG-neutral
349 // placement. No subsequent placement of this block will violate the CFG
350 // shape, so we get to use heuristics to choose a favorable placement.
351 for (MachineBasicBlock
*Succ
: MBB
->successors()) {
352 if (BlockFilter
&& !BlockFilter
->count(Succ
))
354 BlockChain
&SuccChain
= *BlockToChain
[Succ
];
355 // Disregard edges within a fixed chain, or edges to the loop header.
356 if (&Chain
== &SuccChain
|| Succ
== LoopHeaderBB
)
359 // This is a cross-chain edge that is within the loop, so decrement the
360 // loop predecessor count of the destination chain.
361 if (SuccChain
.LoopPredecessors
> 0 && --SuccChain
.LoopPredecessors
== 0)
362 BlockWorkList
.push_back(*SuccChain
.begin());
367 /// \brief Select the best successor for a block.
369 /// This looks across all successors of a particular block and attempts to
370 /// select the "best" one to be the layout successor. It only considers direct
371 /// successors which also pass the block filter. It will attempt to avoid
372 /// breaking CFG structure, but cave and break such structures in the case of
373 /// very hot successor edges.
375 /// \returns The best successor block found, or null if none are viable.
377 MachineBlockPlacement::selectBestSuccessor(MachineBasicBlock
*BB
,
379 const BlockFilterSet
*BlockFilter
) {
380 const BranchProbability
HotProb(4, 5); // 80%
382 MachineBasicBlock
*BestSucc
= nullptr;
383 // FIXME: Due to the performance of the probability and weight routines in
384 // the MBPI analysis, we manually compute probabilities using the edge
385 // weights. This is suboptimal as it means that the somewhat subtle
386 // definition of edge weight semantics is encoded here as well. We should
387 // improve the MBPI interface to efficiently support query patterns such as
389 uint32_t BestWeight
= 0;
390 uint32_t WeightScale
= 0;
391 uint32_t SumWeight
= MBPI
->getSumForBlock(BB
, WeightScale
);
392 DEBUG(dbgs() << "Attempting merge from: " << getBlockName(BB
) << "\n");
393 for (MachineBasicBlock
*Succ
: BB
->successors()) {
394 if (BlockFilter
&& !BlockFilter
->count(Succ
))
396 BlockChain
&SuccChain
= *BlockToChain
[Succ
];
397 if (&SuccChain
== &Chain
) {
398 DEBUG(dbgs() << " " << getBlockName(Succ
) << " -> Already merged!\n");
401 if (Succ
!= *SuccChain
.begin()) {
402 DEBUG(dbgs() << " " << getBlockName(Succ
) << " -> Mid chain!\n");
406 uint32_t SuccWeight
= MBPI
->getEdgeWeight(BB
, Succ
);
407 BranchProbability
SuccProb(SuccWeight
/ WeightScale
, SumWeight
);
409 // If we outline optional branches, look whether Succ is unavoidable, i.e.
410 // dominates all terminators of the MachineFunction. If it does, other
411 // successors must be optional. Don't do this for cold branches.
412 if (OutlineOptionalBranches
&& SuccProb
> HotProb
.getCompl() &&
413 UnavoidableBlocks
.count(Succ
) > 0) {
414 auto HasShortOptionalBranch
= [&]() {
415 for (MachineBasicBlock
*Pred
: Succ
->predecessors()) {
416 // Check whether there is an unplaced optional branch.
417 if (Pred
== Succ
|| (BlockFilter
&& !BlockFilter
->count(Pred
)) ||
418 BlockToChain
[Pred
] == &Chain
)
420 // Check whether the optional branch has exactly one BB.
421 if (Pred
->pred_size() > 1 || *Pred
->pred_begin() != BB
)
423 // Check whether the optional branch is small.
424 if (Pred
->size() < OutlineOptionalThreshold
)
429 if (!HasShortOptionalBranch())
433 // Only consider successors which are either "hot", or wouldn't violate
434 // any CFG constraints.
435 if (SuccChain
.LoopPredecessors
!= 0) {
436 if (SuccProb
< HotProb
) {
437 DEBUG(dbgs() << " " << getBlockName(Succ
) << " -> " << SuccProb
438 << " (prob) (CFG conflict)\n");
442 // Make sure that a hot successor doesn't have a globally more
443 // important predecessor.
444 BlockFrequency CandidateEdgeFreq
=
445 MBFI
->getBlockFreq(BB
) * SuccProb
* HotProb
.getCompl();
446 bool BadCFGConflict
= false;
447 for (MachineBasicBlock
*Pred
: Succ
->predecessors()) {
448 if (Pred
== Succ
|| (BlockFilter
&& !BlockFilter
->count(Pred
)) ||
449 BlockToChain
[Pred
] == &Chain
)
451 BlockFrequency PredEdgeFreq
=
452 MBFI
->getBlockFreq(Pred
) * MBPI
->getEdgeProbability(Pred
, Succ
);
453 if (PredEdgeFreq
>= CandidateEdgeFreq
) {
454 BadCFGConflict
= true;
458 if (BadCFGConflict
) {
459 DEBUG(dbgs() << " " << getBlockName(Succ
) << " -> " << SuccProb
460 << " (prob) (non-cold CFG conflict)\n");
465 DEBUG(dbgs() << " " << getBlockName(Succ
) << " -> " << SuccProb
467 << (SuccChain
.LoopPredecessors
!= 0 ? " (CFG break)" : "")
469 if (BestSucc
&& BestWeight
>= SuccWeight
)
472 BestWeight
= SuccWeight
;
477 /// \brief Select the best block from a worklist.
479 /// This looks through the provided worklist as a list of candidate basic
480 /// blocks and select the most profitable one to place. The definition of
481 /// profitable only really makes sense in the context of a loop. This returns
482 /// the most frequently visited block in the worklist, which in the case of
483 /// a loop, is the one most desirable to be physically close to the rest of the
484 /// loop body in order to improve icache behavior.
486 /// \returns The best block found, or null if none are viable.
487 MachineBasicBlock
*MachineBlockPlacement::selectBestCandidateBlock(
488 BlockChain
&Chain
, SmallVectorImpl
<MachineBasicBlock
*> &WorkList
,
489 const BlockFilterSet
*BlockFilter
) {
490 // Once we need to walk the worklist looking for a candidate, cleanup the
491 // worklist of already placed entries.
492 // FIXME: If this shows up on profiles, it could be folded (at the cost of
493 // some code complexity) into the loop below.
494 WorkList
.erase(std::remove_if(WorkList
.begin(), WorkList
.end(),
495 [&](MachineBasicBlock
*BB
) {
496 return BlockToChain
.lookup(BB
) == &Chain
;
500 MachineBasicBlock
*BestBlock
= nullptr;
501 BlockFrequency BestFreq
;
502 for (MachineBasicBlock
*MBB
: WorkList
) {
503 BlockChain
&SuccChain
= *BlockToChain
[MBB
];
504 if (&SuccChain
== &Chain
) {
505 DEBUG(dbgs() << " " << getBlockName(MBB
) << " -> Already merged!\n");
508 assert(SuccChain
.LoopPredecessors
== 0 && "Found CFG-violating block");
510 BlockFrequency CandidateFreq
= MBFI
->getBlockFreq(MBB
);
511 DEBUG(dbgs() << " " << getBlockName(MBB
) << " -> ";
512 MBFI
->printBlockFreq(dbgs(), CandidateFreq
) << " (freq)\n");
513 if (BestBlock
&& BestFreq
>= CandidateFreq
)
516 BestFreq
= CandidateFreq
;
521 /// \brief Retrieve the first unplaced basic block.
523 /// This routine is called when we are unable to use the CFG to walk through
524 /// all of the basic blocks and form a chain due to unnatural loops in the CFG.
525 /// We walk through the function's blocks in order, starting from the
526 /// LastUnplacedBlockIt. We update this iterator on each call to avoid
527 /// re-scanning the entire sequence on repeated calls to this routine.
528 MachineBasicBlock
*MachineBlockPlacement::getFirstUnplacedBlock(
529 MachineFunction
&F
, const BlockChain
&PlacedChain
,
530 MachineFunction::iterator
&PrevUnplacedBlockIt
,
531 const BlockFilterSet
*BlockFilter
) {
532 for (MachineFunction::iterator I
= PrevUnplacedBlockIt
, E
= F
.end(); I
!= E
;
534 if (BlockFilter
&& !BlockFilter
->count(&*I
))
536 if (BlockToChain
[&*I
] != &PlacedChain
) {
537 PrevUnplacedBlockIt
= I
;
538 // Now select the head of the chain to which the unplaced block belongs
539 // as the block to place. This will force the entire chain to be placed,
540 // and satisfies the requirements of merging chains.
541 return *BlockToChain
[&*I
]->begin();
547 void MachineBlockPlacement::buildChain(
548 MachineBasicBlock
*BB
, BlockChain
&Chain
,
549 SmallVectorImpl
<MachineBasicBlock
*> &BlockWorkList
,
550 const BlockFilterSet
*BlockFilter
) {
552 assert(BlockToChain
[BB
] == &Chain
);
553 MachineFunction
&F
= *BB
->getParent();
554 MachineFunction::iterator PrevUnplacedBlockIt
= F
.begin();
556 MachineBasicBlock
*LoopHeaderBB
= BB
;
557 markChainSuccessors(Chain
, LoopHeaderBB
, BlockWorkList
, BlockFilter
);
558 BB
= *std::prev(Chain
.end());
561 assert(BlockToChain
[BB
] == &Chain
);
562 assert(*std::prev(Chain
.end()) == BB
);
564 // Look for the best viable successor if there is one to place immediately
566 MachineBasicBlock
*BestSucc
= selectBestSuccessor(BB
, Chain
, BlockFilter
);
568 // If an immediate successor isn't available, look for the best viable
569 // block among those we've identified as not violating the loop's CFG at
570 // this point. This won't be a fallthrough, but it will increase locality.
572 BestSucc
= selectBestCandidateBlock(Chain
, BlockWorkList
, BlockFilter
);
576 getFirstUnplacedBlock(F
, Chain
, PrevUnplacedBlockIt
, BlockFilter
);
580 DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
581 "layout successor until the CFG reduces\n");
584 // Place this block, updating the datastructures to reflect its placement.
585 BlockChain
&SuccChain
= *BlockToChain
[BestSucc
];
586 // Zero out LoopPredecessors for the successor we're about to merge in case
587 // we selected a successor that didn't fit naturally into the CFG.
588 SuccChain
.LoopPredecessors
= 0;
589 DEBUG(dbgs() << "Merging from " << getBlockNum(BB
) << " to "
590 << getBlockNum(BestSucc
) << "\n");
591 markChainSuccessors(SuccChain
, LoopHeaderBB
, BlockWorkList
, BlockFilter
);
592 Chain
.merge(BestSucc
, &SuccChain
);
593 BB
= *std::prev(Chain
.end());
596 DEBUG(dbgs() << "Finished forming chain for header block "
597 << getBlockNum(*Chain
.begin()) << "\n");
600 /// \brief Find the best loop top block for layout.
602 /// Look for a block which is strictly better than the loop header for laying
603 /// out at the top of the loop. This looks for one and only one pattern:
604 /// a latch block with no conditional exit. This block will cause a conditional
605 /// jump around it or will be the bottom of the loop if we lay it out in place,
606 /// but if it it doesn't end up at the bottom of the loop for any reason,
607 /// rotation alone won't fix it. Because such a block will always result in an
608 /// unconditional jump (for the backedge) rotating it in front of the loop
609 /// header is always profitable.
611 MachineBlockPlacement::findBestLoopTop(MachineLoop
&L
,
612 const BlockFilterSet
&LoopBlockSet
) {
613 // Check that the header hasn't been fused with a preheader block due to
614 // crazy branches. If it has, we need to start with the header at the top to
615 // prevent pulling the preheader into the loop body.
616 BlockChain
&HeaderChain
= *BlockToChain
[L
.getHeader()];
617 if (!LoopBlockSet
.count(*HeaderChain
.begin()))
618 return L
.getHeader();
620 DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(L
.getHeader())
623 BlockFrequency BestPredFreq
;
624 MachineBasicBlock
*BestPred
= nullptr;
625 for (MachineBasicBlock
*Pred
: L
.getHeader()->predecessors()) {
626 if (!LoopBlockSet
.count(Pred
))
628 DEBUG(dbgs() << " header pred: " << getBlockName(Pred
) << ", "
629 << Pred
->succ_size() << " successors, ";
630 MBFI
->printBlockFreq(dbgs(), Pred
) << " freq\n");
631 if (Pred
->succ_size() > 1)
634 BlockFrequency PredFreq
= MBFI
->getBlockFreq(Pred
);
635 if (!BestPred
|| PredFreq
> BestPredFreq
||
636 (!(PredFreq
< BestPredFreq
) &&
637 Pred
->isLayoutSuccessor(L
.getHeader()))) {
639 BestPredFreq
= PredFreq
;
643 // If no direct predecessor is fine, just use the loop header.
645 return L
.getHeader();
647 // Walk backwards through any straight line of predecessors.
648 while (BestPred
->pred_size() == 1 &&
649 (*BestPred
->pred_begin())->succ_size() == 1 &&
650 *BestPred
->pred_begin() != L
.getHeader())
651 BestPred
= *BestPred
->pred_begin();
653 DEBUG(dbgs() << " final top: " << getBlockName(BestPred
) << "\n");
657 /// \brief Find the best loop exiting block for layout.
659 /// This routine implements the logic to analyze the loop looking for the best
660 /// block to layout at the top of the loop. Typically this is done to maximize
661 /// fallthrough opportunities.
663 MachineBlockPlacement::findBestLoopExit(MachineFunction
&F
, MachineLoop
&L
,
664 const BlockFilterSet
&LoopBlockSet
) {
665 // We don't want to layout the loop linearly in all cases. If the loop header
666 // is just a normal basic block in the loop, we want to look for what block
667 // within the loop is the best one to layout at the top. However, if the loop
668 // header has be pre-merged into a chain due to predecessors not having
669 // analyzable branches, *and* the predecessor it is merged with is *not* part
670 // of the loop, rotating the header into the middle of the loop will create
671 // a non-contiguous range of blocks which is Very Bad. So start with the
672 // header and only rotate if safe.
673 BlockChain
&HeaderChain
= *BlockToChain
[L
.getHeader()];
674 if (!LoopBlockSet
.count(*HeaderChain
.begin()))
677 BlockFrequency BestExitEdgeFreq
;
678 unsigned BestExitLoopDepth
= 0;
679 MachineBasicBlock
*ExitingBB
= nullptr;
680 // If there are exits to outer loops, loop rotation can severely limit
681 // fallthrough opportunites unless it selects such an exit. Keep a set of
682 // blocks where rotating to exit with that block will reach an outer loop.
683 SmallPtrSet
<MachineBasicBlock
*, 4> BlocksExitingToOuterLoop
;
685 DEBUG(dbgs() << "Finding best loop exit for: " << getBlockName(L
.getHeader())
687 for (MachineBasicBlock
*MBB
: L
.getBlocks()) {
688 BlockChain
&Chain
= *BlockToChain
[MBB
];
689 // Ensure that this block is at the end of a chain; otherwise it could be
690 // mid-way through an inner loop or a successor of an unanalyzable branch.
691 if (MBB
!= *std::prev(Chain
.end()))
694 // Now walk the successors. We need to establish whether this has a viable
695 // exiting successor and whether it has a viable non-exiting successor.
696 // We store the old exiting state and restore it if a viable looping
697 // successor isn't found.
698 MachineBasicBlock
*OldExitingBB
= ExitingBB
;
699 BlockFrequency OldBestExitEdgeFreq
= BestExitEdgeFreq
;
700 bool HasLoopingSucc
= false;
701 // FIXME: Due to the performance of the probability and weight routines in
702 // the MBPI analysis, we use the internal weights and manually compute the
703 // probabilities to avoid quadratic behavior.
704 uint32_t WeightScale
= 0;
705 uint32_t SumWeight
= MBPI
->getSumForBlock(MBB
, WeightScale
);
706 for (MachineBasicBlock
*Succ
: MBB
->successors()) {
711 BlockChain
&SuccChain
= *BlockToChain
[Succ
];
712 // Don't split chains, either this chain or the successor's chain.
713 if (&Chain
== &SuccChain
) {
714 DEBUG(dbgs() << " exiting: " << getBlockName(MBB
) << " -> "
715 << getBlockName(Succ
) << " (chain conflict)\n");
719 uint32_t SuccWeight
= MBPI
->getEdgeWeight(MBB
, Succ
);
720 if (LoopBlockSet
.count(Succ
)) {
721 DEBUG(dbgs() << " looping: " << getBlockName(MBB
) << " -> "
722 << getBlockName(Succ
) << " (" << SuccWeight
<< ")\n");
723 HasLoopingSucc
= true;
727 unsigned SuccLoopDepth
= 0;
728 if (MachineLoop
*ExitLoop
= MLI
->getLoopFor(Succ
)) {
729 SuccLoopDepth
= ExitLoop
->getLoopDepth();
730 if (ExitLoop
->contains(&L
))
731 BlocksExitingToOuterLoop
.insert(MBB
);
734 BranchProbability
SuccProb(SuccWeight
/ WeightScale
, SumWeight
);
735 BlockFrequency ExitEdgeFreq
= MBFI
->getBlockFreq(MBB
) * SuccProb
;
736 DEBUG(dbgs() << " exiting: " << getBlockName(MBB
) << " -> "
737 << getBlockName(Succ
) << " [L:" << SuccLoopDepth
<< "] (";
738 MBFI
->printBlockFreq(dbgs(), ExitEdgeFreq
) << ")\n");
739 // Note that we bias this toward an existing layout successor to retain
740 // incoming order in the absence of better information. The exit must have
741 // a frequency higher than the current exit before we consider breaking
743 BranchProbability
Bias(100 - ExitBlockBias
, 100);
744 if (!ExitingBB
|| SuccLoopDepth
> BestExitLoopDepth
||
745 ExitEdgeFreq
> BestExitEdgeFreq
||
746 (MBB
->isLayoutSuccessor(Succ
) &&
747 !(ExitEdgeFreq
< BestExitEdgeFreq
* Bias
))) {
748 BestExitEdgeFreq
= ExitEdgeFreq
;
753 if (!HasLoopingSucc
) {
754 // Restore the old exiting state, no viable looping successor was found.
755 ExitingBB
= OldExitingBB
;
756 BestExitEdgeFreq
= OldBestExitEdgeFreq
;
760 // Without a candidate exiting block or with only a single block in the
761 // loop, just use the loop header to layout the loop.
762 if (!ExitingBB
|| L
.getNumBlocks() == 1)
765 // Also, if we have exit blocks which lead to outer loops but didn't select
766 // one of them as the exiting block we are rotating toward, disable loop
767 // rotation altogether.
768 if (!BlocksExitingToOuterLoop
.empty() &&
769 !BlocksExitingToOuterLoop
.count(ExitingBB
))
772 DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB
) << "\n");
776 /// \brief Attempt to rotate an exiting block to the bottom of the loop.
778 /// Once we have built a chain, try to rotate it to line up the hot exit block
779 /// with fallthrough out of the loop if doing so doesn't introduce unnecessary
780 /// branches. For example, if the loop has fallthrough into its header and out
781 /// of its bottom already, don't rotate it.
782 void MachineBlockPlacement::rotateLoop(BlockChain
&LoopChain
,
783 MachineBasicBlock
*ExitingBB
,
784 const BlockFilterSet
&LoopBlockSet
) {
788 MachineBasicBlock
*Top
= *LoopChain
.begin();
789 bool ViableTopFallthrough
= false;
790 for (MachineBasicBlock
*Pred
: Top
->predecessors()) {
791 BlockChain
*PredChain
= BlockToChain
[Pred
];
792 if (!LoopBlockSet
.count(Pred
) &&
793 (!PredChain
|| Pred
== *std::prev(PredChain
->end()))) {
794 ViableTopFallthrough
= true;
799 // If the header has viable fallthrough, check whether the current loop
800 // bottom is a viable exiting block. If so, bail out as rotating will
801 // introduce an unnecessary branch.
802 if (ViableTopFallthrough
) {
803 MachineBasicBlock
*Bottom
= *std::prev(LoopChain
.end());
804 for (MachineBasicBlock
*Succ
: Bottom
->successors()) {
805 BlockChain
*SuccChain
= BlockToChain
[Succ
];
806 if (!LoopBlockSet
.count(Succ
) &&
807 (!SuccChain
|| Succ
== *SuccChain
->begin()))
812 BlockChain::iterator ExitIt
=
813 std::find(LoopChain
.begin(), LoopChain
.end(), ExitingBB
);
814 if (ExitIt
== LoopChain
.end())
817 std::rotate(LoopChain
.begin(), std::next(ExitIt
), LoopChain
.end());
820 /// \brief Attempt to rotate a loop based on profile data to reduce branch cost.
822 /// With profile data, we can determine the cost in terms of missed fall through
823 /// opportunities when rotating a loop chain and select the best rotation.
824 /// Basically, there are three kinds of cost to consider for each rotation:
825 /// 1. The possibly missed fall through edge (if it exists) from BB out of
826 /// the loop to the loop header.
827 /// 2. The possibly missed fall through edges (if they exist) from the loop
828 /// exits to BB out of the loop.
829 /// 3. The missed fall through edge (if it exists) from the last BB to the
830 /// first BB in the loop chain.
831 /// Therefore, the cost for a given rotation is the sum of costs listed above.
832 /// We select the best rotation with the smallest cost.
833 void MachineBlockPlacement::rotateLoopWithProfile(
834 BlockChain
&LoopChain
, MachineLoop
&L
, const BlockFilterSet
&LoopBlockSet
) {
835 auto HeaderBB
= L
.getHeader();
836 auto HeaderIter
= std::find(LoopChain
.begin(), LoopChain
.end(), HeaderBB
);
837 auto RotationPos
= LoopChain
.end();
839 BlockFrequency SmallestRotationCost
= BlockFrequency::getMaxFrequency();
841 // A utility lambda that scales up a block frequency by dividing it by a
842 // branch probability which is the reciprocal of the scale.
843 auto ScaleBlockFrequency
= [](BlockFrequency Freq
,
844 unsigned Scale
) -> BlockFrequency
{
847 // Use operator / between BlockFrequency and BranchProbability to implement
848 // saturating multiplication.
849 return Freq
/ BranchProbability(1, Scale
);
852 // Compute the cost of the missed fall-through edge to the loop header if the
853 // chain head is not the loop header. As we only consider natural loops with
854 // single header, this computation can be done only once.
855 BlockFrequency
HeaderFallThroughCost(0);
856 for (auto *Pred
: HeaderBB
->predecessors()) {
857 BlockChain
*PredChain
= BlockToChain
[Pred
];
858 if (!LoopBlockSet
.count(Pred
) &&
859 (!PredChain
|| Pred
== *std::prev(PredChain
->end()))) {
861 MBFI
->getBlockFreq(Pred
) * MBPI
->getEdgeProbability(Pred
, HeaderBB
);
862 auto FallThruCost
= ScaleBlockFrequency(EdgeFreq
, MisfetchCost
);
863 // If the predecessor has only an unconditional jump to the header, we
864 // need to consider the cost of this jump.
865 if (Pred
->succ_size() == 1)
866 FallThruCost
+= ScaleBlockFrequency(EdgeFreq
, JumpInstCost
);
867 HeaderFallThroughCost
= std::max(HeaderFallThroughCost
, FallThruCost
);
871 // Here we collect all exit blocks in the loop, and for each exit we find out
872 // its hottest exit edge. For each loop rotation, we define the loop exit cost
873 // as the sum of frequencies of exit edges we collect here, excluding the exit
874 // edge from the tail of the loop chain.
875 SmallVector
<std::pair
<MachineBasicBlock
*, BlockFrequency
>, 4> ExitsWithFreq
;
876 for (auto BB
: LoopChain
) {
877 uint32_t LargestExitEdgeWeight
= 0;
878 for (auto *Succ
: BB
->successors()) {
879 BlockChain
*SuccChain
= BlockToChain
[Succ
];
880 if (!LoopBlockSet
.count(Succ
) &&
881 (!SuccChain
|| Succ
== *SuccChain
->begin())) {
882 uint32_t SuccWeight
= MBPI
->getEdgeWeight(BB
, Succ
);
883 LargestExitEdgeWeight
= std::max(LargestExitEdgeWeight
, SuccWeight
);
886 if (LargestExitEdgeWeight
> 0) {
887 uint32_t WeightScale
= 0;
888 uint32_t SumWeight
= MBPI
->getSumForBlock(BB
, WeightScale
);
890 MBFI
->getBlockFreq(BB
) *
891 BranchProbability(LargestExitEdgeWeight
/ WeightScale
, SumWeight
);
892 ExitsWithFreq
.emplace_back(BB
, ExitFreq
);
896 // In this loop we iterate every block in the loop chain and calculate the
897 // cost assuming the block is the head of the loop chain. When the loop ends,
898 // we should have found the best candidate as the loop chain's head.
899 for (auto Iter
= LoopChain
.begin(), TailIter
= std::prev(LoopChain
.end()),
900 EndIter
= LoopChain
.end();
901 Iter
!= EndIter
; Iter
++, TailIter
++) {
902 // TailIter is used to track the tail of the loop chain if the block we are
903 // checking (pointed by Iter) is the head of the chain.
904 if (TailIter
== LoopChain
.end())
905 TailIter
= LoopChain
.begin();
907 auto TailBB
= *TailIter
;
909 // Calculate the cost by putting this BB to the top.
910 BlockFrequency Cost
= 0;
912 // If the current BB is the loop header, we need to take into account the
913 // cost of the missed fall through edge from outside of the loop to the
915 if (Iter
!= HeaderIter
)
916 Cost
+= HeaderFallThroughCost
;
918 // Collect the loop exit cost by summing up frequencies of all exit edges
919 // except the one from the chain tail.
920 for (auto &ExitWithFreq
: ExitsWithFreq
)
921 if (TailBB
!= ExitWithFreq
.first
)
922 Cost
+= ExitWithFreq
.second
;
924 // The cost of breaking the once fall-through edge from the tail to the top
925 // of the loop chain. Here we need to consider three cases:
926 // 1. If the tail node has only one successor, then we will get an
927 // additional jmp instruction. So the cost here is (MisfetchCost +
928 // JumpInstCost) * tail node frequency.
929 // 2. If the tail node has two successors, then we may still get an
930 // additional jmp instruction if the layout successor after the loop
931 // chain is not its CFG successor. Note that the more frequently executed
932 // jmp instruction will be put ahead of the other one. Assume the
933 // frequency of those two branches are x and y, where x is the frequency
934 // of the edge to the chain head, then the cost will be
935 // (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency.
936 // 3. If the tail node has more than two successors (this rarely happens),
937 // we won't consider any additional cost.
938 if (TailBB
->isSuccessor(*Iter
)) {
939 auto TailBBFreq
= MBFI
->getBlockFreq(TailBB
);
940 if (TailBB
->succ_size() == 1)
941 Cost
+= ScaleBlockFrequency(TailBBFreq
.getFrequency(),
942 MisfetchCost
+ JumpInstCost
);
943 else if (TailBB
->succ_size() == 2) {
944 auto TailToHeadProb
= MBPI
->getEdgeProbability(TailBB
, *Iter
);
945 auto TailToHeadFreq
= TailBBFreq
* TailToHeadProb
;
946 auto ColderEdgeFreq
= TailToHeadProb
> BranchProbability(1, 2)
947 ? TailBBFreq
* TailToHeadProb
.getCompl()
949 Cost
+= ScaleBlockFrequency(TailToHeadFreq
, MisfetchCost
) +
950 ScaleBlockFrequency(ColderEdgeFreq
, JumpInstCost
);
954 DEBUG(dbgs() << "The cost of loop rotation by making " << getBlockNum(*Iter
)
955 << " to the top: " << Cost
.getFrequency() << "\n");
957 if (Cost
< SmallestRotationCost
) {
958 SmallestRotationCost
= Cost
;
963 if (RotationPos
!= LoopChain
.end()) {
964 DEBUG(dbgs() << "Rotate loop by making " << getBlockNum(*RotationPos
)
966 std::rotate(LoopChain
.begin(), RotationPos
, LoopChain
.end());
970 /// \brief Collect blocks in the given loop that are to be placed.
972 /// When profile data is available, exclude cold blocks from the returned set;
973 /// otherwise, collect all blocks in the loop.
974 MachineBlockPlacement::BlockFilterSet
975 MachineBlockPlacement::collectLoopBlockSet(MachineFunction
&F
, MachineLoop
&L
) {
976 BlockFilterSet LoopBlockSet
;
978 // Filter cold blocks off from LoopBlockSet when profile data is available.
979 // Collect the sum of frequencies of incoming edges to the loop header from
980 // outside. If we treat the loop as a super block, this is the frequency of
981 // the loop. Then for each block in the loop, we calculate the ratio between
982 // its frequency and the frequency of the loop block. When it is too small,
983 // don't add it to the loop chain. If there are outer loops, then this block
984 // will be merged into the first outer loop chain for which this block is not
985 // cold anymore. This needs precise profile data and we only do this when
986 // profile data is available.
987 if (F
.getFunction()->getEntryCount()) {
988 BlockFrequency
LoopFreq(0);
989 for (auto LoopPred
: L
.getHeader()->predecessors())
990 if (!L
.contains(LoopPred
))
991 LoopFreq
+= MBFI
->getBlockFreq(LoopPred
) *
992 MBPI
->getEdgeProbability(LoopPred
, L
.getHeader());
994 for (MachineBasicBlock
*LoopBB
: L
.getBlocks()) {
995 auto Freq
= MBFI
->getBlockFreq(LoopBB
).getFrequency();
996 if (Freq
== 0 || LoopFreq
.getFrequency() / Freq
> LoopToColdBlockRatio
)
998 LoopBlockSet
.insert(LoopBB
);
1001 LoopBlockSet
.insert(L
.block_begin(), L
.block_end());
1003 return LoopBlockSet
;
1006 /// \brief Forms basic block chains from the natural loop structures.
1008 /// These chains are designed to preserve the existing *structure* of the code
1009 /// as much as possible. We can then stitch the chains together in a way which
1010 /// both preserves the topological structure and minimizes taken conditional
1012 void MachineBlockPlacement::buildLoopChains(MachineFunction
&F
,
1014 // First recurse through any nested loops, building chains for those inner
1016 for (MachineLoop
*InnerLoop
: L
)
1017 buildLoopChains(F
, *InnerLoop
);
1019 SmallVector
<MachineBasicBlock
*, 16> BlockWorkList
;
1020 BlockFilterSet LoopBlockSet
= collectLoopBlockSet(F
, L
);
1022 // Check if we have profile data for this function. If yes, we will rotate
1023 // this loop by modeling costs more precisely which requires the profile data
1024 // for better layout.
1025 bool RotateLoopWithProfile
=
1026 PreciseRotationCost
&& F
.getFunction()->getEntryCount();
1028 // First check to see if there is an obviously preferable top block for the
1029 // loop. This will default to the header, but may end up as one of the
1030 // predecessors to the header if there is one which will result in strictly
1031 // fewer branches in the loop body.
1032 // When we use profile data to rotate the loop, this is unnecessary.
1033 MachineBasicBlock
*LoopTop
=
1034 RotateLoopWithProfile
? L
.getHeader() : findBestLoopTop(L
, LoopBlockSet
);
1036 // If we selected just the header for the loop top, look for a potentially
1037 // profitable exit block in the event that rotating the loop can eliminate
1038 // branches by placing an exit edge at the bottom.
1039 MachineBasicBlock
*ExitingBB
= nullptr;
1040 if (!RotateLoopWithProfile
&& LoopTop
== L
.getHeader())
1041 ExitingBB
= findBestLoopExit(F
, L
, LoopBlockSet
);
1043 BlockChain
&LoopChain
= *BlockToChain
[LoopTop
];
1045 // FIXME: This is a really lame way of walking the chains in the loop: we
1046 // walk the blocks, and use a set to prevent visiting a particular chain
1048 SmallPtrSet
<BlockChain
*, 4> UpdatedPreds
;
1049 assert(LoopChain
.LoopPredecessors
== 0);
1050 UpdatedPreds
.insert(&LoopChain
);
1052 for (MachineBasicBlock
*LoopBB
: LoopBlockSet
) {
1053 BlockChain
&Chain
= *BlockToChain
[LoopBB
];
1054 if (!UpdatedPreds
.insert(&Chain
).second
)
1057 assert(Chain
.LoopPredecessors
== 0);
1058 for (MachineBasicBlock
*ChainBB
: Chain
) {
1059 assert(BlockToChain
[ChainBB
] == &Chain
);
1060 for (MachineBasicBlock
*Pred
: ChainBB
->predecessors()) {
1061 if (BlockToChain
[Pred
] == &Chain
|| !LoopBlockSet
.count(Pred
))
1063 ++Chain
.LoopPredecessors
;
1067 if (Chain
.LoopPredecessors
== 0)
1068 BlockWorkList
.push_back(*Chain
.begin());
1071 buildChain(LoopTop
, LoopChain
, BlockWorkList
, &LoopBlockSet
);
1073 if (RotateLoopWithProfile
)
1074 rotateLoopWithProfile(LoopChain
, L
, LoopBlockSet
);
1076 rotateLoop(LoopChain
, ExitingBB
, LoopBlockSet
);
1079 // Crash at the end so we get all of the debugging output first.
1080 bool BadLoop
= false;
1081 if (LoopChain
.LoopPredecessors
) {
1083 dbgs() << "Loop chain contains a block without its preds placed!\n"
1084 << " Loop header: " << getBlockName(*L
.block_begin()) << "\n"
1085 << " Chain header: " << getBlockName(*LoopChain
.begin()) << "\n";
1087 for (MachineBasicBlock
*ChainBB
: LoopChain
) {
1088 dbgs() << " ... " << getBlockName(ChainBB
) << "\n";
1089 if (!LoopBlockSet
.erase(ChainBB
)) {
1090 // We don't mark the loop as bad here because there are real situations
1091 // where this can occur. For example, with an unanalyzable fallthrough
1092 // from a loop block to a non-loop block or vice versa.
1093 dbgs() << "Loop chain contains a block not contained by the loop!\n"
1094 << " Loop header: " << getBlockName(*L
.block_begin()) << "\n"
1095 << " Chain header: " << getBlockName(*LoopChain
.begin()) << "\n"
1096 << " Bad block: " << getBlockName(ChainBB
) << "\n";
1100 if (!LoopBlockSet
.empty()) {
1102 for (MachineBasicBlock
*LoopBB
: LoopBlockSet
)
1103 dbgs() << "Loop contains blocks never placed into a chain!\n"
1104 << " Loop header: " << getBlockName(*L
.block_begin()) << "\n"
1105 << " Chain header: " << getBlockName(*LoopChain
.begin()) << "\n"
1106 << " Bad block: " << getBlockName(LoopBB
) << "\n";
1108 assert(!BadLoop
&& "Detected problems with the placement of this loop.");
1112 void MachineBlockPlacement::buildCFGChains(MachineFunction
&F
) {
1113 // Ensure that every BB in the function has an associated chain to simplify
1114 // the assumptions of the remaining algorithm.
1115 SmallVector
<MachineOperand
, 4> Cond
; // For AnalyzeBranch.
1116 for (MachineFunction::iterator FI
= F
.begin(), FE
= F
.end(); FI
!= FE
; ++FI
) {
1117 MachineBasicBlock
*BB
= &*FI
;
1119 new (ChainAllocator
.Allocate()) BlockChain(BlockToChain
, BB
);
1120 // Also, merge any blocks which we cannot reason about and must preserve
1121 // the exact fallthrough behavior for.
1124 MachineBasicBlock
*TBB
= nullptr, *FBB
= nullptr; // For AnalyzeBranch.
1125 if (!TII
->AnalyzeBranch(*BB
, TBB
, FBB
, Cond
) || !FI
->canFallThrough())
1128 MachineFunction::iterator NextFI
= std::next(FI
);
1129 MachineBasicBlock
*NextBB
= &*NextFI
;
1130 // Ensure that the layout successor is a viable block, as we know that
1131 // fallthrough is a possibility.
1132 assert(NextFI
!= FE
&& "Can't fallthrough past the last block.");
1133 DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
1134 << getBlockName(BB
) << " -> " << getBlockName(NextBB
)
1136 Chain
->merge(NextBB
, nullptr);
1142 if (OutlineOptionalBranches
) {
1143 // Find the nearest common dominator of all of F's terminators.
1144 MachineBasicBlock
*Terminator
= nullptr;
1145 for (MachineBasicBlock
&MBB
: F
) {
1146 if (MBB
.succ_size() == 0) {
1147 if (Terminator
== nullptr)
1150 Terminator
= MDT
->findNearestCommonDominator(Terminator
, &MBB
);
1154 // MBBs dominating this common dominator are unavoidable.
1155 UnavoidableBlocks
.clear();
1156 for (MachineBasicBlock
&MBB
: F
) {
1157 if (MDT
->dominates(&MBB
, Terminator
)) {
1158 UnavoidableBlocks
.insert(&MBB
);
1163 // Build any loop-based chains.
1164 for (MachineLoop
*L
: *MLI
)
1165 buildLoopChains(F
, *L
);
1167 SmallVector
<MachineBasicBlock
*, 16> BlockWorkList
;
1169 SmallPtrSet
<BlockChain
*, 4> UpdatedPreds
;
1170 for (MachineBasicBlock
&MBB
: F
) {
1171 BlockChain
&Chain
= *BlockToChain
[&MBB
];
1172 if (!UpdatedPreds
.insert(&Chain
).second
)
1175 assert(Chain
.LoopPredecessors
== 0);
1176 for (MachineBasicBlock
*ChainBB
: Chain
) {
1177 assert(BlockToChain
[ChainBB
] == &Chain
);
1178 for (MachineBasicBlock
*Pred
: ChainBB
->predecessors()) {
1179 if (BlockToChain
[Pred
] == &Chain
)
1181 ++Chain
.LoopPredecessors
;
1185 if (Chain
.LoopPredecessors
== 0)
1186 BlockWorkList
.push_back(*Chain
.begin());
1189 BlockChain
&FunctionChain
= *BlockToChain
[&F
.front()];
1190 buildChain(&F
.front(), FunctionChain
, BlockWorkList
);
1193 typedef SmallPtrSet
<MachineBasicBlock
*, 16> FunctionBlockSetType
;
1196 // Crash at the end so we get all of the debugging output first.
1197 bool BadFunc
= false;
1198 FunctionBlockSetType FunctionBlockSet
;
1199 for (MachineBasicBlock
&MBB
: F
)
1200 FunctionBlockSet
.insert(&MBB
);
1202 for (MachineBasicBlock
*ChainBB
: FunctionChain
)
1203 if (!FunctionBlockSet
.erase(ChainBB
)) {
1205 dbgs() << "Function chain contains a block not in the function!\n"
1206 << " Bad block: " << getBlockName(ChainBB
) << "\n";
1209 if (!FunctionBlockSet
.empty()) {
1211 for (MachineBasicBlock
*RemainingBB
: FunctionBlockSet
)
1212 dbgs() << "Function contains blocks never placed into a chain!\n"
1213 << " Bad block: " << getBlockName(RemainingBB
) << "\n";
1215 assert(!BadFunc
&& "Detected problems with the block placement.");
1218 // Splice the blocks into place.
1219 MachineFunction::iterator InsertPos
= F
.begin();
1220 for (MachineBasicBlock
*ChainBB
: FunctionChain
) {
1221 DEBUG(dbgs() << (ChainBB
== *FunctionChain
.begin() ? "Placing chain "
1223 << getBlockName(ChainBB
) << "\n");
1224 if (InsertPos
!= MachineFunction::iterator(ChainBB
))
1225 F
.splice(InsertPos
, ChainBB
);
1229 // Update the terminator of the previous block.
1230 if (ChainBB
== *FunctionChain
.begin())
1232 MachineBasicBlock
*PrevBB
= &*std::prev(MachineFunction::iterator(ChainBB
));
1234 // FIXME: It would be awesome of updateTerminator would just return rather
1235 // than assert when the branch cannot be analyzed in order to remove this
1238 MachineBasicBlock
*TBB
= nullptr, *FBB
= nullptr; // For AnalyzeBranch.
1239 if (!TII
->AnalyzeBranch(*PrevBB
, TBB
, FBB
, Cond
)) {
1240 // The "PrevBB" is not yet updated to reflect current code layout, so,
1241 // o. it may fall-through to a block without explict "goto" instruction
1242 // before layout, and no longer fall-through it after layout; or
1243 // o. just opposite.
1245 // AnalyzeBranch() may return erroneous value for FBB when these two
1246 // situations take place. For the first scenario FBB is mistakenly set
1247 // NULL; for the 2nd scenario, the FBB, which is expected to be NULL,
1248 // is mistakenly pointing to "*BI".
1250 bool needUpdateBr
= true;
1251 if (!Cond
.empty() && (!FBB
|| FBB
== ChainBB
)) {
1252 PrevBB
->updateTerminator();
1253 needUpdateBr
= false;
1255 TBB
= FBB
= nullptr;
1256 if (TII
->AnalyzeBranch(*PrevBB
, TBB
, FBB
, Cond
)) {
1257 // FIXME: This should never take place.
1258 TBB
= FBB
= nullptr;
1262 // If PrevBB has a two-way branch, try to re-order the branches
1263 // such that we branch to the successor with higher weight first.
1264 if (TBB
&& !Cond
.empty() && FBB
&&
1265 MBPI
->getEdgeWeight(PrevBB
, FBB
) > MBPI
->getEdgeWeight(PrevBB
, TBB
) &&
1266 !TII
->ReverseBranchCondition(Cond
)) {
1267 DEBUG(dbgs() << "Reverse order of the two branches: "
1268 << getBlockName(PrevBB
) << "\n");
1269 DEBUG(dbgs() << " Edge weight: " << MBPI
->getEdgeWeight(PrevBB
, FBB
)
1270 << " vs " << MBPI
->getEdgeWeight(PrevBB
, TBB
) << "\n");
1271 DebugLoc dl
; // FIXME: this is nowhere
1272 TII
->RemoveBranch(*PrevBB
);
1273 TII
->InsertBranch(*PrevBB
, FBB
, TBB
, Cond
, dl
);
1274 needUpdateBr
= true;
1277 PrevBB
->updateTerminator();
1281 // Fixup the last block.
1283 MachineBasicBlock
*TBB
= nullptr, *FBB
= nullptr; // For AnalyzeBranch.
1284 if (!TII
->AnalyzeBranch(F
.back(), TBB
, FBB
, Cond
))
1285 F
.back().updateTerminator();
1287 // Walk through the backedges of the function now that we have fully laid out
1288 // the basic blocks and align the destination of each backedge. We don't rely
1289 // exclusively on the loop info here so that we can align backedges in
1290 // unnatural CFGs and backedges that were introduced purely because of the
1291 // loop rotations done during this layout pass.
1292 // FIXME: Use Function::optForSize().
1293 if (F
.getFunction()->hasFnAttribute(Attribute::OptimizeForSize
))
1295 if (FunctionChain
.begin() == FunctionChain
.end())
1296 return; // Empty chain.
1298 const BranchProbability
ColdProb(1, 5); // 20%
1299 BlockFrequency EntryFreq
= MBFI
->getBlockFreq(&F
.front());
1300 BlockFrequency WeightedEntryFreq
= EntryFreq
* ColdProb
;
1301 for (MachineBasicBlock
*ChainBB
: FunctionChain
) {
1302 if (ChainBB
== *FunctionChain
.begin())
1305 // Don't align non-looping basic blocks. These are unlikely to execute
1306 // enough times to matter in practice. Note that we'll still handle
1307 // unnatural CFGs inside of a natural outer loop (the common case) and
1309 MachineLoop
*L
= MLI
->getLoopFor(ChainBB
);
1313 unsigned Align
= TLI
->getPrefLoopAlignment(L
);
1315 continue; // Don't care about loop alignment.
1317 // If the block is cold relative to the function entry don't waste space
1319 BlockFrequency Freq
= MBFI
->getBlockFreq(ChainBB
);
1320 if (Freq
< WeightedEntryFreq
)
1323 // If the block is cold relative to its loop header, don't align it
1324 // regardless of what edges into the block exist.
1325 MachineBasicBlock
*LoopHeader
= L
->getHeader();
1326 BlockFrequency LoopHeaderFreq
= MBFI
->getBlockFreq(LoopHeader
);
1327 if (Freq
< (LoopHeaderFreq
* ColdProb
))
1330 // Check for the existence of a non-layout predecessor which would benefit
1331 // from aligning this block.
1332 MachineBasicBlock
*LayoutPred
=
1333 &*std::prev(MachineFunction::iterator(ChainBB
));
1335 // Force alignment if all the predecessors are jumps. We already checked
1336 // that the block isn't cold above.
1337 if (!LayoutPred
->isSuccessor(ChainBB
)) {
1338 ChainBB
->setAlignment(Align
);
1342 // Align this block if the layout predecessor's edge into this block is
1343 // cold relative to the block. When this is true, other predecessors make up
1344 // all of the hot entries into the block and thus alignment is likely to be
1346 BranchProbability LayoutProb
=
1347 MBPI
->getEdgeProbability(LayoutPred
, ChainBB
);
1348 BlockFrequency LayoutEdgeFreq
= MBFI
->getBlockFreq(LayoutPred
) * LayoutProb
;
1349 if (LayoutEdgeFreq
<= (Freq
* ColdProb
))
1350 ChainBB
->setAlignment(Align
);
1354 bool MachineBlockPlacement::runOnMachineFunction(MachineFunction
&F
) {
1355 // Check for single-block functions and skip them.
1356 if (std::next(F
.begin()) == F
.end())
1359 if (skipOptnoneFunction(*F
.getFunction()))
1362 MBPI
= &getAnalysis
<MachineBranchProbabilityInfo
>();
1363 MBFI
= &getAnalysis
<MachineBlockFrequencyInfo
>();
1364 MLI
= &getAnalysis
<MachineLoopInfo
>();
1365 TII
= F
.getSubtarget().getInstrInfo();
1366 TLI
= F
.getSubtarget().getTargetLowering();
1367 MDT
= &getAnalysis
<MachineDominatorTree
>();
1368 assert(BlockToChain
.empty());
1372 BlockToChain
.clear();
1373 ChainAllocator
.DestroyAll();
1376 // Align all of the blocks in the function to a specific alignment.
1377 for (MachineBasicBlock
&MBB
: F
)
1378 MBB
.setAlignment(AlignAllBlock
);
1380 // We always return true as we have no way to track whether the final order
1381 // differs from the original order.
1386 /// \brief A pass to compute block placement statistics.
1388 /// A separate pass to compute interesting statistics for evaluating block
1389 /// placement. This is separate from the actual placement pass so that they can
1390 /// be computed in the absence of any placement transformations or when using
1391 /// alternative placement strategies.
1392 class MachineBlockPlacementStats
: public MachineFunctionPass
{
1393 /// \brief A handle to the branch probability pass.
1394 const MachineBranchProbabilityInfo
*MBPI
;
1396 /// \brief A handle to the function-wide block frequency pass.
1397 const MachineBlockFrequencyInfo
*MBFI
;
1400 static char ID
; // Pass identification, replacement for typeid
1401 MachineBlockPlacementStats() : MachineFunctionPass(ID
) {
1402 initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
1405 bool runOnMachineFunction(MachineFunction
&F
) override
;
1407 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
1408 AU
.addRequired
<MachineBranchProbabilityInfo
>();
1409 AU
.addRequired
<MachineBlockFrequencyInfo
>();
1410 AU
.setPreservesAll();
1411 MachineFunctionPass::getAnalysisUsage(AU
);
1416 char MachineBlockPlacementStats::ID
= 0;
1417 char &llvm::MachineBlockPlacementStatsID
= MachineBlockPlacementStats::ID
;
1418 INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats
, "block-placement-stats",
1419 "Basic Block Placement Stats", false, false)
1420 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo
)
1421 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo
)
1422 INITIALIZE_PASS_END(MachineBlockPlacementStats
, "block-placement-stats",
1423 "Basic Block Placement Stats", false, false)
1425 bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction
&F
) {
1426 // Check for single-block functions and skip them.
1427 if (std::next(F
.begin()) == F
.end())
1430 MBPI
= &getAnalysis
<MachineBranchProbabilityInfo
>();
1431 MBFI
= &getAnalysis
<MachineBlockFrequencyInfo
>();
1433 for (MachineBasicBlock
&MBB
: F
) {
1434 BlockFrequency BlockFreq
= MBFI
->getBlockFreq(&MBB
);
1435 Statistic
&NumBranches
=
1436 (MBB
.succ_size() > 1) ? NumCondBranches
: NumUncondBranches
;
1437 Statistic
&BranchTakenFreq
=
1438 (MBB
.succ_size() > 1) ? CondBranchTakenFreq
: UncondBranchTakenFreq
;
1439 for (MachineBasicBlock
*Succ
: MBB
.successors()) {
1440 // Skip if this successor is a fallthrough.
1441 if (MBB
.isLayoutSuccessor(Succ
))
1444 BlockFrequency EdgeFreq
=
1445 BlockFreq
* MBPI
->getEdgeProbability(&MBB
, Succ
);
1447 BranchTakenFreq
+= EdgeFreq
.getFrequency();