blob: 332755d0ff4b47cb074eafd8f1ca502193db105c [file] [log] [blame]
Chandler Carruth10281422011-10-21 06:46:38 +00001//===-- MachineBlockPlacement.cpp - Basic Block Code Layout optimization --===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chandler Carruthbd1be4d2011-10-23 09:18:45 +000010// This file implements basic block placement transformations using the CFG
11// structure and branch probability estimates.
Chandler Carruth10281422011-10-21 06:46:38 +000012//
Chandler Carruthbd1be4d2011-10-23 09:18:45 +000013// The pass strives to preserve the structure of the CFG (that is, retain
Benjamin Kramerbde91762012-06-02 10:20:22 +000014// a topological ordering of basic blocks) in the absence of a *strong* signal
Chandler Carruthbd1be4d2011-10-23 09:18:45 +000015// to the contrary from probabilities. However, within the CFG structure, it
16// attempts to choose an ordering which favors placing more likely sequences of
17// blocks adjacent to each other.
18//
19// The algorithm works from the inner-most loop within a function outward, and
20// at each stage walks through the basic blocks, trying to coalesce them into
21// sequential chains where allowed by the CFG (or demanded by heavy
22// probabilities). Finally, it walks the blocks in topological order, and the
23// first time it reaches a chain of basic blocks, it schedules them in the
24// function in-order.
Chandler Carruth10281422011-10-21 06:46:38 +000025//
26//===----------------------------------------------------------------------===//
27
Chandler Carruthed0881b2012-12-03 16:50:05 +000028#include "llvm/CodeGen/Passes.h"
Haicheng Wu5b458cc2016-06-09 15:24:29 +000029#include "llvm/CodeGen/TargetPassConfig.h"
30#include "BranchFolding.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/ADT/DenseMap.h"
32#include "llvm/ADT/SmallPtrSet.h"
33#include "llvm/ADT/SmallVector.h"
34#include "llvm/ADT/Statistic.h"
Chandler Carruth8b9737c2011-10-21 08:57:37 +000035#include "llvm/CodeGen/MachineBasicBlock.h"
Chandler Carruth10281422011-10-21 06:46:38 +000036#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
37#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Daniel Jasper471e8562015-03-04 11:05:34 +000038#include "llvm/CodeGen/MachineDominators.h"
Chandler Carruth10281422011-10-21 06:46:38 +000039#include "llvm/CodeGen/MachineFunction.h"
Chandler Carruth10281422011-10-21 06:46:38 +000040#include "llvm/CodeGen/MachineFunctionPass.h"
Chandler Carruth8b9737c2011-10-21 08:57:37 +000041#include "llvm/CodeGen/MachineLoopInfo.h"
42#include "llvm/CodeGen/MachineModuleInfo.h"
Chandler Carruth10281422011-10-21 06:46:38 +000043#include "llvm/Support/Allocator.h"
Nadav Rotemc3b0f502013-04-12 00:48:32 +000044#include "llvm/Support/CommandLine.h"
Chandler Carruthbd1be4d2011-10-23 09:18:45 +000045#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000046#include "llvm/Support/raw_ostream.h"
Chandler Carruth10281422011-10-21 06:46:38 +000047#include "llvm/Target/TargetInstrInfo.h"
Chandler Carruth8b9737c2011-10-21 08:57:37 +000048#include "llvm/Target/TargetLowering.h"
Eric Christopherd9134482014-08-04 21:25:23 +000049#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruth10281422011-10-21 06:46:38 +000050#include <algorithm>
51using namespace llvm;
52
Chandler Carruthd0dced52015-03-05 02:28:25 +000053#define DEBUG_TYPE "block-placement"
Chandler Carruth1b9dde02014-04-22 02:02:50 +000054
Chandler Carruthae4e8002011-11-02 07:17:12 +000055STATISTIC(NumCondBranches, "Number of conditional branches");
Craig Topper77ec0772015-09-16 03:52:32 +000056STATISTIC(NumUncondBranches, "Number of unconditional branches");
Chandler Carruthae4e8002011-11-02 07:17:12 +000057STATISTIC(CondBranchTakenFreq,
58 "Potential frequency of taking conditional branches");
59STATISTIC(UncondBranchTakenFreq,
60 "Potential frequency of taking unconditional branches");
61
Nadav Rotemc3b0f502013-04-12 00:48:32 +000062static cl::opt<unsigned> AlignAllBlock("align-all-blocks",
63 cl::desc("Force the alignment of all "
64 "blocks in the function."),
65 cl::init(0), cl::Hidden);
66
Geoff Berry10494ac2016-01-21 17:25:52 +000067static cl::opt<unsigned> AlignAllNonFallThruBlocks(
68 "align-all-nofallthru-blocks",
69 cl::desc("Force the alignment of all "
70 "blocks that have no fall-through predecessors (i.e. don't add "
71 "nops that are executed)."),
72 cl::init(0), cl::Hidden);
73
Benjamin Kramerc8160d62013-11-20 19:08:44 +000074// FIXME: Find a good default for this flag and remove the flag.
Chandler Carruth2fc3fe12015-03-05 02:35:31 +000075static cl::opt<unsigned> ExitBlockBias(
76 "block-placement-exit-block-bias",
77 cl::desc("Block frequency percentage a loop exit block needs "
78 "over the original exit to be considered the new exit."),
79 cl::init(0), cl::Hidden);
Benjamin Kramerc8160d62013-11-20 19:08:44 +000080
Daniel Jasper471e8562015-03-04 11:05:34 +000081static cl::opt<bool> OutlineOptionalBranches(
82 "outline-optional-branches",
83 cl::desc("Put completely optional branches, i.e. branches with a common "
84 "post dominator, out of line."),
85 cl::init(false), cl::Hidden);
86
Daniel Jasper214997c2015-03-20 10:00:37 +000087static cl::opt<unsigned> OutlineOptionalThreshold(
88 "outline-optional-threshold",
89 cl::desc("Don't outline optional branches that are a single block with an "
90 "instruction count below this threshold"),
91 cl::init(4), cl::Hidden);
92
Cong Houb90b9e02015-11-02 21:24:00 +000093static cl::opt<unsigned> LoopToColdBlockRatio(
94 "loop-to-cold-block-ratio",
95 cl::desc("Outline loop blocks from loop chain if (frequency of loop) / "
96 "(frequency of block) is greater than this ratio"),
97 cl::init(5), cl::Hidden);
98
Cong Hou7745dbc2015-10-19 23:16:40 +000099static cl::opt<bool>
100 PreciseRotationCost("precise-rotation-cost",
101 cl::desc("Model the cost of loop rotation more "
102 "precisely by using profile data."),
103 cl::init(false), cl::Hidden);
Xinliang David Lif0ab6df2016-05-12 02:04:41 +0000104static cl::opt<bool>
105 ForcePreciseRotationCost("force-precise-rotation-cost",
Xinliang David Lib840bb82016-05-12 16:39:02 +0000106 cl::desc("Force the use of precise cost "
107 "loop rotation strategy."),
Xinliang David Lif0ab6df2016-05-12 02:04:41 +0000108 cl::init(false), cl::Hidden);
Cong Hou7745dbc2015-10-19 23:16:40 +0000109
110static cl::opt<unsigned> MisfetchCost(
111 "misfetch-cost",
112 cl::desc("Cost that models the probablistic risk of an instruction "
113 "misfetch due to a jump comparing to falling through, whose cost "
114 "is zero."),
115 cl::init(1), cl::Hidden);
116
117static cl::opt<unsigned> JumpInstCost("jump-inst-cost",
118 cl::desc("Cost of jump instructions."),
119 cl::init(1), cl::Hidden);
120
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000121static cl::opt<bool>
122BranchFoldPlacement("branch-fold-placement",
123 cl::desc("Perform branch folding during placement. "
124 "Reduces code size."),
125 cl::init(true), cl::Hidden);
126
Xinliang David Liff287372016-06-03 23:48:36 +0000127extern cl::opt<unsigned> StaticLikelyProb;
Dehao Chen9f2bdfb2016-06-14 22:27:17 +0000128extern cl::opt<unsigned> ProfileLikelyProb;
Xinliang David Liff287372016-06-03 23:48:36 +0000129
Chandler Carruth10281422011-10-21 06:46:38 +0000130namespace {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000131class BlockChain;
Chandler Carruth10281422011-10-21 06:46:38 +0000132/// \brief Type for our function-wide basic block -> block chain mapping.
133typedef DenseMap<MachineBasicBlock *, BlockChain *> BlockToChainMapType;
134}
135
136namespace {
137/// \brief A chain of blocks which will be laid out contiguously.
138///
139/// This is the datastructure representing a chain of consecutive blocks that
140/// are profitable to layout together in order to maximize fallthrough
Chandler Carruth9139f442012-06-26 05:16:37 +0000141/// probabilities and code locality. We also can use a block chain to represent
142/// a sequence of basic blocks which have some external (correctness)
143/// requirement for sequential layout.
Chandler Carruth10281422011-10-21 06:46:38 +0000144///
Chandler Carruth9139f442012-06-26 05:16:37 +0000145/// Chains can be built around a single basic block and can be merged to grow
146/// them. They participate in a block-to-chain mapping, which is updated
147/// automatically as chains are merged together.
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000148class BlockChain {
149 /// \brief The sequence of blocks belonging to this chain.
Chandler Carruth10281422011-10-21 06:46:38 +0000150 ///
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000151 /// This is the sequence of blocks for a particular chain. These will be laid
152 /// out in-order within the function.
153 SmallVector<MachineBasicBlock *, 4> Blocks;
Chandler Carruth10281422011-10-21 06:46:38 +0000154
155 /// \brief A handle to the function-wide basic block to block chain mapping.
156 ///
157 /// This is retained in each block chain to simplify the computation of child
158 /// block chains for SCC-formation and iteration. We store the edges to child
159 /// basic blocks, and map them back to their associated chains using this
160 /// structure.
161 BlockToChainMapType &BlockToChain;
162
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000163public:
Chandler Carruth10281422011-10-21 06:46:38 +0000164 /// \brief Construct a new BlockChain.
165 ///
166 /// This builds a new block chain representing a single basic block in the
167 /// function. It also registers itself as the chain that block participates
168 /// in with the BlockToChain mapping.
169 BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
Philip Reamesae27b232016-03-03 00:58:43 +0000170 : Blocks(1, BB), BlockToChain(BlockToChain), UnscheduledPredecessors(0) {
Chandler Carruth10281422011-10-21 06:46:38 +0000171 assert(BB && "Cannot create a chain with a null basic block");
172 BlockToChain[BB] = this;
173 }
174
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000175 /// \brief Iterator over blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000176 typedef SmallVectorImpl<MachineBasicBlock *>::iterator iterator;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000177
178 /// \brief Beginning of blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000179 iterator begin() { return Blocks.begin(); }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000180
181 /// \brief End of blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000182 iterator end() { return Blocks.end(); }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000183
184 /// \brief Merge a block chain into this one.
Chandler Carruth10281422011-10-21 06:46:38 +0000185 ///
186 /// This routine merges a block chain into this one. It takes care of forming
187 /// a contiguous sequence of basic blocks, updating the edge list, and
188 /// updating the block -> chain mapping. It does not free or tear down the
189 /// old chain, but the old chain's block list is no longer valid.
Jakub Staszak90616162011-12-21 23:02:08 +0000190 void merge(MachineBasicBlock *BB, BlockChain *Chain) {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000191 assert(BB);
192 assert(!Blocks.empty());
Chandler Carruth10281422011-10-21 06:46:38 +0000193
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000194 // Fast path in case we don't have a chain already.
195 if (!Chain) {
196 assert(!BlockToChain[BB]);
197 Blocks.push_back(BB);
198 BlockToChain[BB] = this;
199 return;
Chandler Carruth10281422011-10-21 06:46:38 +0000200 }
201
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000202 assert(BB == *Chain->begin());
203 assert(Chain->begin() != Chain->end());
Chandler Carruth10281422011-10-21 06:46:38 +0000204
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000205 // Update the incoming blocks to point to this chain, and add them to the
206 // chain structure.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000207 for (MachineBasicBlock *ChainBB : *Chain) {
208 Blocks.push_back(ChainBB);
209 assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain");
210 BlockToChain[ChainBB] = this;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000211 }
Chandler Carruth10281422011-10-21 06:46:38 +0000212 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000213
Chandler Carruth49158902012-04-08 14:37:01 +0000214#ifndef NDEBUG
215 /// \brief Dump the blocks in this chain.
Nico Weber7408c702014-01-03 22:53:37 +0000216 LLVM_DUMP_METHOD void dump() {
Chandler Carruth7a715da2015-03-05 03:19:05 +0000217 for (MachineBasicBlock *MBB : *this)
218 MBB->dump();
Chandler Carruth49158902012-04-08 14:37:01 +0000219 }
220#endif // NDEBUG
221
Philip Reamesae27b232016-03-03 00:58:43 +0000222 /// \brief Count of predecessors of any block within the chain which have not
223 /// yet been scheduled. In general, we will delay scheduling this chain
224 /// until those predecessors are scheduled (or we find a sufficiently good
225 /// reason to override this heuristic.) Note that when forming loop chains,
226 /// blocks outside the loop are ignored and treated as if they were already
227 /// scheduled.
Chandler Carruth8d150782011-11-13 11:20:44 +0000228 ///
Philip Reamesae27b232016-03-03 00:58:43 +0000229 /// Note: This field is reinitialized multiple times - once for each loop,
230 /// and then once for the function as a whole.
231 unsigned UnscheduledPredecessors;
Chandler Carruth10281422011-10-21 06:46:38 +0000232};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000233}
Chandler Carruth10281422011-10-21 06:46:38 +0000234
235namespace {
236class MachineBlockPlacement : public MachineFunctionPass {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000237 /// \brief A typedef for a block filter set.
238 typedef SmallPtrSet<MachineBasicBlock *, 16> BlockFilterSet;
239
Xinliang David Li52530a72016-06-13 22:23:44 +0000240 /// \brief Machine Function
241 MachineFunction *F;
242
Chandler Carruth10281422011-10-21 06:46:38 +0000243 /// \brief A handle to the branch probability pass.
244 const MachineBranchProbabilityInfo *MBPI;
245
246 /// \brief A handle to the function-wide block frequency pass.
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000247 std::unique_ptr<BranchFolder::MBFIWrapper> MBFI;
Chandler Carruth10281422011-10-21 06:46:38 +0000248
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000249 /// \brief A handle to the loop info.
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000250 MachineLoopInfo *MLI;
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000251
Chandler Carruth10281422011-10-21 06:46:38 +0000252 /// \brief A handle to the target's instruction info.
253 const TargetInstrInfo *TII;
254
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000255 /// \brief A handle to the target's lowering info.
Benjamin Kramer56b31bd2013-01-11 20:05:37 +0000256 const TargetLoweringBase *TLI;
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000257
Daniel Jasper471e8562015-03-04 11:05:34 +0000258 /// \brief A handle to the post dominator tree.
259 MachineDominatorTree *MDT;
260
261 /// \brief A set of blocks that are unavoidably execute, i.e. they dominate
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000262 /// all terminators of the MachineFunction.
Daniel Jasper471e8562015-03-04 11:05:34 +0000263 SmallPtrSet<MachineBasicBlock *, 4> UnavoidableBlocks;
264
Chandler Carruth10281422011-10-21 06:46:38 +0000265 /// \brief Allocator and owner of BlockChain structures.
266 ///
Chandler Carruth9139f442012-06-26 05:16:37 +0000267 /// We build BlockChains lazily while processing the loop structure of
268 /// a function. To reduce malloc traffic, we allocate them using this
269 /// slab-like allocator, and destroy them after the pass completes. An
270 /// important guarantee is that this allocator produces stable pointers to
271 /// the chains.
Chandler Carruth10281422011-10-21 06:46:38 +0000272 SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
273
274 /// \brief Function wide BasicBlock to BlockChain mapping.
275 ///
276 /// This mapping allows efficiently moving from any given basic block to the
277 /// BlockChain it participates in, if any. We use it to, among other things,
278 /// allow implicitly defining edges between chains as the existing edges
279 /// between basic blocks.
280 DenseMap<MachineBasicBlock *, BlockChain *> BlockToChain;
281
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000282 void markChainSuccessors(BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000283 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000284 SmallVectorImpl<MachineBasicBlock *> &EHPadWorkList,
Craig Topperc0196b12014-04-14 00:51:57 +0000285 const BlockFilterSet *BlockFilter = nullptr);
Xinliang David Li594ffa32016-06-11 18:35:40 +0000286 BranchProbability
287 collectViableSuccessors(MachineBasicBlock *BB, BlockChain &Chain,
288 const BlockFilterSet *BlockFilter,
289 SmallVector<MachineBasicBlock *, 4> &Successors);
Xinliang David Li071d0f12016-06-12 16:54:03 +0000290 bool shouldPredBlockBeOutlined(MachineBasicBlock *BB, MachineBasicBlock *Succ,
291 BlockChain &Chain,
292 const BlockFilterSet *BlockFilter,
293 BranchProbability SuccProb,
294 BranchProbability HotProb);
Xinliang David Licbf12142016-06-13 20:24:19 +0000295 bool
296 hasBetterLayoutPredecessor(MachineBasicBlock *BB, MachineBasicBlock *Succ,
297 BlockChain &SuccChain, BranchProbability SuccProb,
298 BranchProbability RealSuccProb, BlockChain &Chain,
299 const BlockFilterSet *BlockFilter);
Jakub Staszak90616162011-12-21 23:02:08 +0000300 MachineBasicBlock *selectBestSuccessor(MachineBasicBlock *BB,
301 BlockChain &Chain,
302 const BlockFilterSet *BlockFilter);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000303 MachineBasicBlock *
304 selectBestCandidateBlock(BlockChain &Chain,
Amaury Sechet9ee4ddd2016-04-07 06:34:47 +0000305 SmallVectorImpl<MachineBasicBlock *> &WorkList);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000306 MachineBasicBlock *
Xinliang David Li52530a72016-06-13 22:23:44 +0000307 getFirstUnplacedBlock(const BlockChain &PlacedChain,
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000308 MachineFunction::iterator &PrevUnplacedBlockIt,
309 const BlockFilterSet *BlockFilter);
Amaury Secheteae09c22016-03-14 21:24:11 +0000310
311 /// \brief Add a basic block to the work list if it is apropriate.
312 ///
313 /// If the optional parameter BlockFilter is provided, only MBB
314 /// present in the set will be added to the worklist. If nullptr
315 /// is provided, no filtering occurs.
316 void fillWorkLists(MachineBasicBlock *MBB,
317 SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
318 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000319 SmallVectorImpl<MachineBasicBlock *> &EHPadWorkList,
Amaury Secheteae09c22016-03-14 21:24:11 +0000320 const BlockFilterSet *BlockFilter);
Chandler Carruth8d150782011-11-13 11:20:44 +0000321 void buildChain(MachineBasicBlock *BB, BlockChain &Chain,
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000322 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000323 SmallVectorImpl<MachineBasicBlock *> &EHPadWorkList,
Craig Topperc0196b12014-04-14 00:51:57 +0000324 const BlockFilterSet *BlockFilter = nullptr);
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000325 MachineBasicBlock *findBestLoopTop(MachineLoop &L,
326 const BlockFilterSet &LoopBlockSet);
Xinliang David Li52530a72016-06-13 22:23:44 +0000327 MachineBasicBlock *findBestLoopExit(MachineLoop &L,
Chandler Carruthccc7e422012-04-16 01:12:56 +0000328 const BlockFilterSet &LoopBlockSet);
Xinliang David Li52530a72016-06-13 22:23:44 +0000329 BlockFilterSet collectLoopBlockSet(MachineLoop &L);
330 void buildLoopChains(MachineLoop &L);
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000331 void rotateLoop(BlockChain &LoopChain, MachineBasicBlock *ExitingBB,
332 const BlockFilterSet &LoopBlockSet);
Cong Hou7745dbc2015-10-19 23:16:40 +0000333 void rotateLoopWithProfile(BlockChain &LoopChain, MachineLoop &L,
334 const BlockFilterSet &LoopBlockSet);
Xinliang David Li52530a72016-06-13 22:23:44 +0000335 void collectMustExecuteBBs();
336 void buildCFGChains();
337 void optimizeBranches();
338 void alignBlocks();
Chandler Carruth10281422011-10-21 06:46:38 +0000339
340public:
341 static char ID; // Pass identification, replacement for typeid
342 MachineBlockPlacement() : MachineFunctionPass(ID) {
343 initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
344 }
345
Craig Topper4584cd52014-03-07 09:26:03 +0000346 bool runOnMachineFunction(MachineFunction &F) override;
Chandler Carruth10281422011-10-21 06:46:38 +0000347
Craig Topper4584cd52014-03-07 09:26:03 +0000348 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth10281422011-10-21 06:46:38 +0000349 AU.addRequired<MachineBranchProbabilityInfo>();
350 AU.addRequired<MachineBlockFrequencyInfo>();
Daniel Jasper471e8562015-03-04 11:05:34 +0000351 AU.addRequired<MachineDominatorTree>();
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000352 AU.addRequired<MachineLoopInfo>();
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000353 AU.addRequired<TargetPassConfig>();
Chandler Carruth10281422011-10-21 06:46:38 +0000354 MachineFunctionPass::getAnalysisUsage(AU);
355 }
Chandler Carruth10281422011-10-21 06:46:38 +0000356};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000357}
Chandler Carruth10281422011-10-21 06:46:38 +0000358
359char MachineBlockPlacement::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000360char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
Chandler Carruthd0dced52015-03-05 02:28:25 +0000361INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement",
Chandler Carruth10281422011-10-21 06:46:38 +0000362 "Branch Probability Basic Block Placement", false, false)
363INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
364INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
Daniel Jasper471e8562015-03-04 11:05:34 +0000365INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000366INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
Chandler Carruthd0dced52015-03-05 02:28:25 +0000367INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement",
Chandler Carruth10281422011-10-21 06:46:38 +0000368 "Branch Probability Basic Block Placement", false, false)
369
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000370#ifndef NDEBUG
371/// \brief Helper to print the name of a MBB.
372///
373/// Only used by debug logging.
Jakub Staszak90616162011-12-21 23:02:08 +0000374static std::string getBlockName(MachineBasicBlock *BB) {
Alp Tokere69170a2014-06-26 22:52:05 +0000375 std::string Result;
376 raw_string_ostream OS(Result);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000377 OS << "BB#" << BB->getNumber();
Philip Reamesb9688f42016-03-02 21:45:13 +0000378 OS << " ('" << BB->getName() << "')";
Alp Tokere69170a2014-06-26 22:52:05 +0000379 OS.flush();
380 return Result;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000381}
382#endif
383
Chandler Carrutheb4ec3a2011-11-13 11:34:55 +0000384/// \brief Mark a chain's successors as having one fewer preds.
385///
386/// When a chain is being merged into the "placed" chain, this routine will
387/// quickly walk the successors of each block in the chain and mark them as
388/// having one fewer active predecessor. It also adds any successors of this
389/// chain which reach the zero-predecessor state to the worklist passed in.
Chandler Carruth8d150782011-11-13 11:20:44 +0000390void MachineBlockPlacement::markChainSuccessors(
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000391 BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
Chandler Carruth8d150782011-11-13 11:20:44 +0000392 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000393 SmallVectorImpl<MachineBasicBlock *> &EHPadWorkList,
Jakub Staszak90616162011-12-21 23:02:08 +0000394 const BlockFilterSet *BlockFilter) {
Chandler Carruth8d150782011-11-13 11:20:44 +0000395 // Walk all the blocks in this chain, marking their successors as having
396 // a predecessor placed.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000397 for (MachineBasicBlock *MBB : Chain) {
Chandler Carruth8d150782011-11-13 11:20:44 +0000398 // Add any successors for which this is the only un-placed in-loop
399 // predecessor to the worklist as a viable candidate for CFG-neutral
400 // placement. No subsequent placement of this block will violate the CFG
401 // shape, so we get to use heuristics to choose a favorable placement.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000402 for (MachineBasicBlock *Succ : MBB->successors()) {
403 if (BlockFilter && !BlockFilter->count(Succ))
Chandler Carruth8d150782011-11-13 11:20:44 +0000404 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000405 BlockChain &SuccChain = *BlockToChain[Succ];
Chandler Carruth8d150782011-11-13 11:20:44 +0000406 // Disregard edges within a fixed chain, or edges to the loop header.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000407 if (&Chain == &SuccChain || Succ == LoopHeaderBB)
Chandler Carruth8d150782011-11-13 11:20:44 +0000408 continue;
Chandler Carruth10281422011-10-21 06:46:38 +0000409
Chandler Carruth8d150782011-11-13 11:20:44 +0000410 // This is a cross-chain edge that is within the loop, so decrement the
411 // loop predecessor count of the destination chain.
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000412 if (SuccChain.UnscheduledPredecessors == 0 ||
413 --SuccChain.UnscheduledPredecessors > 0)
414 continue;
415
416 auto *MBB = *SuccChain.begin();
417 if (MBB->isEHPad())
418 EHPadWorkList.push_back(MBB);
419 else
420 BlockWorkList.push_back(MBB);
Chandler Carruth10281422011-10-21 06:46:38 +0000421 }
422 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000423}
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000424
Xinliang David Li594ffa32016-06-11 18:35:40 +0000425/// This helper function collects the set of successors of block
426/// \p BB that are allowed to be its layout successors, and return
427/// the total branch probability of edges from \p BB to those
428/// blocks.
429BranchProbability MachineBlockPlacement::collectViableSuccessors(
430 MachineBasicBlock *BB, BlockChain &Chain, const BlockFilterSet *BlockFilter,
431 SmallVector<MachineBasicBlock *, 4> &Successors) {
Cong Houd97c1002015-12-01 05:29:22 +0000432 // Adjust edge probabilities by excluding edges pointing to blocks that is
433 // either not in BlockFilter or is already in the current chain. Consider the
434 // following CFG:
Cong Hou41cf1a52015-11-18 00:52:52 +0000435 //
436 // --->A
437 // | / \
438 // | B C
439 // | \ / \
440 // ----D E
441 //
442 // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after
443 // A->C is chosen as a fall-through, D won't be selected as a successor of C
444 // due to CFG constraint (the probability of C->D is not greater than
Xinliang David Li594ffa32016-06-11 18:35:40 +0000445 // HotProb to break top-oorder). If we exclude E that is not in BlockFilter
446 // when calculating the probability of C->D, D will be selected and we
447 // will get A C D B as the layout of this loop.
Cong Houd97c1002015-12-01 05:29:22 +0000448 auto AdjustedSumProb = BranchProbability::getOne();
Cong Hou41cf1a52015-11-18 00:52:52 +0000449 for (MachineBasicBlock *Succ : BB->successors()) {
450 bool SkipSucc = false;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000451 if (Succ->isEHPad() || (BlockFilter && !BlockFilter->count(Succ))) {
Cong Hou41cf1a52015-11-18 00:52:52 +0000452 SkipSucc = true;
453 } else {
454 BlockChain *SuccChain = BlockToChain[Succ];
455 if (SuccChain == &Chain) {
Cong Hou41cf1a52015-11-18 00:52:52 +0000456 SkipSucc = true;
457 } else if (Succ != *SuccChain->begin()) {
458 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> Mid chain!\n");
459 continue;
460 }
461 }
462 if (SkipSucc)
Cong Houd97c1002015-12-01 05:29:22 +0000463 AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ);
Cong Hou41cf1a52015-11-18 00:52:52 +0000464 else
465 Successors.push_back(Succ);
466 }
467
Xinliang David Li594ffa32016-06-11 18:35:40 +0000468 return AdjustedSumProb;
469}
470
471/// The helper function returns the branch probability that is adjusted
472/// or normalized over the new total \p AdjustedSumProb.
473
474static BranchProbability
475getAdjustedProbability(BranchProbability OrigProb,
476 BranchProbability AdjustedSumProb) {
477 BranchProbability SuccProb;
478 uint32_t SuccProbN = OrigProb.getNumerator();
479 uint32_t SuccProbD = AdjustedSumProb.getNumerator();
480 if (SuccProbN >= SuccProbD)
481 SuccProb = BranchProbability::getOne();
482 else
483 SuccProb = BranchProbability(SuccProbN, SuccProbD);
484
485 return SuccProb;
486}
487
Xinliang David Li071d0f12016-06-12 16:54:03 +0000488/// When the option OutlineOptionalBranches is on, this method
489/// checks if the fallthrough candidate block \p Succ (of block
490/// \p BB) also has other unscheduled predecessor blocks which
491/// are also successors of \p BB (forming triagular shape CFG).
492/// If none of such predecessors are small, it returns true.
493/// The caller can choose to select \p Succ as the layout successors
494/// so that \p Succ's predecessors (optional branches) can be
495/// outlined.
496/// FIXME: fold this with more general layout cost analysis.
497bool MachineBlockPlacement::shouldPredBlockBeOutlined(
498 MachineBasicBlock *BB, MachineBasicBlock *Succ, BlockChain &Chain,
499 const BlockFilterSet *BlockFilter, BranchProbability SuccProb,
500 BranchProbability HotProb) {
501 if (!OutlineOptionalBranches)
502 return false;
503 // If we outline optional branches, look whether Succ is unavoidable, i.e.
504 // dominates all terminators of the MachineFunction. If it does, other
505 // successors must be optional. Don't do this for cold branches.
506 if (SuccProb > HotProb.getCompl() && UnavoidableBlocks.count(Succ) > 0) {
507 for (MachineBasicBlock *Pred : Succ->predecessors()) {
508 // Check whether there is an unplaced optional branch.
509 if (Pred == Succ || (BlockFilter && !BlockFilter->count(Pred)) ||
510 BlockToChain[Pred] == &Chain)
511 continue;
512 // Check whether the optional branch has exactly one BB.
513 if (Pred->pred_size() > 1 || *Pred->pred_begin() != BB)
514 continue;
515 // Check whether the optional branch is small.
516 if (Pred->size() < OutlineOptionalThreshold)
517 return false;
518 }
519 return true;
520 } else
521 return false;
522}
523
Dehao Chen9f2bdfb2016-06-14 22:27:17 +0000524// When profile is not present, return the StaticLikelyProb.
525// When profile is available, we need to handle the triangle-shape CFG.
526static BranchProbability getLayoutSuccessorProbThreshold(
527 MachineBasicBlock *BB) {
528 if (!BB->getParent()->getFunction()->getEntryCount())
529 return BranchProbability(StaticLikelyProb, 100);
530 if (BB->succ_size() == 2) {
531 const MachineBasicBlock *Succ1 = *BB->succ_begin();
532 const MachineBasicBlock *Succ2 = *(BB->succ_begin() + 1);
Xinliang David Lie34ed832016-06-15 03:03:30 +0000533 if (Succ1->isSuccessor(Succ2) || Succ2->isSuccessor(Succ1)) {
534 /* See case 1 below for the cost analysis. For BB->Succ to
535 * be taken with smaller cost, the following needs to hold:
536 * Prob(BB->Succ) > 2* Prob(BB->Pred)
537 * So the threshold T
538 * T = 2 * (1-Prob(BB->Pred). Since T + Prob(BB->Pred) == 1,
539 * We have T + T/2 = 1, i.e. T = 2/3. Also adding user specified
540 * branch bias, we have
541 * T = (2/3)*(ProfileLikelyProb/50)
542 * = (2*ProfileLikelyProb)/150)
543 */
544 return BranchProbability(2 * ProfileLikelyProb, 150);
545 }
Dehao Chen9f2bdfb2016-06-14 22:27:17 +0000546 }
547 return BranchProbability(ProfileLikelyProb, 100);
Xinliang David Licbf12142016-06-13 20:24:19 +0000548}
549
550/// Checks to see if the layout candidate block \p Succ has a better layout
551/// predecessor than \c BB. If yes, returns true.
552bool MachineBlockPlacement::hasBetterLayoutPredecessor(
553 MachineBasicBlock *BB, MachineBasicBlock *Succ, BlockChain &SuccChain,
554 BranchProbability SuccProb, BranchProbability RealSuccProb,
555 BlockChain &Chain, const BlockFilterSet *BlockFilter) {
556
557 // This is no global conflict, just return false.
558 if (SuccChain.UnscheduledPredecessors == 0)
559 return false;
560
561 // There are two basic scenarios here:
562 // -------------------------------------
563 // Case 1: triagular shape CFG:
564 // BB
565 // | \
566 // | \
567 // | Pred
568 // | /
569 // Succ
570 // In this case, we are evaluating whether to select edge -> Succ, e.g.
571 // set Succ as the layout successor of BB. Picking Succ as BB's
572 // successor breaks the CFG constraints. With this layout, Pred BB
573 // is forced to be outlined, so the overall cost will be cost of the
574 // branch taken from BB to Pred, plus the cost of back taken branch
575 // from Pred to Succ, as well as the additional cost asssociated
576 // with the needed unconditional jump instruction from Pred To Succ.
577 // The cost of the topological order layout is the taken branch cost
578 // from BB to Succ, so to make BB->Succ a viable candidate, the following
579 // must hold:
580 // 2 * freq(BB->Pred) * taken_branch_cost + unconditional_jump_cost
581 // < freq(BB->Succ) * taken_branch_cost.
582 // Ignoring unconditional jump cost, we get
583 // freq(BB->Succ) > 2 * freq(BB->Pred), i.e.,
584 // prob(BB->Succ) > 2 * prob(BB->Pred)
585 //
586 // When real profile data is available, we can precisely compute the the
587 // probabililty threshold that is needed for edge BB->Succ to be considered.
588 // With out profile data, the heuristic requires the branch bias to be
589 // a lot larger to make sure the signal is very strong (e.g. 80% default).
590 // -----------------------------------------------------------------
591 // Case 2: diamond like CFG:
592 // S
593 // / \
594 // | \
595 // BB Pred
596 // \ /
597 // Succ
598 // ..
599 // In this case, edge S->BB has already been selected, and we are evaluating
600 // candidate edge BB->Succ. Edge S->BB is selected because prob(S->BB)
601 // is no less than prob(S->Pred). When real profile data is *available*, if
602 // the condition is true, it will be always better to continue the trace with
603 // edge BB->Succ instead of laying out with topological order (i.e. laying
604 // Pred first). The cost of S->BB->Succ is 2 * freq (S->Pred), while with
605 // the topo order, the cost is freq(S-> Pred) + Pred(S->BB) which is larger.
606 // When profile data is not available, however, we need to be more
607 // conservative. If the branch prediction is wrong, breaking the topo-order
608 // will actually yield a layout with large cost. For this reason, we need
609 // strong biaaed branch at block S with Prob(S->BB) in order to select
610 // BB->Succ. This is equialant to looking the CFG backward with backward
611 // edge: Prob(Succ->BB) needs to >= HotProb in order to be selected (without
612 // profile data).
613
Dehao Chen9f2bdfb2016-06-14 22:27:17 +0000614 BranchProbability HotProb = getLayoutSuccessorProbThreshold(BB);
Xinliang David Licbf12142016-06-13 20:24:19 +0000615
616 // Forward checking. For case 2, SuccProb will be 1.
617 if (SuccProb < HotProb) {
618 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
619 << " (prob) (CFG conflict)\n");
620 return true;
621 }
622
623 // Make sure that a hot successor doesn't have a globally more
624 // important predecessor.
625 BlockFrequency CandidateEdgeFreq = MBFI->getBlockFreq(BB) * RealSuccProb;
626 bool BadCFGConflict = false;
627
628 for (MachineBasicBlock *Pred : Succ->predecessors()) {
629 if (Pred == Succ || BlockToChain[Pred] == &SuccChain ||
630 (BlockFilter && !BlockFilter->count(Pred)) ||
631 BlockToChain[Pred] == &Chain)
632 continue;
633 // Do backward checking. For case 1, it is actually redundant check. For
634 // case 2 above, we need a backward checking to filter out edges that are
635 // not 'strongly' biased. With profile data available, the check is mostly
636 // redundant too (when threshold prob is set at 50%) unless S has more than
637 // two successors.
638 // BB Pred
639 // \ /
640 // Succ
641 // We select edgee BB->Succ if
642 // freq(BB->Succ) > freq(Succ) * HotProb
643 // i.e. freq(BB->Succ) > freq(BB->Succ) * HotProb + freq(Pred->Succ) *
644 // HotProb
645 // i.e. freq((BB->Succ) * (1 - HotProb) > freq(Pred->Succ) * HotProb
646 BlockFrequency PredEdgeFreq =
647 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
648 if (PredEdgeFreq * HotProb >= CandidateEdgeFreq * HotProb.getCompl()) {
649 BadCFGConflict = true;
650 break;
651 }
652 }
653
654 if (BadCFGConflict) {
655 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
656 << " (prob) (non-cold CFG conflict)\n");
657 return true;
658 }
659
660 return false;
661}
662
Xinliang David Li594ffa32016-06-11 18:35:40 +0000663/// \brief Select the best successor for a block.
664///
665/// This looks across all successors of a particular block and attempts to
666/// select the "best" one to be the layout successor. It only considers direct
667/// successors which also pass the block filter. It will attempt to avoid
668/// breaking CFG structure, but cave and break such structures in the case of
669/// very hot successor edges.
670///
671/// \returns The best successor block found, or null if none are viable.
672MachineBasicBlock *
673MachineBlockPlacement::selectBestSuccessor(MachineBasicBlock *BB,
674 BlockChain &Chain,
675 const BlockFilterSet *BlockFilter) {
676 const BranchProbability HotProb(StaticLikelyProb, 100);
677
678 MachineBasicBlock *BestSucc = nullptr;
679 auto BestProb = BranchProbability::getZero();
680
681 SmallVector<MachineBasicBlock *, 4> Successors;
682 auto AdjustedSumProb =
683 collectViableSuccessors(BB, Chain, BlockFilter, Successors);
684
Cong Hou41cf1a52015-11-18 00:52:52 +0000685 DEBUG(dbgs() << "Attempting merge from: " << getBlockName(BB) << "\n");
686 for (MachineBasicBlock *Succ : Successors) {
Xinliang David Li594ffa32016-06-11 18:35:40 +0000687 auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ);
688 BranchProbability SuccProb =
689 getAdjustedProbability(RealSuccProb, AdjustedSumProb);
Chandler Carruthb3361722011-11-13 11:34:53 +0000690
Xinliang David Li071d0f12016-06-12 16:54:03 +0000691 // This heuristic is off by default.
692 if (shouldPredBlockBeOutlined(BB, Succ, Chain, BlockFilter, SuccProb,
693 HotProb))
694 return Succ;
Daniel Jasper471e8562015-03-04 11:05:34 +0000695
Cong Hou41cf1a52015-11-18 00:52:52 +0000696 BlockChain &SuccChain = *BlockToChain[Succ];
Xinliang David Licbf12142016-06-13 20:24:19 +0000697 // Skip the edge \c BB->Succ if block \c Succ has a better layout
698 // predecessor that yields lower global cost.
699 if (hasBetterLayoutPredecessor(BB, Succ, SuccChain, SuccProb, RealSuccProb,
700 Chain, BlockFilter))
701 continue;
Chandler Carruth18dfac32011-11-20 11:22:06 +0000702
Xinliang David Licbf12142016-06-13 20:24:19 +0000703 DEBUG(
704 dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
705 << " (prob)"
706 << (SuccChain.UnscheduledPredecessors != 0 ? " (CFG break)" : "")
707 << "\n");
Cong Houd97c1002015-12-01 05:29:22 +0000708 if (BestSucc && BestProb >= SuccProb)
Chandler Carruthb3361722011-11-13 11:34:53 +0000709 continue;
Daniel Jaspered9eb722015-02-18 08:19:16 +0000710 BestSucc = Succ;
Cong Houd97c1002015-12-01 05:29:22 +0000711 BestProb = SuccProb;
Chandler Carruthb3361722011-11-13 11:34:53 +0000712 }
713 return BestSucc;
714}
715
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000716/// \brief Select the best block from a worklist.
717///
718/// This looks through the provided worklist as a list of candidate basic
719/// blocks and select the most profitable one to place. The definition of
720/// profitable only really makes sense in the context of a loop. This returns
721/// the most frequently visited block in the worklist, which in the case of
722/// a loop, is the one most desirable to be physically close to the rest of the
723/// loop body in order to improve icache behavior.
724///
725/// \returns The best block found, or null if none are viable.
726MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
Amaury Sechet9ee4ddd2016-04-07 06:34:47 +0000727 BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList) {
Chandler Carruth0af6a0b2011-11-14 09:46:33 +0000728 // Once we need to walk the worklist looking for a candidate, cleanup the
729 // worklist of already placed entries.
730 // FIXME: If this shows up on profiles, it could be folded (at the cost of
731 // some code complexity) into the loop below.
732 WorkList.erase(std::remove_if(WorkList.begin(), WorkList.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000733 [&](MachineBasicBlock *BB) {
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000734 return BlockToChain.lookup(BB) == &Chain;
735 }),
Chandler Carruth0af6a0b2011-11-14 09:46:33 +0000736 WorkList.end());
737
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000738 if (WorkList.empty())
739 return nullptr;
740
741 bool IsEHPad = WorkList[0]->isEHPad();
742
Craig Topperc0196b12014-04-14 00:51:57 +0000743 MachineBasicBlock *BestBlock = nullptr;
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000744 BlockFrequency BestFreq;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000745 for (MachineBasicBlock *MBB : WorkList) {
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000746 assert(MBB->isEHPad() == IsEHPad);
747
Chandler Carruth7a715da2015-03-05 03:19:05 +0000748 BlockChain &SuccChain = *BlockToChain[MBB];
Philip Reames02e11322016-03-02 22:40:51 +0000749 if (&SuccChain == &Chain)
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000750 continue;
Junmo Park4ba6cf62016-03-11 05:07:07 +0000751
Philip Reamesae27b232016-03-03 00:58:43 +0000752 assert(SuccChain.UnscheduledPredecessors == 0 && "Found CFG-violating block");
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000753
Chandler Carruth7a715da2015-03-05 03:19:05 +0000754 BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
755 DEBUG(dbgs() << " " << getBlockName(MBB) << " -> ";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000756 MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000757
758 // For ehpad, we layout the least probable first as to avoid jumping back
759 // from least probable landingpads to more probable ones.
760 //
761 // FIXME: Using probability is probably (!) not the best way to achieve
762 // this. We should probably have a more principled approach to layout
763 // cleanup code.
764 //
765 // The goal is to get:
766 //
767 // +--------------------------+
768 // | V
769 // InnerLp -> InnerCleanup OuterLp -> OuterCleanup -> Resume
770 //
771 // Rather than:
772 //
773 // +-------------------------------------+
774 // V |
775 // OuterLp -> OuterCleanup -> Resume InnerLp -> InnerCleanup
776 if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq)))
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000777 continue;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000778
Chandler Carruth7a715da2015-03-05 03:19:05 +0000779 BestBlock = MBB;
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000780 BestFreq = CandidateFreq;
781 }
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000782
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000783 return BestBlock;
784}
785
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000786/// \brief Retrieve the first unplaced basic block.
787///
788/// This routine is called when we are unable to use the CFG to walk through
789/// all of the basic blocks and form a chain due to unnatural loops in the CFG.
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000790/// We walk through the function's blocks in order, starting from the
791/// LastUnplacedBlockIt. We update this iterator on each call to avoid
792/// re-scanning the entire sequence on repeated calls to this routine.
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000793MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
Xinliang David Li52530a72016-06-13 22:23:44 +0000794 const BlockChain &PlacedChain,
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000795 MachineFunction::iterator &PrevUnplacedBlockIt,
Jakub Staszak90616162011-12-21 23:02:08 +0000796 const BlockFilterSet *BlockFilter) {
Xinliang David Li52530a72016-06-13 22:23:44 +0000797 for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F->end(); I != E;
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000798 ++I) {
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +0000799 if (BlockFilter && !BlockFilter->count(&*I))
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000800 continue;
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +0000801 if (BlockToChain[&*I] != &PlacedChain) {
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000802 PrevUnplacedBlockIt = I;
Chandler Carruth4a87aa02011-11-23 03:03:21 +0000803 // Now select the head of the chain to which the unplaced block belongs
804 // as the block to place. This will force the entire chain to be placed,
805 // and satisfies the requirements of merging chains.
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +0000806 return *BlockToChain[&*I]->begin();
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000807 }
808 }
Craig Topperc0196b12014-04-14 00:51:57 +0000809 return nullptr;
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000810}
811
Amaury Secheteae09c22016-03-14 21:24:11 +0000812void MachineBlockPlacement::fillWorkLists(
813 MachineBasicBlock *MBB,
814 SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
815 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000816 SmallVectorImpl<MachineBasicBlock *> &EHPadWorkList,
Amaury Secheteae09c22016-03-14 21:24:11 +0000817 const BlockFilterSet *BlockFilter = nullptr) {
818 BlockChain &Chain = *BlockToChain[MBB];
819 if (!UpdatedPreds.insert(&Chain).second)
820 return;
821
822 assert(Chain.UnscheduledPredecessors == 0);
823 for (MachineBasicBlock *ChainBB : Chain) {
824 assert(BlockToChain[ChainBB] == &Chain);
825 for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
826 if (BlockFilter && !BlockFilter->count(Pred))
827 continue;
828 if (BlockToChain[Pred] == &Chain)
829 continue;
830 ++Chain.UnscheduledPredecessors;
831 }
832 }
833
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000834 if (Chain.UnscheduledPredecessors != 0)
835 return;
836
837 MBB = *Chain.begin();
838 if (MBB->isEHPad())
839 EHPadWorkList.push_back(MBB);
840 else
841 BlockWorkList.push_back(MBB);
Amaury Secheteae09c22016-03-14 21:24:11 +0000842}
843
Chandler Carruth8d150782011-11-13 11:20:44 +0000844void MachineBlockPlacement::buildChain(
Daniel Jasper471e8562015-03-04 11:05:34 +0000845 MachineBasicBlock *BB, BlockChain &Chain,
Chandler Carruth8d150782011-11-13 11:20:44 +0000846 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000847 SmallVectorImpl<MachineBasicBlock *> &EHPadWorkList,
Jakub Staszak90616162011-12-21 23:02:08 +0000848 const BlockFilterSet *BlockFilter) {
Chandler Carruth8d150782011-11-13 11:20:44 +0000849 assert(BB);
Jakub Staszak90616162011-12-21 23:02:08 +0000850 assert(BlockToChain[BB] == &Chain);
Xinliang David Li52530a72016-06-13 22:23:44 +0000851 MachineFunction::iterator PrevUnplacedBlockIt = F->begin();
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000852
Chandler Carruth8d150782011-11-13 11:20:44 +0000853 MachineBasicBlock *LoopHeaderBB = BB;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000854 markChainSuccessors(Chain, LoopHeaderBB, BlockWorkList, EHPadWorkList,
855 BlockFilter);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000856 BB = *std::prev(Chain.end());
Chandler Carruth8d150782011-11-13 11:20:44 +0000857 for (;;) {
858 assert(BB);
Jakub Staszak90616162011-12-21 23:02:08 +0000859 assert(BlockToChain[BB] == &Chain);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000860 assert(*std::prev(Chain.end()) == BB);
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000861
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +0000862 // Look for the best viable successor if there is one to place immediately
863 // after this block.
Duncan Sands291d47e2012-09-14 09:00:11 +0000864 MachineBasicBlock *BestSucc = selectBestSuccessor(BB, Chain, BlockFilter);
Chandler Carruth8d150782011-11-13 11:20:44 +0000865
866 // If an immediate successor isn't available, look for the best viable
867 // block among those we've identified as not violating the loop's CFG at
868 // this point. This won't be a fallthrough, but it will increase locality.
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000869 if (!BestSucc)
Amaury Sechet9ee4ddd2016-04-07 06:34:47 +0000870 BestSucc = selectBestCandidateBlock(Chain, BlockWorkList);
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000871 if (!BestSucc)
872 BestSucc = selectBestCandidateBlock(Chain, EHPadWorkList);
Chandler Carruth8d150782011-11-13 11:20:44 +0000873
Chandler Carruth8d150782011-11-13 11:20:44 +0000874 if (!BestSucc) {
Xinliang David Li52530a72016-06-13 22:23:44 +0000875 BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockIt, BlockFilter);
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000876 if (!BestSucc)
877 break;
878
879 DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
880 "layout successor until the CFG reduces\n");
Chandler Carruth8d150782011-11-13 11:20:44 +0000881 }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000882
Chandler Carruth8d150782011-11-13 11:20:44 +0000883 // Place this block, updating the datastructures to reflect its placement.
Jakub Staszak90616162011-12-21 23:02:08 +0000884 BlockChain &SuccChain = *BlockToChain[BestSucc];
Philip Reamesae27b232016-03-03 00:58:43 +0000885 // Zero out UnscheduledPredecessors for the successor we're about to merge in case
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000886 // we selected a successor that didn't fit naturally into the CFG.
Philip Reamesae27b232016-03-03 00:58:43 +0000887 SuccChain.UnscheduledPredecessors = 0;
Philip Reamesb9688f42016-03-02 21:45:13 +0000888 DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to "
889 << getBlockName(BestSucc) << "\n");
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000890 markChainSuccessors(SuccChain, LoopHeaderBB, BlockWorkList, EHPadWorkList,
891 BlockFilter);
Chandler Carruth8d150782011-11-13 11:20:44 +0000892 Chain.merge(BestSucc, &SuccChain);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000893 BB = *std::prev(Chain.end());
Jakub Staszak190c7122011-12-07 19:46:10 +0000894 }
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000895
896 DEBUG(dbgs() << "Finished forming chain for header block "
Philip Reamesb9688f42016-03-02 21:45:13 +0000897 << getBlockName(*Chain.begin()) << "\n");
Chandler Carruth10281422011-10-21 06:46:38 +0000898}
899
Chandler Carruth03adbd42011-11-27 13:34:33 +0000900/// \brief Find the best loop top block for layout.
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000901///
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000902/// Look for a block which is strictly better than the loop header for laying
903/// out at the top of the loop. This looks for one and only one pattern:
904/// a latch block with no conditional exit. This block will cause a conditional
905/// jump around it or will be the bottom of the loop if we lay it out in place,
906/// but if it it doesn't end up at the bottom of the loop for any reason,
907/// rotation alone won't fix it. Because such a block will always result in an
908/// unconditional jump (for the backedge) rotating it in front of the loop
909/// header is always profitable.
910MachineBasicBlock *
911MachineBlockPlacement::findBestLoopTop(MachineLoop &L,
912 const BlockFilterSet &LoopBlockSet) {
913 // Check that the header hasn't been fused with a preheader block due to
914 // crazy branches. If it has, we need to start with the header at the top to
915 // prevent pulling the preheader into the loop body.
916 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
917 if (!LoopBlockSet.count(*HeaderChain.begin()))
918 return L.getHeader();
919
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000920 DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(L.getHeader())
921 << "\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000922
923 BlockFrequency BestPredFreq;
Craig Topperc0196b12014-04-14 00:51:57 +0000924 MachineBasicBlock *BestPred = nullptr;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000925 for (MachineBasicBlock *Pred : L.getHeader()->predecessors()) {
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000926 if (!LoopBlockSet.count(Pred))
927 continue;
928 DEBUG(dbgs() << " header pred: " << getBlockName(Pred) << ", "
Michael Gottesmanb78dec82013-12-14 00:25:45 +0000929 << Pred->succ_size() << " successors, ";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000930 MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000931 if (Pred->succ_size() > 1)
932 continue;
933
934 BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
935 if (!BestPred || PredFreq > BestPredFreq ||
936 (!(PredFreq < BestPredFreq) &&
937 Pred->isLayoutSuccessor(L.getHeader()))) {
938 BestPred = Pred;
939 BestPredFreq = PredFreq;
940 }
941 }
942
943 // If no direct predecessor is fine, just use the loop header.
Philip Reamesb9688f42016-03-02 21:45:13 +0000944 if (!BestPred) {
945 DEBUG(dbgs() << " final top unchanged\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000946 return L.getHeader();
Philip Reamesb9688f42016-03-02 21:45:13 +0000947 }
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000948
949 // Walk backwards through any straight line of predecessors.
950 while (BestPred->pred_size() == 1 &&
951 (*BestPred->pred_begin())->succ_size() == 1 &&
952 *BestPred->pred_begin() != L.getHeader())
953 BestPred = *BestPred->pred_begin();
954
955 DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n");
956 return BestPred;
957}
958
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000959/// \brief Find the best loop exiting block for layout.
960///
Chandler Carruth03adbd42011-11-27 13:34:33 +0000961/// This routine implements the logic to analyze the loop looking for the best
962/// block to layout at the top of the loop. Typically this is done to maximize
963/// fallthrough opportunities.
964MachineBasicBlock *
Xinliang David Li52530a72016-06-13 22:23:44 +0000965MachineBlockPlacement::findBestLoopExit(MachineLoop &L,
Chandler Carruthccc7e422012-04-16 01:12:56 +0000966 const BlockFilterSet &LoopBlockSet) {
Chandler Carruth68062612012-04-10 13:35:57 +0000967 // We don't want to layout the loop linearly in all cases. If the loop header
968 // is just a normal basic block in the loop, we want to look for what block
969 // within the loop is the best one to layout at the top. However, if the loop
970 // header has be pre-merged into a chain due to predecessors not having
971 // analyzable branches, *and* the predecessor it is merged with is *not* part
972 // of the loop, rotating the header into the middle of the loop will create
973 // a non-contiguous range of blocks which is Very Bad. So start with the
974 // header and only rotate if safe.
975 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
976 if (!LoopBlockSet.count(*HeaderChain.begin()))
Craig Topperc0196b12014-04-14 00:51:57 +0000977 return nullptr;
Chandler Carruth68062612012-04-10 13:35:57 +0000978
Chandler Carruth03adbd42011-11-27 13:34:33 +0000979 BlockFrequency BestExitEdgeFreq;
Chandler Carruthccc7e422012-04-16 01:12:56 +0000980 unsigned BestExitLoopDepth = 0;
Craig Topperc0196b12014-04-14 00:51:57 +0000981 MachineBasicBlock *ExitingBB = nullptr;
Chandler Carruth4f567202011-11-27 20:18:00 +0000982 // If there are exits to outer loops, loop rotation can severely limit
983 // fallthrough opportunites unless it selects such an exit. Keep a set of
984 // blocks where rotating to exit with that block will reach an outer loop.
985 SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
986
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000987 DEBUG(dbgs() << "Finding best loop exit for: " << getBlockName(L.getHeader())
988 << "\n");
Chandler Carruth7a715da2015-03-05 03:19:05 +0000989 for (MachineBasicBlock *MBB : L.getBlocks()) {
990 BlockChain &Chain = *BlockToChain[MBB];
Chandler Carruth03adbd42011-11-27 13:34:33 +0000991 // Ensure that this block is at the end of a chain; otherwise it could be
Chandler Carruth9a512a42015-04-15 13:19:54 +0000992 // mid-way through an inner loop or a successor of an unanalyzable branch.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000993 if (MBB != *std::prev(Chain.end()))
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000994 continue;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000995
Chandler Carruth03adbd42011-11-27 13:34:33 +0000996 // Now walk the successors. We need to establish whether this has a viable
997 // exiting successor and whether it has a viable non-exiting successor.
998 // We store the old exiting state and restore it if a viable looping
999 // successor isn't found.
1000 MachineBasicBlock *OldExitingBB = ExitingBB;
1001 BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
Chandler Carruthccc7e422012-04-16 01:12:56 +00001002 bool HasLoopingSucc = false;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001003 for (MachineBasicBlock *Succ : MBB->successors()) {
Reid Kleckner0e288232015-08-27 23:27:47 +00001004 if (Succ->isEHPad())
Chandler Carruth03adbd42011-11-27 13:34:33 +00001005 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001006 if (Succ == MBB)
Chandler Carruth03adbd42011-11-27 13:34:33 +00001007 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001008 BlockChain &SuccChain = *BlockToChain[Succ];
Chandler Carruth03adbd42011-11-27 13:34:33 +00001009 // Don't split chains, either this chain or the successor's chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +00001010 if (&Chain == &SuccChain) {
Chandler Carruth7a715da2015-03-05 03:19:05 +00001011 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
1012 << getBlockName(Succ) << " (chain conflict)\n");
Chandler Carruth03adbd42011-11-27 13:34:33 +00001013 continue;
1014 }
1015
Cong Houd97c1002015-12-01 05:29:22 +00001016 auto SuccProb = MBPI->getEdgeProbability(MBB, Succ);
Chandler Carruth7a715da2015-03-05 03:19:05 +00001017 if (LoopBlockSet.count(Succ)) {
1018 DEBUG(dbgs() << " looping: " << getBlockName(MBB) << " -> "
Cong Houd97c1002015-12-01 05:29:22 +00001019 << getBlockName(Succ) << " (" << SuccProb << ")\n");
Chandler Carruthccc7e422012-04-16 01:12:56 +00001020 HasLoopingSucc = true;
Chandler Carruth03adbd42011-11-27 13:34:33 +00001021 continue;
1022 }
1023
Chandler Carruthccc7e422012-04-16 01:12:56 +00001024 unsigned SuccLoopDepth = 0;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001025 if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
Chandler Carruthccc7e422012-04-16 01:12:56 +00001026 SuccLoopDepth = ExitLoop->getLoopDepth();
1027 if (ExitLoop->contains(&L))
Chandler Carruth7a715da2015-03-05 03:19:05 +00001028 BlocksExitingToOuterLoop.insert(MBB);
Chandler Carruthccc7e422012-04-16 01:12:56 +00001029 }
1030
Chandler Carruth7a715da2015-03-05 03:19:05 +00001031 BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
1032 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
1033 << getBlockName(Succ) << " [L:" << SuccLoopDepth << "] (";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001034 MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
Benjamin Kramerc8160d62013-11-20 19:08:44 +00001035 // Note that we bias this toward an existing layout successor to retain
1036 // incoming order in the absence of better information. The exit must have
1037 // a frequency higher than the current exit before we consider breaking
1038 // the layout.
1039 BranchProbability Bias(100 - ExitBlockBias, 100);
Chandler Carruth26d30172015-04-15 13:39:42 +00001040 if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
Chandler Carruthccc7e422012-04-16 01:12:56 +00001041 ExitEdgeFreq > BestExitEdgeFreq ||
Chandler Carruth7a715da2015-03-05 03:19:05 +00001042 (MBB->isLayoutSuccessor(Succ) &&
Benjamin Kramerc8160d62013-11-20 19:08:44 +00001043 !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
Chandler Carruth03adbd42011-11-27 13:34:33 +00001044 BestExitEdgeFreq = ExitEdgeFreq;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001045 ExitingBB = MBB;
Chandler Carrutha0545802011-11-27 09:22:53 +00001046 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001047 }
Chandler Carruth03adbd42011-11-27 13:34:33 +00001048
Chandler Carruthccc7e422012-04-16 01:12:56 +00001049 if (!HasLoopingSucc) {
Chandler Carruthcfb2b9d2015-04-15 13:26:41 +00001050 // Restore the old exiting state, no viable looping successor was found.
Chandler Carruth03adbd42011-11-27 13:34:33 +00001051 ExitingBB = OldExitingBB;
1052 BestExitEdgeFreq = OldBestExitEdgeFreq;
Chandler Carruth03adbd42011-11-27 13:34:33 +00001053 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001054 }
Chandler Carruthccc7e422012-04-16 01:12:56 +00001055 // Without a candidate exiting block or with only a single block in the
Chandler Carruth03adbd42011-11-27 13:34:33 +00001056 // loop, just use the loop header to layout the loop.
1057 if (!ExitingBB || L.getNumBlocks() == 1)
Craig Topperc0196b12014-04-14 00:51:57 +00001058 return nullptr;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001059
Chandler Carruth4f567202011-11-27 20:18:00 +00001060 // Also, if we have exit blocks which lead to outer loops but didn't select
1061 // one of them as the exiting block we are rotating toward, disable loop
1062 // rotation altogether.
1063 if (!BlocksExitingToOuterLoop.empty() &&
1064 !BlocksExitingToOuterLoop.count(ExitingBB))
Craig Topperc0196b12014-04-14 00:51:57 +00001065 return nullptr;
Chandler Carruth4f567202011-11-27 20:18:00 +00001066
Chandler Carruth03adbd42011-11-27 13:34:33 +00001067 DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB) << "\n");
Chandler Carruthccc7e422012-04-16 01:12:56 +00001068 return ExitingBB;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001069}
1070
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001071/// \brief Attempt to rotate an exiting block to the bottom of the loop.
1072///
1073/// Once we have built a chain, try to rotate it to line up the hot exit block
1074/// with fallthrough out of the loop if doing so doesn't introduce unnecessary
1075/// branches. For example, if the loop has fallthrough into its header and out
1076/// of its bottom already, don't rotate it.
1077void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
1078 MachineBasicBlock *ExitingBB,
1079 const BlockFilterSet &LoopBlockSet) {
1080 if (!ExitingBB)
1081 return;
1082
1083 MachineBasicBlock *Top = *LoopChain.begin();
1084 bool ViableTopFallthrough = false;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001085 for (MachineBasicBlock *Pred : Top->predecessors()) {
1086 BlockChain *PredChain = BlockToChain[Pred];
1087 if (!LoopBlockSet.count(Pred) &&
1088 (!PredChain || Pred == *std::prev(PredChain->end()))) {
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001089 ViableTopFallthrough = true;
1090 break;
1091 }
1092 }
1093
1094 // If the header has viable fallthrough, check whether the current loop
1095 // bottom is a viable exiting block. If so, bail out as rotating will
1096 // introduce an unnecessary branch.
1097 if (ViableTopFallthrough) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001098 MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
Chandler Carruth7a715da2015-03-05 03:19:05 +00001099 for (MachineBasicBlock *Succ : Bottom->successors()) {
1100 BlockChain *SuccChain = BlockToChain[Succ];
1101 if (!LoopBlockSet.count(Succ) &&
1102 (!SuccChain || Succ == *SuccChain->begin()))
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001103 return;
1104 }
1105 }
1106
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001107 BlockChain::iterator ExitIt =
1108 std::find(LoopChain.begin(), LoopChain.end(), ExitingBB);
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001109 if (ExitIt == LoopChain.end())
1110 return;
1111
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001112 std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001113}
1114
Cong Hou7745dbc2015-10-19 23:16:40 +00001115/// \brief Attempt to rotate a loop based on profile data to reduce branch cost.
1116///
1117/// With profile data, we can determine the cost in terms of missed fall through
1118/// opportunities when rotating a loop chain and select the best rotation.
1119/// Basically, there are three kinds of cost to consider for each rotation:
1120/// 1. The possibly missed fall through edge (if it exists) from BB out of
1121/// the loop to the loop header.
1122/// 2. The possibly missed fall through edges (if they exist) from the loop
1123/// exits to BB out of the loop.
1124/// 3. The missed fall through edge (if it exists) from the last BB to the
1125/// first BB in the loop chain.
1126/// Therefore, the cost for a given rotation is the sum of costs listed above.
1127/// We select the best rotation with the smallest cost.
1128void MachineBlockPlacement::rotateLoopWithProfile(
1129 BlockChain &LoopChain, MachineLoop &L, const BlockFilterSet &LoopBlockSet) {
1130 auto HeaderBB = L.getHeader();
1131 auto HeaderIter = std::find(LoopChain.begin(), LoopChain.end(), HeaderBB);
1132 auto RotationPos = LoopChain.end();
1133
1134 BlockFrequency SmallestRotationCost = BlockFrequency::getMaxFrequency();
1135
1136 // A utility lambda that scales up a block frequency by dividing it by a
1137 // branch probability which is the reciprocal of the scale.
1138 auto ScaleBlockFrequency = [](BlockFrequency Freq,
1139 unsigned Scale) -> BlockFrequency {
1140 if (Scale == 0)
1141 return 0;
1142 // Use operator / between BlockFrequency and BranchProbability to implement
1143 // saturating multiplication.
1144 return Freq / BranchProbability(1, Scale);
1145 };
1146
1147 // Compute the cost of the missed fall-through edge to the loop header if the
1148 // chain head is not the loop header. As we only consider natural loops with
1149 // single header, this computation can be done only once.
1150 BlockFrequency HeaderFallThroughCost(0);
1151 for (auto *Pred : HeaderBB->predecessors()) {
1152 BlockChain *PredChain = BlockToChain[Pred];
1153 if (!LoopBlockSet.count(Pred) &&
1154 (!PredChain || Pred == *std::prev(PredChain->end()))) {
1155 auto EdgeFreq =
1156 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, HeaderBB);
1157 auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost);
1158 // If the predecessor has only an unconditional jump to the header, we
1159 // need to consider the cost of this jump.
1160 if (Pred->succ_size() == 1)
1161 FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost);
1162 HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost);
1163 }
1164 }
1165
1166 // Here we collect all exit blocks in the loop, and for each exit we find out
1167 // its hottest exit edge. For each loop rotation, we define the loop exit cost
1168 // as the sum of frequencies of exit edges we collect here, excluding the exit
1169 // edge from the tail of the loop chain.
1170 SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq;
1171 for (auto BB : LoopChain) {
Cong Houd97c1002015-12-01 05:29:22 +00001172 auto LargestExitEdgeProb = BranchProbability::getZero();
Cong Hou7745dbc2015-10-19 23:16:40 +00001173 for (auto *Succ : BB->successors()) {
1174 BlockChain *SuccChain = BlockToChain[Succ];
1175 if (!LoopBlockSet.count(Succ) &&
1176 (!SuccChain || Succ == *SuccChain->begin())) {
Cong Houd97c1002015-12-01 05:29:22 +00001177 auto SuccProb = MBPI->getEdgeProbability(BB, Succ);
1178 LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb);
Cong Hou7745dbc2015-10-19 23:16:40 +00001179 }
1180 }
Cong Houd97c1002015-12-01 05:29:22 +00001181 if (LargestExitEdgeProb > BranchProbability::getZero()) {
1182 auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb;
Cong Hou7745dbc2015-10-19 23:16:40 +00001183 ExitsWithFreq.emplace_back(BB, ExitFreq);
1184 }
1185 }
1186
1187 // In this loop we iterate every block in the loop chain and calculate the
1188 // cost assuming the block is the head of the loop chain. When the loop ends,
1189 // we should have found the best candidate as the loop chain's head.
1190 for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()),
1191 EndIter = LoopChain.end();
1192 Iter != EndIter; Iter++, TailIter++) {
1193 // TailIter is used to track the tail of the loop chain if the block we are
1194 // checking (pointed by Iter) is the head of the chain.
1195 if (TailIter == LoopChain.end())
1196 TailIter = LoopChain.begin();
1197
1198 auto TailBB = *TailIter;
1199
1200 // Calculate the cost by putting this BB to the top.
1201 BlockFrequency Cost = 0;
1202
1203 // If the current BB is the loop header, we need to take into account the
1204 // cost of the missed fall through edge from outside of the loop to the
1205 // header.
1206 if (Iter != HeaderIter)
1207 Cost += HeaderFallThroughCost;
1208
1209 // Collect the loop exit cost by summing up frequencies of all exit edges
1210 // except the one from the chain tail.
1211 for (auto &ExitWithFreq : ExitsWithFreq)
1212 if (TailBB != ExitWithFreq.first)
1213 Cost += ExitWithFreq.second;
1214
1215 // The cost of breaking the once fall-through edge from the tail to the top
1216 // of the loop chain. Here we need to consider three cases:
1217 // 1. If the tail node has only one successor, then we will get an
1218 // additional jmp instruction. So the cost here is (MisfetchCost +
1219 // JumpInstCost) * tail node frequency.
1220 // 2. If the tail node has two successors, then we may still get an
1221 // additional jmp instruction if the layout successor after the loop
1222 // chain is not its CFG successor. Note that the more frequently executed
1223 // jmp instruction will be put ahead of the other one. Assume the
1224 // frequency of those two branches are x and y, where x is the frequency
1225 // of the edge to the chain head, then the cost will be
1226 // (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency.
1227 // 3. If the tail node has more than two successors (this rarely happens),
1228 // we won't consider any additional cost.
1229 if (TailBB->isSuccessor(*Iter)) {
1230 auto TailBBFreq = MBFI->getBlockFreq(TailBB);
1231 if (TailBB->succ_size() == 1)
1232 Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(),
1233 MisfetchCost + JumpInstCost);
1234 else if (TailBB->succ_size() == 2) {
1235 auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter);
1236 auto TailToHeadFreq = TailBBFreq * TailToHeadProb;
1237 auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2)
1238 ? TailBBFreq * TailToHeadProb.getCompl()
1239 : TailToHeadFreq;
1240 Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) +
1241 ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost);
1242 }
1243 }
1244
Philip Reamesb9688f42016-03-02 21:45:13 +00001245 DEBUG(dbgs() << "The cost of loop rotation by making " << getBlockName(*Iter)
Cong Hou7745dbc2015-10-19 23:16:40 +00001246 << " to the top: " << Cost.getFrequency() << "\n");
1247
1248 if (Cost < SmallestRotationCost) {
1249 SmallestRotationCost = Cost;
1250 RotationPos = Iter;
1251 }
1252 }
1253
1254 if (RotationPos != LoopChain.end()) {
Philip Reamesb9688f42016-03-02 21:45:13 +00001255 DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos)
Cong Hou7745dbc2015-10-19 23:16:40 +00001256 << " to the top\n");
1257 std::rotate(LoopChain.begin(), RotationPos, LoopChain.end());
1258 }
1259}
1260
Cong Houb90b9e02015-11-02 21:24:00 +00001261/// \brief Collect blocks in the given loop that are to be placed.
1262///
1263/// When profile data is available, exclude cold blocks from the returned set;
1264/// otherwise, collect all blocks in the loop.
1265MachineBlockPlacement::BlockFilterSet
Xinliang David Li52530a72016-06-13 22:23:44 +00001266MachineBlockPlacement::collectLoopBlockSet(MachineLoop &L) {
Cong Houb90b9e02015-11-02 21:24:00 +00001267 BlockFilterSet LoopBlockSet;
1268
1269 // Filter cold blocks off from LoopBlockSet when profile data is available.
1270 // Collect the sum of frequencies of incoming edges to the loop header from
1271 // outside. If we treat the loop as a super block, this is the frequency of
1272 // the loop. Then for each block in the loop, we calculate the ratio between
1273 // its frequency and the frequency of the loop block. When it is too small,
1274 // don't add it to the loop chain. If there are outer loops, then this block
1275 // will be merged into the first outer loop chain for which this block is not
1276 // cold anymore. This needs precise profile data and we only do this when
1277 // profile data is available.
Xinliang David Li52530a72016-06-13 22:23:44 +00001278 if (F->getFunction()->getEntryCount()) {
Cong Houb90b9e02015-11-02 21:24:00 +00001279 BlockFrequency LoopFreq(0);
1280 for (auto LoopPred : L.getHeader()->predecessors())
1281 if (!L.contains(LoopPred))
1282 LoopFreq += MBFI->getBlockFreq(LoopPred) *
1283 MBPI->getEdgeProbability(LoopPred, L.getHeader());
1284
1285 for (MachineBasicBlock *LoopBB : L.getBlocks()) {
1286 auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency();
1287 if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio)
1288 continue;
1289 LoopBlockSet.insert(LoopBB);
1290 }
1291 } else
1292 LoopBlockSet.insert(L.block_begin(), L.block_end());
1293
1294 return LoopBlockSet;
1295}
1296
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001297/// \brief Forms basic block chains from the natural loop structures.
Chandler Carruth10281422011-10-21 06:46:38 +00001298///
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001299/// These chains are designed to preserve the existing *structure* of the code
1300/// as much as possible. We can then stitch the chains together in a way which
1301/// both preserves the topological structure and minimizes taken conditional
1302/// branches.
Xinliang David Li52530a72016-06-13 22:23:44 +00001303void MachineBlockPlacement::buildLoopChains(MachineLoop &L) {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001304 // First recurse through any nested loops, building chains for those inner
1305 // loops.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001306 for (MachineLoop *InnerLoop : L)
Xinliang David Li52530a72016-06-13 22:23:44 +00001307 buildLoopChains(*InnerLoop);
Chandler Carruth10281422011-10-21 06:46:38 +00001308
Chandler Carruth8d150782011-11-13 11:20:44 +00001309 SmallVector<MachineBasicBlock *, 16> BlockWorkList;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001310 SmallVector<MachineBasicBlock *, 16> EHPadWorkList;
Xinliang David Li52530a72016-06-13 22:23:44 +00001311 BlockFilterSet LoopBlockSet = collectLoopBlockSet(L);
Chandler Carruth03adbd42011-11-27 13:34:33 +00001312
Cong Hou7745dbc2015-10-19 23:16:40 +00001313 // Check if we have profile data for this function. If yes, we will rotate
1314 // this loop by modeling costs more precisely which requires the profile data
1315 // for better layout.
1316 bool RotateLoopWithProfile =
Xinliang David Lif0ab6df2016-05-12 02:04:41 +00001317 ForcePreciseRotationCost ||
Xinliang David Li52530a72016-06-13 22:23:44 +00001318 (PreciseRotationCost && F->getFunction()->getEntryCount());
Cong Hou7745dbc2015-10-19 23:16:40 +00001319
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001320 // First check to see if there is an obviously preferable top block for the
1321 // loop. This will default to the header, but may end up as one of the
1322 // predecessors to the header if there is one which will result in strictly
1323 // fewer branches in the loop body.
Cong Hou7745dbc2015-10-19 23:16:40 +00001324 // When we use profile data to rotate the loop, this is unnecessary.
1325 MachineBasicBlock *LoopTop =
1326 RotateLoopWithProfile ? L.getHeader() : findBestLoopTop(L, LoopBlockSet);
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001327
1328 // If we selected just the header for the loop top, look for a potentially
1329 // profitable exit block in the event that rotating the loop can eliminate
1330 // branches by placing an exit edge at the bottom.
Craig Topperc0196b12014-04-14 00:51:57 +00001331 MachineBasicBlock *ExitingBB = nullptr;
Cong Hou7745dbc2015-10-19 23:16:40 +00001332 if (!RotateLoopWithProfile && LoopTop == L.getHeader())
Xinliang David Li52530a72016-06-13 22:23:44 +00001333 ExitingBB = findBestLoopExit(L, LoopBlockSet);
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001334
1335 BlockChain &LoopChain = *BlockToChain[LoopTop];
Chandler Carruth10281422011-10-21 06:46:38 +00001336
Chandler Carruth8d150782011-11-13 11:20:44 +00001337 // FIXME: This is a really lame way of walking the chains in the loop: we
1338 // walk the blocks, and use a set to prevent visiting a particular chain
1339 // twice.
Jakub Staszak90616162011-12-21 23:02:08 +00001340 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
Philip Reamesae27b232016-03-03 00:58:43 +00001341 assert(LoopChain.UnscheduledPredecessors == 0);
Jakub Staszak190c7122011-12-07 19:46:10 +00001342 UpdatedPreds.insert(&LoopChain);
Cong Houb90b9e02015-11-02 21:24:00 +00001343
Amaury Secheteae09c22016-03-14 21:24:11 +00001344 for (MachineBasicBlock *LoopBB : LoopBlockSet)
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001345 fillWorkLists(LoopBB, UpdatedPreds, BlockWorkList, EHPadWorkList,
1346 &LoopBlockSet);
Chandler Carruth8d150782011-11-13 11:20:44 +00001347
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001348 buildChain(LoopTop, LoopChain, BlockWorkList, EHPadWorkList, &LoopBlockSet);
Cong Hou7745dbc2015-10-19 23:16:40 +00001349
1350 if (RotateLoopWithProfile)
1351 rotateLoopWithProfile(LoopChain, L, LoopBlockSet);
1352 else
1353 rotateLoop(LoopChain, ExitingBB, LoopBlockSet);
Chandler Carruth8d150782011-11-13 11:20:44 +00001354
1355 DEBUG({
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001356 // Crash at the end so we get all of the debugging output first.
1357 bool BadLoop = false;
Philip Reamesae27b232016-03-03 00:58:43 +00001358 if (LoopChain.UnscheduledPredecessors) {
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001359 BadLoop = true;
Chandler Carruth8d150782011-11-13 11:20:44 +00001360 dbgs() << "Loop chain contains a block without its preds placed!\n"
1361 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
1362 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001363 }
Chandler Carruth7a715da2015-03-05 03:19:05 +00001364 for (MachineBasicBlock *ChainBB : LoopChain) {
1365 dbgs() << " ... " << getBlockName(ChainBB) << "\n";
1366 if (!LoopBlockSet.erase(ChainBB)) {
Chandler Carruth0a31d142011-11-14 10:55:53 +00001367 // We don't mark the loop as bad here because there are real situations
1368 // where this can occur. For example, with an unanalyzable fallthrough
Chandler Carruth99fe42f2011-11-23 10:35:36 +00001369 // from a loop block to a non-loop block or vice versa.
Chandler Carruth8d150782011-11-13 11:20:44 +00001370 dbgs() << "Loop chain contains a block not contained by the loop!\n"
1371 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
1372 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00001373 << " Bad block: " << getBlockName(ChainBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001374 }
Chandler Carruthccc7e422012-04-16 01:12:56 +00001375 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001376
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001377 if (!LoopBlockSet.empty()) {
1378 BadLoop = true;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001379 for (MachineBasicBlock *LoopBB : LoopBlockSet)
Chandler Carruth8d150782011-11-13 11:20:44 +00001380 dbgs() << "Loop contains blocks never placed into a chain!\n"
1381 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
1382 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00001383 << " Bad block: " << getBlockName(LoopBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001384 }
1385 assert(!BadLoop && "Detected problems with the placement of this loop.");
Chandler Carruth8d150782011-11-13 11:20:44 +00001386 });
Chandler Carruth10281422011-10-21 06:46:38 +00001387}
1388
Xinliang David Li071d0f12016-06-12 16:54:03 +00001389/// When OutlineOpitonalBranches is on, this method colects BBs that
1390/// dominates all terminator blocks of the function \p F.
Xinliang David Li52530a72016-06-13 22:23:44 +00001391void MachineBlockPlacement::collectMustExecuteBBs() {
Xinliang David Li071d0f12016-06-12 16:54:03 +00001392 if (OutlineOptionalBranches) {
1393 // Find the nearest common dominator of all of F's terminators.
1394 MachineBasicBlock *Terminator = nullptr;
Xinliang David Li52530a72016-06-13 22:23:44 +00001395 for (MachineBasicBlock &MBB : *F) {
Xinliang David Li071d0f12016-06-12 16:54:03 +00001396 if (MBB.succ_size() == 0) {
1397 if (Terminator == nullptr)
1398 Terminator = &MBB;
1399 else
1400 Terminator = MDT->findNearestCommonDominator(Terminator, &MBB);
1401 }
1402 }
1403
1404 // MBBs dominating this common dominator are unavoidable.
1405 UnavoidableBlocks.clear();
Xinliang David Li52530a72016-06-13 22:23:44 +00001406 for (MachineBasicBlock &MBB : *F) {
Xinliang David Li071d0f12016-06-12 16:54:03 +00001407 if (MDT->dominates(&MBB, Terminator)) {
1408 UnavoidableBlocks.insert(&MBB);
1409 }
1410 }
1411 }
1412}
1413
Xinliang David Li52530a72016-06-13 22:23:44 +00001414void MachineBlockPlacement::buildCFGChains() {
Chandler Carruth8d150782011-11-13 11:20:44 +00001415 // Ensure that every BB in the function has an associated chain to simplify
1416 // the assumptions of the remaining algorithm.
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001417 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
Xinliang David Li52530a72016-06-13 22:23:44 +00001418 for (MachineFunction::iterator FI = F->begin(), FE = F->end(); FI != FE;
1419 ++FI) {
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001420 MachineBasicBlock *BB = &*FI;
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001421 BlockChain *Chain =
1422 new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001423 // Also, merge any blocks which we cannot reason about and must preserve
1424 // the exact fallthrough behavior for.
1425 for (;;) {
1426 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001427 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001428 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
1429 break;
1430
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001431 MachineFunction::iterator NextFI = std::next(FI);
1432 MachineBasicBlock *NextBB = &*NextFI;
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001433 // Ensure that the layout successor is a viable block, as we know that
1434 // fallthrough is a possibility.
1435 assert(NextFI != FE && "Can't fallthrough past the last block.");
1436 DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
1437 << getBlockName(BB) << " -> " << getBlockName(NextBB)
1438 << "\n");
Craig Topperc0196b12014-04-14 00:51:57 +00001439 Chain->merge(NextBB, nullptr);
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001440 FI = NextFI;
1441 BB = NextBB;
1442 }
1443 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001444
Xinliang David Li071d0f12016-06-12 16:54:03 +00001445 // Turned on with OutlineOptionalBranches option
Xinliang David Li52530a72016-06-13 22:23:44 +00001446 collectMustExecuteBBs();
Daniel Jasper471e8562015-03-04 11:05:34 +00001447
Chandler Carruth8d150782011-11-13 11:20:44 +00001448 // Build any loop-based chains.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001449 for (MachineLoop *L : *MLI)
Xinliang David Li52530a72016-06-13 22:23:44 +00001450 buildLoopChains(*L);
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001451
Chandler Carruth8d150782011-11-13 11:20:44 +00001452 SmallVector<MachineBasicBlock *, 16> BlockWorkList;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001453 SmallVector<MachineBasicBlock *, 16> EHPadWorkList;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001454
Chandler Carruth8d150782011-11-13 11:20:44 +00001455 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
Xinliang David Li52530a72016-06-13 22:23:44 +00001456 for (MachineBasicBlock &MBB : *F)
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001457 fillWorkLists(&MBB, UpdatedPreds, BlockWorkList, EHPadWorkList);
Chandler Carruth8d150782011-11-13 11:20:44 +00001458
Xinliang David Li52530a72016-06-13 22:23:44 +00001459 BlockChain &FunctionChain = *BlockToChain[&F->front()];
1460 buildChain(&F->front(), FunctionChain, BlockWorkList, EHPadWorkList);
Chandler Carruth8d150782011-11-13 11:20:44 +00001461
Matt Arsenault0f5f0152013-12-10 18:55:37 +00001462#ifndef NDEBUG
Matt Arsenault79d55f52013-12-05 20:02:18 +00001463 typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType;
Matt Arsenault0f5f0152013-12-10 18:55:37 +00001464#endif
Chandler Carruth8d150782011-11-13 11:20:44 +00001465 DEBUG({
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001466 // Crash at the end so we get all of the debugging output first.
1467 bool BadFunc = false;
Chandler Carruth8d150782011-11-13 11:20:44 +00001468 FunctionBlockSetType FunctionBlockSet;
Xinliang David Li52530a72016-06-13 22:23:44 +00001469 for (MachineBasicBlock &MBB : *F)
Chandler Carruth7a715da2015-03-05 03:19:05 +00001470 FunctionBlockSet.insert(&MBB);
Chandler Carruth8d150782011-11-13 11:20:44 +00001471
Chandler Carruth7a715da2015-03-05 03:19:05 +00001472 for (MachineBasicBlock *ChainBB : FunctionChain)
1473 if (!FunctionBlockSet.erase(ChainBB)) {
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001474 BadFunc = true;
Chandler Carruth8d150782011-11-13 11:20:44 +00001475 dbgs() << "Function chain contains a block not in the function!\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00001476 << " Bad block: " << getBlockName(ChainBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001477 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001478
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001479 if (!FunctionBlockSet.empty()) {
1480 BadFunc = true;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001481 for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
Chandler Carruth8d150782011-11-13 11:20:44 +00001482 dbgs() << "Function contains blocks never placed into a chain!\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00001483 << " Bad block: " << getBlockName(RemainingBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001484 }
1485 assert(!BadFunc && "Detected problems with the block placement.");
Chandler Carruth8d150782011-11-13 11:20:44 +00001486 });
1487
1488 // Splice the blocks into place.
Xinliang David Li52530a72016-06-13 22:23:44 +00001489 MachineFunction::iterator InsertPos = F->begin();
Chandler Carruth7a715da2015-03-05 03:19:05 +00001490 for (MachineBasicBlock *ChainBB : FunctionChain) {
1491 DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
1492 : " ... ")
1493 << getBlockName(ChainBB) << "\n");
1494 if (InsertPos != MachineFunction::iterator(ChainBB))
Xinliang David Li52530a72016-06-13 22:23:44 +00001495 F->splice(InsertPos, ChainBB);
Chandler Carruth8d150782011-11-13 11:20:44 +00001496 else
1497 ++InsertPos;
1498
1499 // Update the terminator of the previous block.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001500 if (ChainBB == *FunctionChain.begin())
Chandler Carruth8d150782011-11-13 11:20:44 +00001501 continue;
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001502 MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB));
Chandler Carruth8d150782011-11-13 11:20:44 +00001503
Chandler Carruth10281422011-10-21 06:46:38 +00001504 // FIXME: It would be awesome of updateTerminator would just return rather
1505 // than assert when the branch cannot be analyzed in order to remove this
1506 // boiler plate.
1507 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001508 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001509
Haicheng Wu90a55652016-05-24 22:16:14 +00001510 // The "PrevBB" is not yet updated to reflect current code layout, so,
1511 // o. it may fall-through to a block without explict "goto" instruction
1512 // before layout, and no longer fall-through it after layout; or
1513 // o. just opposite.
1514 //
1515 // AnalyzeBranch() may return erroneous value for FBB when these two
1516 // situations take place. For the first scenario FBB is mistakenly set NULL;
1517 // for the 2nd scenario, the FBB, which is expected to be NULL, is
1518 // mistakenly pointing to "*BI".
1519 // Thus, if the future change needs to use FBB before the layout is set, it
1520 // has to correct FBB first by using the code similar to the following:
1521 //
1522 // if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
1523 // PrevBB->updateTerminator();
1524 // Cond.clear();
1525 // TBB = FBB = nullptr;
1526 // if (TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
1527 // // FIXME: This should never take place.
1528 // TBB = FBB = nullptr;
1529 // }
1530 // }
Xinliang David Li52530a72016-06-13 22:23:44 +00001531 if (!TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond))
Haicheng Wu90a55652016-05-24 22:16:14 +00001532 PrevBB->updateTerminator();
Chandler Carruth10281422011-10-21 06:46:38 +00001533 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001534
1535 // Fixup the last block.
1536 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001537 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Xinliang David Li52530a72016-06-13 22:23:44 +00001538 if (!TII->AnalyzeBranch(F->back(), TBB, FBB, Cond))
1539 F->back().updateTerminator();
Haicheng Wu90a55652016-05-24 22:16:14 +00001540}
1541
Xinliang David Li52530a72016-06-13 22:23:44 +00001542void MachineBlockPlacement::optimizeBranches() {
1543 BlockChain &FunctionChain = *BlockToChain[&F->front()];
Haicheng Wu90a55652016-05-24 22:16:14 +00001544 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
Quentin Colombet776e6de2016-05-02 22:58:59 +00001545
1546 // Now that all the basic blocks in the chain have the proper layout,
1547 // make a final call to AnalyzeBranch with AllowModify set.
1548 // Indeed, the target may be able to optimize the branches in a way we
1549 // cannot because all branches may not be analyzable.
1550 // E.g., the target may be able to remove an unconditional branch to
1551 // a fallthrough when it occurs after predicated terminators.
1552 for (MachineBasicBlock *ChainBB : FunctionChain) {
1553 Cond.clear();
Haicheng Wu90a55652016-05-24 22:16:14 +00001554 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1555 if (!TII->AnalyzeBranch(*ChainBB, TBB, FBB, Cond, /*AllowModify*/ true)) {
1556 // If PrevBB has a two-way branch, try to re-order the branches
1557 // such that we branch to the successor with higher probability first.
1558 if (TBB && !Cond.empty() && FBB &&
1559 MBPI->getEdgeProbability(ChainBB, FBB) >
1560 MBPI->getEdgeProbability(ChainBB, TBB) &&
1561 !TII->ReverseBranchCondition(Cond)) {
1562 DEBUG(dbgs() << "Reverse order of the two branches: "
1563 << getBlockName(ChainBB) << "\n");
1564 DEBUG(dbgs() << " Edge probability: "
1565 << MBPI->getEdgeProbability(ChainBB, FBB) << " vs "
1566 << MBPI->getEdgeProbability(ChainBB, TBB) << "\n");
1567 DebugLoc dl; // FIXME: this is nowhere
1568 TII->RemoveBranch(*ChainBB);
1569 TII->InsertBranch(*ChainBB, FBB, TBB, Cond, dl);
1570 ChainBB->updateTerminator();
1571 }
1572 }
Quentin Colombet776e6de2016-05-02 22:58:59 +00001573 }
Haicheng Wue749ce52016-04-29 17:06:44 +00001574}
Chandler Carruth10281422011-10-21 06:46:38 +00001575
Xinliang David Li52530a72016-06-13 22:23:44 +00001576void MachineBlockPlacement::alignBlocks() {
Chandler Carruthccc7e422012-04-16 01:12:56 +00001577 // Walk through the backedges of the function now that we have fully laid out
1578 // the basic blocks and align the destination of each backedge. We don't rely
Chandler Carruth881d0a72012-08-07 09:45:24 +00001579 // exclusively on the loop info here so that we can align backedges in
1580 // unnatural CFGs and backedges that were introduced purely because of the
1581 // loop rotations done during this layout pass.
Xinliang David Li52530a72016-06-13 22:23:44 +00001582 if (F->getFunction()->optForSize())
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001583 return;
Xinliang David Li52530a72016-06-13 22:23:44 +00001584 BlockChain &FunctionChain = *BlockToChain[&F->front()];
Chandler Carruth881d0a72012-08-07 09:45:24 +00001585 if (FunctionChain.begin() == FunctionChain.end())
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001586 return; // Empty chain.
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001587
Chandler Carruth881d0a72012-08-07 09:45:24 +00001588 const BranchProbability ColdProb(1, 5); // 20%
Xinliang David Li52530a72016-06-13 22:23:44 +00001589 BlockFrequency EntryFreq = MBFI->getBlockFreq(&F->front());
Chandler Carruth881d0a72012-08-07 09:45:24 +00001590 BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001591 for (MachineBasicBlock *ChainBB : FunctionChain) {
1592 if (ChainBB == *FunctionChain.begin())
1593 continue;
1594
Chandler Carruth881d0a72012-08-07 09:45:24 +00001595 // Don't align non-looping basic blocks. These are unlikely to execute
1596 // enough times to matter in practice. Note that we'll still handle
1597 // unnatural CFGs inside of a natural outer loop (the common case) and
1598 // rotated loops.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001599 MachineLoop *L = MLI->getLoopFor(ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001600 if (!L)
1601 continue;
1602
Hal Finkel57725662015-01-03 17:58:24 +00001603 unsigned Align = TLI->getPrefLoopAlignment(L);
1604 if (!Align)
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001605 continue; // Don't care about loop alignment.
Hal Finkel57725662015-01-03 17:58:24 +00001606
Chandler Carruth881d0a72012-08-07 09:45:24 +00001607 // If the block is cold relative to the function entry don't waste space
1608 // aligning it.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001609 BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001610 if (Freq < WeightedEntryFreq)
1611 continue;
1612
1613 // If the block is cold relative to its loop header, don't align it
1614 // regardless of what edges into the block exist.
1615 MachineBasicBlock *LoopHeader = L->getHeader();
1616 BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
1617 if (Freq < (LoopHeaderFreq * ColdProb))
1618 continue;
1619
1620 // Check for the existence of a non-layout predecessor which would benefit
1621 // from aligning this block.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001622 MachineBasicBlock *LayoutPred =
1623 &*std::prev(MachineFunction::iterator(ChainBB));
Chandler Carruth881d0a72012-08-07 09:45:24 +00001624
1625 // Force alignment if all the predecessors are jumps. We already checked
1626 // that the block isn't cold above.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001627 if (!LayoutPred->isSuccessor(ChainBB)) {
1628 ChainBB->setAlignment(Align);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001629 continue;
1630 }
1631
1632 // Align this block if the layout predecessor's edge into this block is
Nadav Rotem6036f582013-03-29 16:34:23 +00001633 // cold relative to the block. When this is true, other predecessors make up
Chandler Carruth881d0a72012-08-07 09:45:24 +00001634 // all of the hot entries into the block and thus alignment is likely to be
1635 // important.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001636 BranchProbability LayoutProb =
1637 MBPI->getEdgeProbability(LayoutPred, ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001638 BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
1639 if (LayoutEdgeFreq <= (Freq * ColdProb))
Chandler Carruth7a715da2015-03-05 03:19:05 +00001640 ChainBB->setAlignment(Align);
Chandler Carruthccc7e422012-04-16 01:12:56 +00001641 }
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001642}
1643
Xinliang David Li52530a72016-06-13 22:23:44 +00001644bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &MF) {
1645 if (skipFunction(*MF.getFunction()))
Andrew Kaylor50271f72016-05-03 22:32:30 +00001646 return false;
1647
Chandler Carruth10281422011-10-21 06:46:38 +00001648 // Check for single-block functions and skip them.
Xinliang David Li52530a72016-06-13 22:23:44 +00001649 if (std::next(MF.begin()) == MF.end())
Chandler Carruth10281422011-10-21 06:46:38 +00001650 return false;
1651
Xinliang David Li52530a72016-06-13 22:23:44 +00001652 F = &MF;
Chandler Carruth10281422011-10-21 06:46:38 +00001653 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
Haicheng Wu5b458cc2016-06-09 15:24:29 +00001654 MBFI = llvm::make_unique<BranchFolder::MBFIWrapper>(
1655 getAnalysis<MachineBlockFrequencyInfo>());
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001656 MLI = &getAnalysis<MachineLoopInfo>();
Xinliang David Li52530a72016-06-13 22:23:44 +00001657 TII = MF.getSubtarget().getInstrInfo();
1658 TLI = MF.getSubtarget().getTargetLowering();
Daniel Jasper471e8562015-03-04 11:05:34 +00001659 MDT = &getAnalysis<MachineDominatorTree>();
Chandler Carruth10281422011-10-21 06:46:38 +00001660 assert(BlockToChain.empty());
Chandler Carruth10281422011-10-21 06:46:38 +00001661
Xinliang David Li52530a72016-06-13 22:23:44 +00001662 buildCFGChains();
Haicheng Wu5b458cc2016-06-09 15:24:29 +00001663
1664 // Changing the layout can create new tail merging opportunities.
1665 TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
1666 // TailMerge can create jump into if branches that make CFG irreducible for
1667 // HW that requires structurized CFG.
Xinliang David Li52530a72016-06-13 22:23:44 +00001668 bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&
Haicheng Wu5b458cc2016-06-09 15:24:29 +00001669 PassConfig->getEnableTailMerge() &&
1670 BranchFoldPlacement;
1671 // No tail merging opportunities if the block number is less than four.
Xinliang David Li52530a72016-06-13 22:23:44 +00001672 if (MF.size() > 3 && EnableTailMerge) {
Haicheng Wu5b458cc2016-06-09 15:24:29 +00001673 BranchFolder BF(/*EnableTailMerge=*/true, /*CommonHoist=*/false, *MBFI,
1674 *MBPI);
1675
Xinliang David Li52530a72016-06-13 22:23:44 +00001676 if (BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
Haicheng Wu5b458cc2016-06-09 15:24:29 +00001677 getAnalysisIfAvailable<MachineModuleInfo>(), MLI,
1678 /*AfterBlockPlacement=*/true)) {
1679 // Redo the layout if tail merging creates/removes/moves blocks.
1680 BlockToChain.clear();
1681 ChainAllocator.DestroyAll();
Xinliang David Li52530a72016-06-13 22:23:44 +00001682 buildCFGChains();
Haicheng Wu5b458cc2016-06-09 15:24:29 +00001683 }
1684 }
1685
Xinliang David Li52530a72016-06-13 22:23:44 +00001686 optimizeBranches();
1687 alignBlocks();
Chandler Carruth10281422011-10-21 06:46:38 +00001688
Chandler Carruth10281422011-10-21 06:46:38 +00001689 BlockToChain.clear();
Chandler Carruthfd9b4d92011-11-14 10:57:23 +00001690 ChainAllocator.DestroyAll();
Chandler Carruth10281422011-10-21 06:46:38 +00001691
Nadav Rotemc0adc9f2013-04-12 01:24:16 +00001692 if (AlignAllBlock)
1693 // Align all of the blocks in the function to a specific alignment.
Xinliang David Li52530a72016-06-13 22:23:44 +00001694 for (MachineBasicBlock &MBB : MF)
Chandler Carruth7a715da2015-03-05 03:19:05 +00001695 MBB.setAlignment(AlignAllBlock);
Geoff Berry10494ac2016-01-21 17:25:52 +00001696 else if (AlignAllNonFallThruBlocks) {
1697 // Align all of the blocks that have no fall-through predecessors to a
1698 // specific alignment.
Xinliang David Li52530a72016-06-13 22:23:44 +00001699 for (auto MBI = std::next(MF.begin()), MBE = MF.end(); MBI != MBE; ++MBI) {
Geoff Berry10494ac2016-01-21 17:25:52 +00001700 auto LayoutPred = std::prev(MBI);
1701 if (!LayoutPred->isSuccessor(&*MBI))
1702 MBI->setAlignment(AlignAllNonFallThruBlocks);
1703 }
1704 }
Nadav Rotemc0adc9f2013-04-12 01:24:16 +00001705
Chandler Carruth10281422011-10-21 06:46:38 +00001706 // We always return true as we have no way to track whether the final order
1707 // differs from the original order.
1708 return true;
1709}
Chandler Carruthae4e8002011-11-02 07:17:12 +00001710
1711namespace {
1712/// \brief A pass to compute block placement statistics.
1713///
1714/// A separate pass to compute interesting statistics for evaluating block
1715/// placement. This is separate from the actual placement pass so that they can
Benjamin Kramerbde91762012-06-02 10:20:22 +00001716/// be computed in the absence of any placement transformations or when using
Chandler Carruthae4e8002011-11-02 07:17:12 +00001717/// alternative placement strategies.
1718class MachineBlockPlacementStats : public MachineFunctionPass {
1719 /// \brief A handle to the branch probability pass.
1720 const MachineBranchProbabilityInfo *MBPI;
1721
1722 /// \brief A handle to the function-wide block frequency pass.
1723 const MachineBlockFrequencyInfo *MBFI;
1724
1725public:
1726 static char ID; // Pass identification, replacement for typeid
1727 MachineBlockPlacementStats() : MachineFunctionPass(ID) {
1728 initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
1729 }
1730
Craig Topper4584cd52014-03-07 09:26:03 +00001731 bool runOnMachineFunction(MachineFunction &F) override;
Chandler Carruthae4e8002011-11-02 07:17:12 +00001732
Craig Topper4584cd52014-03-07 09:26:03 +00001733 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruthae4e8002011-11-02 07:17:12 +00001734 AU.addRequired<MachineBranchProbabilityInfo>();
1735 AU.addRequired<MachineBlockFrequencyInfo>();
1736 AU.setPreservesAll();
1737 MachineFunctionPass::getAnalysisUsage(AU);
1738 }
Chandler Carruthae4e8002011-11-02 07:17:12 +00001739};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001740}
Chandler Carruthae4e8002011-11-02 07:17:12 +00001741
1742char MachineBlockPlacementStats::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +00001743char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
Chandler Carruthae4e8002011-11-02 07:17:12 +00001744INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
1745 "Basic Block Placement Stats", false, false)
1746INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
1747INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
1748INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
1749 "Basic Block Placement Stats", false, false)
1750
Chandler Carruthae4e8002011-11-02 07:17:12 +00001751bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
1752 // Check for single-block functions and skip them.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001753 if (std::next(F.begin()) == F.end())
Chandler Carruthae4e8002011-11-02 07:17:12 +00001754 return false;
1755
1756 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1757 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1758
Chandler Carruth7a715da2015-03-05 03:19:05 +00001759 for (MachineBasicBlock &MBB : F) {
1760 BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001761 Statistic &NumBranches =
Chandler Carruth7a715da2015-03-05 03:19:05 +00001762 (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001763 Statistic &BranchTakenFreq =
Chandler Carruth7a715da2015-03-05 03:19:05 +00001764 (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
1765 for (MachineBasicBlock *Succ : MBB.successors()) {
Chandler Carruthae4e8002011-11-02 07:17:12 +00001766 // Skip if this successor is a fallthrough.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001767 if (MBB.isLayoutSuccessor(Succ))
Chandler Carruthae4e8002011-11-02 07:17:12 +00001768 continue;
1769
Chandler Carruth7a715da2015-03-05 03:19:05 +00001770 BlockFrequency EdgeFreq =
1771 BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
Chandler Carruthae4e8002011-11-02 07:17:12 +00001772 ++NumBranches;
1773 BranchTakenFreq += EdgeFreq.getFrequency();
1774 }
1775 }
1776
1777 return false;
1778}