blob: 889ccf0f196d590c42a76fa5bd52246b34c0cd85 [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"
Xinliang David Lifd3f6452017-01-29 01:57:02 +000035#include "llvm/Analysis/BlockFrequencyInfoImpl.h"
Chandler Carruth8b9737c2011-10-21 08:57:37 +000036#include "llvm/CodeGen/MachineBasicBlock.h"
Chandler Carruth10281422011-10-21 06:46:38 +000037#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
38#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Daniel Jasper471e8562015-03-04 11:05:34 +000039#include "llvm/CodeGen/MachineDominators.h"
Chandler Carruth10281422011-10-21 06:46:38 +000040#include "llvm/CodeGen/MachineFunction.h"
Chandler Carruth10281422011-10-21 06:46:38 +000041#include "llvm/CodeGen/MachineFunctionPass.h"
Chandler Carruth8b9737c2011-10-21 08:57:37 +000042#include "llvm/CodeGen/MachineLoopInfo.h"
43#include "llvm/CodeGen/MachineModuleInfo.h"
Kyle Buttb15c0662017-01-31 23:48:32 +000044#include "llvm/CodeGen/MachinePostDominators.h"
Kyle Butt0846e562016-10-11 20:36:43 +000045#include "llvm/CodeGen/TailDuplicator.h"
Chandler Carruth10281422011-10-21 06:46:38 +000046#include "llvm/Support/Allocator.h"
Nadav Rotemc3b0f502013-04-12 00:48:32 +000047#include "llvm/Support/CommandLine.h"
Chandler Carruthbd1be4d2011-10-23 09:18:45 +000048#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000049#include "llvm/Support/raw_ostream.h"
Chandler Carruth10281422011-10-21 06:46:38 +000050#include "llvm/Target/TargetInstrInfo.h"
Chandler Carruth8b9737c2011-10-21 08:57:37 +000051#include "llvm/Target/TargetLowering.h"
Eric Christopherd9134482014-08-04 21:25:23 +000052#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruth10281422011-10-21 06:46:38 +000053#include <algorithm>
Kyle Buttb15c0662017-01-31 23:48:32 +000054#include <functional>
55#include <utility>
Chandler Carruth10281422011-10-21 06:46:38 +000056using namespace llvm;
57
Chandler Carruthd0dced52015-03-05 02:28:25 +000058#define DEBUG_TYPE "block-placement"
Chandler Carruth1b9dde02014-04-22 02:02:50 +000059
Chandler Carruthae4e8002011-11-02 07:17:12 +000060STATISTIC(NumCondBranches, "Number of conditional branches");
Craig Topper77ec0772015-09-16 03:52:32 +000061STATISTIC(NumUncondBranches, "Number of unconditional branches");
Chandler Carruthae4e8002011-11-02 07:17:12 +000062STATISTIC(CondBranchTakenFreq,
63 "Potential frequency of taking conditional branches");
64STATISTIC(UncondBranchTakenFreq,
65 "Potential frequency of taking unconditional branches");
66
Nadav Rotemc3b0f502013-04-12 00:48:32 +000067static cl::opt<unsigned> AlignAllBlock("align-all-blocks",
68 cl::desc("Force the alignment of all "
69 "blocks in the function."),
70 cl::init(0), cl::Hidden);
71
Geoff Berry10494ac2016-01-21 17:25:52 +000072static cl::opt<unsigned> AlignAllNonFallThruBlocks(
73 "align-all-nofallthru-blocks",
74 cl::desc("Force the alignment of all "
75 "blocks that have no fall-through predecessors (i.e. don't add "
76 "nops that are executed)."),
77 cl::init(0), cl::Hidden);
78
Benjamin Kramerc8160d62013-11-20 19:08:44 +000079// FIXME: Find a good default for this flag and remove the flag.
Chandler Carruth2fc3fe12015-03-05 02:35:31 +000080static cl::opt<unsigned> ExitBlockBias(
81 "block-placement-exit-block-bias",
82 cl::desc("Block frequency percentage a loop exit block needs "
83 "over the original exit to be considered the new exit."),
84 cl::init(0), cl::Hidden);
Benjamin Kramerc8160d62013-11-20 19:08:44 +000085
Sjoerd Meijer5e11a182016-07-27 08:49:23 +000086// Definition:
87// - Outlining: placement of a basic block outside the chain or hot path.
88
Daniel Jasper471e8562015-03-04 11:05:34 +000089static cl::opt<bool> OutlineOptionalBranches(
90 "outline-optional-branches",
Sjoerd Meijer5e11a182016-07-27 08:49:23 +000091 cl::desc("Outlining optional branches will place blocks that are optional "
92 "branches, i.e. branches with a common post dominator, outside "
93 "the hot path or chain"),
Daniel Jasper471e8562015-03-04 11:05:34 +000094 cl::init(false), cl::Hidden);
95
Daniel Jasper214997c2015-03-20 10:00:37 +000096static cl::opt<unsigned> OutlineOptionalThreshold(
97 "outline-optional-threshold",
98 cl::desc("Don't outline optional branches that are a single block with an "
99 "instruction count below this threshold"),
100 cl::init(4), cl::Hidden);
101
Cong Houb90b9e02015-11-02 21:24:00 +0000102static cl::opt<unsigned> LoopToColdBlockRatio(
103 "loop-to-cold-block-ratio",
104 cl::desc("Outline loop blocks from loop chain if (frequency of loop) / "
105 "(frequency of block) is greater than this ratio"),
106 cl::init(5), cl::Hidden);
107
Cong Hou7745dbc2015-10-19 23:16:40 +0000108static cl::opt<bool>
109 PreciseRotationCost("precise-rotation-cost",
110 cl::desc("Model the cost of loop rotation more "
111 "precisely by using profile data."),
112 cl::init(false), cl::Hidden);
Xinliang David Lif0ab6df2016-05-12 02:04:41 +0000113static cl::opt<bool>
114 ForcePreciseRotationCost("force-precise-rotation-cost",
Xinliang David Lib840bb82016-05-12 16:39:02 +0000115 cl::desc("Force the use of precise cost "
116 "loop rotation strategy."),
Xinliang David Lif0ab6df2016-05-12 02:04:41 +0000117 cl::init(false), cl::Hidden);
Cong Hou7745dbc2015-10-19 23:16:40 +0000118
119static cl::opt<unsigned> MisfetchCost(
120 "misfetch-cost",
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000121 cl::desc("Cost that models the probabilistic risk of an instruction "
Cong Hou7745dbc2015-10-19 23:16:40 +0000122 "misfetch due to a jump comparing to falling through, whose cost "
123 "is zero."),
124 cl::init(1), cl::Hidden);
125
126static cl::opt<unsigned> JumpInstCost("jump-inst-cost",
127 cl::desc("Cost of jump instructions."),
128 cl::init(1), cl::Hidden);
Kyle Butt0846e562016-10-11 20:36:43 +0000129static cl::opt<bool>
130TailDupPlacement("tail-dup-placement",
131 cl::desc("Perform tail duplication during placement. "
132 "Creates more fallthrough opportunites in "
133 "outline branches."),
134 cl::init(true), cl::Hidden);
Cong Hou7745dbc2015-10-19 23:16:40 +0000135
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000136static cl::opt<bool>
137BranchFoldPlacement("branch-fold-placement",
138 cl::desc("Perform branch folding during placement. "
139 "Reduces code size."),
140 cl::init(true), cl::Hidden);
141
Kyle Butt0846e562016-10-11 20:36:43 +0000142// Heuristic for tail duplication.
Kyle Buttb15c0662017-01-31 23:48:32 +0000143static cl::opt<unsigned> TailDupPlacementThreshold(
Kyle Butt0846e562016-10-11 20:36:43 +0000144 "tail-dup-placement-threshold",
145 cl::desc("Instruction cutoff for tail duplication during layout. "
146 "Tail merging during layout is forced to have a threshold "
147 "that won't conflict."), cl::init(2),
148 cl::Hidden);
149
Kyle Buttb15c0662017-01-31 23:48:32 +0000150// Heuristic for tail duplication.
151static cl::opt<unsigned> TailDupPlacementPenalty(
152 "tail-dup-placement-penalty",
153 cl::desc("Cost penalty for blocks that can avoid breaking CFG by copying. "
154 "Copying can increase fallthrough, but it also increases icache "
155 "pressure. This parameter controls the penalty to account for that. "
156 "Percent as integer."),
157 cl::init(2),
158 cl::Hidden);
159
Xinliang David Liff287372016-06-03 23:48:36 +0000160extern cl::opt<unsigned> StaticLikelyProb;
Dehao Chen9f2bdfb2016-06-14 22:27:17 +0000161extern cl::opt<unsigned> ProfileLikelyProb;
Xinliang David Liff287372016-06-03 23:48:36 +0000162
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000163// Internal option used to control BFI display only after MBP pass.
164// Defined in CodeGen/MachineBlockFrequencyInfo.cpp:
165// -view-block-layout-with-bfi=
Xinliang David Lifd3f6452017-01-29 01:57:02 +0000166extern cl::opt<GVDAGType> ViewBlockLayoutWithBFI;
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000167
168// Command line option to specify the name of the function for CFG dump
169// Defined in Analysis/BlockFrequencyInfo.cpp: -view-bfi-func-name=
Xinliang David Lifd3f6452017-01-29 01:57:02 +0000170extern cl::opt<std::string> ViewBlockFreqFuncName;
Xinliang David Lifd3f6452017-01-29 01:57:02 +0000171
Chandler Carruth10281422011-10-21 06:46:38 +0000172namespace {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000173class BlockChain;
Chandler Carruth10281422011-10-21 06:46:38 +0000174/// \brief Type for our function-wide basic block -> block chain mapping.
Kyle Butte9425c4f2017-02-04 02:26:32 +0000175typedef DenseMap<const MachineBasicBlock *, BlockChain *> BlockToChainMapType;
Chandler Carruth10281422011-10-21 06:46:38 +0000176}
177
178namespace {
179/// \brief A chain of blocks which will be laid out contiguously.
180///
181/// This is the datastructure representing a chain of consecutive blocks that
182/// are profitable to layout together in order to maximize fallthrough
Chandler Carruth9139f442012-06-26 05:16:37 +0000183/// probabilities and code locality. We also can use a block chain to represent
184/// a sequence of basic blocks which have some external (correctness)
185/// requirement for sequential layout.
Chandler Carruth10281422011-10-21 06:46:38 +0000186///
Chandler Carruth9139f442012-06-26 05:16:37 +0000187/// Chains can be built around a single basic block and can be merged to grow
188/// them. They participate in a block-to-chain mapping, which is updated
189/// automatically as chains are merged together.
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000190class BlockChain {
191 /// \brief The sequence of blocks belonging to this chain.
Chandler Carruth10281422011-10-21 06:46:38 +0000192 ///
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000193 /// This is the sequence of blocks for a particular chain. These will be laid
194 /// out in-order within the function.
195 SmallVector<MachineBasicBlock *, 4> Blocks;
Chandler Carruth10281422011-10-21 06:46:38 +0000196
197 /// \brief A handle to the function-wide basic block to block chain mapping.
198 ///
199 /// This is retained in each block chain to simplify the computation of child
200 /// block chains for SCC-formation and iteration. We store the edges to child
201 /// basic blocks, and map them back to their associated chains using this
202 /// structure.
203 BlockToChainMapType &BlockToChain;
204
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000205public:
Chandler Carruth10281422011-10-21 06:46:38 +0000206 /// \brief Construct a new BlockChain.
207 ///
208 /// This builds a new block chain representing a single basic block in the
209 /// function. It also registers itself as the chain that block participates
210 /// in with the BlockToChain mapping.
211 BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
Philip Reamesae27b232016-03-03 00:58:43 +0000212 : Blocks(1, BB), BlockToChain(BlockToChain), UnscheduledPredecessors(0) {
Chandler Carruth10281422011-10-21 06:46:38 +0000213 assert(BB && "Cannot create a chain with a null basic block");
214 BlockToChain[BB] = this;
215 }
216
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000217 /// \brief Iterator over blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000218 typedef SmallVectorImpl<MachineBasicBlock *>::iterator iterator;
Kyle Butte9425c4f2017-02-04 02:26:32 +0000219 typedef SmallVectorImpl<MachineBasicBlock *>::const_iterator const_iterator;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000220
221 /// \brief Beginning of blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000222 iterator begin() { return Blocks.begin(); }
Kyle Butte9425c4f2017-02-04 02:26:32 +0000223 const_iterator begin() const { return Blocks.begin(); }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000224
225 /// \brief End of blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000226 iterator end() { return Blocks.end(); }
Kyle Butte9425c4f2017-02-04 02:26:32 +0000227 const_iterator end() const { return Blocks.end(); }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000228
Kyle Butt0846e562016-10-11 20:36:43 +0000229 bool remove(MachineBasicBlock* BB) {
230 for(iterator i = begin(); i != end(); ++i) {
231 if (*i == BB) {
232 Blocks.erase(i);
233 return true;
234 }
235 }
236 return false;
237 }
238
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000239 /// \brief Merge a block chain into this one.
Chandler Carruth10281422011-10-21 06:46:38 +0000240 ///
241 /// This routine merges a block chain into this one. It takes care of forming
242 /// a contiguous sequence of basic blocks, updating the edge list, and
243 /// updating the block -> chain mapping. It does not free or tear down the
244 /// old chain, but the old chain's block list is no longer valid.
Jakub Staszak90616162011-12-21 23:02:08 +0000245 void merge(MachineBasicBlock *BB, BlockChain *Chain) {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000246 assert(BB);
247 assert(!Blocks.empty());
Chandler Carruth10281422011-10-21 06:46:38 +0000248
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000249 // Fast path in case we don't have a chain already.
250 if (!Chain) {
251 assert(!BlockToChain[BB]);
252 Blocks.push_back(BB);
253 BlockToChain[BB] = this;
254 return;
Chandler Carruth10281422011-10-21 06:46:38 +0000255 }
256
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000257 assert(BB == *Chain->begin());
258 assert(Chain->begin() != Chain->end());
Chandler Carruth10281422011-10-21 06:46:38 +0000259
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000260 // Update the incoming blocks to point to this chain, and add them to the
261 // chain structure.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000262 for (MachineBasicBlock *ChainBB : *Chain) {
263 Blocks.push_back(ChainBB);
264 assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain");
265 BlockToChain[ChainBB] = this;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000266 }
Chandler Carruth10281422011-10-21 06:46:38 +0000267 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000268
Chandler Carruth49158902012-04-08 14:37:01 +0000269#ifndef NDEBUG
270 /// \brief Dump the blocks in this chain.
Nico Weber7408c702014-01-03 22:53:37 +0000271 LLVM_DUMP_METHOD void dump() {
Chandler Carruth7a715da2015-03-05 03:19:05 +0000272 for (MachineBasicBlock *MBB : *this)
273 MBB->dump();
Chandler Carruth49158902012-04-08 14:37:01 +0000274 }
275#endif // NDEBUG
276
Philip Reamesae27b232016-03-03 00:58:43 +0000277 /// \brief Count of predecessors of any block within the chain which have not
278 /// yet been scheduled. In general, we will delay scheduling this chain
279 /// until those predecessors are scheduled (or we find a sufficiently good
280 /// reason to override this heuristic.) Note that when forming loop chains,
281 /// blocks outside the loop are ignored and treated as if they were already
282 /// scheduled.
Chandler Carruth8d150782011-11-13 11:20:44 +0000283 ///
Philip Reamesae27b232016-03-03 00:58:43 +0000284 /// Note: This field is reinitialized multiple times - once for each loop,
285 /// and then once for the function as a whole.
286 unsigned UnscheduledPredecessors;
Chandler Carruth10281422011-10-21 06:46:38 +0000287};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000288}
Chandler Carruth10281422011-10-21 06:46:38 +0000289
290namespace {
291class MachineBlockPlacement : public MachineFunctionPass {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000292 /// \brief A typedef for a block filter set.
Kyle Butte9425c4f2017-02-04 02:26:32 +0000293 typedef SmallSetVector<const MachineBasicBlock *, 16> BlockFilterSet;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000294
Kyle Buttb15c0662017-01-31 23:48:32 +0000295 /// Pair struct containing basic block and taildup profitiability
296 struct BlockAndTailDupResult {
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000297 MachineBasicBlock *BB;
Kyle Buttb15c0662017-01-31 23:48:32 +0000298 bool ShouldTailDup;
299 };
300
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000301 /// Triple struct containing edge weight and the edge.
302 struct WeightedEdge {
303 BlockFrequency Weight;
304 MachineBasicBlock *Src;
305 MachineBasicBlock *Dest;
306 };
307
Xinliang David Li93926ac2016-07-01 05:46:48 +0000308 /// \brief work lists of blocks that are ready to be laid out
309 SmallVector<MachineBasicBlock *, 16> BlockWorkList;
310 SmallVector<MachineBasicBlock *, 16> EHPadWorkList;
311
Kyle Buttebe6cc42017-02-23 21:22:24 +0000312 /// Edges that have already been computed as optimal.
313 DenseMap<const MachineBasicBlock *, BlockAndTailDupResult> ComputedEdges;
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000314
Xinliang David Li52530a72016-06-13 22:23:44 +0000315 /// \brief Machine Function
316 MachineFunction *F;
317
Chandler Carruth10281422011-10-21 06:46:38 +0000318 /// \brief A handle to the branch probability pass.
319 const MachineBranchProbabilityInfo *MBPI;
320
321 /// \brief A handle to the function-wide block frequency pass.
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000322 std::unique_ptr<BranchFolder::MBFIWrapper> MBFI;
Chandler Carruth10281422011-10-21 06:46:38 +0000323
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000324 /// \brief A handle to the loop info.
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000325 MachineLoopInfo *MLI;
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000326
Kyle Buttab9cca72016-10-27 21:37:20 +0000327 /// \brief Preferred loop exit.
328 /// Member variable for convenience. It may be removed by duplication deep
329 /// in the call stack.
330 MachineBasicBlock *PreferredLoopExit;
331
Chandler Carruth10281422011-10-21 06:46:38 +0000332 /// \brief A handle to the target's instruction info.
333 const TargetInstrInfo *TII;
334
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000335 /// \brief A handle to the target's lowering info.
Benjamin Kramer56b31bd2013-01-11 20:05:37 +0000336 const TargetLoweringBase *TLI;
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000337
Kyle Buttb15c0662017-01-31 23:48:32 +0000338 /// \brief A handle to the dominator tree.
Daniel Jasper471e8562015-03-04 11:05:34 +0000339 MachineDominatorTree *MDT;
340
Kyle Buttb15c0662017-01-31 23:48:32 +0000341 /// \brief A handle to the post dominator tree.
342 MachinePostDominatorTree *MPDT;
343
Kyle Butt0846e562016-10-11 20:36:43 +0000344 /// \brief Duplicator used to duplicate tails during placement.
345 ///
346 /// Placement decisions can open up new tail duplication opportunities, but
347 /// since tail duplication affects placement decisions of later blocks, it
348 /// must be done inline.
349 TailDuplicator TailDup;
350
Daniel Jasper471e8562015-03-04 11:05:34 +0000351 /// \brief A set of blocks that are unavoidably execute, i.e. they dominate
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000352 /// all terminators of the MachineFunction.
Kyle Butte9425c4f2017-02-04 02:26:32 +0000353 SmallPtrSet<const MachineBasicBlock *, 4> UnavoidableBlocks;
Daniel Jasper471e8562015-03-04 11:05:34 +0000354
Chandler Carruth10281422011-10-21 06:46:38 +0000355 /// \brief Allocator and owner of BlockChain structures.
356 ///
Chandler Carruth9139f442012-06-26 05:16:37 +0000357 /// We build BlockChains lazily while processing the loop structure of
358 /// a function. To reduce malloc traffic, we allocate them using this
359 /// slab-like allocator, and destroy them after the pass completes. An
360 /// important guarantee is that this allocator produces stable pointers to
361 /// the chains.
Chandler Carruth10281422011-10-21 06:46:38 +0000362 SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
363
364 /// \brief Function wide BasicBlock to BlockChain mapping.
365 ///
366 /// This mapping allows efficiently moving from any given basic block to the
367 /// BlockChain it participates in, if any. We use it to, among other things,
368 /// allow implicitly defining edges between chains as the existing edges
369 /// between basic blocks.
Kyle Butte9425c4f2017-02-04 02:26:32 +0000370 DenseMap<const MachineBasicBlock *, BlockChain *> BlockToChain;
Chandler Carruth10281422011-10-21 06:46:38 +0000371
Sanjoy Dasd7389d62016-12-15 05:08:57 +0000372#ifndef NDEBUG
373 /// The set of basic blocks that have terminators that cannot be fully
374 /// analyzed. These basic blocks cannot be re-ordered safely by
375 /// MachineBlockPlacement, and we must preserve physical layout of these
376 /// blocks and their successors through the pass.
377 SmallPtrSet<MachineBasicBlock *, 4> BlocksWithUnanalyzableExits;
378#endif
379
Kyle Butt0846e562016-10-11 20:36:43 +0000380 /// Decrease the UnscheduledPredecessors count for all blocks in chain, and
381 /// if the count goes to 0, add them to the appropriate work list.
Kyle Butte9425c4f2017-02-04 02:26:32 +0000382 void markChainSuccessors(
383 const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB,
384 const BlockFilterSet *BlockFilter = nullptr);
Kyle Butt0846e562016-10-11 20:36:43 +0000385
386 /// Decrease the UnscheduledPredecessors count for a single block, and
387 /// if the count goes to 0, add them to the appropriate work list.
388 void markBlockSuccessors(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000389 const BlockChain &Chain, const MachineBasicBlock *BB,
390 const MachineBasicBlock *LoopHeaderBB,
Kyle Butt0846e562016-10-11 20:36:43 +0000391 const BlockFilterSet *BlockFilter = nullptr);
392
Xinliang David Li594ffa32016-06-11 18:35:40 +0000393 BranchProbability
Kyle Butte9425c4f2017-02-04 02:26:32 +0000394 collectViableSuccessors(
395 const MachineBasicBlock *BB, const BlockChain &Chain,
396 const BlockFilterSet *BlockFilter,
397 SmallVector<MachineBasicBlock *, 4> &Successors);
398 bool shouldPredBlockBeOutlined(
399 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
400 const BlockChain &Chain, const BlockFilterSet *BlockFilter,
401 BranchProbability SuccProb, BranchProbability HotProb);
Kyle Butt0846e562016-10-11 20:36:43 +0000402 bool repeatedlyTailDuplicateBlock(
403 MachineBasicBlock *BB, MachineBasicBlock *&LPred,
Kyle Butte9425c4f2017-02-04 02:26:32 +0000404 const MachineBasicBlock *LoopHeaderBB,
Kyle Butt0846e562016-10-11 20:36:43 +0000405 BlockChain &Chain, BlockFilterSet *BlockFilter,
406 MachineFunction::iterator &PrevUnplacedBlockIt);
Kyle Butte9425c4f2017-02-04 02:26:32 +0000407 bool maybeTailDuplicateBlock(
408 MachineBasicBlock *BB, MachineBasicBlock *LPred,
409 BlockChain &Chain, BlockFilterSet *BlockFilter,
410 MachineFunction::iterator &PrevUnplacedBlockIt,
411 bool &DuplicatedToPred);
412 bool hasBetterLayoutPredecessor(
413 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
414 const BlockChain &SuccChain, BranchProbability SuccProb,
415 BranchProbability RealSuccProb, const BlockChain &Chain,
416 const BlockFilterSet *BlockFilter);
417 BlockAndTailDupResult selectBestSuccessor(
418 const MachineBasicBlock *BB, const BlockChain &Chain,
419 const BlockFilterSet *BlockFilter);
420 MachineBasicBlock *selectBestCandidateBlock(
421 const BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList);
422 MachineBasicBlock *getFirstUnplacedBlock(
423 const BlockChain &PlacedChain,
424 MachineFunction::iterator &PrevUnplacedBlockIt,
425 const BlockFilterSet *BlockFilter);
Amaury Secheteae09c22016-03-14 21:24:11 +0000426
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000427 /// \brief Add a basic block to the work list if it is appropriate.
Amaury Secheteae09c22016-03-14 21:24:11 +0000428 ///
429 /// If the optional parameter BlockFilter is provided, only MBB
430 /// present in the set will be added to the worklist. If nullptr
431 /// is provided, no filtering occurs.
Kyle Butte9425c4f2017-02-04 02:26:32 +0000432 void fillWorkLists(const MachineBasicBlock *MBB,
Amaury Secheteae09c22016-03-14 21:24:11 +0000433 SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
Amaury Secheteae09c22016-03-14 21:24:11 +0000434 const BlockFilterSet *BlockFilter);
Kyle Butte9425c4f2017-02-04 02:26:32 +0000435 void buildChain(const MachineBasicBlock *BB, BlockChain &Chain,
Kyle Butt0846e562016-10-11 20:36:43 +0000436 BlockFilterSet *BlockFilter = nullptr);
Kyle Butte9425c4f2017-02-04 02:26:32 +0000437 MachineBasicBlock *findBestLoopTop(
438 const MachineLoop &L, const BlockFilterSet &LoopBlockSet);
439 MachineBasicBlock *findBestLoopExit(
440 const MachineLoop &L, const BlockFilterSet &LoopBlockSet);
441 BlockFilterSet collectLoopBlockSet(const MachineLoop &L);
442 void buildLoopChains(const MachineLoop &L);
443 void rotateLoop(
444 BlockChain &LoopChain, const MachineBasicBlock *ExitingBB,
445 const BlockFilterSet &LoopBlockSet);
446 void rotateLoopWithProfile(
447 BlockChain &LoopChain, const MachineLoop &L,
448 const BlockFilterSet &LoopBlockSet);
Xinliang David Li52530a72016-06-13 22:23:44 +0000449 void collectMustExecuteBBs();
450 void buildCFGChains();
451 void optimizeBranches();
452 void alignBlocks();
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000453 /// Returns true if a block should be tail-duplicated to increase fallthrough
454 /// opportunities.
Kyle Buttb15c0662017-01-31 23:48:32 +0000455 bool shouldTailDuplicate(MachineBasicBlock *BB);
456 /// Check the edge frequencies to see if tail duplication will increase
457 /// fallthroughs.
458 bool isProfitableToTailDup(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000459 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
Kyle Buttb15c0662017-01-31 23:48:32 +0000460 BranchProbability AdjustedSumProb,
Kyle Butte9425c4f2017-02-04 02:26:32 +0000461 const BlockChain &Chain, const BlockFilterSet *BlockFilter);
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000462 /// Check for a trellis layout.
463 bool isTrellis(const MachineBasicBlock *BB,
464 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
465 const BlockChain &Chain, const BlockFilterSet *BlockFilter);
466 /// Get the best successor given a trellis layout.
467 BlockAndTailDupResult getBestTrellisSuccessor(
468 const MachineBasicBlock *BB,
469 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
470 BranchProbability AdjustedSumProb, const BlockChain &Chain,
471 const BlockFilterSet *BlockFilter);
472 /// Get the best pair of non-conflicting edges.
473 static std::pair<WeightedEdge, WeightedEdge> getBestNonConflictingEdges(
474 const MachineBasicBlock *BB,
475 SmallVector<SmallVector<WeightedEdge, 8>, 2> &Edges);
Kyle Buttb15c0662017-01-31 23:48:32 +0000476 /// Returns true if a block can tail duplicate into all unplaced
477 /// predecessors. Filters based on loop.
478 bool canTailDuplicateUnplacedPreds(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000479 const MachineBasicBlock *BB, MachineBasicBlock *Succ,
480 const BlockChain &Chain, const BlockFilterSet *BlockFilter);
Chandler Carruth10281422011-10-21 06:46:38 +0000481
482public:
483 static char ID; // Pass identification, replacement for typeid
484 MachineBlockPlacement() : MachineFunctionPass(ID) {
485 initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
486 }
487
Craig Topper4584cd52014-03-07 09:26:03 +0000488 bool runOnMachineFunction(MachineFunction &F) override;
Chandler Carruth10281422011-10-21 06:46:38 +0000489
Craig Topper4584cd52014-03-07 09:26:03 +0000490 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth10281422011-10-21 06:46:38 +0000491 AU.addRequired<MachineBranchProbabilityInfo>();
492 AU.addRequired<MachineBlockFrequencyInfo>();
Daniel Jasper471e8562015-03-04 11:05:34 +0000493 AU.addRequired<MachineDominatorTree>();
Kyle Buttb15c0662017-01-31 23:48:32 +0000494 if (TailDupPlacement)
495 AU.addRequired<MachinePostDominatorTree>();
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000496 AU.addRequired<MachineLoopInfo>();
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000497 AU.addRequired<TargetPassConfig>();
Chandler Carruth10281422011-10-21 06:46:38 +0000498 MachineFunctionPass::getAnalysisUsage(AU);
499 }
Chandler Carruth10281422011-10-21 06:46:38 +0000500};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000501}
Chandler Carruth10281422011-10-21 06:46:38 +0000502
503char MachineBlockPlacement::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000504char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
Chandler Carruthd0dced52015-03-05 02:28:25 +0000505INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement",
Chandler Carruth10281422011-10-21 06:46:38 +0000506 "Branch Probability Basic Block Placement", false, false)
507INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
508INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
Daniel Jasper471e8562015-03-04 11:05:34 +0000509INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
Kyle Buttb15c0662017-01-31 23:48:32 +0000510INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree)
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000511INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
Chandler Carruthd0dced52015-03-05 02:28:25 +0000512INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement",
Chandler Carruth10281422011-10-21 06:46:38 +0000513 "Branch Probability Basic Block Placement", false, false)
514
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000515#ifndef NDEBUG
516/// \brief Helper to print the name of a MBB.
517///
518/// Only used by debug logging.
Kyle Butte9425c4f2017-02-04 02:26:32 +0000519static std::string getBlockName(const MachineBasicBlock *BB) {
Alp Tokere69170a2014-06-26 22:52:05 +0000520 std::string Result;
521 raw_string_ostream OS(Result);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000522 OS << "BB#" << BB->getNumber();
Philip Reamesb9688f42016-03-02 21:45:13 +0000523 OS << " ('" << BB->getName() << "')";
Alp Tokere69170a2014-06-26 22:52:05 +0000524 OS.flush();
525 return Result;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000526}
527#endif
528
Chandler Carrutheb4ec3a2011-11-13 11:34:55 +0000529/// \brief Mark a chain's successors as having one fewer preds.
530///
531/// When a chain is being merged into the "placed" chain, this routine will
532/// quickly walk the successors of each block in the chain and mark them as
533/// having one fewer active predecessor. It also adds any successors of this
Kyle Butt0846e562016-10-11 20:36:43 +0000534/// chain which reach the zero-predecessor state to the appropriate worklist.
Chandler Carruth8d150782011-11-13 11:20:44 +0000535void MachineBlockPlacement::markChainSuccessors(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000536 const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB,
Jakub Staszak90616162011-12-21 23:02:08 +0000537 const BlockFilterSet *BlockFilter) {
Chandler Carruth8d150782011-11-13 11:20:44 +0000538 // Walk all the blocks in this chain, marking their successors as having
539 // a predecessor placed.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000540 for (MachineBasicBlock *MBB : Chain) {
Kyle Butt0846e562016-10-11 20:36:43 +0000541 markBlockSuccessors(Chain, MBB, LoopHeaderBB, BlockFilter);
542 }
543}
Chandler Carruth10281422011-10-21 06:46:38 +0000544
Kyle Butt0846e562016-10-11 20:36:43 +0000545/// \brief Mark a single block's successors as having one fewer preds.
546///
547/// Under normal circumstances, this is only called by markChainSuccessors,
548/// but if a block that was to be placed is completely tail-duplicated away,
549/// and was duplicated into the chain end, we need to redo markBlockSuccessors
550/// for just that block.
551void MachineBlockPlacement::markBlockSuccessors(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000552 const BlockChain &Chain, const MachineBasicBlock *MBB,
553 const MachineBasicBlock *LoopHeaderBB, const BlockFilterSet *BlockFilter) {
Kyle Butt0846e562016-10-11 20:36:43 +0000554 // Add any successors for which this is the only un-placed in-loop
555 // predecessor to the worklist as a viable candidate for CFG-neutral
556 // placement. No subsequent placement of this block will violate the CFG
557 // shape, so we get to use heuristics to choose a favorable placement.
558 for (MachineBasicBlock *Succ : MBB->successors()) {
559 if (BlockFilter && !BlockFilter->count(Succ))
560 continue;
561 BlockChain &SuccChain = *BlockToChain[Succ];
562 // Disregard edges within a fixed chain, or edges to the loop header.
563 if (&Chain == &SuccChain || Succ == LoopHeaderBB)
564 continue;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000565
Kyle Butt0846e562016-10-11 20:36:43 +0000566 // This is a cross-chain edge that is within the loop, so decrement the
567 // loop predecessor count of the destination chain.
568 if (SuccChain.UnscheduledPredecessors == 0 ||
569 --SuccChain.UnscheduledPredecessors > 0)
570 continue;
571
572 auto *NewBB = *SuccChain.begin();
573 if (NewBB->isEHPad())
574 EHPadWorkList.push_back(NewBB);
575 else
576 BlockWorkList.push_back(NewBB);
Chandler Carruth10281422011-10-21 06:46:38 +0000577 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000578}
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000579
Xinliang David Li594ffa32016-06-11 18:35:40 +0000580/// This helper function collects the set of successors of block
581/// \p BB that are allowed to be its layout successors, and return
582/// the total branch probability of edges from \p BB to those
583/// blocks.
584BranchProbability MachineBlockPlacement::collectViableSuccessors(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000585 const MachineBasicBlock *BB, const BlockChain &Chain,
586 const BlockFilterSet *BlockFilter,
Xinliang David Li594ffa32016-06-11 18:35:40 +0000587 SmallVector<MachineBasicBlock *, 4> &Successors) {
Cong Houd97c1002015-12-01 05:29:22 +0000588 // Adjust edge probabilities by excluding edges pointing to blocks that is
589 // either not in BlockFilter or is already in the current chain. Consider the
590 // following CFG:
Cong Hou41cf1a52015-11-18 00:52:52 +0000591 //
592 // --->A
593 // | / \
594 // | B C
595 // | \ / \
596 // ----D E
597 //
598 // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after
599 // A->C is chosen as a fall-through, D won't be selected as a successor of C
600 // due to CFG constraint (the probability of C->D is not greater than
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000601 // HotProb to break top-order). If we exclude E that is not in BlockFilter
Xinliang David Li594ffa32016-06-11 18:35:40 +0000602 // when calculating the probability of C->D, D will be selected and we
603 // will get A C D B as the layout of this loop.
Cong Houd97c1002015-12-01 05:29:22 +0000604 auto AdjustedSumProb = BranchProbability::getOne();
Cong Hou41cf1a52015-11-18 00:52:52 +0000605 for (MachineBasicBlock *Succ : BB->successors()) {
606 bool SkipSucc = false;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000607 if (Succ->isEHPad() || (BlockFilter && !BlockFilter->count(Succ))) {
Cong Hou41cf1a52015-11-18 00:52:52 +0000608 SkipSucc = true;
609 } else {
610 BlockChain *SuccChain = BlockToChain[Succ];
611 if (SuccChain == &Chain) {
Cong Hou41cf1a52015-11-18 00:52:52 +0000612 SkipSucc = true;
613 } else if (Succ != *SuccChain->begin()) {
614 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> Mid chain!\n");
615 continue;
616 }
617 }
618 if (SkipSucc)
Cong Houd97c1002015-12-01 05:29:22 +0000619 AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ);
Cong Hou41cf1a52015-11-18 00:52:52 +0000620 else
621 Successors.push_back(Succ);
622 }
623
Xinliang David Li594ffa32016-06-11 18:35:40 +0000624 return AdjustedSumProb;
625}
626
627/// The helper function returns the branch probability that is adjusted
628/// or normalized over the new total \p AdjustedSumProb.
Xinliang David Li594ffa32016-06-11 18:35:40 +0000629static BranchProbability
630getAdjustedProbability(BranchProbability OrigProb,
631 BranchProbability AdjustedSumProb) {
632 BranchProbability SuccProb;
633 uint32_t SuccProbN = OrigProb.getNumerator();
634 uint32_t SuccProbD = AdjustedSumProb.getNumerator();
635 if (SuccProbN >= SuccProbD)
636 SuccProb = BranchProbability::getOne();
637 else
638 SuccProb = BranchProbability(SuccProbN, SuccProbD);
639
640 return SuccProb;
641}
642
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000643/// Check if \p BB has exactly the successors in \p Successors.
644static bool
645hasSameSuccessors(MachineBasicBlock &BB,
646 SmallPtrSetImpl<const MachineBasicBlock *> &Successors) {
647 if (BB.succ_size() != Successors.size())
648 return false;
649 // We don't want to count self-loops
650 if (Successors.count(&BB))
651 return false;
652 for (MachineBasicBlock *Succ : BB.successors())
653 if (!Successors.count(Succ))
654 return false;
655 return true;
656}
657
658/// Check if a block should be tail duplicated to increase fallthrough
659/// opportunities.
Kyle Buttb15c0662017-01-31 23:48:32 +0000660/// \p BB Block to check.
661bool MachineBlockPlacement::shouldTailDuplicate(MachineBasicBlock *BB) {
662 // Blocks with single successors don't create additional fallthrough
663 // opportunities. Don't duplicate them. TODO: When conditional exits are
664 // analyzable, allow them to be duplicated.
665 bool IsSimple = TailDup.isSimpleBB(BB);
666
667 if (BB->succ_size() == 1)
668 return false;
669 return TailDup.shouldTailDuplicate(IsSimple, *BB);
670}
671
672/// Compare 2 BlockFrequency's with a small penalty for \p A.
673/// In order to be conservative, we apply a X% penalty to account for
674/// increased icache pressure and static heuristics. For small frequencies
675/// we use only the numerators to improve accuracy. For simplicity, we assume the
676/// penalty is less than 100%
677/// TODO(iteratee): Use 64-bit fixed point edge frequencies everywhere.
678static bool greaterWithBias(BlockFrequency A, BlockFrequency B,
679 uint64_t EntryFreq) {
680 BranchProbability ThresholdProb(TailDupPlacementPenalty, 100);
681 BlockFrequency Gain = A - B;
682 return (Gain / ThresholdProb).getFrequency() >= EntryFreq;
683}
684
685/// Check the edge frequencies to see if tail duplication will increase
686/// fallthroughs. It only makes sense to call this function when
687/// \p Succ would not be chosen otherwise. Tail duplication of \p Succ is
688/// always locally profitable if we would have picked \p Succ without
689/// considering duplication.
690bool MachineBlockPlacement::isProfitableToTailDup(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000691 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
Kyle Buttb15c0662017-01-31 23:48:32 +0000692 BranchProbability QProb,
Kyle Butte9425c4f2017-02-04 02:26:32 +0000693 const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
Kyle Buttb15c0662017-01-31 23:48:32 +0000694 // We need to do a probability calculation to make sure this is profitable.
695 // First: does succ have a successor that post-dominates? This affects the
696 // calculation. The 2 relevant cases are:
697 // BB BB
698 // | \Qout | \Qout
699 // P| C |P C
700 // = C' = C'
701 // | /Qin | /Qin
702 // | / | /
703 // Succ Succ
704 // / \ | \ V
705 // U/ =V |U \
706 // / \ = D
707 // D E | /
708 // | /
709 // |/
710 // PDom
711 // '=' : Branch taken for that CFG edge
712 // In the second case, Placing Succ while duplicating it into C prevents the
713 // fallthrough of Succ into either D or PDom, because they now have C as an
714 // unplaced predecessor
715
716 // Start by figuring out which case we fall into
717 MachineBasicBlock *PDom = nullptr;
718 SmallVector<MachineBasicBlock *, 4> SuccSuccs;
719 // Only scan the relevant successors
720 auto AdjustedSuccSumProb =
721 collectViableSuccessors(Succ, Chain, BlockFilter, SuccSuccs);
722 BranchProbability PProb = MBPI->getEdgeProbability(BB, Succ);
723 auto BBFreq = MBFI->getBlockFreq(BB);
724 auto SuccFreq = MBFI->getBlockFreq(Succ);
725 BlockFrequency P = BBFreq * PProb;
726 BlockFrequency Qout = BBFreq * QProb;
727 uint64_t EntryFreq = MBFI->getEntryFreq();
728 // If there are no more successors, it is profitable to copy, as it strictly
729 // increases fallthrough.
730 if (SuccSuccs.size() == 0)
731 return greaterWithBias(P, Qout, EntryFreq);
732
733 auto BestSuccSucc = BranchProbability::getZero();
734 // Find the PDom or the best Succ if no PDom exists.
735 for (MachineBasicBlock *SuccSucc : SuccSuccs) {
736 auto Prob = MBPI->getEdgeProbability(Succ, SuccSucc);
737 if (Prob > BestSuccSucc)
738 BestSuccSucc = Prob;
739 if (PDom == nullptr)
740 if (MPDT->dominates(SuccSucc, Succ)) {
741 PDom = SuccSucc;
742 break;
743 }
744 }
745 // For the comparisons, we need to know Succ's best incoming edge that isn't
746 // from BB.
747 auto SuccBestPred = BlockFrequency(0);
748 for (MachineBasicBlock *SuccPred : Succ->predecessors()) {
749 if (SuccPred == Succ || SuccPred == BB
750 || BlockToChain[SuccPred] == &Chain
751 || (BlockFilter && !BlockFilter->count(SuccPred)))
752 continue;
753 auto Freq = MBFI->getBlockFreq(SuccPred)
754 * MBPI->getEdgeProbability(SuccPred, Succ);
755 if (Freq > SuccBestPred)
756 SuccBestPred = Freq;
757 }
758 // Qin is Succ's best unplaced incoming edge that isn't BB
759 BlockFrequency Qin = SuccBestPred;
760 // If it doesn't have a post-dominating successor, here is the calculation:
761 // BB BB
762 // | \Qout | \
763 // P| C | =
764 // = C' | C
765 // | /Qin | |
766 // | / | C' (+Succ)
767 // Succ Succ /|
768 // / \ | \/ |
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000769 // U/ =V | == |
Kyle Buttb15c0662017-01-31 23:48:32 +0000770 // / \ | / \|
771 // D E D E
772 // '=' : Branch taken for that CFG edge
773 // Cost in the first case is: P + V
774 // For this calculation, we always assume P > Qout. If Qout > P
775 // The result of this function will be ignored at the caller.
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000776 // Cost in the second case is: Qout + Qin * U + P * V
Kyle Buttb15c0662017-01-31 23:48:32 +0000777
778 if (PDom == nullptr || !Succ->isSuccessor(PDom)) {
779 BranchProbability UProb = BestSuccSucc;
780 BranchProbability VProb = AdjustedSuccSumProb - UProb;
781 BlockFrequency V = SuccFreq * VProb;
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000782 BlockFrequency QinU = Qin * UProb;
Kyle Buttb15c0662017-01-31 23:48:32 +0000783 BlockFrequency BaseCost = P + V;
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000784 BlockFrequency DupCost = Qout + QinU + P * VProb;
Kyle Buttb15c0662017-01-31 23:48:32 +0000785 return greaterWithBias(BaseCost, DupCost, EntryFreq);
786 }
787 BranchProbability UProb = MBPI->getEdgeProbability(Succ, PDom);
788 BranchProbability VProb = AdjustedSuccSumProb - UProb;
789 BlockFrequency U = SuccFreq * UProb;
790 BlockFrequency V = SuccFreq * VProb;
791 // If there is a post-dominating successor, here is the calculation:
792 // BB BB BB BB
793 // | \Qout | \ | \Qout | \
794 // |P C | = |P C | =
795 // = C' |P C = C' |P C
796 // | /Qin | | | /Qin | |
797 // | / | C' (+Succ) | / | C' (+Succ)
798 // Succ Succ /| Succ Succ /|
799 // | \ V | \/ | | \ V | \/ |
800 // |U \ |U /\ | |U = |U /\ |
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000801 // = D = = \= | D | = =|
Kyle Buttb15c0662017-01-31 23:48:32 +0000802 // | / |/ D | / |/ D
803 // | / | / | = | /
804 // |/ | / |/ | =
805 // Dom Dom Dom Dom
806 // '=' : Branch taken for that CFG edge
807 // The cost for taken branches in the first case is P + U
808 // The cost in the second case (assuming independence), given the layout:
809 // BB, Succ, (C+Succ), D, Dom
810 // is Qout + P * V + Qin * U
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000811 // compare P + U vs Qout + P * U + Qin.
Kyle Buttb15c0662017-01-31 23:48:32 +0000812 //
813 // The 3rd and 4th cases cover when Dom would be chosen to follow Succ.
814 //
815 // For the 3rd case, the cost is P + 2 * V
816 // For the 4th case, the cost is Qout + Qin * U + P * V + V
817 // We choose 4 over 3 when (P + V) > Qout + Qin * U + P * V
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000818 if (UProb > AdjustedSuccSumProb / 2 &&
819 !hasBetterLayoutPredecessor(Succ, PDom, *BlockToChain[PDom], UProb, UProb,
820 Chain, BlockFilter))
Kyle Buttb15c0662017-01-31 23:48:32 +0000821 // Cases 3 & 4
822 return greaterWithBias((P + V), (Qout + Qin * UProb + P * VProb),
823 EntryFreq);
Kyle Buttb15c0662017-01-31 23:48:32 +0000824 // Cases 1 & 2
825 return greaterWithBias(
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000826 (P + U), (Qout + Qin * AdjustedSuccSumProb + P * UProb), EntryFreq);
Kyle Buttb15c0662017-01-31 23:48:32 +0000827}
828
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000829/// Check for a trellis layout. \p BB is the upper part of a trellis if its
830/// successors form the lower part of a trellis. A successor set S forms the
831/// lower part of a trellis if all of the predecessors of S are either in S or
832/// have all of S as successors. We ignore trellises where BB doesn't have 2
833/// successors because for fewer than 2, it's trivial, and for 3 or greater they
834/// are very uncommon and complex to compute optimally. Allowing edges within S
835/// is not strictly a trellis, but the same algorithm works, so we allow it.
836bool MachineBlockPlacement::isTrellis(
837 const MachineBasicBlock *BB,
838 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
839 const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
840 // Technically BB could form a trellis with branching factor higher than 2.
841 // But that's extremely uncommon.
842 if (BB->succ_size() != 2 || ViableSuccs.size() != 2)
843 return false;
844
845 SmallPtrSet<const MachineBasicBlock *, 2> Successors(BB->succ_begin(),
846 BB->succ_end());
847 // To avoid reviewing the same predecessors twice.
848 SmallPtrSet<const MachineBasicBlock *, 8> SeenPreds;
849
850 for (MachineBasicBlock *Succ : ViableSuccs) {
851 int PredCount = 0;
852 for (auto SuccPred : Succ->predecessors()) {
853 // Allow triangle successors, but don't count them.
854 if (Successors.count(SuccPred))
855 continue;
856 const BlockChain *PredChain = BlockToChain[SuccPred];
857 if (SuccPred == BB || (BlockFilter && !BlockFilter->count(SuccPred)) ||
858 PredChain == &Chain || PredChain == BlockToChain[Succ])
859 continue;
860 ++PredCount;
861 // Perform the successor check only once.
862 if (!SeenPreds.insert(SuccPred).second)
863 continue;
864 if (!hasSameSuccessors(*SuccPred, Successors))
865 return false;
866 }
867 // If one of the successors has only BB as a predecessor, it is not a
868 // trellis.
869 if (PredCount < 1)
870 return false;
871 }
872 return true;
873}
874
875/// Pick the highest total weight pair of edges that can both be laid out.
876/// The edges in \p Edges[0] are assumed to have a different destination than
877/// the edges in \p Edges[1]. Simple counting shows that the best pair is either
878/// the individual highest weight edges to the 2 different destinations, or in
879/// case of a conflict, one of them should be replaced with a 2nd best edge.
880std::pair<MachineBlockPlacement::WeightedEdge,
881 MachineBlockPlacement::WeightedEdge>
882MachineBlockPlacement::getBestNonConflictingEdges(
883 const MachineBasicBlock *BB,
884 SmallVector<SmallVector<MachineBlockPlacement::WeightedEdge, 8>, 2>
885 &Edges) {
886 // Sort the edges, and then for each successor, find the best incoming
887 // predecessor. If the best incoming predecessors aren't the same,
888 // then that is clearly the best layout. If there is a conflict, one of the
889 // successors will have to fallthrough from the second best predecessor. We
890 // compare which combination is better overall.
891
892 // Sort for highest frequency.
893 auto Cmp = [](WeightedEdge A, WeightedEdge B) { return A.Weight > B.Weight; };
894
895 std::stable_sort(Edges[0].begin(), Edges[0].end(), Cmp);
896 std::stable_sort(Edges[1].begin(), Edges[1].end(), Cmp);
897 auto BestA = Edges[0].begin();
898 auto BestB = Edges[1].begin();
899 // Arrange for the correct answer to be in BestA and BestB
900 // If the 2 best edges don't conflict, the answer is already there.
901 if (BestA->Src == BestB->Src) {
902 // Compare the total fallthrough of (Best + Second Best) for both pairs
903 auto SecondBestA = std::next(BestA);
904 auto SecondBestB = std::next(BestB);
905 BlockFrequency BestAScore = BestA->Weight + SecondBestB->Weight;
906 BlockFrequency BestBScore = BestB->Weight + SecondBestA->Weight;
907 if (BestAScore < BestBScore)
908 BestA = SecondBestA;
909 else
910 BestB = SecondBestB;
911 }
912 // Arrange for the BB edge to be in BestA if it exists.
913 if (BestB->Src == BB)
914 std::swap(BestA, BestB);
915 return std::make_pair(*BestA, *BestB);
916}
917
918/// Get the best successor from \p BB based on \p BB being part of a trellis.
919/// We only handle trellises with 2 successors, so the algorithm is
920/// straightforward: Find the best pair of edges that don't conflict. We find
921/// the best incoming edge for each successor in the trellis. If those conflict,
922/// we consider which of them should be replaced with the second best.
923/// Upon return the two best edges will be in \p BestEdges. If one of the edges
924/// comes from \p BB, it will be in \p BestEdges[0]
925MachineBlockPlacement::BlockAndTailDupResult
926MachineBlockPlacement::getBestTrellisSuccessor(
927 const MachineBasicBlock *BB,
928 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
929 BranchProbability AdjustedSumProb, const BlockChain &Chain,
930 const BlockFilterSet *BlockFilter) {
931
932 BlockAndTailDupResult Result = {nullptr, false};
933 SmallPtrSet<const MachineBasicBlock *, 4> Successors(BB->succ_begin(),
934 BB->succ_end());
935
936 // We assume size 2 because it's common. For general n, we would have to do
937 // the Hungarian algorithm, but it's not worth the complexity because more
938 // than 2 successors is fairly uncommon, and a trellis even more so.
939 if (Successors.size() != 2 || ViableSuccs.size() != 2)
940 return Result;
941
942 // Collect the edge frequencies of all edges that form the trellis.
943 SmallVector<SmallVector<WeightedEdge, 8>, 2> Edges(2);
944 int SuccIndex = 0;
945 for (auto Succ : ViableSuccs) {
946 for (MachineBasicBlock *SuccPred : Succ->predecessors()) {
947 // Skip any placed predecessors that are not BB
948 if (SuccPred != BB)
949 if ((BlockFilter && !BlockFilter->count(SuccPred)) ||
950 BlockToChain[SuccPred] == &Chain ||
951 BlockToChain[SuccPred] == BlockToChain[Succ])
952 continue;
953 BlockFrequency EdgeFreq = MBFI->getBlockFreq(SuccPred) *
954 MBPI->getEdgeProbability(SuccPred, Succ);
955 Edges[SuccIndex].push_back({EdgeFreq, SuccPred, Succ});
956 }
957 ++SuccIndex;
958 }
959
960 // Pick the best combination of 2 edges from all the edges in the trellis.
961 WeightedEdge BestA, BestB;
962 std::tie(BestA, BestB) = getBestNonConflictingEdges(BB, Edges);
963
964 if (BestA.Src != BB) {
965 // If we have a trellis, and BB doesn't have the best fallthrough edges,
966 // we shouldn't choose any successor. We've already looked and there's a
967 // better fallthrough edge for all the successors.
968 DEBUG(dbgs() << "Trellis, but not one of the chosen edges.\n");
969 return Result;
970 }
971
972 // Did we pick the triangle edge? If tail-duplication is profitable, do
973 // that instead. Otherwise merge the triangle edge now while we know it is
974 // optimal.
975 if (BestA.Dest == BestB.Src) {
976 // The edges are BB->Succ1->Succ2, and we're looking to see if BB->Succ2
977 // would be better.
978 MachineBasicBlock *Succ1 = BestA.Dest;
979 MachineBasicBlock *Succ2 = BestB.Dest;
980 // Check to see if tail-duplication would be profitable.
981 if (TailDupPlacement && shouldTailDuplicate(Succ2) &&
982 canTailDuplicateUnplacedPreds(BB, Succ2, Chain, BlockFilter) &&
983 isProfitableToTailDup(BB, Succ2, MBPI->getEdgeProbability(BB, Succ1),
984 Chain, BlockFilter)) {
985 DEBUG(BranchProbability Succ2Prob = getAdjustedProbability(
986 MBPI->getEdgeProbability(BB, Succ2), AdjustedSumProb);
987 dbgs() << " Selected: " << getBlockName(Succ2)
988 << ", probability: " << Succ2Prob << " (Tail Duplicate)\n");
989 Result.BB = Succ2;
990 Result.ShouldTailDup = true;
991 return Result;
992 }
993 }
994 // We have already computed the optimal edge for the other side of the
995 // trellis.
Kyle Buttebe6cc42017-02-23 21:22:24 +0000996 ComputedEdges[BestB.Src] = { BestB.Dest, false };
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000997
998 auto TrellisSucc = BestA.Dest;
999 DEBUG(BranchProbability SuccProb = getAdjustedProbability(
1000 MBPI->getEdgeProbability(BB, TrellisSucc), AdjustedSumProb);
1001 dbgs() << " Selected: " << getBlockName(TrellisSucc)
1002 << ", probability: " << SuccProb << " (Trellis)\n");
1003 Result.BB = TrellisSucc;
1004 return Result;
1005}
Kyle Buttb15c0662017-01-31 23:48:32 +00001006
1007/// When the option TailDupPlacement is on, this method checks if the
1008/// fallthrough candidate block \p Succ (of block \p BB) can be tail-duplicated
1009/// into all of its unplaced, unfiltered predecessors, that are not BB.
1010bool MachineBlockPlacement::canTailDuplicateUnplacedPreds(
Kyle Butte9425c4f2017-02-04 02:26:32 +00001011 const MachineBasicBlock *BB, MachineBasicBlock *Succ,
1012 const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
Kyle Buttb15c0662017-01-31 23:48:32 +00001013 if (!shouldTailDuplicate(Succ))
1014 return false;
1015
Kyle Butt7fbec9b2017-02-15 19:49:14 +00001016 // For CFG checking.
1017 SmallPtrSet<const MachineBasicBlock *, 4> Successors(BB->succ_begin(),
1018 BB->succ_end());
Kyle Buttb15c0662017-01-31 23:48:32 +00001019 for (MachineBasicBlock *Pred : Succ->predecessors()) {
1020 // Make sure all unplaced and unfiltered predecessors can be
1021 // tail-duplicated into.
Kyle Butte9425c4f2017-02-04 02:26:32 +00001022 // Skip any blocks that are already placed or not in this loop.
Kyle Buttb15c0662017-01-31 23:48:32 +00001023 if (Pred == BB || (BlockFilter && !BlockFilter->count(Pred))
1024 || BlockToChain[Pred] == &Chain)
1025 continue;
Kyle Butt7fbec9b2017-02-15 19:49:14 +00001026 if (!TailDup.canTailDuplicate(Succ, Pred)) {
1027 if (Successors.size() > 1 && hasSameSuccessors(*Pred, Successors))
1028 // This will result in a trellis after tail duplication, so we don't
1029 // need to copy Succ into this predecessor. In the presence
1030 // of a trellis tail duplication can continue to be profitable.
1031 // For example:
1032 // A A
1033 // |\ |\
1034 // | \ | \
1035 // | C | C+BB
1036 // | / | |
1037 // |/ | |
1038 // BB => BB |
1039 // |\ |\/|
1040 // | \ |/\|
1041 // | D | D
1042 // | / | /
1043 // |/ |/
1044 // Succ Succ
1045 //
1046 // After BB was duplicated into C, the layout looks like the one on the
1047 // right. BB and C now have the same successors. When considering
1048 // whether Succ can be duplicated into all its unplaced predecessors, we
1049 // ignore C.
1050 // We can do this because C already has a profitable fallthrough, namely
1051 // D. TODO(iteratee): ignore sufficiently cold predecessors for
1052 // duplication and for this test.
1053 //
1054 // This allows trellises to be laid out in 2 separate chains
1055 // (A,B,Succ,...) and later (C,D,...) This is a reasonable heuristic
1056 // because it allows the creation of 2 fallthrough paths with links
1057 // between them, and we correctly identify the best layout for these
1058 // CFGs. We want to extend trellises that the user created in addition
1059 // to trellises created by tail-duplication, so we just look for the
1060 // CFG.
1061 continue;
Kyle Buttb15c0662017-01-31 23:48:32 +00001062 return false;
Kyle Butt7fbec9b2017-02-15 19:49:14 +00001063 }
Kyle Buttb15c0662017-01-31 23:48:32 +00001064 }
1065 return true;
1066}
1067
Xinliang David Li071d0f12016-06-12 16:54:03 +00001068/// When the option OutlineOptionalBranches is on, this method
1069/// checks if the fallthrough candidate block \p Succ (of block
1070/// \p BB) also has other unscheduled predecessor blocks which
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001071/// are also successors of \p BB (forming triangular shape CFG).
Xinliang David Li071d0f12016-06-12 16:54:03 +00001072/// If none of such predecessors are small, it returns true.
1073/// The caller can choose to select \p Succ as the layout successors
1074/// so that \p Succ's predecessors (optional branches) can be
1075/// outlined.
1076/// FIXME: fold this with more general layout cost analysis.
1077bool MachineBlockPlacement::shouldPredBlockBeOutlined(
Kyle Butte9425c4f2017-02-04 02:26:32 +00001078 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
1079 const BlockChain &Chain, const BlockFilterSet *BlockFilter,
1080 BranchProbability SuccProb, BranchProbability HotProb) {
Xinliang David Li071d0f12016-06-12 16:54:03 +00001081 if (!OutlineOptionalBranches)
1082 return false;
1083 // If we outline optional branches, look whether Succ is unavoidable, i.e.
1084 // dominates all terminators of the MachineFunction. If it does, other
1085 // successors must be optional. Don't do this for cold branches.
1086 if (SuccProb > HotProb.getCompl() && UnavoidableBlocks.count(Succ) > 0) {
1087 for (MachineBasicBlock *Pred : Succ->predecessors()) {
1088 // Check whether there is an unplaced optional branch.
1089 if (Pred == Succ || (BlockFilter && !BlockFilter->count(Pred)) ||
1090 BlockToChain[Pred] == &Chain)
1091 continue;
1092 // Check whether the optional branch has exactly one BB.
1093 if (Pred->pred_size() > 1 || *Pred->pred_begin() != BB)
1094 continue;
1095 // Check whether the optional branch is small.
1096 if (Pred->size() < OutlineOptionalThreshold)
1097 return false;
1098 }
1099 return true;
1100 } else
1101 return false;
1102}
1103
Dehao Chen9f2bdfb2016-06-14 22:27:17 +00001104// When profile is not present, return the StaticLikelyProb.
1105// When profile is available, we need to handle the triangle-shape CFG.
1106static BranchProbability getLayoutSuccessorProbThreshold(
Kyle Butte9425c4f2017-02-04 02:26:32 +00001107 const MachineBasicBlock *BB) {
Dehao Chen9f2bdfb2016-06-14 22:27:17 +00001108 if (!BB->getParent()->getFunction()->getEntryCount())
1109 return BranchProbability(StaticLikelyProb, 100);
1110 if (BB->succ_size() == 2) {
1111 const MachineBasicBlock *Succ1 = *BB->succ_begin();
1112 const MachineBasicBlock *Succ2 = *(BB->succ_begin() + 1);
Xinliang David Lie34ed832016-06-15 03:03:30 +00001113 if (Succ1->isSuccessor(Succ2) || Succ2->isSuccessor(Succ1)) {
1114 /* See case 1 below for the cost analysis. For BB->Succ to
1115 * be taken with smaller cost, the following needs to hold:
Kyle Buttb15c0662017-01-31 23:48:32 +00001116 * Prob(BB->Succ) > 2 * Prob(BB->Pred)
1117 * So the threshold T in the calculation below
1118 * (1-T) * Prob(BB->Succ) > T * Prob(BB->Pred)
1119 * So T / (1 - T) = 2, Yielding T = 2/3
1120 * Also adding user specified branch bias, we have
Xinliang David Lie34ed832016-06-15 03:03:30 +00001121 * T = (2/3)*(ProfileLikelyProb/50)
1122 * = (2*ProfileLikelyProb)/150)
1123 */
1124 return BranchProbability(2 * ProfileLikelyProb, 150);
1125 }
Dehao Chen9f2bdfb2016-06-14 22:27:17 +00001126 }
1127 return BranchProbability(ProfileLikelyProb, 100);
Xinliang David Licbf12142016-06-13 20:24:19 +00001128}
1129
1130/// Checks to see if the layout candidate block \p Succ has a better layout
1131/// predecessor than \c BB. If yes, returns true.
Kyle Buttb15c0662017-01-31 23:48:32 +00001132/// \p SuccProb: The probability adjusted for only remaining blocks.
1133/// Only used for logging
1134/// \p RealSuccProb: The un-adjusted probability.
1135/// \p Chain: The chain that BB belongs to and Succ is being considered for.
1136/// \p BlockFilter: if non-null, the set of blocks that make up the loop being
1137/// considered
Xinliang David Licbf12142016-06-13 20:24:19 +00001138bool MachineBlockPlacement::hasBetterLayoutPredecessor(
Kyle Butte9425c4f2017-02-04 02:26:32 +00001139 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
1140 const BlockChain &SuccChain, BranchProbability SuccProb,
1141 BranchProbability RealSuccProb, const BlockChain &Chain,
1142 const BlockFilterSet *BlockFilter) {
Xinliang David Licbf12142016-06-13 20:24:19 +00001143
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001144 // There isn't a better layout when there are no unscheduled predecessors.
Xinliang David Licbf12142016-06-13 20:24:19 +00001145 if (SuccChain.UnscheduledPredecessors == 0)
1146 return false;
1147
1148 // There are two basic scenarios here:
1149 // -------------------------------------
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001150 // Case 1: triangular shape CFG (if-then):
Xinliang David Licbf12142016-06-13 20:24:19 +00001151 // BB
1152 // | \
1153 // | \
1154 // | Pred
1155 // | /
1156 // Succ
1157 // In this case, we are evaluating whether to select edge -> Succ, e.g.
1158 // set Succ as the layout successor of BB. Picking Succ as BB's
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001159 // successor breaks the CFG constraints (FIXME: define these constraints).
1160 // With this layout, Pred BB
Xinliang David Licbf12142016-06-13 20:24:19 +00001161 // is forced to be outlined, so the overall cost will be cost of the
1162 // branch taken from BB to Pred, plus the cost of back taken branch
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001163 // from Pred to Succ, as well as the additional cost associated
Xinliang David Licbf12142016-06-13 20:24:19 +00001164 // with the needed unconditional jump instruction from Pred To Succ.
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001165
Xinliang David Licbf12142016-06-13 20:24:19 +00001166 // The cost of the topological order layout is the taken branch cost
1167 // from BB to Succ, so to make BB->Succ a viable candidate, the following
1168 // must hold:
1169 // 2 * freq(BB->Pred) * taken_branch_cost + unconditional_jump_cost
1170 // < freq(BB->Succ) * taken_branch_cost.
1171 // Ignoring unconditional jump cost, we get
1172 // freq(BB->Succ) > 2 * freq(BB->Pred), i.e.,
1173 // prob(BB->Succ) > 2 * prob(BB->Pred)
1174 //
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001175 // When real profile data is available, we can precisely compute the
1176 // probability threshold that is needed for edge BB->Succ to be considered.
1177 // Without profile data, the heuristic requires the branch bias to be
Xinliang David Licbf12142016-06-13 20:24:19 +00001178 // a lot larger to make sure the signal is very strong (e.g. 80% default).
1179 // -----------------------------------------------------------------
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001180 // Case 2: diamond like CFG (if-then-else):
Xinliang David Licbf12142016-06-13 20:24:19 +00001181 // S
1182 // / \
1183 // | \
1184 // BB Pred
1185 // \ /
1186 // Succ
1187 // ..
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001188 //
1189 // The current block is BB and edge BB->Succ is now being evaluated.
1190 // Note that edge S->BB was previously already selected because
1191 // prob(S->BB) > prob(S->Pred).
1192 // At this point, 2 blocks can be placed after BB: Pred or Succ. If we
1193 // choose Pred, we will have a topological ordering as shown on the left
1194 // in the picture below. If we choose Succ, we have the solution as shown
1195 // on the right:
1196 //
1197 // topo-order:
1198 //
1199 // S----- ---S
1200 // | | | |
1201 // ---BB | | BB
1202 // | | | |
1203 // | pred-- | Succ--
1204 // | | | |
1205 // ---succ ---pred--
1206 //
1207 // cost = freq(S->Pred) + freq(BB->Succ) cost = 2 * freq (S->Pred)
1208 // = freq(S->Pred) + freq(S->BB)
1209 //
1210 // If we have profile data (i.e, branch probabilities can be trusted), the
1211 // cost (number of taken branches) with layout S->BB->Succ->Pred is 2 *
1212 // freq(S->Pred) while the cost of topo order is freq(S->Pred) + freq(S->BB).
1213 // We know Prob(S->BB) > Prob(S->Pred), so freq(S->BB) > freq(S->Pred), which
1214 // means the cost of topological order is greater.
Xinliang David Licbf12142016-06-13 20:24:19 +00001215 // When profile data is not available, however, we need to be more
1216 // conservative. If the branch prediction is wrong, breaking the topo-order
1217 // will actually yield a layout with large cost. For this reason, we need
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001218 // strong biased branch at block S with Prob(S->BB) in order to select
1219 // BB->Succ. This is equivalent to looking the CFG backward with backward
Xinliang David Licbf12142016-06-13 20:24:19 +00001220 // edge: Prob(Succ->BB) needs to >= HotProb in order to be selected (without
1221 // profile data).
Kyle Butt02d8d052016-07-29 18:09:28 +00001222 // --------------------------------------------------------------------------
1223 // Case 3: forked diamond
1224 // S
1225 // / \
1226 // / \
1227 // BB Pred
1228 // | \ / |
1229 // | \ / |
1230 // | X |
1231 // | / \ |
1232 // | / \ |
1233 // S1 S2
1234 //
1235 // The current block is BB and edge BB->S1 is now being evaluated.
1236 // As above S->BB was already selected because
1237 // prob(S->BB) > prob(S->Pred). Assume that prob(BB->S1) >= prob(BB->S2).
1238 //
1239 // topo-order:
1240 //
1241 // S-------| ---S
1242 // | | | |
1243 // ---BB | | BB
1244 // | | | |
1245 // | Pred----| | S1----
1246 // | | | |
1247 // --(S1 or S2) ---Pred--
Kyle Butt7fbec9b2017-02-15 19:49:14 +00001248 // |
1249 // S2
Kyle Butt02d8d052016-07-29 18:09:28 +00001250 //
1251 // topo-cost = freq(S->Pred) + freq(BB->S1) + freq(BB->S2)
1252 // + min(freq(Pred->S1), freq(Pred->S2))
1253 // Non-topo-order cost:
Kyle Butt02d8d052016-07-29 18:09:28 +00001254 // non-topo-cost = 2 * freq(S->Pred) + freq(BB->S2).
1255 // To be conservative, we can assume that min(freq(Pred->S1), freq(Pred->S2))
1256 // is 0. Then the non topo layout is better when
1257 // freq(S->Pred) < freq(BB->S1).
1258 // This is exactly what is checked below.
1259 // Note there are other shapes that apply (Pred may not be a single block,
1260 // but they all fit this general pattern.)
Dehao Chen9f2bdfb2016-06-14 22:27:17 +00001261 BranchProbability HotProb = getLayoutSuccessorProbThreshold(BB);
Xinliang David Licbf12142016-06-13 20:24:19 +00001262
Xinliang David Licbf12142016-06-13 20:24:19 +00001263 // Make sure that a hot successor doesn't have a globally more
1264 // important predecessor.
1265 BlockFrequency CandidateEdgeFreq = MBFI->getBlockFreq(BB) * RealSuccProb;
1266 bool BadCFGConflict = false;
1267
1268 for (MachineBasicBlock *Pred : Succ->predecessors()) {
1269 if (Pred == Succ || BlockToChain[Pred] == &SuccChain ||
1270 (BlockFilter && !BlockFilter->count(Pred)) ||
Kyle Buttb15c0662017-01-31 23:48:32 +00001271 BlockToChain[Pred] == &Chain ||
1272 // This check is redundant except for look ahead. This function is
1273 // called for lookahead by isProfitableToTailDup when BB hasn't been
1274 // placed yet.
1275 (Pred == BB))
Xinliang David Licbf12142016-06-13 20:24:19 +00001276 continue;
Kyle Butt02d8d052016-07-29 18:09:28 +00001277 // Do backward checking.
1278 // For all cases above, we need a backward checking to filter out edges that
Kyle Buttb15c0662017-01-31 23:48:32 +00001279 // are not 'strongly' biased.
Xinliang David Licbf12142016-06-13 20:24:19 +00001280 // BB Pred
1281 // \ /
1282 // Succ
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001283 // We select edge BB->Succ if
Xinliang David Licbf12142016-06-13 20:24:19 +00001284 // freq(BB->Succ) > freq(Succ) * HotProb
1285 // i.e. freq(BB->Succ) > freq(BB->Succ) * HotProb + freq(Pred->Succ) *
1286 // HotProb
1287 // i.e. freq((BB->Succ) * (1 - HotProb) > freq(Pred->Succ) * HotProb
Kyle Butt02d8d052016-07-29 18:09:28 +00001288 // Case 1 is covered too, because the first equation reduces to:
1289 // prob(BB->Succ) > HotProb. (freq(Succ) = freq(BB) for a triangle)
Xinliang David Licbf12142016-06-13 20:24:19 +00001290 BlockFrequency PredEdgeFreq =
1291 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
1292 if (PredEdgeFreq * HotProb >= CandidateEdgeFreq * HotProb.getCompl()) {
1293 BadCFGConflict = true;
1294 break;
1295 }
1296 }
1297
1298 if (BadCFGConflict) {
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001299 DEBUG(dbgs() << " Not a candidate: " << getBlockName(Succ) << " -> " << SuccProb
Xinliang David Licbf12142016-06-13 20:24:19 +00001300 << " (prob) (non-cold CFG conflict)\n");
1301 return true;
1302 }
1303
1304 return false;
1305}
1306
Xinliang David Li594ffa32016-06-11 18:35:40 +00001307/// \brief Select the best successor for a block.
1308///
1309/// This looks across all successors of a particular block and attempts to
1310/// select the "best" one to be the layout successor. It only considers direct
1311/// successors which also pass the block filter. It will attempt to avoid
1312/// breaking CFG structure, but cave and break such structures in the case of
1313/// very hot successor edges.
1314///
Kyle Buttb15c0662017-01-31 23:48:32 +00001315/// \returns The best successor block found, or null if none are viable, along
1316/// with a boolean indicating if tail duplication is necessary.
1317MachineBlockPlacement::BlockAndTailDupResult
Kyle Butte9425c4f2017-02-04 02:26:32 +00001318MachineBlockPlacement::selectBestSuccessor(
1319 const MachineBasicBlock *BB, const BlockChain &Chain,
1320 const BlockFilterSet *BlockFilter) {
Xinliang David Li594ffa32016-06-11 18:35:40 +00001321 const BranchProbability HotProb(StaticLikelyProb, 100);
1322
Kyle Buttb15c0662017-01-31 23:48:32 +00001323 BlockAndTailDupResult BestSucc = { nullptr, false };
Xinliang David Li594ffa32016-06-11 18:35:40 +00001324 auto BestProb = BranchProbability::getZero();
1325
1326 SmallVector<MachineBasicBlock *, 4> Successors;
1327 auto AdjustedSumProb =
1328 collectViableSuccessors(BB, Chain, BlockFilter, Successors);
1329
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001330 DEBUG(dbgs() << "Selecting best successor for: " << getBlockName(BB) << "\n");
Kyle Buttb15c0662017-01-31 23:48:32 +00001331
Kyle Buttebe6cc42017-02-23 21:22:24 +00001332 // if we already precomputed the best successor for BB, return that if still
1333 // applicable.
1334 auto FoundEdge = ComputedEdges.find(BB);
1335 if (FoundEdge != ComputedEdges.end()) {
1336 MachineBasicBlock *Succ = FoundEdge->second.BB;
1337 ComputedEdges.erase(FoundEdge);
Kyle Butt7fbec9b2017-02-15 19:49:14 +00001338 BlockChain *SuccChain = BlockToChain[Succ];
1339 if (BB->isSuccessor(Succ) && (!BlockFilter || BlockFilter->count(Succ)) &&
Kyle Buttebe6cc42017-02-23 21:22:24 +00001340 SuccChain != &Chain && Succ == *SuccChain->begin())
1341 return FoundEdge->second;
Kyle Butt7fbec9b2017-02-15 19:49:14 +00001342 }
1343
1344 // if BB is part of a trellis, Use the trellis to determine the optimal
1345 // fallthrough edges
1346 if (isTrellis(BB, Successors, Chain, BlockFilter))
1347 return getBestTrellisSuccessor(BB, Successors, AdjustedSumProb, Chain,
1348 BlockFilter);
1349
Kyle Buttb15c0662017-01-31 23:48:32 +00001350 // For blocks with CFG violations, we may be able to lay them out anyway with
1351 // tail-duplication. We keep this vector so we can perform the probability
1352 // calculations the minimum number of times.
1353 SmallVector<std::tuple<BranchProbability, MachineBasicBlock *>, 4>
1354 DupCandidates;
Cong Hou41cf1a52015-11-18 00:52:52 +00001355 for (MachineBasicBlock *Succ : Successors) {
Xinliang David Li594ffa32016-06-11 18:35:40 +00001356 auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ);
1357 BranchProbability SuccProb =
1358 getAdjustedProbability(RealSuccProb, AdjustedSumProb);
Chandler Carruthb3361722011-11-13 11:34:53 +00001359
Xinliang David Li071d0f12016-06-12 16:54:03 +00001360 // This heuristic is off by default.
1361 if (shouldPredBlockBeOutlined(BB, Succ, Chain, BlockFilter, SuccProb,
Kyle Buttb15c0662017-01-31 23:48:32 +00001362 HotProb)) {
1363 BestSucc.BB = Succ;
1364 return BestSucc;
1365 }
Daniel Jasper471e8562015-03-04 11:05:34 +00001366
Cong Hou41cf1a52015-11-18 00:52:52 +00001367 BlockChain &SuccChain = *BlockToChain[Succ];
Xinliang David Licbf12142016-06-13 20:24:19 +00001368 // Skip the edge \c BB->Succ if block \c Succ has a better layout
1369 // predecessor that yields lower global cost.
1370 if (hasBetterLayoutPredecessor(BB, Succ, SuccChain, SuccProb, RealSuccProb,
Kyle Buttb15c0662017-01-31 23:48:32 +00001371 Chain, BlockFilter)) {
1372 // If tail duplication would make Succ profitable, place it.
1373 if (TailDupPlacement && shouldTailDuplicate(Succ))
1374 DupCandidates.push_back(std::make_tuple(SuccProb, Succ));
Xinliang David Licbf12142016-06-13 20:24:19 +00001375 continue;
Kyle Buttb15c0662017-01-31 23:48:32 +00001376 }
Chandler Carruth18dfac32011-11-20 11:22:06 +00001377
Xinliang David Licbf12142016-06-13 20:24:19 +00001378 DEBUG(
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001379 dbgs() << " Candidate: " << getBlockName(Succ) << ", probability: "
1380 << SuccProb
Xinliang David Licbf12142016-06-13 20:24:19 +00001381 << (SuccChain.UnscheduledPredecessors != 0 ? " (CFG break)" : "")
1382 << "\n");
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001383
Kyle Buttb15c0662017-01-31 23:48:32 +00001384 if (BestSucc.BB && BestProb >= SuccProb) {
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001385 DEBUG(dbgs() << " Not the best candidate, continuing\n");
Chandler Carruthb3361722011-11-13 11:34:53 +00001386 continue;
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001387 }
1388
1389 DEBUG(dbgs() << " Setting it as best candidate\n");
Kyle Buttb15c0662017-01-31 23:48:32 +00001390 BestSucc.BB = Succ;
Cong Houd97c1002015-12-01 05:29:22 +00001391 BestProb = SuccProb;
Chandler Carruthb3361722011-11-13 11:34:53 +00001392 }
Kyle Buttb15c0662017-01-31 23:48:32 +00001393 // Handle the tail duplication candidates in order of decreasing probability.
1394 // Stop at the first one that is profitable. Also stop if they are less
1395 // profitable than BestSucc. Position is important because we preserve it and
1396 // prefer first best match. Here we aren't comparing in order, so we capture
1397 // the position instead.
1398 if (DupCandidates.size() != 0) {
1399 auto cmp =
1400 [](const std::tuple<BranchProbability, MachineBasicBlock *> &a,
1401 const std::tuple<BranchProbability, MachineBasicBlock *> &b) {
1402 return std::get<0>(a) > std::get<0>(b);
1403 };
1404 std::stable_sort(DupCandidates.begin(), DupCandidates.end(), cmp);
1405 }
1406 for(auto &Tup : DupCandidates) {
1407 BranchProbability DupProb;
1408 MachineBasicBlock *Succ;
1409 std::tie(DupProb, Succ) = Tup;
1410 if (DupProb < BestProb)
1411 break;
1412 if (canTailDuplicateUnplacedPreds(BB, Succ, Chain, BlockFilter)
1413 // If tail duplication gives us fallthrough when we otherwise wouldn't
1414 // have it, that is a strict gain.
1415 && (BestSucc.BB == nullptr
1416 || isProfitableToTailDup(BB, Succ, BestProb, Chain,
1417 BlockFilter))) {
1418 DEBUG(
1419 dbgs() << " Candidate: " << getBlockName(Succ) << ", probability: "
1420 << DupProb
1421 << " (Tail Duplicate)\n");
1422 BestSucc.BB = Succ;
1423 BestSucc.ShouldTailDup = true;
1424 break;
1425 }
1426 }
1427
1428 if (BestSucc.BB)
1429 DEBUG(dbgs() << " Selected: " << getBlockName(BestSucc.BB) << "\n");
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001430
Chandler Carruthb3361722011-11-13 11:34:53 +00001431 return BestSucc;
1432}
1433
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001434/// \brief Select the best block from a worklist.
1435///
1436/// This looks through the provided worklist as a list of candidate basic
1437/// blocks and select the most profitable one to place. The definition of
1438/// profitable only really makes sense in the context of a loop. This returns
1439/// the most frequently visited block in the worklist, which in the case of
1440/// a loop, is the one most desirable to be physically close to the rest of the
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001441/// loop body in order to improve i-cache behavior.
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001442///
1443/// \returns The best block found, or null if none are viable.
1444MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
Kyle Butte9425c4f2017-02-04 02:26:32 +00001445 const BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList) {
Chandler Carruth0af6a0b2011-11-14 09:46:33 +00001446 // Once we need to walk the worklist looking for a candidate, cleanup the
1447 // worklist of already placed entries.
1448 // FIXME: If this shows up on profiles, it could be folded (at the cost of
1449 // some code complexity) into the loop below.
David Majnemerc7004902016-08-12 04:32:37 +00001450 WorkList.erase(remove_if(WorkList,
1451 [&](MachineBasicBlock *BB) {
1452 return BlockToChain.lookup(BB) == &Chain;
1453 }),
Chandler Carruth0af6a0b2011-11-14 09:46:33 +00001454 WorkList.end());
1455
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001456 if (WorkList.empty())
1457 return nullptr;
1458
1459 bool IsEHPad = WorkList[0]->isEHPad();
1460
Craig Topperc0196b12014-04-14 00:51:57 +00001461 MachineBasicBlock *BestBlock = nullptr;
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001462 BlockFrequency BestFreq;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001463 for (MachineBasicBlock *MBB : WorkList) {
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001464 assert(MBB->isEHPad() == IsEHPad);
1465
Chandler Carruth7a715da2015-03-05 03:19:05 +00001466 BlockChain &SuccChain = *BlockToChain[MBB];
Philip Reames02e11322016-03-02 22:40:51 +00001467 if (&SuccChain == &Chain)
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001468 continue;
Junmo Park4ba6cf62016-03-11 05:07:07 +00001469
Philip Reamesae27b232016-03-03 00:58:43 +00001470 assert(SuccChain.UnscheduledPredecessors == 0 && "Found CFG-violating block");
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001471
Chandler Carruth7a715da2015-03-05 03:19:05 +00001472 BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
1473 DEBUG(dbgs() << " " << getBlockName(MBB) << " -> ";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001474 MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001475
1476 // For ehpad, we layout the least probable first as to avoid jumping back
1477 // from least probable landingpads to more probable ones.
1478 //
1479 // FIXME: Using probability is probably (!) not the best way to achieve
1480 // this. We should probably have a more principled approach to layout
1481 // cleanup code.
1482 //
1483 // The goal is to get:
1484 //
1485 // +--------------------------+
1486 // | V
1487 // InnerLp -> InnerCleanup OuterLp -> OuterCleanup -> Resume
1488 //
1489 // Rather than:
1490 //
1491 // +-------------------------------------+
1492 // V |
1493 // OuterLp -> OuterCleanup -> Resume InnerLp -> InnerCleanup
1494 if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq)))
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001495 continue;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001496
Chandler Carruth7a715da2015-03-05 03:19:05 +00001497 BestBlock = MBB;
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001498 BestFreq = CandidateFreq;
1499 }
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001500
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001501 return BestBlock;
1502}
1503
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001504/// \brief Retrieve the first unplaced basic block.
1505///
1506/// This routine is called when we are unable to use the CFG to walk through
1507/// all of the basic blocks and form a chain due to unnatural loops in the CFG.
Chandler Carruth9b548a7f2011-11-15 06:26:43 +00001508/// We walk through the function's blocks in order, starting from the
1509/// LastUnplacedBlockIt. We update this iterator on each call to avoid
1510/// re-scanning the entire sequence on repeated calls to this routine.
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001511MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
Xinliang David Li52530a72016-06-13 22:23:44 +00001512 const BlockChain &PlacedChain,
Chandler Carruth9b548a7f2011-11-15 06:26:43 +00001513 MachineFunction::iterator &PrevUnplacedBlockIt,
Jakub Staszak90616162011-12-21 23:02:08 +00001514 const BlockFilterSet *BlockFilter) {
Xinliang David Li52530a72016-06-13 22:23:44 +00001515 for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F->end(); I != E;
Chandler Carruth9b548a7f2011-11-15 06:26:43 +00001516 ++I) {
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001517 if (BlockFilter && !BlockFilter->count(&*I))
Chandler Carruth9b548a7f2011-11-15 06:26:43 +00001518 continue;
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001519 if (BlockToChain[&*I] != &PlacedChain) {
Chandler Carruth9b548a7f2011-11-15 06:26:43 +00001520 PrevUnplacedBlockIt = I;
Chandler Carruth4a87aa02011-11-23 03:03:21 +00001521 // Now select the head of the chain to which the unplaced block belongs
1522 // as the block to place. This will force the entire chain to be placed,
1523 // and satisfies the requirements of merging chains.
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001524 return *BlockToChain[&*I]->begin();
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001525 }
1526 }
Craig Topperc0196b12014-04-14 00:51:57 +00001527 return nullptr;
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001528}
1529
Amaury Secheteae09c22016-03-14 21:24:11 +00001530void MachineBlockPlacement::fillWorkLists(
Kyle Butte9425c4f2017-02-04 02:26:32 +00001531 const MachineBasicBlock *MBB,
Amaury Secheteae09c22016-03-14 21:24:11 +00001532 SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
Amaury Secheteae09c22016-03-14 21:24:11 +00001533 const BlockFilterSet *BlockFilter = nullptr) {
1534 BlockChain &Chain = *BlockToChain[MBB];
1535 if (!UpdatedPreds.insert(&Chain).second)
1536 return;
1537
1538 assert(Chain.UnscheduledPredecessors == 0);
1539 for (MachineBasicBlock *ChainBB : Chain) {
1540 assert(BlockToChain[ChainBB] == &Chain);
1541 for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
1542 if (BlockFilter && !BlockFilter->count(Pred))
1543 continue;
1544 if (BlockToChain[Pred] == &Chain)
1545 continue;
1546 ++Chain.UnscheduledPredecessors;
1547 }
1548 }
1549
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001550 if (Chain.UnscheduledPredecessors != 0)
1551 return;
1552
Kyle Butte9425c4f2017-02-04 02:26:32 +00001553 MachineBasicBlock *BB = *Chain.begin();
1554 if (BB->isEHPad())
1555 EHPadWorkList.push_back(BB);
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001556 else
Kyle Butte9425c4f2017-02-04 02:26:32 +00001557 BlockWorkList.push_back(BB);
Amaury Secheteae09c22016-03-14 21:24:11 +00001558}
1559
Chandler Carruth8d150782011-11-13 11:20:44 +00001560void MachineBlockPlacement::buildChain(
Kyle Butte9425c4f2017-02-04 02:26:32 +00001561 const MachineBasicBlock *HeadBB, BlockChain &Chain,
Kyle Butt0846e562016-10-11 20:36:43 +00001562 BlockFilterSet *BlockFilter) {
Kyle Butte9425c4f2017-02-04 02:26:32 +00001563 assert(HeadBB && "BB must not be null.\n");
1564 assert(BlockToChain[HeadBB] == &Chain && "BlockToChainMap mis-match.\n");
Xinliang David Li52530a72016-06-13 22:23:44 +00001565 MachineFunction::iterator PrevUnplacedBlockIt = F->begin();
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001566
Kyle Butte9425c4f2017-02-04 02:26:32 +00001567 const MachineBasicBlock *LoopHeaderBB = HeadBB;
Xinliang David Li93926ac2016-07-01 05:46:48 +00001568 markChainSuccessors(Chain, LoopHeaderBB, BlockFilter);
Kyle Butte9425c4f2017-02-04 02:26:32 +00001569 MachineBasicBlock *BB = *std::prev(Chain.end());
Chandler Carruth8d150782011-11-13 11:20:44 +00001570 for (;;) {
Kyle Butt82c22902016-06-28 22:50:54 +00001571 assert(BB && "null block found at end of chain in loop.");
1572 assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match in loop.");
1573 assert(*std::prev(Chain.end()) == BB && "BB Not found at end of chain.");
1574
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001575
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001576 // Look for the best viable successor if there is one to place immediately
1577 // after this block.
Kyle Buttb15c0662017-01-31 23:48:32 +00001578 auto Result = selectBestSuccessor(BB, Chain, BlockFilter);
1579 MachineBasicBlock* BestSucc = Result.BB;
1580 bool ShouldTailDup = Result.ShouldTailDup;
1581 if (TailDupPlacement)
1582 ShouldTailDup |= (BestSucc && shouldTailDuplicate(BestSucc));
Chandler Carruth8d150782011-11-13 11:20:44 +00001583
1584 // If an immediate successor isn't available, look for the best viable
1585 // block among those we've identified as not violating the loop's CFG at
1586 // this point. This won't be a fallthrough, but it will increase locality.
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001587 if (!BestSucc)
Amaury Sechet9ee4ddd2016-04-07 06:34:47 +00001588 BestSucc = selectBestCandidateBlock(Chain, BlockWorkList);
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001589 if (!BestSucc)
1590 BestSucc = selectBestCandidateBlock(Chain, EHPadWorkList);
Chandler Carruth8d150782011-11-13 11:20:44 +00001591
Chandler Carruth8d150782011-11-13 11:20:44 +00001592 if (!BestSucc) {
Xinliang David Li52530a72016-06-13 22:23:44 +00001593 BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockIt, BlockFilter);
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001594 if (!BestSucc)
1595 break;
1596
1597 DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
1598 "layout successor until the CFG reduces\n");
Chandler Carruth8d150782011-11-13 11:20:44 +00001599 }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001600
Kyle Butt0846e562016-10-11 20:36:43 +00001601 // Placement may have changed tail duplication opportunities.
1602 // Check for that now.
Kyle Buttb15c0662017-01-31 23:48:32 +00001603 if (TailDupPlacement && BestSucc && ShouldTailDup) {
Kyle Butt0846e562016-10-11 20:36:43 +00001604 // If the chosen successor was duplicated into all its predecessors,
1605 // don't bother laying it out, just go round the loop again with BB as
1606 // the chain end.
1607 if (repeatedlyTailDuplicateBlock(BestSucc, BB, LoopHeaderBB, Chain,
1608 BlockFilter, PrevUnplacedBlockIt))
1609 continue;
1610 }
1611
Chandler Carruth8d150782011-11-13 11:20:44 +00001612 // Place this block, updating the datastructures to reflect its placement.
Jakub Staszak90616162011-12-21 23:02:08 +00001613 BlockChain &SuccChain = *BlockToChain[BestSucc];
Philip Reamesae27b232016-03-03 00:58:43 +00001614 // Zero out UnscheduledPredecessors for the successor we're about to merge in case
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001615 // we selected a successor that didn't fit naturally into the CFG.
Philip Reamesae27b232016-03-03 00:58:43 +00001616 SuccChain.UnscheduledPredecessors = 0;
Philip Reamesb9688f42016-03-02 21:45:13 +00001617 DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to "
1618 << getBlockName(BestSucc) << "\n");
Xinliang David Li93926ac2016-07-01 05:46:48 +00001619 markChainSuccessors(SuccChain, LoopHeaderBB, BlockFilter);
Chandler Carruth8d150782011-11-13 11:20:44 +00001620 Chain.merge(BestSucc, &SuccChain);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001621 BB = *std::prev(Chain.end());
Jakub Staszak190c7122011-12-07 19:46:10 +00001622 }
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001623
1624 DEBUG(dbgs() << "Finished forming chain for header block "
Philip Reamesb9688f42016-03-02 21:45:13 +00001625 << getBlockName(*Chain.begin()) << "\n");
Chandler Carruth10281422011-10-21 06:46:38 +00001626}
1627
Chandler Carruth03adbd42011-11-27 13:34:33 +00001628/// \brief Find the best loop top block for layout.
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001629///
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001630/// Look for a block which is strictly better than the loop header for laying
1631/// out at the top of the loop. This looks for one and only one pattern:
1632/// a latch block with no conditional exit. This block will cause a conditional
1633/// jump around it or will be the bottom of the loop if we lay it out in place,
1634/// but if it it doesn't end up at the bottom of the loop for any reason,
1635/// rotation alone won't fix it. Because such a block will always result in an
1636/// unconditional jump (for the backedge) rotating it in front of the loop
1637/// header is always profitable.
1638MachineBasicBlock *
Kyle Butte9425c4f2017-02-04 02:26:32 +00001639MachineBlockPlacement::findBestLoopTop(const MachineLoop &L,
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001640 const BlockFilterSet &LoopBlockSet) {
Sjoerd Meijer15c81b02016-08-16 19:50:33 +00001641 // Placing the latch block before the header may introduce an extra branch
1642 // that skips this block the first time the loop is executed, which we want
1643 // to avoid when optimising for size.
1644 // FIXME: in theory there is a case that does not introduce a new branch,
1645 // i.e. when the layout predecessor does not fallthrough to the loop header.
1646 // In practice this never happens though: there always seems to be a preheader
1647 // that can fallthrough and that is also placed before the header.
1648 if (F->getFunction()->optForSize())
1649 return L.getHeader();
1650
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001651 // Check that the header hasn't been fused with a preheader block due to
1652 // crazy branches. If it has, we need to start with the header at the top to
1653 // prevent pulling the preheader into the loop body.
1654 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
1655 if (!LoopBlockSet.count(*HeaderChain.begin()))
1656 return L.getHeader();
1657
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001658 DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(L.getHeader())
1659 << "\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001660
1661 BlockFrequency BestPredFreq;
Craig Topperc0196b12014-04-14 00:51:57 +00001662 MachineBasicBlock *BestPred = nullptr;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001663 for (MachineBasicBlock *Pred : L.getHeader()->predecessors()) {
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001664 if (!LoopBlockSet.count(Pred))
1665 continue;
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001666 DEBUG(dbgs() << " header pred: " << getBlockName(Pred) << ", has "
Michael Gottesmanb78dec82013-12-14 00:25:45 +00001667 << Pred->succ_size() << " successors, ";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001668 MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001669 if (Pred->succ_size() > 1)
1670 continue;
1671
1672 BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
1673 if (!BestPred || PredFreq > BestPredFreq ||
1674 (!(PredFreq < BestPredFreq) &&
1675 Pred->isLayoutSuccessor(L.getHeader()))) {
1676 BestPred = Pred;
1677 BestPredFreq = PredFreq;
1678 }
1679 }
1680
1681 // If no direct predecessor is fine, just use the loop header.
Philip Reamesb9688f42016-03-02 21:45:13 +00001682 if (!BestPred) {
1683 DEBUG(dbgs() << " final top unchanged\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001684 return L.getHeader();
Philip Reamesb9688f42016-03-02 21:45:13 +00001685 }
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001686
1687 // Walk backwards through any straight line of predecessors.
1688 while (BestPred->pred_size() == 1 &&
1689 (*BestPred->pred_begin())->succ_size() == 1 &&
1690 *BestPred->pred_begin() != L.getHeader())
1691 BestPred = *BestPred->pred_begin();
1692
1693 DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n");
1694 return BestPred;
1695}
1696
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001697/// \brief Find the best loop exiting block for layout.
1698///
Chandler Carruth03adbd42011-11-27 13:34:33 +00001699/// This routine implements the logic to analyze the loop looking for the best
1700/// block to layout at the top of the loop. Typically this is done to maximize
1701/// fallthrough opportunities.
1702MachineBasicBlock *
Kyle Butte9425c4f2017-02-04 02:26:32 +00001703MachineBlockPlacement::findBestLoopExit(const MachineLoop &L,
Chandler Carruthccc7e422012-04-16 01:12:56 +00001704 const BlockFilterSet &LoopBlockSet) {
Chandler Carruth68062612012-04-10 13:35:57 +00001705 // We don't want to layout the loop linearly in all cases. If the loop header
1706 // is just a normal basic block in the loop, we want to look for what block
1707 // within the loop is the best one to layout at the top. However, if the loop
1708 // header has be pre-merged into a chain due to predecessors not having
1709 // analyzable branches, *and* the predecessor it is merged with is *not* part
1710 // of the loop, rotating the header into the middle of the loop will create
1711 // a non-contiguous range of blocks which is Very Bad. So start with the
1712 // header and only rotate if safe.
1713 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
1714 if (!LoopBlockSet.count(*HeaderChain.begin()))
Craig Topperc0196b12014-04-14 00:51:57 +00001715 return nullptr;
Chandler Carruth68062612012-04-10 13:35:57 +00001716
Chandler Carruth03adbd42011-11-27 13:34:33 +00001717 BlockFrequency BestExitEdgeFreq;
Chandler Carruthccc7e422012-04-16 01:12:56 +00001718 unsigned BestExitLoopDepth = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00001719 MachineBasicBlock *ExitingBB = nullptr;
Chandler Carruth4f567202011-11-27 20:18:00 +00001720 // If there are exits to outer loops, loop rotation can severely limit
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001721 // fallthrough opportunities unless it selects such an exit. Keep a set of
Chandler Carruth4f567202011-11-27 20:18:00 +00001722 // blocks where rotating to exit with that block will reach an outer loop.
1723 SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
1724
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001725 DEBUG(dbgs() << "Finding best loop exit for: " << getBlockName(L.getHeader())
1726 << "\n");
Chandler Carruth7a715da2015-03-05 03:19:05 +00001727 for (MachineBasicBlock *MBB : L.getBlocks()) {
1728 BlockChain &Chain = *BlockToChain[MBB];
Chandler Carruth03adbd42011-11-27 13:34:33 +00001729 // Ensure that this block is at the end of a chain; otherwise it could be
Chandler Carruth9a512a42015-04-15 13:19:54 +00001730 // mid-way through an inner loop or a successor of an unanalyzable branch.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001731 if (MBB != *std::prev(Chain.end()))
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001732 continue;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001733
Chandler Carruth03adbd42011-11-27 13:34:33 +00001734 // Now walk the successors. We need to establish whether this has a viable
1735 // exiting successor and whether it has a viable non-exiting successor.
1736 // We store the old exiting state and restore it if a viable looping
1737 // successor isn't found.
1738 MachineBasicBlock *OldExitingBB = ExitingBB;
1739 BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
Chandler Carruthccc7e422012-04-16 01:12:56 +00001740 bool HasLoopingSucc = false;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001741 for (MachineBasicBlock *Succ : MBB->successors()) {
Reid Kleckner0e288232015-08-27 23:27:47 +00001742 if (Succ->isEHPad())
Chandler Carruth03adbd42011-11-27 13:34:33 +00001743 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001744 if (Succ == MBB)
Chandler Carruth03adbd42011-11-27 13:34:33 +00001745 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001746 BlockChain &SuccChain = *BlockToChain[Succ];
Chandler Carruth03adbd42011-11-27 13:34:33 +00001747 // Don't split chains, either this chain or the successor's chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +00001748 if (&Chain == &SuccChain) {
Chandler Carruth7a715da2015-03-05 03:19:05 +00001749 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
1750 << getBlockName(Succ) << " (chain conflict)\n");
Chandler Carruth03adbd42011-11-27 13:34:33 +00001751 continue;
1752 }
1753
Cong Houd97c1002015-12-01 05:29:22 +00001754 auto SuccProb = MBPI->getEdgeProbability(MBB, Succ);
Chandler Carruth7a715da2015-03-05 03:19:05 +00001755 if (LoopBlockSet.count(Succ)) {
1756 DEBUG(dbgs() << " looping: " << getBlockName(MBB) << " -> "
Cong Houd97c1002015-12-01 05:29:22 +00001757 << getBlockName(Succ) << " (" << SuccProb << ")\n");
Chandler Carruthccc7e422012-04-16 01:12:56 +00001758 HasLoopingSucc = true;
Chandler Carruth03adbd42011-11-27 13:34:33 +00001759 continue;
1760 }
1761
Chandler Carruthccc7e422012-04-16 01:12:56 +00001762 unsigned SuccLoopDepth = 0;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001763 if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
Chandler Carruthccc7e422012-04-16 01:12:56 +00001764 SuccLoopDepth = ExitLoop->getLoopDepth();
1765 if (ExitLoop->contains(&L))
Chandler Carruth7a715da2015-03-05 03:19:05 +00001766 BlocksExitingToOuterLoop.insert(MBB);
Chandler Carruthccc7e422012-04-16 01:12:56 +00001767 }
1768
Chandler Carruth7a715da2015-03-05 03:19:05 +00001769 BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
1770 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
1771 << getBlockName(Succ) << " [L:" << SuccLoopDepth << "] (";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001772 MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
Benjamin Kramerc8160d62013-11-20 19:08:44 +00001773 // Note that we bias this toward an existing layout successor to retain
1774 // incoming order in the absence of better information. The exit must have
1775 // a frequency higher than the current exit before we consider breaking
1776 // the layout.
1777 BranchProbability Bias(100 - ExitBlockBias, 100);
Chandler Carruth26d30172015-04-15 13:39:42 +00001778 if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
Chandler Carruthccc7e422012-04-16 01:12:56 +00001779 ExitEdgeFreq > BestExitEdgeFreq ||
Chandler Carruth7a715da2015-03-05 03:19:05 +00001780 (MBB->isLayoutSuccessor(Succ) &&
Benjamin Kramerc8160d62013-11-20 19:08:44 +00001781 !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
Chandler Carruth03adbd42011-11-27 13:34:33 +00001782 BestExitEdgeFreq = ExitEdgeFreq;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001783 ExitingBB = MBB;
Chandler Carrutha0545802011-11-27 09:22:53 +00001784 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001785 }
Chandler Carruth03adbd42011-11-27 13:34:33 +00001786
Chandler Carruthccc7e422012-04-16 01:12:56 +00001787 if (!HasLoopingSucc) {
Chandler Carruthcfb2b9d2015-04-15 13:26:41 +00001788 // Restore the old exiting state, no viable looping successor was found.
Chandler Carruth03adbd42011-11-27 13:34:33 +00001789 ExitingBB = OldExitingBB;
1790 BestExitEdgeFreq = OldBestExitEdgeFreq;
Chandler Carruth03adbd42011-11-27 13:34:33 +00001791 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001792 }
Chandler Carruthccc7e422012-04-16 01:12:56 +00001793 // Without a candidate exiting block or with only a single block in the
Chandler Carruth03adbd42011-11-27 13:34:33 +00001794 // loop, just use the loop header to layout the loop.
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001795 if (!ExitingBB) {
1796 DEBUG(dbgs() << " No other candidate exit blocks, using loop header\n");
Craig Topperc0196b12014-04-14 00:51:57 +00001797 return nullptr;
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001798 }
1799 if (L.getNumBlocks() == 1) {
1800 DEBUG(dbgs() << " Loop has 1 block, using loop header as exit\n");
1801 return nullptr;
1802 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001803
Chandler Carruth4f567202011-11-27 20:18:00 +00001804 // Also, if we have exit blocks which lead to outer loops but didn't select
1805 // one of them as the exiting block we are rotating toward, disable loop
1806 // rotation altogether.
1807 if (!BlocksExitingToOuterLoop.empty() &&
1808 !BlocksExitingToOuterLoop.count(ExitingBB))
Craig Topperc0196b12014-04-14 00:51:57 +00001809 return nullptr;
Chandler Carruth4f567202011-11-27 20:18:00 +00001810
Chandler Carruth03adbd42011-11-27 13:34:33 +00001811 DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB) << "\n");
Chandler Carruthccc7e422012-04-16 01:12:56 +00001812 return ExitingBB;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001813}
1814
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001815/// \brief Attempt to rotate an exiting block to the bottom of the loop.
1816///
1817/// Once we have built a chain, try to rotate it to line up the hot exit block
1818/// with fallthrough out of the loop if doing so doesn't introduce unnecessary
1819/// branches. For example, if the loop has fallthrough into its header and out
1820/// of its bottom already, don't rotate it.
1821void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
Kyle Butte9425c4f2017-02-04 02:26:32 +00001822 const MachineBasicBlock *ExitingBB,
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001823 const BlockFilterSet &LoopBlockSet) {
1824 if (!ExitingBB)
1825 return;
1826
1827 MachineBasicBlock *Top = *LoopChain.begin();
1828 bool ViableTopFallthrough = false;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001829 for (MachineBasicBlock *Pred : Top->predecessors()) {
1830 BlockChain *PredChain = BlockToChain[Pred];
1831 if (!LoopBlockSet.count(Pred) &&
1832 (!PredChain || Pred == *std::prev(PredChain->end()))) {
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001833 ViableTopFallthrough = true;
1834 break;
1835 }
1836 }
1837
1838 // If the header has viable fallthrough, check whether the current loop
1839 // bottom is a viable exiting block. If so, bail out as rotating will
1840 // introduce an unnecessary branch.
1841 if (ViableTopFallthrough) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001842 MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
Chandler Carruth7a715da2015-03-05 03:19:05 +00001843 for (MachineBasicBlock *Succ : Bottom->successors()) {
1844 BlockChain *SuccChain = BlockToChain[Succ];
1845 if (!LoopBlockSet.count(Succ) &&
1846 (!SuccChain || Succ == *SuccChain->begin()))
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001847 return;
1848 }
1849 }
1850
David Majnemer0d955d02016-08-11 22:21:41 +00001851 BlockChain::iterator ExitIt = find(LoopChain, ExitingBB);
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001852 if (ExitIt == LoopChain.end())
1853 return;
1854
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001855 std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001856}
1857
Cong Hou7745dbc2015-10-19 23:16:40 +00001858/// \brief Attempt to rotate a loop based on profile data to reduce branch cost.
1859///
1860/// With profile data, we can determine the cost in terms of missed fall through
1861/// opportunities when rotating a loop chain and select the best rotation.
1862/// Basically, there are three kinds of cost to consider for each rotation:
1863/// 1. The possibly missed fall through edge (if it exists) from BB out of
1864/// the loop to the loop header.
1865/// 2. The possibly missed fall through edges (if they exist) from the loop
1866/// exits to BB out of the loop.
1867/// 3. The missed fall through edge (if it exists) from the last BB to the
1868/// first BB in the loop chain.
1869/// Therefore, the cost for a given rotation is the sum of costs listed above.
1870/// We select the best rotation with the smallest cost.
1871void MachineBlockPlacement::rotateLoopWithProfile(
Kyle Butte9425c4f2017-02-04 02:26:32 +00001872 BlockChain &LoopChain, const MachineLoop &L,
1873 const BlockFilterSet &LoopBlockSet) {
Cong Hou7745dbc2015-10-19 23:16:40 +00001874 auto HeaderBB = L.getHeader();
David Majnemer0d955d02016-08-11 22:21:41 +00001875 auto HeaderIter = find(LoopChain, HeaderBB);
Cong Hou7745dbc2015-10-19 23:16:40 +00001876 auto RotationPos = LoopChain.end();
1877
1878 BlockFrequency SmallestRotationCost = BlockFrequency::getMaxFrequency();
1879
1880 // A utility lambda that scales up a block frequency by dividing it by a
1881 // branch probability which is the reciprocal of the scale.
1882 auto ScaleBlockFrequency = [](BlockFrequency Freq,
1883 unsigned Scale) -> BlockFrequency {
1884 if (Scale == 0)
1885 return 0;
1886 // Use operator / between BlockFrequency and BranchProbability to implement
1887 // saturating multiplication.
1888 return Freq / BranchProbability(1, Scale);
1889 };
1890
1891 // Compute the cost of the missed fall-through edge to the loop header if the
1892 // chain head is not the loop header. As we only consider natural loops with
1893 // single header, this computation can be done only once.
1894 BlockFrequency HeaderFallThroughCost(0);
1895 for (auto *Pred : HeaderBB->predecessors()) {
1896 BlockChain *PredChain = BlockToChain[Pred];
1897 if (!LoopBlockSet.count(Pred) &&
1898 (!PredChain || Pred == *std::prev(PredChain->end()))) {
1899 auto EdgeFreq =
1900 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, HeaderBB);
1901 auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost);
1902 // If the predecessor has only an unconditional jump to the header, we
1903 // need to consider the cost of this jump.
1904 if (Pred->succ_size() == 1)
1905 FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost);
1906 HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost);
1907 }
1908 }
1909
1910 // Here we collect all exit blocks in the loop, and for each exit we find out
1911 // its hottest exit edge. For each loop rotation, we define the loop exit cost
1912 // as the sum of frequencies of exit edges we collect here, excluding the exit
1913 // edge from the tail of the loop chain.
1914 SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq;
1915 for (auto BB : LoopChain) {
Cong Houd97c1002015-12-01 05:29:22 +00001916 auto LargestExitEdgeProb = BranchProbability::getZero();
Cong Hou7745dbc2015-10-19 23:16:40 +00001917 for (auto *Succ : BB->successors()) {
1918 BlockChain *SuccChain = BlockToChain[Succ];
1919 if (!LoopBlockSet.count(Succ) &&
1920 (!SuccChain || Succ == *SuccChain->begin())) {
Cong Houd97c1002015-12-01 05:29:22 +00001921 auto SuccProb = MBPI->getEdgeProbability(BB, Succ);
1922 LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb);
Cong Hou7745dbc2015-10-19 23:16:40 +00001923 }
1924 }
Cong Houd97c1002015-12-01 05:29:22 +00001925 if (LargestExitEdgeProb > BranchProbability::getZero()) {
1926 auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb;
Cong Hou7745dbc2015-10-19 23:16:40 +00001927 ExitsWithFreq.emplace_back(BB, ExitFreq);
1928 }
1929 }
1930
1931 // In this loop we iterate every block in the loop chain and calculate the
1932 // cost assuming the block is the head of the loop chain. When the loop ends,
1933 // we should have found the best candidate as the loop chain's head.
1934 for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()),
1935 EndIter = LoopChain.end();
1936 Iter != EndIter; Iter++, TailIter++) {
1937 // TailIter is used to track the tail of the loop chain if the block we are
1938 // checking (pointed by Iter) is the head of the chain.
1939 if (TailIter == LoopChain.end())
1940 TailIter = LoopChain.begin();
1941
1942 auto TailBB = *TailIter;
1943
1944 // Calculate the cost by putting this BB to the top.
1945 BlockFrequency Cost = 0;
1946
1947 // If the current BB is the loop header, we need to take into account the
1948 // cost of the missed fall through edge from outside of the loop to the
1949 // header.
1950 if (Iter != HeaderIter)
1951 Cost += HeaderFallThroughCost;
1952
1953 // Collect the loop exit cost by summing up frequencies of all exit edges
1954 // except the one from the chain tail.
1955 for (auto &ExitWithFreq : ExitsWithFreq)
1956 if (TailBB != ExitWithFreq.first)
1957 Cost += ExitWithFreq.second;
1958
1959 // The cost of breaking the once fall-through edge from the tail to the top
1960 // of the loop chain. Here we need to consider three cases:
1961 // 1. If the tail node has only one successor, then we will get an
1962 // additional jmp instruction. So the cost here is (MisfetchCost +
1963 // JumpInstCost) * tail node frequency.
1964 // 2. If the tail node has two successors, then we may still get an
1965 // additional jmp instruction if the layout successor after the loop
1966 // chain is not its CFG successor. Note that the more frequently executed
1967 // jmp instruction will be put ahead of the other one. Assume the
1968 // frequency of those two branches are x and y, where x is the frequency
1969 // of the edge to the chain head, then the cost will be
1970 // (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency.
1971 // 3. If the tail node has more than two successors (this rarely happens),
1972 // we won't consider any additional cost.
1973 if (TailBB->isSuccessor(*Iter)) {
1974 auto TailBBFreq = MBFI->getBlockFreq(TailBB);
1975 if (TailBB->succ_size() == 1)
1976 Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(),
1977 MisfetchCost + JumpInstCost);
1978 else if (TailBB->succ_size() == 2) {
1979 auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter);
1980 auto TailToHeadFreq = TailBBFreq * TailToHeadProb;
1981 auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2)
1982 ? TailBBFreq * TailToHeadProb.getCompl()
1983 : TailToHeadFreq;
1984 Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) +
1985 ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost);
1986 }
1987 }
1988
Philip Reamesb9688f42016-03-02 21:45:13 +00001989 DEBUG(dbgs() << "The cost of loop rotation by making " << getBlockName(*Iter)
Cong Hou7745dbc2015-10-19 23:16:40 +00001990 << " to the top: " << Cost.getFrequency() << "\n");
1991
1992 if (Cost < SmallestRotationCost) {
1993 SmallestRotationCost = Cost;
1994 RotationPos = Iter;
1995 }
1996 }
1997
1998 if (RotationPos != LoopChain.end()) {
Philip Reamesb9688f42016-03-02 21:45:13 +00001999 DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos)
Cong Hou7745dbc2015-10-19 23:16:40 +00002000 << " to the top\n");
2001 std::rotate(LoopChain.begin(), RotationPos, LoopChain.end());
2002 }
2003}
2004
Cong Houb90b9e02015-11-02 21:24:00 +00002005/// \brief Collect blocks in the given loop that are to be placed.
2006///
2007/// When profile data is available, exclude cold blocks from the returned set;
2008/// otherwise, collect all blocks in the loop.
2009MachineBlockPlacement::BlockFilterSet
Kyle Butte9425c4f2017-02-04 02:26:32 +00002010MachineBlockPlacement::collectLoopBlockSet(const MachineLoop &L) {
Cong Houb90b9e02015-11-02 21:24:00 +00002011 BlockFilterSet LoopBlockSet;
2012
2013 // Filter cold blocks off from LoopBlockSet when profile data is available.
2014 // Collect the sum of frequencies of incoming edges to the loop header from
2015 // outside. If we treat the loop as a super block, this is the frequency of
2016 // the loop. Then for each block in the loop, we calculate the ratio between
2017 // its frequency and the frequency of the loop block. When it is too small,
2018 // don't add it to the loop chain. If there are outer loops, then this block
2019 // will be merged into the first outer loop chain for which this block is not
2020 // cold anymore. This needs precise profile data and we only do this when
2021 // profile data is available.
Xinliang David Li52530a72016-06-13 22:23:44 +00002022 if (F->getFunction()->getEntryCount()) {
Cong Houb90b9e02015-11-02 21:24:00 +00002023 BlockFrequency LoopFreq(0);
2024 for (auto LoopPred : L.getHeader()->predecessors())
2025 if (!L.contains(LoopPred))
2026 LoopFreq += MBFI->getBlockFreq(LoopPred) *
2027 MBPI->getEdgeProbability(LoopPred, L.getHeader());
2028
2029 for (MachineBasicBlock *LoopBB : L.getBlocks()) {
2030 auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency();
2031 if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio)
2032 continue;
2033 LoopBlockSet.insert(LoopBB);
2034 }
2035 } else
2036 LoopBlockSet.insert(L.block_begin(), L.block_end());
2037
2038 return LoopBlockSet;
2039}
2040
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00002041/// \brief Forms basic block chains from the natural loop structures.
Chandler Carruth10281422011-10-21 06:46:38 +00002042///
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00002043/// These chains are designed to preserve the existing *structure* of the code
2044/// as much as possible. We can then stitch the chains together in a way which
2045/// both preserves the topological structure and minimizes taken conditional
2046/// branches.
Kyle Butte9425c4f2017-02-04 02:26:32 +00002047void MachineBlockPlacement::buildLoopChains(const MachineLoop &L) {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00002048 // First recurse through any nested loops, building chains for those inner
2049 // loops.
Kyle Butte9425c4f2017-02-04 02:26:32 +00002050 for (const MachineLoop *InnerLoop : L)
Xinliang David Li52530a72016-06-13 22:23:44 +00002051 buildLoopChains(*InnerLoop);
Chandler Carruth10281422011-10-21 06:46:38 +00002052
Xinliang David Li93926ac2016-07-01 05:46:48 +00002053 assert(BlockWorkList.empty());
2054 assert(EHPadWorkList.empty());
Xinliang David Li52530a72016-06-13 22:23:44 +00002055 BlockFilterSet LoopBlockSet = collectLoopBlockSet(L);
Chandler Carruth03adbd42011-11-27 13:34:33 +00002056
Cong Hou7745dbc2015-10-19 23:16:40 +00002057 // Check if we have profile data for this function. If yes, we will rotate
2058 // this loop by modeling costs more precisely which requires the profile data
2059 // for better layout.
2060 bool RotateLoopWithProfile =
Xinliang David Lif0ab6df2016-05-12 02:04:41 +00002061 ForcePreciseRotationCost ||
Xinliang David Li52530a72016-06-13 22:23:44 +00002062 (PreciseRotationCost && F->getFunction()->getEntryCount());
Cong Hou7745dbc2015-10-19 23:16:40 +00002063
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00002064 // First check to see if there is an obviously preferable top block for the
2065 // loop. This will default to the header, but may end up as one of the
2066 // predecessors to the header if there is one which will result in strictly
2067 // fewer branches in the loop body.
Cong Hou7745dbc2015-10-19 23:16:40 +00002068 // When we use profile data to rotate the loop, this is unnecessary.
2069 MachineBasicBlock *LoopTop =
2070 RotateLoopWithProfile ? L.getHeader() : findBestLoopTop(L, LoopBlockSet);
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00002071
2072 // If we selected just the header for the loop top, look for a potentially
2073 // profitable exit block in the event that rotating the loop can eliminate
2074 // branches by placing an exit edge at the bottom.
Cong Hou7745dbc2015-10-19 23:16:40 +00002075 if (!RotateLoopWithProfile && LoopTop == L.getHeader())
Kyle Buttab9cca72016-10-27 21:37:20 +00002076 PreferredLoopExit = findBestLoopExit(L, LoopBlockSet);
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00002077
2078 BlockChain &LoopChain = *BlockToChain[LoopTop];
Chandler Carruth10281422011-10-21 06:46:38 +00002079
Chandler Carruth8d150782011-11-13 11:20:44 +00002080 // FIXME: This is a really lame way of walking the chains in the loop: we
2081 // walk the blocks, and use a set to prevent visiting a particular chain
2082 // twice.
Jakub Staszak90616162011-12-21 23:02:08 +00002083 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
Philip Reamesae27b232016-03-03 00:58:43 +00002084 assert(LoopChain.UnscheduledPredecessors == 0);
Jakub Staszak190c7122011-12-07 19:46:10 +00002085 UpdatedPreds.insert(&LoopChain);
Cong Houb90b9e02015-11-02 21:24:00 +00002086
Kyle Butte9425c4f2017-02-04 02:26:32 +00002087 for (const MachineBasicBlock *LoopBB : LoopBlockSet)
Xinliang David Li93926ac2016-07-01 05:46:48 +00002088 fillWorkLists(LoopBB, UpdatedPreds, &LoopBlockSet);
Chandler Carruth8d150782011-11-13 11:20:44 +00002089
Xinliang David Li93926ac2016-07-01 05:46:48 +00002090 buildChain(LoopTop, LoopChain, &LoopBlockSet);
Cong Hou7745dbc2015-10-19 23:16:40 +00002091
2092 if (RotateLoopWithProfile)
2093 rotateLoopWithProfile(LoopChain, L, LoopBlockSet);
2094 else
Kyle Buttab9cca72016-10-27 21:37:20 +00002095 rotateLoop(LoopChain, PreferredLoopExit, LoopBlockSet);
Chandler Carruth8d150782011-11-13 11:20:44 +00002096
2097 DEBUG({
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002098 // Crash at the end so we get all of the debugging output first.
2099 bool BadLoop = false;
Philip Reamesae27b232016-03-03 00:58:43 +00002100 if (LoopChain.UnscheduledPredecessors) {
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002101 BadLoop = true;
Chandler Carruth8d150782011-11-13 11:20:44 +00002102 dbgs() << "Loop chain contains a block without its preds placed!\n"
2103 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
2104 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002105 }
Chandler Carruth7a715da2015-03-05 03:19:05 +00002106 for (MachineBasicBlock *ChainBB : LoopChain) {
2107 dbgs() << " ... " << getBlockName(ChainBB) << "\n";
Rong Xu66827422016-11-16 20:50:06 +00002108 if (!LoopBlockSet.remove(ChainBB)) {
Chandler Carruth0a31d142011-11-14 10:55:53 +00002109 // We don't mark the loop as bad here because there are real situations
2110 // where this can occur. For example, with an unanalyzable fallthrough
Chandler Carruth99fe42f2011-11-23 10:35:36 +00002111 // from a loop block to a non-loop block or vice versa.
Chandler Carruth8d150782011-11-13 11:20:44 +00002112 dbgs() << "Loop chain contains a block not contained by the loop!\n"
2113 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
2114 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00002115 << " Bad block: " << getBlockName(ChainBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002116 }
Chandler Carruthccc7e422012-04-16 01:12:56 +00002117 }
Chandler Carruth8d150782011-11-13 11:20:44 +00002118
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002119 if (!LoopBlockSet.empty()) {
2120 BadLoop = true;
Kyle Butte9425c4f2017-02-04 02:26:32 +00002121 for (const MachineBasicBlock *LoopBB : LoopBlockSet)
Chandler Carruth8d150782011-11-13 11:20:44 +00002122 dbgs() << "Loop contains blocks never placed into a chain!\n"
2123 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
2124 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00002125 << " Bad block: " << getBlockName(LoopBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002126 }
2127 assert(!BadLoop && "Detected problems with the placement of this loop.");
Chandler Carruth8d150782011-11-13 11:20:44 +00002128 });
Xinliang David Li93926ac2016-07-01 05:46:48 +00002129
2130 BlockWorkList.clear();
2131 EHPadWorkList.clear();
Chandler Carruth10281422011-10-21 06:46:38 +00002132}
2133
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00002134/// When OutlineOpitonalBranches is on, this method collects BBs that
Xinliang David Li071d0f12016-06-12 16:54:03 +00002135/// dominates all terminator blocks of the function \p F.
Xinliang David Li52530a72016-06-13 22:23:44 +00002136void MachineBlockPlacement::collectMustExecuteBBs() {
Xinliang David Li071d0f12016-06-12 16:54:03 +00002137 if (OutlineOptionalBranches) {
2138 // Find the nearest common dominator of all of F's terminators.
2139 MachineBasicBlock *Terminator = nullptr;
Xinliang David Li52530a72016-06-13 22:23:44 +00002140 for (MachineBasicBlock &MBB : *F) {
Xinliang David Li071d0f12016-06-12 16:54:03 +00002141 if (MBB.succ_size() == 0) {
2142 if (Terminator == nullptr)
2143 Terminator = &MBB;
2144 else
2145 Terminator = MDT->findNearestCommonDominator(Terminator, &MBB);
2146 }
2147 }
2148
2149 // MBBs dominating this common dominator are unavoidable.
2150 UnavoidableBlocks.clear();
Xinliang David Li52530a72016-06-13 22:23:44 +00002151 for (MachineBasicBlock &MBB : *F) {
Xinliang David Li071d0f12016-06-12 16:54:03 +00002152 if (MDT->dominates(&MBB, Terminator)) {
2153 UnavoidableBlocks.insert(&MBB);
2154 }
2155 }
2156 }
2157}
2158
Xinliang David Li52530a72016-06-13 22:23:44 +00002159void MachineBlockPlacement::buildCFGChains() {
Chandler Carruth8d150782011-11-13 11:20:44 +00002160 // Ensure that every BB in the function has an associated chain to simplify
2161 // the assumptions of the remaining algorithm.
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00002162 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
Xinliang David Li52530a72016-06-13 22:23:44 +00002163 for (MachineFunction::iterator FI = F->begin(), FE = F->end(); FI != FE;
2164 ++FI) {
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00002165 MachineBasicBlock *BB = &*FI;
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00002166 BlockChain *Chain =
2167 new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00002168 // Also, merge any blocks which we cannot reason about and must preserve
2169 // the exact fallthrough behavior for.
2170 for (;;) {
2171 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00002172 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002173 if (!TII->analyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00002174 break;
2175
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00002176 MachineFunction::iterator NextFI = std::next(FI);
2177 MachineBasicBlock *NextBB = &*NextFI;
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00002178 // Ensure that the layout successor is a viable block, as we know that
2179 // fallthrough is a possibility.
2180 assert(NextFI != FE && "Can't fallthrough past the last block.");
2181 DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
2182 << getBlockName(BB) << " -> " << getBlockName(NextBB)
2183 << "\n");
Craig Topperc0196b12014-04-14 00:51:57 +00002184 Chain->merge(NextBB, nullptr);
Hal Finkel34f9d6a2016-12-15 05:33:19 +00002185#ifndef NDEBUG
Sanjoy Dasd7389d62016-12-15 05:08:57 +00002186 BlocksWithUnanalyzableExits.insert(&*BB);
Hal Finkel34f9d6a2016-12-15 05:33:19 +00002187#endif
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00002188 FI = NextFI;
2189 BB = NextBB;
2190 }
2191 }
Chandler Carruth8d150782011-11-13 11:20:44 +00002192
Xinliang David Li071d0f12016-06-12 16:54:03 +00002193 // Turned on with OutlineOptionalBranches option
Xinliang David Li52530a72016-06-13 22:23:44 +00002194 collectMustExecuteBBs();
Daniel Jasper471e8562015-03-04 11:05:34 +00002195
Chandler Carruth8d150782011-11-13 11:20:44 +00002196 // Build any loop-based chains.
Sam McCall2a36eee2016-11-01 22:02:14 +00002197 PreferredLoopExit = nullptr;
Chandler Carruth7a715da2015-03-05 03:19:05 +00002198 for (MachineLoop *L : *MLI)
Xinliang David Li52530a72016-06-13 22:23:44 +00002199 buildLoopChains(*L);
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00002200
Xinliang David Li93926ac2016-07-01 05:46:48 +00002201 assert(BlockWorkList.empty());
2202 assert(EHPadWorkList.empty());
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00002203
Chandler Carruth8d150782011-11-13 11:20:44 +00002204 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
Xinliang David Li52530a72016-06-13 22:23:44 +00002205 for (MachineBasicBlock &MBB : *F)
Xinliang David Li93926ac2016-07-01 05:46:48 +00002206 fillWorkLists(&MBB, UpdatedPreds);
Chandler Carruth8d150782011-11-13 11:20:44 +00002207
Xinliang David Li52530a72016-06-13 22:23:44 +00002208 BlockChain &FunctionChain = *BlockToChain[&F->front()];
Xinliang David Li93926ac2016-07-01 05:46:48 +00002209 buildChain(&F->front(), FunctionChain);
Chandler Carruth8d150782011-11-13 11:20:44 +00002210
Matt Arsenault0f5f0152013-12-10 18:55:37 +00002211#ifndef NDEBUG
Matt Arsenault79d55f52013-12-05 20:02:18 +00002212 typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType;
Matt Arsenault0f5f0152013-12-10 18:55:37 +00002213#endif
Chandler Carruth8d150782011-11-13 11:20:44 +00002214 DEBUG({
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002215 // Crash at the end so we get all of the debugging output first.
2216 bool BadFunc = false;
Chandler Carruth8d150782011-11-13 11:20:44 +00002217 FunctionBlockSetType FunctionBlockSet;
Xinliang David Li52530a72016-06-13 22:23:44 +00002218 for (MachineBasicBlock &MBB : *F)
Chandler Carruth7a715da2015-03-05 03:19:05 +00002219 FunctionBlockSet.insert(&MBB);
Chandler Carruth8d150782011-11-13 11:20:44 +00002220
Chandler Carruth7a715da2015-03-05 03:19:05 +00002221 for (MachineBasicBlock *ChainBB : FunctionChain)
2222 if (!FunctionBlockSet.erase(ChainBB)) {
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002223 BadFunc = true;
Chandler Carruth8d150782011-11-13 11:20:44 +00002224 dbgs() << "Function chain contains a block not in the function!\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00002225 << " Bad block: " << getBlockName(ChainBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002226 }
Chandler Carruth8d150782011-11-13 11:20:44 +00002227
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002228 if (!FunctionBlockSet.empty()) {
2229 BadFunc = true;
Chandler Carruth7a715da2015-03-05 03:19:05 +00002230 for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
Chandler Carruth8d150782011-11-13 11:20:44 +00002231 dbgs() << "Function contains blocks never placed into a chain!\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00002232 << " Bad block: " << getBlockName(RemainingBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002233 }
2234 assert(!BadFunc && "Detected problems with the block placement.");
Chandler Carruth8d150782011-11-13 11:20:44 +00002235 });
2236
2237 // Splice the blocks into place.
Xinliang David Li52530a72016-06-13 22:23:44 +00002238 MachineFunction::iterator InsertPos = F->begin();
Xinliang David Li449cdfd2016-06-24 22:54:21 +00002239 DEBUG(dbgs() << "[MBP] Function: "<< F->getName() << "\n");
Chandler Carruth7a715da2015-03-05 03:19:05 +00002240 for (MachineBasicBlock *ChainBB : FunctionChain) {
2241 DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
2242 : " ... ")
2243 << getBlockName(ChainBB) << "\n");
2244 if (InsertPos != MachineFunction::iterator(ChainBB))
Xinliang David Li52530a72016-06-13 22:23:44 +00002245 F->splice(InsertPos, ChainBB);
Chandler Carruth8d150782011-11-13 11:20:44 +00002246 else
2247 ++InsertPos;
2248
2249 // Update the terminator of the previous block.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002250 if (ChainBB == *FunctionChain.begin())
Chandler Carruth8d150782011-11-13 11:20:44 +00002251 continue;
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00002252 MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB));
Chandler Carruth8d150782011-11-13 11:20:44 +00002253
Chandler Carruth10281422011-10-21 06:46:38 +00002254 // FIXME: It would be awesome of updateTerminator would just return rather
2255 // than assert when the branch cannot be analyzed in order to remove this
2256 // boiler plate.
2257 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00002258 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Shuxin Yang8b8fd212013-06-04 01:00:57 +00002259
Sanjoy Dasd7389d62016-12-15 05:08:57 +00002260#ifndef NDEBUG
2261 if (!BlocksWithUnanalyzableExits.count(PrevBB)) {
2262 // Given the exact block placement we chose, we may actually not _need_ to
2263 // be able to edit PrevBB's terminator sequence, but not being _able_ to
2264 // do that at this point is a bug.
2265 assert((!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond) ||
2266 !PrevBB->canFallThrough()) &&
2267 "Unexpected block with un-analyzable fallthrough!");
2268 Cond.clear();
2269 TBB = FBB = nullptr;
2270 }
2271#endif
2272
Haicheng Wu90a55652016-05-24 22:16:14 +00002273 // The "PrevBB" is not yet updated to reflect current code layout, so,
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00002274 // o. it may fall-through to a block without explicit "goto" instruction
Haicheng Wu90a55652016-05-24 22:16:14 +00002275 // before layout, and no longer fall-through it after layout; or
2276 // o. just opposite.
2277 //
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002278 // analyzeBranch() may return erroneous value for FBB when these two
Haicheng Wu90a55652016-05-24 22:16:14 +00002279 // situations take place. For the first scenario FBB is mistakenly set NULL;
2280 // for the 2nd scenario, the FBB, which is expected to be NULL, is
2281 // mistakenly pointing to "*BI".
2282 // Thus, if the future change needs to use FBB before the layout is set, it
2283 // has to correct FBB first by using the code similar to the following:
2284 //
2285 // if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
2286 // PrevBB->updateTerminator();
2287 // Cond.clear();
2288 // TBB = FBB = nullptr;
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002289 // if (TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) {
Haicheng Wu90a55652016-05-24 22:16:14 +00002290 // // FIXME: This should never take place.
2291 // TBB = FBB = nullptr;
2292 // }
2293 // }
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002294 if (!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond))
Haicheng Wu90a55652016-05-24 22:16:14 +00002295 PrevBB->updateTerminator();
Chandler Carruth10281422011-10-21 06:46:38 +00002296 }
Chandler Carruth8d150782011-11-13 11:20:44 +00002297
2298 // Fixup the last block.
2299 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00002300 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002301 if (!TII->analyzeBranch(F->back(), TBB, FBB, Cond))
Xinliang David Li52530a72016-06-13 22:23:44 +00002302 F->back().updateTerminator();
Xinliang David Li93926ac2016-07-01 05:46:48 +00002303
2304 BlockWorkList.clear();
2305 EHPadWorkList.clear();
Haicheng Wu90a55652016-05-24 22:16:14 +00002306}
2307
Xinliang David Li52530a72016-06-13 22:23:44 +00002308void MachineBlockPlacement::optimizeBranches() {
2309 BlockChain &FunctionChain = *BlockToChain[&F->front()];
Haicheng Wu90a55652016-05-24 22:16:14 +00002310 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
Quentin Colombet776e6de2016-05-02 22:58:59 +00002311
2312 // Now that all the basic blocks in the chain have the proper layout,
2313 // make a final call to AnalyzeBranch with AllowModify set.
2314 // Indeed, the target may be able to optimize the branches in a way we
2315 // cannot because all branches may not be analyzable.
2316 // E.g., the target may be able to remove an unconditional branch to
2317 // a fallthrough when it occurs after predicated terminators.
2318 for (MachineBasicBlock *ChainBB : FunctionChain) {
2319 Cond.clear();
Haicheng Wu90a55652016-05-24 22:16:14 +00002320 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002321 if (!TII->analyzeBranch(*ChainBB, TBB, FBB, Cond, /*AllowModify*/ true)) {
Haicheng Wu90a55652016-05-24 22:16:14 +00002322 // If PrevBB has a two-way branch, try to re-order the branches
2323 // such that we branch to the successor with higher probability first.
2324 if (TBB && !Cond.empty() && FBB &&
2325 MBPI->getEdgeProbability(ChainBB, FBB) >
2326 MBPI->getEdgeProbability(ChainBB, TBB) &&
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00002327 !TII->reverseBranchCondition(Cond)) {
Haicheng Wu90a55652016-05-24 22:16:14 +00002328 DEBUG(dbgs() << "Reverse order of the two branches: "
2329 << getBlockName(ChainBB) << "\n");
2330 DEBUG(dbgs() << " Edge probability: "
2331 << MBPI->getEdgeProbability(ChainBB, FBB) << " vs "
2332 << MBPI->getEdgeProbability(ChainBB, TBB) << "\n");
2333 DebugLoc dl; // FIXME: this is nowhere
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00002334 TII->removeBranch(*ChainBB);
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00002335 TII->insertBranch(*ChainBB, FBB, TBB, Cond, dl);
Haicheng Wu90a55652016-05-24 22:16:14 +00002336 ChainBB->updateTerminator();
2337 }
2338 }
Quentin Colombet776e6de2016-05-02 22:58:59 +00002339 }
Haicheng Wue749ce52016-04-29 17:06:44 +00002340}
Chandler Carruth10281422011-10-21 06:46:38 +00002341
Xinliang David Li52530a72016-06-13 22:23:44 +00002342void MachineBlockPlacement::alignBlocks() {
Chandler Carruthccc7e422012-04-16 01:12:56 +00002343 // Walk through the backedges of the function now that we have fully laid out
2344 // the basic blocks and align the destination of each backedge. We don't rely
Chandler Carruth881d0a72012-08-07 09:45:24 +00002345 // exclusively on the loop info here so that we can align backedges in
2346 // unnatural CFGs and backedges that were introduced purely because of the
2347 // loop rotations done during this layout pass.
Xinliang David Li52530a72016-06-13 22:23:44 +00002348 if (F->getFunction()->optForSize())
Chandler Carruth8b9737c2011-10-21 08:57:37 +00002349 return;
Xinliang David Li52530a72016-06-13 22:23:44 +00002350 BlockChain &FunctionChain = *BlockToChain[&F->front()];
Chandler Carruth881d0a72012-08-07 09:45:24 +00002351 if (FunctionChain.begin() == FunctionChain.end())
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00002352 return; // Empty chain.
Chandler Carruth8b9737c2011-10-21 08:57:37 +00002353
Chandler Carruth881d0a72012-08-07 09:45:24 +00002354 const BranchProbability ColdProb(1, 5); // 20%
Xinliang David Li52530a72016-06-13 22:23:44 +00002355 BlockFrequency EntryFreq = MBFI->getBlockFreq(&F->front());
Chandler Carruth881d0a72012-08-07 09:45:24 +00002356 BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
Chandler Carruth7a715da2015-03-05 03:19:05 +00002357 for (MachineBasicBlock *ChainBB : FunctionChain) {
2358 if (ChainBB == *FunctionChain.begin())
2359 continue;
2360
Chandler Carruth881d0a72012-08-07 09:45:24 +00002361 // Don't align non-looping basic blocks. These are unlikely to execute
2362 // enough times to matter in practice. Note that we'll still handle
2363 // unnatural CFGs inside of a natural outer loop (the common case) and
2364 // rotated loops.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002365 MachineLoop *L = MLI->getLoopFor(ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00002366 if (!L)
2367 continue;
2368
Hal Finkel57725662015-01-03 17:58:24 +00002369 unsigned Align = TLI->getPrefLoopAlignment(L);
2370 if (!Align)
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00002371 continue; // Don't care about loop alignment.
Hal Finkel57725662015-01-03 17:58:24 +00002372
Chandler Carruth881d0a72012-08-07 09:45:24 +00002373 // If the block is cold relative to the function entry don't waste space
2374 // aligning it.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002375 BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00002376 if (Freq < WeightedEntryFreq)
2377 continue;
2378
2379 // If the block is cold relative to its loop header, don't align it
2380 // regardless of what edges into the block exist.
2381 MachineBasicBlock *LoopHeader = L->getHeader();
2382 BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
2383 if (Freq < (LoopHeaderFreq * ColdProb))
2384 continue;
2385
2386 // Check for the existence of a non-layout predecessor which would benefit
2387 // from aligning this block.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002388 MachineBasicBlock *LayoutPred =
2389 &*std::prev(MachineFunction::iterator(ChainBB));
Chandler Carruth881d0a72012-08-07 09:45:24 +00002390
2391 // Force alignment if all the predecessors are jumps. We already checked
2392 // that the block isn't cold above.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002393 if (!LayoutPred->isSuccessor(ChainBB)) {
2394 ChainBB->setAlignment(Align);
Chandler Carruth881d0a72012-08-07 09:45:24 +00002395 continue;
2396 }
2397
2398 // Align this block if the layout predecessor's edge into this block is
Nadav Rotem6036f582013-03-29 16:34:23 +00002399 // cold relative to the block. When this is true, other predecessors make up
Chandler Carruth881d0a72012-08-07 09:45:24 +00002400 // all of the hot entries into the block and thus alignment is likely to be
2401 // important.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002402 BranchProbability LayoutProb =
2403 MBPI->getEdgeProbability(LayoutPred, ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00002404 BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
2405 if (LayoutEdgeFreq <= (Freq * ColdProb))
Chandler Carruth7a715da2015-03-05 03:19:05 +00002406 ChainBB->setAlignment(Align);
Chandler Carruthccc7e422012-04-16 01:12:56 +00002407 }
Chandler Carruth8b9737c2011-10-21 08:57:37 +00002408}
2409
Kyle Butt0846e562016-10-11 20:36:43 +00002410/// Tail duplicate \p BB into (some) predecessors if profitable, repeating if
2411/// it was duplicated into its chain predecessor and removed.
2412/// \p BB - Basic block that may be duplicated.
2413///
2414/// \p LPred - Chosen layout predecessor of \p BB.
2415/// Updated to be the chain end if LPred is removed.
2416/// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
2417/// \p BlockFilter - Set of blocks that belong to the loop being laid out.
2418/// Used to identify which blocks to update predecessor
2419/// counts.
2420/// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
2421/// chosen in the given order due to unnatural CFG
2422/// only needed if \p BB is removed and
2423/// \p PrevUnplacedBlockIt pointed to \p BB.
2424/// @return true if \p BB was removed.
2425bool MachineBlockPlacement::repeatedlyTailDuplicateBlock(
2426 MachineBasicBlock *BB, MachineBasicBlock *&LPred,
Kyle Butte9425c4f2017-02-04 02:26:32 +00002427 const MachineBasicBlock *LoopHeaderBB,
Kyle Butt0846e562016-10-11 20:36:43 +00002428 BlockChain &Chain, BlockFilterSet *BlockFilter,
2429 MachineFunction::iterator &PrevUnplacedBlockIt) {
2430 bool Removed, DuplicatedToLPred;
2431 bool DuplicatedToOriginalLPred;
2432 Removed = maybeTailDuplicateBlock(BB, LPred, Chain, BlockFilter,
2433 PrevUnplacedBlockIt,
2434 DuplicatedToLPred);
2435 if (!Removed)
2436 return false;
2437 DuplicatedToOriginalLPred = DuplicatedToLPred;
2438 // Iteratively try to duplicate again. It can happen that a block that is
2439 // duplicated into is still small enough to be duplicated again.
2440 // No need to call markBlockSuccessors in this case, as the blocks being
2441 // duplicated from here on are already scheduled.
2442 // Note that DuplicatedToLPred always implies Removed.
2443 while (DuplicatedToLPred) {
2444 assert (Removed && "Block must have been removed to be duplicated into its "
2445 "layout predecessor.");
2446 MachineBasicBlock *DupBB, *DupPred;
2447 // The removal callback causes Chain.end() to be updated when a block is
2448 // removed. On the first pass through the loop, the chain end should be the
2449 // same as it was on function entry. On subsequent passes, because we are
2450 // duplicating the block at the end of the chain, if it is removed the
2451 // chain will have shrunk by one block.
2452 BlockChain::iterator ChainEnd = Chain.end();
2453 DupBB = *(--ChainEnd);
2454 // Now try to duplicate again.
2455 if (ChainEnd == Chain.begin())
2456 break;
2457 DupPred = *std::prev(ChainEnd);
2458 Removed = maybeTailDuplicateBlock(DupBB, DupPred, Chain, BlockFilter,
2459 PrevUnplacedBlockIt,
2460 DuplicatedToLPred);
2461 }
2462 // If BB was duplicated into LPred, it is now scheduled. But because it was
2463 // removed, markChainSuccessors won't be called for its chain. Instead we
2464 // call markBlockSuccessors for LPred to achieve the same effect. This must go
2465 // at the end because repeating the tail duplication can increase the number
2466 // of unscheduled predecessors.
2467 LPred = *std::prev(Chain.end());
2468 if (DuplicatedToOriginalLPred)
2469 markBlockSuccessors(Chain, LPred, LoopHeaderBB, BlockFilter);
2470 return true;
2471}
2472
2473/// Tail duplicate \p BB into (some) predecessors if profitable.
2474/// \p BB - Basic block that may be duplicated
2475/// \p LPred - Chosen layout predecessor of \p BB
2476/// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
2477/// \p BlockFilter - Set of blocks that belong to the loop being laid out.
2478/// Used to identify which blocks to update predecessor
2479/// counts.
2480/// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
2481/// chosen in the given order due to unnatural CFG
2482/// only needed if \p BB is removed and
2483/// \p PrevUnplacedBlockIt pointed to \p BB.
2484/// \p DuplicatedToLPred - True if the block was duplicated into LPred. Will
2485/// only be true if the block was removed.
2486/// \return - True if the block was duplicated into all preds and removed.
2487bool MachineBlockPlacement::maybeTailDuplicateBlock(
2488 MachineBasicBlock *BB, MachineBasicBlock *LPred,
Kyle Butte9425c4f2017-02-04 02:26:32 +00002489 BlockChain &Chain, BlockFilterSet *BlockFilter,
Kyle Butt0846e562016-10-11 20:36:43 +00002490 MachineFunction::iterator &PrevUnplacedBlockIt,
2491 bool &DuplicatedToLPred) {
Kyle Butt0846e562016-10-11 20:36:43 +00002492 DuplicatedToLPred = false;
Kyle Buttc7d67eef2017-02-04 02:26:34 +00002493 if (!shouldTailDuplicate(BB))
2494 return false;
2495
Kyle Butt0846e562016-10-11 20:36:43 +00002496 DEBUG(dbgs() << "Redoing tail duplication for Succ#"
2497 << BB->getNumber() << "\n");
Kyle Buttb15c0662017-01-31 23:48:32 +00002498
Kyle Butt0846e562016-10-11 20:36:43 +00002499 // This has to be a callback because none of it can be done after
2500 // BB is deleted.
2501 bool Removed = false;
2502 auto RemovalCallback =
2503 [&](MachineBasicBlock *RemBB) {
2504 // Signal to outer function
2505 Removed = true;
2506
2507 // Conservative default.
2508 bool InWorkList = true;
2509 // Remove from the Chain and Chain Map
2510 if (BlockToChain.count(RemBB)) {
2511 BlockChain *Chain = BlockToChain[RemBB];
2512 InWorkList = Chain->UnscheduledPredecessors == 0;
2513 Chain->remove(RemBB);
2514 BlockToChain.erase(RemBB);
2515 }
2516
2517 // Handle the unplaced block iterator
2518 if (&(*PrevUnplacedBlockIt) == RemBB) {
2519 PrevUnplacedBlockIt++;
2520 }
2521
2522 // Handle the Work Lists
2523 if (InWorkList) {
2524 SmallVectorImpl<MachineBasicBlock *> &RemoveList = BlockWorkList;
2525 if (RemBB->isEHPad())
2526 RemoveList = EHPadWorkList;
2527 RemoveList.erase(
2528 remove_if(RemoveList,
2529 [RemBB](MachineBasicBlock *BB) {return BB == RemBB;}),
2530 RemoveList.end());
2531 }
2532
2533 // Handle the filter set
2534 if (BlockFilter) {
Rong Xu66827422016-11-16 20:50:06 +00002535 BlockFilter->remove(RemBB);
Kyle Butt0846e562016-10-11 20:36:43 +00002536 }
2537
2538 // Remove the block from loop info.
2539 MLI->removeBlock(RemBB);
Kyle Buttab9cca72016-10-27 21:37:20 +00002540 if (RemBB == PreferredLoopExit)
2541 PreferredLoopExit = nullptr;
Kyle Butt0846e562016-10-11 20:36:43 +00002542
Kyle Butt0846e562016-10-11 20:36:43 +00002543 DEBUG(dbgs() << "TailDuplicator deleted block: "
2544 << getBlockName(RemBB) << "\n");
2545 };
2546 auto RemovalCallbackRef =
2547 llvm::function_ref<void(MachineBasicBlock*)>(RemovalCallback);
2548
2549 SmallVector<MachineBasicBlock *, 8> DuplicatedPreds;
Kyle Buttb15c0662017-01-31 23:48:32 +00002550 bool IsSimple = TailDup.isSimpleBB(BB);
Kyle Butt0846e562016-10-11 20:36:43 +00002551 TailDup.tailDuplicateAndUpdate(IsSimple, BB, LPred,
2552 &DuplicatedPreds, &RemovalCallbackRef);
2553
2554 // Update UnscheduledPredecessors to reflect tail-duplication.
2555 DuplicatedToLPred = false;
2556 for (MachineBasicBlock *Pred : DuplicatedPreds) {
2557 // We're only looking for unscheduled predecessors that match the filter.
2558 BlockChain* PredChain = BlockToChain[Pred];
2559 if (Pred == LPred)
2560 DuplicatedToLPred = true;
2561 if (Pred == LPred || (BlockFilter && !BlockFilter->count(Pred))
2562 || PredChain == &Chain)
2563 continue;
2564 for (MachineBasicBlock *NewSucc : Pred->successors()) {
2565 if (BlockFilter && !BlockFilter->count(NewSucc))
2566 continue;
2567 BlockChain *NewChain = BlockToChain[NewSucc];
2568 if (NewChain != &Chain && NewChain != PredChain)
2569 NewChain->UnscheduledPredecessors++;
2570 }
2571 }
2572 return Removed;
2573}
2574
Xinliang David Li52530a72016-06-13 22:23:44 +00002575bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &MF) {
2576 if (skipFunction(*MF.getFunction()))
Andrew Kaylor50271f72016-05-03 22:32:30 +00002577 return false;
2578
Chandler Carruth10281422011-10-21 06:46:38 +00002579 // Check for single-block functions and skip them.
Xinliang David Li52530a72016-06-13 22:23:44 +00002580 if (std::next(MF.begin()) == MF.end())
Chandler Carruth10281422011-10-21 06:46:38 +00002581 return false;
2582
Xinliang David Li52530a72016-06-13 22:23:44 +00002583 F = &MF;
Chandler Carruth10281422011-10-21 06:46:38 +00002584 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002585 MBFI = llvm::make_unique<BranchFolder::MBFIWrapper>(
2586 getAnalysis<MachineBlockFrequencyInfo>());
Chandler Carruth8b9737c2011-10-21 08:57:37 +00002587 MLI = &getAnalysis<MachineLoopInfo>();
Xinliang David Li52530a72016-06-13 22:23:44 +00002588 TII = MF.getSubtarget().getInstrInfo();
2589 TLI = MF.getSubtarget().getTargetLowering();
Daniel Jasper471e8562015-03-04 11:05:34 +00002590 MDT = &getAnalysis<MachineDominatorTree>();
Kyle Buttb15c0662017-01-31 23:48:32 +00002591 MPDT = nullptr;
Eric Christopher690f8e52016-11-01 22:15:50 +00002592
2593 // Initialize PreferredLoopExit to nullptr here since it may never be set if
2594 // there are no MachineLoops.
2595 PreferredLoopExit = nullptr;
2596
Kyle Butt0846e562016-10-11 20:36:43 +00002597 if (TailDupPlacement) {
Kyle Buttb15c0662017-01-31 23:48:32 +00002598 MPDT = &getAnalysis<MachinePostDominatorTree>();
2599 unsigned TailDupSize = TailDupPlacementThreshold;
Kyle Butt0846e562016-10-11 20:36:43 +00002600 if (MF.getFunction()->optForSize())
2601 TailDupSize = 1;
2602 TailDup.initMF(MF, MBPI, /* LayoutMode */ true, TailDupSize);
2603 }
2604
Chandler Carruth10281422011-10-21 06:46:38 +00002605 assert(BlockToChain.empty());
Chandler Carruth10281422011-10-21 06:46:38 +00002606
Xinliang David Li52530a72016-06-13 22:23:44 +00002607 buildCFGChains();
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002608
2609 // Changing the layout can create new tail merging opportunities.
2610 TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
2611 // TailMerge can create jump into if branches that make CFG irreducible for
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00002612 // HW that requires structured CFG.
Xinliang David Li52530a72016-06-13 22:23:44 +00002613 bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002614 PassConfig->getEnableTailMerge() &&
2615 BranchFoldPlacement;
2616 // No tail merging opportunities if the block number is less than four.
Xinliang David Li52530a72016-06-13 22:23:44 +00002617 if (MF.size() > 3 && EnableTailMerge) {
Kyle Buttb15c0662017-01-31 23:48:32 +00002618 unsigned TailMergeSize = TailDupPlacementThreshold + 1;
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002619 BranchFolder BF(/*EnableTailMerge=*/true, /*CommonHoist=*/false, *MBFI,
Kyle Butt64e42812016-08-18 18:57:29 +00002620 *MBPI, TailMergeSize);
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002621
Xinliang David Li52530a72016-06-13 22:23:44 +00002622 if (BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002623 getAnalysisIfAvailable<MachineModuleInfo>(), MLI,
2624 /*AfterBlockPlacement=*/true)) {
2625 // Redo the layout if tail merging creates/removes/moves blocks.
2626 BlockToChain.clear();
Kyle Butt0846e562016-10-11 20:36:43 +00002627 // Must redo the dominator tree if blocks were changed.
2628 MDT->runOnMachineFunction(MF);
Kyle Buttb15c0662017-01-31 23:48:32 +00002629 if (MPDT)
2630 MPDT->runOnMachineFunction(MF);
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002631 ChainAllocator.DestroyAll();
Xinliang David Li52530a72016-06-13 22:23:44 +00002632 buildCFGChains();
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002633 }
2634 }
2635
Xinliang David Li52530a72016-06-13 22:23:44 +00002636 optimizeBranches();
2637 alignBlocks();
Chandler Carruth10281422011-10-21 06:46:38 +00002638
Chandler Carruth10281422011-10-21 06:46:38 +00002639 BlockToChain.clear();
Chandler Carruthfd9b4d92011-11-14 10:57:23 +00002640 ChainAllocator.DestroyAll();
Chandler Carruth10281422011-10-21 06:46:38 +00002641
Nadav Rotemc0adc9f2013-04-12 01:24:16 +00002642 if (AlignAllBlock)
2643 // Align all of the blocks in the function to a specific alignment.
Xinliang David Li52530a72016-06-13 22:23:44 +00002644 for (MachineBasicBlock &MBB : MF)
Chandler Carruth7a715da2015-03-05 03:19:05 +00002645 MBB.setAlignment(AlignAllBlock);
Geoff Berry10494ac2016-01-21 17:25:52 +00002646 else if (AlignAllNonFallThruBlocks) {
2647 // Align all of the blocks that have no fall-through predecessors to a
2648 // specific alignment.
Xinliang David Li52530a72016-06-13 22:23:44 +00002649 for (auto MBI = std::next(MF.begin()), MBE = MF.end(); MBI != MBE; ++MBI) {
Geoff Berry10494ac2016-01-21 17:25:52 +00002650 auto LayoutPred = std::prev(MBI);
2651 if (!LayoutPred->isSuccessor(&*MBI))
2652 MBI->setAlignment(AlignAllNonFallThruBlocks);
2653 }
2654 }
Xinliang David Lifd3f6452017-01-29 01:57:02 +00002655 if (ViewBlockLayoutWithBFI != GVDT_None &&
2656 (ViewBlockFreqFuncName.empty() ||
2657 F->getFunction()->getName().equals(ViewBlockFreqFuncName))) {
Xinliang David Li538d6662017-02-15 19:21:04 +00002658 MBFI->view("MBP." + MF.getName(), false);
Xinliang David Lifd3f6452017-01-29 01:57:02 +00002659 }
Xinliang David Lifd3f6452017-01-29 01:57:02 +00002660
Nadav Rotemc0adc9f2013-04-12 01:24:16 +00002661
Chandler Carruth10281422011-10-21 06:46:38 +00002662 // We always return true as we have no way to track whether the final order
2663 // differs from the original order.
2664 return true;
2665}
Chandler Carruthae4e8002011-11-02 07:17:12 +00002666
2667namespace {
2668/// \brief A pass to compute block placement statistics.
2669///
2670/// A separate pass to compute interesting statistics for evaluating block
2671/// placement. This is separate from the actual placement pass so that they can
Benjamin Kramerbde91762012-06-02 10:20:22 +00002672/// be computed in the absence of any placement transformations or when using
Chandler Carruthae4e8002011-11-02 07:17:12 +00002673/// alternative placement strategies.
2674class MachineBlockPlacementStats : public MachineFunctionPass {
2675 /// \brief A handle to the branch probability pass.
2676 const MachineBranchProbabilityInfo *MBPI;
2677
2678 /// \brief A handle to the function-wide block frequency pass.
2679 const MachineBlockFrequencyInfo *MBFI;
2680
2681public:
2682 static char ID; // Pass identification, replacement for typeid
2683 MachineBlockPlacementStats() : MachineFunctionPass(ID) {
2684 initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
2685 }
2686
Craig Topper4584cd52014-03-07 09:26:03 +00002687 bool runOnMachineFunction(MachineFunction &F) override;
Chandler Carruthae4e8002011-11-02 07:17:12 +00002688
Craig Topper4584cd52014-03-07 09:26:03 +00002689 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruthae4e8002011-11-02 07:17:12 +00002690 AU.addRequired<MachineBranchProbabilityInfo>();
2691 AU.addRequired<MachineBlockFrequencyInfo>();
2692 AU.setPreservesAll();
2693 MachineFunctionPass::getAnalysisUsage(AU);
2694 }
Chandler Carruthae4e8002011-11-02 07:17:12 +00002695};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00002696}
Chandler Carruthae4e8002011-11-02 07:17:12 +00002697
2698char MachineBlockPlacementStats::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +00002699char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
Chandler Carruthae4e8002011-11-02 07:17:12 +00002700INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
2701 "Basic Block Placement Stats", false, false)
2702INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
2703INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
2704INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
2705 "Basic Block Placement Stats", false, false)
2706
Chandler Carruthae4e8002011-11-02 07:17:12 +00002707bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
2708 // Check for single-block functions and skip them.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002709 if (std::next(F.begin()) == F.end())
Chandler Carruthae4e8002011-11-02 07:17:12 +00002710 return false;
2711
2712 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
2713 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
2714
Chandler Carruth7a715da2015-03-05 03:19:05 +00002715 for (MachineBasicBlock &MBB : F) {
2716 BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00002717 Statistic &NumBranches =
Chandler Carruth7a715da2015-03-05 03:19:05 +00002718 (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00002719 Statistic &BranchTakenFreq =
Chandler Carruth7a715da2015-03-05 03:19:05 +00002720 (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
2721 for (MachineBasicBlock *Succ : MBB.successors()) {
Chandler Carruthae4e8002011-11-02 07:17:12 +00002722 // Skip if this successor is a fallthrough.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002723 if (MBB.isLayoutSuccessor(Succ))
Chandler Carruthae4e8002011-11-02 07:17:12 +00002724 continue;
2725
Chandler Carruth7a715da2015-03-05 03:19:05 +00002726 BlockFrequency EdgeFreq =
2727 BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
Chandler Carruthae4e8002011-11-02 07:17:12 +00002728 ++NumBranches;
2729 BranchTakenFreq += EdgeFreq.getFrequency();
2730 }
2731 }
2732
2733 return false;
2734}