blob: 03dda8b36a71a465deed0da37c667aa29dac95cd [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",
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000112 cl::desc("Cost that models the probabilistic risk of an instruction "
Cong Hou7745dbc2015-10-19 23:16:40 +0000113 "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 Li93926ac2016-07-01 05:46:48 +0000240 /// \brief work lists of blocks that are ready to be laid out
241 SmallVector<MachineBasicBlock *, 16> BlockWorkList;
242 SmallVector<MachineBasicBlock *, 16> EHPadWorkList;
243
Xinliang David Li52530a72016-06-13 22:23:44 +0000244 /// \brief Machine Function
245 MachineFunction *F;
246
Chandler Carruth10281422011-10-21 06:46:38 +0000247 /// \brief A handle to the branch probability pass.
248 const MachineBranchProbabilityInfo *MBPI;
249
250 /// \brief A handle to the function-wide block frequency pass.
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000251 std::unique_ptr<BranchFolder::MBFIWrapper> MBFI;
Chandler Carruth10281422011-10-21 06:46:38 +0000252
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000253 /// \brief A handle to the loop info.
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000254 MachineLoopInfo *MLI;
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000255
Chandler Carruth10281422011-10-21 06:46:38 +0000256 /// \brief A handle to the target's instruction info.
257 const TargetInstrInfo *TII;
258
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000259 /// \brief A handle to the target's lowering info.
Benjamin Kramer56b31bd2013-01-11 20:05:37 +0000260 const TargetLoweringBase *TLI;
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000261
Daniel Jasper471e8562015-03-04 11:05:34 +0000262 /// \brief A handle to the post dominator tree.
263 MachineDominatorTree *MDT;
264
265 /// \brief A set of blocks that are unavoidably execute, i.e. they dominate
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000266 /// all terminators of the MachineFunction.
Daniel Jasper471e8562015-03-04 11:05:34 +0000267 SmallPtrSet<MachineBasicBlock *, 4> UnavoidableBlocks;
268
Chandler Carruth10281422011-10-21 06:46:38 +0000269 /// \brief Allocator and owner of BlockChain structures.
270 ///
Chandler Carruth9139f442012-06-26 05:16:37 +0000271 /// We build BlockChains lazily while processing the loop structure of
272 /// a function. To reduce malloc traffic, we allocate them using this
273 /// slab-like allocator, and destroy them after the pass completes. An
274 /// important guarantee is that this allocator produces stable pointers to
275 /// the chains.
Chandler Carruth10281422011-10-21 06:46:38 +0000276 SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
277
278 /// \brief Function wide BasicBlock to BlockChain mapping.
279 ///
280 /// This mapping allows efficiently moving from any given basic block to the
281 /// BlockChain it participates in, if any. We use it to, among other things,
282 /// allow implicitly defining edges between chains as the existing edges
283 /// between basic blocks.
284 DenseMap<MachineBasicBlock *, BlockChain *> BlockToChain;
285
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000286 void markChainSuccessors(BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
Craig Topperc0196b12014-04-14 00:51:57 +0000287 const BlockFilterSet *BlockFilter = nullptr);
Xinliang David Li594ffa32016-06-11 18:35:40 +0000288 BranchProbability
289 collectViableSuccessors(MachineBasicBlock *BB, BlockChain &Chain,
290 const BlockFilterSet *BlockFilter,
291 SmallVector<MachineBasicBlock *, 4> &Successors);
Xinliang David Li071d0f12016-06-12 16:54:03 +0000292 bool shouldPredBlockBeOutlined(MachineBasicBlock *BB, MachineBasicBlock *Succ,
293 BlockChain &Chain,
294 const BlockFilterSet *BlockFilter,
295 BranchProbability SuccProb,
296 BranchProbability HotProb);
Xinliang David Licbf12142016-06-13 20:24:19 +0000297 bool
298 hasBetterLayoutPredecessor(MachineBasicBlock *BB, MachineBasicBlock *Succ,
299 BlockChain &SuccChain, BranchProbability SuccProb,
300 BranchProbability RealSuccProb, BlockChain &Chain,
301 const BlockFilterSet *BlockFilter);
Jakub Staszak90616162011-12-21 23:02:08 +0000302 MachineBasicBlock *selectBestSuccessor(MachineBasicBlock *BB,
303 BlockChain &Chain,
304 const BlockFilterSet *BlockFilter);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000305 MachineBasicBlock *
306 selectBestCandidateBlock(BlockChain &Chain,
Amaury Sechet9ee4ddd2016-04-07 06:34:47 +0000307 SmallVectorImpl<MachineBasicBlock *> &WorkList);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000308 MachineBasicBlock *
Xinliang David Li52530a72016-06-13 22:23:44 +0000309 getFirstUnplacedBlock(const BlockChain &PlacedChain,
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000310 MachineFunction::iterator &PrevUnplacedBlockIt,
311 const BlockFilterSet *BlockFilter);
Amaury Secheteae09c22016-03-14 21:24:11 +0000312
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000313 /// \brief Add a basic block to the work list if it is appropriate.
Amaury Secheteae09c22016-03-14 21:24:11 +0000314 ///
315 /// If the optional parameter BlockFilter is provided, only MBB
316 /// present in the set will be added to the worklist. If nullptr
317 /// is provided, no filtering occurs.
318 void fillWorkLists(MachineBasicBlock *MBB,
319 SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
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,
Craig Topperc0196b12014-04-14 00:51:57 +0000322 const BlockFilterSet *BlockFilter = nullptr);
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000323 MachineBasicBlock *findBestLoopTop(MachineLoop &L,
324 const BlockFilterSet &LoopBlockSet);
Xinliang David Li52530a72016-06-13 22:23:44 +0000325 MachineBasicBlock *findBestLoopExit(MachineLoop &L,
Chandler Carruthccc7e422012-04-16 01:12:56 +0000326 const BlockFilterSet &LoopBlockSet);
Xinliang David Li52530a72016-06-13 22:23:44 +0000327 BlockFilterSet collectLoopBlockSet(MachineLoop &L);
328 void buildLoopChains(MachineLoop &L);
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000329 void rotateLoop(BlockChain &LoopChain, MachineBasicBlock *ExitingBB,
330 const BlockFilterSet &LoopBlockSet);
Cong Hou7745dbc2015-10-19 23:16:40 +0000331 void rotateLoopWithProfile(BlockChain &LoopChain, MachineLoop &L,
332 const BlockFilterSet &LoopBlockSet);
Xinliang David Li52530a72016-06-13 22:23:44 +0000333 void collectMustExecuteBBs();
334 void buildCFGChains();
335 void optimizeBranches();
336 void alignBlocks();
Chandler Carruth10281422011-10-21 06:46:38 +0000337
338public:
339 static char ID; // Pass identification, replacement for typeid
340 MachineBlockPlacement() : MachineFunctionPass(ID) {
341 initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
342 }
343
Craig Topper4584cd52014-03-07 09:26:03 +0000344 bool runOnMachineFunction(MachineFunction &F) override;
Chandler Carruth10281422011-10-21 06:46:38 +0000345
Craig Topper4584cd52014-03-07 09:26:03 +0000346 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth10281422011-10-21 06:46:38 +0000347 AU.addRequired<MachineBranchProbabilityInfo>();
348 AU.addRequired<MachineBlockFrequencyInfo>();
Daniel Jasper471e8562015-03-04 11:05:34 +0000349 AU.addRequired<MachineDominatorTree>();
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000350 AU.addRequired<MachineLoopInfo>();
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000351 AU.addRequired<TargetPassConfig>();
Chandler Carruth10281422011-10-21 06:46:38 +0000352 MachineFunctionPass::getAnalysisUsage(AU);
353 }
Chandler Carruth10281422011-10-21 06:46:38 +0000354};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000355}
Chandler Carruth10281422011-10-21 06:46:38 +0000356
357char MachineBlockPlacement::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000358char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
Chandler Carruthd0dced52015-03-05 02:28:25 +0000359INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement",
Chandler Carruth10281422011-10-21 06:46:38 +0000360 "Branch Probability Basic Block Placement", false, false)
361INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
362INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
Daniel Jasper471e8562015-03-04 11:05:34 +0000363INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000364INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
Chandler Carruthd0dced52015-03-05 02:28:25 +0000365INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement",
Chandler Carruth10281422011-10-21 06:46:38 +0000366 "Branch Probability Basic Block Placement", false, false)
367
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000368#ifndef NDEBUG
369/// \brief Helper to print the name of a MBB.
370///
371/// Only used by debug logging.
Jakub Staszak90616162011-12-21 23:02:08 +0000372static std::string getBlockName(MachineBasicBlock *BB) {
Alp Tokere69170a2014-06-26 22:52:05 +0000373 std::string Result;
374 raw_string_ostream OS(Result);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000375 OS << "BB#" << BB->getNumber();
Philip Reamesb9688f42016-03-02 21:45:13 +0000376 OS << " ('" << BB->getName() << "')";
Alp Tokere69170a2014-06-26 22:52:05 +0000377 OS.flush();
378 return Result;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000379}
380#endif
381
Chandler Carrutheb4ec3a2011-11-13 11:34:55 +0000382/// \brief Mark a chain's successors as having one fewer preds.
383///
384/// When a chain is being merged into the "placed" chain, this routine will
385/// quickly walk the successors of each block in the chain and mark them as
386/// having one fewer active predecessor. It also adds any successors of this
387/// chain which reach the zero-predecessor state to the worklist passed in.
Chandler Carruth8d150782011-11-13 11:20:44 +0000388void MachineBlockPlacement::markChainSuccessors(
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000389 BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
Jakub Staszak90616162011-12-21 23:02:08 +0000390 const BlockFilterSet *BlockFilter) {
Chandler Carruth8d150782011-11-13 11:20:44 +0000391 // Walk all the blocks in this chain, marking their successors as having
392 // a predecessor placed.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000393 for (MachineBasicBlock *MBB : Chain) {
Chandler Carruth8d150782011-11-13 11:20:44 +0000394 // Add any successors for which this is the only un-placed in-loop
395 // predecessor to the worklist as a viable candidate for CFG-neutral
396 // placement. No subsequent placement of this block will violate the CFG
397 // shape, so we get to use heuristics to choose a favorable placement.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000398 for (MachineBasicBlock *Succ : MBB->successors()) {
399 if (BlockFilter && !BlockFilter->count(Succ))
Chandler Carruth8d150782011-11-13 11:20:44 +0000400 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000401 BlockChain &SuccChain = *BlockToChain[Succ];
Chandler Carruth8d150782011-11-13 11:20:44 +0000402 // Disregard edges within a fixed chain, or edges to the loop header.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000403 if (&Chain == &SuccChain || Succ == LoopHeaderBB)
Chandler Carruth8d150782011-11-13 11:20:44 +0000404 continue;
Chandler Carruth10281422011-10-21 06:46:38 +0000405
Chandler Carruth8d150782011-11-13 11:20:44 +0000406 // This is a cross-chain edge that is within the loop, so decrement the
407 // loop predecessor count of the destination chain.
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000408 if (SuccChain.UnscheduledPredecessors == 0 ||
409 --SuccChain.UnscheduledPredecessors > 0)
410 continue;
411
412 auto *MBB = *SuccChain.begin();
413 if (MBB->isEHPad())
414 EHPadWorkList.push_back(MBB);
415 else
416 BlockWorkList.push_back(MBB);
Chandler Carruth10281422011-10-21 06:46:38 +0000417 }
418 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000419}
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000420
Xinliang David Li594ffa32016-06-11 18:35:40 +0000421/// This helper function collects the set of successors of block
422/// \p BB that are allowed to be its layout successors, and return
423/// the total branch probability of edges from \p BB to those
424/// blocks.
425BranchProbability MachineBlockPlacement::collectViableSuccessors(
426 MachineBasicBlock *BB, BlockChain &Chain, const BlockFilterSet *BlockFilter,
427 SmallVector<MachineBasicBlock *, 4> &Successors) {
Cong Houd97c1002015-12-01 05:29:22 +0000428 // Adjust edge probabilities by excluding edges pointing to blocks that is
429 // either not in BlockFilter or is already in the current chain. Consider the
430 // following CFG:
Cong Hou41cf1a52015-11-18 00:52:52 +0000431 //
432 // --->A
433 // | / \
434 // | B C
435 // | \ / \
436 // ----D E
437 //
438 // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after
439 // A->C is chosen as a fall-through, D won't be selected as a successor of C
440 // due to CFG constraint (the probability of C->D is not greater than
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000441 // HotProb to break top-order). If we exclude E that is not in BlockFilter
Xinliang David Li594ffa32016-06-11 18:35:40 +0000442 // when calculating the probability of C->D, D will be selected and we
443 // will get A C D B as the layout of this loop.
Cong Houd97c1002015-12-01 05:29:22 +0000444 auto AdjustedSumProb = BranchProbability::getOne();
Cong Hou41cf1a52015-11-18 00:52:52 +0000445 for (MachineBasicBlock *Succ : BB->successors()) {
446 bool SkipSucc = false;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000447 if (Succ->isEHPad() || (BlockFilter && !BlockFilter->count(Succ))) {
Cong Hou41cf1a52015-11-18 00:52:52 +0000448 SkipSucc = true;
449 } else {
450 BlockChain *SuccChain = BlockToChain[Succ];
451 if (SuccChain == &Chain) {
Cong Hou41cf1a52015-11-18 00:52:52 +0000452 SkipSucc = true;
453 } else if (Succ != *SuccChain->begin()) {
454 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> Mid chain!\n");
455 continue;
456 }
457 }
458 if (SkipSucc)
Cong Houd97c1002015-12-01 05:29:22 +0000459 AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ);
Cong Hou41cf1a52015-11-18 00:52:52 +0000460 else
461 Successors.push_back(Succ);
462 }
463
Xinliang David Li594ffa32016-06-11 18:35:40 +0000464 return AdjustedSumProb;
465}
466
467/// The helper function returns the branch probability that is adjusted
468/// or normalized over the new total \p AdjustedSumProb.
Xinliang David Li594ffa32016-06-11 18:35:40 +0000469static BranchProbability
470getAdjustedProbability(BranchProbability OrigProb,
471 BranchProbability AdjustedSumProb) {
472 BranchProbability SuccProb;
473 uint32_t SuccProbN = OrigProb.getNumerator();
474 uint32_t SuccProbD = AdjustedSumProb.getNumerator();
475 if (SuccProbN >= SuccProbD)
476 SuccProb = BranchProbability::getOne();
477 else
478 SuccProb = BranchProbability(SuccProbN, SuccProbD);
479
480 return SuccProb;
481}
482
Xinliang David Li071d0f12016-06-12 16:54:03 +0000483/// When the option OutlineOptionalBranches is on, this method
484/// checks if the fallthrough candidate block \p Succ (of block
485/// \p BB) also has other unscheduled predecessor blocks which
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000486/// are also successors of \p BB (forming triangular shape CFG).
Xinliang David Li071d0f12016-06-12 16:54:03 +0000487/// If none of such predecessors are small, it returns true.
488/// The caller can choose to select \p Succ as the layout successors
489/// so that \p Succ's predecessors (optional branches) can be
490/// outlined.
491/// FIXME: fold this with more general layout cost analysis.
492bool MachineBlockPlacement::shouldPredBlockBeOutlined(
493 MachineBasicBlock *BB, MachineBasicBlock *Succ, BlockChain &Chain,
494 const BlockFilterSet *BlockFilter, BranchProbability SuccProb,
495 BranchProbability HotProb) {
496 if (!OutlineOptionalBranches)
497 return false;
498 // If we outline optional branches, look whether Succ is unavoidable, i.e.
499 // dominates all terminators of the MachineFunction. If it does, other
500 // successors must be optional. Don't do this for cold branches.
501 if (SuccProb > HotProb.getCompl() && UnavoidableBlocks.count(Succ) > 0) {
502 for (MachineBasicBlock *Pred : Succ->predecessors()) {
503 // Check whether there is an unplaced optional branch.
504 if (Pred == Succ || (BlockFilter && !BlockFilter->count(Pred)) ||
505 BlockToChain[Pred] == &Chain)
506 continue;
507 // Check whether the optional branch has exactly one BB.
508 if (Pred->pred_size() > 1 || *Pred->pred_begin() != BB)
509 continue;
510 // Check whether the optional branch is small.
511 if (Pred->size() < OutlineOptionalThreshold)
512 return false;
513 }
514 return true;
515 } else
516 return false;
517}
518
Dehao Chen9f2bdfb2016-06-14 22:27:17 +0000519// When profile is not present, return the StaticLikelyProb.
520// When profile is available, we need to handle the triangle-shape CFG.
521static BranchProbability getLayoutSuccessorProbThreshold(
522 MachineBasicBlock *BB) {
523 if (!BB->getParent()->getFunction()->getEntryCount())
524 return BranchProbability(StaticLikelyProb, 100);
525 if (BB->succ_size() == 2) {
526 const MachineBasicBlock *Succ1 = *BB->succ_begin();
527 const MachineBasicBlock *Succ2 = *(BB->succ_begin() + 1);
Xinliang David Lie34ed832016-06-15 03:03:30 +0000528 if (Succ1->isSuccessor(Succ2) || Succ2->isSuccessor(Succ1)) {
529 /* See case 1 below for the cost analysis. For BB->Succ to
530 * be taken with smaller cost, the following needs to hold:
531 * Prob(BB->Succ) > 2* Prob(BB->Pred)
532 * So the threshold T
533 * T = 2 * (1-Prob(BB->Pred). Since T + Prob(BB->Pred) == 1,
534 * We have T + T/2 = 1, i.e. T = 2/3. Also adding user specified
535 * branch bias, we have
536 * T = (2/3)*(ProfileLikelyProb/50)
537 * = (2*ProfileLikelyProb)/150)
538 */
539 return BranchProbability(2 * ProfileLikelyProb, 150);
540 }
Dehao Chen9f2bdfb2016-06-14 22:27:17 +0000541 }
542 return BranchProbability(ProfileLikelyProb, 100);
Xinliang David Licbf12142016-06-13 20:24:19 +0000543}
544
545/// Checks to see if the layout candidate block \p Succ has a better layout
546/// predecessor than \c BB. If yes, returns true.
547bool MachineBlockPlacement::hasBetterLayoutPredecessor(
548 MachineBasicBlock *BB, MachineBasicBlock *Succ, BlockChain &SuccChain,
549 BranchProbability SuccProb, BranchProbability RealSuccProb,
550 BlockChain &Chain, const BlockFilterSet *BlockFilter) {
551
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000552 // There isn't a better layout when there are no unscheduled predecessors.
Xinliang David Licbf12142016-06-13 20:24:19 +0000553 if (SuccChain.UnscheduledPredecessors == 0)
554 return false;
555
556 // There are two basic scenarios here:
557 // -------------------------------------
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000558 // Case 1: triangular shape CFG (if-then):
Xinliang David Licbf12142016-06-13 20:24:19 +0000559 // BB
560 // | \
561 // | \
562 // | Pred
563 // | /
564 // Succ
565 // In this case, we are evaluating whether to select edge -> Succ, e.g.
566 // set Succ as the layout successor of BB. Picking Succ as BB's
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000567 // successor breaks the CFG constraints (FIXME: define these constraints).
568 // With this layout, Pred BB
Xinliang David Licbf12142016-06-13 20:24:19 +0000569 // is forced to be outlined, so the overall cost will be cost of the
570 // branch taken from BB to Pred, plus the cost of back taken branch
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000571 // from Pred to Succ, as well as the additional cost associated
Xinliang David Licbf12142016-06-13 20:24:19 +0000572 // with the needed unconditional jump instruction from Pred To Succ.
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000573
Xinliang David Licbf12142016-06-13 20:24:19 +0000574 // The cost of the topological order layout is the taken branch cost
575 // from BB to Succ, so to make BB->Succ a viable candidate, the following
576 // must hold:
577 // 2 * freq(BB->Pred) * taken_branch_cost + unconditional_jump_cost
578 // < freq(BB->Succ) * taken_branch_cost.
579 // Ignoring unconditional jump cost, we get
580 // freq(BB->Succ) > 2 * freq(BB->Pred), i.e.,
581 // prob(BB->Succ) > 2 * prob(BB->Pred)
582 //
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000583 // When real profile data is available, we can precisely compute the
584 // probability threshold that is needed for edge BB->Succ to be considered.
585 // Without profile data, the heuristic requires the branch bias to be
Xinliang David Licbf12142016-06-13 20:24:19 +0000586 // a lot larger to make sure the signal is very strong (e.g. 80% default).
587 // -----------------------------------------------------------------
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000588 // Case 2: diamond like CFG (if-then-else):
Xinliang David Licbf12142016-06-13 20:24:19 +0000589 // S
590 // / \
591 // | \
592 // BB Pred
593 // \ /
594 // Succ
595 // ..
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000596 //
597 // The current block is BB and edge BB->Succ is now being evaluated.
598 // Note that edge S->BB was previously already selected because
599 // prob(S->BB) > prob(S->Pred).
600 // At this point, 2 blocks can be placed after BB: Pred or Succ. If we
601 // choose Pred, we will have a topological ordering as shown on the left
602 // in the picture below. If we choose Succ, we have the solution as shown
603 // on the right:
604 //
605 // topo-order:
606 //
607 // S----- ---S
608 // | | | |
609 // ---BB | | BB
610 // | | | |
611 // | pred-- | Succ--
612 // | | | |
613 // ---succ ---pred--
614 //
615 // cost = freq(S->Pred) + freq(BB->Succ) cost = 2 * freq (S->Pred)
616 // = freq(S->Pred) + freq(S->BB)
617 //
618 // If we have profile data (i.e, branch probabilities can be trusted), the
619 // cost (number of taken branches) with layout S->BB->Succ->Pred is 2 *
620 // freq(S->Pred) while the cost of topo order is freq(S->Pred) + freq(S->BB).
621 // We know Prob(S->BB) > Prob(S->Pred), so freq(S->BB) > freq(S->Pred), which
622 // means the cost of topological order is greater.
Xinliang David Licbf12142016-06-13 20:24:19 +0000623 // When profile data is not available, however, we need to be more
624 // conservative. If the branch prediction is wrong, breaking the topo-order
625 // will actually yield a layout with large cost. For this reason, we need
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000626 // strong biased branch at block S with Prob(S->BB) in order to select
627 // BB->Succ. This is equivalent to looking the CFG backward with backward
Xinliang David Licbf12142016-06-13 20:24:19 +0000628 // edge: Prob(Succ->BB) needs to >= HotProb in order to be selected (without
629 // profile data).
630
Dehao Chen9f2bdfb2016-06-14 22:27:17 +0000631 BranchProbability HotProb = getLayoutSuccessorProbThreshold(BB);
Xinliang David Licbf12142016-06-13 20:24:19 +0000632
633 // Forward checking. For case 2, SuccProb will be 1.
634 if (SuccProb < HotProb) {
635 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
636 << " (prob) (CFG conflict)\n");
637 return true;
638 }
639
640 // Make sure that a hot successor doesn't have a globally more
641 // important predecessor.
642 BlockFrequency CandidateEdgeFreq = MBFI->getBlockFreq(BB) * RealSuccProb;
643 bool BadCFGConflict = false;
644
645 for (MachineBasicBlock *Pred : Succ->predecessors()) {
646 if (Pred == Succ || BlockToChain[Pred] == &SuccChain ||
647 (BlockFilter && !BlockFilter->count(Pred)) ||
648 BlockToChain[Pred] == &Chain)
649 continue;
650 // Do backward checking. For case 1, it is actually redundant check. For
651 // case 2 above, we need a backward checking to filter out edges that are
652 // not 'strongly' biased. With profile data available, the check is mostly
653 // redundant too (when threshold prob is set at 50%) unless S has more than
654 // two successors.
655 // BB Pred
656 // \ /
657 // Succ
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000658 // We select edge BB->Succ if
Xinliang David Licbf12142016-06-13 20:24:19 +0000659 // freq(BB->Succ) > freq(Succ) * HotProb
660 // i.e. freq(BB->Succ) > freq(BB->Succ) * HotProb + freq(Pred->Succ) *
661 // HotProb
662 // i.e. freq((BB->Succ) * (1 - HotProb) > freq(Pred->Succ) * HotProb
663 BlockFrequency PredEdgeFreq =
664 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
665 if (PredEdgeFreq * HotProb >= CandidateEdgeFreq * HotProb.getCompl()) {
666 BadCFGConflict = true;
667 break;
668 }
669 }
670
671 if (BadCFGConflict) {
672 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
673 << " (prob) (non-cold CFG conflict)\n");
674 return true;
675 }
676
677 return false;
678}
679
Xinliang David Li594ffa32016-06-11 18:35:40 +0000680/// \brief Select the best successor for a block.
681///
682/// This looks across all successors of a particular block and attempts to
683/// select the "best" one to be the layout successor. It only considers direct
684/// successors which also pass the block filter. It will attempt to avoid
685/// breaking CFG structure, but cave and break such structures in the case of
686/// very hot successor edges.
687///
688/// \returns The best successor block found, or null if none are viable.
689MachineBasicBlock *
690MachineBlockPlacement::selectBestSuccessor(MachineBasicBlock *BB,
691 BlockChain &Chain,
692 const BlockFilterSet *BlockFilter) {
693 const BranchProbability HotProb(StaticLikelyProb, 100);
694
695 MachineBasicBlock *BestSucc = nullptr;
696 auto BestProb = BranchProbability::getZero();
697
698 SmallVector<MachineBasicBlock *, 4> Successors;
699 auto AdjustedSumProb =
700 collectViableSuccessors(BB, Chain, BlockFilter, Successors);
701
Cong Hou41cf1a52015-11-18 00:52:52 +0000702 DEBUG(dbgs() << "Attempting merge from: " << getBlockName(BB) << "\n");
703 for (MachineBasicBlock *Succ : Successors) {
Xinliang David Li594ffa32016-06-11 18:35:40 +0000704 auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ);
705 BranchProbability SuccProb =
706 getAdjustedProbability(RealSuccProb, AdjustedSumProb);
Chandler Carruthb3361722011-11-13 11:34:53 +0000707
Xinliang David Li071d0f12016-06-12 16:54:03 +0000708 // This heuristic is off by default.
709 if (shouldPredBlockBeOutlined(BB, Succ, Chain, BlockFilter, SuccProb,
710 HotProb))
711 return Succ;
Daniel Jasper471e8562015-03-04 11:05:34 +0000712
Cong Hou41cf1a52015-11-18 00:52:52 +0000713 BlockChain &SuccChain = *BlockToChain[Succ];
Xinliang David Licbf12142016-06-13 20:24:19 +0000714 // Skip the edge \c BB->Succ if block \c Succ has a better layout
715 // predecessor that yields lower global cost.
716 if (hasBetterLayoutPredecessor(BB, Succ, SuccChain, SuccProb, RealSuccProb,
717 Chain, BlockFilter))
718 continue;
Chandler Carruth18dfac32011-11-20 11:22:06 +0000719
Xinliang David Licbf12142016-06-13 20:24:19 +0000720 DEBUG(
721 dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
722 << " (prob)"
723 << (SuccChain.UnscheduledPredecessors != 0 ? " (CFG break)" : "")
724 << "\n");
Cong Houd97c1002015-12-01 05:29:22 +0000725 if (BestSucc && BestProb >= SuccProb)
Chandler Carruthb3361722011-11-13 11:34:53 +0000726 continue;
Daniel Jaspered9eb722015-02-18 08:19:16 +0000727 BestSucc = Succ;
Cong Houd97c1002015-12-01 05:29:22 +0000728 BestProb = SuccProb;
Chandler Carruthb3361722011-11-13 11:34:53 +0000729 }
730 return BestSucc;
731}
732
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000733/// \brief Select the best block from a worklist.
734///
735/// This looks through the provided worklist as a list of candidate basic
736/// blocks and select the most profitable one to place. The definition of
737/// profitable only really makes sense in the context of a loop. This returns
738/// the most frequently visited block in the worklist, which in the case of
739/// a loop, is the one most desirable to be physically close to the rest of the
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000740/// loop body in order to improve i-cache behavior.
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000741///
742/// \returns The best block found, or null if none are viable.
743MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
Amaury Sechet9ee4ddd2016-04-07 06:34:47 +0000744 BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList) {
Chandler Carruth0af6a0b2011-11-14 09:46:33 +0000745 // Once we need to walk the worklist looking for a candidate, cleanup the
746 // worklist of already placed entries.
747 // FIXME: If this shows up on profiles, it could be folded (at the cost of
748 // some code complexity) into the loop below.
749 WorkList.erase(std::remove_if(WorkList.begin(), WorkList.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000750 [&](MachineBasicBlock *BB) {
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000751 return BlockToChain.lookup(BB) == &Chain;
752 }),
Chandler Carruth0af6a0b2011-11-14 09:46:33 +0000753 WorkList.end());
754
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000755 if (WorkList.empty())
756 return nullptr;
757
758 bool IsEHPad = WorkList[0]->isEHPad();
759
Craig Topperc0196b12014-04-14 00:51:57 +0000760 MachineBasicBlock *BestBlock = nullptr;
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000761 BlockFrequency BestFreq;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000762 for (MachineBasicBlock *MBB : WorkList) {
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000763 assert(MBB->isEHPad() == IsEHPad);
764
Chandler Carruth7a715da2015-03-05 03:19:05 +0000765 BlockChain &SuccChain = *BlockToChain[MBB];
Philip Reames02e11322016-03-02 22:40:51 +0000766 if (&SuccChain == &Chain)
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000767 continue;
Junmo Park4ba6cf62016-03-11 05:07:07 +0000768
Philip Reamesae27b232016-03-03 00:58:43 +0000769 assert(SuccChain.UnscheduledPredecessors == 0 && "Found CFG-violating block");
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000770
Chandler Carruth7a715da2015-03-05 03:19:05 +0000771 BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
772 DEBUG(dbgs() << " " << getBlockName(MBB) << " -> ";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000773 MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000774
775 // For ehpad, we layout the least probable first as to avoid jumping back
776 // from least probable landingpads to more probable ones.
777 //
778 // FIXME: Using probability is probably (!) not the best way to achieve
779 // this. We should probably have a more principled approach to layout
780 // cleanup code.
781 //
782 // The goal is to get:
783 //
784 // +--------------------------+
785 // | V
786 // InnerLp -> InnerCleanup OuterLp -> OuterCleanup -> Resume
787 //
788 // Rather than:
789 //
790 // +-------------------------------------+
791 // V |
792 // OuterLp -> OuterCleanup -> Resume InnerLp -> InnerCleanup
793 if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq)))
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000794 continue;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000795
Chandler Carruth7a715da2015-03-05 03:19:05 +0000796 BestBlock = MBB;
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000797 BestFreq = CandidateFreq;
798 }
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000799
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000800 return BestBlock;
801}
802
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000803/// \brief Retrieve the first unplaced basic block.
804///
805/// This routine is called when we are unable to use the CFG to walk through
806/// all of the basic blocks and form a chain due to unnatural loops in the CFG.
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000807/// We walk through the function's blocks in order, starting from the
808/// LastUnplacedBlockIt. We update this iterator on each call to avoid
809/// re-scanning the entire sequence on repeated calls to this routine.
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000810MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
Xinliang David Li52530a72016-06-13 22:23:44 +0000811 const BlockChain &PlacedChain,
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000812 MachineFunction::iterator &PrevUnplacedBlockIt,
Jakub Staszak90616162011-12-21 23:02:08 +0000813 const BlockFilterSet *BlockFilter) {
Xinliang David Li52530a72016-06-13 22:23:44 +0000814 for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F->end(); I != E;
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000815 ++I) {
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +0000816 if (BlockFilter && !BlockFilter->count(&*I))
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000817 continue;
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +0000818 if (BlockToChain[&*I] != &PlacedChain) {
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000819 PrevUnplacedBlockIt = I;
Chandler Carruth4a87aa02011-11-23 03:03:21 +0000820 // Now select the head of the chain to which the unplaced block belongs
821 // as the block to place. This will force the entire chain to be placed,
822 // and satisfies the requirements of merging chains.
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +0000823 return *BlockToChain[&*I]->begin();
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000824 }
825 }
Craig Topperc0196b12014-04-14 00:51:57 +0000826 return nullptr;
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000827}
828
Amaury Secheteae09c22016-03-14 21:24:11 +0000829void MachineBlockPlacement::fillWorkLists(
830 MachineBasicBlock *MBB,
831 SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
Amaury Secheteae09c22016-03-14 21:24:11 +0000832 const BlockFilterSet *BlockFilter = nullptr) {
833 BlockChain &Chain = *BlockToChain[MBB];
834 if (!UpdatedPreds.insert(&Chain).second)
835 return;
836
837 assert(Chain.UnscheduledPredecessors == 0);
838 for (MachineBasicBlock *ChainBB : Chain) {
839 assert(BlockToChain[ChainBB] == &Chain);
840 for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
841 if (BlockFilter && !BlockFilter->count(Pred))
842 continue;
843 if (BlockToChain[Pred] == &Chain)
844 continue;
845 ++Chain.UnscheduledPredecessors;
846 }
847 }
848
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000849 if (Chain.UnscheduledPredecessors != 0)
850 return;
851
852 MBB = *Chain.begin();
853 if (MBB->isEHPad())
854 EHPadWorkList.push_back(MBB);
855 else
856 BlockWorkList.push_back(MBB);
Amaury Secheteae09c22016-03-14 21:24:11 +0000857}
858
Chandler Carruth8d150782011-11-13 11:20:44 +0000859void MachineBlockPlacement::buildChain(
Daniel Jasper471e8562015-03-04 11:05:34 +0000860 MachineBasicBlock *BB, BlockChain &Chain,
Jakub Staszak90616162011-12-21 23:02:08 +0000861 const BlockFilterSet *BlockFilter) {
Kyle Buttb3875ea2016-06-17 22:40:19 +0000862 assert(BB && "BB must not be null.\n");
863 assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match.\n");
Xinliang David Li52530a72016-06-13 22:23:44 +0000864 MachineFunction::iterator PrevUnplacedBlockIt = F->begin();
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000865
Chandler Carruth8d150782011-11-13 11:20:44 +0000866 MachineBasicBlock *LoopHeaderBB = BB;
Xinliang David Li93926ac2016-07-01 05:46:48 +0000867 markChainSuccessors(Chain, LoopHeaderBB, BlockFilter);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000868 BB = *std::prev(Chain.end());
Chandler Carruth8d150782011-11-13 11:20:44 +0000869 for (;;) {
Kyle Butt82c22902016-06-28 22:50:54 +0000870 assert(BB && "null block found at end of chain in loop.");
871 assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match in loop.");
872 assert(*std::prev(Chain.end()) == BB && "BB Not found at end of chain.");
873
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000874
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +0000875 // Look for the best viable successor if there is one to place immediately
876 // after this block.
Duncan Sands291d47e2012-09-14 09:00:11 +0000877 MachineBasicBlock *BestSucc = selectBestSuccessor(BB, Chain, BlockFilter);
Chandler Carruth8d150782011-11-13 11:20:44 +0000878
879 // If an immediate successor isn't available, look for the best viable
880 // block among those we've identified as not violating the loop's CFG at
881 // this point. This won't be a fallthrough, but it will increase locality.
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000882 if (!BestSucc)
Amaury Sechet9ee4ddd2016-04-07 06:34:47 +0000883 BestSucc = selectBestCandidateBlock(Chain, BlockWorkList);
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000884 if (!BestSucc)
885 BestSucc = selectBestCandidateBlock(Chain, EHPadWorkList);
Chandler Carruth8d150782011-11-13 11:20:44 +0000886
Chandler Carruth8d150782011-11-13 11:20:44 +0000887 if (!BestSucc) {
Xinliang David Li52530a72016-06-13 22:23:44 +0000888 BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockIt, BlockFilter);
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000889 if (!BestSucc)
890 break;
891
892 DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
893 "layout successor until the CFG reduces\n");
Chandler Carruth8d150782011-11-13 11:20:44 +0000894 }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000895
Chandler Carruth8d150782011-11-13 11:20:44 +0000896 // Place this block, updating the datastructures to reflect its placement.
Jakub Staszak90616162011-12-21 23:02:08 +0000897 BlockChain &SuccChain = *BlockToChain[BestSucc];
Philip Reamesae27b232016-03-03 00:58:43 +0000898 // Zero out UnscheduledPredecessors for the successor we're about to merge in case
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000899 // we selected a successor that didn't fit naturally into the CFG.
Philip Reamesae27b232016-03-03 00:58:43 +0000900 SuccChain.UnscheduledPredecessors = 0;
Philip Reamesb9688f42016-03-02 21:45:13 +0000901 DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to "
902 << getBlockName(BestSucc) << "\n");
Xinliang David Li93926ac2016-07-01 05:46:48 +0000903 markChainSuccessors(SuccChain, LoopHeaderBB, BlockFilter);
Chandler Carruth8d150782011-11-13 11:20:44 +0000904 Chain.merge(BestSucc, &SuccChain);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000905 BB = *std::prev(Chain.end());
Jakub Staszak190c7122011-12-07 19:46:10 +0000906 }
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000907
908 DEBUG(dbgs() << "Finished forming chain for header block "
Philip Reamesb9688f42016-03-02 21:45:13 +0000909 << getBlockName(*Chain.begin()) << "\n");
Chandler Carruth10281422011-10-21 06:46:38 +0000910}
911
Chandler Carruth03adbd42011-11-27 13:34:33 +0000912/// \brief Find the best loop top block for layout.
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000913///
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000914/// Look for a block which is strictly better than the loop header for laying
915/// out at the top of the loop. This looks for one and only one pattern:
916/// a latch block with no conditional exit. This block will cause a conditional
917/// jump around it or will be the bottom of the loop if we lay it out in place,
918/// but if it it doesn't end up at the bottom of the loop for any reason,
919/// rotation alone won't fix it. Because such a block will always result in an
920/// unconditional jump (for the backedge) rotating it in front of the loop
921/// header is always profitable.
922MachineBasicBlock *
923MachineBlockPlacement::findBestLoopTop(MachineLoop &L,
924 const BlockFilterSet &LoopBlockSet) {
925 // Check that the header hasn't been fused with a preheader block due to
926 // crazy branches. If it has, we need to start with the header at the top to
927 // prevent pulling the preheader into the loop body.
928 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
929 if (!LoopBlockSet.count(*HeaderChain.begin()))
930 return L.getHeader();
931
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000932 DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(L.getHeader())
933 << "\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000934
935 BlockFrequency BestPredFreq;
Craig Topperc0196b12014-04-14 00:51:57 +0000936 MachineBasicBlock *BestPred = nullptr;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000937 for (MachineBasicBlock *Pred : L.getHeader()->predecessors()) {
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000938 if (!LoopBlockSet.count(Pred))
939 continue;
940 DEBUG(dbgs() << " header pred: " << getBlockName(Pred) << ", "
Michael Gottesmanb78dec82013-12-14 00:25:45 +0000941 << Pred->succ_size() << " successors, ";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000942 MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000943 if (Pred->succ_size() > 1)
944 continue;
945
946 BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
947 if (!BestPred || PredFreq > BestPredFreq ||
948 (!(PredFreq < BestPredFreq) &&
949 Pred->isLayoutSuccessor(L.getHeader()))) {
950 BestPred = Pred;
951 BestPredFreq = PredFreq;
952 }
953 }
954
955 // If no direct predecessor is fine, just use the loop header.
Philip Reamesb9688f42016-03-02 21:45:13 +0000956 if (!BestPred) {
957 DEBUG(dbgs() << " final top unchanged\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000958 return L.getHeader();
Philip Reamesb9688f42016-03-02 21:45:13 +0000959 }
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000960
961 // Walk backwards through any straight line of predecessors.
962 while (BestPred->pred_size() == 1 &&
963 (*BestPred->pred_begin())->succ_size() == 1 &&
964 *BestPred->pred_begin() != L.getHeader())
965 BestPred = *BestPred->pred_begin();
966
967 DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n");
968 return BestPred;
969}
970
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000971/// \brief Find the best loop exiting block for layout.
972///
Chandler Carruth03adbd42011-11-27 13:34:33 +0000973/// This routine implements the logic to analyze the loop looking for the best
974/// block to layout at the top of the loop. Typically this is done to maximize
975/// fallthrough opportunities.
976MachineBasicBlock *
Xinliang David Li52530a72016-06-13 22:23:44 +0000977MachineBlockPlacement::findBestLoopExit(MachineLoop &L,
Chandler Carruthccc7e422012-04-16 01:12:56 +0000978 const BlockFilterSet &LoopBlockSet) {
Chandler Carruth68062612012-04-10 13:35:57 +0000979 // We don't want to layout the loop linearly in all cases. If the loop header
980 // is just a normal basic block in the loop, we want to look for what block
981 // within the loop is the best one to layout at the top. However, if the loop
982 // header has be pre-merged into a chain due to predecessors not having
983 // analyzable branches, *and* the predecessor it is merged with is *not* part
984 // of the loop, rotating the header into the middle of the loop will create
985 // a non-contiguous range of blocks which is Very Bad. So start with the
986 // header and only rotate if safe.
987 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
988 if (!LoopBlockSet.count(*HeaderChain.begin()))
Craig Topperc0196b12014-04-14 00:51:57 +0000989 return nullptr;
Chandler Carruth68062612012-04-10 13:35:57 +0000990
Chandler Carruth03adbd42011-11-27 13:34:33 +0000991 BlockFrequency BestExitEdgeFreq;
Chandler Carruthccc7e422012-04-16 01:12:56 +0000992 unsigned BestExitLoopDepth = 0;
Craig Topperc0196b12014-04-14 00:51:57 +0000993 MachineBasicBlock *ExitingBB = nullptr;
Chandler Carruth4f567202011-11-27 20:18:00 +0000994 // If there are exits to outer loops, loop rotation can severely limit
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000995 // fallthrough opportunities unless it selects such an exit. Keep a set of
Chandler Carruth4f567202011-11-27 20:18:00 +0000996 // blocks where rotating to exit with that block will reach an outer loop.
997 SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
998
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000999 DEBUG(dbgs() << "Finding best loop exit for: " << getBlockName(L.getHeader())
1000 << "\n");
Chandler Carruth7a715da2015-03-05 03:19:05 +00001001 for (MachineBasicBlock *MBB : L.getBlocks()) {
1002 BlockChain &Chain = *BlockToChain[MBB];
Chandler Carruth03adbd42011-11-27 13:34:33 +00001003 // Ensure that this block is at the end of a chain; otherwise it could be
Chandler Carruth9a512a42015-04-15 13:19:54 +00001004 // mid-way through an inner loop or a successor of an unanalyzable branch.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001005 if (MBB != *std::prev(Chain.end()))
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001006 continue;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001007
Chandler Carruth03adbd42011-11-27 13:34:33 +00001008 // Now walk the successors. We need to establish whether this has a viable
1009 // exiting successor and whether it has a viable non-exiting successor.
1010 // We store the old exiting state and restore it if a viable looping
1011 // successor isn't found.
1012 MachineBasicBlock *OldExitingBB = ExitingBB;
1013 BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
Chandler Carruthccc7e422012-04-16 01:12:56 +00001014 bool HasLoopingSucc = false;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001015 for (MachineBasicBlock *Succ : MBB->successors()) {
Reid Kleckner0e288232015-08-27 23:27:47 +00001016 if (Succ->isEHPad())
Chandler Carruth03adbd42011-11-27 13:34:33 +00001017 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001018 if (Succ == MBB)
Chandler Carruth03adbd42011-11-27 13:34:33 +00001019 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001020 BlockChain &SuccChain = *BlockToChain[Succ];
Chandler Carruth03adbd42011-11-27 13:34:33 +00001021 // Don't split chains, either this chain or the successor's chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +00001022 if (&Chain == &SuccChain) {
Chandler Carruth7a715da2015-03-05 03:19:05 +00001023 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
1024 << getBlockName(Succ) << " (chain conflict)\n");
Chandler Carruth03adbd42011-11-27 13:34:33 +00001025 continue;
1026 }
1027
Cong Houd97c1002015-12-01 05:29:22 +00001028 auto SuccProb = MBPI->getEdgeProbability(MBB, Succ);
Chandler Carruth7a715da2015-03-05 03:19:05 +00001029 if (LoopBlockSet.count(Succ)) {
1030 DEBUG(dbgs() << " looping: " << getBlockName(MBB) << " -> "
Cong Houd97c1002015-12-01 05:29:22 +00001031 << getBlockName(Succ) << " (" << SuccProb << ")\n");
Chandler Carruthccc7e422012-04-16 01:12:56 +00001032 HasLoopingSucc = true;
Chandler Carruth03adbd42011-11-27 13:34:33 +00001033 continue;
1034 }
1035
Chandler Carruthccc7e422012-04-16 01:12:56 +00001036 unsigned SuccLoopDepth = 0;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001037 if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
Chandler Carruthccc7e422012-04-16 01:12:56 +00001038 SuccLoopDepth = ExitLoop->getLoopDepth();
1039 if (ExitLoop->contains(&L))
Chandler Carruth7a715da2015-03-05 03:19:05 +00001040 BlocksExitingToOuterLoop.insert(MBB);
Chandler Carruthccc7e422012-04-16 01:12:56 +00001041 }
1042
Chandler Carruth7a715da2015-03-05 03:19:05 +00001043 BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
1044 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
1045 << getBlockName(Succ) << " [L:" << SuccLoopDepth << "] (";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001046 MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
Benjamin Kramerc8160d62013-11-20 19:08:44 +00001047 // Note that we bias this toward an existing layout successor to retain
1048 // incoming order in the absence of better information. The exit must have
1049 // a frequency higher than the current exit before we consider breaking
1050 // the layout.
1051 BranchProbability Bias(100 - ExitBlockBias, 100);
Chandler Carruth26d30172015-04-15 13:39:42 +00001052 if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
Chandler Carruthccc7e422012-04-16 01:12:56 +00001053 ExitEdgeFreq > BestExitEdgeFreq ||
Chandler Carruth7a715da2015-03-05 03:19:05 +00001054 (MBB->isLayoutSuccessor(Succ) &&
Benjamin Kramerc8160d62013-11-20 19:08:44 +00001055 !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
Chandler Carruth03adbd42011-11-27 13:34:33 +00001056 BestExitEdgeFreq = ExitEdgeFreq;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001057 ExitingBB = MBB;
Chandler Carrutha0545802011-11-27 09:22:53 +00001058 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001059 }
Chandler Carruth03adbd42011-11-27 13:34:33 +00001060
Chandler Carruthccc7e422012-04-16 01:12:56 +00001061 if (!HasLoopingSucc) {
Chandler Carruthcfb2b9d2015-04-15 13:26:41 +00001062 // Restore the old exiting state, no viable looping successor was found.
Chandler Carruth03adbd42011-11-27 13:34:33 +00001063 ExitingBB = OldExitingBB;
1064 BestExitEdgeFreq = OldBestExitEdgeFreq;
Chandler Carruth03adbd42011-11-27 13:34:33 +00001065 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001066 }
Chandler Carruthccc7e422012-04-16 01:12:56 +00001067 // Without a candidate exiting block or with only a single block in the
Chandler Carruth03adbd42011-11-27 13:34:33 +00001068 // loop, just use the loop header to layout the loop.
1069 if (!ExitingBB || L.getNumBlocks() == 1)
Craig Topperc0196b12014-04-14 00:51:57 +00001070 return nullptr;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001071
Chandler Carruth4f567202011-11-27 20:18:00 +00001072 // Also, if we have exit blocks which lead to outer loops but didn't select
1073 // one of them as the exiting block we are rotating toward, disable loop
1074 // rotation altogether.
1075 if (!BlocksExitingToOuterLoop.empty() &&
1076 !BlocksExitingToOuterLoop.count(ExitingBB))
Craig Topperc0196b12014-04-14 00:51:57 +00001077 return nullptr;
Chandler Carruth4f567202011-11-27 20:18:00 +00001078
Chandler Carruth03adbd42011-11-27 13:34:33 +00001079 DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB) << "\n");
Chandler Carruthccc7e422012-04-16 01:12:56 +00001080 return ExitingBB;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001081}
1082
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001083/// \brief Attempt to rotate an exiting block to the bottom of the loop.
1084///
1085/// Once we have built a chain, try to rotate it to line up the hot exit block
1086/// with fallthrough out of the loop if doing so doesn't introduce unnecessary
1087/// branches. For example, if the loop has fallthrough into its header and out
1088/// of its bottom already, don't rotate it.
1089void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
1090 MachineBasicBlock *ExitingBB,
1091 const BlockFilterSet &LoopBlockSet) {
1092 if (!ExitingBB)
1093 return;
1094
1095 MachineBasicBlock *Top = *LoopChain.begin();
1096 bool ViableTopFallthrough = false;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001097 for (MachineBasicBlock *Pred : Top->predecessors()) {
1098 BlockChain *PredChain = BlockToChain[Pred];
1099 if (!LoopBlockSet.count(Pred) &&
1100 (!PredChain || Pred == *std::prev(PredChain->end()))) {
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001101 ViableTopFallthrough = true;
1102 break;
1103 }
1104 }
1105
1106 // If the header has viable fallthrough, check whether the current loop
1107 // bottom is a viable exiting block. If so, bail out as rotating will
1108 // introduce an unnecessary branch.
1109 if (ViableTopFallthrough) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001110 MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
Chandler Carruth7a715da2015-03-05 03:19:05 +00001111 for (MachineBasicBlock *Succ : Bottom->successors()) {
1112 BlockChain *SuccChain = BlockToChain[Succ];
1113 if (!LoopBlockSet.count(Succ) &&
1114 (!SuccChain || Succ == *SuccChain->begin()))
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001115 return;
1116 }
1117 }
1118
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001119 BlockChain::iterator ExitIt =
1120 std::find(LoopChain.begin(), LoopChain.end(), ExitingBB);
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001121 if (ExitIt == LoopChain.end())
1122 return;
1123
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001124 std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001125}
1126
Cong Hou7745dbc2015-10-19 23:16:40 +00001127/// \brief Attempt to rotate a loop based on profile data to reduce branch cost.
1128///
1129/// With profile data, we can determine the cost in terms of missed fall through
1130/// opportunities when rotating a loop chain and select the best rotation.
1131/// Basically, there are three kinds of cost to consider for each rotation:
1132/// 1. The possibly missed fall through edge (if it exists) from BB out of
1133/// the loop to the loop header.
1134/// 2. The possibly missed fall through edges (if they exist) from the loop
1135/// exits to BB out of the loop.
1136/// 3. The missed fall through edge (if it exists) from the last BB to the
1137/// first BB in the loop chain.
1138/// Therefore, the cost for a given rotation is the sum of costs listed above.
1139/// We select the best rotation with the smallest cost.
1140void MachineBlockPlacement::rotateLoopWithProfile(
1141 BlockChain &LoopChain, MachineLoop &L, const BlockFilterSet &LoopBlockSet) {
1142 auto HeaderBB = L.getHeader();
1143 auto HeaderIter = std::find(LoopChain.begin(), LoopChain.end(), HeaderBB);
1144 auto RotationPos = LoopChain.end();
1145
1146 BlockFrequency SmallestRotationCost = BlockFrequency::getMaxFrequency();
1147
1148 // A utility lambda that scales up a block frequency by dividing it by a
1149 // branch probability which is the reciprocal of the scale.
1150 auto ScaleBlockFrequency = [](BlockFrequency Freq,
1151 unsigned Scale) -> BlockFrequency {
1152 if (Scale == 0)
1153 return 0;
1154 // Use operator / between BlockFrequency and BranchProbability to implement
1155 // saturating multiplication.
1156 return Freq / BranchProbability(1, Scale);
1157 };
1158
1159 // Compute the cost of the missed fall-through edge to the loop header if the
1160 // chain head is not the loop header. As we only consider natural loops with
1161 // single header, this computation can be done only once.
1162 BlockFrequency HeaderFallThroughCost(0);
1163 for (auto *Pred : HeaderBB->predecessors()) {
1164 BlockChain *PredChain = BlockToChain[Pred];
1165 if (!LoopBlockSet.count(Pred) &&
1166 (!PredChain || Pred == *std::prev(PredChain->end()))) {
1167 auto EdgeFreq =
1168 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, HeaderBB);
1169 auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost);
1170 // If the predecessor has only an unconditional jump to the header, we
1171 // need to consider the cost of this jump.
1172 if (Pred->succ_size() == 1)
1173 FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost);
1174 HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost);
1175 }
1176 }
1177
1178 // Here we collect all exit blocks in the loop, and for each exit we find out
1179 // its hottest exit edge. For each loop rotation, we define the loop exit cost
1180 // as the sum of frequencies of exit edges we collect here, excluding the exit
1181 // edge from the tail of the loop chain.
1182 SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq;
1183 for (auto BB : LoopChain) {
Cong Houd97c1002015-12-01 05:29:22 +00001184 auto LargestExitEdgeProb = BranchProbability::getZero();
Cong Hou7745dbc2015-10-19 23:16:40 +00001185 for (auto *Succ : BB->successors()) {
1186 BlockChain *SuccChain = BlockToChain[Succ];
1187 if (!LoopBlockSet.count(Succ) &&
1188 (!SuccChain || Succ == *SuccChain->begin())) {
Cong Houd97c1002015-12-01 05:29:22 +00001189 auto SuccProb = MBPI->getEdgeProbability(BB, Succ);
1190 LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb);
Cong Hou7745dbc2015-10-19 23:16:40 +00001191 }
1192 }
Cong Houd97c1002015-12-01 05:29:22 +00001193 if (LargestExitEdgeProb > BranchProbability::getZero()) {
1194 auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb;
Cong Hou7745dbc2015-10-19 23:16:40 +00001195 ExitsWithFreq.emplace_back(BB, ExitFreq);
1196 }
1197 }
1198
1199 // In this loop we iterate every block in the loop chain and calculate the
1200 // cost assuming the block is the head of the loop chain. When the loop ends,
1201 // we should have found the best candidate as the loop chain's head.
1202 for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()),
1203 EndIter = LoopChain.end();
1204 Iter != EndIter; Iter++, TailIter++) {
1205 // TailIter is used to track the tail of the loop chain if the block we are
1206 // checking (pointed by Iter) is the head of the chain.
1207 if (TailIter == LoopChain.end())
1208 TailIter = LoopChain.begin();
1209
1210 auto TailBB = *TailIter;
1211
1212 // Calculate the cost by putting this BB to the top.
1213 BlockFrequency Cost = 0;
1214
1215 // If the current BB is the loop header, we need to take into account the
1216 // cost of the missed fall through edge from outside of the loop to the
1217 // header.
1218 if (Iter != HeaderIter)
1219 Cost += HeaderFallThroughCost;
1220
1221 // Collect the loop exit cost by summing up frequencies of all exit edges
1222 // except the one from the chain tail.
1223 for (auto &ExitWithFreq : ExitsWithFreq)
1224 if (TailBB != ExitWithFreq.first)
1225 Cost += ExitWithFreq.second;
1226
1227 // The cost of breaking the once fall-through edge from the tail to the top
1228 // of the loop chain. Here we need to consider three cases:
1229 // 1. If the tail node has only one successor, then we will get an
1230 // additional jmp instruction. So the cost here is (MisfetchCost +
1231 // JumpInstCost) * tail node frequency.
1232 // 2. If the tail node has two successors, then we may still get an
1233 // additional jmp instruction if the layout successor after the loop
1234 // chain is not its CFG successor. Note that the more frequently executed
1235 // jmp instruction will be put ahead of the other one. Assume the
1236 // frequency of those two branches are x and y, where x is the frequency
1237 // of the edge to the chain head, then the cost will be
1238 // (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency.
1239 // 3. If the tail node has more than two successors (this rarely happens),
1240 // we won't consider any additional cost.
1241 if (TailBB->isSuccessor(*Iter)) {
1242 auto TailBBFreq = MBFI->getBlockFreq(TailBB);
1243 if (TailBB->succ_size() == 1)
1244 Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(),
1245 MisfetchCost + JumpInstCost);
1246 else if (TailBB->succ_size() == 2) {
1247 auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter);
1248 auto TailToHeadFreq = TailBBFreq * TailToHeadProb;
1249 auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2)
1250 ? TailBBFreq * TailToHeadProb.getCompl()
1251 : TailToHeadFreq;
1252 Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) +
1253 ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost);
1254 }
1255 }
1256
Philip Reamesb9688f42016-03-02 21:45:13 +00001257 DEBUG(dbgs() << "The cost of loop rotation by making " << getBlockName(*Iter)
Cong Hou7745dbc2015-10-19 23:16:40 +00001258 << " to the top: " << Cost.getFrequency() << "\n");
1259
1260 if (Cost < SmallestRotationCost) {
1261 SmallestRotationCost = Cost;
1262 RotationPos = Iter;
1263 }
1264 }
1265
1266 if (RotationPos != LoopChain.end()) {
Philip Reamesb9688f42016-03-02 21:45:13 +00001267 DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos)
Cong Hou7745dbc2015-10-19 23:16:40 +00001268 << " to the top\n");
1269 std::rotate(LoopChain.begin(), RotationPos, LoopChain.end());
1270 }
1271}
1272
Cong Houb90b9e02015-11-02 21:24:00 +00001273/// \brief Collect blocks in the given loop that are to be placed.
1274///
1275/// When profile data is available, exclude cold blocks from the returned set;
1276/// otherwise, collect all blocks in the loop.
1277MachineBlockPlacement::BlockFilterSet
Xinliang David Li52530a72016-06-13 22:23:44 +00001278MachineBlockPlacement::collectLoopBlockSet(MachineLoop &L) {
Cong Houb90b9e02015-11-02 21:24:00 +00001279 BlockFilterSet LoopBlockSet;
1280
1281 // Filter cold blocks off from LoopBlockSet when profile data is available.
1282 // Collect the sum of frequencies of incoming edges to the loop header from
1283 // outside. If we treat the loop as a super block, this is the frequency of
1284 // the loop. Then for each block in the loop, we calculate the ratio between
1285 // its frequency and the frequency of the loop block. When it is too small,
1286 // don't add it to the loop chain. If there are outer loops, then this block
1287 // will be merged into the first outer loop chain for which this block is not
1288 // cold anymore. This needs precise profile data and we only do this when
1289 // profile data is available.
Xinliang David Li52530a72016-06-13 22:23:44 +00001290 if (F->getFunction()->getEntryCount()) {
Cong Houb90b9e02015-11-02 21:24:00 +00001291 BlockFrequency LoopFreq(0);
1292 for (auto LoopPred : L.getHeader()->predecessors())
1293 if (!L.contains(LoopPred))
1294 LoopFreq += MBFI->getBlockFreq(LoopPred) *
1295 MBPI->getEdgeProbability(LoopPred, L.getHeader());
1296
1297 for (MachineBasicBlock *LoopBB : L.getBlocks()) {
1298 auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency();
1299 if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio)
1300 continue;
1301 LoopBlockSet.insert(LoopBB);
1302 }
1303 } else
1304 LoopBlockSet.insert(L.block_begin(), L.block_end());
1305
1306 return LoopBlockSet;
1307}
1308
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001309/// \brief Forms basic block chains from the natural loop structures.
Chandler Carruth10281422011-10-21 06:46:38 +00001310///
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001311/// These chains are designed to preserve the existing *structure* of the code
1312/// as much as possible. We can then stitch the chains together in a way which
1313/// both preserves the topological structure and minimizes taken conditional
1314/// branches.
Xinliang David Li52530a72016-06-13 22:23:44 +00001315void MachineBlockPlacement::buildLoopChains(MachineLoop &L) {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001316 // First recurse through any nested loops, building chains for those inner
1317 // loops.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001318 for (MachineLoop *InnerLoop : L)
Xinliang David Li52530a72016-06-13 22:23:44 +00001319 buildLoopChains(*InnerLoop);
Chandler Carruth10281422011-10-21 06:46:38 +00001320
Xinliang David Li93926ac2016-07-01 05:46:48 +00001321 assert(BlockWorkList.empty());
1322 assert(EHPadWorkList.empty());
Xinliang David Li52530a72016-06-13 22:23:44 +00001323 BlockFilterSet LoopBlockSet = collectLoopBlockSet(L);
Chandler Carruth03adbd42011-11-27 13:34:33 +00001324
Cong Hou7745dbc2015-10-19 23:16:40 +00001325 // Check if we have profile data for this function. If yes, we will rotate
1326 // this loop by modeling costs more precisely which requires the profile data
1327 // for better layout.
1328 bool RotateLoopWithProfile =
Xinliang David Lif0ab6df2016-05-12 02:04:41 +00001329 ForcePreciseRotationCost ||
Xinliang David Li52530a72016-06-13 22:23:44 +00001330 (PreciseRotationCost && F->getFunction()->getEntryCount());
Cong Hou7745dbc2015-10-19 23:16:40 +00001331
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001332 // First check to see if there is an obviously preferable top block for the
1333 // loop. This will default to the header, but may end up as one of the
1334 // predecessors to the header if there is one which will result in strictly
1335 // fewer branches in the loop body.
Cong Hou7745dbc2015-10-19 23:16:40 +00001336 // When we use profile data to rotate the loop, this is unnecessary.
1337 MachineBasicBlock *LoopTop =
1338 RotateLoopWithProfile ? L.getHeader() : findBestLoopTop(L, LoopBlockSet);
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001339
1340 // If we selected just the header for the loop top, look for a potentially
1341 // profitable exit block in the event that rotating the loop can eliminate
1342 // branches by placing an exit edge at the bottom.
Craig Topperc0196b12014-04-14 00:51:57 +00001343 MachineBasicBlock *ExitingBB = nullptr;
Cong Hou7745dbc2015-10-19 23:16:40 +00001344 if (!RotateLoopWithProfile && LoopTop == L.getHeader())
Xinliang David Li52530a72016-06-13 22:23:44 +00001345 ExitingBB = findBestLoopExit(L, LoopBlockSet);
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001346
1347 BlockChain &LoopChain = *BlockToChain[LoopTop];
Chandler Carruth10281422011-10-21 06:46:38 +00001348
Chandler Carruth8d150782011-11-13 11:20:44 +00001349 // FIXME: This is a really lame way of walking the chains in the loop: we
1350 // walk the blocks, and use a set to prevent visiting a particular chain
1351 // twice.
Jakub Staszak90616162011-12-21 23:02:08 +00001352 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
Philip Reamesae27b232016-03-03 00:58:43 +00001353 assert(LoopChain.UnscheduledPredecessors == 0);
Jakub Staszak190c7122011-12-07 19:46:10 +00001354 UpdatedPreds.insert(&LoopChain);
Cong Houb90b9e02015-11-02 21:24:00 +00001355
Amaury Secheteae09c22016-03-14 21:24:11 +00001356 for (MachineBasicBlock *LoopBB : LoopBlockSet)
Xinliang David Li93926ac2016-07-01 05:46:48 +00001357 fillWorkLists(LoopBB, UpdatedPreds, &LoopBlockSet);
Chandler Carruth8d150782011-11-13 11:20:44 +00001358
Xinliang David Li93926ac2016-07-01 05:46:48 +00001359 buildChain(LoopTop, LoopChain, &LoopBlockSet);
Cong Hou7745dbc2015-10-19 23:16:40 +00001360
1361 if (RotateLoopWithProfile)
1362 rotateLoopWithProfile(LoopChain, L, LoopBlockSet);
1363 else
1364 rotateLoop(LoopChain, ExitingBB, LoopBlockSet);
Chandler Carruth8d150782011-11-13 11:20:44 +00001365
1366 DEBUG({
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001367 // Crash at the end so we get all of the debugging output first.
1368 bool BadLoop = false;
Philip Reamesae27b232016-03-03 00:58:43 +00001369 if (LoopChain.UnscheduledPredecessors) {
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001370 BadLoop = true;
Chandler Carruth8d150782011-11-13 11:20:44 +00001371 dbgs() << "Loop chain contains a block without its preds placed!\n"
1372 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
1373 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001374 }
Chandler Carruth7a715da2015-03-05 03:19:05 +00001375 for (MachineBasicBlock *ChainBB : LoopChain) {
1376 dbgs() << " ... " << getBlockName(ChainBB) << "\n";
1377 if (!LoopBlockSet.erase(ChainBB)) {
Chandler Carruth0a31d142011-11-14 10:55:53 +00001378 // We don't mark the loop as bad here because there are real situations
1379 // where this can occur. For example, with an unanalyzable fallthrough
Chandler Carruth99fe42f2011-11-23 10:35:36 +00001380 // from a loop block to a non-loop block or vice versa.
Chandler Carruth8d150782011-11-13 11:20:44 +00001381 dbgs() << "Loop chain contains a block not contained by the loop!\n"
1382 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
1383 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00001384 << " Bad block: " << getBlockName(ChainBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001385 }
Chandler Carruthccc7e422012-04-16 01:12:56 +00001386 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001387
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001388 if (!LoopBlockSet.empty()) {
1389 BadLoop = true;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001390 for (MachineBasicBlock *LoopBB : LoopBlockSet)
Chandler Carruth8d150782011-11-13 11:20:44 +00001391 dbgs() << "Loop contains blocks never placed into a chain!\n"
1392 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
1393 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00001394 << " Bad block: " << getBlockName(LoopBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001395 }
1396 assert(!BadLoop && "Detected problems with the placement of this loop.");
Chandler Carruth8d150782011-11-13 11:20:44 +00001397 });
Xinliang David Li93926ac2016-07-01 05:46:48 +00001398
1399 BlockWorkList.clear();
1400 EHPadWorkList.clear();
Chandler Carruth10281422011-10-21 06:46:38 +00001401}
1402
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001403/// When OutlineOpitonalBranches is on, this method collects BBs that
Xinliang David Li071d0f12016-06-12 16:54:03 +00001404/// dominates all terminator blocks of the function \p F.
Xinliang David Li52530a72016-06-13 22:23:44 +00001405void MachineBlockPlacement::collectMustExecuteBBs() {
Xinliang David Li071d0f12016-06-12 16:54:03 +00001406 if (OutlineOptionalBranches) {
1407 // Find the nearest common dominator of all of F's terminators.
1408 MachineBasicBlock *Terminator = nullptr;
Xinliang David Li52530a72016-06-13 22:23:44 +00001409 for (MachineBasicBlock &MBB : *F) {
Xinliang David Li071d0f12016-06-12 16:54:03 +00001410 if (MBB.succ_size() == 0) {
1411 if (Terminator == nullptr)
1412 Terminator = &MBB;
1413 else
1414 Terminator = MDT->findNearestCommonDominator(Terminator, &MBB);
1415 }
1416 }
1417
1418 // MBBs dominating this common dominator are unavoidable.
1419 UnavoidableBlocks.clear();
Xinliang David Li52530a72016-06-13 22:23:44 +00001420 for (MachineBasicBlock &MBB : *F) {
Xinliang David Li071d0f12016-06-12 16:54:03 +00001421 if (MDT->dominates(&MBB, Terminator)) {
1422 UnavoidableBlocks.insert(&MBB);
1423 }
1424 }
1425 }
1426}
1427
Xinliang David Li52530a72016-06-13 22:23:44 +00001428void MachineBlockPlacement::buildCFGChains() {
Chandler Carruth8d150782011-11-13 11:20:44 +00001429 // Ensure that every BB in the function has an associated chain to simplify
1430 // the assumptions of the remaining algorithm.
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001431 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
Xinliang David Li52530a72016-06-13 22:23:44 +00001432 for (MachineFunction::iterator FI = F->begin(), FE = F->end(); FI != FE;
1433 ++FI) {
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001434 MachineBasicBlock *BB = &*FI;
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001435 BlockChain *Chain =
1436 new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001437 // Also, merge any blocks which we cannot reason about and must preserve
1438 // the exact fallthrough behavior for.
1439 for (;;) {
1440 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001441 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Jacques Pienaar71c30a12016-07-15 14:41:04 +00001442 if (!TII->analyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001443 break;
1444
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001445 MachineFunction::iterator NextFI = std::next(FI);
1446 MachineBasicBlock *NextBB = &*NextFI;
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001447 // Ensure that the layout successor is a viable block, as we know that
1448 // fallthrough is a possibility.
1449 assert(NextFI != FE && "Can't fallthrough past the last block.");
1450 DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
1451 << getBlockName(BB) << " -> " << getBlockName(NextBB)
1452 << "\n");
Craig Topperc0196b12014-04-14 00:51:57 +00001453 Chain->merge(NextBB, nullptr);
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001454 FI = NextFI;
1455 BB = NextBB;
1456 }
1457 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001458
Xinliang David Li071d0f12016-06-12 16:54:03 +00001459 // Turned on with OutlineOptionalBranches option
Xinliang David Li52530a72016-06-13 22:23:44 +00001460 collectMustExecuteBBs();
Daniel Jasper471e8562015-03-04 11:05:34 +00001461
Chandler Carruth8d150782011-11-13 11:20:44 +00001462 // Build any loop-based chains.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001463 for (MachineLoop *L : *MLI)
Xinliang David Li52530a72016-06-13 22:23:44 +00001464 buildLoopChains(*L);
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001465
Xinliang David Li93926ac2016-07-01 05:46:48 +00001466 assert(BlockWorkList.empty());
1467 assert(EHPadWorkList.empty());
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001468
Chandler Carruth8d150782011-11-13 11:20:44 +00001469 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
Xinliang David Li52530a72016-06-13 22:23:44 +00001470 for (MachineBasicBlock &MBB : *F)
Xinliang David Li93926ac2016-07-01 05:46:48 +00001471 fillWorkLists(&MBB, UpdatedPreds);
Chandler Carruth8d150782011-11-13 11:20:44 +00001472
Xinliang David Li52530a72016-06-13 22:23:44 +00001473 BlockChain &FunctionChain = *BlockToChain[&F->front()];
Xinliang David Li93926ac2016-07-01 05:46:48 +00001474 buildChain(&F->front(), FunctionChain);
Chandler Carruth8d150782011-11-13 11:20:44 +00001475
Matt Arsenault0f5f0152013-12-10 18:55:37 +00001476#ifndef NDEBUG
Matt Arsenault79d55f52013-12-05 20:02:18 +00001477 typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType;
Matt Arsenault0f5f0152013-12-10 18:55:37 +00001478#endif
Chandler Carruth8d150782011-11-13 11:20:44 +00001479 DEBUG({
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001480 // Crash at the end so we get all of the debugging output first.
1481 bool BadFunc = false;
Chandler Carruth8d150782011-11-13 11:20:44 +00001482 FunctionBlockSetType FunctionBlockSet;
Xinliang David Li52530a72016-06-13 22:23:44 +00001483 for (MachineBasicBlock &MBB : *F)
Chandler Carruth7a715da2015-03-05 03:19:05 +00001484 FunctionBlockSet.insert(&MBB);
Chandler Carruth8d150782011-11-13 11:20:44 +00001485
Chandler Carruth7a715da2015-03-05 03:19:05 +00001486 for (MachineBasicBlock *ChainBB : FunctionChain)
1487 if (!FunctionBlockSet.erase(ChainBB)) {
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001488 BadFunc = true;
Chandler Carruth8d150782011-11-13 11:20:44 +00001489 dbgs() << "Function chain contains a block not in the function!\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00001490 << " Bad block: " << getBlockName(ChainBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001491 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001492
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001493 if (!FunctionBlockSet.empty()) {
1494 BadFunc = true;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001495 for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
Chandler Carruth8d150782011-11-13 11:20:44 +00001496 dbgs() << "Function contains blocks never placed into a chain!\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00001497 << " Bad block: " << getBlockName(RemainingBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001498 }
1499 assert(!BadFunc && "Detected problems with the block placement.");
Chandler Carruth8d150782011-11-13 11:20:44 +00001500 });
1501
1502 // Splice the blocks into place.
Xinliang David Li52530a72016-06-13 22:23:44 +00001503 MachineFunction::iterator InsertPos = F->begin();
Xinliang David Li449cdfd2016-06-24 22:54:21 +00001504 DEBUG(dbgs() << "[MBP] Function: "<< F->getName() << "\n");
Chandler Carruth7a715da2015-03-05 03:19:05 +00001505 for (MachineBasicBlock *ChainBB : FunctionChain) {
1506 DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
1507 : " ... ")
1508 << getBlockName(ChainBB) << "\n");
1509 if (InsertPos != MachineFunction::iterator(ChainBB))
Xinliang David Li52530a72016-06-13 22:23:44 +00001510 F->splice(InsertPos, ChainBB);
Chandler Carruth8d150782011-11-13 11:20:44 +00001511 else
1512 ++InsertPos;
1513
1514 // Update the terminator of the previous block.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001515 if (ChainBB == *FunctionChain.begin())
Chandler Carruth8d150782011-11-13 11:20:44 +00001516 continue;
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001517 MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB));
Chandler Carruth8d150782011-11-13 11:20:44 +00001518
Chandler Carruth10281422011-10-21 06:46:38 +00001519 // FIXME: It would be awesome of updateTerminator would just return rather
1520 // than assert when the branch cannot be analyzed in order to remove this
1521 // boiler plate.
1522 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001523 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001524
Haicheng Wu90a55652016-05-24 22:16:14 +00001525 // The "PrevBB" is not yet updated to reflect current code layout, so,
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001526 // o. it may fall-through to a block without explicit "goto" instruction
Haicheng Wu90a55652016-05-24 22:16:14 +00001527 // before layout, and no longer fall-through it after layout; or
1528 // o. just opposite.
1529 //
Jacques Pienaar71c30a12016-07-15 14:41:04 +00001530 // analyzeBranch() may return erroneous value for FBB when these two
Haicheng Wu90a55652016-05-24 22:16:14 +00001531 // situations take place. For the first scenario FBB is mistakenly set NULL;
1532 // for the 2nd scenario, the FBB, which is expected to be NULL, is
1533 // mistakenly pointing to "*BI".
1534 // Thus, if the future change needs to use FBB before the layout is set, it
1535 // has to correct FBB first by using the code similar to the following:
1536 //
1537 // if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
1538 // PrevBB->updateTerminator();
1539 // Cond.clear();
1540 // TBB = FBB = nullptr;
Jacques Pienaar71c30a12016-07-15 14:41:04 +00001541 // if (TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) {
Haicheng Wu90a55652016-05-24 22:16:14 +00001542 // // FIXME: This should never take place.
1543 // TBB = FBB = nullptr;
1544 // }
1545 // }
Jacques Pienaar71c30a12016-07-15 14:41:04 +00001546 if (!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond))
Haicheng Wu90a55652016-05-24 22:16:14 +00001547 PrevBB->updateTerminator();
Chandler Carruth10281422011-10-21 06:46:38 +00001548 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001549
1550 // Fixup the last block.
1551 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001552 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Jacques Pienaar71c30a12016-07-15 14:41:04 +00001553 if (!TII->analyzeBranch(F->back(), TBB, FBB, Cond))
Xinliang David Li52530a72016-06-13 22:23:44 +00001554 F->back().updateTerminator();
Xinliang David Li93926ac2016-07-01 05:46:48 +00001555
1556 BlockWorkList.clear();
1557 EHPadWorkList.clear();
Haicheng Wu90a55652016-05-24 22:16:14 +00001558}
1559
Xinliang David Li52530a72016-06-13 22:23:44 +00001560void MachineBlockPlacement::optimizeBranches() {
1561 BlockChain &FunctionChain = *BlockToChain[&F->front()];
Haicheng Wu90a55652016-05-24 22:16:14 +00001562 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
Quentin Colombet776e6de2016-05-02 22:58:59 +00001563
1564 // Now that all the basic blocks in the chain have the proper layout,
1565 // make a final call to AnalyzeBranch with AllowModify set.
1566 // Indeed, the target may be able to optimize the branches in a way we
1567 // cannot because all branches may not be analyzable.
1568 // E.g., the target may be able to remove an unconditional branch to
1569 // a fallthrough when it occurs after predicated terminators.
1570 for (MachineBasicBlock *ChainBB : FunctionChain) {
1571 Cond.clear();
Haicheng Wu90a55652016-05-24 22:16:14 +00001572 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Jacques Pienaar71c30a12016-07-15 14:41:04 +00001573 if (!TII->analyzeBranch(*ChainBB, TBB, FBB, Cond, /*AllowModify*/ true)) {
Haicheng Wu90a55652016-05-24 22:16:14 +00001574 // If PrevBB has a two-way branch, try to re-order the branches
1575 // such that we branch to the successor with higher probability first.
1576 if (TBB && !Cond.empty() && FBB &&
1577 MBPI->getEdgeProbability(ChainBB, FBB) >
1578 MBPI->getEdgeProbability(ChainBB, TBB) &&
1579 !TII->ReverseBranchCondition(Cond)) {
1580 DEBUG(dbgs() << "Reverse order of the two branches: "
1581 << getBlockName(ChainBB) << "\n");
1582 DEBUG(dbgs() << " Edge probability: "
1583 << MBPI->getEdgeProbability(ChainBB, FBB) << " vs "
1584 << MBPI->getEdgeProbability(ChainBB, TBB) << "\n");
1585 DebugLoc dl; // FIXME: this is nowhere
1586 TII->RemoveBranch(*ChainBB);
1587 TII->InsertBranch(*ChainBB, FBB, TBB, Cond, dl);
1588 ChainBB->updateTerminator();
1589 }
1590 }
Quentin Colombet776e6de2016-05-02 22:58:59 +00001591 }
Haicheng Wue749ce52016-04-29 17:06:44 +00001592}
Chandler Carruth10281422011-10-21 06:46:38 +00001593
Xinliang David Li52530a72016-06-13 22:23:44 +00001594void MachineBlockPlacement::alignBlocks() {
Chandler Carruthccc7e422012-04-16 01:12:56 +00001595 // Walk through the backedges of the function now that we have fully laid out
1596 // the basic blocks and align the destination of each backedge. We don't rely
Chandler Carruth881d0a72012-08-07 09:45:24 +00001597 // exclusively on the loop info here so that we can align backedges in
1598 // unnatural CFGs and backedges that were introduced purely because of the
1599 // loop rotations done during this layout pass.
Xinliang David Li52530a72016-06-13 22:23:44 +00001600 if (F->getFunction()->optForSize())
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001601 return;
Xinliang David Li52530a72016-06-13 22:23:44 +00001602 BlockChain &FunctionChain = *BlockToChain[&F->front()];
Chandler Carruth881d0a72012-08-07 09:45:24 +00001603 if (FunctionChain.begin() == FunctionChain.end())
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001604 return; // Empty chain.
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001605
Chandler Carruth881d0a72012-08-07 09:45:24 +00001606 const BranchProbability ColdProb(1, 5); // 20%
Xinliang David Li52530a72016-06-13 22:23:44 +00001607 BlockFrequency EntryFreq = MBFI->getBlockFreq(&F->front());
Chandler Carruth881d0a72012-08-07 09:45:24 +00001608 BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001609 for (MachineBasicBlock *ChainBB : FunctionChain) {
1610 if (ChainBB == *FunctionChain.begin())
1611 continue;
1612
Chandler Carruth881d0a72012-08-07 09:45:24 +00001613 // Don't align non-looping basic blocks. These are unlikely to execute
1614 // enough times to matter in practice. Note that we'll still handle
1615 // unnatural CFGs inside of a natural outer loop (the common case) and
1616 // rotated loops.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001617 MachineLoop *L = MLI->getLoopFor(ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001618 if (!L)
1619 continue;
1620
Hal Finkel57725662015-01-03 17:58:24 +00001621 unsigned Align = TLI->getPrefLoopAlignment(L);
1622 if (!Align)
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001623 continue; // Don't care about loop alignment.
Hal Finkel57725662015-01-03 17:58:24 +00001624
Chandler Carruth881d0a72012-08-07 09:45:24 +00001625 // If the block is cold relative to the function entry don't waste space
1626 // aligning it.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001627 BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001628 if (Freq < WeightedEntryFreq)
1629 continue;
1630
1631 // If the block is cold relative to its loop header, don't align it
1632 // regardless of what edges into the block exist.
1633 MachineBasicBlock *LoopHeader = L->getHeader();
1634 BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
1635 if (Freq < (LoopHeaderFreq * ColdProb))
1636 continue;
1637
1638 // Check for the existence of a non-layout predecessor which would benefit
1639 // from aligning this block.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001640 MachineBasicBlock *LayoutPred =
1641 &*std::prev(MachineFunction::iterator(ChainBB));
Chandler Carruth881d0a72012-08-07 09:45:24 +00001642
1643 // Force alignment if all the predecessors are jumps. We already checked
1644 // that the block isn't cold above.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001645 if (!LayoutPred->isSuccessor(ChainBB)) {
1646 ChainBB->setAlignment(Align);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001647 continue;
1648 }
1649
1650 // Align this block if the layout predecessor's edge into this block is
Nadav Rotem6036f582013-03-29 16:34:23 +00001651 // cold relative to the block. When this is true, other predecessors make up
Chandler Carruth881d0a72012-08-07 09:45:24 +00001652 // all of the hot entries into the block and thus alignment is likely to be
1653 // important.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001654 BranchProbability LayoutProb =
1655 MBPI->getEdgeProbability(LayoutPred, ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001656 BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
1657 if (LayoutEdgeFreq <= (Freq * ColdProb))
Chandler Carruth7a715da2015-03-05 03:19:05 +00001658 ChainBB->setAlignment(Align);
Chandler Carruthccc7e422012-04-16 01:12:56 +00001659 }
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001660}
1661
Xinliang David Li52530a72016-06-13 22:23:44 +00001662bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &MF) {
1663 if (skipFunction(*MF.getFunction()))
Andrew Kaylor50271f72016-05-03 22:32:30 +00001664 return false;
1665
Chandler Carruth10281422011-10-21 06:46:38 +00001666 // Check for single-block functions and skip them.
Xinliang David Li52530a72016-06-13 22:23:44 +00001667 if (std::next(MF.begin()) == MF.end())
Chandler Carruth10281422011-10-21 06:46:38 +00001668 return false;
1669
Xinliang David Li52530a72016-06-13 22:23:44 +00001670 F = &MF;
Chandler Carruth10281422011-10-21 06:46:38 +00001671 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
Haicheng Wu5b458cc2016-06-09 15:24:29 +00001672 MBFI = llvm::make_unique<BranchFolder::MBFIWrapper>(
1673 getAnalysis<MachineBlockFrequencyInfo>());
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001674 MLI = &getAnalysis<MachineLoopInfo>();
Xinliang David Li52530a72016-06-13 22:23:44 +00001675 TII = MF.getSubtarget().getInstrInfo();
1676 TLI = MF.getSubtarget().getTargetLowering();
Daniel Jasper471e8562015-03-04 11:05:34 +00001677 MDT = &getAnalysis<MachineDominatorTree>();
Chandler Carruth10281422011-10-21 06:46:38 +00001678 assert(BlockToChain.empty());
Chandler Carruth10281422011-10-21 06:46:38 +00001679
Xinliang David Li52530a72016-06-13 22:23:44 +00001680 buildCFGChains();
Haicheng Wu5b458cc2016-06-09 15:24:29 +00001681
1682 // Changing the layout can create new tail merging opportunities.
1683 TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
1684 // TailMerge can create jump into if branches that make CFG irreducible for
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001685 // HW that requires structured CFG.
Xinliang David Li52530a72016-06-13 22:23:44 +00001686 bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&
Haicheng Wu5b458cc2016-06-09 15:24:29 +00001687 PassConfig->getEnableTailMerge() &&
1688 BranchFoldPlacement;
1689 // No tail merging opportunities if the block number is less than four.
Xinliang David Li52530a72016-06-13 22:23:44 +00001690 if (MF.size() > 3 && EnableTailMerge) {
Haicheng Wu5b458cc2016-06-09 15:24:29 +00001691 BranchFolder BF(/*EnableTailMerge=*/true, /*CommonHoist=*/false, *MBFI,
1692 *MBPI);
1693
Xinliang David Li52530a72016-06-13 22:23:44 +00001694 if (BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
Haicheng Wu5b458cc2016-06-09 15:24:29 +00001695 getAnalysisIfAvailable<MachineModuleInfo>(), MLI,
1696 /*AfterBlockPlacement=*/true)) {
1697 // Redo the layout if tail merging creates/removes/moves blocks.
1698 BlockToChain.clear();
1699 ChainAllocator.DestroyAll();
Xinliang David Li52530a72016-06-13 22:23:44 +00001700 buildCFGChains();
Haicheng Wu5b458cc2016-06-09 15:24:29 +00001701 }
1702 }
1703
Xinliang David Li52530a72016-06-13 22:23:44 +00001704 optimizeBranches();
1705 alignBlocks();
Chandler Carruth10281422011-10-21 06:46:38 +00001706
Chandler Carruth10281422011-10-21 06:46:38 +00001707 BlockToChain.clear();
Chandler Carruthfd9b4d92011-11-14 10:57:23 +00001708 ChainAllocator.DestroyAll();
Chandler Carruth10281422011-10-21 06:46:38 +00001709
Nadav Rotemc0adc9f2013-04-12 01:24:16 +00001710 if (AlignAllBlock)
1711 // Align all of the blocks in the function to a specific alignment.
Xinliang David Li52530a72016-06-13 22:23:44 +00001712 for (MachineBasicBlock &MBB : MF)
Chandler Carruth7a715da2015-03-05 03:19:05 +00001713 MBB.setAlignment(AlignAllBlock);
Geoff Berry10494ac2016-01-21 17:25:52 +00001714 else if (AlignAllNonFallThruBlocks) {
1715 // Align all of the blocks that have no fall-through predecessors to a
1716 // specific alignment.
Xinliang David Li52530a72016-06-13 22:23:44 +00001717 for (auto MBI = std::next(MF.begin()), MBE = MF.end(); MBI != MBE; ++MBI) {
Geoff Berry10494ac2016-01-21 17:25:52 +00001718 auto LayoutPred = std::prev(MBI);
1719 if (!LayoutPred->isSuccessor(&*MBI))
1720 MBI->setAlignment(AlignAllNonFallThruBlocks);
1721 }
1722 }
Nadav Rotemc0adc9f2013-04-12 01:24:16 +00001723
Chandler Carruth10281422011-10-21 06:46:38 +00001724 // We always return true as we have no way to track whether the final order
1725 // differs from the original order.
1726 return true;
1727}
Chandler Carruthae4e8002011-11-02 07:17:12 +00001728
1729namespace {
1730/// \brief A pass to compute block placement statistics.
1731///
1732/// A separate pass to compute interesting statistics for evaluating block
1733/// placement. This is separate from the actual placement pass so that they can
Benjamin Kramerbde91762012-06-02 10:20:22 +00001734/// be computed in the absence of any placement transformations or when using
Chandler Carruthae4e8002011-11-02 07:17:12 +00001735/// alternative placement strategies.
1736class MachineBlockPlacementStats : public MachineFunctionPass {
1737 /// \brief A handle to the branch probability pass.
1738 const MachineBranchProbabilityInfo *MBPI;
1739
1740 /// \brief A handle to the function-wide block frequency pass.
1741 const MachineBlockFrequencyInfo *MBFI;
1742
1743public:
1744 static char ID; // Pass identification, replacement for typeid
1745 MachineBlockPlacementStats() : MachineFunctionPass(ID) {
1746 initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
1747 }
1748
Craig Topper4584cd52014-03-07 09:26:03 +00001749 bool runOnMachineFunction(MachineFunction &F) override;
Chandler Carruthae4e8002011-11-02 07:17:12 +00001750
Craig Topper4584cd52014-03-07 09:26:03 +00001751 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruthae4e8002011-11-02 07:17:12 +00001752 AU.addRequired<MachineBranchProbabilityInfo>();
1753 AU.addRequired<MachineBlockFrequencyInfo>();
1754 AU.setPreservesAll();
1755 MachineFunctionPass::getAnalysisUsage(AU);
1756 }
Chandler Carruthae4e8002011-11-02 07:17:12 +00001757};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001758}
Chandler Carruthae4e8002011-11-02 07:17:12 +00001759
1760char MachineBlockPlacementStats::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +00001761char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
Chandler Carruthae4e8002011-11-02 07:17:12 +00001762INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
1763 "Basic Block Placement Stats", false, false)
1764INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
1765INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
1766INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
1767 "Basic Block Placement Stats", false, false)
1768
Chandler Carruthae4e8002011-11-02 07:17:12 +00001769bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
1770 // Check for single-block functions and skip them.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001771 if (std::next(F.begin()) == F.end())
Chandler Carruthae4e8002011-11-02 07:17:12 +00001772 return false;
1773
1774 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1775 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1776
Chandler Carruth7a715da2015-03-05 03:19:05 +00001777 for (MachineBasicBlock &MBB : F) {
1778 BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001779 Statistic &NumBranches =
Chandler Carruth7a715da2015-03-05 03:19:05 +00001780 (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001781 Statistic &BranchTakenFreq =
Chandler Carruth7a715da2015-03-05 03:19:05 +00001782 (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
1783 for (MachineBasicBlock *Succ : MBB.successors()) {
Chandler Carruthae4e8002011-11-02 07:17:12 +00001784 // Skip if this successor is a fallthrough.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001785 if (MBB.isLayoutSuccessor(Succ))
Chandler Carruthae4e8002011-11-02 07:17:12 +00001786 continue;
1787
Chandler Carruth7a715da2015-03-05 03:19:05 +00001788 BlockFrequency EdgeFreq =
1789 BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
Chandler Carruthae4e8002011-11-02 07:17:12 +00001790 ++NumBranches;
1791 BranchTakenFreq += EdgeFreq.getFrequency();
1792 }
1793 }
1794
1795 return false;
1796}