blob: aa440b2e1ca5175b18ee778b54a25fa3128d6c89 [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"
Kyle Butt0846e562016-10-11 20:36:43 +000043#include "llvm/CodeGen/TailDuplicator.h"
Chandler Carruth10281422011-10-21 06:46:38 +000044#include "llvm/Support/Allocator.h"
Nadav Rotemc3b0f502013-04-12 00:48:32 +000045#include "llvm/Support/CommandLine.h"
Chandler Carruthbd1be4d2011-10-23 09:18:45 +000046#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000047#include "llvm/Support/raw_ostream.h"
Chandler Carruth10281422011-10-21 06:46:38 +000048#include "llvm/Target/TargetInstrInfo.h"
Chandler Carruth8b9737c2011-10-21 08:57:37 +000049#include "llvm/Target/TargetLowering.h"
Eric Christopherd9134482014-08-04 21:25:23 +000050#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruth10281422011-10-21 06:46:38 +000051#include <algorithm>
52using namespace llvm;
53
Chandler Carruthd0dced52015-03-05 02:28:25 +000054#define DEBUG_TYPE "block-placement"
Chandler Carruth1b9dde02014-04-22 02:02:50 +000055
Chandler Carruthae4e8002011-11-02 07:17:12 +000056STATISTIC(NumCondBranches, "Number of conditional branches");
Craig Topper77ec0772015-09-16 03:52:32 +000057STATISTIC(NumUncondBranches, "Number of unconditional branches");
Chandler Carruthae4e8002011-11-02 07:17:12 +000058STATISTIC(CondBranchTakenFreq,
59 "Potential frequency of taking conditional branches");
60STATISTIC(UncondBranchTakenFreq,
61 "Potential frequency of taking unconditional branches");
62
Nadav Rotemc3b0f502013-04-12 00:48:32 +000063static cl::opt<unsigned> AlignAllBlock("align-all-blocks",
64 cl::desc("Force the alignment of all "
65 "blocks in the function."),
66 cl::init(0), cl::Hidden);
67
Geoff Berry10494ac2016-01-21 17:25:52 +000068static cl::opt<unsigned> AlignAllNonFallThruBlocks(
69 "align-all-nofallthru-blocks",
70 cl::desc("Force the alignment of all "
71 "blocks that have no fall-through predecessors (i.e. don't add "
72 "nops that are executed)."),
73 cl::init(0), cl::Hidden);
74
Benjamin Kramerc8160d62013-11-20 19:08:44 +000075// FIXME: Find a good default for this flag and remove the flag.
Chandler Carruth2fc3fe12015-03-05 02:35:31 +000076static cl::opt<unsigned> ExitBlockBias(
77 "block-placement-exit-block-bias",
78 cl::desc("Block frequency percentage a loop exit block needs "
79 "over the original exit to be considered the new exit."),
80 cl::init(0), cl::Hidden);
Benjamin Kramerc8160d62013-11-20 19:08:44 +000081
Sjoerd Meijer5e11a182016-07-27 08:49:23 +000082// Definition:
83// - Outlining: placement of a basic block outside the chain or hot path.
84
Daniel Jasper471e8562015-03-04 11:05:34 +000085static cl::opt<bool> OutlineOptionalBranches(
86 "outline-optional-branches",
Sjoerd Meijer5e11a182016-07-27 08:49:23 +000087 cl::desc("Outlining optional branches will place blocks that are optional "
88 "branches, i.e. branches with a common post dominator, outside "
89 "the hot path or chain"),
Daniel Jasper471e8562015-03-04 11:05:34 +000090 cl::init(false), cl::Hidden);
91
Daniel Jasper214997c2015-03-20 10:00:37 +000092static cl::opt<unsigned> OutlineOptionalThreshold(
93 "outline-optional-threshold",
94 cl::desc("Don't outline optional branches that are a single block with an "
95 "instruction count below this threshold"),
96 cl::init(4), cl::Hidden);
97
Cong Houb90b9e02015-11-02 21:24:00 +000098static cl::opt<unsigned> LoopToColdBlockRatio(
99 "loop-to-cold-block-ratio",
100 cl::desc("Outline loop blocks from loop chain if (frequency of loop) / "
101 "(frequency of block) is greater than this ratio"),
102 cl::init(5), cl::Hidden);
103
Cong Hou7745dbc2015-10-19 23:16:40 +0000104static cl::opt<bool>
105 PreciseRotationCost("precise-rotation-cost",
106 cl::desc("Model the cost of loop rotation more "
107 "precisely by using profile data."),
108 cl::init(false), cl::Hidden);
Xinliang David Lif0ab6df2016-05-12 02:04:41 +0000109static cl::opt<bool>
110 ForcePreciseRotationCost("force-precise-rotation-cost",
Xinliang David Lib840bb82016-05-12 16:39:02 +0000111 cl::desc("Force the use of precise cost "
112 "loop rotation strategy."),
Xinliang David Lif0ab6df2016-05-12 02:04:41 +0000113 cl::init(false), cl::Hidden);
Cong Hou7745dbc2015-10-19 23:16:40 +0000114
115static cl::opt<unsigned> MisfetchCost(
116 "misfetch-cost",
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000117 cl::desc("Cost that models the probabilistic risk of an instruction "
Cong Hou7745dbc2015-10-19 23:16:40 +0000118 "misfetch due to a jump comparing to falling through, whose cost "
119 "is zero."),
120 cl::init(1), cl::Hidden);
121
122static cl::opt<unsigned> JumpInstCost("jump-inst-cost",
123 cl::desc("Cost of jump instructions."),
124 cl::init(1), cl::Hidden);
Kyle Butt0846e562016-10-11 20:36:43 +0000125static cl::opt<bool>
126TailDupPlacement("tail-dup-placement",
127 cl::desc("Perform tail duplication during placement. "
128 "Creates more fallthrough opportunites in "
129 "outline branches."),
130 cl::init(true), cl::Hidden);
Cong Hou7745dbc2015-10-19 23:16:40 +0000131
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000132static cl::opt<bool>
133BranchFoldPlacement("branch-fold-placement",
134 cl::desc("Perform branch folding during placement. "
135 "Reduces code size."),
136 cl::init(true), cl::Hidden);
137
Kyle Butt0846e562016-10-11 20:36:43 +0000138// Heuristic for tail duplication.
139static cl::opt<unsigned> TailDuplicatePlacementThreshold(
140 "tail-dup-placement-threshold",
141 cl::desc("Instruction cutoff for tail duplication during layout. "
142 "Tail merging during layout is forced to have a threshold "
143 "that won't conflict."), cl::init(2),
144 cl::Hidden);
145
Xinliang David Liff287372016-06-03 23:48:36 +0000146extern cl::opt<unsigned> StaticLikelyProb;
Dehao Chen9f2bdfb2016-06-14 22:27:17 +0000147extern cl::opt<unsigned> ProfileLikelyProb;
Xinliang David Liff287372016-06-03 23:48:36 +0000148
Chandler Carruth10281422011-10-21 06:46:38 +0000149namespace {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000150class BlockChain;
Chandler Carruth10281422011-10-21 06:46:38 +0000151/// \brief Type for our function-wide basic block -> block chain mapping.
152typedef DenseMap<MachineBasicBlock *, BlockChain *> BlockToChainMapType;
153}
154
155namespace {
156/// \brief A chain of blocks which will be laid out contiguously.
157///
158/// This is the datastructure representing a chain of consecutive blocks that
159/// are profitable to layout together in order to maximize fallthrough
Chandler Carruth9139f442012-06-26 05:16:37 +0000160/// probabilities and code locality. We also can use a block chain to represent
161/// a sequence of basic blocks which have some external (correctness)
162/// requirement for sequential layout.
Chandler Carruth10281422011-10-21 06:46:38 +0000163///
Chandler Carruth9139f442012-06-26 05:16:37 +0000164/// Chains can be built around a single basic block and can be merged to grow
165/// them. They participate in a block-to-chain mapping, which is updated
166/// automatically as chains are merged together.
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000167class BlockChain {
168 /// \brief The sequence of blocks belonging to this chain.
Chandler Carruth10281422011-10-21 06:46:38 +0000169 ///
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000170 /// This is the sequence of blocks for a particular chain. These will be laid
171 /// out in-order within the function.
172 SmallVector<MachineBasicBlock *, 4> Blocks;
Chandler Carruth10281422011-10-21 06:46:38 +0000173
174 /// \brief A handle to the function-wide basic block to block chain mapping.
175 ///
176 /// This is retained in each block chain to simplify the computation of child
177 /// block chains for SCC-formation and iteration. We store the edges to child
178 /// basic blocks, and map them back to their associated chains using this
179 /// structure.
180 BlockToChainMapType &BlockToChain;
181
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000182public:
Chandler Carruth10281422011-10-21 06:46:38 +0000183 /// \brief Construct a new BlockChain.
184 ///
185 /// This builds a new block chain representing a single basic block in the
186 /// function. It also registers itself as the chain that block participates
187 /// in with the BlockToChain mapping.
188 BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
Philip Reamesae27b232016-03-03 00:58:43 +0000189 : Blocks(1, BB), BlockToChain(BlockToChain), UnscheduledPredecessors(0) {
Chandler Carruth10281422011-10-21 06:46:38 +0000190 assert(BB && "Cannot create a chain with a null basic block");
191 BlockToChain[BB] = this;
192 }
193
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000194 /// \brief Iterator over blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000195 typedef SmallVectorImpl<MachineBasicBlock *>::iterator iterator;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000196
197 /// \brief Beginning of blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000198 iterator begin() { return Blocks.begin(); }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000199
200 /// \brief End of blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000201 iterator end() { return Blocks.end(); }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000202
Kyle Butt0846e562016-10-11 20:36:43 +0000203 bool remove(MachineBasicBlock* BB) {
204 for(iterator i = begin(); i != end(); ++i) {
205 if (*i == BB) {
206 Blocks.erase(i);
207 return true;
208 }
209 }
210 return false;
211 }
212
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000213 /// \brief Merge a block chain into this one.
Chandler Carruth10281422011-10-21 06:46:38 +0000214 ///
215 /// This routine merges a block chain into this one. It takes care of forming
216 /// a contiguous sequence of basic blocks, updating the edge list, and
217 /// updating the block -> chain mapping. It does not free or tear down the
218 /// old chain, but the old chain's block list is no longer valid.
Jakub Staszak90616162011-12-21 23:02:08 +0000219 void merge(MachineBasicBlock *BB, BlockChain *Chain) {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000220 assert(BB);
221 assert(!Blocks.empty());
Chandler Carruth10281422011-10-21 06:46:38 +0000222
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000223 // Fast path in case we don't have a chain already.
224 if (!Chain) {
225 assert(!BlockToChain[BB]);
226 Blocks.push_back(BB);
227 BlockToChain[BB] = this;
228 return;
Chandler Carruth10281422011-10-21 06:46:38 +0000229 }
230
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000231 assert(BB == *Chain->begin());
232 assert(Chain->begin() != Chain->end());
Chandler Carruth10281422011-10-21 06:46:38 +0000233
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000234 // Update the incoming blocks to point to this chain, and add them to the
235 // chain structure.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000236 for (MachineBasicBlock *ChainBB : *Chain) {
237 Blocks.push_back(ChainBB);
238 assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain");
239 BlockToChain[ChainBB] = this;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000240 }
Chandler Carruth10281422011-10-21 06:46:38 +0000241 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000242
Chandler Carruth49158902012-04-08 14:37:01 +0000243#ifndef NDEBUG
244 /// \brief Dump the blocks in this chain.
Nico Weber7408c702014-01-03 22:53:37 +0000245 LLVM_DUMP_METHOD void dump() {
Chandler Carruth7a715da2015-03-05 03:19:05 +0000246 for (MachineBasicBlock *MBB : *this)
247 MBB->dump();
Chandler Carruth49158902012-04-08 14:37:01 +0000248 }
249#endif // NDEBUG
250
Philip Reamesae27b232016-03-03 00:58:43 +0000251 /// \brief Count of predecessors of any block within the chain which have not
252 /// yet been scheduled. In general, we will delay scheduling this chain
253 /// until those predecessors are scheduled (or we find a sufficiently good
254 /// reason to override this heuristic.) Note that when forming loop chains,
255 /// blocks outside the loop are ignored and treated as if they were already
256 /// scheduled.
Chandler Carruth8d150782011-11-13 11:20:44 +0000257 ///
Philip Reamesae27b232016-03-03 00:58:43 +0000258 /// Note: This field is reinitialized multiple times - once for each loop,
259 /// and then once for the function as a whole.
260 unsigned UnscheduledPredecessors;
Chandler Carruth10281422011-10-21 06:46:38 +0000261};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000262}
Chandler Carruth10281422011-10-21 06:46:38 +0000263
264namespace {
265class MachineBlockPlacement : public MachineFunctionPass {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000266 /// \brief A typedef for a block filter set.
267 typedef SmallPtrSet<MachineBasicBlock *, 16> BlockFilterSet;
268
Xinliang David Li93926ac2016-07-01 05:46:48 +0000269 /// \brief work lists of blocks that are ready to be laid out
270 SmallVector<MachineBasicBlock *, 16> BlockWorkList;
271 SmallVector<MachineBasicBlock *, 16> EHPadWorkList;
272
Xinliang David Li52530a72016-06-13 22:23:44 +0000273 /// \brief Machine Function
274 MachineFunction *F;
275
Chandler Carruth10281422011-10-21 06:46:38 +0000276 /// \brief A handle to the branch probability pass.
277 const MachineBranchProbabilityInfo *MBPI;
278
279 /// \brief A handle to the function-wide block frequency pass.
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000280 std::unique_ptr<BranchFolder::MBFIWrapper> MBFI;
Chandler Carruth10281422011-10-21 06:46:38 +0000281
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000282 /// \brief A handle to the loop info.
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000283 MachineLoopInfo *MLI;
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000284
Chandler Carruth10281422011-10-21 06:46:38 +0000285 /// \brief A handle to the target's instruction info.
286 const TargetInstrInfo *TII;
287
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000288 /// \brief A handle to the target's lowering info.
Benjamin Kramer56b31bd2013-01-11 20:05:37 +0000289 const TargetLoweringBase *TLI;
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000290
Daniel Jasper471e8562015-03-04 11:05:34 +0000291 /// \brief A handle to the post dominator tree.
292 MachineDominatorTree *MDT;
293
Kyle Butt0846e562016-10-11 20:36:43 +0000294 /// \brief Duplicator used to duplicate tails during placement.
295 ///
296 /// Placement decisions can open up new tail duplication opportunities, but
297 /// since tail duplication affects placement decisions of later blocks, it
298 /// must be done inline.
299 TailDuplicator TailDup;
300
Daniel Jasper471e8562015-03-04 11:05:34 +0000301 /// \brief A set of blocks that are unavoidably execute, i.e. they dominate
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000302 /// all terminators of the MachineFunction.
Daniel Jasper471e8562015-03-04 11:05:34 +0000303 SmallPtrSet<MachineBasicBlock *, 4> UnavoidableBlocks;
304
Chandler Carruth10281422011-10-21 06:46:38 +0000305 /// \brief Allocator and owner of BlockChain structures.
306 ///
Chandler Carruth9139f442012-06-26 05:16:37 +0000307 /// We build BlockChains lazily while processing the loop structure of
308 /// a function. To reduce malloc traffic, we allocate them using this
309 /// slab-like allocator, and destroy them after the pass completes. An
310 /// important guarantee is that this allocator produces stable pointers to
311 /// the chains.
Chandler Carruth10281422011-10-21 06:46:38 +0000312 SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
313
314 /// \brief Function wide BasicBlock to BlockChain mapping.
315 ///
316 /// This mapping allows efficiently moving from any given basic block to the
317 /// BlockChain it participates in, if any. We use it to, among other things,
318 /// allow implicitly defining edges between chains as the existing edges
319 /// between basic blocks.
320 DenseMap<MachineBasicBlock *, BlockChain *> BlockToChain;
321
Kyle Butt0846e562016-10-11 20:36:43 +0000322 /// Decrease the UnscheduledPredecessors count for all blocks in chain, and
323 /// if the count goes to 0, add them to the appropriate work list.
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000324 void markChainSuccessors(BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
Craig Topperc0196b12014-04-14 00:51:57 +0000325 const BlockFilterSet *BlockFilter = nullptr);
Kyle Butt0846e562016-10-11 20:36:43 +0000326
327 /// Decrease the UnscheduledPredecessors count for a single block, and
328 /// if the count goes to 0, add them to the appropriate work list.
329 void markBlockSuccessors(
330 BlockChain &Chain, MachineBasicBlock *BB, MachineBasicBlock *LoopHeaderBB,
331 const BlockFilterSet *BlockFilter = nullptr);
332
333
Xinliang David Li594ffa32016-06-11 18:35:40 +0000334 BranchProbability
335 collectViableSuccessors(MachineBasicBlock *BB, BlockChain &Chain,
336 const BlockFilterSet *BlockFilter,
337 SmallVector<MachineBasicBlock *, 4> &Successors);
Xinliang David Li071d0f12016-06-12 16:54:03 +0000338 bool shouldPredBlockBeOutlined(MachineBasicBlock *BB, MachineBasicBlock *Succ,
339 BlockChain &Chain,
340 const BlockFilterSet *BlockFilter,
341 BranchProbability SuccProb,
342 BranchProbability HotProb);
Kyle Butt0846e562016-10-11 20:36:43 +0000343 bool repeatedlyTailDuplicateBlock(
344 MachineBasicBlock *BB, MachineBasicBlock *&LPred,
345 MachineBasicBlock *LoopHeaderBB,
346 BlockChain &Chain, BlockFilterSet *BlockFilter,
347 MachineFunction::iterator &PrevUnplacedBlockIt);
348 bool maybeTailDuplicateBlock(MachineBasicBlock *BB, MachineBasicBlock *LPred,
349 const BlockChain &Chain,
350 BlockFilterSet *BlockFilter,
351 MachineFunction::iterator &PrevUnplacedBlockIt,
352 bool &DuplicatedToPred);
Xinliang David Licbf12142016-06-13 20:24:19 +0000353 bool
354 hasBetterLayoutPredecessor(MachineBasicBlock *BB, MachineBasicBlock *Succ,
355 BlockChain &SuccChain, BranchProbability SuccProb,
356 BranchProbability RealSuccProb, BlockChain &Chain,
357 const BlockFilterSet *BlockFilter);
Jakub Staszak90616162011-12-21 23:02:08 +0000358 MachineBasicBlock *selectBestSuccessor(MachineBasicBlock *BB,
359 BlockChain &Chain,
360 const BlockFilterSet *BlockFilter);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000361 MachineBasicBlock *
362 selectBestCandidateBlock(BlockChain &Chain,
Amaury Sechet9ee4ddd2016-04-07 06:34:47 +0000363 SmallVectorImpl<MachineBasicBlock *> &WorkList);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000364 MachineBasicBlock *
Xinliang David Li52530a72016-06-13 22:23:44 +0000365 getFirstUnplacedBlock(const BlockChain &PlacedChain,
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000366 MachineFunction::iterator &PrevUnplacedBlockIt,
367 const BlockFilterSet *BlockFilter);
Amaury Secheteae09c22016-03-14 21:24:11 +0000368
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000369 /// \brief Add a basic block to the work list if it is appropriate.
Amaury Secheteae09c22016-03-14 21:24:11 +0000370 ///
371 /// If the optional parameter BlockFilter is provided, only MBB
372 /// present in the set will be added to the worklist. If nullptr
373 /// is provided, no filtering occurs.
374 void fillWorkLists(MachineBasicBlock *MBB,
375 SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
Amaury Secheteae09c22016-03-14 21:24:11 +0000376 const BlockFilterSet *BlockFilter);
Chandler Carruth8d150782011-11-13 11:20:44 +0000377 void buildChain(MachineBasicBlock *BB, BlockChain &Chain,
Kyle Butt0846e562016-10-11 20:36:43 +0000378 BlockFilterSet *BlockFilter = nullptr);
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000379 MachineBasicBlock *findBestLoopTop(MachineLoop &L,
380 const BlockFilterSet &LoopBlockSet);
Xinliang David Li52530a72016-06-13 22:23:44 +0000381 MachineBasicBlock *findBestLoopExit(MachineLoop &L,
Chandler Carruthccc7e422012-04-16 01:12:56 +0000382 const BlockFilterSet &LoopBlockSet);
Xinliang David Li52530a72016-06-13 22:23:44 +0000383 BlockFilterSet collectLoopBlockSet(MachineLoop &L);
384 void buildLoopChains(MachineLoop &L);
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000385 void rotateLoop(BlockChain &LoopChain, MachineBasicBlock *ExitingBB,
386 const BlockFilterSet &LoopBlockSet);
Cong Hou7745dbc2015-10-19 23:16:40 +0000387 void rotateLoopWithProfile(BlockChain &LoopChain, MachineLoop &L,
388 const BlockFilterSet &LoopBlockSet);
Xinliang David Li52530a72016-06-13 22:23:44 +0000389 void collectMustExecuteBBs();
390 void buildCFGChains();
391 void optimizeBranches();
392 void alignBlocks();
Chandler Carruth10281422011-10-21 06:46:38 +0000393
394public:
395 static char ID; // Pass identification, replacement for typeid
396 MachineBlockPlacement() : MachineFunctionPass(ID) {
397 initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
398 }
399
Craig Topper4584cd52014-03-07 09:26:03 +0000400 bool runOnMachineFunction(MachineFunction &F) override;
Chandler Carruth10281422011-10-21 06:46:38 +0000401
Craig Topper4584cd52014-03-07 09:26:03 +0000402 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth10281422011-10-21 06:46:38 +0000403 AU.addRequired<MachineBranchProbabilityInfo>();
404 AU.addRequired<MachineBlockFrequencyInfo>();
Daniel Jasper471e8562015-03-04 11:05:34 +0000405 AU.addRequired<MachineDominatorTree>();
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000406 AU.addRequired<MachineLoopInfo>();
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000407 AU.addRequired<TargetPassConfig>();
Chandler Carruth10281422011-10-21 06:46:38 +0000408 MachineFunctionPass::getAnalysisUsage(AU);
409 }
Chandler Carruth10281422011-10-21 06:46:38 +0000410};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000411}
Chandler Carruth10281422011-10-21 06:46:38 +0000412
413char MachineBlockPlacement::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000414char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
Chandler Carruthd0dced52015-03-05 02:28:25 +0000415INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement",
Chandler Carruth10281422011-10-21 06:46:38 +0000416 "Branch Probability Basic Block Placement", false, false)
417INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
418INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
Daniel Jasper471e8562015-03-04 11:05:34 +0000419INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000420INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
Chandler Carruthd0dced52015-03-05 02:28:25 +0000421INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement",
Chandler Carruth10281422011-10-21 06:46:38 +0000422 "Branch Probability Basic Block Placement", false, false)
423
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000424#ifndef NDEBUG
425/// \brief Helper to print the name of a MBB.
426///
427/// Only used by debug logging.
Jakub Staszak90616162011-12-21 23:02:08 +0000428static std::string getBlockName(MachineBasicBlock *BB) {
Alp Tokere69170a2014-06-26 22:52:05 +0000429 std::string Result;
430 raw_string_ostream OS(Result);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000431 OS << "BB#" << BB->getNumber();
Philip Reamesb9688f42016-03-02 21:45:13 +0000432 OS << " ('" << BB->getName() << "')";
Alp Tokere69170a2014-06-26 22:52:05 +0000433 OS.flush();
434 return Result;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000435}
436#endif
437
Chandler Carrutheb4ec3a2011-11-13 11:34:55 +0000438/// \brief Mark a chain's successors as having one fewer preds.
439///
440/// When a chain is being merged into the "placed" chain, this routine will
441/// quickly walk the successors of each block in the chain and mark them as
442/// having one fewer active predecessor. It also adds any successors of this
Kyle Butt0846e562016-10-11 20:36:43 +0000443/// chain which reach the zero-predecessor state to the appropriate worklist.
Chandler Carruth8d150782011-11-13 11:20:44 +0000444void MachineBlockPlacement::markChainSuccessors(
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000445 BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
Jakub Staszak90616162011-12-21 23:02:08 +0000446 const BlockFilterSet *BlockFilter) {
Chandler Carruth8d150782011-11-13 11:20:44 +0000447 // Walk all the blocks in this chain, marking their successors as having
448 // a predecessor placed.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000449 for (MachineBasicBlock *MBB : Chain) {
Kyle Butt0846e562016-10-11 20:36:43 +0000450 markBlockSuccessors(Chain, MBB, LoopHeaderBB, BlockFilter);
451 }
452}
Chandler Carruth10281422011-10-21 06:46:38 +0000453
Kyle Butt0846e562016-10-11 20:36:43 +0000454/// \brief Mark a single block's successors as having one fewer preds.
455///
456/// Under normal circumstances, this is only called by markChainSuccessors,
457/// but if a block that was to be placed is completely tail-duplicated away,
458/// and was duplicated into the chain end, we need to redo markBlockSuccessors
459/// for just that block.
460void MachineBlockPlacement::markBlockSuccessors(
461 BlockChain &Chain, MachineBasicBlock *MBB, MachineBasicBlock *LoopHeaderBB,
462 const BlockFilterSet *BlockFilter) {
463 // Add any successors for which this is the only un-placed in-loop
464 // predecessor to the worklist as a viable candidate for CFG-neutral
465 // placement. No subsequent placement of this block will violate the CFG
466 // shape, so we get to use heuristics to choose a favorable placement.
467 for (MachineBasicBlock *Succ : MBB->successors()) {
468 if (BlockFilter && !BlockFilter->count(Succ))
469 continue;
470 BlockChain &SuccChain = *BlockToChain[Succ];
471 // Disregard edges within a fixed chain, or edges to the loop header.
472 if (&Chain == &SuccChain || Succ == LoopHeaderBB)
473 continue;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000474
Kyle Butt0846e562016-10-11 20:36:43 +0000475 // This is a cross-chain edge that is within the loop, so decrement the
476 // loop predecessor count of the destination chain.
477 if (SuccChain.UnscheduledPredecessors == 0 ||
478 --SuccChain.UnscheduledPredecessors > 0)
479 continue;
480
481 auto *NewBB = *SuccChain.begin();
482 if (NewBB->isEHPad())
483 EHPadWorkList.push_back(NewBB);
484 else
485 BlockWorkList.push_back(NewBB);
Chandler Carruth10281422011-10-21 06:46:38 +0000486 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000487}
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000488
Xinliang David Li594ffa32016-06-11 18:35:40 +0000489/// This helper function collects the set of successors of block
490/// \p BB that are allowed to be its layout successors, and return
491/// the total branch probability of edges from \p BB to those
492/// blocks.
493BranchProbability MachineBlockPlacement::collectViableSuccessors(
494 MachineBasicBlock *BB, BlockChain &Chain, const BlockFilterSet *BlockFilter,
495 SmallVector<MachineBasicBlock *, 4> &Successors) {
Cong Houd97c1002015-12-01 05:29:22 +0000496 // Adjust edge probabilities by excluding edges pointing to blocks that is
497 // either not in BlockFilter or is already in the current chain. Consider the
498 // following CFG:
Cong Hou41cf1a52015-11-18 00:52:52 +0000499 //
500 // --->A
501 // | / \
502 // | B C
503 // | \ / \
504 // ----D E
505 //
506 // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after
507 // A->C is chosen as a fall-through, D won't be selected as a successor of C
508 // due to CFG constraint (the probability of C->D is not greater than
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000509 // HotProb to break top-order). If we exclude E that is not in BlockFilter
Xinliang David Li594ffa32016-06-11 18:35:40 +0000510 // when calculating the probability of C->D, D will be selected and we
511 // will get A C D B as the layout of this loop.
Cong Houd97c1002015-12-01 05:29:22 +0000512 auto AdjustedSumProb = BranchProbability::getOne();
Cong Hou41cf1a52015-11-18 00:52:52 +0000513 for (MachineBasicBlock *Succ : BB->successors()) {
514 bool SkipSucc = false;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000515 if (Succ->isEHPad() || (BlockFilter && !BlockFilter->count(Succ))) {
Cong Hou41cf1a52015-11-18 00:52:52 +0000516 SkipSucc = true;
517 } else {
518 BlockChain *SuccChain = BlockToChain[Succ];
519 if (SuccChain == &Chain) {
Cong Hou41cf1a52015-11-18 00:52:52 +0000520 SkipSucc = true;
521 } else if (Succ != *SuccChain->begin()) {
522 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> Mid chain!\n");
523 continue;
524 }
525 }
526 if (SkipSucc)
Cong Houd97c1002015-12-01 05:29:22 +0000527 AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ);
Cong Hou41cf1a52015-11-18 00:52:52 +0000528 else
529 Successors.push_back(Succ);
530 }
531
Xinliang David Li594ffa32016-06-11 18:35:40 +0000532 return AdjustedSumProb;
533}
534
535/// The helper function returns the branch probability that is adjusted
536/// or normalized over the new total \p AdjustedSumProb.
Xinliang David Li594ffa32016-06-11 18:35:40 +0000537static BranchProbability
538getAdjustedProbability(BranchProbability OrigProb,
539 BranchProbability AdjustedSumProb) {
540 BranchProbability SuccProb;
541 uint32_t SuccProbN = OrigProb.getNumerator();
542 uint32_t SuccProbD = AdjustedSumProb.getNumerator();
543 if (SuccProbN >= SuccProbD)
544 SuccProb = BranchProbability::getOne();
545 else
546 SuccProb = BranchProbability(SuccProbN, SuccProbD);
547
548 return SuccProb;
549}
550
Xinliang David Li071d0f12016-06-12 16:54:03 +0000551/// When the option OutlineOptionalBranches is on, this method
552/// checks if the fallthrough candidate block \p Succ (of block
553/// \p BB) also has other unscheduled predecessor blocks which
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000554/// are also successors of \p BB (forming triangular shape CFG).
Xinliang David Li071d0f12016-06-12 16:54:03 +0000555/// If none of such predecessors are small, it returns true.
556/// The caller can choose to select \p Succ as the layout successors
557/// so that \p Succ's predecessors (optional branches) can be
558/// outlined.
559/// FIXME: fold this with more general layout cost analysis.
560bool MachineBlockPlacement::shouldPredBlockBeOutlined(
561 MachineBasicBlock *BB, MachineBasicBlock *Succ, BlockChain &Chain,
562 const BlockFilterSet *BlockFilter, BranchProbability SuccProb,
563 BranchProbability HotProb) {
564 if (!OutlineOptionalBranches)
565 return false;
566 // If we outline optional branches, look whether Succ is unavoidable, i.e.
567 // dominates all terminators of the MachineFunction. If it does, other
568 // successors must be optional. Don't do this for cold branches.
569 if (SuccProb > HotProb.getCompl() && UnavoidableBlocks.count(Succ) > 0) {
570 for (MachineBasicBlock *Pred : Succ->predecessors()) {
571 // Check whether there is an unplaced optional branch.
572 if (Pred == Succ || (BlockFilter && !BlockFilter->count(Pred)) ||
573 BlockToChain[Pred] == &Chain)
574 continue;
575 // Check whether the optional branch has exactly one BB.
576 if (Pred->pred_size() > 1 || *Pred->pred_begin() != BB)
577 continue;
578 // Check whether the optional branch is small.
579 if (Pred->size() < OutlineOptionalThreshold)
580 return false;
581 }
582 return true;
583 } else
584 return false;
585}
586
Dehao Chen9f2bdfb2016-06-14 22:27:17 +0000587// When profile is not present, return the StaticLikelyProb.
588// When profile is available, we need to handle the triangle-shape CFG.
589static BranchProbability getLayoutSuccessorProbThreshold(
590 MachineBasicBlock *BB) {
591 if (!BB->getParent()->getFunction()->getEntryCount())
592 return BranchProbability(StaticLikelyProb, 100);
593 if (BB->succ_size() == 2) {
594 const MachineBasicBlock *Succ1 = *BB->succ_begin();
595 const MachineBasicBlock *Succ2 = *(BB->succ_begin() + 1);
Xinliang David Lie34ed832016-06-15 03:03:30 +0000596 if (Succ1->isSuccessor(Succ2) || Succ2->isSuccessor(Succ1)) {
597 /* See case 1 below for the cost analysis. For BB->Succ to
598 * be taken with smaller cost, the following needs to hold:
599 * Prob(BB->Succ) > 2* Prob(BB->Pred)
600 * So the threshold T
601 * T = 2 * (1-Prob(BB->Pred). Since T + Prob(BB->Pred) == 1,
602 * We have T + T/2 = 1, i.e. T = 2/3. Also adding user specified
603 * branch bias, we have
604 * T = (2/3)*(ProfileLikelyProb/50)
605 * = (2*ProfileLikelyProb)/150)
606 */
607 return BranchProbability(2 * ProfileLikelyProb, 150);
608 }
Dehao Chen9f2bdfb2016-06-14 22:27:17 +0000609 }
610 return BranchProbability(ProfileLikelyProb, 100);
Xinliang David Licbf12142016-06-13 20:24:19 +0000611}
612
613/// Checks to see if the layout candidate block \p Succ has a better layout
614/// predecessor than \c BB. If yes, returns true.
615bool MachineBlockPlacement::hasBetterLayoutPredecessor(
616 MachineBasicBlock *BB, MachineBasicBlock *Succ, BlockChain &SuccChain,
617 BranchProbability SuccProb, BranchProbability RealSuccProb,
618 BlockChain &Chain, const BlockFilterSet *BlockFilter) {
619
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000620 // There isn't a better layout when there are no unscheduled predecessors.
Xinliang David Licbf12142016-06-13 20:24:19 +0000621 if (SuccChain.UnscheduledPredecessors == 0)
622 return false;
623
624 // There are two basic scenarios here:
625 // -------------------------------------
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000626 // Case 1: triangular shape CFG (if-then):
Xinliang David Licbf12142016-06-13 20:24:19 +0000627 // BB
628 // | \
629 // | \
630 // | Pred
631 // | /
632 // Succ
633 // In this case, we are evaluating whether to select edge -> Succ, e.g.
634 // set Succ as the layout successor of BB. Picking Succ as BB's
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000635 // successor breaks the CFG constraints (FIXME: define these constraints).
636 // With this layout, Pred BB
Xinliang David Licbf12142016-06-13 20:24:19 +0000637 // is forced to be outlined, so the overall cost will be cost of the
638 // branch taken from BB to Pred, plus the cost of back taken branch
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000639 // from Pred to Succ, as well as the additional cost associated
Xinliang David Licbf12142016-06-13 20:24:19 +0000640 // with the needed unconditional jump instruction from Pred To Succ.
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000641
Xinliang David Licbf12142016-06-13 20:24:19 +0000642 // The cost of the topological order layout is the taken branch cost
643 // from BB to Succ, so to make BB->Succ a viable candidate, the following
644 // must hold:
645 // 2 * freq(BB->Pred) * taken_branch_cost + unconditional_jump_cost
646 // < freq(BB->Succ) * taken_branch_cost.
647 // Ignoring unconditional jump cost, we get
648 // freq(BB->Succ) > 2 * freq(BB->Pred), i.e.,
649 // prob(BB->Succ) > 2 * prob(BB->Pred)
650 //
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000651 // When real profile data is available, we can precisely compute the
652 // probability threshold that is needed for edge BB->Succ to be considered.
653 // Without profile data, the heuristic requires the branch bias to be
Xinliang David Licbf12142016-06-13 20:24:19 +0000654 // a lot larger to make sure the signal is very strong (e.g. 80% default).
655 // -----------------------------------------------------------------
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000656 // Case 2: diamond like CFG (if-then-else):
Xinliang David Licbf12142016-06-13 20:24:19 +0000657 // S
658 // / \
659 // | \
660 // BB Pred
661 // \ /
662 // Succ
663 // ..
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000664 //
665 // The current block is BB and edge BB->Succ is now being evaluated.
666 // Note that edge S->BB was previously already selected because
667 // prob(S->BB) > prob(S->Pred).
668 // At this point, 2 blocks can be placed after BB: Pred or Succ. If we
669 // choose Pred, we will have a topological ordering as shown on the left
670 // in the picture below. If we choose Succ, we have the solution as shown
671 // on the right:
672 //
673 // topo-order:
674 //
675 // S----- ---S
676 // | | | |
677 // ---BB | | BB
678 // | | | |
679 // | pred-- | Succ--
680 // | | | |
681 // ---succ ---pred--
682 //
683 // cost = freq(S->Pred) + freq(BB->Succ) cost = 2 * freq (S->Pred)
684 // = freq(S->Pred) + freq(S->BB)
685 //
686 // If we have profile data (i.e, branch probabilities can be trusted), the
687 // cost (number of taken branches) with layout S->BB->Succ->Pred is 2 *
688 // freq(S->Pred) while the cost of topo order is freq(S->Pred) + freq(S->BB).
689 // We know Prob(S->BB) > Prob(S->Pred), so freq(S->BB) > freq(S->Pred), which
690 // means the cost of topological order is greater.
Xinliang David Licbf12142016-06-13 20:24:19 +0000691 // When profile data is not available, however, we need to be more
692 // conservative. If the branch prediction is wrong, breaking the topo-order
693 // will actually yield a layout with large cost. For this reason, we need
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000694 // strong biased branch at block S with Prob(S->BB) in order to select
695 // BB->Succ. This is equivalent to looking the CFG backward with backward
Xinliang David Licbf12142016-06-13 20:24:19 +0000696 // edge: Prob(Succ->BB) needs to >= HotProb in order to be selected (without
697 // profile data).
Kyle Butt02d8d052016-07-29 18:09:28 +0000698 // --------------------------------------------------------------------------
699 // Case 3: forked diamond
700 // S
701 // / \
702 // / \
703 // BB Pred
704 // | \ / |
705 // | \ / |
706 // | X |
707 // | / \ |
708 // | / \ |
709 // S1 S2
710 //
711 // The current block is BB and edge BB->S1 is now being evaluated.
712 // As above S->BB was already selected because
713 // prob(S->BB) > prob(S->Pred). Assume that prob(BB->S1) >= prob(BB->S2).
714 //
715 // topo-order:
716 //
717 // S-------| ---S
718 // | | | |
719 // ---BB | | BB
720 // | | | |
721 // | Pred----| | S1----
722 // | | | |
723 // --(S1 or S2) ---Pred--
724 //
725 // topo-cost = freq(S->Pred) + freq(BB->S1) + freq(BB->S2)
726 // + min(freq(Pred->S1), freq(Pred->S2))
727 // Non-topo-order cost:
728 // In the worst case, S2 will not get laid out after Pred.
729 // non-topo-cost = 2 * freq(S->Pred) + freq(BB->S2).
730 // To be conservative, we can assume that min(freq(Pred->S1), freq(Pred->S2))
731 // is 0. Then the non topo layout is better when
732 // freq(S->Pred) < freq(BB->S1).
733 // This is exactly what is checked below.
734 // Note there are other shapes that apply (Pred may not be a single block,
735 // but they all fit this general pattern.)
Dehao Chen9f2bdfb2016-06-14 22:27:17 +0000736 BranchProbability HotProb = getLayoutSuccessorProbThreshold(BB);
Xinliang David Licbf12142016-06-13 20:24:19 +0000737
Xinliang David Licbf12142016-06-13 20:24:19 +0000738 // Make sure that a hot successor doesn't have a globally more
739 // important predecessor.
740 BlockFrequency CandidateEdgeFreq = MBFI->getBlockFreq(BB) * RealSuccProb;
741 bool BadCFGConflict = false;
742
743 for (MachineBasicBlock *Pred : Succ->predecessors()) {
744 if (Pred == Succ || BlockToChain[Pred] == &SuccChain ||
745 (BlockFilter && !BlockFilter->count(Pred)) ||
746 BlockToChain[Pred] == &Chain)
747 continue;
Kyle Butt02d8d052016-07-29 18:09:28 +0000748 // Do backward checking.
749 // For all cases above, we need a backward checking to filter out edges that
750 // are not 'strongly' biased. With profile data available, the check is
751 // mostly redundant for case 2 (when threshold prob is set at 50%) unless S
752 // has more than two successors.
Xinliang David Licbf12142016-06-13 20:24:19 +0000753 // BB Pred
754 // \ /
755 // Succ
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000756 // We select edge BB->Succ if
Xinliang David Licbf12142016-06-13 20:24:19 +0000757 // freq(BB->Succ) > freq(Succ) * HotProb
758 // i.e. freq(BB->Succ) > freq(BB->Succ) * HotProb + freq(Pred->Succ) *
759 // HotProb
760 // i.e. freq((BB->Succ) * (1 - HotProb) > freq(Pred->Succ) * HotProb
Kyle Butt02d8d052016-07-29 18:09:28 +0000761 // Case 1 is covered too, because the first equation reduces to:
762 // prob(BB->Succ) > HotProb. (freq(Succ) = freq(BB) for a triangle)
Xinliang David Licbf12142016-06-13 20:24:19 +0000763 BlockFrequency PredEdgeFreq =
764 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
765 if (PredEdgeFreq * HotProb >= CandidateEdgeFreq * HotProb.getCompl()) {
766 BadCFGConflict = true;
767 break;
768 }
769 }
770
771 if (BadCFGConflict) {
Sjoerd Meijer5e11a182016-07-27 08:49:23 +0000772 DEBUG(dbgs() << " Not a candidate: " << getBlockName(Succ) << " -> " << SuccProb
Xinliang David Licbf12142016-06-13 20:24:19 +0000773 << " (prob) (non-cold CFG conflict)\n");
774 return true;
775 }
776
777 return false;
778}
779
Xinliang David Li594ffa32016-06-11 18:35:40 +0000780/// \brief Select the best successor for a block.
781///
782/// This looks across all successors of a particular block and attempts to
783/// select the "best" one to be the layout successor. It only considers direct
784/// successors which also pass the block filter. It will attempt to avoid
785/// breaking CFG structure, but cave and break such structures in the case of
786/// very hot successor edges.
787///
788/// \returns The best successor block found, or null if none are viable.
789MachineBasicBlock *
790MachineBlockPlacement::selectBestSuccessor(MachineBasicBlock *BB,
791 BlockChain &Chain,
792 const BlockFilterSet *BlockFilter) {
793 const BranchProbability HotProb(StaticLikelyProb, 100);
794
795 MachineBasicBlock *BestSucc = nullptr;
796 auto BestProb = BranchProbability::getZero();
797
798 SmallVector<MachineBasicBlock *, 4> Successors;
799 auto AdjustedSumProb =
800 collectViableSuccessors(BB, Chain, BlockFilter, Successors);
801
Sjoerd Meijer5e11a182016-07-27 08:49:23 +0000802 DEBUG(dbgs() << "Selecting best successor for: " << getBlockName(BB) << "\n");
Cong Hou41cf1a52015-11-18 00:52:52 +0000803 for (MachineBasicBlock *Succ : Successors) {
Xinliang David Li594ffa32016-06-11 18:35:40 +0000804 auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ);
805 BranchProbability SuccProb =
806 getAdjustedProbability(RealSuccProb, AdjustedSumProb);
Chandler Carruthb3361722011-11-13 11:34:53 +0000807
Xinliang David Li071d0f12016-06-12 16:54:03 +0000808 // This heuristic is off by default.
809 if (shouldPredBlockBeOutlined(BB, Succ, Chain, BlockFilter, SuccProb,
810 HotProb))
811 return Succ;
Daniel Jasper471e8562015-03-04 11:05:34 +0000812
Cong Hou41cf1a52015-11-18 00:52:52 +0000813 BlockChain &SuccChain = *BlockToChain[Succ];
Xinliang David Licbf12142016-06-13 20:24:19 +0000814 // Skip the edge \c BB->Succ if block \c Succ has a better layout
815 // predecessor that yields lower global cost.
816 if (hasBetterLayoutPredecessor(BB, Succ, SuccChain, SuccProb, RealSuccProb,
817 Chain, BlockFilter))
818 continue;
Chandler Carruth18dfac32011-11-20 11:22:06 +0000819
Xinliang David Licbf12142016-06-13 20:24:19 +0000820 DEBUG(
Sjoerd Meijer5e11a182016-07-27 08:49:23 +0000821 dbgs() << " Candidate: " << getBlockName(Succ) << ", probability: "
822 << SuccProb
Xinliang David Licbf12142016-06-13 20:24:19 +0000823 << (SuccChain.UnscheduledPredecessors != 0 ? " (CFG break)" : "")
824 << "\n");
Sjoerd Meijer5e11a182016-07-27 08:49:23 +0000825
826 if (BestSucc && BestProb >= SuccProb) {
827 DEBUG(dbgs() << " Not the best candidate, continuing\n");
Chandler Carruthb3361722011-11-13 11:34:53 +0000828 continue;
Sjoerd Meijer5e11a182016-07-27 08:49:23 +0000829 }
830
831 DEBUG(dbgs() << " Setting it as best candidate\n");
Daniel Jaspered9eb722015-02-18 08:19:16 +0000832 BestSucc = Succ;
Cong Houd97c1002015-12-01 05:29:22 +0000833 BestProb = SuccProb;
Chandler Carruthb3361722011-11-13 11:34:53 +0000834 }
Sjoerd Meijer5e11a182016-07-27 08:49:23 +0000835 if (BestSucc)
836 DEBUG(dbgs() << " Selected: " << getBlockName(BestSucc) << "\n");
837
Chandler Carruthb3361722011-11-13 11:34:53 +0000838 return BestSucc;
839}
840
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000841/// \brief Select the best block from a worklist.
842///
843/// This looks through the provided worklist as a list of candidate basic
844/// blocks and select the most profitable one to place. The definition of
845/// profitable only really makes sense in the context of a loop. This returns
846/// the most frequently visited block in the worklist, which in the case of
847/// a loop, is the one most desirable to be physically close to the rest of the
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000848/// loop body in order to improve i-cache behavior.
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000849///
850/// \returns The best block found, or null if none are viable.
851MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
Amaury Sechet9ee4ddd2016-04-07 06:34:47 +0000852 BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList) {
Chandler Carruth0af6a0b2011-11-14 09:46:33 +0000853 // Once we need to walk the worklist looking for a candidate, cleanup the
854 // worklist of already placed entries.
855 // FIXME: If this shows up on profiles, it could be folded (at the cost of
856 // some code complexity) into the loop below.
David Majnemerc7004902016-08-12 04:32:37 +0000857 WorkList.erase(remove_if(WorkList,
858 [&](MachineBasicBlock *BB) {
859 return BlockToChain.lookup(BB) == &Chain;
860 }),
Chandler Carruth0af6a0b2011-11-14 09:46:33 +0000861 WorkList.end());
862
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000863 if (WorkList.empty())
864 return nullptr;
865
866 bool IsEHPad = WorkList[0]->isEHPad();
867
Craig Topperc0196b12014-04-14 00:51:57 +0000868 MachineBasicBlock *BestBlock = nullptr;
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000869 BlockFrequency BestFreq;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000870 for (MachineBasicBlock *MBB : WorkList) {
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000871 assert(MBB->isEHPad() == IsEHPad);
872
Chandler Carruth7a715da2015-03-05 03:19:05 +0000873 BlockChain &SuccChain = *BlockToChain[MBB];
Philip Reames02e11322016-03-02 22:40:51 +0000874 if (&SuccChain == &Chain)
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000875 continue;
Junmo Park4ba6cf62016-03-11 05:07:07 +0000876
Philip Reamesae27b232016-03-03 00:58:43 +0000877 assert(SuccChain.UnscheduledPredecessors == 0 && "Found CFG-violating block");
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000878
Chandler Carruth7a715da2015-03-05 03:19:05 +0000879 BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
880 DEBUG(dbgs() << " " << getBlockName(MBB) << " -> ";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000881 MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000882
883 // For ehpad, we layout the least probable first as to avoid jumping back
884 // from least probable landingpads to more probable ones.
885 //
886 // FIXME: Using probability is probably (!) not the best way to achieve
887 // this. We should probably have a more principled approach to layout
888 // cleanup code.
889 //
890 // The goal is to get:
891 //
892 // +--------------------------+
893 // | V
894 // InnerLp -> InnerCleanup OuterLp -> OuterCleanup -> Resume
895 //
896 // Rather than:
897 //
898 // +-------------------------------------+
899 // V |
900 // OuterLp -> OuterCleanup -> Resume InnerLp -> InnerCleanup
901 if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq)))
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000902 continue;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000903
Chandler Carruth7a715da2015-03-05 03:19:05 +0000904 BestBlock = MBB;
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000905 BestFreq = CandidateFreq;
906 }
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000907
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000908 return BestBlock;
909}
910
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000911/// \brief Retrieve the first unplaced basic block.
912///
913/// This routine is called when we are unable to use the CFG to walk through
914/// all of the basic blocks and form a chain due to unnatural loops in the CFG.
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000915/// We walk through the function's blocks in order, starting from the
916/// LastUnplacedBlockIt. We update this iterator on each call to avoid
917/// re-scanning the entire sequence on repeated calls to this routine.
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000918MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
Xinliang David Li52530a72016-06-13 22:23:44 +0000919 const BlockChain &PlacedChain,
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000920 MachineFunction::iterator &PrevUnplacedBlockIt,
Jakub Staszak90616162011-12-21 23:02:08 +0000921 const BlockFilterSet *BlockFilter) {
Xinliang David Li52530a72016-06-13 22:23:44 +0000922 for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F->end(); I != E;
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000923 ++I) {
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +0000924 if (BlockFilter && !BlockFilter->count(&*I))
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000925 continue;
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +0000926 if (BlockToChain[&*I] != &PlacedChain) {
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000927 PrevUnplacedBlockIt = I;
Chandler Carruth4a87aa02011-11-23 03:03:21 +0000928 // Now select the head of the chain to which the unplaced block belongs
929 // as the block to place. This will force the entire chain to be placed,
930 // and satisfies the requirements of merging chains.
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +0000931 return *BlockToChain[&*I]->begin();
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000932 }
933 }
Craig Topperc0196b12014-04-14 00:51:57 +0000934 return nullptr;
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000935}
936
Amaury Secheteae09c22016-03-14 21:24:11 +0000937void MachineBlockPlacement::fillWorkLists(
938 MachineBasicBlock *MBB,
939 SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
Amaury Secheteae09c22016-03-14 21:24:11 +0000940 const BlockFilterSet *BlockFilter = nullptr) {
941 BlockChain &Chain = *BlockToChain[MBB];
942 if (!UpdatedPreds.insert(&Chain).second)
943 return;
944
945 assert(Chain.UnscheduledPredecessors == 0);
946 for (MachineBasicBlock *ChainBB : Chain) {
947 assert(BlockToChain[ChainBB] == &Chain);
948 for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
949 if (BlockFilter && !BlockFilter->count(Pred))
950 continue;
951 if (BlockToChain[Pred] == &Chain)
952 continue;
953 ++Chain.UnscheduledPredecessors;
954 }
955 }
956
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000957 if (Chain.UnscheduledPredecessors != 0)
958 return;
959
960 MBB = *Chain.begin();
961 if (MBB->isEHPad())
962 EHPadWorkList.push_back(MBB);
963 else
964 BlockWorkList.push_back(MBB);
Amaury Secheteae09c22016-03-14 21:24:11 +0000965}
966
Chandler Carruth8d150782011-11-13 11:20:44 +0000967void MachineBlockPlacement::buildChain(
Daniel Jasper471e8562015-03-04 11:05:34 +0000968 MachineBasicBlock *BB, BlockChain &Chain,
Kyle Butt0846e562016-10-11 20:36:43 +0000969 BlockFilterSet *BlockFilter) {
Kyle Buttb3875ea2016-06-17 22:40:19 +0000970 assert(BB && "BB must not be null.\n");
971 assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match.\n");
Xinliang David Li52530a72016-06-13 22:23:44 +0000972 MachineFunction::iterator PrevUnplacedBlockIt = F->begin();
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000973
Chandler Carruth8d150782011-11-13 11:20:44 +0000974 MachineBasicBlock *LoopHeaderBB = BB;
Xinliang David Li93926ac2016-07-01 05:46:48 +0000975 markChainSuccessors(Chain, LoopHeaderBB, BlockFilter);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000976 BB = *std::prev(Chain.end());
Chandler Carruth8d150782011-11-13 11:20:44 +0000977 for (;;) {
Kyle Butt82c22902016-06-28 22:50:54 +0000978 assert(BB && "null block found at end of chain in loop.");
979 assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match in loop.");
980 assert(*std::prev(Chain.end()) == BB && "BB Not found at end of chain.");
981
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000982
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +0000983 // Look for the best viable successor if there is one to place immediately
984 // after this block.
Duncan Sands291d47e2012-09-14 09:00:11 +0000985 MachineBasicBlock *BestSucc = selectBestSuccessor(BB, Chain, BlockFilter);
Chandler Carruth8d150782011-11-13 11:20:44 +0000986
987 // If an immediate successor isn't available, look for the best viable
988 // block among those we've identified as not violating the loop's CFG at
989 // this point. This won't be a fallthrough, but it will increase locality.
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000990 if (!BestSucc)
Amaury Sechet9ee4ddd2016-04-07 06:34:47 +0000991 BestSucc = selectBestCandidateBlock(Chain, BlockWorkList);
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000992 if (!BestSucc)
993 BestSucc = selectBestCandidateBlock(Chain, EHPadWorkList);
Chandler Carruth8d150782011-11-13 11:20:44 +0000994
Chandler Carruth8d150782011-11-13 11:20:44 +0000995 if (!BestSucc) {
Xinliang David Li52530a72016-06-13 22:23:44 +0000996 BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockIt, BlockFilter);
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000997 if (!BestSucc)
998 break;
999
1000 DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
1001 "layout successor until the CFG reduces\n");
Chandler Carruth8d150782011-11-13 11:20:44 +00001002 }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001003
Kyle Butt0846e562016-10-11 20:36:43 +00001004 // Placement may have changed tail duplication opportunities.
1005 // Check for that now.
1006 if (TailDupPlacement && BestSucc) {
1007 // If the chosen successor was duplicated into all its predecessors,
1008 // don't bother laying it out, just go round the loop again with BB as
1009 // the chain end.
1010 if (repeatedlyTailDuplicateBlock(BestSucc, BB, LoopHeaderBB, Chain,
1011 BlockFilter, PrevUnplacedBlockIt))
1012 continue;
1013 }
1014
Chandler Carruth8d150782011-11-13 11:20:44 +00001015 // Place this block, updating the datastructures to reflect its placement.
Jakub Staszak90616162011-12-21 23:02:08 +00001016 BlockChain &SuccChain = *BlockToChain[BestSucc];
Philip Reamesae27b232016-03-03 00:58:43 +00001017 // Zero out UnscheduledPredecessors for the successor we're about to merge in case
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001018 // we selected a successor that didn't fit naturally into the CFG.
Philip Reamesae27b232016-03-03 00:58:43 +00001019 SuccChain.UnscheduledPredecessors = 0;
Philip Reamesb9688f42016-03-02 21:45:13 +00001020 DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to "
1021 << getBlockName(BestSucc) << "\n");
Xinliang David Li93926ac2016-07-01 05:46:48 +00001022 markChainSuccessors(SuccChain, LoopHeaderBB, BlockFilter);
Chandler Carruth8d150782011-11-13 11:20:44 +00001023 Chain.merge(BestSucc, &SuccChain);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001024 BB = *std::prev(Chain.end());
Jakub Staszak190c7122011-12-07 19:46:10 +00001025 }
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001026
1027 DEBUG(dbgs() << "Finished forming chain for header block "
Philip Reamesb9688f42016-03-02 21:45:13 +00001028 << getBlockName(*Chain.begin()) << "\n");
Chandler Carruth10281422011-10-21 06:46:38 +00001029}
1030
Chandler Carruth03adbd42011-11-27 13:34:33 +00001031/// \brief Find the best loop top block for layout.
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001032///
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001033/// Look for a block which is strictly better than the loop header for laying
1034/// out at the top of the loop. This looks for one and only one pattern:
1035/// a latch block with no conditional exit. This block will cause a conditional
1036/// jump around it or will be the bottom of the loop if we lay it out in place,
1037/// but if it it doesn't end up at the bottom of the loop for any reason,
1038/// rotation alone won't fix it. Because such a block will always result in an
1039/// unconditional jump (for the backedge) rotating it in front of the loop
1040/// header is always profitable.
1041MachineBasicBlock *
1042MachineBlockPlacement::findBestLoopTop(MachineLoop &L,
1043 const BlockFilterSet &LoopBlockSet) {
Sjoerd Meijer15c81b02016-08-16 19:50:33 +00001044 // Placing the latch block before the header may introduce an extra branch
1045 // that skips this block the first time the loop is executed, which we want
1046 // to avoid when optimising for size.
1047 // FIXME: in theory there is a case that does not introduce a new branch,
1048 // i.e. when the layout predecessor does not fallthrough to the loop header.
1049 // In practice this never happens though: there always seems to be a preheader
1050 // that can fallthrough and that is also placed before the header.
1051 if (F->getFunction()->optForSize())
1052 return L.getHeader();
1053
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001054 // Check that the header hasn't been fused with a preheader block due to
1055 // crazy branches. If it has, we need to start with the header at the top to
1056 // prevent pulling the preheader into the loop body.
1057 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
1058 if (!LoopBlockSet.count(*HeaderChain.begin()))
1059 return L.getHeader();
1060
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001061 DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(L.getHeader())
1062 << "\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001063
1064 BlockFrequency BestPredFreq;
Craig Topperc0196b12014-04-14 00:51:57 +00001065 MachineBasicBlock *BestPred = nullptr;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001066 for (MachineBasicBlock *Pred : L.getHeader()->predecessors()) {
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001067 if (!LoopBlockSet.count(Pred))
1068 continue;
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001069 DEBUG(dbgs() << " header pred: " << getBlockName(Pred) << ", has "
Michael Gottesmanb78dec82013-12-14 00:25:45 +00001070 << Pred->succ_size() << " successors, ";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001071 MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001072 if (Pred->succ_size() > 1)
1073 continue;
1074
1075 BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
1076 if (!BestPred || PredFreq > BestPredFreq ||
1077 (!(PredFreq < BestPredFreq) &&
1078 Pred->isLayoutSuccessor(L.getHeader()))) {
1079 BestPred = Pred;
1080 BestPredFreq = PredFreq;
1081 }
1082 }
1083
1084 // If no direct predecessor is fine, just use the loop header.
Philip Reamesb9688f42016-03-02 21:45:13 +00001085 if (!BestPred) {
1086 DEBUG(dbgs() << " final top unchanged\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001087 return L.getHeader();
Philip Reamesb9688f42016-03-02 21:45:13 +00001088 }
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001089
1090 // Walk backwards through any straight line of predecessors.
1091 while (BestPred->pred_size() == 1 &&
1092 (*BestPred->pred_begin())->succ_size() == 1 &&
1093 *BestPred->pred_begin() != L.getHeader())
1094 BestPred = *BestPred->pred_begin();
1095
1096 DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n");
1097 return BestPred;
1098}
1099
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001100/// \brief Find the best loop exiting block for layout.
1101///
Chandler Carruth03adbd42011-11-27 13:34:33 +00001102/// This routine implements the logic to analyze the loop looking for the best
1103/// block to layout at the top of the loop. Typically this is done to maximize
1104/// fallthrough opportunities.
1105MachineBasicBlock *
Xinliang David Li52530a72016-06-13 22:23:44 +00001106MachineBlockPlacement::findBestLoopExit(MachineLoop &L,
Chandler Carruthccc7e422012-04-16 01:12:56 +00001107 const BlockFilterSet &LoopBlockSet) {
Chandler Carruth68062612012-04-10 13:35:57 +00001108 // We don't want to layout the loop linearly in all cases. If the loop header
1109 // is just a normal basic block in the loop, we want to look for what block
1110 // within the loop is the best one to layout at the top. However, if the loop
1111 // header has be pre-merged into a chain due to predecessors not having
1112 // analyzable branches, *and* the predecessor it is merged with is *not* part
1113 // of the loop, rotating the header into the middle of the loop will create
1114 // a non-contiguous range of blocks which is Very Bad. So start with the
1115 // header and only rotate if safe.
1116 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
1117 if (!LoopBlockSet.count(*HeaderChain.begin()))
Craig Topperc0196b12014-04-14 00:51:57 +00001118 return nullptr;
Chandler Carruth68062612012-04-10 13:35:57 +00001119
Chandler Carruth03adbd42011-11-27 13:34:33 +00001120 BlockFrequency BestExitEdgeFreq;
Chandler Carruthccc7e422012-04-16 01:12:56 +00001121 unsigned BestExitLoopDepth = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00001122 MachineBasicBlock *ExitingBB = nullptr;
Chandler Carruth4f567202011-11-27 20:18:00 +00001123 // If there are exits to outer loops, loop rotation can severely limit
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001124 // fallthrough opportunities unless it selects such an exit. Keep a set of
Chandler Carruth4f567202011-11-27 20:18:00 +00001125 // blocks where rotating to exit with that block will reach an outer loop.
1126 SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
1127
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001128 DEBUG(dbgs() << "Finding best loop exit for: " << getBlockName(L.getHeader())
1129 << "\n");
Chandler Carruth7a715da2015-03-05 03:19:05 +00001130 for (MachineBasicBlock *MBB : L.getBlocks()) {
1131 BlockChain &Chain = *BlockToChain[MBB];
Chandler Carruth03adbd42011-11-27 13:34:33 +00001132 // Ensure that this block is at the end of a chain; otherwise it could be
Chandler Carruth9a512a42015-04-15 13:19:54 +00001133 // mid-way through an inner loop or a successor of an unanalyzable branch.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001134 if (MBB != *std::prev(Chain.end()))
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001135 continue;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001136
Chandler Carruth03adbd42011-11-27 13:34:33 +00001137 // Now walk the successors. We need to establish whether this has a viable
1138 // exiting successor and whether it has a viable non-exiting successor.
1139 // We store the old exiting state and restore it if a viable looping
1140 // successor isn't found.
1141 MachineBasicBlock *OldExitingBB = ExitingBB;
1142 BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
Chandler Carruthccc7e422012-04-16 01:12:56 +00001143 bool HasLoopingSucc = false;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001144 for (MachineBasicBlock *Succ : MBB->successors()) {
Reid Kleckner0e288232015-08-27 23:27:47 +00001145 if (Succ->isEHPad())
Chandler Carruth03adbd42011-11-27 13:34:33 +00001146 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001147 if (Succ == MBB)
Chandler Carruth03adbd42011-11-27 13:34:33 +00001148 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001149 BlockChain &SuccChain = *BlockToChain[Succ];
Chandler Carruth03adbd42011-11-27 13:34:33 +00001150 // Don't split chains, either this chain or the successor's chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +00001151 if (&Chain == &SuccChain) {
Chandler Carruth7a715da2015-03-05 03:19:05 +00001152 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
1153 << getBlockName(Succ) << " (chain conflict)\n");
Chandler Carruth03adbd42011-11-27 13:34:33 +00001154 continue;
1155 }
1156
Cong Houd97c1002015-12-01 05:29:22 +00001157 auto SuccProb = MBPI->getEdgeProbability(MBB, Succ);
Chandler Carruth7a715da2015-03-05 03:19:05 +00001158 if (LoopBlockSet.count(Succ)) {
1159 DEBUG(dbgs() << " looping: " << getBlockName(MBB) << " -> "
Cong Houd97c1002015-12-01 05:29:22 +00001160 << getBlockName(Succ) << " (" << SuccProb << ")\n");
Chandler Carruthccc7e422012-04-16 01:12:56 +00001161 HasLoopingSucc = true;
Chandler Carruth03adbd42011-11-27 13:34:33 +00001162 continue;
1163 }
1164
Chandler Carruthccc7e422012-04-16 01:12:56 +00001165 unsigned SuccLoopDepth = 0;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001166 if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
Chandler Carruthccc7e422012-04-16 01:12:56 +00001167 SuccLoopDepth = ExitLoop->getLoopDepth();
1168 if (ExitLoop->contains(&L))
Chandler Carruth7a715da2015-03-05 03:19:05 +00001169 BlocksExitingToOuterLoop.insert(MBB);
Chandler Carruthccc7e422012-04-16 01:12:56 +00001170 }
1171
Chandler Carruth7a715da2015-03-05 03:19:05 +00001172 BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
1173 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
1174 << getBlockName(Succ) << " [L:" << SuccLoopDepth << "] (";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001175 MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
Benjamin Kramerc8160d62013-11-20 19:08:44 +00001176 // Note that we bias this toward an existing layout successor to retain
1177 // incoming order in the absence of better information. The exit must have
1178 // a frequency higher than the current exit before we consider breaking
1179 // the layout.
1180 BranchProbability Bias(100 - ExitBlockBias, 100);
Chandler Carruth26d30172015-04-15 13:39:42 +00001181 if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
Chandler Carruthccc7e422012-04-16 01:12:56 +00001182 ExitEdgeFreq > BestExitEdgeFreq ||
Chandler Carruth7a715da2015-03-05 03:19:05 +00001183 (MBB->isLayoutSuccessor(Succ) &&
Benjamin Kramerc8160d62013-11-20 19:08:44 +00001184 !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
Chandler Carruth03adbd42011-11-27 13:34:33 +00001185 BestExitEdgeFreq = ExitEdgeFreq;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001186 ExitingBB = MBB;
Chandler Carrutha0545802011-11-27 09:22:53 +00001187 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001188 }
Chandler Carruth03adbd42011-11-27 13:34:33 +00001189
Chandler Carruthccc7e422012-04-16 01:12:56 +00001190 if (!HasLoopingSucc) {
Chandler Carruthcfb2b9d2015-04-15 13:26:41 +00001191 // Restore the old exiting state, no viable looping successor was found.
Chandler Carruth03adbd42011-11-27 13:34:33 +00001192 ExitingBB = OldExitingBB;
1193 BestExitEdgeFreq = OldBestExitEdgeFreq;
Chandler Carruth03adbd42011-11-27 13:34:33 +00001194 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001195 }
Chandler Carruthccc7e422012-04-16 01:12:56 +00001196 // Without a candidate exiting block or with only a single block in the
Chandler Carruth03adbd42011-11-27 13:34:33 +00001197 // loop, just use the loop header to layout the loop.
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001198 if (!ExitingBB) {
1199 DEBUG(dbgs() << " No other candidate exit blocks, using loop header\n");
Craig Topperc0196b12014-04-14 00:51:57 +00001200 return nullptr;
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001201 }
1202 if (L.getNumBlocks() == 1) {
1203 DEBUG(dbgs() << " Loop has 1 block, using loop header as exit\n");
1204 return nullptr;
1205 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001206
Chandler Carruth4f567202011-11-27 20:18:00 +00001207 // Also, if we have exit blocks which lead to outer loops but didn't select
1208 // one of them as the exiting block we are rotating toward, disable loop
1209 // rotation altogether.
1210 if (!BlocksExitingToOuterLoop.empty() &&
1211 !BlocksExitingToOuterLoop.count(ExitingBB))
Craig Topperc0196b12014-04-14 00:51:57 +00001212 return nullptr;
Chandler Carruth4f567202011-11-27 20:18:00 +00001213
Chandler Carruth03adbd42011-11-27 13:34:33 +00001214 DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB) << "\n");
Chandler Carruthccc7e422012-04-16 01:12:56 +00001215 return ExitingBB;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001216}
1217
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001218/// \brief Attempt to rotate an exiting block to the bottom of the loop.
1219///
1220/// Once we have built a chain, try to rotate it to line up the hot exit block
1221/// with fallthrough out of the loop if doing so doesn't introduce unnecessary
1222/// branches. For example, if the loop has fallthrough into its header and out
1223/// of its bottom already, don't rotate it.
1224void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
1225 MachineBasicBlock *ExitingBB,
1226 const BlockFilterSet &LoopBlockSet) {
1227 if (!ExitingBB)
1228 return;
1229
1230 MachineBasicBlock *Top = *LoopChain.begin();
1231 bool ViableTopFallthrough = false;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001232 for (MachineBasicBlock *Pred : Top->predecessors()) {
1233 BlockChain *PredChain = BlockToChain[Pred];
1234 if (!LoopBlockSet.count(Pred) &&
1235 (!PredChain || Pred == *std::prev(PredChain->end()))) {
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001236 ViableTopFallthrough = true;
1237 break;
1238 }
1239 }
1240
1241 // If the header has viable fallthrough, check whether the current loop
1242 // bottom is a viable exiting block. If so, bail out as rotating will
1243 // introduce an unnecessary branch.
1244 if (ViableTopFallthrough) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001245 MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
Chandler Carruth7a715da2015-03-05 03:19:05 +00001246 for (MachineBasicBlock *Succ : Bottom->successors()) {
1247 BlockChain *SuccChain = BlockToChain[Succ];
1248 if (!LoopBlockSet.count(Succ) &&
1249 (!SuccChain || Succ == *SuccChain->begin()))
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001250 return;
1251 }
1252 }
1253
David Majnemer0d955d02016-08-11 22:21:41 +00001254 BlockChain::iterator ExitIt = find(LoopChain, ExitingBB);
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001255 if (ExitIt == LoopChain.end())
1256 return;
1257
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001258 std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001259}
1260
Cong Hou7745dbc2015-10-19 23:16:40 +00001261/// \brief Attempt to rotate a loop based on profile data to reduce branch cost.
1262///
1263/// With profile data, we can determine the cost in terms of missed fall through
1264/// opportunities when rotating a loop chain and select the best rotation.
1265/// Basically, there are three kinds of cost to consider for each rotation:
1266/// 1. The possibly missed fall through edge (if it exists) from BB out of
1267/// the loop to the loop header.
1268/// 2. The possibly missed fall through edges (if they exist) from the loop
1269/// exits to BB out of the loop.
1270/// 3. The missed fall through edge (if it exists) from the last BB to the
1271/// first BB in the loop chain.
1272/// Therefore, the cost for a given rotation is the sum of costs listed above.
1273/// We select the best rotation with the smallest cost.
1274void MachineBlockPlacement::rotateLoopWithProfile(
1275 BlockChain &LoopChain, MachineLoop &L, const BlockFilterSet &LoopBlockSet) {
1276 auto HeaderBB = L.getHeader();
David Majnemer0d955d02016-08-11 22:21:41 +00001277 auto HeaderIter = find(LoopChain, HeaderBB);
Cong Hou7745dbc2015-10-19 23:16:40 +00001278 auto RotationPos = LoopChain.end();
1279
1280 BlockFrequency SmallestRotationCost = BlockFrequency::getMaxFrequency();
1281
1282 // A utility lambda that scales up a block frequency by dividing it by a
1283 // branch probability which is the reciprocal of the scale.
1284 auto ScaleBlockFrequency = [](BlockFrequency Freq,
1285 unsigned Scale) -> BlockFrequency {
1286 if (Scale == 0)
1287 return 0;
1288 // Use operator / between BlockFrequency and BranchProbability to implement
1289 // saturating multiplication.
1290 return Freq / BranchProbability(1, Scale);
1291 };
1292
1293 // Compute the cost of the missed fall-through edge to the loop header if the
1294 // chain head is not the loop header. As we only consider natural loops with
1295 // single header, this computation can be done only once.
1296 BlockFrequency HeaderFallThroughCost(0);
1297 for (auto *Pred : HeaderBB->predecessors()) {
1298 BlockChain *PredChain = BlockToChain[Pred];
1299 if (!LoopBlockSet.count(Pred) &&
1300 (!PredChain || Pred == *std::prev(PredChain->end()))) {
1301 auto EdgeFreq =
1302 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, HeaderBB);
1303 auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost);
1304 // If the predecessor has only an unconditional jump to the header, we
1305 // need to consider the cost of this jump.
1306 if (Pred->succ_size() == 1)
1307 FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost);
1308 HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost);
1309 }
1310 }
1311
1312 // Here we collect all exit blocks in the loop, and for each exit we find out
1313 // its hottest exit edge. For each loop rotation, we define the loop exit cost
1314 // as the sum of frequencies of exit edges we collect here, excluding the exit
1315 // edge from the tail of the loop chain.
1316 SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq;
1317 for (auto BB : LoopChain) {
Cong Houd97c1002015-12-01 05:29:22 +00001318 auto LargestExitEdgeProb = BranchProbability::getZero();
Cong Hou7745dbc2015-10-19 23:16:40 +00001319 for (auto *Succ : BB->successors()) {
1320 BlockChain *SuccChain = BlockToChain[Succ];
1321 if (!LoopBlockSet.count(Succ) &&
1322 (!SuccChain || Succ == *SuccChain->begin())) {
Cong Houd97c1002015-12-01 05:29:22 +00001323 auto SuccProb = MBPI->getEdgeProbability(BB, Succ);
1324 LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb);
Cong Hou7745dbc2015-10-19 23:16:40 +00001325 }
1326 }
Cong Houd97c1002015-12-01 05:29:22 +00001327 if (LargestExitEdgeProb > BranchProbability::getZero()) {
1328 auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb;
Cong Hou7745dbc2015-10-19 23:16:40 +00001329 ExitsWithFreq.emplace_back(BB, ExitFreq);
1330 }
1331 }
1332
1333 // In this loop we iterate every block in the loop chain and calculate the
1334 // cost assuming the block is the head of the loop chain. When the loop ends,
1335 // we should have found the best candidate as the loop chain's head.
1336 for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()),
1337 EndIter = LoopChain.end();
1338 Iter != EndIter; Iter++, TailIter++) {
1339 // TailIter is used to track the tail of the loop chain if the block we are
1340 // checking (pointed by Iter) is the head of the chain.
1341 if (TailIter == LoopChain.end())
1342 TailIter = LoopChain.begin();
1343
1344 auto TailBB = *TailIter;
1345
1346 // Calculate the cost by putting this BB to the top.
1347 BlockFrequency Cost = 0;
1348
1349 // If the current BB is the loop header, we need to take into account the
1350 // cost of the missed fall through edge from outside of the loop to the
1351 // header.
1352 if (Iter != HeaderIter)
1353 Cost += HeaderFallThroughCost;
1354
1355 // Collect the loop exit cost by summing up frequencies of all exit edges
1356 // except the one from the chain tail.
1357 for (auto &ExitWithFreq : ExitsWithFreq)
1358 if (TailBB != ExitWithFreq.first)
1359 Cost += ExitWithFreq.second;
1360
1361 // The cost of breaking the once fall-through edge from the tail to the top
1362 // of the loop chain. Here we need to consider three cases:
1363 // 1. If the tail node has only one successor, then we will get an
1364 // additional jmp instruction. So the cost here is (MisfetchCost +
1365 // JumpInstCost) * tail node frequency.
1366 // 2. If the tail node has two successors, then we may still get an
1367 // additional jmp instruction if the layout successor after the loop
1368 // chain is not its CFG successor. Note that the more frequently executed
1369 // jmp instruction will be put ahead of the other one. Assume the
1370 // frequency of those two branches are x and y, where x is the frequency
1371 // of the edge to the chain head, then the cost will be
1372 // (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency.
1373 // 3. If the tail node has more than two successors (this rarely happens),
1374 // we won't consider any additional cost.
1375 if (TailBB->isSuccessor(*Iter)) {
1376 auto TailBBFreq = MBFI->getBlockFreq(TailBB);
1377 if (TailBB->succ_size() == 1)
1378 Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(),
1379 MisfetchCost + JumpInstCost);
1380 else if (TailBB->succ_size() == 2) {
1381 auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter);
1382 auto TailToHeadFreq = TailBBFreq * TailToHeadProb;
1383 auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2)
1384 ? TailBBFreq * TailToHeadProb.getCompl()
1385 : TailToHeadFreq;
1386 Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) +
1387 ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost);
1388 }
1389 }
1390
Philip Reamesb9688f42016-03-02 21:45:13 +00001391 DEBUG(dbgs() << "The cost of loop rotation by making " << getBlockName(*Iter)
Cong Hou7745dbc2015-10-19 23:16:40 +00001392 << " to the top: " << Cost.getFrequency() << "\n");
1393
1394 if (Cost < SmallestRotationCost) {
1395 SmallestRotationCost = Cost;
1396 RotationPos = Iter;
1397 }
1398 }
1399
1400 if (RotationPos != LoopChain.end()) {
Philip Reamesb9688f42016-03-02 21:45:13 +00001401 DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos)
Cong Hou7745dbc2015-10-19 23:16:40 +00001402 << " to the top\n");
1403 std::rotate(LoopChain.begin(), RotationPos, LoopChain.end());
1404 }
1405}
1406
Cong Houb90b9e02015-11-02 21:24:00 +00001407/// \brief Collect blocks in the given loop that are to be placed.
1408///
1409/// When profile data is available, exclude cold blocks from the returned set;
1410/// otherwise, collect all blocks in the loop.
1411MachineBlockPlacement::BlockFilterSet
Xinliang David Li52530a72016-06-13 22:23:44 +00001412MachineBlockPlacement::collectLoopBlockSet(MachineLoop &L) {
Cong Houb90b9e02015-11-02 21:24:00 +00001413 BlockFilterSet LoopBlockSet;
1414
1415 // Filter cold blocks off from LoopBlockSet when profile data is available.
1416 // Collect the sum of frequencies of incoming edges to the loop header from
1417 // outside. If we treat the loop as a super block, this is the frequency of
1418 // the loop. Then for each block in the loop, we calculate the ratio between
1419 // its frequency and the frequency of the loop block. When it is too small,
1420 // don't add it to the loop chain. If there are outer loops, then this block
1421 // will be merged into the first outer loop chain for which this block is not
1422 // cold anymore. This needs precise profile data and we only do this when
1423 // profile data is available.
Xinliang David Li52530a72016-06-13 22:23:44 +00001424 if (F->getFunction()->getEntryCount()) {
Cong Houb90b9e02015-11-02 21:24:00 +00001425 BlockFrequency LoopFreq(0);
1426 for (auto LoopPred : L.getHeader()->predecessors())
1427 if (!L.contains(LoopPred))
1428 LoopFreq += MBFI->getBlockFreq(LoopPred) *
1429 MBPI->getEdgeProbability(LoopPred, L.getHeader());
1430
1431 for (MachineBasicBlock *LoopBB : L.getBlocks()) {
1432 auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency();
1433 if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio)
1434 continue;
1435 LoopBlockSet.insert(LoopBB);
1436 }
1437 } else
1438 LoopBlockSet.insert(L.block_begin(), L.block_end());
1439
1440 return LoopBlockSet;
1441}
1442
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001443/// \brief Forms basic block chains from the natural loop structures.
Chandler Carruth10281422011-10-21 06:46:38 +00001444///
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001445/// These chains are designed to preserve the existing *structure* of the code
1446/// as much as possible. We can then stitch the chains together in a way which
1447/// both preserves the topological structure and minimizes taken conditional
1448/// branches.
Xinliang David Li52530a72016-06-13 22:23:44 +00001449void MachineBlockPlacement::buildLoopChains(MachineLoop &L) {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001450 // First recurse through any nested loops, building chains for those inner
1451 // loops.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001452 for (MachineLoop *InnerLoop : L)
Xinliang David Li52530a72016-06-13 22:23:44 +00001453 buildLoopChains(*InnerLoop);
Chandler Carruth10281422011-10-21 06:46:38 +00001454
Xinliang David Li93926ac2016-07-01 05:46:48 +00001455 assert(BlockWorkList.empty());
1456 assert(EHPadWorkList.empty());
Xinliang David Li52530a72016-06-13 22:23:44 +00001457 BlockFilterSet LoopBlockSet = collectLoopBlockSet(L);
Chandler Carruth03adbd42011-11-27 13:34:33 +00001458
Cong Hou7745dbc2015-10-19 23:16:40 +00001459 // Check if we have profile data for this function. If yes, we will rotate
1460 // this loop by modeling costs more precisely which requires the profile data
1461 // for better layout.
1462 bool RotateLoopWithProfile =
Xinliang David Lif0ab6df2016-05-12 02:04:41 +00001463 ForcePreciseRotationCost ||
Xinliang David Li52530a72016-06-13 22:23:44 +00001464 (PreciseRotationCost && F->getFunction()->getEntryCount());
Cong Hou7745dbc2015-10-19 23:16:40 +00001465
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001466 // First check to see if there is an obviously preferable top block for the
1467 // loop. This will default to the header, but may end up as one of the
1468 // predecessors to the header if there is one which will result in strictly
1469 // fewer branches in the loop body.
Cong Hou7745dbc2015-10-19 23:16:40 +00001470 // When we use profile data to rotate the loop, this is unnecessary.
1471 MachineBasicBlock *LoopTop =
1472 RotateLoopWithProfile ? L.getHeader() : findBestLoopTop(L, LoopBlockSet);
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001473
1474 // If we selected just the header for the loop top, look for a potentially
1475 // profitable exit block in the event that rotating the loop can eliminate
1476 // branches by placing an exit edge at the bottom.
Craig Topperc0196b12014-04-14 00:51:57 +00001477 MachineBasicBlock *ExitingBB = nullptr;
Cong Hou7745dbc2015-10-19 23:16:40 +00001478 if (!RotateLoopWithProfile && LoopTop == L.getHeader())
Xinliang David Li52530a72016-06-13 22:23:44 +00001479 ExitingBB = findBestLoopExit(L, LoopBlockSet);
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001480
1481 BlockChain &LoopChain = *BlockToChain[LoopTop];
Chandler Carruth10281422011-10-21 06:46:38 +00001482
Chandler Carruth8d150782011-11-13 11:20:44 +00001483 // FIXME: This is a really lame way of walking the chains in the loop: we
1484 // walk the blocks, and use a set to prevent visiting a particular chain
1485 // twice.
Jakub Staszak90616162011-12-21 23:02:08 +00001486 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
Philip Reamesae27b232016-03-03 00:58:43 +00001487 assert(LoopChain.UnscheduledPredecessors == 0);
Jakub Staszak190c7122011-12-07 19:46:10 +00001488 UpdatedPreds.insert(&LoopChain);
Cong Houb90b9e02015-11-02 21:24:00 +00001489
Amaury Secheteae09c22016-03-14 21:24:11 +00001490 for (MachineBasicBlock *LoopBB : LoopBlockSet)
Xinliang David Li93926ac2016-07-01 05:46:48 +00001491 fillWorkLists(LoopBB, UpdatedPreds, &LoopBlockSet);
Chandler Carruth8d150782011-11-13 11:20:44 +00001492
Xinliang David Li93926ac2016-07-01 05:46:48 +00001493 buildChain(LoopTop, LoopChain, &LoopBlockSet);
Cong Hou7745dbc2015-10-19 23:16:40 +00001494
1495 if (RotateLoopWithProfile)
1496 rotateLoopWithProfile(LoopChain, L, LoopBlockSet);
1497 else
1498 rotateLoop(LoopChain, ExitingBB, LoopBlockSet);
Chandler Carruth8d150782011-11-13 11:20:44 +00001499
1500 DEBUG({
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001501 // Crash at the end so we get all of the debugging output first.
1502 bool BadLoop = false;
Philip Reamesae27b232016-03-03 00:58:43 +00001503 if (LoopChain.UnscheduledPredecessors) {
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001504 BadLoop = true;
Chandler Carruth8d150782011-11-13 11:20:44 +00001505 dbgs() << "Loop chain contains a block without its preds placed!\n"
1506 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
1507 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001508 }
Chandler Carruth7a715da2015-03-05 03:19:05 +00001509 for (MachineBasicBlock *ChainBB : LoopChain) {
1510 dbgs() << " ... " << getBlockName(ChainBB) << "\n";
1511 if (!LoopBlockSet.erase(ChainBB)) {
Chandler Carruth0a31d142011-11-14 10:55:53 +00001512 // We don't mark the loop as bad here because there are real situations
1513 // where this can occur. For example, with an unanalyzable fallthrough
Chandler Carruth99fe42f2011-11-23 10:35:36 +00001514 // from a loop block to a non-loop block or vice versa.
Chandler Carruth8d150782011-11-13 11:20:44 +00001515 dbgs() << "Loop chain contains a block not contained by the loop!\n"
1516 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
1517 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00001518 << " Bad block: " << getBlockName(ChainBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001519 }
Chandler Carruthccc7e422012-04-16 01:12:56 +00001520 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001521
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001522 if (!LoopBlockSet.empty()) {
1523 BadLoop = true;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001524 for (MachineBasicBlock *LoopBB : LoopBlockSet)
Chandler Carruth8d150782011-11-13 11:20:44 +00001525 dbgs() << "Loop contains blocks never placed into a chain!\n"
1526 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
1527 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00001528 << " Bad block: " << getBlockName(LoopBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001529 }
1530 assert(!BadLoop && "Detected problems with the placement of this loop.");
Chandler Carruth8d150782011-11-13 11:20:44 +00001531 });
Xinliang David Li93926ac2016-07-01 05:46:48 +00001532
1533 BlockWorkList.clear();
1534 EHPadWorkList.clear();
Chandler Carruth10281422011-10-21 06:46:38 +00001535}
1536
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001537/// When OutlineOpitonalBranches is on, this method collects BBs that
Xinliang David Li071d0f12016-06-12 16:54:03 +00001538/// dominates all terminator blocks of the function \p F.
Xinliang David Li52530a72016-06-13 22:23:44 +00001539void MachineBlockPlacement::collectMustExecuteBBs() {
Xinliang David Li071d0f12016-06-12 16:54:03 +00001540 if (OutlineOptionalBranches) {
1541 // Find the nearest common dominator of all of F's terminators.
1542 MachineBasicBlock *Terminator = nullptr;
Xinliang David Li52530a72016-06-13 22:23:44 +00001543 for (MachineBasicBlock &MBB : *F) {
Xinliang David Li071d0f12016-06-12 16:54:03 +00001544 if (MBB.succ_size() == 0) {
1545 if (Terminator == nullptr)
1546 Terminator = &MBB;
1547 else
1548 Terminator = MDT->findNearestCommonDominator(Terminator, &MBB);
1549 }
1550 }
1551
1552 // MBBs dominating this common dominator are unavoidable.
1553 UnavoidableBlocks.clear();
Xinliang David Li52530a72016-06-13 22:23:44 +00001554 for (MachineBasicBlock &MBB : *F) {
Xinliang David Li071d0f12016-06-12 16:54:03 +00001555 if (MDT->dominates(&MBB, Terminator)) {
1556 UnavoidableBlocks.insert(&MBB);
1557 }
1558 }
1559 }
1560}
1561
Xinliang David Li52530a72016-06-13 22:23:44 +00001562void MachineBlockPlacement::buildCFGChains() {
Chandler Carruth8d150782011-11-13 11:20:44 +00001563 // Ensure that every BB in the function has an associated chain to simplify
1564 // the assumptions of the remaining algorithm.
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001565 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
Xinliang David Li52530a72016-06-13 22:23:44 +00001566 for (MachineFunction::iterator FI = F->begin(), FE = F->end(); FI != FE;
1567 ++FI) {
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001568 MachineBasicBlock *BB = &*FI;
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001569 BlockChain *Chain =
1570 new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001571 // Also, merge any blocks which we cannot reason about and must preserve
1572 // the exact fallthrough behavior for.
1573 for (;;) {
1574 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001575 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Jacques Pienaar71c30a12016-07-15 14:41:04 +00001576 if (!TII->analyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001577 break;
1578
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001579 MachineFunction::iterator NextFI = std::next(FI);
1580 MachineBasicBlock *NextBB = &*NextFI;
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001581 // Ensure that the layout successor is a viable block, as we know that
1582 // fallthrough is a possibility.
1583 assert(NextFI != FE && "Can't fallthrough past the last block.");
1584 DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
1585 << getBlockName(BB) << " -> " << getBlockName(NextBB)
1586 << "\n");
Craig Topperc0196b12014-04-14 00:51:57 +00001587 Chain->merge(NextBB, nullptr);
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001588 FI = NextFI;
1589 BB = NextBB;
1590 }
1591 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001592
Xinliang David Li071d0f12016-06-12 16:54:03 +00001593 // Turned on with OutlineOptionalBranches option
Xinliang David Li52530a72016-06-13 22:23:44 +00001594 collectMustExecuteBBs();
Daniel Jasper471e8562015-03-04 11:05:34 +00001595
Chandler Carruth8d150782011-11-13 11:20:44 +00001596 // Build any loop-based chains.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001597 for (MachineLoop *L : *MLI)
Xinliang David Li52530a72016-06-13 22:23:44 +00001598 buildLoopChains(*L);
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001599
Xinliang David Li93926ac2016-07-01 05:46:48 +00001600 assert(BlockWorkList.empty());
1601 assert(EHPadWorkList.empty());
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001602
Chandler Carruth8d150782011-11-13 11:20:44 +00001603 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
Xinliang David Li52530a72016-06-13 22:23:44 +00001604 for (MachineBasicBlock &MBB : *F)
Xinliang David Li93926ac2016-07-01 05:46:48 +00001605 fillWorkLists(&MBB, UpdatedPreds);
Chandler Carruth8d150782011-11-13 11:20:44 +00001606
Xinliang David Li52530a72016-06-13 22:23:44 +00001607 BlockChain &FunctionChain = *BlockToChain[&F->front()];
Xinliang David Li93926ac2016-07-01 05:46:48 +00001608 buildChain(&F->front(), FunctionChain);
Chandler Carruth8d150782011-11-13 11:20:44 +00001609
Matt Arsenault0f5f0152013-12-10 18:55:37 +00001610#ifndef NDEBUG
Matt Arsenault79d55f52013-12-05 20:02:18 +00001611 typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType;
Matt Arsenault0f5f0152013-12-10 18:55:37 +00001612#endif
Chandler Carruth8d150782011-11-13 11:20:44 +00001613 DEBUG({
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001614 // Crash at the end so we get all of the debugging output first.
1615 bool BadFunc = false;
Chandler Carruth8d150782011-11-13 11:20:44 +00001616 FunctionBlockSetType FunctionBlockSet;
Xinliang David Li52530a72016-06-13 22:23:44 +00001617 for (MachineBasicBlock &MBB : *F)
Chandler Carruth7a715da2015-03-05 03:19:05 +00001618 FunctionBlockSet.insert(&MBB);
Chandler Carruth8d150782011-11-13 11:20:44 +00001619
Chandler Carruth7a715da2015-03-05 03:19:05 +00001620 for (MachineBasicBlock *ChainBB : FunctionChain)
1621 if (!FunctionBlockSet.erase(ChainBB)) {
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001622 BadFunc = true;
Chandler Carruth8d150782011-11-13 11:20:44 +00001623 dbgs() << "Function chain contains a block not in the function!\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00001624 << " Bad block: " << getBlockName(ChainBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001625 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001626
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001627 if (!FunctionBlockSet.empty()) {
1628 BadFunc = true;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001629 for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
Chandler Carruth8d150782011-11-13 11:20:44 +00001630 dbgs() << "Function contains blocks never placed into a chain!\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00001631 << " Bad block: " << getBlockName(RemainingBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001632 }
1633 assert(!BadFunc && "Detected problems with the block placement.");
Chandler Carruth8d150782011-11-13 11:20:44 +00001634 });
1635
1636 // Splice the blocks into place.
Xinliang David Li52530a72016-06-13 22:23:44 +00001637 MachineFunction::iterator InsertPos = F->begin();
Xinliang David Li449cdfd2016-06-24 22:54:21 +00001638 DEBUG(dbgs() << "[MBP] Function: "<< F->getName() << "\n");
Chandler Carruth7a715da2015-03-05 03:19:05 +00001639 for (MachineBasicBlock *ChainBB : FunctionChain) {
1640 DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
1641 : " ... ")
1642 << getBlockName(ChainBB) << "\n");
1643 if (InsertPos != MachineFunction::iterator(ChainBB))
Xinliang David Li52530a72016-06-13 22:23:44 +00001644 F->splice(InsertPos, ChainBB);
Chandler Carruth8d150782011-11-13 11:20:44 +00001645 else
1646 ++InsertPos;
1647
1648 // Update the terminator of the previous block.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001649 if (ChainBB == *FunctionChain.begin())
Chandler Carruth8d150782011-11-13 11:20:44 +00001650 continue;
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001651 MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB));
Chandler Carruth8d150782011-11-13 11:20:44 +00001652
Chandler Carruth10281422011-10-21 06:46:38 +00001653 // FIXME: It would be awesome of updateTerminator would just return rather
1654 // than assert when the branch cannot be analyzed in order to remove this
1655 // boiler plate.
1656 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001657 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001658
Haicheng Wu90a55652016-05-24 22:16:14 +00001659 // The "PrevBB" is not yet updated to reflect current code layout, so,
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001660 // o. it may fall-through to a block without explicit "goto" instruction
Haicheng Wu90a55652016-05-24 22:16:14 +00001661 // before layout, and no longer fall-through it after layout; or
1662 // o. just opposite.
1663 //
Jacques Pienaar71c30a12016-07-15 14:41:04 +00001664 // analyzeBranch() may return erroneous value for FBB when these two
Haicheng Wu90a55652016-05-24 22:16:14 +00001665 // situations take place. For the first scenario FBB is mistakenly set NULL;
1666 // for the 2nd scenario, the FBB, which is expected to be NULL, is
1667 // mistakenly pointing to "*BI".
1668 // Thus, if the future change needs to use FBB before the layout is set, it
1669 // has to correct FBB first by using the code similar to the following:
1670 //
1671 // if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
1672 // PrevBB->updateTerminator();
1673 // Cond.clear();
1674 // TBB = FBB = nullptr;
Jacques Pienaar71c30a12016-07-15 14:41:04 +00001675 // if (TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) {
Haicheng Wu90a55652016-05-24 22:16:14 +00001676 // // FIXME: This should never take place.
1677 // TBB = FBB = nullptr;
1678 // }
1679 // }
Jacques Pienaar71c30a12016-07-15 14:41:04 +00001680 if (!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond))
Haicheng Wu90a55652016-05-24 22:16:14 +00001681 PrevBB->updateTerminator();
Chandler Carruth10281422011-10-21 06:46:38 +00001682 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001683
1684 // Fixup the last block.
1685 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001686 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Jacques Pienaar71c30a12016-07-15 14:41:04 +00001687 if (!TII->analyzeBranch(F->back(), TBB, FBB, Cond))
Xinliang David Li52530a72016-06-13 22:23:44 +00001688 F->back().updateTerminator();
Xinliang David Li93926ac2016-07-01 05:46:48 +00001689
1690 BlockWorkList.clear();
1691 EHPadWorkList.clear();
Haicheng Wu90a55652016-05-24 22:16:14 +00001692}
1693
Xinliang David Li52530a72016-06-13 22:23:44 +00001694void MachineBlockPlacement::optimizeBranches() {
1695 BlockChain &FunctionChain = *BlockToChain[&F->front()];
Haicheng Wu90a55652016-05-24 22:16:14 +00001696 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
Quentin Colombet776e6de2016-05-02 22:58:59 +00001697
1698 // Now that all the basic blocks in the chain have the proper layout,
1699 // make a final call to AnalyzeBranch with AllowModify set.
1700 // Indeed, the target may be able to optimize the branches in a way we
1701 // cannot because all branches may not be analyzable.
1702 // E.g., the target may be able to remove an unconditional branch to
1703 // a fallthrough when it occurs after predicated terminators.
1704 for (MachineBasicBlock *ChainBB : FunctionChain) {
1705 Cond.clear();
Haicheng Wu90a55652016-05-24 22:16:14 +00001706 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Jacques Pienaar71c30a12016-07-15 14:41:04 +00001707 if (!TII->analyzeBranch(*ChainBB, TBB, FBB, Cond, /*AllowModify*/ true)) {
Haicheng Wu90a55652016-05-24 22:16:14 +00001708 // If PrevBB has a two-way branch, try to re-order the branches
1709 // such that we branch to the successor with higher probability first.
1710 if (TBB && !Cond.empty() && FBB &&
1711 MBPI->getEdgeProbability(ChainBB, FBB) >
1712 MBPI->getEdgeProbability(ChainBB, TBB) &&
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001713 !TII->reverseBranchCondition(Cond)) {
Haicheng Wu90a55652016-05-24 22:16:14 +00001714 DEBUG(dbgs() << "Reverse order of the two branches: "
1715 << getBlockName(ChainBB) << "\n");
1716 DEBUG(dbgs() << " Edge probability: "
1717 << MBPI->getEdgeProbability(ChainBB, FBB) << " vs "
1718 << MBPI->getEdgeProbability(ChainBB, TBB) << "\n");
1719 DebugLoc dl; // FIXME: this is nowhere
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001720 TII->removeBranch(*ChainBB);
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00001721 TII->insertBranch(*ChainBB, FBB, TBB, Cond, dl);
Haicheng Wu90a55652016-05-24 22:16:14 +00001722 ChainBB->updateTerminator();
1723 }
1724 }
Quentin Colombet776e6de2016-05-02 22:58:59 +00001725 }
Haicheng Wue749ce52016-04-29 17:06:44 +00001726}
Chandler Carruth10281422011-10-21 06:46:38 +00001727
Xinliang David Li52530a72016-06-13 22:23:44 +00001728void MachineBlockPlacement::alignBlocks() {
Chandler Carruthccc7e422012-04-16 01:12:56 +00001729 // Walk through the backedges of the function now that we have fully laid out
1730 // the basic blocks and align the destination of each backedge. We don't rely
Chandler Carruth881d0a72012-08-07 09:45:24 +00001731 // exclusively on the loop info here so that we can align backedges in
1732 // unnatural CFGs and backedges that were introduced purely because of the
1733 // loop rotations done during this layout pass.
Xinliang David Li52530a72016-06-13 22:23:44 +00001734 if (F->getFunction()->optForSize())
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001735 return;
Xinliang David Li52530a72016-06-13 22:23:44 +00001736 BlockChain &FunctionChain = *BlockToChain[&F->front()];
Chandler Carruth881d0a72012-08-07 09:45:24 +00001737 if (FunctionChain.begin() == FunctionChain.end())
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001738 return; // Empty chain.
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001739
Chandler Carruth881d0a72012-08-07 09:45:24 +00001740 const BranchProbability ColdProb(1, 5); // 20%
Xinliang David Li52530a72016-06-13 22:23:44 +00001741 BlockFrequency EntryFreq = MBFI->getBlockFreq(&F->front());
Chandler Carruth881d0a72012-08-07 09:45:24 +00001742 BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001743 for (MachineBasicBlock *ChainBB : FunctionChain) {
1744 if (ChainBB == *FunctionChain.begin())
1745 continue;
1746
Chandler Carruth881d0a72012-08-07 09:45:24 +00001747 // Don't align non-looping basic blocks. These are unlikely to execute
1748 // enough times to matter in practice. Note that we'll still handle
1749 // unnatural CFGs inside of a natural outer loop (the common case) and
1750 // rotated loops.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001751 MachineLoop *L = MLI->getLoopFor(ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001752 if (!L)
1753 continue;
1754
Hal Finkel57725662015-01-03 17:58:24 +00001755 unsigned Align = TLI->getPrefLoopAlignment(L);
1756 if (!Align)
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001757 continue; // Don't care about loop alignment.
Hal Finkel57725662015-01-03 17:58:24 +00001758
Chandler Carruth881d0a72012-08-07 09:45:24 +00001759 // If the block is cold relative to the function entry don't waste space
1760 // aligning it.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001761 BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001762 if (Freq < WeightedEntryFreq)
1763 continue;
1764
1765 // If the block is cold relative to its loop header, don't align it
1766 // regardless of what edges into the block exist.
1767 MachineBasicBlock *LoopHeader = L->getHeader();
1768 BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
1769 if (Freq < (LoopHeaderFreq * ColdProb))
1770 continue;
1771
1772 // Check for the existence of a non-layout predecessor which would benefit
1773 // from aligning this block.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001774 MachineBasicBlock *LayoutPred =
1775 &*std::prev(MachineFunction::iterator(ChainBB));
Chandler Carruth881d0a72012-08-07 09:45:24 +00001776
1777 // Force alignment if all the predecessors are jumps. We already checked
1778 // that the block isn't cold above.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001779 if (!LayoutPred->isSuccessor(ChainBB)) {
1780 ChainBB->setAlignment(Align);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001781 continue;
1782 }
1783
1784 // Align this block if the layout predecessor's edge into this block is
Nadav Rotem6036f582013-03-29 16:34:23 +00001785 // cold relative to the block. When this is true, other predecessors make up
Chandler Carruth881d0a72012-08-07 09:45:24 +00001786 // all of the hot entries into the block and thus alignment is likely to be
1787 // important.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001788 BranchProbability LayoutProb =
1789 MBPI->getEdgeProbability(LayoutPred, ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001790 BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
1791 if (LayoutEdgeFreq <= (Freq * ColdProb))
Chandler Carruth7a715da2015-03-05 03:19:05 +00001792 ChainBB->setAlignment(Align);
Chandler Carruthccc7e422012-04-16 01:12:56 +00001793 }
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001794}
1795
Kyle Butt0846e562016-10-11 20:36:43 +00001796/// Tail duplicate \p BB into (some) predecessors if profitable, repeating if
1797/// it was duplicated into its chain predecessor and removed.
1798/// \p BB - Basic block that may be duplicated.
1799///
1800/// \p LPred - Chosen layout predecessor of \p BB.
1801/// Updated to be the chain end if LPred is removed.
1802/// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
1803/// \p BlockFilter - Set of blocks that belong to the loop being laid out.
1804/// Used to identify which blocks to update predecessor
1805/// counts.
1806/// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
1807/// chosen in the given order due to unnatural CFG
1808/// only needed if \p BB is removed and
1809/// \p PrevUnplacedBlockIt pointed to \p BB.
1810/// @return true if \p BB was removed.
1811bool MachineBlockPlacement::repeatedlyTailDuplicateBlock(
1812 MachineBasicBlock *BB, MachineBasicBlock *&LPred,
1813 MachineBasicBlock *LoopHeaderBB,
1814 BlockChain &Chain, BlockFilterSet *BlockFilter,
1815 MachineFunction::iterator &PrevUnplacedBlockIt) {
1816 bool Removed, DuplicatedToLPred;
1817 bool DuplicatedToOriginalLPred;
1818 Removed = maybeTailDuplicateBlock(BB, LPred, Chain, BlockFilter,
1819 PrevUnplacedBlockIt,
1820 DuplicatedToLPred);
1821 if (!Removed)
1822 return false;
1823 DuplicatedToOriginalLPred = DuplicatedToLPred;
1824 // Iteratively try to duplicate again. It can happen that a block that is
1825 // duplicated into is still small enough to be duplicated again.
1826 // No need to call markBlockSuccessors in this case, as the blocks being
1827 // duplicated from here on are already scheduled.
1828 // Note that DuplicatedToLPred always implies Removed.
1829 while (DuplicatedToLPred) {
1830 assert (Removed && "Block must have been removed to be duplicated into its "
1831 "layout predecessor.");
1832 MachineBasicBlock *DupBB, *DupPred;
1833 // The removal callback causes Chain.end() to be updated when a block is
1834 // removed. On the first pass through the loop, the chain end should be the
1835 // same as it was on function entry. On subsequent passes, because we are
1836 // duplicating the block at the end of the chain, if it is removed the
1837 // chain will have shrunk by one block.
1838 BlockChain::iterator ChainEnd = Chain.end();
1839 DupBB = *(--ChainEnd);
1840 // Now try to duplicate again.
1841 if (ChainEnd == Chain.begin())
1842 break;
1843 DupPred = *std::prev(ChainEnd);
1844 Removed = maybeTailDuplicateBlock(DupBB, DupPred, Chain, BlockFilter,
1845 PrevUnplacedBlockIt,
1846 DuplicatedToLPred);
1847 }
1848 // If BB was duplicated into LPred, it is now scheduled. But because it was
1849 // removed, markChainSuccessors won't be called for its chain. Instead we
1850 // call markBlockSuccessors for LPred to achieve the same effect. This must go
1851 // at the end because repeating the tail duplication can increase the number
1852 // of unscheduled predecessors.
1853 LPred = *std::prev(Chain.end());
1854 if (DuplicatedToOriginalLPred)
1855 markBlockSuccessors(Chain, LPred, LoopHeaderBB, BlockFilter);
1856 return true;
1857}
1858
1859/// Tail duplicate \p BB into (some) predecessors if profitable.
1860/// \p BB - Basic block that may be duplicated
1861/// \p LPred - Chosen layout predecessor of \p BB
1862/// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
1863/// \p BlockFilter - Set of blocks that belong to the loop being laid out.
1864/// Used to identify which blocks to update predecessor
1865/// counts.
1866/// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
1867/// chosen in the given order due to unnatural CFG
1868/// only needed if \p BB is removed and
1869/// \p PrevUnplacedBlockIt pointed to \p BB.
1870/// \p DuplicatedToLPred - True if the block was duplicated into LPred. Will
1871/// only be true if the block was removed.
1872/// \return - True if the block was duplicated into all preds and removed.
1873bool MachineBlockPlacement::maybeTailDuplicateBlock(
1874 MachineBasicBlock *BB, MachineBasicBlock *LPred,
1875 const BlockChain &Chain, BlockFilterSet *BlockFilter,
1876 MachineFunction::iterator &PrevUnplacedBlockIt,
1877 bool &DuplicatedToLPred) {
1878
1879 DuplicatedToLPred = false;
1880 DEBUG(dbgs() << "Redoing tail duplication for Succ#"
1881 << BB->getNumber() << "\n");
1882 bool IsSimple = TailDup.isSimpleBB(BB);
1883 // Blocks with single successors don't create additional fallthrough
1884 // opportunities. Don't duplicate them. TODO: When conditional exits are
1885 // analyzable, allow them to be duplicated.
1886 if (!IsSimple && BB->succ_size() == 1)
1887 return false;
1888 if (!TailDup.shouldTailDuplicate(IsSimple, *BB))
1889 return false;
1890 // This has to be a callback because none of it can be done after
1891 // BB is deleted.
1892 bool Removed = false;
1893 auto RemovalCallback =
1894 [&](MachineBasicBlock *RemBB) {
1895 // Signal to outer function
1896 Removed = true;
1897
1898 // Conservative default.
1899 bool InWorkList = true;
1900 // Remove from the Chain and Chain Map
1901 if (BlockToChain.count(RemBB)) {
1902 BlockChain *Chain = BlockToChain[RemBB];
1903 InWorkList = Chain->UnscheduledPredecessors == 0;
1904 Chain->remove(RemBB);
1905 BlockToChain.erase(RemBB);
1906 }
1907
1908 // Handle the unplaced block iterator
1909 if (&(*PrevUnplacedBlockIt) == RemBB) {
1910 PrevUnplacedBlockIt++;
1911 }
1912
1913 // Handle the Work Lists
1914 if (InWorkList) {
1915 SmallVectorImpl<MachineBasicBlock *> &RemoveList = BlockWorkList;
1916 if (RemBB->isEHPad())
1917 RemoveList = EHPadWorkList;
1918 RemoveList.erase(
1919 remove_if(RemoveList,
1920 [RemBB](MachineBasicBlock *BB) {return BB == RemBB;}),
1921 RemoveList.end());
1922 }
1923
1924 // Handle the filter set
1925 if (BlockFilter) {
1926 BlockFilter->erase(RemBB);
1927 }
1928
1929 // Remove the block from loop info.
1930 MLI->removeBlock(RemBB);
1931
1932 // TailDuplicator handles removing it from loops.
1933 DEBUG(dbgs() << "TailDuplicator deleted block: "
1934 << getBlockName(RemBB) << "\n");
1935 };
1936 auto RemovalCallbackRef =
1937 llvm::function_ref<void(MachineBasicBlock*)>(RemovalCallback);
1938
1939 SmallVector<MachineBasicBlock *, 8> DuplicatedPreds;
1940 TailDup.tailDuplicateAndUpdate(IsSimple, BB, LPred,
1941 &DuplicatedPreds, &RemovalCallbackRef);
1942
1943 // Update UnscheduledPredecessors to reflect tail-duplication.
1944 DuplicatedToLPred = false;
1945 for (MachineBasicBlock *Pred : DuplicatedPreds) {
1946 // We're only looking for unscheduled predecessors that match the filter.
1947 BlockChain* PredChain = BlockToChain[Pred];
1948 if (Pred == LPred)
1949 DuplicatedToLPred = true;
1950 if (Pred == LPred || (BlockFilter && !BlockFilter->count(Pred))
1951 || PredChain == &Chain)
1952 continue;
1953 for (MachineBasicBlock *NewSucc : Pred->successors()) {
1954 if (BlockFilter && !BlockFilter->count(NewSucc))
1955 continue;
1956 BlockChain *NewChain = BlockToChain[NewSucc];
1957 if (NewChain != &Chain && NewChain != PredChain)
1958 NewChain->UnscheduledPredecessors++;
1959 }
1960 }
1961 return Removed;
1962}
1963
Xinliang David Li52530a72016-06-13 22:23:44 +00001964bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &MF) {
1965 if (skipFunction(*MF.getFunction()))
Andrew Kaylor50271f72016-05-03 22:32:30 +00001966 return false;
1967
Chandler Carruth10281422011-10-21 06:46:38 +00001968 // Check for single-block functions and skip them.
Xinliang David Li52530a72016-06-13 22:23:44 +00001969 if (std::next(MF.begin()) == MF.end())
Chandler Carruth10281422011-10-21 06:46:38 +00001970 return false;
1971
Xinliang David Li52530a72016-06-13 22:23:44 +00001972 F = &MF;
Chandler Carruth10281422011-10-21 06:46:38 +00001973 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
Haicheng Wu5b458cc2016-06-09 15:24:29 +00001974 MBFI = llvm::make_unique<BranchFolder::MBFIWrapper>(
1975 getAnalysis<MachineBlockFrequencyInfo>());
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001976 MLI = &getAnalysis<MachineLoopInfo>();
Xinliang David Li52530a72016-06-13 22:23:44 +00001977 TII = MF.getSubtarget().getInstrInfo();
1978 TLI = MF.getSubtarget().getTargetLowering();
Daniel Jasper471e8562015-03-04 11:05:34 +00001979 MDT = &getAnalysis<MachineDominatorTree>();
Kyle Butt0846e562016-10-11 20:36:43 +00001980 if (TailDupPlacement) {
1981 unsigned TailDupSize = TailDuplicatePlacementThreshold;
1982 if (MF.getFunction()->optForSize())
1983 TailDupSize = 1;
1984 TailDup.initMF(MF, MBPI, /* LayoutMode */ true, TailDupSize);
1985 }
1986
Chandler Carruth10281422011-10-21 06:46:38 +00001987 assert(BlockToChain.empty());
Chandler Carruth10281422011-10-21 06:46:38 +00001988
Xinliang David Li52530a72016-06-13 22:23:44 +00001989 buildCFGChains();
Haicheng Wu5b458cc2016-06-09 15:24:29 +00001990
1991 // Changing the layout can create new tail merging opportunities.
1992 TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
1993 // TailMerge can create jump into if branches that make CFG irreducible for
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001994 // HW that requires structured CFG.
Xinliang David Li52530a72016-06-13 22:23:44 +00001995 bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&
Haicheng Wu5b458cc2016-06-09 15:24:29 +00001996 PassConfig->getEnableTailMerge() &&
1997 BranchFoldPlacement;
1998 // No tail merging opportunities if the block number is less than four.
Xinliang David Li52530a72016-06-13 22:23:44 +00001999 if (MF.size() > 3 && EnableTailMerge) {
Kyle Butt0846e562016-10-11 20:36:43 +00002000 unsigned TailMergeSize = TailDuplicatePlacementThreshold + 1;
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002001 BranchFolder BF(/*EnableTailMerge=*/true, /*CommonHoist=*/false, *MBFI,
Kyle Butt64e42812016-08-18 18:57:29 +00002002 *MBPI, TailMergeSize);
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002003
Xinliang David Li52530a72016-06-13 22:23:44 +00002004 if (BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002005 getAnalysisIfAvailable<MachineModuleInfo>(), MLI,
2006 /*AfterBlockPlacement=*/true)) {
2007 // Redo the layout if tail merging creates/removes/moves blocks.
2008 BlockToChain.clear();
Kyle Butt0846e562016-10-11 20:36:43 +00002009 // Must redo the dominator tree if blocks were changed.
2010 MDT->runOnMachineFunction(MF);
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002011 ChainAllocator.DestroyAll();
Xinliang David Li52530a72016-06-13 22:23:44 +00002012 buildCFGChains();
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002013 }
2014 }
2015
Xinliang David Li52530a72016-06-13 22:23:44 +00002016 optimizeBranches();
2017 alignBlocks();
Chandler Carruth10281422011-10-21 06:46:38 +00002018
Chandler Carruth10281422011-10-21 06:46:38 +00002019 BlockToChain.clear();
Chandler Carruthfd9b4d92011-11-14 10:57:23 +00002020 ChainAllocator.DestroyAll();
Chandler Carruth10281422011-10-21 06:46:38 +00002021
Nadav Rotemc0adc9f2013-04-12 01:24:16 +00002022 if (AlignAllBlock)
2023 // Align all of the blocks in the function to a specific alignment.
Xinliang David Li52530a72016-06-13 22:23:44 +00002024 for (MachineBasicBlock &MBB : MF)
Chandler Carruth7a715da2015-03-05 03:19:05 +00002025 MBB.setAlignment(AlignAllBlock);
Geoff Berry10494ac2016-01-21 17:25:52 +00002026 else if (AlignAllNonFallThruBlocks) {
2027 // Align all of the blocks that have no fall-through predecessors to a
2028 // specific alignment.
Xinliang David Li52530a72016-06-13 22:23:44 +00002029 for (auto MBI = std::next(MF.begin()), MBE = MF.end(); MBI != MBE; ++MBI) {
Geoff Berry10494ac2016-01-21 17:25:52 +00002030 auto LayoutPred = std::prev(MBI);
2031 if (!LayoutPred->isSuccessor(&*MBI))
2032 MBI->setAlignment(AlignAllNonFallThruBlocks);
2033 }
2034 }
Nadav Rotemc0adc9f2013-04-12 01:24:16 +00002035
Chandler Carruth10281422011-10-21 06:46:38 +00002036 // We always return true as we have no way to track whether the final order
2037 // differs from the original order.
2038 return true;
2039}
Chandler Carruthae4e8002011-11-02 07:17:12 +00002040
2041namespace {
2042/// \brief A pass to compute block placement statistics.
2043///
2044/// A separate pass to compute interesting statistics for evaluating block
2045/// placement. This is separate from the actual placement pass so that they can
Benjamin Kramerbde91762012-06-02 10:20:22 +00002046/// be computed in the absence of any placement transformations or when using
Chandler Carruthae4e8002011-11-02 07:17:12 +00002047/// alternative placement strategies.
2048class MachineBlockPlacementStats : public MachineFunctionPass {
2049 /// \brief A handle to the branch probability pass.
2050 const MachineBranchProbabilityInfo *MBPI;
2051
2052 /// \brief A handle to the function-wide block frequency pass.
2053 const MachineBlockFrequencyInfo *MBFI;
2054
2055public:
2056 static char ID; // Pass identification, replacement for typeid
2057 MachineBlockPlacementStats() : MachineFunctionPass(ID) {
2058 initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
2059 }
2060
Craig Topper4584cd52014-03-07 09:26:03 +00002061 bool runOnMachineFunction(MachineFunction &F) override;
Chandler Carruthae4e8002011-11-02 07:17:12 +00002062
Craig Topper4584cd52014-03-07 09:26:03 +00002063 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruthae4e8002011-11-02 07:17:12 +00002064 AU.addRequired<MachineBranchProbabilityInfo>();
2065 AU.addRequired<MachineBlockFrequencyInfo>();
2066 AU.setPreservesAll();
2067 MachineFunctionPass::getAnalysisUsage(AU);
2068 }
Chandler Carruthae4e8002011-11-02 07:17:12 +00002069};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00002070}
Chandler Carruthae4e8002011-11-02 07:17:12 +00002071
2072char MachineBlockPlacementStats::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +00002073char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
Chandler Carruthae4e8002011-11-02 07:17:12 +00002074INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
2075 "Basic Block Placement Stats", false, false)
2076INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
2077INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
2078INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
2079 "Basic Block Placement Stats", false, false)
2080
Chandler Carruthae4e8002011-11-02 07:17:12 +00002081bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
2082 // Check for single-block functions and skip them.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002083 if (std::next(F.begin()) == F.end())
Chandler Carruthae4e8002011-11-02 07:17:12 +00002084 return false;
2085
2086 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
2087 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
2088
Chandler Carruth7a715da2015-03-05 03:19:05 +00002089 for (MachineBasicBlock &MBB : F) {
2090 BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00002091 Statistic &NumBranches =
Chandler Carruth7a715da2015-03-05 03:19:05 +00002092 (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00002093 Statistic &BranchTakenFreq =
Chandler Carruth7a715da2015-03-05 03:19:05 +00002094 (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
2095 for (MachineBasicBlock *Succ : MBB.successors()) {
Chandler Carruthae4e8002011-11-02 07:17:12 +00002096 // Skip if this successor is a fallthrough.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002097 if (MBB.isLayoutSuccessor(Succ))
Chandler Carruthae4e8002011-11-02 07:17:12 +00002098 continue;
2099
Chandler Carruth7a715da2015-03-05 03:19:05 +00002100 BlockFrequency EdgeFreq =
2101 BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
Chandler Carruthae4e8002011-11-02 07:17:12 +00002102 ++NumBranches;
2103 BranchTakenFreq += EdgeFreq.getFrequency();
2104 }
2105 }
2106
2107 return false;
2108}