blob: 74a64631cb915b7ea7722871fecf05661e1d3c14 [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 Buttb15c0662017-01-31 23:48:32 +000053#include <functional>
54#include <utility>
Chandler Carruth10281422011-10-21 06:46:38 +000055using namespace llvm;
56
Chandler Carruthd0dced52015-03-05 02:28:25 +000057#define DEBUG_TYPE "block-placement"
Chandler Carruth1b9dde02014-04-22 02:02:50 +000058
Chandler Carruthae4e8002011-11-02 07:17:12 +000059STATISTIC(NumCondBranches, "Number of conditional branches");
Craig Topper77ec0772015-09-16 03:52:32 +000060STATISTIC(NumUncondBranches, "Number of unconditional branches");
Chandler Carruthae4e8002011-11-02 07:17:12 +000061STATISTIC(CondBranchTakenFreq,
62 "Potential frequency of taking conditional branches");
63STATISTIC(UncondBranchTakenFreq,
64 "Potential frequency of taking unconditional branches");
65
Nadav Rotemc3b0f502013-04-12 00:48:32 +000066static cl::opt<unsigned> AlignAllBlock("align-all-blocks",
67 cl::desc("Force the alignment of all "
68 "blocks in the function."),
69 cl::init(0), cl::Hidden);
70
Geoff Berry10494ac2016-01-21 17:25:52 +000071static cl::opt<unsigned> AlignAllNonFallThruBlocks(
72 "align-all-nofallthru-blocks",
73 cl::desc("Force the alignment of all "
74 "blocks that have no fall-through predecessors (i.e. don't add "
75 "nops that are executed)."),
76 cl::init(0), cl::Hidden);
77
Benjamin Kramerc8160d62013-11-20 19:08:44 +000078// FIXME: Find a good default for this flag and remove the flag.
Chandler Carruth2fc3fe12015-03-05 02:35:31 +000079static cl::opt<unsigned> ExitBlockBias(
80 "block-placement-exit-block-bias",
81 cl::desc("Block frequency percentage a loop exit block needs "
82 "over the original exit to be considered the new exit."),
83 cl::init(0), cl::Hidden);
Benjamin Kramerc8160d62013-11-20 19:08:44 +000084
Sjoerd Meijer5e11a182016-07-27 08:49:23 +000085// Definition:
86// - Outlining: placement of a basic block outside the chain or hot path.
87
Cong Houb90b9e02015-11-02 21:24:00 +000088static cl::opt<unsigned> LoopToColdBlockRatio(
89 "loop-to-cold-block-ratio",
90 cl::desc("Outline loop blocks from loop chain if (frequency of loop) / "
91 "(frequency of block) is greater than this ratio"),
92 cl::init(5), cl::Hidden);
93
Cong Hou7745dbc2015-10-19 23:16:40 +000094static cl::opt<bool>
95 PreciseRotationCost("precise-rotation-cost",
96 cl::desc("Model the cost of loop rotation more "
97 "precisely by using profile data."),
98 cl::init(false), cl::Hidden);
Xinliang David Lif0ab6df2016-05-12 02:04:41 +000099static cl::opt<bool>
100 ForcePreciseRotationCost("force-precise-rotation-cost",
Xinliang David Lib840bb82016-05-12 16:39:02 +0000101 cl::desc("Force the use of precise cost "
102 "loop rotation strategy."),
Xinliang David Lif0ab6df2016-05-12 02:04:41 +0000103 cl::init(false), cl::Hidden);
Cong Hou7745dbc2015-10-19 23:16:40 +0000104
105static cl::opt<unsigned> MisfetchCost(
106 "misfetch-cost",
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000107 cl::desc("Cost that models the probabilistic risk of an instruction "
Cong Hou7745dbc2015-10-19 23:16:40 +0000108 "misfetch due to a jump comparing to falling through, whose cost "
109 "is zero."),
110 cl::init(1), cl::Hidden);
111
112static cl::opt<unsigned> JumpInstCost("jump-inst-cost",
113 cl::desc("Cost of jump instructions."),
114 cl::init(1), cl::Hidden);
Kyle Butt0846e562016-10-11 20:36:43 +0000115static cl::opt<bool>
116TailDupPlacement("tail-dup-placement",
117 cl::desc("Perform tail duplication during placement. "
118 "Creates more fallthrough opportunites in "
119 "outline branches."),
120 cl::init(true), cl::Hidden);
Cong Hou7745dbc2015-10-19 23:16:40 +0000121
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000122static cl::opt<bool>
123BranchFoldPlacement("branch-fold-placement",
124 cl::desc("Perform branch folding during placement. "
125 "Reduces code size."),
126 cl::init(true), cl::Hidden);
127
Kyle Butt0846e562016-10-11 20:36:43 +0000128// Heuristic for tail duplication.
Kyle Buttb15c0662017-01-31 23:48:32 +0000129static cl::opt<unsigned> TailDupPlacementThreshold(
Kyle Butt0846e562016-10-11 20:36:43 +0000130 "tail-dup-placement-threshold",
131 cl::desc("Instruction cutoff for tail duplication during layout. "
132 "Tail merging during layout is forced to have a threshold "
133 "that won't conflict."), cl::init(2),
134 cl::Hidden);
135
Kyle Buttb15c0662017-01-31 23:48:32 +0000136// Heuristic for tail duplication.
137static cl::opt<unsigned> TailDupPlacementPenalty(
138 "tail-dup-placement-penalty",
139 cl::desc("Cost penalty for blocks that can avoid breaking CFG by copying. "
140 "Copying can increase fallthrough, but it also increases icache "
141 "pressure. This parameter controls the penalty to account for that. "
142 "Percent as integer."),
143 cl::init(2),
144 cl::Hidden);
145
Xinliang David Liff287372016-06-03 23:48:36 +0000146extern cl::opt<unsigned> StaticLikelyProb;
Dehao Chen9f2bdfb2016-06-14 22:27:17 +0000147extern cl::opt<unsigned> ProfileLikelyProb;
Xinliang David Liff287372016-06-03 23:48:36 +0000148
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000149// Internal option used to control BFI display only after MBP pass.
150// Defined in CodeGen/MachineBlockFrequencyInfo.cpp:
151// -view-block-layout-with-bfi=
Xinliang David Lifd3f6452017-01-29 01:57:02 +0000152extern cl::opt<GVDAGType> ViewBlockLayoutWithBFI;
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000153
154// Command line option to specify the name of the function for CFG dump
155// Defined in Analysis/BlockFrequencyInfo.cpp: -view-bfi-func-name=
Xinliang David Lifd3f6452017-01-29 01:57:02 +0000156extern cl::opt<std::string> ViewBlockFreqFuncName;
Xinliang David Lifd3f6452017-01-29 01:57:02 +0000157
Chandler Carruth10281422011-10-21 06:46:38 +0000158namespace {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000159class BlockChain;
Chandler Carruth10281422011-10-21 06:46:38 +0000160/// \brief Type for our function-wide basic block -> block chain mapping.
Kyle Butte9425c4f2017-02-04 02:26:32 +0000161typedef DenseMap<const MachineBasicBlock *, BlockChain *> BlockToChainMapType;
Chandler Carruth10281422011-10-21 06:46:38 +0000162}
163
164namespace {
165/// \brief A chain of blocks which will be laid out contiguously.
166///
167/// This is the datastructure representing a chain of consecutive blocks that
168/// are profitable to layout together in order to maximize fallthrough
Chandler Carruth9139f442012-06-26 05:16:37 +0000169/// probabilities and code locality. We also can use a block chain to represent
170/// a sequence of basic blocks which have some external (correctness)
171/// requirement for sequential layout.
Chandler Carruth10281422011-10-21 06:46:38 +0000172///
Chandler Carruth9139f442012-06-26 05:16:37 +0000173/// Chains can be built around a single basic block and can be merged to grow
174/// them. They participate in a block-to-chain mapping, which is updated
175/// automatically as chains are merged together.
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000176class BlockChain {
177 /// \brief The sequence of blocks belonging to this chain.
Chandler Carruth10281422011-10-21 06:46:38 +0000178 ///
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000179 /// This is the sequence of blocks for a particular chain. These will be laid
180 /// out in-order within the function.
181 SmallVector<MachineBasicBlock *, 4> Blocks;
Chandler Carruth10281422011-10-21 06:46:38 +0000182
183 /// \brief A handle to the function-wide basic block to block chain mapping.
184 ///
185 /// This is retained in each block chain to simplify the computation of child
186 /// block chains for SCC-formation and iteration. We store the edges to child
187 /// basic blocks, and map them back to their associated chains using this
188 /// structure.
189 BlockToChainMapType &BlockToChain;
190
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000191public:
Chandler Carruth10281422011-10-21 06:46:38 +0000192 /// \brief Construct a new BlockChain.
193 ///
194 /// This builds a new block chain representing a single basic block in the
195 /// function. It also registers itself as the chain that block participates
196 /// in with the BlockToChain mapping.
197 BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
Philip Reamesae27b232016-03-03 00:58:43 +0000198 : Blocks(1, BB), BlockToChain(BlockToChain), UnscheduledPredecessors(0) {
Chandler Carruth10281422011-10-21 06:46:38 +0000199 assert(BB && "Cannot create a chain with a null basic block");
200 BlockToChain[BB] = this;
201 }
202
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000203 /// \brief Iterator over blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000204 typedef SmallVectorImpl<MachineBasicBlock *>::iterator iterator;
Kyle Butte9425c4f2017-02-04 02:26:32 +0000205 typedef SmallVectorImpl<MachineBasicBlock *>::const_iterator const_iterator;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000206
207 /// \brief Beginning of blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000208 iterator begin() { return Blocks.begin(); }
Kyle Butte9425c4f2017-02-04 02:26:32 +0000209 const_iterator begin() const { return Blocks.begin(); }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000210
211 /// \brief End of blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000212 iterator end() { return Blocks.end(); }
Kyle Butte9425c4f2017-02-04 02:26:32 +0000213 const_iterator end() const { return Blocks.end(); }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000214
Kyle Butt0846e562016-10-11 20:36:43 +0000215 bool remove(MachineBasicBlock* BB) {
216 for(iterator i = begin(); i != end(); ++i) {
217 if (*i == BB) {
218 Blocks.erase(i);
219 return true;
220 }
221 }
222 return false;
223 }
224
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000225 /// \brief Merge a block chain into this one.
Chandler Carruth10281422011-10-21 06:46:38 +0000226 ///
227 /// This routine merges a block chain into this one. It takes care of forming
228 /// a contiguous sequence of basic blocks, updating the edge list, and
229 /// updating the block -> chain mapping. It does not free or tear down the
230 /// old chain, but the old chain's block list is no longer valid.
Jakub Staszak90616162011-12-21 23:02:08 +0000231 void merge(MachineBasicBlock *BB, BlockChain *Chain) {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000232 assert(BB);
233 assert(!Blocks.empty());
Chandler Carruth10281422011-10-21 06:46:38 +0000234
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000235 // Fast path in case we don't have a chain already.
236 if (!Chain) {
237 assert(!BlockToChain[BB]);
238 Blocks.push_back(BB);
239 BlockToChain[BB] = this;
240 return;
Chandler Carruth10281422011-10-21 06:46:38 +0000241 }
242
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000243 assert(BB == *Chain->begin());
244 assert(Chain->begin() != Chain->end());
Chandler Carruth10281422011-10-21 06:46:38 +0000245
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000246 // Update the incoming blocks to point to this chain, and add them to the
247 // chain structure.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000248 for (MachineBasicBlock *ChainBB : *Chain) {
249 Blocks.push_back(ChainBB);
250 assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain");
251 BlockToChain[ChainBB] = this;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000252 }
Chandler Carruth10281422011-10-21 06:46:38 +0000253 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000254
Chandler Carruth49158902012-04-08 14:37:01 +0000255#ifndef NDEBUG
256 /// \brief Dump the blocks in this chain.
Nico Weber7408c702014-01-03 22:53:37 +0000257 LLVM_DUMP_METHOD void dump() {
Chandler Carruth7a715da2015-03-05 03:19:05 +0000258 for (MachineBasicBlock *MBB : *this)
259 MBB->dump();
Chandler Carruth49158902012-04-08 14:37:01 +0000260 }
261#endif // NDEBUG
262
Philip Reamesae27b232016-03-03 00:58:43 +0000263 /// \brief Count of predecessors of any block within the chain which have not
264 /// yet been scheduled. In general, we will delay scheduling this chain
265 /// until those predecessors are scheduled (or we find a sufficiently good
266 /// reason to override this heuristic.) Note that when forming loop chains,
267 /// blocks outside the loop are ignored and treated as if they were already
268 /// scheduled.
Chandler Carruth8d150782011-11-13 11:20:44 +0000269 ///
Philip Reamesae27b232016-03-03 00:58:43 +0000270 /// Note: This field is reinitialized multiple times - once for each loop,
271 /// and then once for the function as a whole.
272 unsigned UnscheduledPredecessors;
Chandler Carruth10281422011-10-21 06:46:38 +0000273};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000274}
Chandler Carruth10281422011-10-21 06:46:38 +0000275
276namespace {
277class MachineBlockPlacement : public MachineFunctionPass {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000278 /// \brief A typedef for a block filter set.
Kyle Butte9425c4f2017-02-04 02:26:32 +0000279 typedef SmallSetVector<const MachineBasicBlock *, 16> BlockFilterSet;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000280
Kyle Buttb15c0662017-01-31 23:48:32 +0000281 /// Pair struct containing basic block and taildup profitiability
282 struct BlockAndTailDupResult {
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000283 MachineBasicBlock *BB;
Kyle Buttb15c0662017-01-31 23:48:32 +0000284 bool ShouldTailDup;
285 };
286
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000287 /// Triple struct containing edge weight and the edge.
288 struct WeightedEdge {
289 BlockFrequency Weight;
290 MachineBasicBlock *Src;
291 MachineBasicBlock *Dest;
292 };
293
Xinliang David Li93926ac2016-07-01 05:46:48 +0000294 /// \brief work lists of blocks that are ready to be laid out
295 SmallVector<MachineBasicBlock *, 16> BlockWorkList;
296 SmallVector<MachineBasicBlock *, 16> EHPadWorkList;
297
Kyle Buttebe6cc42017-02-23 21:22:24 +0000298 /// Edges that have already been computed as optimal.
299 DenseMap<const MachineBasicBlock *, BlockAndTailDupResult> ComputedEdges;
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000300
Xinliang David Li52530a72016-06-13 22:23:44 +0000301 /// \brief Machine Function
302 MachineFunction *F;
303
Chandler Carruth10281422011-10-21 06:46:38 +0000304 /// \brief A handle to the branch probability pass.
305 const MachineBranchProbabilityInfo *MBPI;
306
307 /// \brief A handle to the function-wide block frequency pass.
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000308 std::unique_ptr<BranchFolder::MBFIWrapper> MBFI;
Chandler Carruth10281422011-10-21 06:46:38 +0000309
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000310 /// \brief A handle to the loop info.
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000311 MachineLoopInfo *MLI;
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000312
Kyle Buttab9cca72016-10-27 21:37:20 +0000313 /// \brief Preferred loop exit.
314 /// Member variable for convenience. It may be removed by duplication deep
315 /// in the call stack.
316 MachineBasicBlock *PreferredLoopExit;
317
Chandler Carruth10281422011-10-21 06:46:38 +0000318 /// \brief A handle to the target's instruction info.
319 const TargetInstrInfo *TII;
320
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000321 /// \brief A handle to the target's lowering info.
Benjamin Kramer56b31bd2013-01-11 20:05:37 +0000322 const TargetLoweringBase *TLI;
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000323
Kyle Buttb15c0662017-01-31 23:48:32 +0000324 /// \brief A handle to the post dominator tree.
325 MachinePostDominatorTree *MPDT;
326
Kyle Butt0846e562016-10-11 20:36:43 +0000327 /// \brief Duplicator used to duplicate tails during placement.
328 ///
329 /// Placement decisions can open up new tail duplication opportunities, but
330 /// since tail duplication affects placement decisions of later blocks, it
331 /// must be done inline.
332 TailDuplicator TailDup;
333
Chandler Carruth10281422011-10-21 06:46:38 +0000334 /// \brief Allocator and owner of BlockChain structures.
335 ///
Chandler Carruth9139f442012-06-26 05:16:37 +0000336 /// We build BlockChains lazily while processing the loop structure of
337 /// a function. To reduce malloc traffic, we allocate them using this
338 /// slab-like allocator, and destroy them after the pass completes. An
339 /// important guarantee is that this allocator produces stable pointers to
340 /// the chains.
Chandler Carruth10281422011-10-21 06:46:38 +0000341 SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
342
343 /// \brief Function wide BasicBlock to BlockChain mapping.
344 ///
345 /// This mapping allows efficiently moving from any given basic block to the
346 /// BlockChain it participates in, if any. We use it to, among other things,
347 /// allow implicitly defining edges between chains as the existing edges
348 /// between basic blocks.
Kyle Butte9425c4f2017-02-04 02:26:32 +0000349 DenseMap<const MachineBasicBlock *, BlockChain *> BlockToChain;
Chandler Carruth10281422011-10-21 06:46:38 +0000350
Sanjoy Dasd7389d62016-12-15 05:08:57 +0000351#ifndef NDEBUG
352 /// The set of basic blocks that have terminators that cannot be fully
353 /// analyzed. These basic blocks cannot be re-ordered safely by
354 /// MachineBlockPlacement, and we must preserve physical layout of these
355 /// blocks and their successors through the pass.
356 SmallPtrSet<MachineBasicBlock *, 4> BlocksWithUnanalyzableExits;
357#endif
358
Kyle Butt0846e562016-10-11 20:36:43 +0000359 /// Decrease the UnscheduledPredecessors count for all blocks in chain, and
360 /// if the count goes to 0, add them to the appropriate work list.
Kyle Butte9425c4f2017-02-04 02:26:32 +0000361 void markChainSuccessors(
362 const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB,
363 const BlockFilterSet *BlockFilter = nullptr);
Kyle Butt0846e562016-10-11 20:36:43 +0000364
365 /// Decrease the UnscheduledPredecessors count for a single block, and
366 /// if the count goes to 0, add them to the appropriate work list.
367 void markBlockSuccessors(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000368 const BlockChain &Chain, const MachineBasicBlock *BB,
369 const MachineBasicBlock *LoopHeaderBB,
Kyle Butt0846e562016-10-11 20:36:43 +0000370 const BlockFilterSet *BlockFilter = nullptr);
371
Xinliang David Li594ffa32016-06-11 18:35:40 +0000372 BranchProbability
Kyle Butte9425c4f2017-02-04 02:26:32 +0000373 collectViableSuccessors(
374 const MachineBasicBlock *BB, const BlockChain &Chain,
375 const BlockFilterSet *BlockFilter,
376 SmallVector<MachineBasicBlock *, 4> &Successors);
377 bool shouldPredBlockBeOutlined(
378 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
379 const BlockChain &Chain, const BlockFilterSet *BlockFilter,
380 BranchProbability SuccProb, BranchProbability HotProb);
Kyle Butt0846e562016-10-11 20:36:43 +0000381 bool repeatedlyTailDuplicateBlock(
382 MachineBasicBlock *BB, MachineBasicBlock *&LPred,
Kyle Butte9425c4f2017-02-04 02:26:32 +0000383 const MachineBasicBlock *LoopHeaderBB,
Kyle Butt0846e562016-10-11 20:36:43 +0000384 BlockChain &Chain, BlockFilterSet *BlockFilter,
385 MachineFunction::iterator &PrevUnplacedBlockIt);
Kyle Butte9425c4f2017-02-04 02:26:32 +0000386 bool maybeTailDuplicateBlock(
387 MachineBasicBlock *BB, MachineBasicBlock *LPred,
388 BlockChain &Chain, BlockFilterSet *BlockFilter,
389 MachineFunction::iterator &PrevUnplacedBlockIt,
390 bool &DuplicatedToPred);
391 bool hasBetterLayoutPredecessor(
392 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
393 const BlockChain &SuccChain, BranchProbability SuccProb,
394 BranchProbability RealSuccProb, const BlockChain &Chain,
395 const BlockFilterSet *BlockFilter);
396 BlockAndTailDupResult selectBestSuccessor(
397 const MachineBasicBlock *BB, const BlockChain &Chain,
398 const BlockFilterSet *BlockFilter);
399 MachineBasicBlock *selectBestCandidateBlock(
400 const BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList);
401 MachineBasicBlock *getFirstUnplacedBlock(
402 const BlockChain &PlacedChain,
403 MachineFunction::iterator &PrevUnplacedBlockIt,
404 const BlockFilterSet *BlockFilter);
Amaury Secheteae09c22016-03-14 21:24:11 +0000405
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000406 /// \brief Add a basic block to the work list if it is appropriate.
Amaury Secheteae09c22016-03-14 21:24:11 +0000407 ///
408 /// If the optional parameter BlockFilter is provided, only MBB
409 /// present in the set will be added to the worklist. If nullptr
410 /// is provided, no filtering occurs.
Kyle Butte9425c4f2017-02-04 02:26:32 +0000411 void fillWorkLists(const MachineBasicBlock *MBB,
Amaury Secheteae09c22016-03-14 21:24:11 +0000412 SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
Amaury Secheteae09c22016-03-14 21:24:11 +0000413 const BlockFilterSet *BlockFilter);
Kyle Butte9425c4f2017-02-04 02:26:32 +0000414 void buildChain(const MachineBasicBlock *BB, BlockChain &Chain,
Kyle Butt0846e562016-10-11 20:36:43 +0000415 BlockFilterSet *BlockFilter = nullptr);
Kyle Butte9425c4f2017-02-04 02:26:32 +0000416 MachineBasicBlock *findBestLoopTop(
417 const MachineLoop &L, const BlockFilterSet &LoopBlockSet);
418 MachineBasicBlock *findBestLoopExit(
419 const MachineLoop &L, const BlockFilterSet &LoopBlockSet);
420 BlockFilterSet collectLoopBlockSet(const MachineLoop &L);
421 void buildLoopChains(const MachineLoop &L);
422 void rotateLoop(
423 BlockChain &LoopChain, const MachineBasicBlock *ExitingBB,
424 const BlockFilterSet &LoopBlockSet);
425 void rotateLoopWithProfile(
426 BlockChain &LoopChain, const MachineLoop &L,
427 const BlockFilterSet &LoopBlockSet);
Xinliang David Li52530a72016-06-13 22:23:44 +0000428 void buildCFGChains();
429 void optimizeBranches();
430 void alignBlocks();
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000431 /// Returns true if a block should be tail-duplicated to increase fallthrough
432 /// opportunities.
Kyle Buttb15c0662017-01-31 23:48:32 +0000433 bool shouldTailDuplicate(MachineBasicBlock *BB);
434 /// Check the edge frequencies to see if tail duplication will increase
435 /// fallthroughs.
436 bool isProfitableToTailDup(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000437 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
Kyle Buttb15c0662017-01-31 23:48:32 +0000438 BranchProbability AdjustedSumProb,
Kyle Butte9425c4f2017-02-04 02:26:32 +0000439 const BlockChain &Chain, const BlockFilterSet *BlockFilter);
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000440 /// Check for a trellis layout.
441 bool isTrellis(const MachineBasicBlock *BB,
442 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
443 const BlockChain &Chain, const BlockFilterSet *BlockFilter);
444 /// Get the best successor given a trellis layout.
445 BlockAndTailDupResult getBestTrellisSuccessor(
446 const MachineBasicBlock *BB,
447 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
448 BranchProbability AdjustedSumProb, const BlockChain &Chain,
449 const BlockFilterSet *BlockFilter);
450 /// Get the best pair of non-conflicting edges.
451 static std::pair<WeightedEdge, WeightedEdge> getBestNonConflictingEdges(
452 const MachineBasicBlock *BB,
453 SmallVector<SmallVector<WeightedEdge, 8>, 2> &Edges);
Kyle Buttb15c0662017-01-31 23:48:32 +0000454 /// Returns true if a block can tail duplicate into all unplaced
455 /// predecessors. Filters based on loop.
456 bool canTailDuplicateUnplacedPreds(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000457 const MachineBasicBlock *BB, MachineBasicBlock *Succ,
458 const BlockChain &Chain, const BlockFilterSet *BlockFilter);
Chandler Carruth10281422011-10-21 06:46:38 +0000459
460public:
461 static char ID; // Pass identification, replacement for typeid
462 MachineBlockPlacement() : MachineFunctionPass(ID) {
463 initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
464 }
465
Craig Topper4584cd52014-03-07 09:26:03 +0000466 bool runOnMachineFunction(MachineFunction &F) override;
Chandler Carruth10281422011-10-21 06:46:38 +0000467
Craig Topper4584cd52014-03-07 09:26:03 +0000468 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth10281422011-10-21 06:46:38 +0000469 AU.addRequired<MachineBranchProbabilityInfo>();
470 AU.addRequired<MachineBlockFrequencyInfo>();
Kyle Buttb15c0662017-01-31 23:48:32 +0000471 if (TailDupPlacement)
472 AU.addRequired<MachinePostDominatorTree>();
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000473 AU.addRequired<MachineLoopInfo>();
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000474 AU.addRequired<TargetPassConfig>();
Chandler Carruth10281422011-10-21 06:46:38 +0000475 MachineFunctionPass::getAnalysisUsage(AU);
476 }
Chandler Carruth10281422011-10-21 06:46:38 +0000477};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000478}
Chandler Carruth10281422011-10-21 06:46:38 +0000479
480char MachineBlockPlacement::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000481char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
Chandler Carruthd0dced52015-03-05 02:28:25 +0000482INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement",
Chandler Carruth10281422011-10-21 06:46:38 +0000483 "Branch Probability Basic Block Placement", false, false)
484INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
485INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
Kyle Buttb15c0662017-01-31 23:48:32 +0000486INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree)
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000487INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
Chandler Carruthd0dced52015-03-05 02:28:25 +0000488INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement",
Chandler Carruth10281422011-10-21 06:46:38 +0000489 "Branch Probability Basic Block Placement", false, false)
490
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000491#ifndef NDEBUG
492/// \brief Helper to print the name of a MBB.
493///
494/// Only used by debug logging.
Kyle Butte9425c4f2017-02-04 02:26:32 +0000495static std::string getBlockName(const MachineBasicBlock *BB) {
Alp Tokere69170a2014-06-26 22:52:05 +0000496 std::string Result;
497 raw_string_ostream OS(Result);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000498 OS << "BB#" << BB->getNumber();
Philip Reamesb9688f42016-03-02 21:45:13 +0000499 OS << " ('" << BB->getName() << "')";
Alp Tokere69170a2014-06-26 22:52:05 +0000500 OS.flush();
501 return Result;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000502}
503#endif
504
Chandler Carrutheb4ec3a2011-11-13 11:34:55 +0000505/// \brief Mark a chain's successors as having one fewer preds.
506///
507/// When a chain is being merged into the "placed" chain, this routine will
508/// quickly walk the successors of each block in the chain and mark them as
509/// having one fewer active predecessor. It also adds any successors of this
Kyle Butt0846e562016-10-11 20:36:43 +0000510/// chain which reach the zero-predecessor state to the appropriate worklist.
Chandler Carruth8d150782011-11-13 11:20:44 +0000511void MachineBlockPlacement::markChainSuccessors(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000512 const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB,
Jakub Staszak90616162011-12-21 23:02:08 +0000513 const BlockFilterSet *BlockFilter) {
Chandler Carruth8d150782011-11-13 11:20:44 +0000514 // Walk all the blocks in this chain, marking their successors as having
515 // a predecessor placed.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000516 for (MachineBasicBlock *MBB : Chain) {
Kyle Butt0846e562016-10-11 20:36:43 +0000517 markBlockSuccessors(Chain, MBB, LoopHeaderBB, BlockFilter);
518 }
519}
Chandler Carruth10281422011-10-21 06:46:38 +0000520
Kyle Butt0846e562016-10-11 20:36:43 +0000521/// \brief Mark a single block's successors as having one fewer preds.
522///
523/// Under normal circumstances, this is only called by markChainSuccessors,
524/// but if a block that was to be placed is completely tail-duplicated away,
525/// and was duplicated into the chain end, we need to redo markBlockSuccessors
526/// for just that block.
527void MachineBlockPlacement::markBlockSuccessors(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000528 const BlockChain &Chain, const MachineBasicBlock *MBB,
529 const MachineBasicBlock *LoopHeaderBB, const BlockFilterSet *BlockFilter) {
Kyle Butt0846e562016-10-11 20:36:43 +0000530 // Add any successors for which this is the only un-placed in-loop
531 // predecessor to the worklist as a viable candidate for CFG-neutral
532 // placement. No subsequent placement of this block will violate the CFG
533 // shape, so we get to use heuristics to choose a favorable placement.
534 for (MachineBasicBlock *Succ : MBB->successors()) {
535 if (BlockFilter && !BlockFilter->count(Succ))
536 continue;
537 BlockChain &SuccChain = *BlockToChain[Succ];
538 // Disregard edges within a fixed chain, or edges to the loop header.
539 if (&Chain == &SuccChain || Succ == LoopHeaderBB)
540 continue;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000541
Kyle Butt0846e562016-10-11 20:36:43 +0000542 // This is a cross-chain edge that is within the loop, so decrement the
543 // loop predecessor count of the destination chain.
544 if (SuccChain.UnscheduledPredecessors == 0 ||
545 --SuccChain.UnscheduledPredecessors > 0)
546 continue;
547
548 auto *NewBB = *SuccChain.begin();
549 if (NewBB->isEHPad())
550 EHPadWorkList.push_back(NewBB);
551 else
552 BlockWorkList.push_back(NewBB);
Chandler Carruth10281422011-10-21 06:46:38 +0000553 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000554}
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000555
Xinliang David Li594ffa32016-06-11 18:35:40 +0000556/// This helper function collects the set of successors of block
557/// \p BB that are allowed to be its layout successors, and return
558/// the total branch probability of edges from \p BB to those
559/// blocks.
560BranchProbability MachineBlockPlacement::collectViableSuccessors(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000561 const MachineBasicBlock *BB, const BlockChain &Chain,
562 const BlockFilterSet *BlockFilter,
Xinliang David Li594ffa32016-06-11 18:35:40 +0000563 SmallVector<MachineBasicBlock *, 4> &Successors) {
Cong Houd97c1002015-12-01 05:29:22 +0000564 // Adjust edge probabilities by excluding edges pointing to blocks that is
565 // either not in BlockFilter or is already in the current chain. Consider the
566 // following CFG:
Cong Hou41cf1a52015-11-18 00:52:52 +0000567 //
568 // --->A
569 // | / \
570 // | B C
571 // | \ / \
572 // ----D E
573 //
574 // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after
575 // A->C is chosen as a fall-through, D won't be selected as a successor of C
576 // due to CFG constraint (the probability of C->D is not greater than
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000577 // HotProb to break top-order). If we exclude E that is not in BlockFilter
Xinliang David Li594ffa32016-06-11 18:35:40 +0000578 // when calculating the probability of C->D, D will be selected and we
579 // will get A C D B as the layout of this loop.
Cong Houd97c1002015-12-01 05:29:22 +0000580 auto AdjustedSumProb = BranchProbability::getOne();
Cong Hou41cf1a52015-11-18 00:52:52 +0000581 for (MachineBasicBlock *Succ : BB->successors()) {
582 bool SkipSucc = false;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000583 if (Succ->isEHPad() || (BlockFilter && !BlockFilter->count(Succ))) {
Cong Hou41cf1a52015-11-18 00:52:52 +0000584 SkipSucc = true;
585 } else {
586 BlockChain *SuccChain = BlockToChain[Succ];
587 if (SuccChain == &Chain) {
Cong Hou41cf1a52015-11-18 00:52:52 +0000588 SkipSucc = true;
589 } else if (Succ != *SuccChain->begin()) {
590 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> Mid chain!\n");
591 continue;
592 }
593 }
594 if (SkipSucc)
Cong Houd97c1002015-12-01 05:29:22 +0000595 AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ);
Cong Hou41cf1a52015-11-18 00:52:52 +0000596 else
597 Successors.push_back(Succ);
598 }
599
Xinliang David Li594ffa32016-06-11 18:35:40 +0000600 return AdjustedSumProb;
601}
602
603/// The helper function returns the branch probability that is adjusted
604/// or normalized over the new total \p AdjustedSumProb.
Xinliang David Li594ffa32016-06-11 18:35:40 +0000605static BranchProbability
606getAdjustedProbability(BranchProbability OrigProb,
607 BranchProbability AdjustedSumProb) {
608 BranchProbability SuccProb;
609 uint32_t SuccProbN = OrigProb.getNumerator();
610 uint32_t SuccProbD = AdjustedSumProb.getNumerator();
611 if (SuccProbN >= SuccProbD)
612 SuccProb = BranchProbability::getOne();
613 else
614 SuccProb = BranchProbability(SuccProbN, SuccProbD);
615
616 return SuccProb;
617}
618
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000619/// Check if \p BB has exactly the successors in \p Successors.
620static bool
621hasSameSuccessors(MachineBasicBlock &BB,
622 SmallPtrSetImpl<const MachineBasicBlock *> &Successors) {
623 if (BB.succ_size() != Successors.size())
624 return false;
625 // We don't want to count self-loops
626 if (Successors.count(&BB))
627 return false;
628 for (MachineBasicBlock *Succ : BB.successors())
629 if (!Successors.count(Succ))
630 return false;
631 return true;
632}
633
634/// Check if a block should be tail duplicated to increase fallthrough
635/// opportunities.
Kyle Buttb15c0662017-01-31 23:48:32 +0000636/// \p BB Block to check.
637bool MachineBlockPlacement::shouldTailDuplicate(MachineBasicBlock *BB) {
638 // Blocks with single successors don't create additional fallthrough
639 // opportunities. Don't duplicate them. TODO: When conditional exits are
640 // analyzable, allow them to be duplicated.
641 bool IsSimple = TailDup.isSimpleBB(BB);
642
643 if (BB->succ_size() == 1)
644 return false;
645 return TailDup.shouldTailDuplicate(IsSimple, *BB);
646}
647
648/// Compare 2 BlockFrequency's with a small penalty for \p A.
649/// In order to be conservative, we apply a X% penalty to account for
650/// increased icache pressure and static heuristics. For small frequencies
651/// we use only the numerators to improve accuracy. For simplicity, we assume the
652/// penalty is less than 100%
653/// TODO(iteratee): Use 64-bit fixed point edge frequencies everywhere.
654static bool greaterWithBias(BlockFrequency A, BlockFrequency B,
655 uint64_t EntryFreq) {
656 BranchProbability ThresholdProb(TailDupPlacementPenalty, 100);
657 BlockFrequency Gain = A - B;
658 return (Gain / ThresholdProb).getFrequency() >= EntryFreq;
659}
660
661/// Check the edge frequencies to see if tail duplication will increase
662/// fallthroughs. It only makes sense to call this function when
663/// \p Succ would not be chosen otherwise. Tail duplication of \p Succ is
664/// always locally profitable if we would have picked \p Succ without
665/// considering duplication.
666bool MachineBlockPlacement::isProfitableToTailDup(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000667 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
Kyle Buttb15c0662017-01-31 23:48:32 +0000668 BranchProbability QProb,
Kyle Butte9425c4f2017-02-04 02:26:32 +0000669 const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
Kyle Buttb15c0662017-01-31 23:48:32 +0000670 // We need to do a probability calculation to make sure this is profitable.
671 // First: does succ have a successor that post-dominates? This affects the
672 // calculation. The 2 relevant cases are:
673 // BB BB
674 // | \Qout | \Qout
675 // P| C |P C
676 // = C' = C'
677 // | /Qin | /Qin
678 // | / | /
679 // Succ Succ
680 // / \ | \ V
681 // U/ =V |U \
682 // / \ = D
683 // D E | /
684 // | /
685 // |/
686 // PDom
687 // '=' : Branch taken for that CFG edge
688 // In the second case, Placing Succ while duplicating it into C prevents the
689 // fallthrough of Succ into either D or PDom, because they now have C as an
690 // unplaced predecessor
691
692 // Start by figuring out which case we fall into
693 MachineBasicBlock *PDom = nullptr;
694 SmallVector<MachineBasicBlock *, 4> SuccSuccs;
695 // Only scan the relevant successors
696 auto AdjustedSuccSumProb =
697 collectViableSuccessors(Succ, Chain, BlockFilter, SuccSuccs);
698 BranchProbability PProb = MBPI->getEdgeProbability(BB, Succ);
699 auto BBFreq = MBFI->getBlockFreq(BB);
700 auto SuccFreq = MBFI->getBlockFreq(Succ);
701 BlockFrequency P = BBFreq * PProb;
702 BlockFrequency Qout = BBFreq * QProb;
703 uint64_t EntryFreq = MBFI->getEntryFreq();
704 // If there are no more successors, it is profitable to copy, as it strictly
705 // increases fallthrough.
706 if (SuccSuccs.size() == 0)
707 return greaterWithBias(P, Qout, EntryFreq);
708
709 auto BestSuccSucc = BranchProbability::getZero();
710 // Find the PDom or the best Succ if no PDom exists.
711 for (MachineBasicBlock *SuccSucc : SuccSuccs) {
712 auto Prob = MBPI->getEdgeProbability(Succ, SuccSucc);
713 if (Prob > BestSuccSucc)
714 BestSuccSucc = Prob;
715 if (PDom == nullptr)
716 if (MPDT->dominates(SuccSucc, Succ)) {
717 PDom = SuccSucc;
718 break;
719 }
720 }
721 // For the comparisons, we need to know Succ's best incoming edge that isn't
722 // from BB.
723 auto SuccBestPred = BlockFrequency(0);
724 for (MachineBasicBlock *SuccPred : Succ->predecessors()) {
725 if (SuccPred == Succ || SuccPred == BB
726 || BlockToChain[SuccPred] == &Chain
727 || (BlockFilter && !BlockFilter->count(SuccPred)))
728 continue;
729 auto Freq = MBFI->getBlockFreq(SuccPred)
730 * MBPI->getEdgeProbability(SuccPred, Succ);
731 if (Freq > SuccBestPred)
732 SuccBestPred = Freq;
733 }
734 // Qin is Succ's best unplaced incoming edge that isn't BB
735 BlockFrequency Qin = SuccBestPred;
736 // If it doesn't have a post-dominating successor, here is the calculation:
737 // BB BB
738 // | \Qout | \
739 // P| C | =
740 // = C' | C
741 // | /Qin | |
742 // | / | C' (+Succ)
743 // Succ Succ /|
744 // / \ | \/ |
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000745 // U/ =V | == |
Kyle Buttb15c0662017-01-31 23:48:32 +0000746 // / \ | / \|
747 // D E D E
748 // '=' : Branch taken for that CFG edge
749 // Cost in the first case is: P + V
750 // For this calculation, we always assume P > Qout. If Qout > P
751 // The result of this function will be ignored at the caller.
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000752 // Cost in the second case is: Qout + Qin * U + P * V
Kyle Buttb15c0662017-01-31 23:48:32 +0000753
754 if (PDom == nullptr || !Succ->isSuccessor(PDom)) {
755 BranchProbability UProb = BestSuccSucc;
756 BranchProbability VProb = AdjustedSuccSumProb - UProb;
757 BlockFrequency V = SuccFreq * VProb;
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000758 BlockFrequency QinU = Qin * UProb;
Kyle Buttb15c0662017-01-31 23:48:32 +0000759 BlockFrequency BaseCost = P + V;
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000760 BlockFrequency DupCost = Qout + QinU + P * VProb;
Kyle Buttb15c0662017-01-31 23:48:32 +0000761 return greaterWithBias(BaseCost, DupCost, EntryFreq);
762 }
763 BranchProbability UProb = MBPI->getEdgeProbability(Succ, PDom);
764 BranchProbability VProb = AdjustedSuccSumProb - UProb;
765 BlockFrequency U = SuccFreq * UProb;
766 BlockFrequency V = SuccFreq * VProb;
767 // If there is a post-dominating successor, here is the calculation:
768 // BB BB BB BB
769 // | \Qout | \ | \Qout | \
770 // |P C | = |P C | =
771 // = C' |P C = C' |P C
772 // | /Qin | | | /Qin | |
773 // | / | C' (+Succ) | / | C' (+Succ)
774 // Succ Succ /| Succ Succ /|
775 // | \ V | \/ | | \ V | \/ |
776 // |U \ |U /\ | |U = |U /\ |
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000777 // = D = = \= | D | = =|
Kyle Buttb15c0662017-01-31 23:48:32 +0000778 // | / |/ D | / |/ D
779 // | / | / | = | /
780 // |/ | / |/ | =
781 // Dom Dom Dom Dom
782 // '=' : Branch taken for that CFG edge
783 // The cost for taken branches in the first case is P + U
784 // The cost in the second case (assuming independence), given the layout:
785 // BB, Succ, (C+Succ), D, Dom
786 // is Qout + P * V + Qin * U
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000787 // compare P + U vs Qout + P * U + Qin.
Kyle Buttb15c0662017-01-31 23:48:32 +0000788 //
789 // The 3rd and 4th cases cover when Dom would be chosen to follow Succ.
790 //
791 // For the 3rd case, the cost is P + 2 * V
792 // For the 4th case, the cost is Qout + Qin * U + P * V + V
793 // We choose 4 over 3 when (P + V) > Qout + Qin * U + P * V
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000794 if (UProb > AdjustedSuccSumProb / 2 &&
795 !hasBetterLayoutPredecessor(Succ, PDom, *BlockToChain[PDom], UProb, UProb,
796 Chain, BlockFilter))
Kyle Buttb15c0662017-01-31 23:48:32 +0000797 // Cases 3 & 4
798 return greaterWithBias((P + V), (Qout + Qin * UProb + P * VProb),
799 EntryFreq);
Kyle Buttb15c0662017-01-31 23:48:32 +0000800 // Cases 1 & 2
801 return greaterWithBias(
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000802 (P + U), (Qout + Qin * AdjustedSuccSumProb + P * UProb), EntryFreq);
Kyle Buttb15c0662017-01-31 23:48:32 +0000803}
804
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000805/// Check for a trellis layout. \p BB is the upper part of a trellis if its
806/// successors form the lower part of a trellis. A successor set S forms the
807/// lower part of a trellis if all of the predecessors of S are either in S or
808/// have all of S as successors. We ignore trellises where BB doesn't have 2
809/// successors because for fewer than 2, it's trivial, and for 3 or greater they
810/// are very uncommon and complex to compute optimally. Allowing edges within S
811/// is not strictly a trellis, but the same algorithm works, so we allow it.
812bool MachineBlockPlacement::isTrellis(
813 const MachineBasicBlock *BB,
814 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
815 const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
816 // Technically BB could form a trellis with branching factor higher than 2.
817 // But that's extremely uncommon.
818 if (BB->succ_size() != 2 || ViableSuccs.size() != 2)
819 return false;
820
821 SmallPtrSet<const MachineBasicBlock *, 2> Successors(BB->succ_begin(),
822 BB->succ_end());
823 // To avoid reviewing the same predecessors twice.
824 SmallPtrSet<const MachineBasicBlock *, 8> SeenPreds;
825
826 for (MachineBasicBlock *Succ : ViableSuccs) {
827 int PredCount = 0;
828 for (auto SuccPred : Succ->predecessors()) {
829 // Allow triangle successors, but don't count them.
830 if (Successors.count(SuccPred))
831 continue;
832 const BlockChain *PredChain = BlockToChain[SuccPred];
833 if (SuccPred == BB || (BlockFilter && !BlockFilter->count(SuccPred)) ||
834 PredChain == &Chain || PredChain == BlockToChain[Succ])
835 continue;
836 ++PredCount;
837 // Perform the successor check only once.
838 if (!SeenPreds.insert(SuccPred).second)
839 continue;
840 if (!hasSameSuccessors(*SuccPred, Successors))
841 return false;
842 }
843 // If one of the successors has only BB as a predecessor, it is not a
844 // trellis.
845 if (PredCount < 1)
846 return false;
847 }
848 return true;
849}
850
851/// Pick the highest total weight pair of edges that can both be laid out.
852/// The edges in \p Edges[0] are assumed to have a different destination than
853/// the edges in \p Edges[1]. Simple counting shows that the best pair is either
854/// the individual highest weight edges to the 2 different destinations, or in
855/// case of a conflict, one of them should be replaced with a 2nd best edge.
856std::pair<MachineBlockPlacement::WeightedEdge,
857 MachineBlockPlacement::WeightedEdge>
858MachineBlockPlacement::getBestNonConflictingEdges(
859 const MachineBasicBlock *BB,
860 SmallVector<SmallVector<MachineBlockPlacement::WeightedEdge, 8>, 2>
861 &Edges) {
862 // Sort the edges, and then for each successor, find the best incoming
863 // predecessor. If the best incoming predecessors aren't the same,
864 // then that is clearly the best layout. If there is a conflict, one of the
865 // successors will have to fallthrough from the second best predecessor. We
866 // compare which combination is better overall.
867
868 // Sort for highest frequency.
869 auto Cmp = [](WeightedEdge A, WeightedEdge B) { return A.Weight > B.Weight; };
870
871 std::stable_sort(Edges[0].begin(), Edges[0].end(), Cmp);
872 std::stable_sort(Edges[1].begin(), Edges[1].end(), Cmp);
873 auto BestA = Edges[0].begin();
874 auto BestB = Edges[1].begin();
875 // Arrange for the correct answer to be in BestA and BestB
876 // If the 2 best edges don't conflict, the answer is already there.
877 if (BestA->Src == BestB->Src) {
878 // Compare the total fallthrough of (Best + Second Best) for both pairs
879 auto SecondBestA = std::next(BestA);
880 auto SecondBestB = std::next(BestB);
881 BlockFrequency BestAScore = BestA->Weight + SecondBestB->Weight;
882 BlockFrequency BestBScore = BestB->Weight + SecondBestA->Weight;
883 if (BestAScore < BestBScore)
884 BestA = SecondBestA;
885 else
886 BestB = SecondBestB;
887 }
888 // Arrange for the BB edge to be in BestA if it exists.
889 if (BestB->Src == BB)
890 std::swap(BestA, BestB);
891 return std::make_pair(*BestA, *BestB);
892}
893
894/// Get the best successor from \p BB based on \p BB being part of a trellis.
895/// We only handle trellises with 2 successors, so the algorithm is
896/// straightforward: Find the best pair of edges that don't conflict. We find
897/// the best incoming edge for each successor in the trellis. If those conflict,
898/// we consider which of them should be replaced with the second best.
899/// Upon return the two best edges will be in \p BestEdges. If one of the edges
900/// comes from \p BB, it will be in \p BestEdges[0]
901MachineBlockPlacement::BlockAndTailDupResult
902MachineBlockPlacement::getBestTrellisSuccessor(
903 const MachineBasicBlock *BB,
904 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
905 BranchProbability AdjustedSumProb, const BlockChain &Chain,
906 const BlockFilterSet *BlockFilter) {
907
908 BlockAndTailDupResult Result = {nullptr, false};
909 SmallPtrSet<const MachineBasicBlock *, 4> Successors(BB->succ_begin(),
910 BB->succ_end());
911
912 // We assume size 2 because it's common. For general n, we would have to do
913 // the Hungarian algorithm, but it's not worth the complexity because more
914 // than 2 successors is fairly uncommon, and a trellis even more so.
915 if (Successors.size() != 2 || ViableSuccs.size() != 2)
916 return Result;
917
918 // Collect the edge frequencies of all edges that form the trellis.
919 SmallVector<SmallVector<WeightedEdge, 8>, 2> Edges(2);
920 int SuccIndex = 0;
921 for (auto Succ : ViableSuccs) {
922 for (MachineBasicBlock *SuccPred : Succ->predecessors()) {
923 // Skip any placed predecessors that are not BB
924 if (SuccPred != BB)
925 if ((BlockFilter && !BlockFilter->count(SuccPred)) ||
926 BlockToChain[SuccPred] == &Chain ||
927 BlockToChain[SuccPred] == BlockToChain[Succ])
928 continue;
929 BlockFrequency EdgeFreq = MBFI->getBlockFreq(SuccPred) *
930 MBPI->getEdgeProbability(SuccPred, Succ);
931 Edges[SuccIndex].push_back({EdgeFreq, SuccPred, Succ});
932 }
933 ++SuccIndex;
934 }
935
936 // Pick the best combination of 2 edges from all the edges in the trellis.
937 WeightedEdge BestA, BestB;
938 std::tie(BestA, BestB) = getBestNonConflictingEdges(BB, Edges);
939
940 if (BestA.Src != BB) {
941 // If we have a trellis, and BB doesn't have the best fallthrough edges,
942 // we shouldn't choose any successor. We've already looked and there's a
943 // better fallthrough edge for all the successors.
944 DEBUG(dbgs() << "Trellis, but not one of the chosen edges.\n");
945 return Result;
946 }
947
948 // Did we pick the triangle edge? If tail-duplication is profitable, do
949 // that instead. Otherwise merge the triangle edge now while we know it is
950 // optimal.
951 if (BestA.Dest == BestB.Src) {
952 // The edges are BB->Succ1->Succ2, and we're looking to see if BB->Succ2
953 // would be better.
954 MachineBasicBlock *Succ1 = BestA.Dest;
955 MachineBasicBlock *Succ2 = BestB.Dest;
956 // Check to see if tail-duplication would be profitable.
957 if (TailDupPlacement && shouldTailDuplicate(Succ2) &&
958 canTailDuplicateUnplacedPreds(BB, Succ2, Chain, BlockFilter) &&
959 isProfitableToTailDup(BB, Succ2, MBPI->getEdgeProbability(BB, Succ1),
960 Chain, BlockFilter)) {
961 DEBUG(BranchProbability Succ2Prob = getAdjustedProbability(
962 MBPI->getEdgeProbability(BB, Succ2), AdjustedSumProb);
963 dbgs() << " Selected: " << getBlockName(Succ2)
964 << ", probability: " << Succ2Prob << " (Tail Duplicate)\n");
965 Result.BB = Succ2;
966 Result.ShouldTailDup = true;
967 return Result;
968 }
969 }
970 // We have already computed the optimal edge for the other side of the
971 // trellis.
Kyle Buttebe6cc42017-02-23 21:22:24 +0000972 ComputedEdges[BestB.Src] = { BestB.Dest, false };
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000973
974 auto TrellisSucc = BestA.Dest;
975 DEBUG(BranchProbability SuccProb = getAdjustedProbability(
976 MBPI->getEdgeProbability(BB, TrellisSucc), AdjustedSumProb);
977 dbgs() << " Selected: " << getBlockName(TrellisSucc)
978 << ", probability: " << SuccProb << " (Trellis)\n");
979 Result.BB = TrellisSucc;
980 return Result;
981}
Kyle Buttb15c0662017-01-31 23:48:32 +0000982
983/// When the option TailDupPlacement is on, this method checks if the
984/// fallthrough candidate block \p Succ (of block \p BB) can be tail-duplicated
985/// into all of its unplaced, unfiltered predecessors, that are not BB.
986bool MachineBlockPlacement::canTailDuplicateUnplacedPreds(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000987 const MachineBasicBlock *BB, MachineBasicBlock *Succ,
988 const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
Kyle Buttb15c0662017-01-31 23:48:32 +0000989 if (!shouldTailDuplicate(Succ))
990 return false;
991
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000992 // For CFG checking.
993 SmallPtrSet<const MachineBasicBlock *, 4> Successors(BB->succ_begin(),
994 BB->succ_end());
Kyle Buttb15c0662017-01-31 23:48:32 +0000995 for (MachineBasicBlock *Pred : Succ->predecessors()) {
996 // Make sure all unplaced and unfiltered predecessors can be
997 // tail-duplicated into.
Kyle Butte9425c4f2017-02-04 02:26:32 +0000998 // Skip any blocks that are already placed or not in this loop.
Kyle Buttb15c0662017-01-31 23:48:32 +0000999 if (Pred == BB || (BlockFilter && !BlockFilter->count(Pred))
1000 || BlockToChain[Pred] == &Chain)
1001 continue;
Kyle Butt7fbec9b2017-02-15 19:49:14 +00001002 if (!TailDup.canTailDuplicate(Succ, Pred)) {
1003 if (Successors.size() > 1 && hasSameSuccessors(*Pred, Successors))
1004 // This will result in a trellis after tail duplication, so we don't
1005 // need to copy Succ into this predecessor. In the presence
1006 // of a trellis tail duplication can continue to be profitable.
1007 // For example:
1008 // A A
1009 // |\ |\
1010 // | \ | \
1011 // | C | C+BB
1012 // | / | |
1013 // |/ | |
1014 // BB => BB |
1015 // |\ |\/|
1016 // | \ |/\|
1017 // | D | D
1018 // | / | /
1019 // |/ |/
1020 // Succ Succ
1021 //
1022 // After BB was duplicated into C, the layout looks like the one on the
1023 // right. BB and C now have the same successors. When considering
1024 // whether Succ can be duplicated into all its unplaced predecessors, we
1025 // ignore C.
1026 // We can do this because C already has a profitable fallthrough, namely
1027 // D. TODO(iteratee): ignore sufficiently cold predecessors for
1028 // duplication and for this test.
1029 //
1030 // This allows trellises to be laid out in 2 separate chains
1031 // (A,B,Succ,...) and later (C,D,...) This is a reasonable heuristic
1032 // because it allows the creation of 2 fallthrough paths with links
1033 // between them, and we correctly identify the best layout for these
1034 // CFGs. We want to extend trellises that the user created in addition
1035 // to trellises created by tail-duplication, so we just look for the
1036 // CFG.
1037 continue;
Kyle Buttb15c0662017-01-31 23:48:32 +00001038 return false;
Kyle Butt7fbec9b2017-02-15 19:49:14 +00001039 }
Kyle Buttb15c0662017-01-31 23:48:32 +00001040 }
1041 return true;
1042}
1043
Dehao Chen9f2bdfb2016-06-14 22:27:17 +00001044// When profile is not present, return the StaticLikelyProb.
1045// When profile is available, we need to handle the triangle-shape CFG.
1046static BranchProbability getLayoutSuccessorProbThreshold(
Kyle Butte9425c4f2017-02-04 02:26:32 +00001047 const MachineBasicBlock *BB) {
Dehao Chen9f2bdfb2016-06-14 22:27:17 +00001048 if (!BB->getParent()->getFunction()->getEntryCount())
1049 return BranchProbability(StaticLikelyProb, 100);
1050 if (BB->succ_size() == 2) {
1051 const MachineBasicBlock *Succ1 = *BB->succ_begin();
1052 const MachineBasicBlock *Succ2 = *(BB->succ_begin() + 1);
Xinliang David Lie34ed832016-06-15 03:03:30 +00001053 if (Succ1->isSuccessor(Succ2) || Succ2->isSuccessor(Succ1)) {
1054 /* See case 1 below for the cost analysis. For BB->Succ to
1055 * be taken with smaller cost, the following needs to hold:
Kyle Buttb15c0662017-01-31 23:48:32 +00001056 * Prob(BB->Succ) > 2 * Prob(BB->Pred)
1057 * So the threshold T in the calculation below
1058 * (1-T) * Prob(BB->Succ) > T * Prob(BB->Pred)
1059 * So T / (1 - T) = 2, Yielding T = 2/3
1060 * Also adding user specified branch bias, we have
Xinliang David Lie34ed832016-06-15 03:03:30 +00001061 * T = (2/3)*(ProfileLikelyProb/50)
1062 * = (2*ProfileLikelyProb)/150)
1063 */
1064 return BranchProbability(2 * ProfileLikelyProb, 150);
1065 }
Dehao Chen9f2bdfb2016-06-14 22:27:17 +00001066 }
1067 return BranchProbability(ProfileLikelyProb, 100);
Xinliang David Licbf12142016-06-13 20:24:19 +00001068}
1069
1070/// Checks to see if the layout candidate block \p Succ has a better layout
1071/// predecessor than \c BB. If yes, returns true.
Kyle Buttb15c0662017-01-31 23:48:32 +00001072/// \p SuccProb: The probability adjusted for only remaining blocks.
1073/// Only used for logging
1074/// \p RealSuccProb: The un-adjusted probability.
1075/// \p Chain: The chain that BB belongs to and Succ is being considered for.
1076/// \p BlockFilter: if non-null, the set of blocks that make up the loop being
1077/// considered
Xinliang David Licbf12142016-06-13 20:24:19 +00001078bool MachineBlockPlacement::hasBetterLayoutPredecessor(
Kyle Butte9425c4f2017-02-04 02:26:32 +00001079 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
1080 const BlockChain &SuccChain, BranchProbability SuccProb,
1081 BranchProbability RealSuccProb, const BlockChain &Chain,
1082 const BlockFilterSet *BlockFilter) {
Xinliang David Licbf12142016-06-13 20:24:19 +00001083
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001084 // There isn't a better layout when there are no unscheduled predecessors.
Xinliang David Licbf12142016-06-13 20:24:19 +00001085 if (SuccChain.UnscheduledPredecessors == 0)
1086 return false;
1087
1088 // There are two basic scenarios here:
1089 // -------------------------------------
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001090 // Case 1: triangular shape CFG (if-then):
Xinliang David Licbf12142016-06-13 20:24:19 +00001091 // BB
1092 // | \
1093 // | \
1094 // | Pred
1095 // | /
1096 // Succ
1097 // In this case, we are evaluating whether to select edge -> Succ, e.g.
1098 // set Succ as the layout successor of BB. Picking Succ as BB's
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001099 // successor breaks the CFG constraints (FIXME: define these constraints).
1100 // With this layout, Pred BB
Xinliang David Licbf12142016-06-13 20:24:19 +00001101 // is forced to be outlined, so the overall cost will be cost of the
1102 // branch taken from BB to Pred, plus the cost of back taken branch
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001103 // from Pred to Succ, as well as the additional cost associated
Xinliang David Licbf12142016-06-13 20:24:19 +00001104 // with the needed unconditional jump instruction from Pred To Succ.
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001105
Xinliang David Licbf12142016-06-13 20:24:19 +00001106 // The cost of the topological order layout is the taken branch cost
1107 // from BB to Succ, so to make BB->Succ a viable candidate, the following
1108 // must hold:
1109 // 2 * freq(BB->Pred) * taken_branch_cost + unconditional_jump_cost
1110 // < freq(BB->Succ) * taken_branch_cost.
1111 // Ignoring unconditional jump cost, we get
1112 // freq(BB->Succ) > 2 * freq(BB->Pred), i.e.,
1113 // prob(BB->Succ) > 2 * prob(BB->Pred)
1114 //
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001115 // When real profile data is available, we can precisely compute the
1116 // probability threshold that is needed for edge BB->Succ to be considered.
1117 // Without profile data, the heuristic requires the branch bias to be
Xinliang David Licbf12142016-06-13 20:24:19 +00001118 // a lot larger to make sure the signal is very strong (e.g. 80% default).
1119 // -----------------------------------------------------------------
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001120 // Case 2: diamond like CFG (if-then-else):
Xinliang David Licbf12142016-06-13 20:24:19 +00001121 // S
1122 // / \
1123 // | \
1124 // BB Pred
1125 // \ /
1126 // Succ
1127 // ..
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001128 //
1129 // The current block is BB and edge BB->Succ is now being evaluated.
1130 // Note that edge S->BB was previously already selected because
1131 // prob(S->BB) > prob(S->Pred).
1132 // At this point, 2 blocks can be placed after BB: Pred or Succ. If we
1133 // choose Pred, we will have a topological ordering as shown on the left
1134 // in the picture below. If we choose Succ, we have the solution as shown
1135 // on the right:
1136 //
1137 // topo-order:
1138 //
1139 // S----- ---S
1140 // | | | |
1141 // ---BB | | BB
1142 // | | | |
1143 // | pred-- | Succ--
1144 // | | | |
1145 // ---succ ---pred--
1146 //
1147 // cost = freq(S->Pred) + freq(BB->Succ) cost = 2 * freq (S->Pred)
1148 // = freq(S->Pred) + freq(S->BB)
1149 //
1150 // If we have profile data (i.e, branch probabilities can be trusted), the
1151 // cost (number of taken branches) with layout S->BB->Succ->Pred is 2 *
1152 // freq(S->Pred) while the cost of topo order is freq(S->Pred) + freq(S->BB).
1153 // We know Prob(S->BB) > Prob(S->Pred), so freq(S->BB) > freq(S->Pred), which
1154 // means the cost of topological order is greater.
Xinliang David Licbf12142016-06-13 20:24:19 +00001155 // When profile data is not available, however, we need to be more
1156 // conservative. If the branch prediction is wrong, breaking the topo-order
1157 // will actually yield a layout with large cost. For this reason, we need
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001158 // strong biased branch at block S with Prob(S->BB) in order to select
1159 // BB->Succ. This is equivalent to looking the CFG backward with backward
Xinliang David Licbf12142016-06-13 20:24:19 +00001160 // edge: Prob(Succ->BB) needs to >= HotProb in order to be selected (without
1161 // profile data).
Kyle Butt02d8d052016-07-29 18:09:28 +00001162 // --------------------------------------------------------------------------
1163 // Case 3: forked diamond
1164 // S
1165 // / \
1166 // / \
1167 // BB Pred
1168 // | \ / |
1169 // | \ / |
1170 // | X |
1171 // | / \ |
1172 // | / \ |
1173 // S1 S2
1174 //
1175 // The current block is BB and edge BB->S1 is now being evaluated.
1176 // As above S->BB was already selected because
1177 // prob(S->BB) > prob(S->Pred). Assume that prob(BB->S1) >= prob(BB->S2).
1178 //
1179 // topo-order:
1180 //
1181 // S-------| ---S
1182 // | | | |
1183 // ---BB | | BB
1184 // | | | |
1185 // | Pred----| | S1----
1186 // | | | |
1187 // --(S1 or S2) ---Pred--
Kyle Butt7fbec9b2017-02-15 19:49:14 +00001188 // |
1189 // S2
Kyle Butt02d8d052016-07-29 18:09:28 +00001190 //
1191 // topo-cost = freq(S->Pred) + freq(BB->S1) + freq(BB->S2)
1192 // + min(freq(Pred->S1), freq(Pred->S2))
1193 // Non-topo-order cost:
Kyle Butt02d8d052016-07-29 18:09:28 +00001194 // non-topo-cost = 2 * freq(S->Pred) + freq(BB->S2).
1195 // To be conservative, we can assume that min(freq(Pred->S1), freq(Pred->S2))
1196 // is 0. Then the non topo layout is better when
1197 // freq(S->Pred) < freq(BB->S1).
1198 // This is exactly what is checked below.
1199 // Note there are other shapes that apply (Pred may not be a single block,
1200 // but they all fit this general pattern.)
Dehao Chen9f2bdfb2016-06-14 22:27:17 +00001201 BranchProbability HotProb = getLayoutSuccessorProbThreshold(BB);
Xinliang David Licbf12142016-06-13 20:24:19 +00001202
Xinliang David Licbf12142016-06-13 20:24:19 +00001203 // Make sure that a hot successor doesn't have a globally more
1204 // important predecessor.
1205 BlockFrequency CandidateEdgeFreq = MBFI->getBlockFreq(BB) * RealSuccProb;
1206 bool BadCFGConflict = false;
1207
1208 for (MachineBasicBlock *Pred : Succ->predecessors()) {
1209 if (Pred == Succ || BlockToChain[Pred] == &SuccChain ||
1210 (BlockFilter && !BlockFilter->count(Pred)) ||
Kyle Buttb15c0662017-01-31 23:48:32 +00001211 BlockToChain[Pred] == &Chain ||
1212 // This check is redundant except for look ahead. This function is
1213 // called for lookahead by isProfitableToTailDup when BB hasn't been
1214 // placed yet.
1215 (Pred == BB))
Xinliang David Licbf12142016-06-13 20:24:19 +00001216 continue;
Kyle Butt02d8d052016-07-29 18:09:28 +00001217 // Do backward checking.
1218 // For all cases above, we need a backward checking to filter out edges that
Kyle Buttb15c0662017-01-31 23:48:32 +00001219 // are not 'strongly' biased.
Xinliang David Licbf12142016-06-13 20:24:19 +00001220 // BB Pred
1221 // \ /
1222 // Succ
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001223 // We select edge BB->Succ if
Xinliang David Licbf12142016-06-13 20:24:19 +00001224 // freq(BB->Succ) > freq(Succ) * HotProb
1225 // i.e. freq(BB->Succ) > freq(BB->Succ) * HotProb + freq(Pred->Succ) *
1226 // HotProb
1227 // i.e. freq((BB->Succ) * (1 - HotProb) > freq(Pred->Succ) * HotProb
Kyle Butt02d8d052016-07-29 18:09:28 +00001228 // Case 1 is covered too, because the first equation reduces to:
1229 // prob(BB->Succ) > HotProb. (freq(Succ) = freq(BB) for a triangle)
Xinliang David Licbf12142016-06-13 20:24:19 +00001230 BlockFrequency PredEdgeFreq =
1231 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
1232 if (PredEdgeFreq * HotProb >= CandidateEdgeFreq * HotProb.getCompl()) {
1233 BadCFGConflict = true;
1234 break;
1235 }
1236 }
1237
1238 if (BadCFGConflict) {
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001239 DEBUG(dbgs() << " Not a candidate: " << getBlockName(Succ) << " -> " << SuccProb
Xinliang David Licbf12142016-06-13 20:24:19 +00001240 << " (prob) (non-cold CFG conflict)\n");
1241 return true;
1242 }
1243
1244 return false;
1245}
1246
Xinliang David Li594ffa32016-06-11 18:35:40 +00001247/// \brief Select the best successor for a block.
1248///
1249/// This looks across all successors of a particular block and attempts to
1250/// select the "best" one to be the layout successor. It only considers direct
1251/// successors which also pass the block filter. It will attempt to avoid
1252/// breaking CFG structure, but cave and break such structures in the case of
1253/// very hot successor edges.
1254///
Kyle Buttb15c0662017-01-31 23:48:32 +00001255/// \returns The best successor block found, or null if none are viable, along
1256/// with a boolean indicating if tail duplication is necessary.
1257MachineBlockPlacement::BlockAndTailDupResult
Kyle Butte9425c4f2017-02-04 02:26:32 +00001258MachineBlockPlacement::selectBestSuccessor(
1259 const MachineBasicBlock *BB, const BlockChain &Chain,
1260 const BlockFilterSet *BlockFilter) {
Xinliang David Li594ffa32016-06-11 18:35:40 +00001261 const BranchProbability HotProb(StaticLikelyProb, 100);
1262
Kyle Buttb15c0662017-01-31 23:48:32 +00001263 BlockAndTailDupResult BestSucc = { nullptr, false };
Xinliang David Li594ffa32016-06-11 18:35:40 +00001264 auto BestProb = BranchProbability::getZero();
1265
1266 SmallVector<MachineBasicBlock *, 4> Successors;
1267 auto AdjustedSumProb =
1268 collectViableSuccessors(BB, Chain, BlockFilter, Successors);
1269
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001270 DEBUG(dbgs() << "Selecting best successor for: " << getBlockName(BB) << "\n");
Kyle Buttb15c0662017-01-31 23:48:32 +00001271
Kyle Buttebe6cc42017-02-23 21:22:24 +00001272 // if we already precomputed the best successor for BB, return that if still
1273 // applicable.
1274 auto FoundEdge = ComputedEdges.find(BB);
1275 if (FoundEdge != ComputedEdges.end()) {
1276 MachineBasicBlock *Succ = FoundEdge->second.BB;
1277 ComputedEdges.erase(FoundEdge);
Kyle Butt7fbec9b2017-02-15 19:49:14 +00001278 BlockChain *SuccChain = BlockToChain[Succ];
1279 if (BB->isSuccessor(Succ) && (!BlockFilter || BlockFilter->count(Succ)) &&
Kyle Buttebe6cc42017-02-23 21:22:24 +00001280 SuccChain != &Chain && Succ == *SuccChain->begin())
1281 return FoundEdge->second;
Kyle Butt7fbec9b2017-02-15 19:49:14 +00001282 }
1283
1284 // if BB is part of a trellis, Use the trellis to determine the optimal
1285 // fallthrough edges
1286 if (isTrellis(BB, Successors, Chain, BlockFilter))
1287 return getBestTrellisSuccessor(BB, Successors, AdjustedSumProb, Chain,
1288 BlockFilter);
1289
Kyle Buttb15c0662017-01-31 23:48:32 +00001290 // For blocks with CFG violations, we may be able to lay them out anyway with
1291 // tail-duplication. We keep this vector so we can perform the probability
1292 // calculations the minimum number of times.
1293 SmallVector<std::tuple<BranchProbability, MachineBasicBlock *>, 4>
1294 DupCandidates;
Cong Hou41cf1a52015-11-18 00:52:52 +00001295 for (MachineBasicBlock *Succ : Successors) {
Xinliang David Li594ffa32016-06-11 18:35:40 +00001296 auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ);
1297 BranchProbability SuccProb =
1298 getAdjustedProbability(RealSuccProb, AdjustedSumProb);
Chandler Carruthb3361722011-11-13 11:34:53 +00001299
Cong Hou41cf1a52015-11-18 00:52:52 +00001300 BlockChain &SuccChain = *BlockToChain[Succ];
Xinliang David Licbf12142016-06-13 20:24:19 +00001301 // Skip the edge \c BB->Succ if block \c Succ has a better layout
1302 // predecessor that yields lower global cost.
1303 if (hasBetterLayoutPredecessor(BB, Succ, SuccChain, SuccProb, RealSuccProb,
Kyle Buttb15c0662017-01-31 23:48:32 +00001304 Chain, BlockFilter)) {
1305 // If tail duplication would make Succ profitable, place it.
1306 if (TailDupPlacement && shouldTailDuplicate(Succ))
1307 DupCandidates.push_back(std::make_tuple(SuccProb, Succ));
Xinliang David Licbf12142016-06-13 20:24:19 +00001308 continue;
Kyle Buttb15c0662017-01-31 23:48:32 +00001309 }
Chandler Carruth18dfac32011-11-20 11:22:06 +00001310
Xinliang David Licbf12142016-06-13 20:24:19 +00001311 DEBUG(
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001312 dbgs() << " Candidate: " << getBlockName(Succ) << ", probability: "
1313 << SuccProb
Xinliang David Licbf12142016-06-13 20:24:19 +00001314 << (SuccChain.UnscheduledPredecessors != 0 ? " (CFG break)" : "")
1315 << "\n");
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001316
Kyle Buttb15c0662017-01-31 23:48:32 +00001317 if (BestSucc.BB && BestProb >= SuccProb) {
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001318 DEBUG(dbgs() << " Not the best candidate, continuing\n");
Chandler Carruthb3361722011-11-13 11:34:53 +00001319 continue;
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001320 }
1321
1322 DEBUG(dbgs() << " Setting it as best candidate\n");
Kyle Buttb15c0662017-01-31 23:48:32 +00001323 BestSucc.BB = Succ;
Cong Houd97c1002015-12-01 05:29:22 +00001324 BestProb = SuccProb;
Chandler Carruthb3361722011-11-13 11:34:53 +00001325 }
Kyle Buttb15c0662017-01-31 23:48:32 +00001326 // Handle the tail duplication candidates in order of decreasing probability.
1327 // Stop at the first one that is profitable. Also stop if they are less
1328 // profitable than BestSucc. Position is important because we preserve it and
1329 // prefer first best match. Here we aren't comparing in order, so we capture
1330 // the position instead.
1331 if (DupCandidates.size() != 0) {
1332 auto cmp =
1333 [](const std::tuple<BranchProbability, MachineBasicBlock *> &a,
1334 const std::tuple<BranchProbability, MachineBasicBlock *> &b) {
1335 return std::get<0>(a) > std::get<0>(b);
1336 };
1337 std::stable_sort(DupCandidates.begin(), DupCandidates.end(), cmp);
1338 }
1339 for(auto &Tup : DupCandidates) {
1340 BranchProbability DupProb;
1341 MachineBasicBlock *Succ;
1342 std::tie(DupProb, Succ) = Tup;
1343 if (DupProb < BestProb)
1344 break;
1345 if (canTailDuplicateUnplacedPreds(BB, Succ, Chain, BlockFilter)
1346 // If tail duplication gives us fallthrough when we otherwise wouldn't
1347 // have it, that is a strict gain.
1348 && (BestSucc.BB == nullptr
1349 || isProfitableToTailDup(BB, Succ, BestProb, Chain,
1350 BlockFilter))) {
1351 DEBUG(
1352 dbgs() << " Candidate: " << getBlockName(Succ) << ", probability: "
1353 << DupProb
1354 << " (Tail Duplicate)\n");
1355 BestSucc.BB = Succ;
1356 BestSucc.ShouldTailDup = true;
1357 break;
1358 }
1359 }
1360
1361 if (BestSucc.BB)
1362 DEBUG(dbgs() << " Selected: " << getBlockName(BestSucc.BB) << "\n");
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001363
Chandler Carruthb3361722011-11-13 11:34:53 +00001364 return BestSucc;
1365}
1366
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001367/// \brief Select the best block from a worklist.
1368///
1369/// This looks through the provided worklist as a list of candidate basic
1370/// blocks and select the most profitable one to place. The definition of
1371/// profitable only really makes sense in the context of a loop. This returns
1372/// the most frequently visited block in the worklist, which in the case of
1373/// a loop, is the one most desirable to be physically close to the rest of the
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001374/// loop body in order to improve i-cache behavior.
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001375///
1376/// \returns The best block found, or null if none are viable.
1377MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
Kyle Butte9425c4f2017-02-04 02:26:32 +00001378 const BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList) {
Chandler Carruth0af6a0b2011-11-14 09:46:33 +00001379 // Once we need to walk the worklist looking for a candidate, cleanup the
1380 // worklist of already placed entries.
1381 // FIXME: If this shows up on profiles, it could be folded (at the cost of
1382 // some code complexity) into the loop below.
David Majnemerc7004902016-08-12 04:32:37 +00001383 WorkList.erase(remove_if(WorkList,
1384 [&](MachineBasicBlock *BB) {
1385 return BlockToChain.lookup(BB) == &Chain;
1386 }),
Chandler Carruth0af6a0b2011-11-14 09:46:33 +00001387 WorkList.end());
1388
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001389 if (WorkList.empty())
1390 return nullptr;
1391
1392 bool IsEHPad = WorkList[0]->isEHPad();
1393
Craig Topperc0196b12014-04-14 00:51:57 +00001394 MachineBasicBlock *BestBlock = nullptr;
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001395 BlockFrequency BestFreq;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001396 for (MachineBasicBlock *MBB : WorkList) {
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001397 assert(MBB->isEHPad() == IsEHPad);
1398
Chandler Carruth7a715da2015-03-05 03:19:05 +00001399 BlockChain &SuccChain = *BlockToChain[MBB];
Philip Reames02e11322016-03-02 22:40:51 +00001400 if (&SuccChain == &Chain)
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001401 continue;
Junmo Park4ba6cf62016-03-11 05:07:07 +00001402
Philip Reamesae27b232016-03-03 00:58:43 +00001403 assert(SuccChain.UnscheduledPredecessors == 0 && "Found CFG-violating block");
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001404
Chandler Carruth7a715da2015-03-05 03:19:05 +00001405 BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
1406 DEBUG(dbgs() << " " << getBlockName(MBB) << " -> ";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001407 MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001408
1409 // For ehpad, we layout the least probable first as to avoid jumping back
1410 // from least probable landingpads to more probable ones.
1411 //
1412 // FIXME: Using probability is probably (!) not the best way to achieve
1413 // this. We should probably have a more principled approach to layout
1414 // cleanup code.
1415 //
1416 // The goal is to get:
1417 //
1418 // +--------------------------+
1419 // | V
1420 // InnerLp -> InnerCleanup OuterLp -> OuterCleanup -> Resume
1421 //
1422 // Rather than:
1423 //
1424 // +-------------------------------------+
1425 // V |
1426 // OuterLp -> OuterCleanup -> Resume InnerLp -> InnerCleanup
1427 if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq)))
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001428 continue;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001429
Chandler Carruth7a715da2015-03-05 03:19:05 +00001430 BestBlock = MBB;
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001431 BestFreq = CandidateFreq;
1432 }
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001433
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001434 return BestBlock;
1435}
1436
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001437/// \brief Retrieve the first unplaced basic block.
1438///
1439/// This routine is called when we are unable to use the CFG to walk through
1440/// all of the basic blocks and form a chain due to unnatural loops in the CFG.
Chandler Carruth9b548a7f2011-11-15 06:26:43 +00001441/// We walk through the function's blocks in order, starting from the
1442/// LastUnplacedBlockIt. We update this iterator on each call to avoid
1443/// re-scanning the entire sequence on repeated calls to this routine.
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001444MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
Xinliang David Li52530a72016-06-13 22:23:44 +00001445 const BlockChain &PlacedChain,
Chandler Carruth9b548a7f2011-11-15 06:26:43 +00001446 MachineFunction::iterator &PrevUnplacedBlockIt,
Jakub Staszak90616162011-12-21 23:02:08 +00001447 const BlockFilterSet *BlockFilter) {
Xinliang David Li52530a72016-06-13 22:23:44 +00001448 for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F->end(); I != E;
Chandler Carruth9b548a7f2011-11-15 06:26:43 +00001449 ++I) {
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001450 if (BlockFilter && !BlockFilter->count(&*I))
Chandler Carruth9b548a7f2011-11-15 06:26:43 +00001451 continue;
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001452 if (BlockToChain[&*I] != &PlacedChain) {
Chandler Carruth9b548a7f2011-11-15 06:26:43 +00001453 PrevUnplacedBlockIt = I;
Chandler Carruth4a87aa02011-11-23 03:03:21 +00001454 // Now select the head of the chain to which the unplaced block belongs
1455 // as the block to place. This will force the entire chain to be placed,
1456 // and satisfies the requirements of merging chains.
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001457 return *BlockToChain[&*I]->begin();
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001458 }
1459 }
Craig Topperc0196b12014-04-14 00:51:57 +00001460 return nullptr;
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001461}
1462
Amaury Secheteae09c22016-03-14 21:24:11 +00001463void MachineBlockPlacement::fillWorkLists(
Kyle Butte9425c4f2017-02-04 02:26:32 +00001464 const MachineBasicBlock *MBB,
Amaury Secheteae09c22016-03-14 21:24:11 +00001465 SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
Amaury Secheteae09c22016-03-14 21:24:11 +00001466 const BlockFilterSet *BlockFilter = nullptr) {
1467 BlockChain &Chain = *BlockToChain[MBB];
1468 if (!UpdatedPreds.insert(&Chain).second)
1469 return;
1470
1471 assert(Chain.UnscheduledPredecessors == 0);
1472 for (MachineBasicBlock *ChainBB : Chain) {
1473 assert(BlockToChain[ChainBB] == &Chain);
1474 for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
1475 if (BlockFilter && !BlockFilter->count(Pred))
1476 continue;
1477 if (BlockToChain[Pred] == &Chain)
1478 continue;
1479 ++Chain.UnscheduledPredecessors;
1480 }
1481 }
1482
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001483 if (Chain.UnscheduledPredecessors != 0)
1484 return;
1485
Kyle Butte9425c4f2017-02-04 02:26:32 +00001486 MachineBasicBlock *BB = *Chain.begin();
1487 if (BB->isEHPad())
1488 EHPadWorkList.push_back(BB);
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001489 else
Kyle Butte9425c4f2017-02-04 02:26:32 +00001490 BlockWorkList.push_back(BB);
Amaury Secheteae09c22016-03-14 21:24:11 +00001491}
1492
Chandler Carruth8d150782011-11-13 11:20:44 +00001493void MachineBlockPlacement::buildChain(
Kyle Butte9425c4f2017-02-04 02:26:32 +00001494 const MachineBasicBlock *HeadBB, BlockChain &Chain,
Kyle Butt0846e562016-10-11 20:36:43 +00001495 BlockFilterSet *BlockFilter) {
Kyle Butte9425c4f2017-02-04 02:26:32 +00001496 assert(HeadBB && "BB must not be null.\n");
1497 assert(BlockToChain[HeadBB] == &Chain && "BlockToChainMap mis-match.\n");
Xinliang David Li52530a72016-06-13 22:23:44 +00001498 MachineFunction::iterator PrevUnplacedBlockIt = F->begin();
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001499
Kyle Butte9425c4f2017-02-04 02:26:32 +00001500 const MachineBasicBlock *LoopHeaderBB = HeadBB;
Xinliang David Li93926ac2016-07-01 05:46:48 +00001501 markChainSuccessors(Chain, LoopHeaderBB, BlockFilter);
Kyle Butte9425c4f2017-02-04 02:26:32 +00001502 MachineBasicBlock *BB = *std::prev(Chain.end());
Chandler Carruth8d150782011-11-13 11:20:44 +00001503 for (;;) {
Kyle Butt82c22902016-06-28 22:50:54 +00001504 assert(BB && "null block found at end of chain in loop.");
1505 assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match in loop.");
1506 assert(*std::prev(Chain.end()) == BB && "BB Not found at end of chain.");
1507
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001508
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001509 // Look for the best viable successor if there is one to place immediately
1510 // after this block.
Kyle Buttb15c0662017-01-31 23:48:32 +00001511 auto Result = selectBestSuccessor(BB, Chain, BlockFilter);
1512 MachineBasicBlock* BestSucc = Result.BB;
1513 bool ShouldTailDup = Result.ShouldTailDup;
1514 if (TailDupPlacement)
1515 ShouldTailDup |= (BestSucc && shouldTailDuplicate(BestSucc));
Chandler Carruth8d150782011-11-13 11:20:44 +00001516
1517 // If an immediate successor isn't available, look for the best viable
1518 // block among those we've identified as not violating the loop's CFG at
1519 // this point. This won't be a fallthrough, but it will increase locality.
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001520 if (!BestSucc)
Amaury Sechet9ee4ddd2016-04-07 06:34:47 +00001521 BestSucc = selectBestCandidateBlock(Chain, BlockWorkList);
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001522 if (!BestSucc)
1523 BestSucc = selectBestCandidateBlock(Chain, EHPadWorkList);
Chandler Carruth8d150782011-11-13 11:20:44 +00001524
Chandler Carruth8d150782011-11-13 11:20:44 +00001525 if (!BestSucc) {
Xinliang David Li52530a72016-06-13 22:23:44 +00001526 BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockIt, BlockFilter);
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001527 if (!BestSucc)
1528 break;
1529
1530 DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
1531 "layout successor until the CFG reduces\n");
Chandler Carruth8d150782011-11-13 11:20:44 +00001532 }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001533
Kyle Butt0846e562016-10-11 20:36:43 +00001534 // Placement may have changed tail duplication opportunities.
1535 // Check for that now.
Kyle Buttb15c0662017-01-31 23:48:32 +00001536 if (TailDupPlacement && BestSucc && ShouldTailDup) {
Kyle Butt0846e562016-10-11 20:36:43 +00001537 // If the chosen successor was duplicated into all its predecessors,
1538 // don't bother laying it out, just go round the loop again with BB as
1539 // the chain end.
1540 if (repeatedlyTailDuplicateBlock(BestSucc, BB, LoopHeaderBB, Chain,
1541 BlockFilter, PrevUnplacedBlockIt))
1542 continue;
1543 }
1544
Chandler Carruth8d150782011-11-13 11:20:44 +00001545 // Place this block, updating the datastructures to reflect its placement.
Jakub Staszak90616162011-12-21 23:02:08 +00001546 BlockChain &SuccChain = *BlockToChain[BestSucc];
Philip Reamesae27b232016-03-03 00:58:43 +00001547 // Zero out UnscheduledPredecessors for the successor we're about to merge in case
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001548 // we selected a successor that didn't fit naturally into the CFG.
Philip Reamesae27b232016-03-03 00:58:43 +00001549 SuccChain.UnscheduledPredecessors = 0;
Philip Reamesb9688f42016-03-02 21:45:13 +00001550 DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to "
1551 << getBlockName(BestSucc) << "\n");
Xinliang David Li93926ac2016-07-01 05:46:48 +00001552 markChainSuccessors(SuccChain, LoopHeaderBB, BlockFilter);
Chandler Carruth8d150782011-11-13 11:20:44 +00001553 Chain.merge(BestSucc, &SuccChain);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001554 BB = *std::prev(Chain.end());
Jakub Staszak190c7122011-12-07 19:46:10 +00001555 }
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001556
1557 DEBUG(dbgs() << "Finished forming chain for header block "
Philip Reamesb9688f42016-03-02 21:45:13 +00001558 << getBlockName(*Chain.begin()) << "\n");
Chandler Carruth10281422011-10-21 06:46:38 +00001559}
1560
Chandler Carruth03adbd42011-11-27 13:34:33 +00001561/// \brief Find the best loop top block for layout.
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001562///
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001563/// Look for a block which is strictly better than the loop header for laying
1564/// out at the top of the loop. This looks for one and only one pattern:
1565/// a latch block with no conditional exit. This block will cause a conditional
1566/// jump around it or will be the bottom of the loop if we lay it out in place,
1567/// but if it it doesn't end up at the bottom of the loop for any reason,
1568/// rotation alone won't fix it. Because such a block will always result in an
1569/// unconditional jump (for the backedge) rotating it in front of the loop
1570/// header is always profitable.
1571MachineBasicBlock *
Kyle Butte9425c4f2017-02-04 02:26:32 +00001572MachineBlockPlacement::findBestLoopTop(const MachineLoop &L,
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001573 const BlockFilterSet &LoopBlockSet) {
Sjoerd Meijer15c81b02016-08-16 19:50:33 +00001574 // Placing the latch block before the header may introduce an extra branch
1575 // that skips this block the first time the loop is executed, which we want
1576 // to avoid when optimising for size.
1577 // FIXME: in theory there is a case that does not introduce a new branch,
1578 // i.e. when the layout predecessor does not fallthrough to the loop header.
1579 // In practice this never happens though: there always seems to be a preheader
1580 // that can fallthrough and that is also placed before the header.
1581 if (F->getFunction()->optForSize())
1582 return L.getHeader();
1583
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001584 // Check that the header hasn't been fused with a preheader block due to
1585 // crazy branches. If it has, we need to start with the header at the top to
1586 // prevent pulling the preheader into the loop body.
1587 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
1588 if (!LoopBlockSet.count(*HeaderChain.begin()))
1589 return L.getHeader();
1590
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001591 DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(L.getHeader())
1592 << "\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001593
1594 BlockFrequency BestPredFreq;
Craig Topperc0196b12014-04-14 00:51:57 +00001595 MachineBasicBlock *BestPred = nullptr;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001596 for (MachineBasicBlock *Pred : L.getHeader()->predecessors()) {
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001597 if (!LoopBlockSet.count(Pred))
1598 continue;
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001599 DEBUG(dbgs() << " header pred: " << getBlockName(Pred) << ", has "
Michael Gottesmanb78dec82013-12-14 00:25:45 +00001600 << Pred->succ_size() << " successors, ";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001601 MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001602 if (Pred->succ_size() > 1)
1603 continue;
1604
1605 BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
1606 if (!BestPred || PredFreq > BestPredFreq ||
1607 (!(PredFreq < BestPredFreq) &&
1608 Pred->isLayoutSuccessor(L.getHeader()))) {
1609 BestPred = Pred;
1610 BestPredFreq = PredFreq;
1611 }
1612 }
1613
1614 // If no direct predecessor is fine, just use the loop header.
Philip Reamesb9688f42016-03-02 21:45:13 +00001615 if (!BestPred) {
1616 DEBUG(dbgs() << " final top unchanged\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001617 return L.getHeader();
Philip Reamesb9688f42016-03-02 21:45:13 +00001618 }
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001619
1620 // Walk backwards through any straight line of predecessors.
1621 while (BestPred->pred_size() == 1 &&
1622 (*BestPred->pred_begin())->succ_size() == 1 &&
1623 *BestPred->pred_begin() != L.getHeader())
1624 BestPred = *BestPred->pred_begin();
1625
1626 DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n");
1627 return BestPred;
1628}
1629
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001630/// \brief Find the best loop exiting block for layout.
1631///
Chandler Carruth03adbd42011-11-27 13:34:33 +00001632/// This routine implements the logic to analyze the loop looking for the best
1633/// block to layout at the top of the loop. Typically this is done to maximize
1634/// fallthrough opportunities.
1635MachineBasicBlock *
Kyle Butte9425c4f2017-02-04 02:26:32 +00001636MachineBlockPlacement::findBestLoopExit(const MachineLoop &L,
Chandler Carruthccc7e422012-04-16 01:12:56 +00001637 const BlockFilterSet &LoopBlockSet) {
Chandler Carruth68062612012-04-10 13:35:57 +00001638 // We don't want to layout the loop linearly in all cases. If the loop header
1639 // is just a normal basic block in the loop, we want to look for what block
1640 // within the loop is the best one to layout at the top. However, if the loop
1641 // header has be pre-merged into a chain due to predecessors not having
1642 // analyzable branches, *and* the predecessor it is merged with is *not* part
1643 // of the loop, rotating the header into the middle of the loop will create
1644 // a non-contiguous range of blocks which is Very Bad. So start with the
1645 // header and only rotate if safe.
1646 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
1647 if (!LoopBlockSet.count(*HeaderChain.begin()))
Craig Topperc0196b12014-04-14 00:51:57 +00001648 return nullptr;
Chandler Carruth68062612012-04-10 13:35:57 +00001649
Chandler Carruth03adbd42011-11-27 13:34:33 +00001650 BlockFrequency BestExitEdgeFreq;
Chandler Carruthccc7e422012-04-16 01:12:56 +00001651 unsigned BestExitLoopDepth = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00001652 MachineBasicBlock *ExitingBB = nullptr;
Chandler Carruth4f567202011-11-27 20:18:00 +00001653 // If there are exits to outer loops, loop rotation can severely limit
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001654 // fallthrough opportunities unless it selects such an exit. Keep a set of
Chandler Carruth4f567202011-11-27 20:18:00 +00001655 // blocks where rotating to exit with that block will reach an outer loop.
1656 SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
1657
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001658 DEBUG(dbgs() << "Finding best loop exit for: " << getBlockName(L.getHeader())
1659 << "\n");
Chandler Carruth7a715da2015-03-05 03:19:05 +00001660 for (MachineBasicBlock *MBB : L.getBlocks()) {
1661 BlockChain &Chain = *BlockToChain[MBB];
Chandler Carruth03adbd42011-11-27 13:34:33 +00001662 // Ensure that this block is at the end of a chain; otherwise it could be
Chandler Carruth9a512a42015-04-15 13:19:54 +00001663 // mid-way through an inner loop or a successor of an unanalyzable branch.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001664 if (MBB != *std::prev(Chain.end()))
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001665 continue;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001666
Chandler Carruth03adbd42011-11-27 13:34:33 +00001667 // Now walk the successors. We need to establish whether this has a viable
1668 // exiting successor and whether it has a viable non-exiting successor.
1669 // We store the old exiting state and restore it if a viable looping
1670 // successor isn't found.
1671 MachineBasicBlock *OldExitingBB = ExitingBB;
1672 BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
Chandler Carruthccc7e422012-04-16 01:12:56 +00001673 bool HasLoopingSucc = false;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001674 for (MachineBasicBlock *Succ : MBB->successors()) {
Reid Kleckner0e288232015-08-27 23:27:47 +00001675 if (Succ->isEHPad())
Chandler Carruth03adbd42011-11-27 13:34:33 +00001676 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001677 if (Succ == MBB)
Chandler Carruth03adbd42011-11-27 13:34:33 +00001678 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001679 BlockChain &SuccChain = *BlockToChain[Succ];
Chandler Carruth03adbd42011-11-27 13:34:33 +00001680 // Don't split chains, either this chain or the successor's chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +00001681 if (&Chain == &SuccChain) {
Chandler Carruth7a715da2015-03-05 03:19:05 +00001682 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
1683 << getBlockName(Succ) << " (chain conflict)\n");
Chandler Carruth03adbd42011-11-27 13:34:33 +00001684 continue;
1685 }
1686
Cong Houd97c1002015-12-01 05:29:22 +00001687 auto SuccProb = MBPI->getEdgeProbability(MBB, Succ);
Chandler Carruth7a715da2015-03-05 03:19:05 +00001688 if (LoopBlockSet.count(Succ)) {
1689 DEBUG(dbgs() << " looping: " << getBlockName(MBB) << " -> "
Cong Houd97c1002015-12-01 05:29:22 +00001690 << getBlockName(Succ) << " (" << SuccProb << ")\n");
Chandler Carruthccc7e422012-04-16 01:12:56 +00001691 HasLoopingSucc = true;
Chandler Carruth03adbd42011-11-27 13:34:33 +00001692 continue;
1693 }
1694
Chandler Carruthccc7e422012-04-16 01:12:56 +00001695 unsigned SuccLoopDepth = 0;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001696 if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
Chandler Carruthccc7e422012-04-16 01:12:56 +00001697 SuccLoopDepth = ExitLoop->getLoopDepth();
1698 if (ExitLoop->contains(&L))
Chandler Carruth7a715da2015-03-05 03:19:05 +00001699 BlocksExitingToOuterLoop.insert(MBB);
Chandler Carruthccc7e422012-04-16 01:12:56 +00001700 }
1701
Chandler Carruth7a715da2015-03-05 03:19:05 +00001702 BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
1703 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
1704 << getBlockName(Succ) << " [L:" << SuccLoopDepth << "] (";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001705 MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
Benjamin Kramerc8160d62013-11-20 19:08:44 +00001706 // Note that we bias this toward an existing layout successor to retain
1707 // incoming order in the absence of better information. The exit must have
1708 // a frequency higher than the current exit before we consider breaking
1709 // the layout.
1710 BranchProbability Bias(100 - ExitBlockBias, 100);
Chandler Carruth26d30172015-04-15 13:39:42 +00001711 if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
Chandler Carruthccc7e422012-04-16 01:12:56 +00001712 ExitEdgeFreq > BestExitEdgeFreq ||
Chandler Carruth7a715da2015-03-05 03:19:05 +00001713 (MBB->isLayoutSuccessor(Succ) &&
Benjamin Kramerc8160d62013-11-20 19:08:44 +00001714 !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
Chandler Carruth03adbd42011-11-27 13:34:33 +00001715 BestExitEdgeFreq = ExitEdgeFreq;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001716 ExitingBB = MBB;
Chandler Carrutha0545802011-11-27 09:22:53 +00001717 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001718 }
Chandler Carruth03adbd42011-11-27 13:34:33 +00001719
Chandler Carruthccc7e422012-04-16 01:12:56 +00001720 if (!HasLoopingSucc) {
Chandler Carruthcfb2b9d2015-04-15 13:26:41 +00001721 // Restore the old exiting state, no viable looping successor was found.
Chandler Carruth03adbd42011-11-27 13:34:33 +00001722 ExitingBB = OldExitingBB;
1723 BestExitEdgeFreq = OldBestExitEdgeFreq;
Chandler Carruth03adbd42011-11-27 13:34:33 +00001724 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001725 }
Chandler Carruthccc7e422012-04-16 01:12:56 +00001726 // Without a candidate exiting block or with only a single block in the
Chandler Carruth03adbd42011-11-27 13:34:33 +00001727 // loop, just use the loop header to layout the loop.
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001728 if (!ExitingBB) {
1729 DEBUG(dbgs() << " No other candidate exit blocks, using loop header\n");
Craig Topperc0196b12014-04-14 00:51:57 +00001730 return nullptr;
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001731 }
1732 if (L.getNumBlocks() == 1) {
1733 DEBUG(dbgs() << " Loop has 1 block, using loop header as exit\n");
1734 return nullptr;
1735 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001736
Chandler Carruth4f567202011-11-27 20:18:00 +00001737 // Also, if we have exit blocks which lead to outer loops but didn't select
1738 // one of them as the exiting block we are rotating toward, disable loop
1739 // rotation altogether.
1740 if (!BlocksExitingToOuterLoop.empty() &&
1741 !BlocksExitingToOuterLoop.count(ExitingBB))
Craig Topperc0196b12014-04-14 00:51:57 +00001742 return nullptr;
Chandler Carruth4f567202011-11-27 20:18:00 +00001743
Chandler Carruth03adbd42011-11-27 13:34:33 +00001744 DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB) << "\n");
Chandler Carruthccc7e422012-04-16 01:12:56 +00001745 return ExitingBB;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001746}
1747
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001748/// \brief Attempt to rotate an exiting block to the bottom of the loop.
1749///
1750/// Once we have built a chain, try to rotate it to line up the hot exit block
1751/// with fallthrough out of the loop if doing so doesn't introduce unnecessary
1752/// branches. For example, if the loop has fallthrough into its header and out
1753/// of its bottom already, don't rotate it.
1754void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
Kyle Butte9425c4f2017-02-04 02:26:32 +00001755 const MachineBasicBlock *ExitingBB,
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001756 const BlockFilterSet &LoopBlockSet) {
1757 if (!ExitingBB)
1758 return;
1759
1760 MachineBasicBlock *Top = *LoopChain.begin();
1761 bool ViableTopFallthrough = false;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001762 for (MachineBasicBlock *Pred : Top->predecessors()) {
1763 BlockChain *PredChain = BlockToChain[Pred];
1764 if (!LoopBlockSet.count(Pred) &&
1765 (!PredChain || Pred == *std::prev(PredChain->end()))) {
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001766 ViableTopFallthrough = true;
1767 break;
1768 }
1769 }
1770
1771 // If the header has viable fallthrough, check whether the current loop
1772 // bottom is a viable exiting block. If so, bail out as rotating will
1773 // introduce an unnecessary branch.
1774 if (ViableTopFallthrough) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001775 MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
Chandler Carruth7a715da2015-03-05 03:19:05 +00001776 for (MachineBasicBlock *Succ : Bottom->successors()) {
1777 BlockChain *SuccChain = BlockToChain[Succ];
1778 if (!LoopBlockSet.count(Succ) &&
1779 (!SuccChain || Succ == *SuccChain->begin()))
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001780 return;
1781 }
1782 }
1783
David Majnemer0d955d02016-08-11 22:21:41 +00001784 BlockChain::iterator ExitIt = find(LoopChain, ExitingBB);
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001785 if (ExitIt == LoopChain.end())
1786 return;
1787
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001788 std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001789}
1790
Cong Hou7745dbc2015-10-19 23:16:40 +00001791/// \brief Attempt to rotate a loop based on profile data to reduce branch cost.
1792///
1793/// With profile data, we can determine the cost in terms of missed fall through
1794/// opportunities when rotating a loop chain and select the best rotation.
1795/// Basically, there are three kinds of cost to consider for each rotation:
1796/// 1. The possibly missed fall through edge (if it exists) from BB out of
1797/// the loop to the loop header.
1798/// 2. The possibly missed fall through edges (if they exist) from the loop
1799/// exits to BB out of the loop.
1800/// 3. The missed fall through edge (if it exists) from the last BB to the
1801/// first BB in the loop chain.
1802/// Therefore, the cost for a given rotation is the sum of costs listed above.
1803/// We select the best rotation with the smallest cost.
1804void MachineBlockPlacement::rotateLoopWithProfile(
Kyle Butte9425c4f2017-02-04 02:26:32 +00001805 BlockChain &LoopChain, const MachineLoop &L,
1806 const BlockFilterSet &LoopBlockSet) {
Cong Hou7745dbc2015-10-19 23:16:40 +00001807 auto HeaderBB = L.getHeader();
David Majnemer0d955d02016-08-11 22:21:41 +00001808 auto HeaderIter = find(LoopChain, HeaderBB);
Cong Hou7745dbc2015-10-19 23:16:40 +00001809 auto RotationPos = LoopChain.end();
1810
1811 BlockFrequency SmallestRotationCost = BlockFrequency::getMaxFrequency();
1812
1813 // A utility lambda that scales up a block frequency by dividing it by a
1814 // branch probability which is the reciprocal of the scale.
1815 auto ScaleBlockFrequency = [](BlockFrequency Freq,
1816 unsigned Scale) -> BlockFrequency {
1817 if (Scale == 0)
1818 return 0;
1819 // Use operator / between BlockFrequency and BranchProbability to implement
1820 // saturating multiplication.
1821 return Freq / BranchProbability(1, Scale);
1822 };
1823
1824 // Compute the cost of the missed fall-through edge to the loop header if the
1825 // chain head is not the loop header. As we only consider natural loops with
1826 // single header, this computation can be done only once.
1827 BlockFrequency HeaderFallThroughCost(0);
1828 for (auto *Pred : HeaderBB->predecessors()) {
1829 BlockChain *PredChain = BlockToChain[Pred];
1830 if (!LoopBlockSet.count(Pred) &&
1831 (!PredChain || Pred == *std::prev(PredChain->end()))) {
1832 auto EdgeFreq =
1833 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, HeaderBB);
1834 auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost);
1835 // If the predecessor has only an unconditional jump to the header, we
1836 // need to consider the cost of this jump.
1837 if (Pred->succ_size() == 1)
1838 FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost);
1839 HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost);
1840 }
1841 }
1842
1843 // Here we collect all exit blocks in the loop, and for each exit we find out
1844 // its hottest exit edge. For each loop rotation, we define the loop exit cost
1845 // as the sum of frequencies of exit edges we collect here, excluding the exit
1846 // edge from the tail of the loop chain.
1847 SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq;
1848 for (auto BB : LoopChain) {
Cong Houd97c1002015-12-01 05:29:22 +00001849 auto LargestExitEdgeProb = BranchProbability::getZero();
Cong Hou7745dbc2015-10-19 23:16:40 +00001850 for (auto *Succ : BB->successors()) {
1851 BlockChain *SuccChain = BlockToChain[Succ];
1852 if (!LoopBlockSet.count(Succ) &&
1853 (!SuccChain || Succ == *SuccChain->begin())) {
Cong Houd97c1002015-12-01 05:29:22 +00001854 auto SuccProb = MBPI->getEdgeProbability(BB, Succ);
1855 LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb);
Cong Hou7745dbc2015-10-19 23:16:40 +00001856 }
1857 }
Cong Houd97c1002015-12-01 05:29:22 +00001858 if (LargestExitEdgeProb > BranchProbability::getZero()) {
1859 auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb;
Cong Hou7745dbc2015-10-19 23:16:40 +00001860 ExitsWithFreq.emplace_back(BB, ExitFreq);
1861 }
1862 }
1863
1864 // In this loop we iterate every block in the loop chain and calculate the
1865 // cost assuming the block is the head of the loop chain. When the loop ends,
1866 // we should have found the best candidate as the loop chain's head.
1867 for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()),
1868 EndIter = LoopChain.end();
1869 Iter != EndIter; Iter++, TailIter++) {
1870 // TailIter is used to track the tail of the loop chain if the block we are
1871 // checking (pointed by Iter) is the head of the chain.
1872 if (TailIter == LoopChain.end())
1873 TailIter = LoopChain.begin();
1874
1875 auto TailBB = *TailIter;
1876
1877 // Calculate the cost by putting this BB to the top.
1878 BlockFrequency Cost = 0;
1879
1880 // If the current BB is the loop header, we need to take into account the
1881 // cost of the missed fall through edge from outside of the loop to the
1882 // header.
1883 if (Iter != HeaderIter)
1884 Cost += HeaderFallThroughCost;
1885
1886 // Collect the loop exit cost by summing up frequencies of all exit edges
1887 // except the one from the chain tail.
1888 for (auto &ExitWithFreq : ExitsWithFreq)
1889 if (TailBB != ExitWithFreq.first)
1890 Cost += ExitWithFreq.second;
1891
1892 // The cost of breaking the once fall-through edge from the tail to the top
1893 // of the loop chain. Here we need to consider three cases:
1894 // 1. If the tail node has only one successor, then we will get an
1895 // additional jmp instruction. So the cost here is (MisfetchCost +
1896 // JumpInstCost) * tail node frequency.
1897 // 2. If the tail node has two successors, then we may still get an
1898 // additional jmp instruction if the layout successor after the loop
1899 // chain is not its CFG successor. Note that the more frequently executed
1900 // jmp instruction will be put ahead of the other one. Assume the
1901 // frequency of those two branches are x and y, where x is the frequency
1902 // of the edge to the chain head, then the cost will be
1903 // (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency.
1904 // 3. If the tail node has more than two successors (this rarely happens),
1905 // we won't consider any additional cost.
1906 if (TailBB->isSuccessor(*Iter)) {
1907 auto TailBBFreq = MBFI->getBlockFreq(TailBB);
1908 if (TailBB->succ_size() == 1)
1909 Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(),
1910 MisfetchCost + JumpInstCost);
1911 else if (TailBB->succ_size() == 2) {
1912 auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter);
1913 auto TailToHeadFreq = TailBBFreq * TailToHeadProb;
1914 auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2)
1915 ? TailBBFreq * TailToHeadProb.getCompl()
1916 : TailToHeadFreq;
1917 Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) +
1918 ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost);
1919 }
1920 }
1921
Philip Reamesb9688f42016-03-02 21:45:13 +00001922 DEBUG(dbgs() << "The cost of loop rotation by making " << getBlockName(*Iter)
Cong Hou7745dbc2015-10-19 23:16:40 +00001923 << " to the top: " << Cost.getFrequency() << "\n");
1924
1925 if (Cost < SmallestRotationCost) {
1926 SmallestRotationCost = Cost;
1927 RotationPos = Iter;
1928 }
1929 }
1930
1931 if (RotationPos != LoopChain.end()) {
Philip Reamesb9688f42016-03-02 21:45:13 +00001932 DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos)
Cong Hou7745dbc2015-10-19 23:16:40 +00001933 << " to the top\n");
1934 std::rotate(LoopChain.begin(), RotationPos, LoopChain.end());
1935 }
1936}
1937
Cong Houb90b9e02015-11-02 21:24:00 +00001938/// \brief Collect blocks in the given loop that are to be placed.
1939///
1940/// When profile data is available, exclude cold blocks from the returned set;
1941/// otherwise, collect all blocks in the loop.
1942MachineBlockPlacement::BlockFilterSet
Kyle Butte9425c4f2017-02-04 02:26:32 +00001943MachineBlockPlacement::collectLoopBlockSet(const MachineLoop &L) {
Cong Houb90b9e02015-11-02 21:24:00 +00001944 BlockFilterSet LoopBlockSet;
1945
1946 // Filter cold blocks off from LoopBlockSet when profile data is available.
1947 // Collect the sum of frequencies of incoming edges to the loop header from
1948 // outside. If we treat the loop as a super block, this is the frequency of
1949 // the loop. Then for each block in the loop, we calculate the ratio between
1950 // its frequency and the frequency of the loop block. When it is too small,
1951 // don't add it to the loop chain. If there are outer loops, then this block
1952 // will be merged into the first outer loop chain for which this block is not
1953 // cold anymore. This needs precise profile data and we only do this when
1954 // profile data is available.
Xinliang David Li52530a72016-06-13 22:23:44 +00001955 if (F->getFunction()->getEntryCount()) {
Cong Houb90b9e02015-11-02 21:24:00 +00001956 BlockFrequency LoopFreq(0);
1957 for (auto LoopPred : L.getHeader()->predecessors())
1958 if (!L.contains(LoopPred))
1959 LoopFreq += MBFI->getBlockFreq(LoopPred) *
1960 MBPI->getEdgeProbability(LoopPred, L.getHeader());
1961
1962 for (MachineBasicBlock *LoopBB : L.getBlocks()) {
1963 auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency();
1964 if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio)
1965 continue;
1966 LoopBlockSet.insert(LoopBB);
1967 }
1968 } else
1969 LoopBlockSet.insert(L.block_begin(), L.block_end());
1970
1971 return LoopBlockSet;
1972}
1973
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001974/// \brief Forms basic block chains from the natural loop structures.
Chandler Carruth10281422011-10-21 06:46:38 +00001975///
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001976/// These chains are designed to preserve the existing *structure* of the code
1977/// as much as possible. We can then stitch the chains together in a way which
1978/// both preserves the topological structure and minimizes taken conditional
1979/// branches.
Kyle Butte9425c4f2017-02-04 02:26:32 +00001980void MachineBlockPlacement::buildLoopChains(const MachineLoop &L) {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001981 // First recurse through any nested loops, building chains for those inner
1982 // loops.
Kyle Butte9425c4f2017-02-04 02:26:32 +00001983 for (const MachineLoop *InnerLoop : L)
Xinliang David Li52530a72016-06-13 22:23:44 +00001984 buildLoopChains(*InnerLoop);
Chandler Carruth10281422011-10-21 06:46:38 +00001985
Xinliang David Li93926ac2016-07-01 05:46:48 +00001986 assert(BlockWorkList.empty());
1987 assert(EHPadWorkList.empty());
Xinliang David Li52530a72016-06-13 22:23:44 +00001988 BlockFilterSet LoopBlockSet = collectLoopBlockSet(L);
Chandler Carruth03adbd42011-11-27 13:34:33 +00001989
Cong Hou7745dbc2015-10-19 23:16:40 +00001990 // Check if we have profile data for this function. If yes, we will rotate
1991 // this loop by modeling costs more precisely which requires the profile data
1992 // for better layout.
1993 bool RotateLoopWithProfile =
Xinliang David Lif0ab6df2016-05-12 02:04:41 +00001994 ForcePreciseRotationCost ||
Xinliang David Li52530a72016-06-13 22:23:44 +00001995 (PreciseRotationCost && F->getFunction()->getEntryCount());
Cong Hou7745dbc2015-10-19 23:16:40 +00001996
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001997 // First check to see if there is an obviously preferable top block for the
1998 // loop. This will default to the header, but may end up as one of the
1999 // predecessors to the header if there is one which will result in strictly
2000 // fewer branches in the loop body.
Cong Hou7745dbc2015-10-19 23:16:40 +00002001 // When we use profile data to rotate the loop, this is unnecessary.
2002 MachineBasicBlock *LoopTop =
2003 RotateLoopWithProfile ? L.getHeader() : findBestLoopTop(L, LoopBlockSet);
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00002004
2005 // If we selected just the header for the loop top, look for a potentially
2006 // profitable exit block in the event that rotating the loop can eliminate
2007 // branches by placing an exit edge at the bottom.
Cong Hou7745dbc2015-10-19 23:16:40 +00002008 if (!RotateLoopWithProfile && LoopTop == L.getHeader())
Kyle Buttab9cca72016-10-27 21:37:20 +00002009 PreferredLoopExit = findBestLoopExit(L, LoopBlockSet);
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00002010
2011 BlockChain &LoopChain = *BlockToChain[LoopTop];
Chandler Carruth10281422011-10-21 06:46:38 +00002012
Chandler Carruth8d150782011-11-13 11:20:44 +00002013 // FIXME: This is a really lame way of walking the chains in the loop: we
2014 // walk the blocks, and use a set to prevent visiting a particular chain
2015 // twice.
Jakub Staszak90616162011-12-21 23:02:08 +00002016 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
Philip Reamesae27b232016-03-03 00:58:43 +00002017 assert(LoopChain.UnscheduledPredecessors == 0);
Jakub Staszak190c7122011-12-07 19:46:10 +00002018 UpdatedPreds.insert(&LoopChain);
Cong Houb90b9e02015-11-02 21:24:00 +00002019
Kyle Butte9425c4f2017-02-04 02:26:32 +00002020 for (const MachineBasicBlock *LoopBB : LoopBlockSet)
Xinliang David Li93926ac2016-07-01 05:46:48 +00002021 fillWorkLists(LoopBB, UpdatedPreds, &LoopBlockSet);
Chandler Carruth8d150782011-11-13 11:20:44 +00002022
Xinliang David Li93926ac2016-07-01 05:46:48 +00002023 buildChain(LoopTop, LoopChain, &LoopBlockSet);
Cong Hou7745dbc2015-10-19 23:16:40 +00002024
2025 if (RotateLoopWithProfile)
2026 rotateLoopWithProfile(LoopChain, L, LoopBlockSet);
2027 else
Kyle Buttab9cca72016-10-27 21:37:20 +00002028 rotateLoop(LoopChain, PreferredLoopExit, LoopBlockSet);
Chandler Carruth8d150782011-11-13 11:20:44 +00002029
2030 DEBUG({
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002031 // Crash at the end so we get all of the debugging output first.
2032 bool BadLoop = false;
Philip Reamesae27b232016-03-03 00:58:43 +00002033 if (LoopChain.UnscheduledPredecessors) {
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002034 BadLoop = true;
Chandler Carruth8d150782011-11-13 11:20:44 +00002035 dbgs() << "Loop chain contains a block without its preds placed!\n"
2036 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
2037 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002038 }
Chandler Carruth7a715da2015-03-05 03:19:05 +00002039 for (MachineBasicBlock *ChainBB : LoopChain) {
2040 dbgs() << " ... " << getBlockName(ChainBB) << "\n";
Rong Xu66827422016-11-16 20:50:06 +00002041 if (!LoopBlockSet.remove(ChainBB)) {
Chandler Carruth0a31d142011-11-14 10:55:53 +00002042 // We don't mark the loop as bad here because there are real situations
2043 // where this can occur. For example, with an unanalyzable fallthrough
Chandler Carruth99fe42f2011-11-23 10:35:36 +00002044 // from a loop block to a non-loop block or vice versa.
Chandler Carruth8d150782011-11-13 11:20:44 +00002045 dbgs() << "Loop chain contains a block not contained by the loop!\n"
2046 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
2047 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00002048 << " Bad block: " << getBlockName(ChainBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002049 }
Chandler Carruthccc7e422012-04-16 01:12:56 +00002050 }
Chandler Carruth8d150782011-11-13 11:20:44 +00002051
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002052 if (!LoopBlockSet.empty()) {
2053 BadLoop = true;
Kyle Butte9425c4f2017-02-04 02:26:32 +00002054 for (const MachineBasicBlock *LoopBB : LoopBlockSet)
Chandler Carruth8d150782011-11-13 11:20:44 +00002055 dbgs() << "Loop contains blocks never placed into a chain!\n"
2056 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
2057 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00002058 << " Bad block: " << getBlockName(LoopBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002059 }
2060 assert(!BadLoop && "Detected problems with the placement of this loop.");
Chandler Carruth8d150782011-11-13 11:20:44 +00002061 });
Xinliang David Li93926ac2016-07-01 05:46:48 +00002062
2063 BlockWorkList.clear();
2064 EHPadWorkList.clear();
Chandler Carruth10281422011-10-21 06:46:38 +00002065}
2066
Xinliang David Li52530a72016-06-13 22:23:44 +00002067void MachineBlockPlacement::buildCFGChains() {
Chandler Carruth8d150782011-11-13 11:20:44 +00002068 // Ensure that every BB in the function has an associated chain to simplify
2069 // the assumptions of the remaining algorithm.
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00002070 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
Xinliang David Li52530a72016-06-13 22:23:44 +00002071 for (MachineFunction::iterator FI = F->begin(), FE = F->end(); FI != FE;
2072 ++FI) {
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00002073 MachineBasicBlock *BB = &*FI;
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00002074 BlockChain *Chain =
2075 new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00002076 // Also, merge any blocks which we cannot reason about and must preserve
2077 // the exact fallthrough behavior for.
2078 for (;;) {
2079 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00002080 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002081 if (!TII->analyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00002082 break;
2083
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00002084 MachineFunction::iterator NextFI = std::next(FI);
2085 MachineBasicBlock *NextBB = &*NextFI;
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00002086 // Ensure that the layout successor is a viable block, as we know that
2087 // fallthrough is a possibility.
2088 assert(NextFI != FE && "Can't fallthrough past the last block.");
2089 DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
2090 << getBlockName(BB) << " -> " << getBlockName(NextBB)
2091 << "\n");
Craig Topperc0196b12014-04-14 00:51:57 +00002092 Chain->merge(NextBB, nullptr);
Hal Finkel34f9d6a2016-12-15 05:33:19 +00002093#ifndef NDEBUG
Sanjoy Dasd7389d62016-12-15 05:08:57 +00002094 BlocksWithUnanalyzableExits.insert(&*BB);
Hal Finkel34f9d6a2016-12-15 05:33:19 +00002095#endif
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00002096 FI = NextFI;
2097 BB = NextBB;
2098 }
2099 }
Chandler Carruth8d150782011-11-13 11:20:44 +00002100
2101 // Build any loop-based chains.
Sam McCall2a36eee2016-11-01 22:02:14 +00002102 PreferredLoopExit = nullptr;
Chandler Carruth7a715da2015-03-05 03:19:05 +00002103 for (MachineLoop *L : *MLI)
Xinliang David Li52530a72016-06-13 22:23:44 +00002104 buildLoopChains(*L);
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00002105
Xinliang David Li93926ac2016-07-01 05:46:48 +00002106 assert(BlockWorkList.empty());
2107 assert(EHPadWorkList.empty());
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00002108
Chandler Carruth8d150782011-11-13 11:20:44 +00002109 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
Xinliang David Li52530a72016-06-13 22:23:44 +00002110 for (MachineBasicBlock &MBB : *F)
Xinliang David Li93926ac2016-07-01 05:46:48 +00002111 fillWorkLists(&MBB, UpdatedPreds);
Chandler Carruth8d150782011-11-13 11:20:44 +00002112
Xinliang David Li52530a72016-06-13 22:23:44 +00002113 BlockChain &FunctionChain = *BlockToChain[&F->front()];
Xinliang David Li93926ac2016-07-01 05:46:48 +00002114 buildChain(&F->front(), FunctionChain);
Chandler Carruth8d150782011-11-13 11:20:44 +00002115
Matt Arsenault0f5f0152013-12-10 18:55:37 +00002116#ifndef NDEBUG
Matt Arsenault79d55f52013-12-05 20:02:18 +00002117 typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType;
Matt Arsenault0f5f0152013-12-10 18:55:37 +00002118#endif
Chandler Carruth8d150782011-11-13 11:20:44 +00002119 DEBUG({
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002120 // Crash at the end so we get all of the debugging output first.
2121 bool BadFunc = false;
Chandler Carruth8d150782011-11-13 11:20:44 +00002122 FunctionBlockSetType FunctionBlockSet;
Xinliang David Li52530a72016-06-13 22:23:44 +00002123 for (MachineBasicBlock &MBB : *F)
Chandler Carruth7a715da2015-03-05 03:19:05 +00002124 FunctionBlockSet.insert(&MBB);
Chandler Carruth8d150782011-11-13 11:20:44 +00002125
Chandler Carruth7a715da2015-03-05 03:19:05 +00002126 for (MachineBasicBlock *ChainBB : FunctionChain)
2127 if (!FunctionBlockSet.erase(ChainBB)) {
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002128 BadFunc = true;
Chandler Carruth8d150782011-11-13 11:20:44 +00002129 dbgs() << "Function chain contains a block not in the function!\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00002130 << " Bad block: " << getBlockName(ChainBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002131 }
Chandler Carruth8d150782011-11-13 11:20:44 +00002132
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002133 if (!FunctionBlockSet.empty()) {
2134 BadFunc = true;
Chandler Carruth7a715da2015-03-05 03:19:05 +00002135 for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
Chandler Carruth8d150782011-11-13 11:20:44 +00002136 dbgs() << "Function contains blocks never placed into a chain!\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00002137 << " Bad block: " << getBlockName(RemainingBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002138 }
2139 assert(!BadFunc && "Detected problems with the block placement.");
Chandler Carruth8d150782011-11-13 11:20:44 +00002140 });
2141
2142 // Splice the blocks into place.
Xinliang David Li52530a72016-06-13 22:23:44 +00002143 MachineFunction::iterator InsertPos = F->begin();
Xinliang David Li449cdfd2016-06-24 22:54:21 +00002144 DEBUG(dbgs() << "[MBP] Function: "<< F->getName() << "\n");
Chandler Carruth7a715da2015-03-05 03:19:05 +00002145 for (MachineBasicBlock *ChainBB : FunctionChain) {
2146 DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
2147 : " ... ")
2148 << getBlockName(ChainBB) << "\n");
2149 if (InsertPos != MachineFunction::iterator(ChainBB))
Xinliang David Li52530a72016-06-13 22:23:44 +00002150 F->splice(InsertPos, ChainBB);
Chandler Carruth8d150782011-11-13 11:20:44 +00002151 else
2152 ++InsertPos;
2153
2154 // Update the terminator of the previous block.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002155 if (ChainBB == *FunctionChain.begin())
Chandler Carruth8d150782011-11-13 11:20:44 +00002156 continue;
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00002157 MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB));
Chandler Carruth8d150782011-11-13 11:20:44 +00002158
Chandler Carruth10281422011-10-21 06:46:38 +00002159 // FIXME: It would be awesome of updateTerminator would just return rather
2160 // than assert when the branch cannot be analyzed in order to remove this
2161 // boiler plate.
2162 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00002163 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Shuxin Yang8b8fd212013-06-04 01:00:57 +00002164
Sanjoy Dasd7389d62016-12-15 05:08:57 +00002165#ifndef NDEBUG
2166 if (!BlocksWithUnanalyzableExits.count(PrevBB)) {
2167 // Given the exact block placement we chose, we may actually not _need_ to
2168 // be able to edit PrevBB's terminator sequence, but not being _able_ to
2169 // do that at this point is a bug.
2170 assert((!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond) ||
2171 !PrevBB->canFallThrough()) &&
2172 "Unexpected block with un-analyzable fallthrough!");
2173 Cond.clear();
2174 TBB = FBB = nullptr;
2175 }
2176#endif
2177
Haicheng Wu90a55652016-05-24 22:16:14 +00002178 // The "PrevBB" is not yet updated to reflect current code layout, so,
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00002179 // o. it may fall-through to a block without explicit "goto" instruction
Haicheng Wu90a55652016-05-24 22:16:14 +00002180 // before layout, and no longer fall-through it after layout; or
2181 // o. just opposite.
2182 //
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002183 // analyzeBranch() may return erroneous value for FBB when these two
Haicheng Wu90a55652016-05-24 22:16:14 +00002184 // situations take place. For the first scenario FBB is mistakenly set NULL;
2185 // for the 2nd scenario, the FBB, which is expected to be NULL, is
2186 // mistakenly pointing to "*BI".
2187 // Thus, if the future change needs to use FBB before the layout is set, it
2188 // has to correct FBB first by using the code similar to the following:
2189 //
2190 // if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
2191 // PrevBB->updateTerminator();
2192 // Cond.clear();
2193 // TBB = FBB = nullptr;
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002194 // if (TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) {
Haicheng Wu90a55652016-05-24 22:16:14 +00002195 // // FIXME: This should never take place.
2196 // TBB = FBB = nullptr;
2197 // }
2198 // }
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002199 if (!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond))
Haicheng Wu90a55652016-05-24 22:16:14 +00002200 PrevBB->updateTerminator();
Chandler Carruth10281422011-10-21 06:46:38 +00002201 }
Chandler Carruth8d150782011-11-13 11:20:44 +00002202
2203 // Fixup the last block.
2204 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00002205 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002206 if (!TII->analyzeBranch(F->back(), TBB, FBB, Cond))
Xinliang David Li52530a72016-06-13 22:23:44 +00002207 F->back().updateTerminator();
Xinliang David Li93926ac2016-07-01 05:46:48 +00002208
2209 BlockWorkList.clear();
2210 EHPadWorkList.clear();
Haicheng Wu90a55652016-05-24 22:16:14 +00002211}
2212
Xinliang David Li52530a72016-06-13 22:23:44 +00002213void MachineBlockPlacement::optimizeBranches() {
2214 BlockChain &FunctionChain = *BlockToChain[&F->front()];
Haicheng Wu90a55652016-05-24 22:16:14 +00002215 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
Quentin Colombet776e6de2016-05-02 22:58:59 +00002216
2217 // Now that all the basic blocks in the chain have the proper layout,
2218 // make a final call to AnalyzeBranch with AllowModify set.
2219 // Indeed, the target may be able to optimize the branches in a way we
2220 // cannot because all branches may not be analyzable.
2221 // E.g., the target may be able to remove an unconditional branch to
2222 // a fallthrough when it occurs after predicated terminators.
2223 for (MachineBasicBlock *ChainBB : FunctionChain) {
2224 Cond.clear();
Haicheng Wu90a55652016-05-24 22:16:14 +00002225 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002226 if (!TII->analyzeBranch(*ChainBB, TBB, FBB, Cond, /*AllowModify*/ true)) {
Haicheng Wu90a55652016-05-24 22:16:14 +00002227 // If PrevBB has a two-way branch, try to re-order the branches
2228 // such that we branch to the successor with higher probability first.
2229 if (TBB && !Cond.empty() && FBB &&
2230 MBPI->getEdgeProbability(ChainBB, FBB) >
2231 MBPI->getEdgeProbability(ChainBB, TBB) &&
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00002232 !TII->reverseBranchCondition(Cond)) {
Haicheng Wu90a55652016-05-24 22:16:14 +00002233 DEBUG(dbgs() << "Reverse order of the two branches: "
2234 << getBlockName(ChainBB) << "\n");
2235 DEBUG(dbgs() << " Edge probability: "
2236 << MBPI->getEdgeProbability(ChainBB, FBB) << " vs "
2237 << MBPI->getEdgeProbability(ChainBB, TBB) << "\n");
2238 DebugLoc dl; // FIXME: this is nowhere
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00002239 TII->removeBranch(*ChainBB);
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00002240 TII->insertBranch(*ChainBB, FBB, TBB, Cond, dl);
Haicheng Wu90a55652016-05-24 22:16:14 +00002241 ChainBB->updateTerminator();
2242 }
2243 }
Quentin Colombet776e6de2016-05-02 22:58:59 +00002244 }
Haicheng Wue749ce52016-04-29 17:06:44 +00002245}
Chandler Carruth10281422011-10-21 06:46:38 +00002246
Xinliang David Li52530a72016-06-13 22:23:44 +00002247void MachineBlockPlacement::alignBlocks() {
Chandler Carruthccc7e422012-04-16 01:12:56 +00002248 // Walk through the backedges of the function now that we have fully laid out
2249 // the basic blocks and align the destination of each backedge. We don't rely
Chandler Carruth881d0a72012-08-07 09:45:24 +00002250 // exclusively on the loop info here so that we can align backedges in
2251 // unnatural CFGs and backedges that were introduced purely because of the
2252 // loop rotations done during this layout pass.
Xinliang David Li52530a72016-06-13 22:23:44 +00002253 if (F->getFunction()->optForSize())
Chandler Carruth8b9737c2011-10-21 08:57:37 +00002254 return;
Xinliang David Li52530a72016-06-13 22:23:44 +00002255 BlockChain &FunctionChain = *BlockToChain[&F->front()];
Chandler Carruth881d0a72012-08-07 09:45:24 +00002256 if (FunctionChain.begin() == FunctionChain.end())
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00002257 return; // Empty chain.
Chandler Carruth8b9737c2011-10-21 08:57:37 +00002258
Chandler Carruth881d0a72012-08-07 09:45:24 +00002259 const BranchProbability ColdProb(1, 5); // 20%
Xinliang David Li52530a72016-06-13 22:23:44 +00002260 BlockFrequency EntryFreq = MBFI->getBlockFreq(&F->front());
Chandler Carruth881d0a72012-08-07 09:45:24 +00002261 BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
Chandler Carruth7a715da2015-03-05 03:19:05 +00002262 for (MachineBasicBlock *ChainBB : FunctionChain) {
2263 if (ChainBB == *FunctionChain.begin())
2264 continue;
2265
Chandler Carruth881d0a72012-08-07 09:45:24 +00002266 // Don't align non-looping basic blocks. These are unlikely to execute
2267 // enough times to matter in practice. Note that we'll still handle
2268 // unnatural CFGs inside of a natural outer loop (the common case) and
2269 // rotated loops.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002270 MachineLoop *L = MLI->getLoopFor(ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00002271 if (!L)
2272 continue;
2273
Hal Finkel57725662015-01-03 17:58:24 +00002274 unsigned Align = TLI->getPrefLoopAlignment(L);
2275 if (!Align)
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00002276 continue; // Don't care about loop alignment.
Hal Finkel57725662015-01-03 17:58:24 +00002277
Chandler Carruth881d0a72012-08-07 09:45:24 +00002278 // If the block is cold relative to the function entry don't waste space
2279 // aligning it.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002280 BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00002281 if (Freq < WeightedEntryFreq)
2282 continue;
2283
2284 // If the block is cold relative to its loop header, don't align it
2285 // regardless of what edges into the block exist.
2286 MachineBasicBlock *LoopHeader = L->getHeader();
2287 BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
2288 if (Freq < (LoopHeaderFreq * ColdProb))
2289 continue;
2290
2291 // Check for the existence of a non-layout predecessor which would benefit
2292 // from aligning this block.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002293 MachineBasicBlock *LayoutPred =
2294 &*std::prev(MachineFunction::iterator(ChainBB));
Chandler Carruth881d0a72012-08-07 09:45:24 +00002295
2296 // Force alignment if all the predecessors are jumps. We already checked
2297 // that the block isn't cold above.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002298 if (!LayoutPred->isSuccessor(ChainBB)) {
2299 ChainBB->setAlignment(Align);
Chandler Carruth881d0a72012-08-07 09:45:24 +00002300 continue;
2301 }
2302
2303 // Align this block if the layout predecessor's edge into this block is
Nadav Rotem6036f582013-03-29 16:34:23 +00002304 // cold relative to the block. When this is true, other predecessors make up
Chandler Carruth881d0a72012-08-07 09:45:24 +00002305 // all of the hot entries into the block and thus alignment is likely to be
2306 // important.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002307 BranchProbability LayoutProb =
2308 MBPI->getEdgeProbability(LayoutPred, ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00002309 BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
2310 if (LayoutEdgeFreq <= (Freq * ColdProb))
Chandler Carruth7a715da2015-03-05 03:19:05 +00002311 ChainBB->setAlignment(Align);
Chandler Carruthccc7e422012-04-16 01:12:56 +00002312 }
Chandler Carruth8b9737c2011-10-21 08:57:37 +00002313}
2314
Kyle Butt0846e562016-10-11 20:36:43 +00002315/// Tail duplicate \p BB into (some) predecessors if profitable, repeating if
2316/// it was duplicated into its chain predecessor and removed.
2317/// \p BB - Basic block that may be duplicated.
2318///
2319/// \p LPred - Chosen layout predecessor of \p BB.
2320/// Updated to be the chain end if LPred is removed.
2321/// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
2322/// \p BlockFilter - Set of blocks that belong to the loop being laid out.
2323/// Used to identify which blocks to update predecessor
2324/// counts.
2325/// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
2326/// chosen in the given order due to unnatural CFG
2327/// only needed if \p BB is removed and
2328/// \p PrevUnplacedBlockIt pointed to \p BB.
2329/// @return true if \p BB was removed.
2330bool MachineBlockPlacement::repeatedlyTailDuplicateBlock(
2331 MachineBasicBlock *BB, MachineBasicBlock *&LPred,
Kyle Butte9425c4f2017-02-04 02:26:32 +00002332 const MachineBasicBlock *LoopHeaderBB,
Kyle Butt0846e562016-10-11 20:36:43 +00002333 BlockChain &Chain, BlockFilterSet *BlockFilter,
2334 MachineFunction::iterator &PrevUnplacedBlockIt) {
2335 bool Removed, DuplicatedToLPred;
2336 bool DuplicatedToOriginalLPred;
2337 Removed = maybeTailDuplicateBlock(BB, LPred, Chain, BlockFilter,
2338 PrevUnplacedBlockIt,
2339 DuplicatedToLPred);
2340 if (!Removed)
2341 return false;
2342 DuplicatedToOriginalLPred = DuplicatedToLPred;
2343 // Iteratively try to duplicate again. It can happen that a block that is
2344 // duplicated into is still small enough to be duplicated again.
2345 // No need to call markBlockSuccessors in this case, as the blocks being
2346 // duplicated from here on are already scheduled.
2347 // Note that DuplicatedToLPred always implies Removed.
2348 while (DuplicatedToLPred) {
2349 assert (Removed && "Block must have been removed to be duplicated into its "
2350 "layout predecessor.");
2351 MachineBasicBlock *DupBB, *DupPred;
2352 // The removal callback causes Chain.end() to be updated when a block is
2353 // removed. On the first pass through the loop, the chain end should be the
2354 // same as it was on function entry. On subsequent passes, because we are
2355 // duplicating the block at the end of the chain, if it is removed the
2356 // chain will have shrunk by one block.
2357 BlockChain::iterator ChainEnd = Chain.end();
2358 DupBB = *(--ChainEnd);
2359 // Now try to duplicate again.
2360 if (ChainEnd == Chain.begin())
2361 break;
2362 DupPred = *std::prev(ChainEnd);
2363 Removed = maybeTailDuplicateBlock(DupBB, DupPred, Chain, BlockFilter,
2364 PrevUnplacedBlockIt,
2365 DuplicatedToLPred);
2366 }
2367 // If BB was duplicated into LPred, it is now scheduled. But because it was
2368 // removed, markChainSuccessors won't be called for its chain. Instead we
2369 // call markBlockSuccessors for LPred to achieve the same effect. This must go
2370 // at the end because repeating the tail duplication can increase the number
2371 // of unscheduled predecessors.
2372 LPred = *std::prev(Chain.end());
2373 if (DuplicatedToOriginalLPred)
2374 markBlockSuccessors(Chain, LPred, LoopHeaderBB, BlockFilter);
2375 return true;
2376}
2377
2378/// Tail duplicate \p BB into (some) predecessors if profitable.
2379/// \p BB - Basic block that may be duplicated
2380/// \p LPred - Chosen layout predecessor of \p BB
2381/// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
2382/// \p BlockFilter - Set of blocks that belong to the loop being laid out.
2383/// Used to identify which blocks to update predecessor
2384/// counts.
2385/// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
2386/// chosen in the given order due to unnatural CFG
2387/// only needed if \p BB is removed and
2388/// \p PrevUnplacedBlockIt pointed to \p BB.
2389/// \p DuplicatedToLPred - True if the block was duplicated into LPred. Will
2390/// only be true if the block was removed.
2391/// \return - True if the block was duplicated into all preds and removed.
2392bool MachineBlockPlacement::maybeTailDuplicateBlock(
2393 MachineBasicBlock *BB, MachineBasicBlock *LPred,
Kyle Butte9425c4f2017-02-04 02:26:32 +00002394 BlockChain &Chain, BlockFilterSet *BlockFilter,
Kyle Butt0846e562016-10-11 20:36:43 +00002395 MachineFunction::iterator &PrevUnplacedBlockIt,
2396 bool &DuplicatedToLPred) {
Kyle Butt0846e562016-10-11 20:36:43 +00002397 DuplicatedToLPred = false;
Kyle Buttc7d67eef2017-02-04 02:26:34 +00002398 if (!shouldTailDuplicate(BB))
2399 return false;
2400
Kyle Butt0846e562016-10-11 20:36:43 +00002401 DEBUG(dbgs() << "Redoing tail duplication for Succ#"
2402 << BB->getNumber() << "\n");
Kyle Buttb15c0662017-01-31 23:48:32 +00002403
Kyle Butt0846e562016-10-11 20:36:43 +00002404 // This has to be a callback because none of it can be done after
2405 // BB is deleted.
2406 bool Removed = false;
2407 auto RemovalCallback =
2408 [&](MachineBasicBlock *RemBB) {
2409 // Signal to outer function
2410 Removed = true;
2411
2412 // Conservative default.
2413 bool InWorkList = true;
2414 // Remove from the Chain and Chain Map
2415 if (BlockToChain.count(RemBB)) {
2416 BlockChain *Chain = BlockToChain[RemBB];
2417 InWorkList = Chain->UnscheduledPredecessors == 0;
2418 Chain->remove(RemBB);
2419 BlockToChain.erase(RemBB);
2420 }
2421
2422 // Handle the unplaced block iterator
2423 if (&(*PrevUnplacedBlockIt) == RemBB) {
2424 PrevUnplacedBlockIt++;
2425 }
2426
2427 // Handle the Work Lists
2428 if (InWorkList) {
2429 SmallVectorImpl<MachineBasicBlock *> &RemoveList = BlockWorkList;
2430 if (RemBB->isEHPad())
2431 RemoveList = EHPadWorkList;
2432 RemoveList.erase(
2433 remove_if(RemoveList,
2434 [RemBB](MachineBasicBlock *BB) {return BB == RemBB;}),
2435 RemoveList.end());
2436 }
2437
2438 // Handle the filter set
2439 if (BlockFilter) {
Rong Xu66827422016-11-16 20:50:06 +00002440 BlockFilter->remove(RemBB);
Kyle Butt0846e562016-10-11 20:36:43 +00002441 }
2442
2443 // Remove the block from loop info.
2444 MLI->removeBlock(RemBB);
Kyle Buttab9cca72016-10-27 21:37:20 +00002445 if (RemBB == PreferredLoopExit)
2446 PreferredLoopExit = nullptr;
Kyle Butt0846e562016-10-11 20:36:43 +00002447
Kyle Butt0846e562016-10-11 20:36:43 +00002448 DEBUG(dbgs() << "TailDuplicator deleted block: "
2449 << getBlockName(RemBB) << "\n");
2450 };
2451 auto RemovalCallbackRef =
2452 llvm::function_ref<void(MachineBasicBlock*)>(RemovalCallback);
2453
2454 SmallVector<MachineBasicBlock *, 8> DuplicatedPreds;
Kyle Buttb15c0662017-01-31 23:48:32 +00002455 bool IsSimple = TailDup.isSimpleBB(BB);
Kyle Butt0846e562016-10-11 20:36:43 +00002456 TailDup.tailDuplicateAndUpdate(IsSimple, BB, LPred,
2457 &DuplicatedPreds, &RemovalCallbackRef);
2458
2459 // Update UnscheduledPredecessors to reflect tail-duplication.
2460 DuplicatedToLPred = false;
2461 for (MachineBasicBlock *Pred : DuplicatedPreds) {
2462 // We're only looking for unscheduled predecessors that match the filter.
2463 BlockChain* PredChain = BlockToChain[Pred];
2464 if (Pred == LPred)
2465 DuplicatedToLPred = true;
2466 if (Pred == LPred || (BlockFilter && !BlockFilter->count(Pred))
2467 || PredChain == &Chain)
2468 continue;
2469 for (MachineBasicBlock *NewSucc : Pred->successors()) {
2470 if (BlockFilter && !BlockFilter->count(NewSucc))
2471 continue;
2472 BlockChain *NewChain = BlockToChain[NewSucc];
2473 if (NewChain != &Chain && NewChain != PredChain)
2474 NewChain->UnscheduledPredecessors++;
2475 }
2476 }
2477 return Removed;
2478}
2479
Xinliang David Li52530a72016-06-13 22:23:44 +00002480bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &MF) {
2481 if (skipFunction(*MF.getFunction()))
Andrew Kaylor50271f72016-05-03 22:32:30 +00002482 return false;
2483
Chandler Carruth10281422011-10-21 06:46:38 +00002484 // Check for single-block functions and skip them.
Xinliang David Li52530a72016-06-13 22:23:44 +00002485 if (std::next(MF.begin()) == MF.end())
Chandler Carruth10281422011-10-21 06:46:38 +00002486 return false;
2487
Xinliang David Li52530a72016-06-13 22:23:44 +00002488 F = &MF;
Chandler Carruth10281422011-10-21 06:46:38 +00002489 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002490 MBFI = llvm::make_unique<BranchFolder::MBFIWrapper>(
2491 getAnalysis<MachineBlockFrequencyInfo>());
Chandler Carruth8b9737c2011-10-21 08:57:37 +00002492 MLI = &getAnalysis<MachineLoopInfo>();
Xinliang David Li52530a72016-06-13 22:23:44 +00002493 TII = MF.getSubtarget().getInstrInfo();
2494 TLI = MF.getSubtarget().getTargetLowering();
Kyle Buttb15c0662017-01-31 23:48:32 +00002495 MPDT = nullptr;
Eric Christopher690f8e52016-11-01 22:15:50 +00002496
2497 // Initialize PreferredLoopExit to nullptr here since it may never be set if
2498 // there are no MachineLoops.
2499 PreferredLoopExit = nullptr;
2500
Kyle Butt0846e562016-10-11 20:36:43 +00002501 if (TailDupPlacement) {
Kyle Buttb15c0662017-01-31 23:48:32 +00002502 MPDT = &getAnalysis<MachinePostDominatorTree>();
2503 unsigned TailDupSize = TailDupPlacementThreshold;
Kyle Butt0846e562016-10-11 20:36:43 +00002504 if (MF.getFunction()->optForSize())
2505 TailDupSize = 1;
2506 TailDup.initMF(MF, MBPI, /* LayoutMode */ true, TailDupSize);
2507 }
2508
Chandler Carruth10281422011-10-21 06:46:38 +00002509 assert(BlockToChain.empty());
Chandler Carruth10281422011-10-21 06:46:38 +00002510
Xinliang David Li52530a72016-06-13 22:23:44 +00002511 buildCFGChains();
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002512
2513 // Changing the layout can create new tail merging opportunities.
2514 TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
2515 // TailMerge can create jump into if branches that make CFG irreducible for
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00002516 // HW that requires structured CFG.
Xinliang David Li52530a72016-06-13 22:23:44 +00002517 bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002518 PassConfig->getEnableTailMerge() &&
2519 BranchFoldPlacement;
2520 // No tail merging opportunities if the block number is less than four.
Xinliang David Li52530a72016-06-13 22:23:44 +00002521 if (MF.size() > 3 && EnableTailMerge) {
Kyle Buttb15c0662017-01-31 23:48:32 +00002522 unsigned TailMergeSize = TailDupPlacementThreshold + 1;
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002523 BranchFolder BF(/*EnableTailMerge=*/true, /*CommonHoist=*/false, *MBFI,
Kyle Butt64e42812016-08-18 18:57:29 +00002524 *MBPI, TailMergeSize);
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002525
Xinliang David Li52530a72016-06-13 22:23:44 +00002526 if (BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002527 getAnalysisIfAvailable<MachineModuleInfo>(), MLI,
2528 /*AfterBlockPlacement=*/true)) {
2529 // Redo the layout if tail merging creates/removes/moves blocks.
2530 BlockToChain.clear();
Kyle Butt13937612017-03-02 21:44:24 +00002531 // Must redo the post-dominator tree if blocks were changed.
Kyle Buttb15c0662017-01-31 23:48:32 +00002532 if (MPDT)
2533 MPDT->runOnMachineFunction(MF);
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002534 ChainAllocator.DestroyAll();
Xinliang David Li52530a72016-06-13 22:23:44 +00002535 buildCFGChains();
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002536 }
2537 }
2538
Xinliang David Li52530a72016-06-13 22:23:44 +00002539 optimizeBranches();
2540 alignBlocks();
Chandler Carruth10281422011-10-21 06:46:38 +00002541
Chandler Carruth10281422011-10-21 06:46:38 +00002542 BlockToChain.clear();
Chandler Carruthfd9b4d92011-11-14 10:57:23 +00002543 ChainAllocator.DestroyAll();
Chandler Carruth10281422011-10-21 06:46:38 +00002544
Nadav Rotemc0adc9f2013-04-12 01:24:16 +00002545 if (AlignAllBlock)
2546 // Align all of the blocks in the function to a specific alignment.
Xinliang David Li52530a72016-06-13 22:23:44 +00002547 for (MachineBasicBlock &MBB : MF)
Chandler Carruth7a715da2015-03-05 03:19:05 +00002548 MBB.setAlignment(AlignAllBlock);
Geoff Berry10494ac2016-01-21 17:25:52 +00002549 else if (AlignAllNonFallThruBlocks) {
2550 // Align all of the blocks that have no fall-through predecessors to a
2551 // specific alignment.
Xinliang David Li52530a72016-06-13 22:23:44 +00002552 for (auto MBI = std::next(MF.begin()), MBE = MF.end(); MBI != MBE; ++MBI) {
Geoff Berry10494ac2016-01-21 17:25:52 +00002553 auto LayoutPred = std::prev(MBI);
2554 if (!LayoutPred->isSuccessor(&*MBI))
2555 MBI->setAlignment(AlignAllNonFallThruBlocks);
2556 }
2557 }
Xinliang David Lifd3f6452017-01-29 01:57:02 +00002558 if (ViewBlockLayoutWithBFI != GVDT_None &&
2559 (ViewBlockFreqFuncName.empty() ||
2560 F->getFunction()->getName().equals(ViewBlockFreqFuncName))) {
Xinliang David Li538d6662017-02-15 19:21:04 +00002561 MBFI->view("MBP." + MF.getName(), false);
Xinliang David Lifd3f6452017-01-29 01:57:02 +00002562 }
Xinliang David Lifd3f6452017-01-29 01:57:02 +00002563
Nadav Rotemc0adc9f2013-04-12 01:24:16 +00002564
Chandler Carruth10281422011-10-21 06:46:38 +00002565 // We always return true as we have no way to track whether the final order
2566 // differs from the original order.
2567 return true;
2568}
Chandler Carruthae4e8002011-11-02 07:17:12 +00002569
2570namespace {
2571/// \brief A pass to compute block placement statistics.
2572///
2573/// A separate pass to compute interesting statistics for evaluating block
2574/// placement. This is separate from the actual placement pass so that they can
Benjamin Kramerbde91762012-06-02 10:20:22 +00002575/// be computed in the absence of any placement transformations or when using
Chandler Carruthae4e8002011-11-02 07:17:12 +00002576/// alternative placement strategies.
2577class MachineBlockPlacementStats : public MachineFunctionPass {
2578 /// \brief A handle to the branch probability pass.
2579 const MachineBranchProbabilityInfo *MBPI;
2580
2581 /// \brief A handle to the function-wide block frequency pass.
2582 const MachineBlockFrequencyInfo *MBFI;
2583
2584public:
2585 static char ID; // Pass identification, replacement for typeid
2586 MachineBlockPlacementStats() : MachineFunctionPass(ID) {
2587 initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
2588 }
2589
Craig Topper4584cd52014-03-07 09:26:03 +00002590 bool runOnMachineFunction(MachineFunction &F) override;
Chandler Carruthae4e8002011-11-02 07:17:12 +00002591
Craig Topper4584cd52014-03-07 09:26:03 +00002592 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruthae4e8002011-11-02 07:17:12 +00002593 AU.addRequired<MachineBranchProbabilityInfo>();
2594 AU.addRequired<MachineBlockFrequencyInfo>();
2595 AU.setPreservesAll();
2596 MachineFunctionPass::getAnalysisUsage(AU);
2597 }
Chandler Carruthae4e8002011-11-02 07:17:12 +00002598};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00002599}
Chandler Carruthae4e8002011-11-02 07:17:12 +00002600
2601char MachineBlockPlacementStats::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +00002602char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
Chandler Carruthae4e8002011-11-02 07:17:12 +00002603INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
2604 "Basic Block Placement Stats", false, false)
2605INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
2606INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
2607INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
2608 "Basic Block Placement Stats", false, false)
2609
Chandler Carruthae4e8002011-11-02 07:17:12 +00002610bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
2611 // Check for single-block functions and skip them.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002612 if (std::next(F.begin()) == F.end())
Chandler Carruthae4e8002011-11-02 07:17:12 +00002613 return false;
2614
2615 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
2616 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
2617
Chandler Carruth7a715da2015-03-05 03:19:05 +00002618 for (MachineBasicBlock &MBB : F) {
2619 BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00002620 Statistic &NumBranches =
Chandler Carruth7a715da2015-03-05 03:19:05 +00002621 (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00002622 Statistic &BranchTakenFreq =
Chandler Carruth7a715da2015-03-05 03:19:05 +00002623 (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
2624 for (MachineBasicBlock *Succ : MBB.successors()) {
Chandler Carruthae4e8002011-11-02 07:17:12 +00002625 // Skip if this successor is a fallthrough.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002626 if (MBB.isLayoutSuccessor(Succ))
Chandler Carruthae4e8002011-11-02 07:17:12 +00002627 continue;
2628
Chandler Carruth7a715da2015-03-05 03:19:05 +00002629 BlockFrequency EdgeFreq =
2630 BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
Chandler Carruthae4e8002011-11-02 07:17:12 +00002631 ++NumBranches;
2632 BranchTakenFreq += EdgeFreq.getFrequency();
2633 }
2634 }
2635
2636 return false;
2637}