blob: c03ffdd3732d70ad680d99ffcf14c618a9fbd718 [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"
39#include "llvm/CodeGen/MachineFunction.h"
Chandler Carruth10281422011-10-21 06:46:38 +000040#include "llvm/CodeGen/MachineFunctionPass.h"
Chandler Carruth8b9737c2011-10-21 08:57:37 +000041#include "llvm/CodeGen/MachineLoopInfo.h"
42#include "llvm/CodeGen/MachineModuleInfo.h"
Kyle Buttb15c0662017-01-31 23:48:32 +000043#include "llvm/CodeGen/MachinePostDominators.h"
Kyle Butt0846e562016-10-11 20:36:43 +000044#include "llvm/CodeGen/TailDuplicator.h"
Chandler Carruth10281422011-10-21 06:46:38 +000045#include "llvm/Support/Allocator.h"
Nadav Rotemc3b0f502013-04-12 00:48:32 +000046#include "llvm/Support/CommandLine.h"
Chandler Carruthbd1be4d2011-10-23 09:18:45 +000047#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000048#include "llvm/Support/raw_ostream.h"
Chandler Carruth10281422011-10-21 06:46:38 +000049#include "llvm/Target/TargetInstrInfo.h"
Chandler Carruth8b9737c2011-10-21 08:57:37 +000050#include "llvm/Target/TargetLowering.h"
Eric Christopherd9134482014-08-04 21:25:23 +000051#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruth10281422011-10-21 06:46:38 +000052#include <algorithm>
Kyle Butt1fa60302017-03-03 01:00:22 +000053#include <forward_list>
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
Cong Houb90b9e02015-11-02 21:24:00 +000089static cl::opt<unsigned> LoopToColdBlockRatio(
90 "loop-to-cold-block-ratio",
91 cl::desc("Outline loop blocks from loop chain if (frequency of loop) / "
92 "(frequency of block) is greater than this ratio"),
93 cl::init(5), cl::Hidden);
94
Cong Hou7745dbc2015-10-19 23:16:40 +000095static cl::opt<bool>
96 PreciseRotationCost("precise-rotation-cost",
97 cl::desc("Model the cost of loop rotation more "
98 "precisely by using profile data."),
99 cl::init(false), cl::Hidden);
Xinliang David Lif0ab6df2016-05-12 02:04:41 +0000100static cl::opt<bool>
101 ForcePreciseRotationCost("force-precise-rotation-cost",
Xinliang David Lib840bb82016-05-12 16:39:02 +0000102 cl::desc("Force the use of precise cost "
103 "loop rotation strategy."),
Xinliang David Lif0ab6df2016-05-12 02:04:41 +0000104 cl::init(false), cl::Hidden);
Cong Hou7745dbc2015-10-19 23:16:40 +0000105
106static cl::opt<unsigned> MisfetchCost(
107 "misfetch-cost",
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000108 cl::desc("Cost that models the probabilistic risk of an instruction "
Cong Hou7745dbc2015-10-19 23:16:40 +0000109 "misfetch due to a jump comparing to falling through, whose cost "
110 "is zero."),
111 cl::init(1), cl::Hidden);
112
113static cl::opt<unsigned> JumpInstCost("jump-inst-cost",
114 cl::desc("Cost of jump instructions."),
115 cl::init(1), cl::Hidden);
Kyle Butt0846e562016-10-11 20:36:43 +0000116static cl::opt<bool>
117TailDupPlacement("tail-dup-placement",
118 cl::desc("Perform tail duplication during placement. "
119 "Creates more fallthrough opportunites in "
120 "outline branches."),
121 cl::init(true), cl::Hidden);
Cong Hou7745dbc2015-10-19 23:16:40 +0000122
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000123static cl::opt<bool>
124BranchFoldPlacement("branch-fold-placement",
125 cl::desc("Perform branch folding during placement. "
126 "Reduces code size."),
127 cl::init(true), cl::Hidden);
128
Kyle Butt0846e562016-10-11 20:36:43 +0000129// Heuristic for tail duplication.
Kyle Buttb15c0662017-01-31 23:48:32 +0000130static cl::opt<unsigned> TailDupPlacementThreshold(
Kyle Butt0846e562016-10-11 20:36:43 +0000131 "tail-dup-placement-threshold",
132 cl::desc("Instruction cutoff for tail duplication during layout. "
133 "Tail merging during layout is forced to have a threshold "
134 "that won't conflict."), cl::init(2),
135 cl::Hidden);
136
Kyle Buttb15c0662017-01-31 23:48:32 +0000137// Heuristic for tail duplication.
138static cl::opt<unsigned> TailDupPlacementPenalty(
139 "tail-dup-placement-penalty",
140 cl::desc("Cost penalty for blocks that can avoid breaking CFG by copying. "
141 "Copying can increase fallthrough, but it also increases icache "
142 "pressure. This parameter controls the penalty to account for that. "
143 "Percent as integer."),
144 cl::init(2),
145 cl::Hidden);
146
Kyle Butt1fa60302017-03-03 01:00:22 +0000147// Heuristic for triangle chains.
148static cl::opt<unsigned> TriangleChainCount(
149 "triangle-chain-count",
150 cl::desc("Number of triangle-shaped-CFG's that need to be in a row for the "
151 "triangle tail duplication heuristic to kick in. 0 to disable."),
Kyle Butt08655992017-03-16 01:32:29 +0000152 cl::init(2),
Kyle Butt1fa60302017-03-03 01:00:22 +0000153 cl::Hidden);
154
Xinliang David Liff287372016-06-03 23:48:36 +0000155extern cl::opt<unsigned> StaticLikelyProb;
Dehao Chen9f2bdfb2016-06-14 22:27:17 +0000156extern cl::opt<unsigned> ProfileLikelyProb;
Xinliang David Liff287372016-06-03 23:48:36 +0000157
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000158// Internal option used to control BFI display only after MBP pass.
159// Defined in CodeGen/MachineBlockFrequencyInfo.cpp:
160// -view-block-layout-with-bfi=
Xinliang David Lifd3f6452017-01-29 01:57:02 +0000161extern cl::opt<GVDAGType> ViewBlockLayoutWithBFI;
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000162
163// Command line option to specify the name of the function for CFG dump
164// Defined in Analysis/BlockFrequencyInfo.cpp: -view-bfi-func-name=
Xinliang David Lifd3f6452017-01-29 01:57:02 +0000165extern cl::opt<std::string> ViewBlockFreqFuncName;
Xinliang David Lifd3f6452017-01-29 01:57:02 +0000166
Chandler Carruth10281422011-10-21 06:46:38 +0000167namespace {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000168class BlockChain;
Chandler Carruth10281422011-10-21 06:46:38 +0000169/// \brief Type for our function-wide basic block -> block chain mapping.
Kyle Butte9425c4f2017-02-04 02:26:32 +0000170typedef DenseMap<const MachineBasicBlock *, BlockChain *> BlockToChainMapType;
Chandler Carruth10281422011-10-21 06:46:38 +0000171}
172
173namespace {
174/// \brief A chain of blocks which will be laid out contiguously.
175///
176/// This is the datastructure representing a chain of consecutive blocks that
177/// are profitable to layout together in order to maximize fallthrough
Chandler Carruth9139f442012-06-26 05:16:37 +0000178/// probabilities and code locality. We also can use a block chain to represent
179/// a sequence of basic blocks which have some external (correctness)
180/// requirement for sequential layout.
Chandler Carruth10281422011-10-21 06:46:38 +0000181///
Chandler Carruth9139f442012-06-26 05:16:37 +0000182/// Chains can be built around a single basic block and can be merged to grow
183/// them. They participate in a block-to-chain mapping, which is updated
184/// automatically as chains are merged together.
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000185class BlockChain {
186 /// \brief The sequence of blocks belonging to this chain.
Chandler Carruth10281422011-10-21 06:46:38 +0000187 ///
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000188 /// This is the sequence of blocks for a particular chain. These will be laid
189 /// out in-order within the function.
190 SmallVector<MachineBasicBlock *, 4> Blocks;
Chandler Carruth10281422011-10-21 06:46:38 +0000191
192 /// \brief A handle to the function-wide basic block to block chain mapping.
193 ///
194 /// This is retained in each block chain to simplify the computation of child
195 /// block chains for SCC-formation and iteration. We store the edges to child
196 /// basic blocks, and map them back to their associated chains using this
197 /// structure.
198 BlockToChainMapType &BlockToChain;
199
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000200public:
Chandler Carruth10281422011-10-21 06:46:38 +0000201 /// \brief Construct a new BlockChain.
202 ///
203 /// This builds a new block chain representing a single basic block in the
204 /// function. It also registers itself as the chain that block participates
205 /// in with the BlockToChain mapping.
206 BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
Philip Reamesae27b232016-03-03 00:58:43 +0000207 : Blocks(1, BB), BlockToChain(BlockToChain), UnscheduledPredecessors(0) {
Chandler Carruth10281422011-10-21 06:46:38 +0000208 assert(BB && "Cannot create a chain with a null basic block");
209 BlockToChain[BB] = this;
210 }
211
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000212 /// \brief Iterator over blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000213 typedef SmallVectorImpl<MachineBasicBlock *>::iterator iterator;
Kyle Butte9425c4f2017-02-04 02:26:32 +0000214 typedef SmallVectorImpl<MachineBasicBlock *>::const_iterator const_iterator;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000215
216 /// \brief Beginning of blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000217 iterator begin() { return Blocks.begin(); }
Kyle Butte9425c4f2017-02-04 02:26:32 +0000218 const_iterator begin() const { return Blocks.begin(); }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000219
220 /// \brief End of blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000221 iterator end() { return Blocks.end(); }
Kyle Butte9425c4f2017-02-04 02:26:32 +0000222 const_iterator end() const { return Blocks.end(); }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000223
Kyle Butt0846e562016-10-11 20:36:43 +0000224 bool remove(MachineBasicBlock* BB) {
225 for(iterator i = begin(); i != end(); ++i) {
226 if (*i == BB) {
227 Blocks.erase(i);
228 return true;
229 }
230 }
231 return false;
232 }
233
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000234 /// \brief Merge a block chain into this one.
Chandler Carruth10281422011-10-21 06:46:38 +0000235 ///
236 /// This routine merges a block chain into this one. It takes care of forming
237 /// a contiguous sequence of basic blocks, updating the edge list, and
238 /// updating the block -> chain mapping. It does not free or tear down the
239 /// old chain, but the old chain's block list is no longer valid.
Jakub Staszak90616162011-12-21 23:02:08 +0000240 void merge(MachineBasicBlock *BB, BlockChain *Chain) {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000241 assert(BB);
242 assert(!Blocks.empty());
Chandler Carruth10281422011-10-21 06:46:38 +0000243
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000244 // Fast path in case we don't have a chain already.
245 if (!Chain) {
246 assert(!BlockToChain[BB]);
247 Blocks.push_back(BB);
248 BlockToChain[BB] = this;
249 return;
Chandler Carruth10281422011-10-21 06:46:38 +0000250 }
251
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000252 assert(BB == *Chain->begin());
253 assert(Chain->begin() != Chain->end());
Chandler Carruth10281422011-10-21 06:46:38 +0000254
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000255 // Update the incoming blocks to point to this chain, and add them to the
256 // chain structure.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000257 for (MachineBasicBlock *ChainBB : *Chain) {
258 Blocks.push_back(ChainBB);
259 assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain");
260 BlockToChain[ChainBB] = this;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000261 }
Chandler Carruth10281422011-10-21 06:46:38 +0000262 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000263
Chandler Carruth49158902012-04-08 14:37:01 +0000264#ifndef NDEBUG
265 /// \brief Dump the blocks in this chain.
Nico Weber7408c702014-01-03 22:53:37 +0000266 LLVM_DUMP_METHOD void dump() {
Chandler Carruth7a715da2015-03-05 03:19:05 +0000267 for (MachineBasicBlock *MBB : *this)
268 MBB->dump();
Chandler Carruth49158902012-04-08 14:37:01 +0000269 }
270#endif // NDEBUG
271
Philip Reamesae27b232016-03-03 00:58:43 +0000272 /// \brief Count of predecessors of any block within the chain which have not
273 /// yet been scheduled. In general, we will delay scheduling this chain
274 /// until those predecessors are scheduled (or we find a sufficiently good
275 /// reason to override this heuristic.) Note that when forming loop chains,
276 /// blocks outside the loop are ignored and treated as if they were already
277 /// scheduled.
Chandler Carruth8d150782011-11-13 11:20:44 +0000278 ///
Philip Reamesae27b232016-03-03 00:58:43 +0000279 /// Note: This field is reinitialized multiple times - once for each loop,
280 /// and then once for the function as a whole.
281 unsigned UnscheduledPredecessors;
Chandler Carruth10281422011-10-21 06:46:38 +0000282};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000283}
Chandler Carruth10281422011-10-21 06:46:38 +0000284
285namespace {
286class MachineBlockPlacement : public MachineFunctionPass {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000287 /// \brief A typedef for a block filter set.
Kyle Butte9425c4f2017-02-04 02:26:32 +0000288 typedef SmallSetVector<const MachineBasicBlock *, 16> BlockFilterSet;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000289
Kyle Buttb15c0662017-01-31 23:48:32 +0000290 /// Pair struct containing basic block and taildup profitiability
291 struct BlockAndTailDupResult {
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000292 MachineBasicBlock *BB;
Kyle Buttb15c0662017-01-31 23:48:32 +0000293 bool ShouldTailDup;
294 };
295
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000296 /// Triple struct containing edge weight and the edge.
297 struct WeightedEdge {
298 BlockFrequency Weight;
299 MachineBasicBlock *Src;
300 MachineBasicBlock *Dest;
301 };
302
Xinliang David Li93926ac2016-07-01 05:46:48 +0000303 /// \brief work lists of blocks that are ready to be laid out
304 SmallVector<MachineBasicBlock *, 16> BlockWorkList;
305 SmallVector<MachineBasicBlock *, 16> EHPadWorkList;
306
Kyle Buttebe6cc42017-02-23 21:22:24 +0000307 /// Edges that have already been computed as optimal.
308 DenseMap<const MachineBasicBlock *, BlockAndTailDupResult> ComputedEdges;
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000309
Xinliang David Li52530a72016-06-13 22:23:44 +0000310 /// \brief Machine Function
311 MachineFunction *F;
312
Chandler Carruth10281422011-10-21 06:46:38 +0000313 /// \brief A handle to the branch probability pass.
314 const MachineBranchProbabilityInfo *MBPI;
315
316 /// \brief A handle to the function-wide block frequency pass.
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000317 std::unique_ptr<BranchFolder::MBFIWrapper> MBFI;
Chandler Carruth10281422011-10-21 06:46:38 +0000318
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000319 /// \brief A handle to the loop info.
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000320 MachineLoopInfo *MLI;
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000321
Kyle Buttab9cca72016-10-27 21:37:20 +0000322 /// \brief Preferred loop exit.
323 /// Member variable for convenience. It may be removed by duplication deep
324 /// in the call stack.
325 MachineBasicBlock *PreferredLoopExit;
326
Chandler Carruth10281422011-10-21 06:46:38 +0000327 /// \brief A handle to the target's instruction info.
328 const TargetInstrInfo *TII;
329
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000330 /// \brief A handle to the target's lowering info.
Benjamin Kramer56b31bd2013-01-11 20:05:37 +0000331 const TargetLoweringBase *TLI;
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000332
Kyle Buttb15c0662017-01-31 23:48:32 +0000333 /// \brief A handle to the post dominator tree.
334 MachinePostDominatorTree *MPDT;
335
Kyle Butt0846e562016-10-11 20:36:43 +0000336 /// \brief Duplicator used to duplicate tails during placement.
337 ///
338 /// Placement decisions can open up new tail duplication opportunities, but
339 /// since tail duplication affects placement decisions of later blocks, it
340 /// must be done inline.
341 TailDuplicator TailDup;
342
Chandler Carruth10281422011-10-21 06:46:38 +0000343 /// \brief Allocator and owner of BlockChain structures.
344 ///
Chandler Carruth9139f442012-06-26 05:16:37 +0000345 /// We build BlockChains lazily while processing the loop structure of
346 /// a function. To reduce malloc traffic, we allocate them using this
347 /// slab-like allocator, and destroy them after the pass completes. An
348 /// important guarantee is that this allocator produces stable pointers to
349 /// the chains.
Chandler Carruth10281422011-10-21 06:46:38 +0000350 SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
351
352 /// \brief Function wide BasicBlock to BlockChain mapping.
353 ///
354 /// This mapping allows efficiently moving from any given basic block to the
355 /// BlockChain it participates in, if any. We use it to, among other things,
356 /// allow implicitly defining edges between chains as the existing edges
357 /// between basic blocks.
Kyle Butte9425c4f2017-02-04 02:26:32 +0000358 DenseMap<const MachineBasicBlock *, BlockChain *> BlockToChain;
Chandler Carruth10281422011-10-21 06:46:38 +0000359
Sanjoy Dasd7389d62016-12-15 05:08:57 +0000360#ifndef NDEBUG
361 /// The set of basic blocks that have terminators that cannot be fully
362 /// analyzed. These basic blocks cannot be re-ordered safely by
363 /// MachineBlockPlacement, and we must preserve physical layout of these
364 /// blocks and their successors through the pass.
365 SmallPtrSet<MachineBasicBlock *, 4> BlocksWithUnanalyzableExits;
366#endif
367
Kyle Butt0846e562016-10-11 20:36:43 +0000368 /// Decrease the UnscheduledPredecessors count for all blocks in chain, and
369 /// if the count goes to 0, add them to the appropriate work list.
Kyle Butte9425c4f2017-02-04 02:26:32 +0000370 void markChainSuccessors(
371 const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB,
372 const BlockFilterSet *BlockFilter = nullptr);
Kyle Butt0846e562016-10-11 20:36:43 +0000373
374 /// Decrease the UnscheduledPredecessors count for a single block, and
375 /// if the count goes to 0, add them to the appropriate work list.
376 void markBlockSuccessors(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000377 const BlockChain &Chain, const MachineBasicBlock *BB,
378 const MachineBasicBlock *LoopHeaderBB,
Kyle Butt0846e562016-10-11 20:36:43 +0000379 const BlockFilterSet *BlockFilter = nullptr);
380
Xinliang David Li594ffa32016-06-11 18:35:40 +0000381 BranchProbability
Kyle Butte9425c4f2017-02-04 02:26:32 +0000382 collectViableSuccessors(
383 const MachineBasicBlock *BB, const BlockChain &Chain,
384 const BlockFilterSet *BlockFilter,
385 SmallVector<MachineBasicBlock *, 4> &Successors);
386 bool shouldPredBlockBeOutlined(
387 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
388 const BlockChain &Chain, const BlockFilterSet *BlockFilter,
389 BranchProbability SuccProb, BranchProbability HotProb);
Kyle Butt0846e562016-10-11 20:36:43 +0000390 bool repeatedlyTailDuplicateBlock(
391 MachineBasicBlock *BB, MachineBasicBlock *&LPred,
Kyle Butte9425c4f2017-02-04 02:26:32 +0000392 const MachineBasicBlock *LoopHeaderBB,
Kyle Butt0846e562016-10-11 20:36:43 +0000393 BlockChain &Chain, BlockFilterSet *BlockFilter,
394 MachineFunction::iterator &PrevUnplacedBlockIt);
Kyle Butte9425c4f2017-02-04 02:26:32 +0000395 bool maybeTailDuplicateBlock(
396 MachineBasicBlock *BB, MachineBasicBlock *LPred,
397 BlockChain &Chain, BlockFilterSet *BlockFilter,
398 MachineFunction::iterator &PrevUnplacedBlockIt,
399 bool &DuplicatedToPred);
400 bool hasBetterLayoutPredecessor(
401 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
402 const BlockChain &SuccChain, BranchProbability SuccProb,
403 BranchProbability RealSuccProb, const BlockChain &Chain,
404 const BlockFilterSet *BlockFilter);
405 BlockAndTailDupResult selectBestSuccessor(
406 const MachineBasicBlock *BB, const BlockChain &Chain,
407 const BlockFilterSet *BlockFilter);
408 MachineBasicBlock *selectBestCandidateBlock(
409 const BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList);
410 MachineBasicBlock *getFirstUnplacedBlock(
411 const BlockChain &PlacedChain,
412 MachineFunction::iterator &PrevUnplacedBlockIt,
413 const BlockFilterSet *BlockFilter);
Amaury Secheteae09c22016-03-14 21:24:11 +0000414
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000415 /// \brief Add a basic block to the work list if it is appropriate.
Amaury Secheteae09c22016-03-14 21:24:11 +0000416 ///
417 /// If the optional parameter BlockFilter is provided, only MBB
418 /// present in the set will be added to the worklist. If nullptr
419 /// is provided, no filtering occurs.
Kyle Butte9425c4f2017-02-04 02:26:32 +0000420 void fillWorkLists(const MachineBasicBlock *MBB,
Amaury Secheteae09c22016-03-14 21:24:11 +0000421 SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
Amaury Secheteae09c22016-03-14 21:24:11 +0000422 const BlockFilterSet *BlockFilter);
Kyle Butte9425c4f2017-02-04 02:26:32 +0000423 void buildChain(const MachineBasicBlock *BB, BlockChain &Chain,
Kyle Butt0846e562016-10-11 20:36:43 +0000424 BlockFilterSet *BlockFilter = nullptr);
Kyle Butte9425c4f2017-02-04 02:26:32 +0000425 MachineBasicBlock *findBestLoopTop(
426 const MachineLoop &L, const BlockFilterSet &LoopBlockSet);
427 MachineBasicBlock *findBestLoopExit(
428 const MachineLoop &L, const BlockFilterSet &LoopBlockSet);
429 BlockFilterSet collectLoopBlockSet(const MachineLoop &L);
430 void buildLoopChains(const MachineLoop &L);
431 void rotateLoop(
432 BlockChain &LoopChain, const MachineBasicBlock *ExitingBB,
433 const BlockFilterSet &LoopBlockSet);
434 void rotateLoopWithProfile(
435 BlockChain &LoopChain, const MachineLoop &L,
436 const BlockFilterSet &LoopBlockSet);
Xinliang David Li52530a72016-06-13 22:23:44 +0000437 void buildCFGChains();
438 void optimizeBranches();
439 void alignBlocks();
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000440 /// Returns true if a block should be tail-duplicated to increase fallthrough
441 /// opportunities.
Kyle Buttb15c0662017-01-31 23:48:32 +0000442 bool shouldTailDuplicate(MachineBasicBlock *BB);
443 /// Check the edge frequencies to see if tail duplication will increase
444 /// fallthroughs.
445 bool isProfitableToTailDup(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000446 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
Kyle Buttb15c0662017-01-31 23:48:32 +0000447 BranchProbability AdjustedSumProb,
Kyle Butte9425c4f2017-02-04 02:26:32 +0000448 const BlockChain &Chain, const BlockFilterSet *BlockFilter);
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000449 /// Check for a trellis layout.
450 bool isTrellis(const MachineBasicBlock *BB,
451 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
452 const BlockChain &Chain, const BlockFilterSet *BlockFilter);
453 /// Get the best successor given a trellis layout.
454 BlockAndTailDupResult getBestTrellisSuccessor(
455 const MachineBasicBlock *BB,
456 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
457 BranchProbability AdjustedSumProb, const BlockChain &Chain,
458 const BlockFilterSet *BlockFilter);
459 /// Get the best pair of non-conflicting edges.
460 static std::pair<WeightedEdge, WeightedEdge> getBestNonConflictingEdges(
461 const MachineBasicBlock *BB,
462 SmallVector<SmallVector<WeightedEdge, 8>, 2> &Edges);
Kyle Buttb15c0662017-01-31 23:48:32 +0000463 /// Returns true if a block can tail duplicate into all unplaced
464 /// predecessors. Filters based on loop.
465 bool canTailDuplicateUnplacedPreds(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000466 const MachineBasicBlock *BB, MachineBasicBlock *Succ,
467 const BlockChain &Chain, const BlockFilterSet *BlockFilter);
Kyle Butt1fa60302017-03-03 01:00:22 +0000468 /// Find chains of triangles to tail-duplicate where a global analysis works,
469 /// but a local analysis would not find them.
470 void precomputeTriangleChains();
Chandler Carruth10281422011-10-21 06:46:38 +0000471
472public:
473 static char ID; // Pass identification, replacement for typeid
474 MachineBlockPlacement() : MachineFunctionPass(ID) {
475 initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
476 }
477
Craig Topper4584cd52014-03-07 09:26:03 +0000478 bool runOnMachineFunction(MachineFunction &F) override;
Chandler Carruth10281422011-10-21 06:46:38 +0000479
Craig Topper4584cd52014-03-07 09:26:03 +0000480 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth10281422011-10-21 06:46:38 +0000481 AU.addRequired<MachineBranchProbabilityInfo>();
482 AU.addRequired<MachineBlockFrequencyInfo>();
Kyle Buttb15c0662017-01-31 23:48:32 +0000483 if (TailDupPlacement)
484 AU.addRequired<MachinePostDominatorTree>();
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000485 AU.addRequired<MachineLoopInfo>();
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000486 AU.addRequired<TargetPassConfig>();
Chandler Carruth10281422011-10-21 06:46:38 +0000487 MachineFunctionPass::getAnalysisUsage(AU);
488 }
Chandler Carruth10281422011-10-21 06:46:38 +0000489};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000490}
Chandler Carruth10281422011-10-21 06:46:38 +0000491
492char MachineBlockPlacement::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000493char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
Chandler Carruthd0dced52015-03-05 02:28:25 +0000494INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement",
Chandler Carruth10281422011-10-21 06:46:38 +0000495 "Branch Probability Basic Block Placement", false, false)
496INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
497INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
Kyle Buttb15c0662017-01-31 23:48:32 +0000498INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree)
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000499INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
Chandler Carruthd0dced52015-03-05 02:28:25 +0000500INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement",
Chandler Carruth10281422011-10-21 06:46:38 +0000501 "Branch Probability Basic Block Placement", false, false)
502
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000503#ifndef NDEBUG
504/// \brief Helper to print the name of a MBB.
505///
506/// Only used by debug logging.
Kyle Butte9425c4f2017-02-04 02:26:32 +0000507static std::string getBlockName(const MachineBasicBlock *BB) {
Alp Tokere69170a2014-06-26 22:52:05 +0000508 std::string Result;
509 raw_string_ostream OS(Result);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000510 OS << "BB#" << BB->getNumber();
Philip Reamesb9688f42016-03-02 21:45:13 +0000511 OS << " ('" << BB->getName() << "')";
Alp Tokere69170a2014-06-26 22:52:05 +0000512 OS.flush();
513 return Result;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000514}
515#endif
516
Chandler Carrutheb4ec3a2011-11-13 11:34:55 +0000517/// \brief Mark a chain's successors as having one fewer preds.
518///
519/// When a chain is being merged into the "placed" chain, this routine will
520/// quickly walk the successors of each block in the chain and mark them as
521/// having one fewer active predecessor. It also adds any successors of this
Kyle Butt0846e562016-10-11 20:36:43 +0000522/// chain which reach the zero-predecessor state to the appropriate worklist.
Chandler Carruth8d150782011-11-13 11:20:44 +0000523void MachineBlockPlacement::markChainSuccessors(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000524 const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB,
Jakub Staszak90616162011-12-21 23:02:08 +0000525 const BlockFilterSet *BlockFilter) {
Chandler Carruth8d150782011-11-13 11:20:44 +0000526 // Walk all the blocks in this chain, marking their successors as having
527 // a predecessor placed.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000528 for (MachineBasicBlock *MBB : Chain) {
Kyle Butt0846e562016-10-11 20:36:43 +0000529 markBlockSuccessors(Chain, MBB, LoopHeaderBB, BlockFilter);
530 }
531}
Chandler Carruth10281422011-10-21 06:46:38 +0000532
Kyle Butt0846e562016-10-11 20:36:43 +0000533/// \brief Mark a single block's successors as having one fewer preds.
534///
535/// Under normal circumstances, this is only called by markChainSuccessors,
536/// but if a block that was to be placed is completely tail-duplicated away,
537/// and was duplicated into the chain end, we need to redo markBlockSuccessors
538/// for just that block.
539void MachineBlockPlacement::markBlockSuccessors(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000540 const BlockChain &Chain, const MachineBasicBlock *MBB,
541 const MachineBasicBlock *LoopHeaderBB, const BlockFilterSet *BlockFilter) {
Kyle Butt0846e562016-10-11 20:36:43 +0000542 // Add any successors for which this is the only un-placed in-loop
543 // predecessor to the worklist as a viable candidate for CFG-neutral
544 // placement. No subsequent placement of this block will violate the CFG
545 // shape, so we get to use heuristics to choose a favorable placement.
546 for (MachineBasicBlock *Succ : MBB->successors()) {
547 if (BlockFilter && !BlockFilter->count(Succ))
548 continue;
549 BlockChain &SuccChain = *BlockToChain[Succ];
550 // Disregard edges within a fixed chain, or edges to the loop header.
551 if (&Chain == &SuccChain || Succ == LoopHeaderBB)
552 continue;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000553
Kyle Butt0846e562016-10-11 20:36:43 +0000554 // This is a cross-chain edge that is within the loop, so decrement the
555 // loop predecessor count of the destination chain.
556 if (SuccChain.UnscheduledPredecessors == 0 ||
557 --SuccChain.UnscheduledPredecessors > 0)
558 continue;
559
560 auto *NewBB = *SuccChain.begin();
561 if (NewBB->isEHPad())
562 EHPadWorkList.push_back(NewBB);
563 else
564 BlockWorkList.push_back(NewBB);
Chandler Carruth10281422011-10-21 06:46:38 +0000565 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000566}
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000567
Xinliang David Li594ffa32016-06-11 18:35:40 +0000568/// This helper function collects the set of successors of block
569/// \p BB that are allowed to be its layout successors, and return
570/// the total branch probability of edges from \p BB to those
571/// blocks.
572BranchProbability MachineBlockPlacement::collectViableSuccessors(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000573 const MachineBasicBlock *BB, const BlockChain &Chain,
574 const BlockFilterSet *BlockFilter,
Xinliang David Li594ffa32016-06-11 18:35:40 +0000575 SmallVector<MachineBasicBlock *, 4> &Successors) {
Cong Houd97c1002015-12-01 05:29:22 +0000576 // Adjust edge probabilities by excluding edges pointing to blocks that is
577 // either not in BlockFilter or is already in the current chain. Consider the
578 // following CFG:
Cong Hou41cf1a52015-11-18 00:52:52 +0000579 //
580 // --->A
581 // | / \
582 // | B C
583 // | \ / \
584 // ----D E
585 //
586 // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after
587 // A->C is chosen as a fall-through, D won't be selected as a successor of C
588 // due to CFG constraint (the probability of C->D is not greater than
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000589 // HotProb to break top-order). If we exclude E that is not in BlockFilter
Xinliang David Li594ffa32016-06-11 18:35:40 +0000590 // when calculating the probability of C->D, D will be selected and we
591 // will get A C D B as the layout of this loop.
Cong Houd97c1002015-12-01 05:29:22 +0000592 auto AdjustedSumProb = BranchProbability::getOne();
Cong Hou41cf1a52015-11-18 00:52:52 +0000593 for (MachineBasicBlock *Succ : BB->successors()) {
594 bool SkipSucc = false;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000595 if (Succ->isEHPad() || (BlockFilter && !BlockFilter->count(Succ))) {
Cong Hou41cf1a52015-11-18 00:52:52 +0000596 SkipSucc = true;
597 } else {
598 BlockChain *SuccChain = BlockToChain[Succ];
599 if (SuccChain == &Chain) {
Cong Hou41cf1a52015-11-18 00:52:52 +0000600 SkipSucc = true;
601 } else if (Succ != *SuccChain->begin()) {
602 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> Mid chain!\n");
603 continue;
604 }
605 }
606 if (SkipSucc)
Cong Houd97c1002015-12-01 05:29:22 +0000607 AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ);
Cong Hou41cf1a52015-11-18 00:52:52 +0000608 else
609 Successors.push_back(Succ);
610 }
611
Xinliang David Li594ffa32016-06-11 18:35:40 +0000612 return AdjustedSumProb;
613}
614
615/// The helper function returns the branch probability that is adjusted
616/// or normalized over the new total \p AdjustedSumProb.
Xinliang David Li594ffa32016-06-11 18:35:40 +0000617static BranchProbability
618getAdjustedProbability(BranchProbability OrigProb,
619 BranchProbability AdjustedSumProb) {
620 BranchProbability SuccProb;
621 uint32_t SuccProbN = OrigProb.getNumerator();
622 uint32_t SuccProbD = AdjustedSumProb.getNumerator();
623 if (SuccProbN >= SuccProbD)
624 SuccProb = BranchProbability::getOne();
625 else
626 SuccProb = BranchProbability(SuccProbN, SuccProbD);
627
628 return SuccProb;
629}
630
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000631/// Check if \p BB has exactly the successors in \p Successors.
632static bool
633hasSameSuccessors(MachineBasicBlock &BB,
634 SmallPtrSetImpl<const MachineBasicBlock *> &Successors) {
635 if (BB.succ_size() != Successors.size())
636 return false;
637 // We don't want to count self-loops
638 if (Successors.count(&BB))
639 return false;
640 for (MachineBasicBlock *Succ : BB.successors())
641 if (!Successors.count(Succ))
642 return false;
643 return true;
644}
645
646/// Check if a block should be tail duplicated to increase fallthrough
647/// opportunities.
Kyle Buttb15c0662017-01-31 23:48:32 +0000648/// \p BB Block to check.
649bool MachineBlockPlacement::shouldTailDuplicate(MachineBasicBlock *BB) {
650 // Blocks with single successors don't create additional fallthrough
651 // opportunities. Don't duplicate them. TODO: When conditional exits are
652 // analyzable, allow them to be duplicated.
653 bool IsSimple = TailDup.isSimpleBB(BB);
654
655 if (BB->succ_size() == 1)
656 return false;
657 return TailDup.shouldTailDuplicate(IsSimple, *BB);
658}
659
660/// Compare 2 BlockFrequency's with a small penalty for \p A.
661/// In order to be conservative, we apply a X% penalty to account for
662/// increased icache pressure and static heuristics. For small frequencies
663/// we use only the numerators to improve accuracy. For simplicity, we assume the
664/// penalty is less than 100%
665/// TODO(iteratee): Use 64-bit fixed point edge frequencies everywhere.
666static bool greaterWithBias(BlockFrequency A, BlockFrequency B,
667 uint64_t EntryFreq) {
668 BranchProbability ThresholdProb(TailDupPlacementPenalty, 100);
669 BlockFrequency Gain = A - B;
670 return (Gain / ThresholdProb).getFrequency() >= EntryFreq;
671}
672
673/// Check the edge frequencies to see if tail duplication will increase
674/// fallthroughs. It only makes sense to call this function when
675/// \p Succ would not be chosen otherwise. Tail duplication of \p Succ is
676/// always locally profitable if we would have picked \p Succ without
677/// considering duplication.
678bool MachineBlockPlacement::isProfitableToTailDup(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000679 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
Kyle Buttb15c0662017-01-31 23:48:32 +0000680 BranchProbability QProb,
Kyle Butte9425c4f2017-02-04 02:26:32 +0000681 const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
Kyle Buttb15c0662017-01-31 23:48:32 +0000682 // We need to do a probability calculation to make sure this is profitable.
683 // First: does succ have a successor that post-dominates? This affects the
684 // calculation. The 2 relevant cases are:
685 // BB BB
686 // | \Qout | \Qout
687 // P| C |P C
688 // = C' = C'
689 // | /Qin | /Qin
690 // | / | /
691 // Succ Succ
692 // / \ | \ V
693 // U/ =V |U \
694 // / \ = D
695 // D E | /
696 // | /
697 // |/
698 // PDom
699 // '=' : Branch taken for that CFG edge
700 // In the second case, Placing Succ while duplicating it into C prevents the
701 // fallthrough of Succ into either D or PDom, because they now have C as an
702 // unplaced predecessor
703
704 // Start by figuring out which case we fall into
705 MachineBasicBlock *PDom = nullptr;
706 SmallVector<MachineBasicBlock *, 4> SuccSuccs;
707 // Only scan the relevant successors
708 auto AdjustedSuccSumProb =
709 collectViableSuccessors(Succ, Chain, BlockFilter, SuccSuccs);
710 BranchProbability PProb = MBPI->getEdgeProbability(BB, Succ);
711 auto BBFreq = MBFI->getBlockFreq(BB);
712 auto SuccFreq = MBFI->getBlockFreq(Succ);
713 BlockFrequency P = BBFreq * PProb;
714 BlockFrequency Qout = BBFreq * QProb;
715 uint64_t EntryFreq = MBFI->getEntryFreq();
716 // If there are no more successors, it is profitable to copy, as it strictly
717 // increases fallthrough.
718 if (SuccSuccs.size() == 0)
719 return greaterWithBias(P, Qout, EntryFreq);
720
721 auto BestSuccSucc = BranchProbability::getZero();
722 // Find the PDom or the best Succ if no PDom exists.
723 for (MachineBasicBlock *SuccSucc : SuccSuccs) {
724 auto Prob = MBPI->getEdgeProbability(Succ, SuccSucc);
725 if (Prob > BestSuccSucc)
726 BestSuccSucc = Prob;
727 if (PDom == nullptr)
728 if (MPDT->dominates(SuccSucc, Succ)) {
729 PDom = SuccSucc;
730 break;
731 }
732 }
733 // For the comparisons, we need to know Succ's best incoming edge that isn't
734 // from BB.
735 auto SuccBestPred = BlockFrequency(0);
736 for (MachineBasicBlock *SuccPred : Succ->predecessors()) {
737 if (SuccPred == Succ || SuccPred == BB
738 || BlockToChain[SuccPred] == &Chain
739 || (BlockFilter && !BlockFilter->count(SuccPred)))
740 continue;
741 auto Freq = MBFI->getBlockFreq(SuccPred)
742 * MBPI->getEdgeProbability(SuccPred, Succ);
743 if (Freq > SuccBestPred)
744 SuccBestPred = Freq;
745 }
746 // Qin is Succ's best unplaced incoming edge that isn't BB
747 BlockFrequency Qin = SuccBestPred;
748 // If it doesn't have a post-dominating successor, here is the calculation:
749 // BB BB
750 // | \Qout | \
751 // P| C | =
752 // = C' | C
753 // | /Qin | |
754 // | / | C' (+Succ)
755 // Succ Succ /|
756 // / \ | \/ |
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000757 // U/ =V | == |
Kyle Buttb15c0662017-01-31 23:48:32 +0000758 // / \ | / \|
759 // D E D E
760 // '=' : Branch taken for that CFG edge
761 // Cost in the first case is: P + V
762 // For this calculation, we always assume P > Qout. If Qout > P
763 // The result of this function will be ignored at the caller.
Kyle Buttee51a202017-04-10 22:28:18 +0000764 // Let F = SuccFreq - Qin
765 // Cost in the second case is: Qout + min(Qin, F) * U + max(Qin, F) * V
Kyle Buttb15c0662017-01-31 23:48:32 +0000766
767 if (PDom == nullptr || !Succ->isSuccessor(PDom)) {
768 BranchProbability UProb = BestSuccSucc;
769 BranchProbability VProb = AdjustedSuccSumProb - UProb;
Kyle Buttee51a202017-04-10 22:28:18 +0000770 BlockFrequency F = SuccFreq - Qin;
Kyle Buttb15c0662017-01-31 23:48:32 +0000771 BlockFrequency V = SuccFreq * VProb;
Kyle Buttee51a202017-04-10 22:28:18 +0000772 BlockFrequency QinU = std::min(Qin, F) * UProb;
Kyle Buttb15c0662017-01-31 23:48:32 +0000773 BlockFrequency BaseCost = P + V;
Kyle Buttee51a202017-04-10 22:28:18 +0000774 BlockFrequency DupCost = Qout + QinU + std::max(Qin, F) * VProb;
Kyle Buttb15c0662017-01-31 23:48:32 +0000775 return greaterWithBias(BaseCost, DupCost, EntryFreq);
776 }
777 BranchProbability UProb = MBPI->getEdgeProbability(Succ, PDom);
778 BranchProbability VProb = AdjustedSuccSumProb - UProb;
779 BlockFrequency U = SuccFreq * UProb;
780 BlockFrequency V = SuccFreq * VProb;
Kyle Buttee51a202017-04-10 22:28:18 +0000781 BlockFrequency F = SuccFreq - Qin;
Kyle Buttb15c0662017-01-31 23:48:32 +0000782 // If there is a post-dominating successor, here is the calculation:
783 // BB BB BB BB
Kyle Buttee51a202017-04-10 22:28:18 +0000784 // | \Qout | \ | \Qout | \
785 // |P C | = |P C | =
786 // = C' |P C = C' |P C
787 // | /Qin | | | /Qin | |
788 // | / | C' (+Succ) | / | C' (+Succ)
789 // Succ Succ /| Succ Succ /|
790 // | \ V | \/ | | \ V | \/ |
791 // |U \ |U /\ =? |U = |U /\ |
792 // = D = = =?| | D | = =|
793 // | / |/ D | / |/ D
794 // | / | / | = | /
795 // |/ | / |/ | =
796 // Dom Dom Dom Dom
Kyle Buttb15c0662017-01-31 23:48:32 +0000797 // '=' : Branch taken for that CFG edge
798 // The cost for taken branches in the first case is P + U
Kyle Buttee51a202017-04-10 22:28:18 +0000799 // Let F = SuccFreq - Qin
Kyle Buttb15c0662017-01-31 23:48:32 +0000800 // The cost in the second case (assuming independence), given the layout:
Kyle Buttee51a202017-04-10 22:28:18 +0000801 // BB, Succ, (C+Succ), D, Dom or the layout:
802 // BB, Succ, D, Dom, (C+Succ)
803 // is Qout + max(F, Qin) * U + min(F, Qin)
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000804 // compare P + U vs Qout + P * U + Qin.
Kyle Buttb15c0662017-01-31 23:48:32 +0000805 //
806 // The 3rd and 4th cases cover when Dom would be chosen to follow Succ.
807 //
808 // For the 3rd case, the cost is P + 2 * V
Kyle Buttee51a202017-04-10 22:28:18 +0000809 // For the 4th case, the cost is Qout + min(Qin, F) * U + max(Qin, F) * V + V
810 // We choose 4 over 3 when (P + V) > Qout + min(Qin, F) * U + max(Qin, F) * V
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000811 if (UProb > AdjustedSuccSumProb / 2 &&
812 !hasBetterLayoutPredecessor(Succ, PDom, *BlockToChain[PDom], UProb, UProb,
813 Chain, BlockFilter))
Kyle Buttb15c0662017-01-31 23:48:32 +0000814 // Cases 3 & 4
Kyle Buttee51a202017-04-10 22:28:18 +0000815 return greaterWithBias(
816 (P + V), (Qout + std::max(Qin, F) * VProb + std::min(Qin, F) * UProb),
817 EntryFreq);
Kyle Buttb15c0662017-01-31 23:48:32 +0000818 // Cases 1 & 2
Kyle Buttee51a202017-04-10 22:28:18 +0000819 return greaterWithBias((P + U),
820 (Qout + std::min(Qin, F) * AdjustedSuccSumProb +
821 std::max(Qin, F) * UProb),
822 EntryFreq);
Kyle Buttb15c0662017-01-31 23:48:32 +0000823}
824
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000825/// Check for a trellis layout. \p BB is the upper part of a trellis if its
826/// successors form the lower part of a trellis. A successor set S forms the
827/// lower part of a trellis if all of the predecessors of S are either in S or
828/// have all of S as successors. We ignore trellises where BB doesn't have 2
829/// successors because for fewer than 2, it's trivial, and for 3 or greater they
830/// are very uncommon and complex to compute optimally. Allowing edges within S
831/// is not strictly a trellis, but the same algorithm works, so we allow it.
832bool MachineBlockPlacement::isTrellis(
833 const MachineBasicBlock *BB,
834 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
835 const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
836 // Technically BB could form a trellis with branching factor higher than 2.
837 // But that's extremely uncommon.
838 if (BB->succ_size() != 2 || ViableSuccs.size() != 2)
839 return false;
840
841 SmallPtrSet<const MachineBasicBlock *, 2> Successors(BB->succ_begin(),
842 BB->succ_end());
843 // To avoid reviewing the same predecessors twice.
844 SmallPtrSet<const MachineBasicBlock *, 8> SeenPreds;
845
846 for (MachineBasicBlock *Succ : ViableSuccs) {
847 int PredCount = 0;
848 for (auto SuccPred : Succ->predecessors()) {
849 // Allow triangle successors, but don't count them.
Dehao Chenb197d5b2017-03-23 23:28:09 +0000850 if (Successors.count(SuccPred)) {
851 // Make sure that it is actually a triangle.
852 for (MachineBasicBlock *CheckSucc : SuccPred->successors())
853 if (!Successors.count(CheckSucc))
854 return false;
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000855 continue;
Dehao Chenb197d5b2017-03-23 23:28:09 +0000856 }
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000857 const BlockChain *PredChain = BlockToChain[SuccPred];
858 if (SuccPred == BB || (BlockFilter && !BlockFilter->count(SuccPred)) ||
859 PredChain == &Chain || PredChain == BlockToChain[Succ])
860 continue;
861 ++PredCount;
862 // Perform the successor check only once.
863 if (!SeenPreds.insert(SuccPred).second)
864 continue;
865 if (!hasSameSuccessors(*SuccPred, Successors))
866 return false;
867 }
868 // If one of the successors has only BB as a predecessor, it is not a
869 // trellis.
870 if (PredCount < 1)
871 return false;
872 }
873 return true;
874}
875
876/// Pick the highest total weight pair of edges that can both be laid out.
877/// The edges in \p Edges[0] are assumed to have a different destination than
878/// the edges in \p Edges[1]. Simple counting shows that the best pair is either
879/// the individual highest weight edges to the 2 different destinations, or in
880/// case of a conflict, one of them should be replaced with a 2nd best edge.
881std::pair<MachineBlockPlacement::WeightedEdge,
882 MachineBlockPlacement::WeightedEdge>
883MachineBlockPlacement::getBestNonConflictingEdges(
884 const MachineBasicBlock *BB,
885 SmallVector<SmallVector<MachineBlockPlacement::WeightedEdge, 8>, 2>
886 &Edges) {
887 // Sort the edges, and then for each successor, find the best incoming
888 // predecessor. If the best incoming predecessors aren't the same,
889 // then that is clearly the best layout. If there is a conflict, one of the
890 // successors will have to fallthrough from the second best predecessor. We
891 // compare which combination is better overall.
892
893 // Sort for highest frequency.
894 auto Cmp = [](WeightedEdge A, WeightedEdge B) { return A.Weight > B.Weight; };
895
896 std::stable_sort(Edges[0].begin(), Edges[0].end(), Cmp);
897 std::stable_sort(Edges[1].begin(), Edges[1].end(), Cmp);
898 auto BestA = Edges[0].begin();
899 auto BestB = Edges[1].begin();
900 // Arrange for the correct answer to be in BestA and BestB
901 // If the 2 best edges don't conflict, the answer is already there.
902 if (BestA->Src == BestB->Src) {
903 // Compare the total fallthrough of (Best + Second Best) for both pairs
904 auto SecondBestA = std::next(BestA);
905 auto SecondBestB = std::next(BestB);
906 BlockFrequency BestAScore = BestA->Weight + SecondBestB->Weight;
907 BlockFrequency BestBScore = BestB->Weight + SecondBestA->Weight;
908 if (BestAScore < BestBScore)
909 BestA = SecondBestA;
910 else
911 BestB = SecondBestB;
912 }
913 // Arrange for the BB edge to be in BestA if it exists.
914 if (BestB->Src == BB)
915 std::swap(BestA, BestB);
916 return std::make_pair(*BestA, *BestB);
917}
918
919/// Get the best successor from \p BB based on \p BB being part of a trellis.
920/// We only handle trellises with 2 successors, so the algorithm is
921/// straightforward: Find the best pair of edges that don't conflict. We find
922/// the best incoming edge for each successor in the trellis. If those conflict,
923/// we consider which of them should be replaced with the second best.
924/// Upon return the two best edges will be in \p BestEdges. If one of the edges
925/// comes from \p BB, it will be in \p BestEdges[0]
926MachineBlockPlacement::BlockAndTailDupResult
927MachineBlockPlacement::getBestTrellisSuccessor(
928 const MachineBasicBlock *BB,
929 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
930 BranchProbability AdjustedSumProb, const BlockChain &Chain,
931 const BlockFilterSet *BlockFilter) {
932
933 BlockAndTailDupResult Result = {nullptr, false};
934 SmallPtrSet<const MachineBasicBlock *, 4> Successors(BB->succ_begin(),
935 BB->succ_end());
936
937 // We assume size 2 because it's common. For general n, we would have to do
938 // the Hungarian algorithm, but it's not worth the complexity because more
939 // than 2 successors is fairly uncommon, and a trellis even more so.
940 if (Successors.size() != 2 || ViableSuccs.size() != 2)
941 return Result;
942
943 // Collect the edge frequencies of all edges that form the trellis.
944 SmallVector<SmallVector<WeightedEdge, 8>, 2> Edges(2);
945 int SuccIndex = 0;
946 for (auto Succ : ViableSuccs) {
947 for (MachineBasicBlock *SuccPred : Succ->predecessors()) {
948 // Skip any placed predecessors that are not BB
949 if (SuccPred != BB)
950 if ((BlockFilter && !BlockFilter->count(SuccPred)) ||
951 BlockToChain[SuccPred] == &Chain ||
952 BlockToChain[SuccPred] == BlockToChain[Succ])
953 continue;
954 BlockFrequency EdgeFreq = MBFI->getBlockFreq(SuccPred) *
955 MBPI->getEdgeProbability(SuccPred, Succ);
956 Edges[SuccIndex].push_back({EdgeFreq, SuccPred, Succ});
957 }
958 ++SuccIndex;
959 }
960
961 // Pick the best combination of 2 edges from all the edges in the trellis.
962 WeightedEdge BestA, BestB;
963 std::tie(BestA, BestB) = getBestNonConflictingEdges(BB, Edges);
964
965 if (BestA.Src != BB) {
966 // If we have a trellis, and BB doesn't have the best fallthrough edges,
967 // we shouldn't choose any successor. We've already looked and there's a
968 // better fallthrough edge for all the successors.
969 DEBUG(dbgs() << "Trellis, but not one of the chosen edges.\n");
970 return Result;
971 }
972
973 // Did we pick the triangle edge? If tail-duplication is profitable, do
974 // that instead. Otherwise merge the triangle edge now while we know it is
975 // optimal.
976 if (BestA.Dest == BestB.Src) {
977 // The edges are BB->Succ1->Succ2, and we're looking to see if BB->Succ2
978 // would be better.
979 MachineBasicBlock *Succ1 = BestA.Dest;
980 MachineBasicBlock *Succ2 = BestB.Dest;
981 // Check to see if tail-duplication would be profitable.
982 if (TailDupPlacement && shouldTailDuplicate(Succ2) &&
983 canTailDuplicateUnplacedPreds(BB, Succ2, Chain, BlockFilter) &&
984 isProfitableToTailDup(BB, Succ2, MBPI->getEdgeProbability(BB, Succ1),
985 Chain, BlockFilter)) {
986 DEBUG(BranchProbability Succ2Prob = getAdjustedProbability(
987 MBPI->getEdgeProbability(BB, Succ2), AdjustedSumProb);
988 dbgs() << " Selected: " << getBlockName(Succ2)
989 << ", probability: " << Succ2Prob << " (Tail Duplicate)\n");
990 Result.BB = Succ2;
991 Result.ShouldTailDup = true;
992 return Result;
993 }
994 }
995 // We have already computed the optimal edge for the other side of the
996 // trellis.
Kyle Buttebe6cc42017-02-23 21:22:24 +0000997 ComputedEdges[BestB.Src] = { BestB.Dest, false };
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000998
999 auto TrellisSucc = BestA.Dest;
1000 DEBUG(BranchProbability SuccProb = getAdjustedProbability(
1001 MBPI->getEdgeProbability(BB, TrellisSucc), AdjustedSumProb);
1002 dbgs() << " Selected: " << getBlockName(TrellisSucc)
1003 << ", probability: " << SuccProb << " (Trellis)\n");
1004 Result.BB = TrellisSucc;
1005 return Result;
1006}
Kyle Buttb15c0662017-01-31 23:48:32 +00001007
1008/// When the option TailDupPlacement is on, this method checks if the
1009/// fallthrough candidate block \p Succ (of block \p BB) can be tail-duplicated
1010/// into all of its unplaced, unfiltered predecessors, that are not BB.
1011bool MachineBlockPlacement::canTailDuplicateUnplacedPreds(
Kyle Butte9425c4f2017-02-04 02:26:32 +00001012 const MachineBasicBlock *BB, MachineBasicBlock *Succ,
1013 const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
Kyle Buttb15c0662017-01-31 23:48:32 +00001014 if (!shouldTailDuplicate(Succ))
1015 return false;
1016
Kyle Butt7fbec9b2017-02-15 19:49:14 +00001017 // For CFG checking.
1018 SmallPtrSet<const MachineBasicBlock *, 4> Successors(BB->succ_begin(),
1019 BB->succ_end());
Kyle Buttb15c0662017-01-31 23:48:32 +00001020 for (MachineBasicBlock *Pred : Succ->predecessors()) {
1021 // Make sure all unplaced and unfiltered predecessors can be
1022 // tail-duplicated into.
Kyle Butte9425c4f2017-02-04 02:26:32 +00001023 // Skip any blocks that are already placed or not in this loop.
Kyle Buttb15c0662017-01-31 23:48:32 +00001024 if (Pred == BB || (BlockFilter && !BlockFilter->count(Pred))
1025 || BlockToChain[Pred] == &Chain)
1026 continue;
Kyle Butt7fbec9b2017-02-15 19:49:14 +00001027 if (!TailDup.canTailDuplicate(Succ, Pred)) {
1028 if (Successors.size() > 1 && hasSameSuccessors(*Pred, Successors))
1029 // This will result in a trellis after tail duplication, so we don't
1030 // need to copy Succ into this predecessor. In the presence
1031 // of a trellis tail duplication can continue to be profitable.
1032 // For example:
1033 // A A
1034 // |\ |\
1035 // | \ | \
1036 // | C | C+BB
1037 // | / | |
1038 // |/ | |
1039 // BB => BB |
1040 // |\ |\/|
1041 // | \ |/\|
1042 // | D | D
1043 // | / | /
1044 // |/ |/
1045 // Succ Succ
1046 //
1047 // After BB was duplicated into C, the layout looks like the one on the
1048 // right. BB and C now have the same successors. When considering
1049 // whether Succ can be duplicated into all its unplaced predecessors, we
1050 // ignore C.
1051 // We can do this because C already has a profitable fallthrough, namely
1052 // D. TODO(iteratee): ignore sufficiently cold predecessors for
1053 // duplication and for this test.
1054 //
1055 // This allows trellises to be laid out in 2 separate chains
1056 // (A,B,Succ,...) and later (C,D,...) This is a reasonable heuristic
1057 // because it allows the creation of 2 fallthrough paths with links
1058 // between them, and we correctly identify the best layout for these
1059 // CFGs. We want to extend trellises that the user created in addition
1060 // to trellises created by tail-duplication, so we just look for the
1061 // CFG.
1062 continue;
Kyle Buttb15c0662017-01-31 23:48:32 +00001063 return false;
Kyle Butt7fbec9b2017-02-15 19:49:14 +00001064 }
Kyle Buttb15c0662017-01-31 23:48:32 +00001065 }
1066 return true;
1067}
1068
Kyle Butt1fa60302017-03-03 01:00:22 +00001069/// Find chains of triangles where we believe it would be profitable to
1070/// tail-duplicate them all, but a local analysis would not find them.
1071/// There are 3 ways this can be profitable:
1072/// 1) The post-dominators marked 50% are actually taken 55% (This shrinks with
1073/// longer chains)
1074/// 2) The chains are statically correlated. Branch probabilities have a very
1075/// U-shaped distribution.
1076/// [http://nrs.harvard.edu/urn-3:HUL.InstRepos:24015805]
1077/// If the branches in a chain are likely to be from the same side of the
1078/// distribution as their predecessor, but are independent at runtime, this
1079/// transformation is profitable. (Because the cost of being wrong is a small
1080/// fixed cost, unlike the standard triangle layout where the cost of being
1081/// wrong scales with the # of triangles.)
1082/// 3) The chains are dynamically correlated. If the probability that a previous
1083/// branch was taken positively influences whether the next branch will be
1084/// taken
1085/// We believe that 2 and 3 are common enough to justify the small margin in 1.
1086void MachineBlockPlacement::precomputeTriangleChains() {
1087 struct TriangleChain {
1088 unsigned Count;
1089 std::forward_list<MachineBasicBlock*> Edges;
1090 TriangleChain(MachineBasicBlock* src, MachineBasicBlock *dst) {
1091 Edges.push_front(src);
1092 Edges.push_front(dst);
1093 Count = 1;
1094 }
1095
1096 void append(MachineBasicBlock *dst) {
1097 assert(!Edges.empty() && Edges.front()->isSuccessor(dst) &&
1098 "Attempting to append a block that is not a successor.");
1099 Edges.push_front(dst);
1100 ++Count;
1101 }
1102
1103 MachineBasicBlock *getKey() {
1104 return Edges.front();
1105 }
1106 };
1107
1108 if (TriangleChainCount == 0)
1109 return;
1110
1111 DEBUG(dbgs() << "Pre-computing triangle chains.\n");
1112 // Map from last block to the chain that contains it. This allows us to extend
1113 // chains as we find new triangles.
1114 DenseMap<const MachineBasicBlock *, TriangleChain> TriangleChainMap;
1115 for (MachineBasicBlock &BB : *F) {
1116 // If BB doesn't have 2 successors, it doesn't start a triangle.
1117 if (BB.succ_size() != 2)
1118 continue;
1119 MachineBasicBlock *PDom = nullptr;
1120 for (MachineBasicBlock *Succ : BB.successors()) {
1121 if (!MPDT->dominates(Succ, &BB))
1122 continue;
1123 PDom = Succ;
1124 break;
1125 }
1126 // If BB doesn't have a post-dominating successor, it doesn't form a
1127 // triangle.
1128 if (PDom == nullptr)
1129 continue;
1130 // If PDom has a hint that it is low probability, skip this triangle.
1131 if (MBPI->getEdgeProbability(&BB, PDom) < BranchProbability(50, 100))
1132 continue;
1133 // If PDom isn't eligible for duplication, this isn't the kind of triangle
1134 // we're looking for.
1135 if (!shouldTailDuplicate(PDom))
1136 continue;
1137 bool CanTailDuplicate = true;
1138 // If PDom can't tail-duplicate into it's non-BB predecessors, then this
1139 // isn't the kind of triangle we're looking for.
1140 for (MachineBasicBlock* Pred : PDom->predecessors()) {
1141 if (Pred == &BB)
1142 continue;
1143 if (!TailDup.canTailDuplicate(PDom, Pred)) {
1144 CanTailDuplicate = false;
1145 break;
1146 }
1147 }
1148 // If we can't tail-duplicate PDom to its predecessors, then skip this
1149 // triangle.
1150 if (!CanTailDuplicate)
1151 continue;
1152
1153 // Now we have an interesting triangle. Insert it if it's not part of an
1154 // existing chain
1155 // Note: This cannot be replaced with a call insert() or emplace() because
1156 // the find key is BB, but the insert/emplace key is PDom.
1157 auto Found = TriangleChainMap.find(&BB);
1158 // If it is, remove the chain from the map, grow it, and put it back in the
1159 // map with the end as the new key.
1160 if (Found != TriangleChainMap.end()) {
1161 TriangleChain Chain = std::move(Found->second);
1162 TriangleChainMap.erase(Found);
1163 Chain.append(PDom);
1164 TriangleChainMap.insert(std::make_pair(Chain.getKey(), std::move(Chain)));
1165 } else {
1166 auto InsertResult = TriangleChainMap.try_emplace(PDom, &BB, PDom);
1167 assert (InsertResult.second && "Block seen twice.");
1168 (void) InsertResult;
1169 }
1170 }
1171
1172 for (auto &ChainPair : TriangleChainMap) {
1173 TriangleChain &Chain = ChainPair.second;
1174 // Benchmarking has shown that due to branch correlation duplicating 2 or
1175 // more triangles is profitable, despite the calculations assuming
1176 // independence.
1177 if (Chain.Count < TriangleChainCount)
1178 continue;
1179 MachineBasicBlock *dst = Chain.Edges.front();
1180 Chain.Edges.pop_front();
1181 for (MachineBasicBlock *src : Chain.Edges) {
1182 DEBUG(dbgs() << "Marking edge: " << getBlockName(src) << "->" <<
1183 getBlockName(dst) << " as pre-computed based on triangles.\n");
1184 ComputedEdges[src] = { dst, true };
1185 dst = src;
1186 }
1187 }
1188}
1189
Dehao Chen9f2bdfb2016-06-14 22:27:17 +00001190// When profile is not present, return the StaticLikelyProb.
1191// When profile is available, we need to handle the triangle-shape CFG.
1192static BranchProbability getLayoutSuccessorProbThreshold(
Kyle Butte9425c4f2017-02-04 02:26:32 +00001193 const MachineBasicBlock *BB) {
Dehao Chen9f2bdfb2016-06-14 22:27:17 +00001194 if (!BB->getParent()->getFunction()->getEntryCount())
1195 return BranchProbability(StaticLikelyProb, 100);
1196 if (BB->succ_size() == 2) {
1197 const MachineBasicBlock *Succ1 = *BB->succ_begin();
1198 const MachineBasicBlock *Succ2 = *(BB->succ_begin() + 1);
Xinliang David Lie34ed832016-06-15 03:03:30 +00001199 if (Succ1->isSuccessor(Succ2) || Succ2->isSuccessor(Succ1)) {
1200 /* See case 1 below for the cost analysis. For BB->Succ to
1201 * be taken with smaller cost, the following needs to hold:
Kyle Buttb15c0662017-01-31 23:48:32 +00001202 * Prob(BB->Succ) > 2 * Prob(BB->Pred)
1203 * So the threshold T in the calculation below
1204 * (1-T) * Prob(BB->Succ) > T * Prob(BB->Pred)
1205 * So T / (1 - T) = 2, Yielding T = 2/3
1206 * Also adding user specified branch bias, we have
Xinliang David Lie34ed832016-06-15 03:03:30 +00001207 * T = (2/3)*(ProfileLikelyProb/50)
1208 * = (2*ProfileLikelyProb)/150)
1209 */
1210 return BranchProbability(2 * ProfileLikelyProb, 150);
1211 }
Dehao Chen9f2bdfb2016-06-14 22:27:17 +00001212 }
1213 return BranchProbability(ProfileLikelyProb, 100);
Xinliang David Licbf12142016-06-13 20:24:19 +00001214}
1215
1216/// Checks to see if the layout candidate block \p Succ has a better layout
1217/// predecessor than \c BB. If yes, returns true.
Kyle Buttb15c0662017-01-31 23:48:32 +00001218/// \p SuccProb: The probability adjusted for only remaining blocks.
1219/// Only used for logging
1220/// \p RealSuccProb: The un-adjusted probability.
1221/// \p Chain: The chain that BB belongs to and Succ is being considered for.
1222/// \p BlockFilter: if non-null, the set of blocks that make up the loop being
1223/// considered
Xinliang David Licbf12142016-06-13 20:24:19 +00001224bool MachineBlockPlacement::hasBetterLayoutPredecessor(
Kyle Butte9425c4f2017-02-04 02:26:32 +00001225 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
1226 const BlockChain &SuccChain, BranchProbability SuccProb,
1227 BranchProbability RealSuccProb, const BlockChain &Chain,
1228 const BlockFilterSet *BlockFilter) {
Xinliang David Licbf12142016-06-13 20:24:19 +00001229
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001230 // There isn't a better layout when there are no unscheduled predecessors.
Xinliang David Licbf12142016-06-13 20:24:19 +00001231 if (SuccChain.UnscheduledPredecessors == 0)
1232 return false;
1233
1234 // There are two basic scenarios here:
1235 // -------------------------------------
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001236 // Case 1: triangular shape CFG (if-then):
Xinliang David Licbf12142016-06-13 20:24:19 +00001237 // BB
1238 // | \
1239 // | \
1240 // | Pred
1241 // | /
1242 // Succ
1243 // In this case, we are evaluating whether to select edge -> Succ, e.g.
1244 // set Succ as the layout successor of BB. Picking Succ as BB's
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001245 // successor breaks the CFG constraints (FIXME: define these constraints).
1246 // With this layout, Pred BB
Xinliang David Licbf12142016-06-13 20:24:19 +00001247 // is forced to be outlined, so the overall cost will be cost of the
1248 // branch taken from BB to Pred, plus the cost of back taken branch
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001249 // from Pred to Succ, as well as the additional cost associated
Xinliang David Licbf12142016-06-13 20:24:19 +00001250 // with the needed unconditional jump instruction from Pred To Succ.
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001251
Xinliang David Licbf12142016-06-13 20:24:19 +00001252 // The cost of the topological order layout is the taken branch cost
1253 // from BB to Succ, so to make BB->Succ a viable candidate, the following
1254 // must hold:
1255 // 2 * freq(BB->Pred) * taken_branch_cost + unconditional_jump_cost
1256 // < freq(BB->Succ) * taken_branch_cost.
1257 // Ignoring unconditional jump cost, we get
1258 // freq(BB->Succ) > 2 * freq(BB->Pred), i.e.,
1259 // prob(BB->Succ) > 2 * prob(BB->Pred)
1260 //
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001261 // When real profile data is available, we can precisely compute the
1262 // probability threshold that is needed for edge BB->Succ to be considered.
1263 // Without profile data, the heuristic requires the branch bias to be
Xinliang David Licbf12142016-06-13 20:24:19 +00001264 // a lot larger to make sure the signal is very strong (e.g. 80% default).
1265 // -----------------------------------------------------------------
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001266 // Case 2: diamond like CFG (if-then-else):
Xinliang David Licbf12142016-06-13 20:24:19 +00001267 // S
1268 // / \
1269 // | \
1270 // BB Pred
1271 // \ /
1272 // Succ
1273 // ..
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001274 //
1275 // The current block is BB and edge BB->Succ is now being evaluated.
1276 // Note that edge S->BB was previously already selected because
1277 // prob(S->BB) > prob(S->Pred).
1278 // At this point, 2 blocks can be placed after BB: Pred or Succ. If we
1279 // choose Pred, we will have a topological ordering as shown on the left
1280 // in the picture below. If we choose Succ, we have the solution as shown
1281 // on the right:
1282 //
1283 // topo-order:
1284 //
1285 // S----- ---S
1286 // | | | |
1287 // ---BB | | BB
1288 // | | | |
1289 // | pred-- | Succ--
1290 // | | | |
1291 // ---succ ---pred--
1292 //
1293 // cost = freq(S->Pred) + freq(BB->Succ) cost = 2 * freq (S->Pred)
1294 // = freq(S->Pred) + freq(S->BB)
1295 //
1296 // If we have profile data (i.e, branch probabilities can be trusted), the
1297 // cost (number of taken branches) with layout S->BB->Succ->Pred is 2 *
1298 // freq(S->Pred) while the cost of topo order is freq(S->Pred) + freq(S->BB).
1299 // We know Prob(S->BB) > Prob(S->Pred), so freq(S->BB) > freq(S->Pred), which
1300 // means the cost of topological order is greater.
Xinliang David Licbf12142016-06-13 20:24:19 +00001301 // When profile data is not available, however, we need to be more
1302 // conservative. If the branch prediction is wrong, breaking the topo-order
1303 // will actually yield a layout with large cost. For this reason, we need
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001304 // strong biased branch at block S with Prob(S->BB) in order to select
1305 // BB->Succ. This is equivalent to looking the CFG backward with backward
Xinliang David Licbf12142016-06-13 20:24:19 +00001306 // edge: Prob(Succ->BB) needs to >= HotProb in order to be selected (without
1307 // profile data).
Kyle Butt02d8d052016-07-29 18:09:28 +00001308 // --------------------------------------------------------------------------
1309 // Case 3: forked diamond
1310 // S
1311 // / \
1312 // / \
1313 // BB Pred
1314 // | \ / |
1315 // | \ / |
1316 // | X |
1317 // | / \ |
1318 // | / \ |
1319 // S1 S2
1320 //
1321 // The current block is BB and edge BB->S1 is now being evaluated.
1322 // As above S->BB was already selected because
1323 // prob(S->BB) > prob(S->Pred). Assume that prob(BB->S1) >= prob(BB->S2).
1324 //
1325 // topo-order:
1326 //
1327 // S-------| ---S
1328 // | | | |
1329 // ---BB | | BB
1330 // | | | |
1331 // | Pred----| | S1----
1332 // | | | |
1333 // --(S1 or S2) ---Pred--
Kyle Butt7fbec9b2017-02-15 19:49:14 +00001334 // |
1335 // S2
Kyle Butt02d8d052016-07-29 18:09:28 +00001336 //
1337 // topo-cost = freq(S->Pred) + freq(BB->S1) + freq(BB->S2)
1338 // + min(freq(Pred->S1), freq(Pred->S2))
1339 // Non-topo-order cost:
Kyle Butt02d8d052016-07-29 18:09:28 +00001340 // non-topo-cost = 2 * freq(S->Pred) + freq(BB->S2).
1341 // To be conservative, we can assume that min(freq(Pred->S1), freq(Pred->S2))
1342 // is 0. Then the non topo layout is better when
1343 // freq(S->Pred) < freq(BB->S1).
1344 // This is exactly what is checked below.
1345 // Note there are other shapes that apply (Pred may not be a single block,
1346 // but they all fit this general pattern.)
Dehao Chen9f2bdfb2016-06-14 22:27:17 +00001347 BranchProbability HotProb = getLayoutSuccessorProbThreshold(BB);
Xinliang David Licbf12142016-06-13 20:24:19 +00001348
Xinliang David Licbf12142016-06-13 20:24:19 +00001349 // Make sure that a hot successor doesn't have a globally more
1350 // important predecessor.
1351 BlockFrequency CandidateEdgeFreq = MBFI->getBlockFreq(BB) * RealSuccProb;
1352 bool BadCFGConflict = false;
1353
1354 for (MachineBasicBlock *Pred : Succ->predecessors()) {
1355 if (Pred == Succ || BlockToChain[Pred] == &SuccChain ||
1356 (BlockFilter && !BlockFilter->count(Pred)) ||
Kyle Buttb15c0662017-01-31 23:48:32 +00001357 BlockToChain[Pred] == &Chain ||
1358 // This check is redundant except for look ahead. This function is
1359 // called for lookahead by isProfitableToTailDup when BB hasn't been
1360 // placed yet.
1361 (Pred == BB))
Xinliang David Licbf12142016-06-13 20:24:19 +00001362 continue;
Kyle Butt02d8d052016-07-29 18:09:28 +00001363 // Do backward checking.
1364 // For all cases above, we need a backward checking to filter out edges that
Kyle Buttb15c0662017-01-31 23:48:32 +00001365 // are not 'strongly' biased.
Xinliang David Licbf12142016-06-13 20:24:19 +00001366 // BB Pred
1367 // \ /
1368 // Succ
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001369 // We select edge BB->Succ if
Xinliang David Licbf12142016-06-13 20:24:19 +00001370 // freq(BB->Succ) > freq(Succ) * HotProb
1371 // i.e. freq(BB->Succ) > freq(BB->Succ) * HotProb + freq(Pred->Succ) *
1372 // HotProb
1373 // i.e. freq((BB->Succ) * (1 - HotProb) > freq(Pred->Succ) * HotProb
Kyle Butt02d8d052016-07-29 18:09:28 +00001374 // Case 1 is covered too, because the first equation reduces to:
1375 // prob(BB->Succ) > HotProb. (freq(Succ) = freq(BB) for a triangle)
Xinliang David Licbf12142016-06-13 20:24:19 +00001376 BlockFrequency PredEdgeFreq =
1377 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
1378 if (PredEdgeFreq * HotProb >= CandidateEdgeFreq * HotProb.getCompl()) {
1379 BadCFGConflict = true;
1380 break;
1381 }
1382 }
1383
1384 if (BadCFGConflict) {
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001385 DEBUG(dbgs() << " Not a candidate: " << getBlockName(Succ) << " -> " << SuccProb
Xinliang David Licbf12142016-06-13 20:24:19 +00001386 << " (prob) (non-cold CFG conflict)\n");
1387 return true;
1388 }
1389
1390 return false;
1391}
1392
Xinliang David Li594ffa32016-06-11 18:35:40 +00001393/// \brief Select the best successor for a block.
1394///
1395/// This looks across all successors of a particular block and attempts to
1396/// select the "best" one to be the layout successor. It only considers direct
1397/// successors which also pass the block filter. It will attempt to avoid
1398/// breaking CFG structure, but cave and break such structures in the case of
1399/// very hot successor edges.
1400///
Kyle Buttb15c0662017-01-31 23:48:32 +00001401/// \returns The best successor block found, or null if none are viable, along
1402/// with a boolean indicating if tail duplication is necessary.
1403MachineBlockPlacement::BlockAndTailDupResult
Kyle Butte9425c4f2017-02-04 02:26:32 +00001404MachineBlockPlacement::selectBestSuccessor(
1405 const MachineBasicBlock *BB, const BlockChain &Chain,
1406 const BlockFilterSet *BlockFilter) {
Xinliang David Li594ffa32016-06-11 18:35:40 +00001407 const BranchProbability HotProb(StaticLikelyProb, 100);
1408
Kyle Buttb15c0662017-01-31 23:48:32 +00001409 BlockAndTailDupResult BestSucc = { nullptr, false };
Xinliang David Li594ffa32016-06-11 18:35:40 +00001410 auto BestProb = BranchProbability::getZero();
1411
1412 SmallVector<MachineBasicBlock *, 4> Successors;
1413 auto AdjustedSumProb =
1414 collectViableSuccessors(BB, Chain, BlockFilter, Successors);
1415
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001416 DEBUG(dbgs() << "Selecting best successor for: " << getBlockName(BB) << "\n");
Kyle Buttb15c0662017-01-31 23:48:32 +00001417
Kyle Buttebe6cc42017-02-23 21:22:24 +00001418 // if we already precomputed the best successor for BB, return that if still
1419 // applicable.
1420 auto FoundEdge = ComputedEdges.find(BB);
1421 if (FoundEdge != ComputedEdges.end()) {
1422 MachineBasicBlock *Succ = FoundEdge->second.BB;
1423 ComputedEdges.erase(FoundEdge);
Kyle Butt7fbec9b2017-02-15 19:49:14 +00001424 BlockChain *SuccChain = BlockToChain[Succ];
1425 if (BB->isSuccessor(Succ) && (!BlockFilter || BlockFilter->count(Succ)) &&
Kyle Buttebe6cc42017-02-23 21:22:24 +00001426 SuccChain != &Chain && Succ == *SuccChain->begin())
1427 return FoundEdge->second;
Kyle Butt7fbec9b2017-02-15 19:49:14 +00001428 }
1429
1430 // if BB is part of a trellis, Use the trellis to determine the optimal
1431 // fallthrough edges
1432 if (isTrellis(BB, Successors, Chain, BlockFilter))
1433 return getBestTrellisSuccessor(BB, Successors, AdjustedSumProb, Chain,
1434 BlockFilter);
1435
Kyle Buttb15c0662017-01-31 23:48:32 +00001436 // For blocks with CFG violations, we may be able to lay them out anyway with
1437 // tail-duplication. We keep this vector so we can perform the probability
1438 // calculations the minimum number of times.
1439 SmallVector<std::tuple<BranchProbability, MachineBasicBlock *>, 4>
1440 DupCandidates;
Cong Hou41cf1a52015-11-18 00:52:52 +00001441 for (MachineBasicBlock *Succ : Successors) {
Xinliang David Li594ffa32016-06-11 18:35:40 +00001442 auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ);
1443 BranchProbability SuccProb =
1444 getAdjustedProbability(RealSuccProb, AdjustedSumProb);
Chandler Carruthb3361722011-11-13 11:34:53 +00001445
Cong Hou41cf1a52015-11-18 00:52:52 +00001446 BlockChain &SuccChain = *BlockToChain[Succ];
Xinliang David Licbf12142016-06-13 20:24:19 +00001447 // Skip the edge \c BB->Succ if block \c Succ has a better layout
1448 // predecessor that yields lower global cost.
1449 if (hasBetterLayoutPredecessor(BB, Succ, SuccChain, SuccProb, RealSuccProb,
Kyle Buttb15c0662017-01-31 23:48:32 +00001450 Chain, BlockFilter)) {
1451 // If tail duplication would make Succ profitable, place it.
1452 if (TailDupPlacement && shouldTailDuplicate(Succ))
1453 DupCandidates.push_back(std::make_tuple(SuccProb, Succ));
Xinliang David Licbf12142016-06-13 20:24:19 +00001454 continue;
Kyle Buttb15c0662017-01-31 23:48:32 +00001455 }
Chandler Carruth18dfac32011-11-20 11:22:06 +00001456
Xinliang David Licbf12142016-06-13 20:24:19 +00001457 DEBUG(
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001458 dbgs() << " Candidate: " << getBlockName(Succ) << ", probability: "
1459 << SuccProb
Xinliang David Licbf12142016-06-13 20:24:19 +00001460 << (SuccChain.UnscheduledPredecessors != 0 ? " (CFG break)" : "")
1461 << "\n");
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001462
Kyle Buttb15c0662017-01-31 23:48:32 +00001463 if (BestSucc.BB && BestProb >= SuccProb) {
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001464 DEBUG(dbgs() << " Not the best candidate, continuing\n");
Chandler Carruthb3361722011-11-13 11:34:53 +00001465 continue;
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001466 }
1467
1468 DEBUG(dbgs() << " Setting it as best candidate\n");
Kyle Buttb15c0662017-01-31 23:48:32 +00001469 BestSucc.BB = Succ;
Cong Houd97c1002015-12-01 05:29:22 +00001470 BestProb = SuccProb;
Chandler Carruthb3361722011-11-13 11:34:53 +00001471 }
Kyle Buttb15c0662017-01-31 23:48:32 +00001472 // Handle the tail duplication candidates in order of decreasing probability.
1473 // Stop at the first one that is profitable. Also stop if they are less
1474 // profitable than BestSucc. Position is important because we preserve it and
1475 // prefer first best match. Here we aren't comparing in order, so we capture
1476 // the position instead.
1477 if (DupCandidates.size() != 0) {
1478 auto cmp =
1479 [](const std::tuple<BranchProbability, MachineBasicBlock *> &a,
1480 const std::tuple<BranchProbability, MachineBasicBlock *> &b) {
1481 return std::get<0>(a) > std::get<0>(b);
1482 };
1483 std::stable_sort(DupCandidates.begin(), DupCandidates.end(), cmp);
1484 }
1485 for(auto &Tup : DupCandidates) {
1486 BranchProbability DupProb;
1487 MachineBasicBlock *Succ;
1488 std::tie(DupProb, Succ) = Tup;
1489 if (DupProb < BestProb)
1490 break;
1491 if (canTailDuplicateUnplacedPreds(BB, Succ, Chain, BlockFilter)
1492 // If tail duplication gives us fallthrough when we otherwise wouldn't
1493 // have it, that is a strict gain.
1494 && (BestSucc.BB == nullptr
1495 || isProfitableToTailDup(BB, Succ, BestProb, Chain,
1496 BlockFilter))) {
1497 DEBUG(
1498 dbgs() << " Candidate: " << getBlockName(Succ) << ", probability: "
1499 << DupProb
1500 << " (Tail Duplicate)\n");
1501 BestSucc.BB = Succ;
1502 BestSucc.ShouldTailDup = true;
1503 break;
1504 }
1505 }
1506
1507 if (BestSucc.BB)
1508 DEBUG(dbgs() << " Selected: " << getBlockName(BestSucc.BB) << "\n");
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001509
Chandler Carruthb3361722011-11-13 11:34:53 +00001510 return BestSucc;
1511}
1512
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001513/// \brief Select the best block from a worklist.
1514///
1515/// This looks through the provided worklist as a list of candidate basic
1516/// blocks and select the most profitable one to place. The definition of
1517/// profitable only really makes sense in the context of a loop. This returns
1518/// the most frequently visited block in the worklist, which in the case of
1519/// a loop, is the one most desirable to be physically close to the rest of the
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001520/// loop body in order to improve i-cache behavior.
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001521///
1522/// \returns The best block found, or null if none are viable.
1523MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
Kyle Butte9425c4f2017-02-04 02:26:32 +00001524 const BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList) {
Chandler Carruth0af6a0b2011-11-14 09:46:33 +00001525 // Once we need to walk the worklist looking for a candidate, cleanup the
1526 // worklist of already placed entries.
1527 // FIXME: If this shows up on profiles, it could be folded (at the cost of
1528 // some code complexity) into the loop below.
David Majnemerc7004902016-08-12 04:32:37 +00001529 WorkList.erase(remove_if(WorkList,
1530 [&](MachineBasicBlock *BB) {
1531 return BlockToChain.lookup(BB) == &Chain;
1532 }),
Chandler Carruth0af6a0b2011-11-14 09:46:33 +00001533 WorkList.end());
1534
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001535 if (WorkList.empty())
1536 return nullptr;
1537
1538 bool IsEHPad = WorkList[0]->isEHPad();
1539
Craig Topperc0196b12014-04-14 00:51:57 +00001540 MachineBasicBlock *BestBlock = nullptr;
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001541 BlockFrequency BestFreq;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001542 for (MachineBasicBlock *MBB : WorkList) {
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001543 assert(MBB->isEHPad() == IsEHPad);
1544
Chandler Carruth7a715da2015-03-05 03:19:05 +00001545 BlockChain &SuccChain = *BlockToChain[MBB];
Philip Reames02e11322016-03-02 22:40:51 +00001546 if (&SuccChain == &Chain)
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001547 continue;
Junmo Park4ba6cf62016-03-11 05:07:07 +00001548
Philip Reamesae27b232016-03-03 00:58:43 +00001549 assert(SuccChain.UnscheduledPredecessors == 0 && "Found CFG-violating block");
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001550
Chandler Carruth7a715da2015-03-05 03:19:05 +00001551 BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
1552 DEBUG(dbgs() << " " << getBlockName(MBB) << " -> ";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001553 MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001554
1555 // For ehpad, we layout the least probable first as to avoid jumping back
1556 // from least probable landingpads to more probable ones.
1557 //
1558 // FIXME: Using probability is probably (!) not the best way to achieve
1559 // this. We should probably have a more principled approach to layout
1560 // cleanup code.
1561 //
1562 // The goal is to get:
1563 //
1564 // +--------------------------+
1565 // | V
1566 // InnerLp -> InnerCleanup OuterLp -> OuterCleanup -> Resume
1567 //
1568 // Rather than:
1569 //
1570 // +-------------------------------------+
1571 // V |
1572 // OuterLp -> OuterCleanup -> Resume InnerLp -> InnerCleanup
1573 if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq)))
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001574 continue;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001575
Chandler Carruth7a715da2015-03-05 03:19:05 +00001576 BestBlock = MBB;
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001577 BestFreq = CandidateFreq;
1578 }
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001579
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001580 return BestBlock;
1581}
1582
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001583/// \brief Retrieve the first unplaced basic block.
1584///
1585/// This routine is called when we are unable to use the CFG to walk through
1586/// all of the basic blocks and form a chain due to unnatural loops in the CFG.
Chandler Carruth9b548a7f2011-11-15 06:26:43 +00001587/// We walk through the function's blocks in order, starting from the
1588/// LastUnplacedBlockIt. We update this iterator on each call to avoid
1589/// re-scanning the entire sequence on repeated calls to this routine.
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001590MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
Xinliang David Li52530a72016-06-13 22:23:44 +00001591 const BlockChain &PlacedChain,
Chandler Carruth9b548a7f2011-11-15 06:26:43 +00001592 MachineFunction::iterator &PrevUnplacedBlockIt,
Jakub Staszak90616162011-12-21 23:02:08 +00001593 const BlockFilterSet *BlockFilter) {
Xinliang David Li52530a72016-06-13 22:23:44 +00001594 for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F->end(); I != E;
Chandler Carruth9b548a7f2011-11-15 06:26:43 +00001595 ++I) {
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001596 if (BlockFilter && !BlockFilter->count(&*I))
Chandler Carruth9b548a7f2011-11-15 06:26:43 +00001597 continue;
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001598 if (BlockToChain[&*I] != &PlacedChain) {
Chandler Carruth9b548a7f2011-11-15 06:26:43 +00001599 PrevUnplacedBlockIt = I;
Chandler Carruth4a87aa02011-11-23 03:03:21 +00001600 // Now select the head of the chain to which the unplaced block belongs
1601 // as the block to place. This will force the entire chain to be placed,
1602 // and satisfies the requirements of merging chains.
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001603 return *BlockToChain[&*I]->begin();
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001604 }
1605 }
Craig Topperc0196b12014-04-14 00:51:57 +00001606 return nullptr;
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001607}
1608
Amaury Secheteae09c22016-03-14 21:24:11 +00001609void MachineBlockPlacement::fillWorkLists(
Kyle Butte9425c4f2017-02-04 02:26:32 +00001610 const MachineBasicBlock *MBB,
Amaury Secheteae09c22016-03-14 21:24:11 +00001611 SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
Amaury Secheteae09c22016-03-14 21:24:11 +00001612 const BlockFilterSet *BlockFilter = nullptr) {
1613 BlockChain &Chain = *BlockToChain[MBB];
1614 if (!UpdatedPreds.insert(&Chain).second)
1615 return;
1616
1617 assert(Chain.UnscheduledPredecessors == 0);
1618 for (MachineBasicBlock *ChainBB : Chain) {
1619 assert(BlockToChain[ChainBB] == &Chain);
1620 for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
1621 if (BlockFilter && !BlockFilter->count(Pred))
1622 continue;
1623 if (BlockToChain[Pred] == &Chain)
1624 continue;
1625 ++Chain.UnscheduledPredecessors;
1626 }
1627 }
1628
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001629 if (Chain.UnscheduledPredecessors != 0)
1630 return;
1631
Kyle Butte9425c4f2017-02-04 02:26:32 +00001632 MachineBasicBlock *BB = *Chain.begin();
1633 if (BB->isEHPad())
1634 EHPadWorkList.push_back(BB);
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001635 else
Kyle Butte9425c4f2017-02-04 02:26:32 +00001636 BlockWorkList.push_back(BB);
Amaury Secheteae09c22016-03-14 21:24:11 +00001637}
1638
Chandler Carruth8d150782011-11-13 11:20:44 +00001639void MachineBlockPlacement::buildChain(
Kyle Butte9425c4f2017-02-04 02:26:32 +00001640 const MachineBasicBlock *HeadBB, BlockChain &Chain,
Kyle Butt0846e562016-10-11 20:36:43 +00001641 BlockFilterSet *BlockFilter) {
Kyle Butte9425c4f2017-02-04 02:26:32 +00001642 assert(HeadBB && "BB must not be null.\n");
1643 assert(BlockToChain[HeadBB] == &Chain && "BlockToChainMap mis-match.\n");
Xinliang David Li52530a72016-06-13 22:23:44 +00001644 MachineFunction::iterator PrevUnplacedBlockIt = F->begin();
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001645
Kyle Butte9425c4f2017-02-04 02:26:32 +00001646 const MachineBasicBlock *LoopHeaderBB = HeadBB;
Xinliang David Li93926ac2016-07-01 05:46:48 +00001647 markChainSuccessors(Chain, LoopHeaderBB, BlockFilter);
Kyle Butte9425c4f2017-02-04 02:26:32 +00001648 MachineBasicBlock *BB = *std::prev(Chain.end());
Chandler Carruth8d150782011-11-13 11:20:44 +00001649 for (;;) {
Kyle Butt82c22902016-06-28 22:50:54 +00001650 assert(BB && "null block found at end of chain in loop.");
1651 assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match in loop.");
1652 assert(*std::prev(Chain.end()) == BB && "BB Not found at end of chain.");
1653
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001654
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001655 // Look for the best viable successor if there is one to place immediately
1656 // after this block.
Kyle Buttb15c0662017-01-31 23:48:32 +00001657 auto Result = selectBestSuccessor(BB, Chain, BlockFilter);
1658 MachineBasicBlock* BestSucc = Result.BB;
1659 bool ShouldTailDup = Result.ShouldTailDup;
1660 if (TailDupPlacement)
1661 ShouldTailDup |= (BestSucc && shouldTailDuplicate(BestSucc));
Chandler Carruth8d150782011-11-13 11:20:44 +00001662
1663 // If an immediate successor isn't available, look for the best viable
1664 // block among those we've identified as not violating the loop's CFG at
1665 // this point. This won't be a fallthrough, but it will increase locality.
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001666 if (!BestSucc)
Amaury Sechet9ee4ddd2016-04-07 06:34:47 +00001667 BestSucc = selectBestCandidateBlock(Chain, BlockWorkList);
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001668 if (!BestSucc)
1669 BestSucc = selectBestCandidateBlock(Chain, EHPadWorkList);
Chandler Carruth8d150782011-11-13 11:20:44 +00001670
Chandler Carruth8d150782011-11-13 11:20:44 +00001671 if (!BestSucc) {
Xinliang David Li52530a72016-06-13 22:23:44 +00001672 BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockIt, BlockFilter);
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001673 if (!BestSucc)
1674 break;
1675
1676 DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
1677 "layout successor until the CFG reduces\n");
Chandler Carruth8d150782011-11-13 11:20:44 +00001678 }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001679
Kyle Butt0846e562016-10-11 20:36:43 +00001680 // Placement may have changed tail duplication opportunities.
1681 // Check for that now.
Kyle Buttb15c0662017-01-31 23:48:32 +00001682 if (TailDupPlacement && BestSucc && ShouldTailDup) {
Kyle Butt0846e562016-10-11 20:36:43 +00001683 // If the chosen successor was duplicated into all its predecessors,
1684 // don't bother laying it out, just go round the loop again with BB as
1685 // the chain end.
1686 if (repeatedlyTailDuplicateBlock(BestSucc, BB, LoopHeaderBB, Chain,
1687 BlockFilter, PrevUnplacedBlockIt))
1688 continue;
1689 }
1690
Chandler Carruth8d150782011-11-13 11:20:44 +00001691 // Place this block, updating the datastructures to reflect its placement.
Jakub Staszak90616162011-12-21 23:02:08 +00001692 BlockChain &SuccChain = *BlockToChain[BestSucc];
Philip Reamesae27b232016-03-03 00:58:43 +00001693 // Zero out UnscheduledPredecessors for the successor we're about to merge in case
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001694 // we selected a successor that didn't fit naturally into the CFG.
Philip Reamesae27b232016-03-03 00:58:43 +00001695 SuccChain.UnscheduledPredecessors = 0;
Philip Reamesb9688f42016-03-02 21:45:13 +00001696 DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to "
1697 << getBlockName(BestSucc) << "\n");
Xinliang David Li93926ac2016-07-01 05:46:48 +00001698 markChainSuccessors(SuccChain, LoopHeaderBB, BlockFilter);
Chandler Carruth8d150782011-11-13 11:20:44 +00001699 Chain.merge(BestSucc, &SuccChain);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001700 BB = *std::prev(Chain.end());
Jakub Staszak190c7122011-12-07 19:46:10 +00001701 }
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001702
1703 DEBUG(dbgs() << "Finished forming chain for header block "
Philip Reamesb9688f42016-03-02 21:45:13 +00001704 << getBlockName(*Chain.begin()) << "\n");
Chandler Carruth10281422011-10-21 06:46:38 +00001705}
1706
Chandler Carruth03adbd42011-11-27 13:34:33 +00001707/// \brief Find the best loop top block for layout.
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001708///
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001709/// Look for a block which is strictly better than the loop header for laying
1710/// out at the top of the loop. This looks for one and only one pattern:
1711/// a latch block with no conditional exit. This block will cause a conditional
1712/// jump around it or will be the bottom of the loop if we lay it out in place,
1713/// but if it it doesn't end up at the bottom of the loop for any reason,
1714/// rotation alone won't fix it. Because such a block will always result in an
1715/// unconditional jump (for the backedge) rotating it in front of the loop
1716/// header is always profitable.
1717MachineBasicBlock *
Kyle Butte9425c4f2017-02-04 02:26:32 +00001718MachineBlockPlacement::findBestLoopTop(const MachineLoop &L,
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001719 const BlockFilterSet &LoopBlockSet) {
Sjoerd Meijer15c81b02016-08-16 19:50:33 +00001720 // Placing the latch block before the header may introduce an extra branch
1721 // that skips this block the first time the loop is executed, which we want
1722 // to avoid when optimising for size.
1723 // FIXME: in theory there is a case that does not introduce a new branch,
1724 // i.e. when the layout predecessor does not fallthrough to the loop header.
1725 // In practice this never happens though: there always seems to be a preheader
1726 // that can fallthrough and that is also placed before the header.
1727 if (F->getFunction()->optForSize())
1728 return L.getHeader();
1729
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001730 // Check that the header hasn't been fused with a preheader block due to
1731 // crazy branches. If it has, we need to start with the header at the top to
1732 // prevent pulling the preheader into the loop body.
1733 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
1734 if (!LoopBlockSet.count(*HeaderChain.begin()))
1735 return L.getHeader();
1736
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001737 DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(L.getHeader())
1738 << "\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001739
1740 BlockFrequency BestPredFreq;
Craig Topperc0196b12014-04-14 00:51:57 +00001741 MachineBasicBlock *BestPred = nullptr;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001742 for (MachineBasicBlock *Pred : L.getHeader()->predecessors()) {
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001743 if (!LoopBlockSet.count(Pred))
1744 continue;
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001745 DEBUG(dbgs() << " header pred: " << getBlockName(Pred) << ", has "
Michael Gottesmanb78dec82013-12-14 00:25:45 +00001746 << Pred->succ_size() << " successors, ";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001747 MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001748 if (Pred->succ_size() > 1)
1749 continue;
1750
1751 BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
1752 if (!BestPred || PredFreq > BestPredFreq ||
1753 (!(PredFreq < BestPredFreq) &&
1754 Pred->isLayoutSuccessor(L.getHeader()))) {
1755 BestPred = Pred;
1756 BestPredFreq = PredFreq;
1757 }
1758 }
1759
1760 // If no direct predecessor is fine, just use the loop header.
Philip Reamesb9688f42016-03-02 21:45:13 +00001761 if (!BestPred) {
1762 DEBUG(dbgs() << " final top unchanged\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001763 return L.getHeader();
Philip Reamesb9688f42016-03-02 21:45:13 +00001764 }
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001765
1766 // Walk backwards through any straight line of predecessors.
1767 while (BestPred->pred_size() == 1 &&
1768 (*BestPred->pred_begin())->succ_size() == 1 &&
1769 *BestPred->pred_begin() != L.getHeader())
1770 BestPred = *BestPred->pred_begin();
1771
1772 DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n");
1773 return BestPred;
1774}
1775
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001776/// \brief Find the best loop exiting block for layout.
1777///
Chandler Carruth03adbd42011-11-27 13:34:33 +00001778/// This routine implements the logic to analyze the loop looking for the best
1779/// block to layout at the top of the loop. Typically this is done to maximize
1780/// fallthrough opportunities.
1781MachineBasicBlock *
Kyle Butte9425c4f2017-02-04 02:26:32 +00001782MachineBlockPlacement::findBestLoopExit(const MachineLoop &L,
Chandler Carruthccc7e422012-04-16 01:12:56 +00001783 const BlockFilterSet &LoopBlockSet) {
Chandler Carruth68062612012-04-10 13:35:57 +00001784 // We don't want to layout the loop linearly in all cases. If the loop header
1785 // is just a normal basic block in the loop, we want to look for what block
1786 // within the loop is the best one to layout at the top. However, if the loop
1787 // header has be pre-merged into a chain due to predecessors not having
1788 // analyzable branches, *and* the predecessor it is merged with is *not* part
1789 // of the loop, rotating the header into the middle of the loop will create
1790 // a non-contiguous range of blocks which is Very Bad. So start with the
1791 // header and only rotate if safe.
1792 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
1793 if (!LoopBlockSet.count(*HeaderChain.begin()))
Craig Topperc0196b12014-04-14 00:51:57 +00001794 return nullptr;
Chandler Carruth68062612012-04-10 13:35:57 +00001795
Chandler Carruth03adbd42011-11-27 13:34:33 +00001796 BlockFrequency BestExitEdgeFreq;
Chandler Carruthccc7e422012-04-16 01:12:56 +00001797 unsigned BestExitLoopDepth = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00001798 MachineBasicBlock *ExitingBB = nullptr;
Chandler Carruth4f567202011-11-27 20:18:00 +00001799 // If there are exits to outer loops, loop rotation can severely limit
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001800 // fallthrough opportunities unless it selects such an exit. Keep a set of
Chandler Carruth4f567202011-11-27 20:18:00 +00001801 // blocks where rotating to exit with that block will reach an outer loop.
1802 SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
1803
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001804 DEBUG(dbgs() << "Finding best loop exit for: " << getBlockName(L.getHeader())
1805 << "\n");
Chandler Carruth7a715da2015-03-05 03:19:05 +00001806 for (MachineBasicBlock *MBB : L.getBlocks()) {
1807 BlockChain &Chain = *BlockToChain[MBB];
Chandler Carruth03adbd42011-11-27 13:34:33 +00001808 // Ensure that this block is at the end of a chain; otherwise it could be
Chandler Carruth9a512a42015-04-15 13:19:54 +00001809 // mid-way through an inner loop or a successor of an unanalyzable branch.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001810 if (MBB != *std::prev(Chain.end()))
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001811 continue;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001812
Chandler Carruth03adbd42011-11-27 13:34:33 +00001813 // Now walk the successors. We need to establish whether this has a viable
1814 // exiting successor and whether it has a viable non-exiting successor.
1815 // We store the old exiting state and restore it if a viable looping
1816 // successor isn't found.
1817 MachineBasicBlock *OldExitingBB = ExitingBB;
1818 BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
Chandler Carruthccc7e422012-04-16 01:12:56 +00001819 bool HasLoopingSucc = false;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001820 for (MachineBasicBlock *Succ : MBB->successors()) {
Reid Kleckner0e288232015-08-27 23:27:47 +00001821 if (Succ->isEHPad())
Chandler Carruth03adbd42011-11-27 13:34:33 +00001822 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001823 if (Succ == MBB)
Chandler Carruth03adbd42011-11-27 13:34:33 +00001824 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001825 BlockChain &SuccChain = *BlockToChain[Succ];
Chandler Carruth03adbd42011-11-27 13:34:33 +00001826 // Don't split chains, either this chain or the successor's chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +00001827 if (&Chain == &SuccChain) {
Chandler Carruth7a715da2015-03-05 03:19:05 +00001828 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
1829 << getBlockName(Succ) << " (chain conflict)\n");
Chandler Carruth03adbd42011-11-27 13:34:33 +00001830 continue;
1831 }
1832
Cong Houd97c1002015-12-01 05:29:22 +00001833 auto SuccProb = MBPI->getEdgeProbability(MBB, Succ);
Chandler Carruth7a715da2015-03-05 03:19:05 +00001834 if (LoopBlockSet.count(Succ)) {
1835 DEBUG(dbgs() << " looping: " << getBlockName(MBB) << " -> "
Cong Houd97c1002015-12-01 05:29:22 +00001836 << getBlockName(Succ) << " (" << SuccProb << ")\n");
Chandler Carruthccc7e422012-04-16 01:12:56 +00001837 HasLoopingSucc = true;
Chandler Carruth03adbd42011-11-27 13:34:33 +00001838 continue;
1839 }
1840
Chandler Carruthccc7e422012-04-16 01:12:56 +00001841 unsigned SuccLoopDepth = 0;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001842 if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
Chandler Carruthccc7e422012-04-16 01:12:56 +00001843 SuccLoopDepth = ExitLoop->getLoopDepth();
1844 if (ExitLoop->contains(&L))
Chandler Carruth7a715da2015-03-05 03:19:05 +00001845 BlocksExitingToOuterLoop.insert(MBB);
Chandler Carruthccc7e422012-04-16 01:12:56 +00001846 }
1847
Chandler Carruth7a715da2015-03-05 03:19:05 +00001848 BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
1849 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
1850 << getBlockName(Succ) << " [L:" << SuccLoopDepth << "] (";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001851 MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
Benjamin Kramerc8160d62013-11-20 19:08:44 +00001852 // Note that we bias this toward an existing layout successor to retain
1853 // incoming order in the absence of better information. The exit must have
1854 // a frequency higher than the current exit before we consider breaking
1855 // the layout.
1856 BranchProbability Bias(100 - ExitBlockBias, 100);
Chandler Carruth26d30172015-04-15 13:39:42 +00001857 if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
Chandler Carruthccc7e422012-04-16 01:12:56 +00001858 ExitEdgeFreq > BestExitEdgeFreq ||
Chandler Carruth7a715da2015-03-05 03:19:05 +00001859 (MBB->isLayoutSuccessor(Succ) &&
Benjamin Kramerc8160d62013-11-20 19:08:44 +00001860 !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
Chandler Carruth03adbd42011-11-27 13:34:33 +00001861 BestExitEdgeFreq = ExitEdgeFreq;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001862 ExitingBB = MBB;
Chandler Carrutha0545802011-11-27 09:22:53 +00001863 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001864 }
Chandler Carruth03adbd42011-11-27 13:34:33 +00001865
Chandler Carruthccc7e422012-04-16 01:12:56 +00001866 if (!HasLoopingSucc) {
Chandler Carruthcfb2b9d2015-04-15 13:26:41 +00001867 // Restore the old exiting state, no viable looping successor was found.
Chandler Carruth03adbd42011-11-27 13:34:33 +00001868 ExitingBB = OldExitingBB;
1869 BestExitEdgeFreq = OldBestExitEdgeFreq;
Chandler Carruth03adbd42011-11-27 13:34:33 +00001870 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001871 }
Chandler Carruthccc7e422012-04-16 01:12:56 +00001872 // Without a candidate exiting block or with only a single block in the
Chandler Carruth03adbd42011-11-27 13:34:33 +00001873 // loop, just use the loop header to layout the loop.
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001874 if (!ExitingBB) {
1875 DEBUG(dbgs() << " No other candidate exit blocks, using loop header\n");
Craig Topperc0196b12014-04-14 00:51:57 +00001876 return nullptr;
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001877 }
1878 if (L.getNumBlocks() == 1) {
1879 DEBUG(dbgs() << " Loop has 1 block, using loop header as exit\n");
1880 return nullptr;
1881 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001882
Chandler Carruth4f567202011-11-27 20:18:00 +00001883 // Also, if we have exit blocks which lead to outer loops but didn't select
1884 // one of them as the exiting block we are rotating toward, disable loop
1885 // rotation altogether.
1886 if (!BlocksExitingToOuterLoop.empty() &&
1887 !BlocksExitingToOuterLoop.count(ExitingBB))
Craig Topperc0196b12014-04-14 00:51:57 +00001888 return nullptr;
Chandler Carruth4f567202011-11-27 20:18:00 +00001889
Chandler Carruth03adbd42011-11-27 13:34:33 +00001890 DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB) << "\n");
Chandler Carruthccc7e422012-04-16 01:12:56 +00001891 return ExitingBB;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001892}
1893
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001894/// \brief Attempt to rotate an exiting block to the bottom of the loop.
1895///
1896/// Once we have built a chain, try to rotate it to line up the hot exit block
1897/// with fallthrough out of the loop if doing so doesn't introduce unnecessary
1898/// branches. For example, if the loop has fallthrough into its header and out
1899/// of its bottom already, don't rotate it.
1900void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
Kyle Butte9425c4f2017-02-04 02:26:32 +00001901 const MachineBasicBlock *ExitingBB,
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001902 const BlockFilterSet &LoopBlockSet) {
1903 if (!ExitingBB)
1904 return;
1905
1906 MachineBasicBlock *Top = *LoopChain.begin();
1907 bool ViableTopFallthrough = false;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001908 for (MachineBasicBlock *Pred : Top->predecessors()) {
1909 BlockChain *PredChain = BlockToChain[Pred];
1910 if (!LoopBlockSet.count(Pred) &&
1911 (!PredChain || Pred == *std::prev(PredChain->end()))) {
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001912 ViableTopFallthrough = true;
1913 break;
1914 }
1915 }
1916
1917 // If the header has viable fallthrough, check whether the current loop
1918 // bottom is a viable exiting block. If so, bail out as rotating will
1919 // introduce an unnecessary branch.
1920 if (ViableTopFallthrough) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001921 MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
Chandler Carruth7a715da2015-03-05 03:19:05 +00001922 for (MachineBasicBlock *Succ : Bottom->successors()) {
1923 BlockChain *SuccChain = BlockToChain[Succ];
1924 if (!LoopBlockSet.count(Succ) &&
1925 (!SuccChain || Succ == *SuccChain->begin()))
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001926 return;
1927 }
1928 }
1929
David Majnemer0d955d02016-08-11 22:21:41 +00001930 BlockChain::iterator ExitIt = find(LoopChain, ExitingBB);
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001931 if (ExitIt == LoopChain.end())
1932 return;
1933
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001934 std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001935}
1936
Cong Hou7745dbc2015-10-19 23:16:40 +00001937/// \brief Attempt to rotate a loop based on profile data to reduce branch cost.
1938///
1939/// With profile data, we can determine the cost in terms of missed fall through
1940/// opportunities when rotating a loop chain and select the best rotation.
1941/// Basically, there are three kinds of cost to consider for each rotation:
1942/// 1. The possibly missed fall through edge (if it exists) from BB out of
1943/// the loop to the loop header.
1944/// 2. The possibly missed fall through edges (if they exist) from the loop
1945/// exits to BB out of the loop.
1946/// 3. The missed fall through edge (if it exists) from the last BB to the
1947/// first BB in the loop chain.
1948/// Therefore, the cost for a given rotation is the sum of costs listed above.
1949/// We select the best rotation with the smallest cost.
1950void MachineBlockPlacement::rotateLoopWithProfile(
Kyle Butte9425c4f2017-02-04 02:26:32 +00001951 BlockChain &LoopChain, const MachineLoop &L,
1952 const BlockFilterSet &LoopBlockSet) {
Cong Hou7745dbc2015-10-19 23:16:40 +00001953 auto HeaderBB = L.getHeader();
David Majnemer0d955d02016-08-11 22:21:41 +00001954 auto HeaderIter = find(LoopChain, HeaderBB);
Cong Hou7745dbc2015-10-19 23:16:40 +00001955 auto RotationPos = LoopChain.end();
1956
1957 BlockFrequency SmallestRotationCost = BlockFrequency::getMaxFrequency();
1958
1959 // A utility lambda that scales up a block frequency by dividing it by a
1960 // branch probability which is the reciprocal of the scale.
1961 auto ScaleBlockFrequency = [](BlockFrequency Freq,
1962 unsigned Scale) -> BlockFrequency {
1963 if (Scale == 0)
1964 return 0;
1965 // Use operator / between BlockFrequency and BranchProbability to implement
1966 // saturating multiplication.
1967 return Freq / BranchProbability(1, Scale);
1968 };
1969
1970 // Compute the cost of the missed fall-through edge to the loop header if the
1971 // chain head is not the loop header. As we only consider natural loops with
1972 // single header, this computation can be done only once.
1973 BlockFrequency HeaderFallThroughCost(0);
1974 for (auto *Pred : HeaderBB->predecessors()) {
1975 BlockChain *PredChain = BlockToChain[Pred];
1976 if (!LoopBlockSet.count(Pred) &&
1977 (!PredChain || Pred == *std::prev(PredChain->end()))) {
1978 auto EdgeFreq =
1979 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, HeaderBB);
1980 auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost);
1981 // If the predecessor has only an unconditional jump to the header, we
1982 // need to consider the cost of this jump.
1983 if (Pred->succ_size() == 1)
1984 FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost);
1985 HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost);
1986 }
1987 }
1988
1989 // Here we collect all exit blocks in the loop, and for each exit we find out
1990 // its hottest exit edge. For each loop rotation, we define the loop exit cost
1991 // as the sum of frequencies of exit edges we collect here, excluding the exit
1992 // edge from the tail of the loop chain.
1993 SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq;
1994 for (auto BB : LoopChain) {
Cong Houd97c1002015-12-01 05:29:22 +00001995 auto LargestExitEdgeProb = BranchProbability::getZero();
Cong Hou7745dbc2015-10-19 23:16:40 +00001996 for (auto *Succ : BB->successors()) {
1997 BlockChain *SuccChain = BlockToChain[Succ];
1998 if (!LoopBlockSet.count(Succ) &&
1999 (!SuccChain || Succ == *SuccChain->begin())) {
Cong Houd97c1002015-12-01 05:29:22 +00002000 auto SuccProb = MBPI->getEdgeProbability(BB, Succ);
2001 LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb);
Cong Hou7745dbc2015-10-19 23:16:40 +00002002 }
2003 }
Cong Houd97c1002015-12-01 05:29:22 +00002004 if (LargestExitEdgeProb > BranchProbability::getZero()) {
2005 auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb;
Cong Hou7745dbc2015-10-19 23:16:40 +00002006 ExitsWithFreq.emplace_back(BB, ExitFreq);
2007 }
2008 }
2009
2010 // In this loop we iterate every block in the loop chain and calculate the
2011 // cost assuming the block is the head of the loop chain. When the loop ends,
2012 // we should have found the best candidate as the loop chain's head.
2013 for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()),
2014 EndIter = LoopChain.end();
2015 Iter != EndIter; Iter++, TailIter++) {
2016 // TailIter is used to track the tail of the loop chain if the block we are
2017 // checking (pointed by Iter) is the head of the chain.
2018 if (TailIter == LoopChain.end())
2019 TailIter = LoopChain.begin();
2020
2021 auto TailBB = *TailIter;
2022
2023 // Calculate the cost by putting this BB to the top.
2024 BlockFrequency Cost = 0;
2025
2026 // If the current BB is the loop header, we need to take into account the
2027 // cost of the missed fall through edge from outside of the loop to the
2028 // header.
2029 if (Iter != HeaderIter)
2030 Cost += HeaderFallThroughCost;
2031
2032 // Collect the loop exit cost by summing up frequencies of all exit edges
2033 // except the one from the chain tail.
2034 for (auto &ExitWithFreq : ExitsWithFreq)
2035 if (TailBB != ExitWithFreq.first)
2036 Cost += ExitWithFreq.second;
2037
2038 // The cost of breaking the once fall-through edge from the tail to the top
2039 // of the loop chain. Here we need to consider three cases:
2040 // 1. If the tail node has only one successor, then we will get an
2041 // additional jmp instruction. So the cost here is (MisfetchCost +
2042 // JumpInstCost) * tail node frequency.
2043 // 2. If the tail node has two successors, then we may still get an
2044 // additional jmp instruction if the layout successor after the loop
2045 // chain is not its CFG successor. Note that the more frequently executed
2046 // jmp instruction will be put ahead of the other one. Assume the
2047 // frequency of those two branches are x and y, where x is the frequency
2048 // of the edge to the chain head, then the cost will be
2049 // (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency.
2050 // 3. If the tail node has more than two successors (this rarely happens),
2051 // we won't consider any additional cost.
2052 if (TailBB->isSuccessor(*Iter)) {
2053 auto TailBBFreq = MBFI->getBlockFreq(TailBB);
2054 if (TailBB->succ_size() == 1)
2055 Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(),
2056 MisfetchCost + JumpInstCost);
2057 else if (TailBB->succ_size() == 2) {
2058 auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter);
2059 auto TailToHeadFreq = TailBBFreq * TailToHeadProb;
2060 auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2)
2061 ? TailBBFreq * TailToHeadProb.getCompl()
2062 : TailToHeadFreq;
2063 Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) +
2064 ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost);
2065 }
2066 }
2067
Philip Reamesb9688f42016-03-02 21:45:13 +00002068 DEBUG(dbgs() << "The cost of loop rotation by making " << getBlockName(*Iter)
Cong Hou7745dbc2015-10-19 23:16:40 +00002069 << " to the top: " << Cost.getFrequency() << "\n");
2070
2071 if (Cost < SmallestRotationCost) {
2072 SmallestRotationCost = Cost;
2073 RotationPos = Iter;
2074 }
2075 }
2076
2077 if (RotationPos != LoopChain.end()) {
Philip Reamesb9688f42016-03-02 21:45:13 +00002078 DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos)
Cong Hou7745dbc2015-10-19 23:16:40 +00002079 << " to the top\n");
2080 std::rotate(LoopChain.begin(), RotationPos, LoopChain.end());
2081 }
2082}
2083
Cong Houb90b9e02015-11-02 21:24:00 +00002084/// \brief Collect blocks in the given loop that are to be placed.
2085///
2086/// When profile data is available, exclude cold blocks from the returned set;
2087/// otherwise, collect all blocks in the loop.
2088MachineBlockPlacement::BlockFilterSet
Kyle Butte9425c4f2017-02-04 02:26:32 +00002089MachineBlockPlacement::collectLoopBlockSet(const MachineLoop &L) {
Cong Houb90b9e02015-11-02 21:24:00 +00002090 BlockFilterSet LoopBlockSet;
2091
2092 // Filter cold blocks off from LoopBlockSet when profile data is available.
2093 // Collect the sum of frequencies of incoming edges to the loop header from
2094 // outside. If we treat the loop as a super block, this is the frequency of
2095 // the loop. Then for each block in the loop, we calculate the ratio between
2096 // its frequency and the frequency of the loop block. When it is too small,
2097 // don't add it to the loop chain. If there are outer loops, then this block
2098 // will be merged into the first outer loop chain for which this block is not
2099 // cold anymore. This needs precise profile data and we only do this when
2100 // profile data is available.
Xinliang David Li52530a72016-06-13 22:23:44 +00002101 if (F->getFunction()->getEntryCount()) {
Cong Houb90b9e02015-11-02 21:24:00 +00002102 BlockFrequency LoopFreq(0);
2103 for (auto LoopPred : L.getHeader()->predecessors())
2104 if (!L.contains(LoopPred))
2105 LoopFreq += MBFI->getBlockFreq(LoopPred) *
2106 MBPI->getEdgeProbability(LoopPred, L.getHeader());
2107
2108 for (MachineBasicBlock *LoopBB : L.getBlocks()) {
2109 auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency();
2110 if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio)
2111 continue;
2112 LoopBlockSet.insert(LoopBB);
2113 }
2114 } else
2115 LoopBlockSet.insert(L.block_begin(), L.block_end());
2116
2117 return LoopBlockSet;
2118}
2119
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00002120/// \brief Forms basic block chains from the natural loop structures.
Chandler Carruth10281422011-10-21 06:46:38 +00002121///
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00002122/// These chains are designed to preserve the existing *structure* of the code
2123/// as much as possible. We can then stitch the chains together in a way which
2124/// both preserves the topological structure and minimizes taken conditional
2125/// branches.
Kyle Butte9425c4f2017-02-04 02:26:32 +00002126void MachineBlockPlacement::buildLoopChains(const MachineLoop &L) {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00002127 // First recurse through any nested loops, building chains for those inner
2128 // loops.
Kyle Butte9425c4f2017-02-04 02:26:32 +00002129 for (const MachineLoop *InnerLoop : L)
Xinliang David Li52530a72016-06-13 22:23:44 +00002130 buildLoopChains(*InnerLoop);
Chandler Carruth10281422011-10-21 06:46:38 +00002131
Xinliang David Li93926ac2016-07-01 05:46:48 +00002132 assert(BlockWorkList.empty());
2133 assert(EHPadWorkList.empty());
Xinliang David Li52530a72016-06-13 22:23:44 +00002134 BlockFilterSet LoopBlockSet = collectLoopBlockSet(L);
Chandler Carruth03adbd42011-11-27 13:34:33 +00002135
Cong Hou7745dbc2015-10-19 23:16:40 +00002136 // Check if we have profile data for this function. If yes, we will rotate
2137 // this loop by modeling costs more precisely which requires the profile data
2138 // for better layout.
2139 bool RotateLoopWithProfile =
Xinliang David Lif0ab6df2016-05-12 02:04:41 +00002140 ForcePreciseRotationCost ||
Xinliang David Li52530a72016-06-13 22:23:44 +00002141 (PreciseRotationCost && F->getFunction()->getEntryCount());
Cong Hou7745dbc2015-10-19 23:16:40 +00002142
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00002143 // First check to see if there is an obviously preferable top block for the
2144 // loop. This will default to the header, but may end up as one of the
2145 // predecessors to the header if there is one which will result in strictly
2146 // fewer branches in the loop body.
Cong Hou7745dbc2015-10-19 23:16:40 +00002147 // When we use profile data to rotate the loop, this is unnecessary.
2148 MachineBasicBlock *LoopTop =
2149 RotateLoopWithProfile ? L.getHeader() : findBestLoopTop(L, LoopBlockSet);
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00002150
2151 // If we selected just the header for the loop top, look for a potentially
2152 // profitable exit block in the event that rotating the loop can eliminate
2153 // branches by placing an exit edge at the bottom.
Cong Hou7745dbc2015-10-19 23:16:40 +00002154 if (!RotateLoopWithProfile && LoopTop == L.getHeader())
Kyle Buttab9cca72016-10-27 21:37:20 +00002155 PreferredLoopExit = findBestLoopExit(L, LoopBlockSet);
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00002156
2157 BlockChain &LoopChain = *BlockToChain[LoopTop];
Chandler Carruth10281422011-10-21 06:46:38 +00002158
Chandler Carruth8d150782011-11-13 11:20:44 +00002159 // FIXME: This is a really lame way of walking the chains in the loop: we
2160 // walk the blocks, and use a set to prevent visiting a particular chain
2161 // twice.
Jakub Staszak90616162011-12-21 23:02:08 +00002162 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
Philip Reamesae27b232016-03-03 00:58:43 +00002163 assert(LoopChain.UnscheduledPredecessors == 0);
Jakub Staszak190c7122011-12-07 19:46:10 +00002164 UpdatedPreds.insert(&LoopChain);
Cong Houb90b9e02015-11-02 21:24:00 +00002165
Kyle Butte9425c4f2017-02-04 02:26:32 +00002166 for (const MachineBasicBlock *LoopBB : LoopBlockSet)
Xinliang David Li93926ac2016-07-01 05:46:48 +00002167 fillWorkLists(LoopBB, UpdatedPreds, &LoopBlockSet);
Chandler Carruth8d150782011-11-13 11:20:44 +00002168
Xinliang David Li93926ac2016-07-01 05:46:48 +00002169 buildChain(LoopTop, LoopChain, &LoopBlockSet);
Cong Hou7745dbc2015-10-19 23:16:40 +00002170
2171 if (RotateLoopWithProfile)
2172 rotateLoopWithProfile(LoopChain, L, LoopBlockSet);
2173 else
Kyle Buttab9cca72016-10-27 21:37:20 +00002174 rotateLoop(LoopChain, PreferredLoopExit, LoopBlockSet);
Chandler Carruth8d150782011-11-13 11:20:44 +00002175
2176 DEBUG({
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002177 // Crash at the end so we get all of the debugging output first.
2178 bool BadLoop = false;
Philip Reamesae27b232016-03-03 00:58:43 +00002179 if (LoopChain.UnscheduledPredecessors) {
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002180 BadLoop = true;
Chandler Carruth8d150782011-11-13 11:20:44 +00002181 dbgs() << "Loop chain contains a block without its preds placed!\n"
2182 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
2183 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002184 }
Chandler Carruth7a715da2015-03-05 03:19:05 +00002185 for (MachineBasicBlock *ChainBB : LoopChain) {
2186 dbgs() << " ... " << getBlockName(ChainBB) << "\n";
Rong Xu66827422016-11-16 20:50:06 +00002187 if (!LoopBlockSet.remove(ChainBB)) {
Chandler Carruth0a31d142011-11-14 10:55:53 +00002188 // We don't mark the loop as bad here because there are real situations
2189 // where this can occur. For example, with an unanalyzable fallthrough
Chandler Carruth99fe42f2011-11-23 10:35:36 +00002190 // from a loop block to a non-loop block or vice versa.
Chandler Carruth8d150782011-11-13 11:20:44 +00002191 dbgs() << "Loop chain contains a block not contained by the loop!\n"
2192 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
2193 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00002194 << " Bad block: " << getBlockName(ChainBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002195 }
Chandler Carruthccc7e422012-04-16 01:12:56 +00002196 }
Chandler Carruth8d150782011-11-13 11:20:44 +00002197
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002198 if (!LoopBlockSet.empty()) {
2199 BadLoop = true;
Kyle Butte9425c4f2017-02-04 02:26:32 +00002200 for (const MachineBasicBlock *LoopBB : LoopBlockSet)
Chandler Carruth8d150782011-11-13 11:20:44 +00002201 dbgs() << "Loop contains blocks never placed into a chain!\n"
2202 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
2203 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00002204 << " Bad block: " << getBlockName(LoopBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002205 }
2206 assert(!BadLoop && "Detected problems with the placement of this loop.");
Chandler Carruth8d150782011-11-13 11:20:44 +00002207 });
Xinliang David Li93926ac2016-07-01 05:46:48 +00002208
2209 BlockWorkList.clear();
2210 EHPadWorkList.clear();
Chandler Carruth10281422011-10-21 06:46:38 +00002211}
2212
Xinliang David Li52530a72016-06-13 22:23:44 +00002213void MachineBlockPlacement::buildCFGChains() {
Chandler Carruth8d150782011-11-13 11:20:44 +00002214 // Ensure that every BB in the function has an associated chain to simplify
2215 // the assumptions of the remaining algorithm.
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00002216 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
Xinliang David Li52530a72016-06-13 22:23:44 +00002217 for (MachineFunction::iterator FI = F->begin(), FE = F->end(); FI != FE;
2218 ++FI) {
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00002219 MachineBasicBlock *BB = &*FI;
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00002220 BlockChain *Chain =
2221 new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00002222 // Also, merge any blocks which we cannot reason about and must preserve
2223 // the exact fallthrough behavior for.
2224 for (;;) {
2225 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00002226 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002227 if (!TII->analyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00002228 break;
2229
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00002230 MachineFunction::iterator NextFI = std::next(FI);
2231 MachineBasicBlock *NextBB = &*NextFI;
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00002232 // Ensure that the layout successor is a viable block, as we know that
2233 // fallthrough is a possibility.
2234 assert(NextFI != FE && "Can't fallthrough past the last block.");
2235 DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
2236 << getBlockName(BB) << " -> " << getBlockName(NextBB)
2237 << "\n");
Craig Topperc0196b12014-04-14 00:51:57 +00002238 Chain->merge(NextBB, nullptr);
Hal Finkel34f9d6a2016-12-15 05:33:19 +00002239#ifndef NDEBUG
Sanjoy Dasd7389d62016-12-15 05:08:57 +00002240 BlocksWithUnanalyzableExits.insert(&*BB);
Hal Finkel34f9d6a2016-12-15 05:33:19 +00002241#endif
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00002242 FI = NextFI;
2243 BB = NextBB;
2244 }
2245 }
Chandler Carruth8d150782011-11-13 11:20:44 +00002246
2247 // Build any loop-based chains.
Sam McCall2a36eee2016-11-01 22:02:14 +00002248 PreferredLoopExit = nullptr;
Chandler Carruth7a715da2015-03-05 03:19:05 +00002249 for (MachineLoop *L : *MLI)
Xinliang David Li52530a72016-06-13 22:23:44 +00002250 buildLoopChains(*L);
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00002251
Xinliang David Li93926ac2016-07-01 05:46:48 +00002252 assert(BlockWorkList.empty());
2253 assert(EHPadWorkList.empty());
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00002254
Chandler Carruth8d150782011-11-13 11:20:44 +00002255 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
Xinliang David Li52530a72016-06-13 22:23:44 +00002256 for (MachineBasicBlock &MBB : *F)
Xinliang David Li93926ac2016-07-01 05:46:48 +00002257 fillWorkLists(&MBB, UpdatedPreds);
Chandler Carruth8d150782011-11-13 11:20:44 +00002258
Xinliang David Li52530a72016-06-13 22:23:44 +00002259 BlockChain &FunctionChain = *BlockToChain[&F->front()];
Xinliang David Li93926ac2016-07-01 05:46:48 +00002260 buildChain(&F->front(), FunctionChain);
Chandler Carruth8d150782011-11-13 11:20:44 +00002261
Matt Arsenault0f5f0152013-12-10 18:55:37 +00002262#ifndef NDEBUG
Matt Arsenault79d55f52013-12-05 20:02:18 +00002263 typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType;
Matt Arsenault0f5f0152013-12-10 18:55:37 +00002264#endif
Chandler Carruth8d150782011-11-13 11:20:44 +00002265 DEBUG({
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002266 // Crash at the end so we get all of the debugging output first.
2267 bool BadFunc = false;
Chandler Carruth8d150782011-11-13 11:20:44 +00002268 FunctionBlockSetType FunctionBlockSet;
Xinliang David Li52530a72016-06-13 22:23:44 +00002269 for (MachineBasicBlock &MBB : *F)
Chandler Carruth7a715da2015-03-05 03:19:05 +00002270 FunctionBlockSet.insert(&MBB);
Chandler Carruth8d150782011-11-13 11:20:44 +00002271
Chandler Carruth7a715da2015-03-05 03:19:05 +00002272 for (MachineBasicBlock *ChainBB : FunctionChain)
2273 if (!FunctionBlockSet.erase(ChainBB)) {
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002274 BadFunc = true;
Chandler Carruth8d150782011-11-13 11:20:44 +00002275 dbgs() << "Function chain contains a block not in the function!\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00002276 << " Bad block: " << getBlockName(ChainBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002277 }
Chandler Carruth8d150782011-11-13 11:20:44 +00002278
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002279 if (!FunctionBlockSet.empty()) {
2280 BadFunc = true;
Chandler Carruth7a715da2015-03-05 03:19:05 +00002281 for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
Chandler Carruth8d150782011-11-13 11:20:44 +00002282 dbgs() << "Function contains blocks never placed into a chain!\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00002283 << " Bad block: " << getBlockName(RemainingBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002284 }
2285 assert(!BadFunc && "Detected problems with the block placement.");
Chandler Carruth8d150782011-11-13 11:20:44 +00002286 });
2287
2288 // Splice the blocks into place.
Xinliang David Li52530a72016-06-13 22:23:44 +00002289 MachineFunction::iterator InsertPos = F->begin();
Xinliang David Li449cdfd2016-06-24 22:54:21 +00002290 DEBUG(dbgs() << "[MBP] Function: "<< F->getName() << "\n");
Chandler Carruth7a715da2015-03-05 03:19:05 +00002291 for (MachineBasicBlock *ChainBB : FunctionChain) {
2292 DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
2293 : " ... ")
2294 << getBlockName(ChainBB) << "\n");
2295 if (InsertPos != MachineFunction::iterator(ChainBB))
Xinliang David Li52530a72016-06-13 22:23:44 +00002296 F->splice(InsertPos, ChainBB);
Chandler Carruth8d150782011-11-13 11:20:44 +00002297 else
2298 ++InsertPos;
2299
2300 // Update the terminator of the previous block.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002301 if (ChainBB == *FunctionChain.begin())
Chandler Carruth8d150782011-11-13 11:20:44 +00002302 continue;
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00002303 MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB));
Chandler Carruth8d150782011-11-13 11:20:44 +00002304
Chandler Carruth10281422011-10-21 06:46:38 +00002305 // FIXME: It would be awesome of updateTerminator would just return rather
2306 // than assert when the branch cannot be analyzed in order to remove this
2307 // boiler plate.
2308 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00002309 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Shuxin Yang8b8fd212013-06-04 01:00:57 +00002310
Sanjoy Dasd7389d62016-12-15 05:08:57 +00002311#ifndef NDEBUG
2312 if (!BlocksWithUnanalyzableExits.count(PrevBB)) {
2313 // Given the exact block placement we chose, we may actually not _need_ to
2314 // be able to edit PrevBB's terminator sequence, but not being _able_ to
2315 // do that at this point is a bug.
2316 assert((!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond) ||
2317 !PrevBB->canFallThrough()) &&
2318 "Unexpected block with un-analyzable fallthrough!");
2319 Cond.clear();
2320 TBB = FBB = nullptr;
2321 }
2322#endif
2323
Haicheng Wu90a55652016-05-24 22:16:14 +00002324 // The "PrevBB" is not yet updated to reflect current code layout, so,
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00002325 // o. it may fall-through to a block without explicit "goto" instruction
Haicheng Wu90a55652016-05-24 22:16:14 +00002326 // before layout, and no longer fall-through it after layout; or
2327 // o. just opposite.
2328 //
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002329 // analyzeBranch() may return erroneous value for FBB when these two
Haicheng Wu90a55652016-05-24 22:16:14 +00002330 // situations take place. For the first scenario FBB is mistakenly set NULL;
2331 // for the 2nd scenario, the FBB, which is expected to be NULL, is
2332 // mistakenly pointing to "*BI".
2333 // Thus, if the future change needs to use FBB before the layout is set, it
2334 // has to correct FBB first by using the code similar to the following:
2335 //
2336 // if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
2337 // PrevBB->updateTerminator();
2338 // Cond.clear();
2339 // TBB = FBB = nullptr;
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002340 // if (TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) {
Haicheng Wu90a55652016-05-24 22:16:14 +00002341 // // FIXME: This should never take place.
2342 // TBB = FBB = nullptr;
2343 // }
2344 // }
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002345 if (!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond))
Haicheng Wu90a55652016-05-24 22:16:14 +00002346 PrevBB->updateTerminator();
Chandler Carruth10281422011-10-21 06:46:38 +00002347 }
Chandler Carruth8d150782011-11-13 11:20:44 +00002348
2349 // Fixup the last block.
2350 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00002351 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002352 if (!TII->analyzeBranch(F->back(), TBB, FBB, Cond))
Xinliang David Li52530a72016-06-13 22:23:44 +00002353 F->back().updateTerminator();
Xinliang David Li93926ac2016-07-01 05:46:48 +00002354
2355 BlockWorkList.clear();
2356 EHPadWorkList.clear();
Haicheng Wu90a55652016-05-24 22:16:14 +00002357}
2358
Xinliang David Li52530a72016-06-13 22:23:44 +00002359void MachineBlockPlacement::optimizeBranches() {
2360 BlockChain &FunctionChain = *BlockToChain[&F->front()];
Haicheng Wu90a55652016-05-24 22:16:14 +00002361 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
Quentin Colombet776e6de2016-05-02 22:58:59 +00002362
2363 // Now that all the basic blocks in the chain have the proper layout,
2364 // make a final call to AnalyzeBranch with AllowModify set.
2365 // Indeed, the target may be able to optimize the branches in a way we
2366 // cannot because all branches may not be analyzable.
2367 // E.g., the target may be able to remove an unconditional branch to
2368 // a fallthrough when it occurs after predicated terminators.
2369 for (MachineBasicBlock *ChainBB : FunctionChain) {
2370 Cond.clear();
Haicheng Wu90a55652016-05-24 22:16:14 +00002371 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002372 if (!TII->analyzeBranch(*ChainBB, TBB, FBB, Cond, /*AllowModify*/ true)) {
Haicheng Wu90a55652016-05-24 22:16:14 +00002373 // If PrevBB has a two-way branch, try to re-order the branches
2374 // such that we branch to the successor with higher probability first.
2375 if (TBB && !Cond.empty() && FBB &&
2376 MBPI->getEdgeProbability(ChainBB, FBB) >
2377 MBPI->getEdgeProbability(ChainBB, TBB) &&
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00002378 !TII->reverseBranchCondition(Cond)) {
Haicheng Wu90a55652016-05-24 22:16:14 +00002379 DEBUG(dbgs() << "Reverse order of the two branches: "
2380 << getBlockName(ChainBB) << "\n");
2381 DEBUG(dbgs() << " Edge probability: "
2382 << MBPI->getEdgeProbability(ChainBB, FBB) << " vs "
2383 << MBPI->getEdgeProbability(ChainBB, TBB) << "\n");
2384 DebugLoc dl; // FIXME: this is nowhere
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00002385 TII->removeBranch(*ChainBB);
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00002386 TII->insertBranch(*ChainBB, FBB, TBB, Cond, dl);
Haicheng Wu90a55652016-05-24 22:16:14 +00002387 ChainBB->updateTerminator();
2388 }
2389 }
Quentin Colombet776e6de2016-05-02 22:58:59 +00002390 }
Haicheng Wue749ce52016-04-29 17:06:44 +00002391}
Chandler Carruth10281422011-10-21 06:46:38 +00002392
Xinliang David Li52530a72016-06-13 22:23:44 +00002393void MachineBlockPlacement::alignBlocks() {
Chandler Carruthccc7e422012-04-16 01:12:56 +00002394 // Walk through the backedges of the function now that we have fully laid out
2395 // the basic blocks and align the destination of each backedge. We don't rely
Chandler Carruth881d0a72012-08-07 09:45:24 +00002396 // exclusively on the loop info here so that we can align backedges in
2397 // unnatural CFGs and backedges that were introduced purely because of the
2398 // loop rotations done during this layout pass.
Xinliang David Li52530a72016-06-13 22:23:44 +00002399 if (F->getFunction()->optForSize())
Chandler Carruth8b9737c2011-10-21 08:57:37 +00002400 return;
Xinliang David Li52530a72016-06-13 22:23:44 +00002401 BlockChain &FunctionChain = *BlockToChain[&F->front()];
Chandler Carruth881d0a72012-08-07 09:45:24 +00002402 if (FunctionChain.begin() == FunctionChain.end())
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00002403 return; // Empty chain.
Chandler Carruth8b9737c2011-10-21 08:57:37 +00002404
Chandler Carruth881d0a72012-08-07 09:45:24 +00002405 const BranchProbability ColdProb(1, 5); // 20%
Xinliang David Li52530a72016-06-13 22:23:44 +00002406 BlockFrequency EntryFreq = MBFI->getBlockFreq(&F->front());
Chandler Carruth881d0a72012-08-07 09:45:24 +00002407 BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
Chandler Carruth7a715da2015-03-05 03:19:05 +00002408 for (MachineBasicBlock *ChainBB : FunctionChain) {
2409 if (ChainBB == *FunctionChain.begin())
2410 continue;
2411
Chandler Carruth881d0a72012-08-07 09:45:24 +00002412 // Don't align non-looping basic blocks. These are unlikely to execute
2413 // enough times to matter in practice. Note that we'll still handle
2414 // unnatural CFGs inside of a natural outer loop (the common case) and
2415 // rotated loops.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002416 MachineLoop *L = MLI->getLoopFor(ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00002417 if (!L)
2418 continue;
2419
Hal Finkel57725662015-01-03 17:58:24 +00002420 unsigned Align = TLI->getPrefLoopAlignment(L);
2421 if (!Align)
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00002422 continue; // Don't care about loop alignment.
Hal Finkel57725662015-01-03 17:58:24 +00002423
Chandler Carruth881d0a72012-08-07 09:45:24 +00002424 // If the block is cold relative to the function entry don't waste space
2425 // aligning it.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002426 BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00002427 if (Freq < WeightedEntryFreq)
2428 continue;
2429
2430 // If the block is cold relative to its loop header, don't align it
2431 // regardless of what edges into the block exist.
2432 MachineBasicBlock *LoopHeader = L->getHeader();
2433 BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
2434 if (Freq < (LoopHeaderFreq * ColdProb))
2435 continue;
2436
2437 // Check for the existence of a non-layout predecessor which would benefit
2438 // from aligning this block.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002439 MachineBasicBlock *LayoutPred =
2440 &*std::prev(MachineFunction::iterator(ChainBB));
Chandler Carruth881d0a72012-08-07 09:45:24 +00002441
2442 // Force alignment if all the predecessors are jumps. We already checked
2443 // that the block isn't cold above.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002444 if (!LayoutPred->isSuccessor(ChainBB)) {
2445 ChainBB->setAlignment(Align);
Chandler Carruth881d0a72012-08-07 09:45:24 +00002446 continue;
2447 }
2448
2449 // Align this block if the layout predecessor's edge into this block is
Nadav Rotem6036f582013-03-29 16:34:23 +00002450 // cold relative to the block. When this is true, other predecessors make up
Chandler Carruth881d0a72012-08-07 09:45:24 +00002451 // all of the hot entries into the block and thus alignment is likely to be
2452 // important.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002453 BranchProbability LayoutProb =
2454 MBPI->getEdgeProbability(LayoutPred, ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00002455 BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
2456 if (LayoutEdgeFreq <= (Freq * ColdProb))
Chandler Carruth7a715da2015-03-05 03:19:05 +00002457 ChainBB->setAlignment(Align);
Chandler Carruthccc7e422012-04-16 01:12:56 +00002458 }
Chandler Carruth8b9737c2011-10-21 08:57:37 +00002459}
2460
Kyle Butt0846e562016-10-11 20:36:43 +00002461/// Tail duplicate \p BB into (some) predecessors if profitable, repeating if
2462/// it was duplicated into its chain predecessor and removed.
2463/// \p BB - Basic block that may be duplicated.
2464///
2465/// \p LPred - Chosen layout predecessor of \p BB.
2466/// Updated to be the chain end if LPred is removed.
2467/// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
2468/// \p BlockFilter - Set of blocks that belong to the loop being laid out.
2469/// Used to identify which blocks to update predecessor
2470/// counts.
2471/// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
2472/// chosen in the given order due to unnatural CFG
2473/// only needed if \p BB is removed and
2474/// \p PrevUnplacedBlockIt pointed to \p BB.
2475/// @return true if \p BB was removed.
2476bool MachineBlockPlacement::repeatedlyTailDuplicateBlock(
2477 MachineBasicBlock *BB, MachineBasicBlock *&LPred,
Kyle Butte9425c4f2017-02-04 02:26:32 +00002478 const MachineBasicBlock *LoopHeaderBB,
Kyle Butt0846e562016-10-11 20:36:43 +00002479 BlockChain &Chain, BlockFilterSet *BlockFilter,
2480 MachineFunction::iterator &PrevUnplacedBlockIt) {
2481 bool Removed, DuplicatedToLPred;
2482 bool DuplicatedToOriginalLPred;
2483 Removed = maybeTailDuplicateBlock(BB, LPred, Chain, BlockFilter,
2484 PrevUnplacedBlockIt,
2485 DuplicatedToLPred);
2486 if (!Removed)
2487 return false;
2488 DuplicatedToOriginalLPred = DuplicatedToLPred;
2489 // Iteratively try to duplicate again. It can happen that a block that is
2490 // duplicated into is still small enough to be duplicated again.
2491 // No need to call markBlockSuccessors in this case, as the blocks being
2492 // duplicated from here on are already scheduled.
2493 // Note that DuplicatedToLPred always implies Removed.
2494 while (DuplicatedToLPred) {
2495 assert (Removed && "Block must have been removed to be duplicated into its "
2496 "layout predecessor.");
2497 MachineBasicBlock *DupBB, *DupPred;
2498 // The removal callback causes Chain.end() to be updated when a block is
2499 // removed. On the first pass through the loop, the chain end should be the
2500 // same as it was on function entry. On subsequent passes, because we are
2501 // duplicating the block at the end of the chain, if it is removed the
2502 // chain will have shrunk by one block.
2503 BlockChain::iterator ChainEnd = Chain.end();
2504 DupBB = *(--ChainEnd);
2505 // Now try to duplicate again.
2506 if (ChainEnd == Chain.begin())
2507 break;
2508 DupPred = *std::prev(ChainEnd);
2509 Removed = maybeTailDuplicateBlock(DupBB, DupPred, Chain, BlockFilter,
2510 PrevUnplacedBlockIt,
2511 DuplicatedToLPred);
2512 }
2513 // If BB was duplicated into LPred, it is now scheduled. But because it was
2514 // removed, markChainSuccessors won't be called for its chain. Instead we
2515 // call markBlockSuccessors for LPred to achieve the same effect. This must go
2516 // at the end because repeating the tail duplication can increase the number
2517 // of unscheduled predecessors.
2518 LPred = *std::prev(Chain.end());
2519 if (DuplicatedToOriginalLPred)
2520 markBlockSuccessors(Chain, LPred, LoopHeaderBB, BlockFilter);
2521 return true;
2522}
2523
2524/// Tail duplicate \p BB into (some) predecessors if profitable.
2525/// \p BB - Basic block that may be duplicated
2526/// \p LPred - Chosen layout predecessor of \p BB
2527/// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
2528/// \p BlockFilter - Set of blocks that belong to the loop being laid out.
2529/// Used to identify which blocks to update predecessor
2530/// counts.
2531/// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
2532/// chosen in the given order due to unnatural CFG
2533/// only needed if \p BB is removed and
2534/// \p PrevUnplacedBlockIt pointed to \p BB.
2535/// \p DuplicatedToLPred - True if the block was duplicated into LPred. Will
2536/// only be true if the block was removed.
2537/// \return - True if the block was duplicated into all preds and removed.
2538bool MachineBlockPlacement::maybeTailDuplicateBlock(
2539 MachineBasicBlock *BB, MachineBasicBlock *LPred,
Kyle Butte9425c4f2017-02-04 02:26:32 +00002540 BlockChain &Chain, BlockFilterSet *BlockFilter,
Kyle Butt0846e562016-10-11 20:36:43 +00002541 MachineFunction::iterator &PrevUnplacedBlockIt,
2542 bool &DuplicatedToLPred) {
Kyle Butt0846e562016-10-11 20:36:43 +00002543 DuplicatedToLPred = false;
Kyle Buttc7d67eef2017-02-04 02:26:34 +00002544 if (!shouldTailDuplicate(BB))
2545 return false;
2546
Kyle Butt0846e562016-10-11 20:36:43 +00002547 DEBUG(dbgs() << "Redoing tail duplication for Succ#"
2548 << BB->getNumber() << "\n");
Kyle Buttb15c0662017-01-31 23:48:32 +00002549
Kyle Butt0846e562016-10-11 20:36:43 +00002550 // This has to be a callback because none of it can be done after
2551 // BB is deleted.
2552 bool Removed = false;
2553 auto RemovalCallback =
2554 [&](MachineBasicBlock *RemBB) {
2555 // Signal to outer function
2556 Removed = true;
2557
2558 // Conservative default.
2559 bool InWorkList = true;
2560 // Remove from the Chain and Chain Map
2561 if (BlockToChain.count(RemBB)) {
2562 BlockChain *Chain = BlockToChain[RemBB];
2563 InWorkList = Chain->UnscheduledPredecessors == 0;
2564 Chain->remove(RemBB);
2565 BlockToChain.erase(RemBB);
2566 }
2567
2568 // Handle the unplaced block iterator
2569 if (&(*PrevUnplacedBlockIt) == RemBB) {
2570 PrevUnplacedBlockIt++;
2571 }
2572
2573 // Handle the Work Lists
2574 if (InWorkList) {
2575 SmallVectorImpl<MachineBasicBlock *> &RemoveList = BlockWorkList;
2576 if (RemBB->isEHPad())
2577 RemoveList = EHPadWorkList;
2578 RemoveList.erase(
2579 remove_if(RemoveList,
2580 [RemBB](MachineBasicBlock *BB) {return BB == RemBB;}),
2581 RemoveList.end());
2582 }
2583
2584 // Handle the filter set
2585 if (BlockFilter) {
Rong Xu66827422016-11-16 20:50:06 +00002586 BlockFilter->remove(RemBB);
Kyle Butt0846e562016-10-11 20:36:43 +00002587 }
2588
2589 // Remove the block from loop info.
2590 MLI->removeBlock(RemBB);
Kyle Buttab9cca72016-10-27 21:37:20 +00002591 if (RemBB == PreferredLoopExit)
2592 PreferredLoopExit = nullptr;
Kyle Butt0846e562016-10-11 20:36:43 +00002593
Kyle Butt0846e562016-10-11 20:36:43 +00002594 DEBUG(dbgs() << "TailDuplicator deleted block: "
2595 << getBlockName(RemBB) << "\n");
2596 };
2597 auto RemovalCallbackRef =
2598 llvm::function_ref<void(MachineBasicBlock*)>(RemovalCallback);
2599
2600 SmallVector<MachineBasicBlock *, 8> DuplicatedPreds;
Kyle Buttb15c0662017-01-31 23:48:32 +00002601 bool IsSimple = TailDup.isSimpleBB(BB);
Kyle Butt0846e562016-10-11 20:36:43 +00002602 TailDup.tailDuplicateAndUpdate(IsSimple, BB, LPred,
2603 &DuplicatedPreds, &RemovalCallbackRef);
2604
2605 // Update UnscheduledPredecessors to reflect tail-duplication.
2606 DuplicatedToLPred = false;
2607 for (MachineBasicBlock *Pred : DuplicatedPreds) {
2608 // We're only looking for unscheduled predecessors that match the filter.
2609 BlockChain* PredChain = BlockToChain[Pred];
2610 if (Pred == LPred)
2611 DuplicatedToLPred = true;
2612 if (Pred == LPred || (BlockFilter && !BlockFilter->count(Pred))
2613 || PredChain == &Chain)
2614 continue;
2615 for (MachineBasicBlock *NewSucc : Pred->successors()) {
2616 if (BlockFilter && !BlockFilter->count(NewSucc))
2617 continue;
2618 BlockChain *NewChain = BlockToChain[NewSucc];
2619 if (NewChain != &Chain && NewChain != PredChain)
2620 NewChain->UnscheduledPredecessors++;
2621 }
2622 }
2623 return Removed;
2624}
2625
Xinliang David Li52530a72016-06-13 22:23:44 +00002626bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &MF) {
2627 if (skipFunction(*MF.getFunction()))
Andrew Kaylor50271f72016-05-03 22:32:30 +00002628 return false;
2629
Chandler Carruth10281422011-10-21 06:46:38 +00002630 // Check for single-block functions and skip them.
Xinliang David Li52530a72016-06-13 22:23:44 +00002631 if (std::next(MF.begin()) == MF.end())
Chandler Carruth10281422011-10-21 06:46:38 +00002632 return false;
2633
Xinliang David Li52530a72016-06-13 22:23:44 +00002634 F = &MF;
Chandler Carruth10281422011-10-21 06:46:38 +00002635 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002636 MBFI = llvm::make_unique<BranchFolder::MBFIWrapper>(
2637 getAnalysis<MachineBlockFrequencyInfo>());
Chandler Carruth8b9737c2011-10-21 08:57:37 +00002638 MLI = &getAnalysis<MachineLoopInfo>();
Xinliang David Li52530a72016-06-13 22:23:44 +00002639 TII = MF.getSubtarget().getInstrInfo();
2640 TLI = MF.getSubtarget().getTargetLowering();
Kyle Buttb15c0662017-01-31 23:48:32 +00002641 MPDT = nullptr;
Eric Christopher690f8e52016-11-01 22:15:50 +00002642
2643 // Initialize PreferredLoopExit to nullptr here since it may never be set if
2644 // there are no MachineLoops.
2645 PreferredLoopExit = nullptr;
2646
Kyle Butt0846e562016-10-11 20:36:43 +00002647 if (TailDupPlacement) {
Kyle Buttb15c0662017-01-31 23:48:32 +00002648 MPDT = &getAnalysis<MachinePostDominatorTree>();
2649 unsigned TailDupSize = TailDupPlacementThreshold;
Kyle Butt0846e562016-10-11 20:36:43 +00002650 if (MF.getFunction()->optForSize())
2651 TailDupSize = 1;
2652 TailDup.initMF(MF, MBPI, /* LayoutMode */ true, TailDupSize);
Kyle Butt1fa60302017-03-03 01:00:22 +00002653 precomputeTriangleChains();
Kyle Butt0846e562016-10-11 20:36:43 +00002654 }
2655
Chandler Carruth10281422011-10-21 06:46:38 +00002656 assert(BlockToChain.empty());
Chandler Carruth10281422011-10-21 06:46:38 +00002657
Xinliang David Li52530a72016-06-13 22:23:44 +00002658 buildCFGChains();
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002659
2660 // Changing the layout can create new tail merging opportunities.
2661 TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
2662 // TailMerge can create jump into if branches that make CFG irreducible for
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00002663 // HW that requires structured CFG.
Xinliang David Li52530a72016-06-13 22:23:44 +00002664 bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002665 PassConfig->getEnableTailMerge() &&
2666 BranchFoldPlacement;
2667 // No tail merging opportunities if the block number is less than four.
Xinliang David Li52530a72016-06-13 22:23:44 +00002668 if (MF.size() > 3 && EnableTailMerge) {
Kyle Buttb15c0662017-01-31 23:48:32 +00002669 unsigned TailMergeSize = TailDupPlacementThreshold + 1;
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002670 BranchFolder BF(/*EnableTailMerge=*/true, /*CommonHoist=*/false, *MBFI,
Kyle Butt64e42812016-08-18 18:57:29 +00002671 *MBPI, TailMergeSize);
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002672
Xinliang David Li52530a72016-06-13 22:23:44 +00002673 if (BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002674 getAnalysisIfAvailable<MachineModuleInfo>(), MLI,
2675 /*AfterBlockPlacement=*/true)) {
2676 // Redo the layout if tail merging creates/removes/moves blocks.
2677 BlockToChain.clear();
Kyle Butt13937612017-03-02 21:44:24 +00002678 // Must redo the post-dominator tree if blocks were changed.
Kyle Buttb15c0662017-01-31 23:48:32 +00002679 if (MPDT)
2680 MPDT->runOnMachineFunction(MF);
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002681 ChainAllocator.DestroyAll();
Xinliang David Li52530a72016-06-13 22:23:44 +00002682 buildCFGChains();
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002683 }
2684 }
2685
Xinliang David Li52530a72016-06-13 22:23:44 +00002686 optimizeBranches();
2687 alignBlocks();
Chandler Carruth10281422011-10-21 06:46:38 +00002688
Chandler Carruth10281422011-10-21 06:46:38 +00002689 BlockToChain.clear();
Chandler Carruthfd9b4d92011-11-14 10:57:23 +00002690 ChainAllocator.DestroyAll();
Chandler Carruth10281422011-10-21 06:46:38 +00002691
Nadav Rotemc0adc9f2013-04-12 01:24:16 +00002692 if (AlignAllBlock)
2693 // Align all of the blocks in the function to a specific alignment.
Xinliang David Li52530a72016-06-13 22:23:44 +00002694 for (MachineBasicBlock &MBB : MF)
Chandler Carruth7a715da2015-03-05 03:19:05 +00002695 MBB.setAlignment(AlignAllBlock);
Geoff Berry10494ac2016-01-21 17:25:52 +00002696 else if (AlignAllNonFallThruBlocks) {
2697 // Align all of the blocks that have no fall-through predecessors to a
2698 // specific alignment.
Xinliang David Li52530a72016-06-13 22:23:44 +00002699 for (auto MBI = std::next(MF.begin()), MBE = MF.end(); MBI != MBE; ++MBI) {
Geoff Berry10494ac2016-01-21 17:25:52 +00002700 auto LayoutPred = std::prev(MBI);
2701 if (!LayoutPred->isSuccessor(&*MBI))
2702 MBI->setAlignment(AlignAllNonFallThruBlocks);
2703 }
2704 }
Xinliang David Lifd3f6452017-01-29 01:57:02 +00002705 if (ViewBlockLayoutWithBFI != GVDT_None &&
2706 (ViewBlockFreqFuncName.empty() ||
2707 F->getFunction()->getName().equals(ViewBlockFreqFuncName))) {
Xinliang David Li538d6662017-02-15 19:21:04 +00002708 MBFI->view("MBP." + MF.getName(), false);
Xinliang David Lifd3f6452017-01-29 01:57:02 +00002709 }
Xinliang David Lifd3f6452017-01-29 01:57:02 +00002710
Nadav Rotemc0adc9f2013-04-12 01:24:16 +00002711
Chandler Carruth10281422011-10-21 06:46:38 +00002712 // We always return true as we have no way to track whether the final order
2713 // differs from the original order.
2714 return true;
2715}
Chandler Carruthae4e8002011-11-02 07:17:12 +00002716
2717namespace {
2718/// \brief A pass to compute block placement statistics.
2719///
2720/// A separate pass to compute interesting statistics for evaluating block
2721/// placement. This is separate from the actual placement pass so that they can
Benjamin Kramerbde91762012-06-02 10:20:22 +00002722/// be computed in the absence of any placement transformations or when using
Chandler Carruthae4e8002011-11-02 07:17:12 +00002723/// alternative placement strategies.
2724class MachineBlockPlacementStats : public MachineFunctionPass {
2725 /// \brief A handle to the branch probability pass.
2726 const MachineBranchProbabilityInfo *MBPI;
2727
2728 /// \brief A handle to the function-wide block frequency pass.
2729 const MachineBlockFrequencyInfo *MBFI;
2730
2731public:
2732 static char ID; // Pass identification, replacement for typeid
2733 MachineBlockPlacementStats() : MachineFunctionPass(ID) {
2734 initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
2735 }
2736
Craig Topper4584cd52014-03-07 09:26:03 +00002737 bool runOnMachineFunction(MachineFunction &F) override;
Chandler Carruthae4e8002011-11-02 07:17:12 +00002738
Craig Topper4584cd52014-03-07 09:26:03 +00002739 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruthae4e8002011-11-02 07:17:12 +00002740 AU.addRequired<MachineBranchProbabilityInfo>();
2741 AU.addRequired<MachineBlockFrequencyInfo>();
2742 AU.setPreservesAll();
2743 MachineFunctionPass::getAnalysisUsage(AU);
2744 }
Chandler Carruthae4e8002011-11-02 07:17:12 +00002745};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00002746}
Chandler Carruthae4e8002011-11-02 07:17:12 +00002747
2748char MachineBlockPlacementStats::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +00002749char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
Chandler Carruthae4e8002011-11-02 07:17:12 +00002750INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
2751 "Basic Block Placement Stats", false, false)
2752INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
2753INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
2754INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
2755 "Basic Block Placement Stats", false, false)
2756
Chandler Carruthae4e8002011-11-02 07:17:12 +00002757bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
2758 // Check for single-block functions and skip them.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002759 if (std::next(F.begin()) == F.end())
Chandler Carruthae4e8002011-11-02 07:17:12 +00002760 return false;
2761
2762 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
2763 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
2764
Chandler Carruth7a715da2015-03-05 03:19:05 +00002765 for (MachineBasicBlock &MBB : F) {
2766 BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00002767 Statistic &NumBranches =
Chandler Carruth7a715da2015-03-05 03:19:05 +00002768 (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00002769 Statistic &BranchTakenFreq =
Chandler Carruth7a715da2015-03-05 03:19:05 +00002770 (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
2771 for (MachineBasicBlock *Succ : MBB.successors()) {
Chandler Carruthae4e8002011-11-02 07:17:12 +00002772 // Skip if this successor is a fallthrough.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002773 if (MBB.isLayoutSuccessor(Succ))
Chandler Carruthae4e8002011-11-02 07:17:12 +00002774 continue;
2775
Chandler Carruth7a715da2015-03-05 03:19:05 +00002776 BlockFrequency EdgeFreq =
2777 BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
Chandler Carruthae4e8002011-11-02 07:17:12 +00002778 ++NumBranches;
2779 BranchTakenFreq += EdgeFreq.getFrequency();
2780 }
2781 }
2782
2783 return false;
2784}