blob: 4cfc128a8c1d61460c686feca130ad79299713b2 [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
Kyle Butt1fa60302017-03-03 01:00:22 +0000146// Heuristic for triangle chains.
147static cl::opt<unsigned> TriangleChainCount(
148 "triangle-chain-count",
149 cl::desc("Number of triangle-shaped-CFG's that need to be in a row for the "
150 "triangle tail duplication heuristic to kick in. 0 to disable."),
Kyle Butt08655992017-03-16 01:32:29 +0000151 cl::init(2),
Kyle Butt1fa60302017-03-03 01:00:22 +0000152 cl::Hidden);
153
Xinliang David Liff287372016-06-03 23:48:36 +0000154extern cl::opt<unsigned> StaticLikelyProb;
Dehao Chen9f2bdfb2016-06-14 22:27:17 +0000155extern cl::opt<unsigned> ProfileLikelyProb;
Xinliang David Liff287372016-06-03 23:48:36 +0000156
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000157// Internal option used to control BFI display only after MBP pass.
158// Defined in CodeGen/MachineBlockFrequencyInfo.cpp:
159// -view-block-layout-with-bfi=
Xinliang David Lifd3f6452017-01-29 01:57:02 +0000160extern cl::opt<GVDAGType> ViewBlockLayoutWithBFI;
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000161
162// Command line option to specify the name of the function for CFG dump
163// Defined in Analysis/BlockFrequencyInfo.cpp: -view-bfi-func-name=
Xinliang David Lifd3f6452017-01-29 01:57:02 +0000164extern cl::opt<std::string> ViewBlockFreqFuncName;
Xinliang David Lifd3f6452017-01-29 01:57:02 +0000165
Chandler Carruth10281422011-10-21 06:46:38 +0000166namespace {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000167class BlockChain;
Chandler Carruth10281422011-10-21 06:46:38 +0000168/// \brief Type for our function-wide basic block -> block chain mapping.
Kyle Butte9425c4f2017-02-04 02:26:32 +0000169typedef DenseMap<const MachineBasicBlock *, BlockChain *> BlockToChainMapType;
Chandler Carruth10281422011-10-21 06:46:38 +0000170}
171
172namespace {
173/// \brief A chain of blocks which will be laid out contiguously.
174///
175/// This is the datastructure representing a chain of consecutive blocks that
176/// are profitable to layout together in order to maximize fallthrough
Chandler Carruth9139f442012-06-26 05:16:37 +0000177/// probabilities and code locality. We also can use a block chain to represent
178/// a sequence of basic blocks which have some external (correctness)
179/// requirement for sequential layout.
Chandler Carruth10281422011-10-21 06:46:38 +0000180///
Chandler Carruth9139f442012-06-26 05:16:37 +0000181/// Chains can be built around a single basic block and can be merged to grow
182/// them. They participate in a block-to-chain mapping, which is updated
183/// automatically as chains are merged together.
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000184class BlockChain {
185 /// \brief The sequence of blocks belonging to this chain.
Chandler Carruth10281422011-10-21 06:46:38 +0000186 ///
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000187 /// This is the sequence of blocks for a particular chain. These will be laid
188 /// out in-order within the function.
189 SmallVector<MachineBasicBlock *, 4> Blocks;
Chandler Carruth10281422011-10-21 06:46:38 +0000190
191 /// \brief A handle to the function-wide basic block to block chain mapping.
192 ///
193 /// This is retained in each block chain to simplify the computation of child
194 /// block chains for SCC-formation and iteration. We store the edges to child
195 /// basic blocks, and map them back to their associated chains using this
196 /// structure.
197 BlockToChainMapType &BlockToChain;
198
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000199public:
Chandler Carruth10281422011-10-21 06:46:38 +0000200 /// \brief Construct a new BlockChain.
201 ///
202 /// This builds a new block chain representing a single basic block in the
203 /// function. It also registers itself as the chain that block participates
204 /// in with the BlockToChain mapping.
205 BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
Philip Reamesae27b232016-03-03 00:58:43 +0000206 : Blocks(1, BB), BlockToChain(BlockToChain), UnscheduledPredecessors(0) {
Chandler Carruth10281422011-10-21 06:46:38 +0000207 assert(BB && "Cannot create a chain with a null basic block");
208 BlockToChain[BB] = this;
209 }
210
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000211 /// \brief Iterator over blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000212 typedef SmallVectorImpl<MachineBasicBlock *>::iterator iterator;
Kyle Butte9425c4f2017-02-04 02:26:32 +0000213 typedef SmallVectorImpl<MachineBasicBlock *>::const_iterator const_iterator;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000214
215 /// \brief Beginning of blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000216 iterator begin() { return Blocks.begin(); }
Kyle Butte9425c4f2017-02-04 02:26:32 +0000217 const_iterator begin() const { return Blocks.begin(); }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000218
219 /// \brief End of blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000220 iterator end() { return Blocks.end(); }
Kyle Butte9425c4f2017-02-04 02:26:32 +0000221 const_iterator end() const { return Blocks.end(); }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000222
Kyle Butt0846e562016-10-11 20:36:43 +0000223 bool remove(MachineBasicBlock* BB) {
224 for(iterator i = begin(); i != end(); ++i) {
225 if (*i == BB) {
226 Blocks.erase(i);
227 return true;
228 }
229 }
230 return false;
231 }
232
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000233 /// \brief Merge a block chain into this one.
Chandler Carruth10281422011-10-21 06:46:38 +0000234 ///
235 /// This routine merges a block chain into this one. It takes care of forming
236 /// a contiguous sequence of basic blocks, updating the edge list, and
237 /// updating the block -> chain mapping. It does not free or tear down the
238 /// old chain, but the old chain's block list is no longer valid.
Jakub Staszak90616162011-12-21 23:02:08 +0000239 void merge(MachineBasicBlock *BB, BlockChain *Chain) {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000240 assert(BB);
241 assert(!Blocks.empty());
Chandler Carruth10281422011-10-21 06:46:38 +0000242
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000243 // Fast path in case we don't have a chain already.
244 if (!Chain) {
245 assert(!BlockToChain[BB]);
246 Blocks.push_back(BB);
247 BlockToChain[BB] = this;
248 return;
Chandler Carruth10281422011-10-21 06:46:38 +0000249 }
250
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000251 assert(BB == *Chain->begin());
252 assert(Chain->begin() != Chain->end());
Chandler Carruth10281422011-10-21 06:46:38 +0000253
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000254 // Update the incoming blocks to point to this chain, and add them to the
255 // chain structure.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000256 for (MachineBasicBlock *ChainBB : *Chain) {
257 Blocks.push_back(ChainBB);
258 assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain");
259 BlockToChain[ChainBB] = this;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000260 }
Chandler Carruth10281422011-10-21 06:46:38 +0000261 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000262
Chandler Carruth49158902012-04-08 14:37:01 +0000263#ifndef NDEBUG
264 /// \brief Dump the blocks in this chain.
Nico Weber7408c702014-01-03 22:53:37 +0000265 LLVM_DUMP_METHOD void dump() {
Chandler Carruth7a715da2015-03-05 03:19:05 +0000266 for (MachineBasicBlock *MBB : *this)
267 MBB->dump();
Chandler Carruth49158902012-04-08 14:37:01 +0000268 }
269#endif // NDEBUG
270
Philip Reamesae27b232016-03-03 00:58:43 +0000271 /// \brief Count of predecessors of any block within the chain which have not
272 /// yet been scheduled. In general, we will delay scheduling this chain
273 /// until those predecessors are scheduled (or we find a sufficiently good
274 /// reason to override this heuristic.) Note that when forming loop chains,
275 /// blocks outside the loop are ignored and treated as if they were already
276 /// scheduled.
Chandler Carruth8d150782011-11-13 11:20:44 +0000277 ///
Philip Reamesae27b232016-03-03 00:58:43 +0000278 /// Note: This field is reinitialized multiple times - once for each loop,
279 /// and then once for the function as a whole.
280 unsigned UnscheduledPredecessors;
Chandler Carruth10281422011-10-21 06:46:38 +0000281};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000282}
Chandler Carruth10281422011-10-21 06:46:38 +0000283
284namespace {
285class MachineBlockPlacement : public MachineFunctionPass {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000286 /// \brief A typedef for a block filter set.
Kyle Butte9425c4f2017-02-04 02:26:32 +0000287 typedef SmallSetVector<const MachineBasicBlock *, 16> BlockFilterSet;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000288
Kyle Buttb15c0662017-01-31 23:48:32 +0000289 /// Pair struct containing basic block and taildup profitiability
290 struct BlockAndTailDupResult {
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000291 MachineBasicBlock *BB;
Kyle Buttb15c0662017-01-31 23:48:32 +0000292 bool ShouldTailDup;
293 };
294
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000295 /// Triple struct containing edge weight and the edge.
296 struct WeightedEdge {
297 BlockFrequency Weight;
298 MachineBasicBlock *Src;
299 MachineBasicBlock *Dest;
300 };
301
Xinliang David Li93926ac2016-07-01 05:46:48 +0000302 /// \brief work lists of blocks that are ready to be laid out
303 SmallVector<MachineBasicBlock *, 16> BlockWorkList;
304 SmallVector<MachineBasicBlock *, 16> EHPadWorkList;
305
Kyle Buttebe6cc42017-02-23 21:22:24 +0000306 /// Edges that have already been computed as optimal.
307 DenseMap<const MachineBasicBlock *, BlockAndTailDupResult> ComputedEdges;
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000308
Xinliang David Li52530a72016-06-13 22:23:44 +0000309 /// \brief Machine Function
310 MachineFunction *F;
311
Chandler Carruth10281422011-10-21 06:46:38 +0000312 /// \brief A handle to the branch probability pass.
313 const MachineBranchProbabilityInfo *MBPI;
314
315 /// \brief A handle to the function-wide block frequency pass.
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000316 std::unique_ptr<BranchFolder::MBFIWrapper> MBFI;
Chandler Carruth10281422011-10-21 06:46:38 +0000317
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000318 /// \brief A handle to the loop info.
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000319 MachineLoopInfo *MLI;
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000320
Kyle Buttab9cca72016-10-27 21:37:20 +0000321 /// \brief Preferred loop exit.
322 /// Member variable for convenience. It may be removed by duplication deep
323 /// in the call stack.
324 MachineBasicBlock *PreferredLoopExit;
325
Chandler Carruth10281422011-10-21 06:46:38 +0000326 /// \brief A handle to the target's instruction info.
327 const TargetInstrInfo *TII;
328
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000329 /// \brief A handle to the target's lowering info.
Benjamin Kramer56b31bd2013-01-11 20:05:37 +0000330 const TargetLoweringBase *TLI;
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000331
Kyle Buttb15c0662017-01-31 23:48:32 +0000332 /// \brief A handle to the post dominator tree.
333 MachinePostDominatorTree *MPDT;
334
Kyle Butt0846e562016-10-11 20:36:43 +0000335 /// \brief Duplicator used to duplicate tails during placement.
336 ///
337 /// Placement decisions can open up new tail duplication opportunities, but
338 /// since tail duplication affects placement decisions of later blocks, it
339 /// must be done inline.
340 TailDuplicator TailDup;
341
Chandler Carruth10281422011-10-21 06:46:38 +0000342 /// \brief Allocator and owner of BlockChain structures.
343 ///
Chandler Carruth9139f442012-06-26 05:16:37 +0000344 /// We build BlockChains lazily while processing the loop structure of
345 /// a function. To reduce malloc traffic, we allocate them using this
346 /// slab-like allocator, and destroy them after the pass completes. An
347 /// important guarantee is that this allocator produces stable pointers to
348 /// the chains.
Chandler Carruth10281422011-10-21 06:46:38 +0000349 SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
350
351 /// \brief Function wide BasicBlock to BlockChain mapping.
352 ///
353 /// This mapping allows efficiently moving from any given basic block to the
354 /// BlockChain it participates in, if any. We use it to, among other things,
355 /// allow implicitly defining edges between chains as the existing edges
356 /// between basic blocks.
Kyle Butte9425c4f2017-02-04 02:26:32 +0000357 DenseMap<const MachineBasicBlock *, BlockChain *> BlockToChain;
Chandler Carruth10281422011-10-21 06:46:38 +0000358
Sanjoy Dasd7389d62016-12-15 05:08:57 +0000359#ifndef NDEBUG
360 /// The set of basic blocks that have terminators that cannot be fully
361 /// analyzed. These basic blocks cannot be re-ordered safely by
362 /// MachineBlockPlacement, and we must preserve physical layout of these
363 /// blocks and their successors through the pass.
364 SmallPtrSet<MachineBasicBlock *, 4> BlocksWithUnanalyzableExits;
365#endif
366
Kyle Butt0846e562016-10-11 20:36:43 +0000367 /// Decrease the UnscheduledPredecessors count for all blocks in chain, and
368 /// if the count goes to 0, add them to the appropriate work list.
Kyle Butte9425c4f2017-02-04 02:26:32 +0000369 void markChainSuccessors(
370 const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB,
371 const BlockFilterSet *BlockFilter = nullptr);
Kyle Butt0846e562016-10-11 20:36:43 +0000372
373 /// Decrease the UnscheduledPredecessors count for a single block, and
374 /// if the count goes to 0, add them to the appropriate work list.
375 void markBlockSuccessors(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000376 const BlockChain &Chain, const MachineBasicBlock *BB,
377 const MachineBasicBlock *LoopHeaderBB,
Kyle Butt0846e562016-10-11 20:36:43 +0000378 const BlockFilterSet *BlockFilter = nullptr);
379
Xinliang David Li594ffa32016-06-11 18:35:40 +0000380 BranchProbability
Kyle Butte9425c4f2017-02-04 02:26:32 +0000381 collectViableSuccessors(
382 const MachineBasicBlock *BB, const BlockChain &Chain,
383 const BlockFilterSet *BlockFilter,
384 SmallVector<MachineBasicBlock *, 4> &Successors);
385 bool shouldPredBlockBeOutlined(
386 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
387 const BlockChain &Chain, const BlockFilterSet *BlockFilter,
388 BranchProbability SuccProb, BranchProbability HotProb);
Kyle Butt0846e562016-10-11 20:36:43 +0000389 bool repeatedlyTailDuplicateBlock(
390 MachineBasicBlock *BB, MachineBasicBlock *&LPred,
Kyle Butte9425c4f2017-02-04 02:26:32 +0000391 const MachineBasicBlock *LoopHeaderBB,
Kyle Butt0846e562016-10-11 20:36:43 +0000392 BlockChain &Chain, BlockFilterSet *BlockFilter,
393 MachineFunction::iterator &PrevUnplacedBlockIt);
Kyle Butte9425c4f2017-02-04 02:26:32 +0000394 bool maybeTailDuplicateBlock(
395 MachineBasicBlock *BB, MachineBasicBlock *LPred,
396 BlockChain &Chain, BlockFilterSet *BlockFilter,
397 MachineFunction::iterator &PrevUnplacedBlockIt,
398 bool &DuplicatedToPred);
399 bool hasBetterLayoutPredecessor(
400 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
401 const BlockChain &SuccChain, BranchProbability SuccProb,
402 BranchProbability RealSuccProb, const BlockChain &Chain,
403 const BlockFilterSet *BlockFilter);
404 BlockAndTailDupResult selectBestSuccessor(
405 const MachineBasicBlock *BB, const BlockChain &Chain,
406 const BlockFilterSet *BlockFilter);
407 MachineBasicBlock *selectBestCandidateBlock(
408 const BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList);
409 MachineBasicBlock *getFirstUnplacedBlock(
410 const BlockChain &PlacedChain,
411 MachineFunction::iterator &PrevUnplacedBlockIt,
412 const BlockFilterSet *BlockFilter);
Amaury Secheteae09c22016-03-14 21:24:11 +0000413
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000414 /// \brief Add a basic block to the work list if it is appropriate.
Amaury Secheteae09c22016-03-14 21:24:11 +0000415 ///
416 /// If the optional parameter BlockFilter is provided, only MBB
417 /// present in the set will be added to the worklist. If nullptr
418 /// is provided, no filtering occurs.
Kyle Butte9425c4f2017-02-04 02:26:32 +0000419 void fillWorkLists(const MachineBasicBlock *MBB,
Amaury Secheteae09c22016-03-14 21:24:11 +0000420 SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
Amaury Secheteae09c22016-03-14 21:24:11 +0000421 const BlockFilterSet *BlockFilter);
Kyle Butte9425c4f2017-02-04 02:26:32 +0000422 void buildChain(const MachineBasicBlock *BB, BlockChain &Chain,
Kyle Butt0846e562016-10-11 20:36:43 +0000423 BlockFilterSet *BlockFilter = nullptr);
Kyle Butte9425c4f2017-02-04 02:26:32 +0000424 MachineBasicBlock *findBestLoopTop(
425 const MachineLoop &L, const BlockFilterSet &LoopBlockSet);
426 MachineBasicBlock *findBestLoopExit(
427 const MachineLoop &L, const BlockFilterSet &LoopBlockSet);
428 BlockFilterSet collectLoopBlockSet(const MachineLoop &L);
429 void buildLoopChains(const MachineLoop &L);
430 void rotateLoop(
431 BlockChain &LoopChain, const MachineBasicBlock *ExitingBB,
432 const BlockFilterSet &LoopBlockSet);
433 void rotateLoopWithProfile(
434 BlockChain &LoopChain, const MachineLoop &L,
435 const BlockFilterSet &LoopBlockSet);
Xinliang David Li52530a72016-06-13 22:23:44 +0000436 void buildCFGChains();
437 void optimizeBranches();
438 void alignBlocks();
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000439 /// Returns true if a block should be tail-duplicated to increase fallthrough
440 /// opportunities.
Kyle Buttb15c0662017-01-31 23:48:32 +0000441 bool shouldTailDuplicate(MachineBasicBlock *BB);
442 /// Check the edge frequencies to see if tail duplication will increase
443 /// fallthroughs.
444 bool isProfitableToTailDup(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000445 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
Kyle Buttb15c0662017-01-31 23:48:32 +0000446 BranchProbability AdjustedSumProb,
Kyle Butte9425c4f2017-02-04 02:26:32 +0000447 const BlockChain &Chain, const BlockFilterSet *BlockFilter);
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000448 /// Check for a trellis layout.
449 bool isTrellis(const MachineBasicBlock *BB,
450 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
451 const BlockChain &Chain, const BlockFilterSet *BlockFilter);
452 /// Get the best successor given a trellis layout.
453 BlockAndTailDupResult getBestTrellisSuccessor(
454 const MachineBasicBlock *BB,
455 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
456 BranchProbability AdjustedSumProb, const BlockChain &Chain,
457 const BlockFilterSet *BlockFilter);
458 /// Get the best pair of non-conflicting edges.
459 static std::pair<WeightedEdge, WeightedEdge> getBestNonConflictingEdges(
460 const MachineBasicBlock *BB,
Benjamin Kramerd71461c2017-04-12 13:26:28 +0000461 MutableArrayRef<SmallVector<WeightedEdge, 8>> Edges);
Kyle Buttb15c0662017-01-31 23:48:32 +0000462 /// Returns true if a block can tail duplicate into all unplaced
463 /// predecessors. Filters based on loop.
464 bool canTailDuplicateUnplacedPreds(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000465 const MachineBasicBlock *BB, MachineBasicBlock *Succ,
466 const BlockChain &Chain, const BlockFilterSet *BlockFilter);
Kyle Butt1fa60302017-03-03 01:00:22 +0000467 /// Find chains of triangles to tail-duplicate where a global analysis works,
468 /// but a local analysis would not find them.
469 void precomputeTriangleChains();
Chandler Carruth10281422011-10-21 06:46:38 +0000470
471public:
472 static char ID; // Pass identification, replacement for typeid
473 MachineBlockPlacement() : MachineFunctionPass(ID) {
474 initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
475 }
476
Craig Topper4584cd52014-03-07 09:26:03 +0000477 bool runOnMachineFunction(MachineFunction &F) override;
Chandler Carruth10281422011-10-21 06:46:38 +0000478
Craig Topper4584cd52014-03-07 09:26:03 +0000479 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth10281422011-10-21 06:46:38 +0000480 AU.addRequired<MachineBranchProbabilityInfo>();
481 AU.addRequired<MachineBlockFrequencyInfo>();
Kyle Buttb15c0662017-01-31 23:48:32 +0000482 if (TailDupPlacement)
483 AU.addRequired<MachinePostDominatorTree>();
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000484 AU.addRequired<MachineLoopInfo>();
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000485 AU.addRequired<TargetPassConfig>();
Chandler Carruth10281422011-10-21 06:46:38 +0000486 MachineFunctionPass::getAnalysisUsage(AU);
487 }
Chandler Carruth10281422011-10-21 06:46:38 +0000488};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000489}
Chandler Carruth10281422011-10-21 06:46:38 +0000490
491char MachineBlockPlacement::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000492char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
Chandler Carruthd0dced52015-03-05 02:28:25 +0000493INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement",
Chandler Carruth10281422011-10-21 06:46:38 +0000494 "Branch Probability Basic Block Placement", false, false)
495INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
496INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
Kyle Buttb15c0662017-01-31 23:48:32 +0000497INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree)
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000498INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
Chandler Carruthd0dced52015-03-05 02:28:25 +0000499INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement",
Chandler Carruth10281422011-10-21 06:46:38 +0000500 "Branch Probability Basic Block Placement", false, false)
501
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000502#ifndef NDEBUG
503/// \brief Helper to print the name of a MBB.
504///
505/// Only used by debug logging.
Kyle Butte9425c4f2017-02-04 02:26:32 +0000506static std::string getBlockName(const MachineBasicBlock *BB) {
Alp Tokere69170a2014-06-26 22:52:05 +0000507 std::string Result;
508 raw_string_ostream OS(Result);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000509 OS << "BB#" << BB->getNumber();
Philip Reamesb9688f42016-03-02 21:45:13 +0000510 OS << " ('" << BB->getName() << "')";
Alp Tokere69170a2014-06-26 22:52:05 +0000511 OS.flush();
512 return Result;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000513}
514#endif
515
Chandler Carrutheb4ec3a2011-11-13 11:34:55 +0000516/// \brief Mark a chain's successors as having one fewer preds.
517///
518/// When a chain is being merged into the "placed" chain, this routine will
519/// quickly walk the successors of each block in the chain and mark them as
520/// having one fewer active predecessor. It also adds any successors of this
Kyle Butt0846e562016-10-11 20:36:43 +0000521/// chain which reach the zero-predecessor state to the appropriate worklist.
Chandler Carruth8d150782011-11-13 11:20:44 +0000522void MachineBlockPlacement::markChainSuccessors(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000523 const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB,
Jakub Staszak90616162011-12-21 23:02:08 +0000524 const BlockFilterSet *BlockFilter) {
Chandler Carruth8d150782011-11-13 11:20:44 +0000525 // Walk all the blocks in this chain, marking their successors as having
526 // a predecessor placed.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000527 for (MachineBasicBlock *MBB : Chain) {
Kyle Butt0846e562016-10-11 20:36:43 +0000528 markBlockSuccessors(Chain, MBB, LoopHeaderBB, BlockFilter);
529 }
530}
Chandler Carruth10281422011-10-21 06:46:38 +0000531
Kyle Butt0846e562016-10-11 20:36:43 +0000532/// \brief Mark a single block's successors as having one fewer preds.
533///
534/// Under normal circumstances, this is only called by markChainSuccessors,
535/// but if a block that was to be placed is completely tail-duplicated away,
536/// and was duplicated into the chain end, we need to redo markBlockSuccessors
537/// for just that block.
538void MachineBlockPlacement::markBlockSuccessors(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000539 const BlockChain &Chain, const MachineBasicBlock *MBB,
540 const MachineBasicBlock *LoopHeaderBB, const BlockFilterSet *BlockFilter) {
Kyle Butt0846e562016-10-11 20:36:43 +0000541 // Add any successors for which this is the only un-placed in-loop
542 // predecessor to the worklist as a viable candidate for CFG-neutral
543 // placement. No subsequent placement of this block will violate the CFG
544 // shape, so we get to use heuristics to choose a favorable placement.
545 for (MachineBasicBlock *Succ : MBB->successors()) {
546 if (BlockFilter && !BlockFilter->count(Succ))
547 continue;
548 BlockChain &SuccChain = *BlockToChain[Succ];
549 // Disregard edges within a fixed chain, or edges to the loop header.
550 if (&Chain == &SuccChain || Succ == LoopHeaderBB)
551 continue;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000552
Kyle Butt0846e562016-10-11 20:36:43 +0000553 // This is a cross-chain edge that is within the loop, so decrement the
554 // loop predecessor count of the destination chain.
555 if (SuccChain.UnscheduledPredecessors == 0 ||
556 --SuccChain.UnscheduledPredecessors > 0)
557 continue;
558
559 auto *NewBB = *SuccChain.begin();
560 if (NewBB->isEHPad())
561 EHPadWorkList.push_back(NewBB);
562 else
563 BlockWorkList.push_back(NewBB);
Chandler Carruth10281422011-10-21 06:46:38 +0000564 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000565}
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000566
Xinliang David Li594ffa32016-06-11 18:35:40 +0000567/// This helper function collects the set of successors of block
568/// \p BB that are allowed to be its layout successors, and return
569/// the total branch probability of edges from \p BB to those
570/// blocks.
571BranchProbability MachineBlockPlacement::collectViableSuccessors(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000572 const MachineBasicBlock *BB, const BlockChain &Chain,
573 const BlockFilterSet *BlockFilter,
Xinliang David Li594ffa32016-06-11 18:35:40 +0000574 SmallVector<MachineBasicBlock *, 4> &Successors) {
Cong Houd97c1002015-12-01 05:29:22 +0000575 // Adjust edge probabilities by excluding edges pointing to blocks that is
576 // either not in BlockFilter or is already in the current chain. Consider the
577 // following CFG:
Cong Hou41cf1a52015-11-18 00:52:52 +0000578 //
579 // --->A
580 // | / \
581 // | B C
582 // | \ / \
583 // ----D E
584 //
585 // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after
586 // A->C is chosen as a fall-through, D won't be selected as a successor of C
587 // due to CFG constraint (the probability of C->D is not greater than
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000588 // HotProb to break top-order). If we exclude E that is not in BlockFilter
Xinliang David Li594ffa32016-06-11 18:35:40 +0000589 // when calculating the probability of C->D, D will be selected and we
590 // will get A C D B as the layout of this loop.
Cong Houd97c1002015-12-01 05:29:22 +0000591 auto AdjustedSumProb = BranchProbability::getOne();
Cong Hou41cf1a52015-11-18 00:52:52 +0000592 for (MachineBasicBlock *Succ : BB->successors()) {
593 bool SkipSucc = false;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000594 if (Succ->isEHPad() || (BlockFilter && !BlockFilter->count(Succ))) {
Cong Hou41cf1a52015-11-18 00:52:52 +0000595 SkipSucc = true;
596 } else {
597 BlockChain *SuccChain = BlockToChain[Succ];
598 if (SuccChain == &Chain) {
Cong Hou41cf1a52015-11-18 00:52:52 +0000599 SkipSucc = true;
600 } else if (Succ != *SuccChain->begin()) {
601 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> Mid chain!\n");
602 continue;
603 }
604 }
605 if (SkipSucc)
Cong Houd97c1002015-12-01 05:29:22 +0000606 AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ);
Cong Hou41cf1a52015-11-18 00:52:52 +0000607 else
608 Successors.push_back(Succ);
609 }
610
Xinliang David Li594ffa32016-06-11 18:35:40 +0000611 return AdjustedSumProb;
612}
613
614/// The helper function returns the branch probability that is adjusted
615/// or normalized over the new total \p AdjustedSumProb.
Xinliang David Li594ffa32016-06-11 18:35:40 +0000616static BranchProbability
617getAdjustedProbability(BranchProbability OrigProb,
618 BranchProbability AdjustedSumProb) {
619 BranchProbability SuccProb;
620 uint32_t SuccProbN = OrigProb.getNumerator();
621 uint32_t SuccProbD = AdjustedSumProb.getNumerator();
622 if (SuccProbN >= SuccProbD)
623 SuccProb = BranchProbability::getOne();
624 else
625 SuccProb = BranchProbability(SuccProbN, SuccProbD);
626
627 return SuccProb;
628}
629
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000630/// Check if \p BB has exactly the successors in \p Successors.
631static bool
632hasSameSuccessors(MachineBasicBlock &BB,
633 SmallPtrSetImpl<const MachineBasicBlock *> &Successors) {
634 if (BB.succ_size() != Successors.size())
635 return false;
636 // We don't want to count self-loops
637 if (Successors.count(&BB))
638 return false;
639 for (MachineBasicBlock *Succ : BB.successors())
640 if (!Successors.count(Succ))
641 return false;
642 return true;
643}
644
645/// Check if a block should be tail duplicated to increase fallthrough
646/// opportunities.
Kyle Buttb15c0662017-01-31 23:48:32 +0000647/// \p BB Block to check.
648bool MachineBlockPlacement::shouldTailDuplicate(MachineBasicBlock *BB) {
649 // Blocks with single successors don't create additional fallthrough
650 // opportunities. Don't duplicate them. TODO: When conditional exits are
651 // analyzable, allow them to be duplicated.
652 bool IsSimple = TailDup.isSimpleBB(BB);
653
654 if (BB->succ_size() == 1)
655 return false;
656 return TailDup.shouldTailDuplicate(IsSimple, *BB);
657}
658
659/// Compare 2 BlockFrequency's with a small penalty for \p A.
660/// In order to be conservative, we apply a X% penalty to account for
661/// increased icache pressure and static heuristics. For small frequencies
662/// we use only the numerators to improve accuracy. For simplicity, we assume the
663/// penalty is less than 100%
664/// TODO(iteratee): Use 64-bit fixed point edge frequencies everywhere.
665static bool greaterWithBias(BlockFrequency A, BlockFrequency B,
666 uint64_t EntryFreq) {
667 BranchProbability ThresholdProb(TailDupPlacementPenalty, 100);
668 BlockFrequency Gain = A - B;
669 return (Gain / ThresholdProb).getFrequency() >= EntryFreq;
670}
671
672/// Check the edge frequencies to see if tail duplication will increase
673/// fallthroughs. It only makes sense to call this function when
674/// \p Succ would not be chosen otherwise. Tail duplication of \p Succ is
675/// always locally profitable if we would have picked \p Succ without
676/// considering duplication.
677bool MachineBlockPlacement::isProfitableToTailDup(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000678 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
Kyle Buttb15c0662017-01-31 23:48:32 +0000679 BranchProbability QProb,
Kyle Butte9425c4f2017-02-04 02:26:32 +0000680 const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
Kyle Buttb15c0662017-01-31 23:48:32 +0000681 // We need to do a probability calculation to make sure this is profitable.
682 // First: does succ have a successor that post-dominates? This affects the
683 // calculation. The 2 relevant cases are:
684 // BB BB
685 // | \Qout | \Qout
686 // P| C |P C
687 // = C' = C'
688 // | /Qin | /Qin
689 // | / | /
690 // Succ Succ
691 // / \ | \ V
692 // U/ =V |U \
693 // / \ = D
694 // D E | /
695 // | /
696 // |/
697 // PDom
698 // '=' : Branch taken for that CFG edge
699 // In the second case, Placing Succ while duplicating it into C prevents the
700 // fallthrough of Succ into either D or PDom, because they now have C as an
701 // unplaced predecessor
702
703 // Start by figuring out which case we fall into
704 MachineBasicBlock *PDom = nullptr;
705 SmallVector<MachineBasicBlock *, 4> SuccSuccs;
706 // Only scan the relevant successors
707 auto AdjustedSuccSumProb =
708 collectViableSuccessors(Succ, Chain, BlockFilter, SuccSuccs);
709 BranchProbability PProb = MBPI->getEdgeProbability(BB, Succ);
710 auto BBFreq = MBFI->getBlockFreq(BB);
711 auto SuccFreq = MBFI->getBlockFreq(Succ);
712 BlockFrequency P = BBFreq * PProb;
713 BlockFrequency Qout = BBFreq * QProb;
714 uint64_t EntryFreq = MBFI->getEntryFreq();
715 // If there are no more successors, it is profitable to copy, as it strictly
716 // increases fallthrough.
717 if (SuccSuccs.size() == 0)
718 return greaterWithBias(P, Qout, EntryFreq);
719
720 auto BestSuccSucc = BranchProbability::getZero();
721 // Find the PDom or the best Succ if no PDom exists.
722 for (MachineBasicBlock *SuccSucc : SuccSuccs) {
723 auto Prob = MBPI->getEdgeProbability(Succ, SuccSucc);
724 if (Prob > BestSuccSucc)
725 BestSuccSucc = Prob;
726 if (PDom == nullptr)
727 if (MPDT->dominates(SuccSucc, Succ)) {
728 PDom = SuccSucc;
729 break;
730 }
731 }
732 // For the comparisons, we need to know Succ's best incoming edge that isn't
733 // from BB.
734 auto SuccBestPred = BlockFrequency(0);
735 for (MachineBasicBlock *SuccPred : Succ->predecessors()) {
736 if (SuccPred == Succ || SuccPred == BB
737 || BlockToChain[SuccPred] == &Chain
738 || (BlockFilter && !BlockFilter->count(SuccPred)))
739 continue;
740 auto Freq = MBFI->getBlockFreq(SuccPred)
741 * MBPI->getEdgeProbability(SuccPred, Succ);
742 if (Freq > SuccBestPred)
743 SuccBestPred = Freq;
744 }
745 // Qin is Succ's best unplaced incoming edge that isn't BB
746 BlockFrequency Qin = SuccBestPred;
747 // If it doesn't have a post-dominating successor, here is the calculation:
748 // BB BB
749 // | \Qout | \
750 // P| C | =
751 // = C' | C
752 // | /Qin | |
753 // | / | C' (+Succ)
754 // Succ Succ /|
755 // / \ | \/ |
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000756 // U/ =V | == |
Kyle Buttb15c0662017-01-31 23:48:32 +0000757 // / \ | / \|
758 // D E D E
759 // '=' : Branch taken for that CFG edge
760 // Cost in the first case is: P + V
761 // For this calculation, we always assume P > Qout. If Qout > P
762 // The result of this function will be ignored at the caller.
Kyle Buttee51a202017-04-10 22:28:18 +0000763 // Let F = SuccFreq - Qin
764 // Cost in the second case is: Qout + min(Qin, F) * U + max(Qin, F) * V
Kyle Buttb15c0662017-01-31 23:48:32 +0000765
766 if (PDom == nullptr || !Succ->isSuccessor(PDom)) {
767 BranchProbability UProb = BestSuccSucc;
768 BranchProbability VProb = AdjustedSuccSumProb - UProb;
Kyle Buttee51a202017-04-10 22:28:18 +0000769 BlockFrequency F = SuccFreq - Qin;
Kyle Buttb15c0662017-01-31 23:48:32 +0000770 BlockFrequency V = SuccFreq * VProb;
Kyle Buttee51a202017-04-10 22:28:18 +0000771 BlockFrequency QinU = std::min(Qin, F) * UProb;
Kyle Buttb15c0662017-01-31 23:48:32 +0000772 BlockFrequency BaseCost = P + V;
Kyle Buttee51a202017-04-10 22:28:18 +0000773 BlockFrequency DupCost = Qout + QinU + std::max(Qin, F) * VProb;
Kyle Buttb15c0662017-01-31 23:48:32 +0000774 return greaterWithBias(BaseCost, DupCost, EntryFreq);
775 }
776 BranchProbability UProb = MBPI->getEdgeProbability(Succ, PDom);
777 BranchProbability VProb = AdjustedSuccSumProb - UProb;
778 BlockFrequency U = SuccFreq * UProb;
779 BlockFrequency V = SuccFreq * VProb;
Kyle Buttee51a202017-04-10 22:28:18 +0000780 BlockFrequency F = SuccFreq - Qin;
Kyle Buttb15c0662017-01-31 23:48:32 +0000781 // If there is a post-dominating successor, here is the calculation:
782 // BB BB BB BB
Kyle Buttee51a202017-04-10 22:28:18 +0000783 // | \Qout | \ | \Qout | \
784 // |P C | = |P C | =
785 // = C' |P C = C' |P C
786 // | /Qin | | | /Qin | |
787 // | / | C' (+Succ) | / | C' (+Succ)
788 // Succ Succ /| Succ Succ /|
789 // | \ V | \/ | | \ V | \/ |
790 // |U \ |U /\ =? |U = |U /\ |
791 // = D = = =?| | D | = =|
792 // | / |/ D | / |/ D
793 // | / | / | = | /
794 // |/ | / |/ | =
795 // Dom Dom Dom Dom
Kyle Buttb15c0662017-01-31 23:48:32 +0000796 // '=' : Branch taken for that CFG edge
797 // The cost for taken branches in the first case is P + U
Kyle Buttee51a202017-04-10 22:28:18 +0000798 // Let F = SuccFreq - Qin
Kyle Buttb15c0662017-01-31 23:48:32 +0000799 // The cost in the second case (assuming independence), given the layout:
Kyle Buttee51a202017-04-10 22:28:18 +0000800 // BB, Succ, (C+Succ), D, Dom or the layout:
801 // BB, Succ, D, Dom, (C+Succ)
802 // is Qout + max(F, Qin) * U + min(F, Qin)
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000803 // compare P + U vs Qout + P * U + Qin.
Kyle Buttb15c0662017-01-31 23:48:32 +0000804 //
805 // The 3rd and 4th cases cover when Dom would be chosen to follow Succ.
806 //
807 // For the 3rd case, the cost is P + 2 * V
Kyle Buttee51a202017-04-10 22:28:18 +0000808 // For the 4th case, the cost is Qout + min(Qin, F) * U + max(Qin, F) * V + V
809 // We choose 4 over 3 when (P + V) > Qout + min(Qin, F) * U + max(Qin, F) * V
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000810 if (UProb > AdjustedSuccSumProb / 2 &&
811 !hasBetterLayoutPredecessor(Succ, PDom, *BlockToChain[PDom], UProb, UProb,
812 Chain, BlockFilter))
Kyle Buttb15c0662017-01-31 23:48:32 +0000813 // Cases 3 & 4
Kyle Buttee51a202017-04-10 22:28:18 +0000814 return greaterWithBias(
815 (P + V), (Qout + std::max(Qin, F) * VProb + std::min(Qin, F) * UProb),
816 EntryFreq);
Kyle Buttb15c0662017-01-31 23:48:32 +0000817 // Cases 1 & 2
Kyle Buttee51a202017-04-10 22:28:18 +0000818 return greaterWithBias((P + U),
819 (Qout + std::min(Qin, F) * AdjustedSuccSumProb +
820 std::max(Qin, F) * UProb),
821 EntryFreq);
Kyle Buttb15c0662017-01-31 23:48:32 +0000822}
823
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000824/// Check for a trellis layout. \p BB is the upper part of a trellis if its
825/// successors form the lower part of a trellis. A successor set S forms the
826/// lower part of a trellis if all of the predecessors of S are either in S or
827/// have all of S as successors. We ignore trellises where BB doesn't have 2
828/// successors because for fewer than 2, it's trivial, and for 3 or greater they
829/// are very uncommon and complex to compute optimally. Allowing edges within S
830/// is not strictly a trellis, but the same algorithm works, so we allow it.
831bool MachineBlockPlacement::isTrellis(
832 const MachineBasicBlock *BB,
833 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
834 const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
835 // Technically BB could form a trellis with branching factor higher than 2.
836 // But that's extremely uncommon.
837 if (BB->succ_size() != 2 || ViableSuccs.size() != 2)
838 return false;
839
840 SmallPtrSet<const MachineBasicBlock *, 2> Successors(BB->succ_begin(),
841 BB->succ_end());
842 // To avoid reviewing the same predecessors twice.
843 SmallPtrSet<const MachineBasicBlock *, 8> SeenPreds;
844
845 for (MachineBasicBlock *Succ : ViableSuccs) {
846 int PredCount = 0;
847 for (auto SuccPred : Succ->predecessors()) {
848 // Allow triangle successors, but don't count them.
Dehao Chenb197d5b2017-03-23 23:28:09 +0000849 if (Successors.count(SuccPred)) {
850 // Make sure that it is actually a triangle.
851 for (MachineBasicBlock *CheckSucc : SuccPred->successors())
852 if (!Successors.count(CheckSucc))
853 return false;
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000854 continue;
Dehao Chenb197d5b2017-03-23 23:28:09 +0000855 }
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000856 const BlockChain *PredChain = BlockToChain[SuccPred];
857 if (SuccPred == BB || (BlockFilter && !BlockFilter->count(SuccPred)) ||
858 PredChain == &Chain || PredChain == BlockToChain[Succ])
859 continue;
860 ++PredCount;
861 // Perform the successor check only once.
862 if (!SeenPreds.insert(SuccPred).second)
863 continue;
864 if (!hasSameSuccessors(*SuccPred, Successors))
865 return false;
866 }
867 // If one of the successors has only BB as a predecessor, it is not a
868 // trellis.
869 if (PredCount < 1)
870 return false;
871 }
872 return true;
873}
874
875/// Pick the highest total weight pair of edges that can both be laid out.
876/// The edges in \p Edges[0] are assumed to have a different destination than
877/// the edges in \p Edges[1]. Simple counting shows that the best pair is either
878/// the individual highest weight edges to the 2 different destinations, or in
879/// case of a conflict, one of them should be replaced with a 2nd best edge.
880std::pair<MachineBlockPlacement::WeightedEdge,
881 MachineBlockPlacement::WeightedEdge>
882MachineBlockPlacement::getBestNonConflictingEdges(
883 const MachineBasicBlock *BB,
Benjamin Kramerd71461c2017-04-12 13:26:28 +0000884 MutableArrayRef<SmallVector<MachineBlockPlacement::WeightedEdge, 8>>
885 Edges) {
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000886 // Sort the edges, and then for each successor, find the best incoming
887 // predecessor. If the best incoming predecessors aren't the same,
888 // then that is clearly the best layout. If there is a conflict, one of the
889 // successors will have to fallthrough from the second best predecessor. We
890 // compare which combination is better overall.
891
892 // Sort for highest frequency.
893 auto Cmp = [](WeightedEdge A, WeightedEdge B) { return A.Weight > B.Weight; };
894
895 std::stable_sort(Edges[0].begin(), Edges[0].end(), Cmp);
896 std::stable_sort(Edges[1].begin(), Edges[1].end(), Cmp);
897 auto BestA = Edges[0].begin();
898 auto BestB = Edges[1].begin();
899 // Arrange for the correct answer to be in BestA and BestB
900 // If the 2 best edges don't conflict, the answer is already there.
901 if (BestA->Src == BestB->Src) {
902 // Compare the total fallthrough of (Best + Second Best) for both pairs
903 auto SecondBestA = std::next(BestA);
904 auto SecondBestB = std::next(BestB);
905 BlockFrequency BestAScore = BestA->Weight + SecondBestB->Weight;
906 BlockFrequency BestBScore = BestB->Weight + SecondBestA->Weight;
907 if (BestAScore < BestBScore)
908 BestA = SecondBestA;
909 else
910 BestB = SecondBestB;
911 }
912 // Arrange for the BB edge to be in BestA if it exists.
913 if (BestB->Src == BB)
914 std::swap(BestA, BestB);
915 return std::make_pair(*BestA, *BestB);
916}
917
918/// Get the best successor from \p BB based on \p BB being part of a trellis.
919/// We only handle trellises with 2 successors, so the algorithm is
920/// straightforward: Find the best pair of edges that don't conflict. We find
921/// the best incoming edge for each successor in the trellis. If those conflict,
922/// we consider which of them should be replaced with the second best.
923/// Upon return the two best edges will be in \p BestEdges. If one of the edges
924/// comes from \p BB, it will be in \p BestEdges[0]
925MachineBlockPlacement::BlockAndTailDupResult
926MachineBlockPlacement::getBestTrellisSuccessor(
927 const MachineBasicBlock *BB,
928 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
929 BranchProbability AdjustedSumProb, const BlockChain &Chain,
930 const BlockFilterSet *BlockFilter) {
931
932 BlockAndTailDupResult Result = {nullptr, false};
933 SmallPtrSet<const MachineBasicBlock *, 4> Successors(BB->succ_begin(),
934 BB->succ_end());
935
936 // We assume size 2 because it's common. For general n, we would have to do
937 // the Hungarian algorithm, but it's not worth the complexity because more
938 // than 2 successors is fairly uncommon, and a trellis even more so.
939 if (Successors.size() != 2 || ViableSuccs.size() != 2)
940 return Result;
941
942 // Collect the edge frequencies of all edges that form the trellis.
Benjamin Kramerd71461c2017-04-12 13:26:28 +0000943 SmallVector<WeightedEdge, 8> Edges[2];
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000944 int SuccIndex = 0;
945 for (auto Succ : ViableSuccs) {
946 for (MachineBasicBlock *SuccPred : Succ->predecessors()) {
947 // Skip any placed predecessors that are not BB
948 if (SuccPred != BB)
949 if ((BlockFilter && !BlockFilter->count(SuccPred)) ||
950 BlockToChain[SuccPred] == &Chain ||
951 BlockToChain[SuccPred] == BlockToChain[Succ])
952 continue;
953 BlockFrequency EdgeFreq = MBFI->getBlockFreq(SuccPred) *
954 MBPI->getEdgeProbability(SuccPred, Succ);
955 Edges[SuccIndex].push_back({EdgeFreq, SuccPred, Succ});
956 }
957 ++SuccIndex;
958 }
959
960 // Pick the best combination of 2 edges from all the edges in the trellis.
961 WeightedEdge BestA, BestB;
962 std::tie(BestA, BestB) = getBestNonConflictingEdges(BB, Edges);
963
964 if (BestA.Src != BB) {
965 // If we have a trellis, and BB doesn't have the best fallthrough edges,
966 // we shouldn't choose any successor. We've already looked and there's a
967 // better fallthrough edge for all the successors.
968 DEBUG(dbgs() << "Trellis, but not one of the chosen edges.\n");
969 return Result;
970 }
971
972 // Did we pick the triangle edge? If tail-duplication is profitable, do
973 // that instead. Otherwise merge the triangle edge now while we know it is
974 // optimal.
975 if (BestA.Dest == BestB.Src) {
976 // The edges are BB->Succ1->Succ2, and we're looking to see if BB->Succ2
977 // would be better.
978 MachineBasicBlock *Succ1 = BestA.Dest;
979 MachineBasicBlock *Succ2 = BestB.Dest;
980 // Check to see if tail-duplication would be profitable.
981 if (TailDupPlacement && shouldTailDuplicate(Succ2) &&
982 canTailDuplicateUnplacedPreds(BB, Succ2, Chain, BlockFilter) &&
983 isProfitableToTailDup(BB, Succ2, MBPI->getEdgeProbability(BB, Succ1),
984 Chain, BlockFilter)) {
985 DEBUG(BranchProbability Succ2Prob = getAdjustedProbability(
986 MBPI->getEdgeProbability(BB, Succ2), AdjustedSumProb);
987 dbgs() << " Selected: " << getBlockName(Succ2)
988 << ", probability: " << Succ2Prob << " (Tail Duplicate)\n");
989 Result.BB = Succ2;
990 Result.ShouldTailDup = true;
991 return Result;
992 }
993 }
994 // We have already computed the optimal edge for the other side of the
995 // trellis.
Kyle Buttebe6cc42017-02-23 21:22:24 +0000996 ComputedEdges[BestB.Src] = { BestB.Dest, false };
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000997
998 auto TrellisSucc = BestA.Dest;
999 DEBUG(BranchProbability SuccProb = getAdjustedProbability(
1000 MBPI->getEdgeProbability(BB, TrellisSucc), AdjustedSumProb);
1001 dbgs() << " Selected: " << getBlockName(TrellisSucc)
1002 << ", probability: " << SuccProb << " (Trellis)\n");
1003 Result.BB = TrellisSucc;
1004 return Result;
1005}
Kyle Buttb15c0662017-01-31 23:48:32 +00001006
1007/// When the option TailDupPlacement is on, this method checks if the
1008/// fallthrough candidate block \p Succ (of block \p BB) can be tail-duplicated
1009/// into all of its unplaced, unfiltered predecessors, that are not BB.
1010bool MachineBlockPlacement::canTailDuplicateUnplacedPreds(
Kyle Butte9425c4f2017-02-04 02:26:32 +00001011 const MachineBasicBlock *BB, MachineBasicBlock *Succ,
1012 const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
Kyle Buttb15c0662017-01-31 23:48:32 +00001013 if (!shouldTailDuplicate(Succ))
1014 return false;
1015
Kyle Butt7fbec9b2017-02-15 19:49:14 +00001016 // For CFG checking.
1017 SmallPtrSet<const MachineBasicBlock *, 4> Successors(BB->succ_begin(),
1018 BB->succ_end());
Kyle Buttb15c0662017-01-31 23:48:32 +00001019 for (MachineBasicBlock *Pred : Succ->predecessors()) {
1020 // Make sure all unplaced and unfiltered predecessors can be
1021 // tail-duplicated into.
Kyle Butte9425c4f2017-02-04 02:26:32 +00001022 // Skip any blocks that are already placed or not in this loop.
Kyle Buttb15c0662017-01-31 23:48:32 +00001023 if (Pred == BB || (BlockFilter && !BlockFilter->count(Pred))
1024 || BlockToChain[Pred] == &Chain)
1025 continue;
Kyle Butt7fbec9b2017-02-15 19:49:14 +00001026 if (!TailDup.canTailDuplicate(Succ, Pred)) {
1027 if (Successors.size() > 1 && hasSameSuccessors(*Pred, Successors))
1028 // This will result in a trellis after tail duplication, so we don't
1029 // need to copy Succ into this predecessor. In the presence
1030 // of a trellis tail duplication can continue to be profitable.
1031 // For example:
1032 // A A
1033 // |\ |\
1034 // | \ | \
1035 // | C | C+BB
1036 // | / | |
1037 // |/ | |
1038 // BB => BB |
1039 // |\ |\/|
1040 // | \ |/\|
1041 // | D | D
1042 // | / | /
1043 // |/ |/
1044 // Succ Succ
1045 //
1046 // After BB was duplicated into C, the layout looks like the one on the
1047 // right. BB and C now have the same successors. When considering
1048 // whether Succ can be duplicated into all its unplaced predecessors, we
1049 // ignore C.
1050 // We can do this because C already has a profitable fallthrough, namely
1051 // D. TODO(iteratee): ignore sufficiently cold predecessors for
1052 // duplication and for this test.
1053 //
1054 // This allows trellises to be laid out in 2 separate chains
1055 // (A,B,Succ,...) and later (C,D,...) This is a reasonable heuristic
1056 // because it allows the creation of 2 fallthrough paths with links
1057 // between them, and we correctly identify the best layout for these
1058 // CFGs. We want to extend trellises that the user created in addition
1059 // to trellises created by tail-duplication, so we just look for the
1060 // CFG.
1061 continue;
Kyle Buttb15c0662017-01-31 23:48:32 +00001062 return false;
Kyle Butt7fbec9b2017-02-15 19:49:14 +00001063 }
Kyle Buttb15c0662017-01-31 23:48:32 +00001064 }
1065 return true;
1066}
1067
Kyle Butt1fa60302017-03-03 01:00:22 +00001068/// Find chains of triangles where we believe it would be profitable to
1069/// tail-duplicate them all, but a local analysis would not find them.
1070/// There are 3 ways this can be profitable:
1071/// 1) The post-dominators marked 50% are actually taken 55% (This shrinks with
1072/// longer chains)
1073/// 2) The chains are statically correlated. Branch probabilities have a very
1074/// U-shaped distribution.
1075/// [http://nrs.harvard.edu/urn-3:HUL.InstRepos:24015805]
1076/// If the branches in a chain are likely to be from the same side of the
1077/// distribution as their predecessor, but are independent at runtime, this
1078/// transformation is profitable. (Because the cost of being wrong is a small
1079/// fixed cost, unlike the standard triangle layout where the cost of being
1080/// wrong scales with the # of triangles.)
1081/// 3) The chains are dynamically correlated. If the probability that a previous
1082/// branch was taken positively influences whether the next branch will be
1083/// taken
1084/// We believe that 2 and 3 are common enough to justify the small margin in 1.
1085void MachineBlockPlacement::precomputeTriangleChains() {
1086 struct TriangleChain {
Benjamin Kramerd71461c2017-04-12 13:26:28 +00001087 std::vector<MachineBasicBlock *> Edges;
1088 TriangleChain(MachineBasicBlock *src, MachineBasicBlock *dst)
1089 : Edges({src, dst}) {}
Kyle Butt1fa60302017-03-03 01:00:22 +00001090
1091 void append(MachineBasicBlock *dst) {
Benjamin Kramerd71461c2017-04-12 13:26:28 +00001092 assert(getKey()->isSuccessor(dst) &&
Kyle Butt1fa60302017-03-03 01:00:22 +00001093 "Attempting to append a block that is not a successor.");
Benjamin Kramerd71461c2017-04-12 13:26:28 +00001094 Edges.push_back(dst);
Kyle Butt1fa60302017-03-03 01:00:22 +00001095 }
1096
Benjamin Kramerd71461c2017-04-12 13:26:28 +00001097 unsigned count() const { return Edges.size() - 1; }
1098
1099 MachineBasicBlock *getKey() const {
1100 return Edges.back();
Kyle Butt1fa60302017-03-03 01:00:22 +00001101 }
1102 };
1103
1104 if (TriangleChainCount == 0)
1105 return;
1106
1107 DEBUG(dbgs() << "Pre-computing triangle chains.\n");
1108 // Map from last block to the chain that contains it. This allows us to extend
1109 // chains as we find new triangles.
1110 DenseMap<const MachineBasicBlock *, TriangleChain> TriangleChainMap;
1111 for (MachineBasicBlock &BB : *F) {
1112 // If BB doesn't have 2 successors, it doesn't start a triangle.
1113 if (BB.succ_size() != 2)
1114 continue;
1115 MachineBasicBlock *PDom = nullptr;
1116 for (MachineBasicBlock *Succ : BB.successors()) {
1117 if (!MPDT->dominates(Succ, &BB))
1118 continue;
1119 PDom = Succ;
1120 break;
1121 }
1122 // If BB doesn't have a post-dominating successor, it doesn't form a
1123 // triangle.
1124 if (PDom == nullptr)
1125 continue;
1126 // If PDom has a hint that it is low probability, skip this triangle.
1127 if (MBPI->getEdgeProbability(&BB, PDom) < BranchProbability(50, 100))
1128 continue;
1129 // If PDom isn't eligible for duplication, this isn't the kind of triangle
1130 // we're looking for.
1131 if (!shouldTailDuplicate(PDom))
1132 continue;
1133 bool CanTailDuplicate = true;
1134 // If PDom can't tail-duplicate into it's non-BB predecessors, then this
1135 // isn't the kind of triangle we're looking for.
1136 for (MachineBasicBlock* Pred : PDom->predecessors()) {
1137 if (Pred == &BB)
1138 continue;
1139 if (!TailDup.canTailDuplicate(PDom, Pred)) {
1140 CanTailDuplicate = false;
1141 break;
1142 }
1143 }
1144 // If we can't tail-duplicate PDom to its predecessors, then skip this
1145 // triangle.
1146 if (!CanTailDuplicate)
1147 continue;
1148
1149 // Now we have an interesting triangle. Insert it if it's not part of an
1150 // existing chain
1151 // Note: This cannot be replaced with a call insert() or emplace() because
1152 // the find key is BB, but the insert/emplace key is PDom.
1153 auto Found = TriangleChainMap.find(&BB);
1154 // If it is, remove the chain from the map, grow it, and put it back in the
1155 // map with the end as the new key.
1156 if (Found != TriangleChainMap.end()) {
1157 TriangleChain Chain = std::move(Found->second);
1158 TriangleChainMap.erase(Found);
1159 Chain.append(PDom);
1160 TriangleChainMap.insert(std::make_pair(Chain.getKey(), std::move(Chain)));
1161 } else {
1162 auto InsertResult = TriangleChainMap.try_emplace(PDom, &BB, PDom);
Benjamin Kramer33580692017-04-12 13:26:31 +00001163 assert(InsertResult.second && "Block seen twice.");
1164 (void)InsertResult;
Kyle Butt1fa60302017-03-03 01:00:22 +00001165 }
1166 }
1167
Kyle Butt336c78f2017-04-12 18:30:32 +00001168 // Iterating over a DenseMap is safe here, because the only thing in the body
1169 // of the loop is inserting into another DenseMap (ComputedEdges).
1170 // ComputedEdges is never iterated, so this doesn't lead to non-determinism.
Kyle Butt1fa60302017-03-03 01:00:22 +00001171 for (auto &ChainPair : TriangleChainMap) {
1172 TriangleChain &Chain = ChainPair.second;
1173 // Benchmarking has shown that due to branch correlation duplicating 2 or
1174 // more triangles is profitable, despite the calculations assuming
1175 // independence.
Benjamin Kramerd71461c2017-04-12 13:26:28 +00001176 if (Chain.count() < TriangleChainCount)
Kyle Butt1fa60302017-03-03 01:00:22 +00001177 continue;
Benjamin Kramerd71461c2017-04-12 13:26:28 +00001178 MachineBasicBlock *dst = Chain.Edges.back();
1179 Chain.Edges.pop_back();
1180 for (MachineBasicBlock *src : reverse(Chain.Edges)) {
Kyle Butt1fa60302017-03-03 01:00:22 +00001181 DEBUG(dbgs() << "Marking edge: " << getBlockName(src) << "->" <<
1182 getBlockName(dst) << " as pre-computed based on triangles.\n");
Benjamin Kramer33580692017-04-12 13:26:31 +00001183
1184 auto InsertResult = ComputedEdges.insert({src, {dst, true}});
1185 assert(InsertResult.second && "Block seen twice.");
1186 (void)InsertResult;
1187
Kyle Butt1fa60302017-03-03 01:00:22 +00001188 dst = src;
1189 }
1190 }
1191}
1192
Dehao Chen9f2bdfb2016-06-14 22:27:17 +00001193// When profile is not present, return the StaticLikelyProb.
1194// When profile is available, we need to handle the triangle-shape CFG.
1195static BranchProbability getLayoutSuccessorProbThreshold(
Kyle Butte9425c4f2017-02-04 02:26:32 +00001196 const MachineBasicBlock *BB) {
Dehao Chen9f2bdfb2016-06-14 22:27:17 +00001197 if (!BB->getParent()->getFunction()->getEntryCount())
1198 return BranchProbability(StaticLikelyProb, 100);
1199 if (BB->succ_size() == 2) {
1200 const MachineBasicBlock *Succ1 = *BB->succ_begin();
1201 const MachineBasicBlock *Succ2 = *(BB->succ_begin() + 1);
Xinliang David Lie34ed832016-06-15 03:03:30 +00001202 if (Succ1->isSuccessor(Succ2) || Succ2->isSuccessor(Succ1)) {
1203 /* See case 1 below for the cost analysis. For BB->Succ to
1204 * be taken with smaller cost, the following needs to hold:
Kyle Buttb15c0662017-01-31 23:48:32 +00001205 * Prob(BB->Succ) > 2 * Prob(BB->Pred)
1206 * So the threshold T in the calculation below
1207 * (1-T) * Prob(BB->Succ) > T * Prob(BB->Pred)
1208 * So T / (1 - T) = 2, Yielding T = 2/3
1209 * Also adding user specified branch bias, we have
Xinliang David Lie34ed832016-06-15 03:03:30 +00001210 * T = (2/3)*(ProfileLikelyProb/50)
1211 * = (2*ProfileLikelyProb)/150)
1212 */
1213 return BranchProbability(2 * ProfileLikelyProb, 150);
1214 }
Dehao Chen9f2bdfb2016-06-14 22:27:17 +00001215 }
1216 return BranchProbability(ProfileLikelyProb, 100);
Xinliang David Licbf12142016-06-13 20:24:19 +00001217}
1218
1219/// Checks to see if the layout candidate block \p Succ has a better layout
1220/// predecessor than \c BB. If yes, returns true.
Kyle Buttb15c0662017-01-31 23:48:32 +00001221/// \p SuccProb: The probability adjusted for only remaining blocks.
1222/// Only used for logging
1223/// \p RealSuccProb: The un-adjusted probability.
1224/// \p Chain: The chain that BB belongs to and Succ is being considered for.
1225/// \p BlockFilter: if non-null, the set of blocks that make up the loop being
1226/// considered
Xinliang David Licbf12142016-06-13 20:24:19 +00001227bool MachineBlockPlacement::hasBetterLayoutPredecessor(
Kyle Butte9425c4f2017-02-04 02:26:32 +00001228 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
1229 const BlockChain &SuccChain, BranchProbability SuccProb,
1230 BranchProbability RealSuccProb, const BlockChain &Chain,
1231 const BlockFilterSet *BlockFilter) {
Xinliang David Licbf12142016-06-13 20:24:19 +00001232
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001233 // There isn't a better layout when there are no unscheduled predecessors.
Xinliang David Licbf12142016-06-13 20:24:19 +00001234 if (SuccChain.UnscheduledPredecessors == 0)
1235 return false;
1236
1237 // There are two basic scenarios here:
1238 // -------------------------------------
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001239 // Case 1: triangular shape CFG (if-then):
Xinliang David Licbf12142016-06-13 20:24:19 +00001240 // BB
1241 // | \
1242 // | \
1243 // | Pred
1244 // | /
1245 // Succ
1246 // In this case, we are evaluating whether to select edge -> Succ, e.g.
1247 // set Succ as the layout successor of BB. Picking Succ as BB's
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001248 // successor breaks the CFG constraints (FIXME: define these constraints).
1249 // With this layout, Pred BB
Xinliang David Licbf12142016-06-13 20:24:19 +00001250 // is forced to be outlined, so the overall cost will be cost of the
1251 // branch taken from BB to Pred, plus the cost of back taken branch
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001252 // from Pred to Succ, as well as the additional cost associated
Xinliang David Licbf12142016-06-13 20:24:19 +00001253 // with the needed unconditional jump instruction from Pred To Succ.
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001254
Xinliang David Licbf12142016-06-13 20:24:19 +00001255 // The cost of the topological order layout is the taken branch cost
1256 // from BB to Succ, so to make BB->Succ a viable candidate, the following
1257 // must hold:
1258 // 2 * freq(BB->Pred) * taken_branch_cost + unconditional_jump_cost
1259 // < freq(BB->Succ) * taken_branch_cost.
1260 // Ignoring unconditional jump cost, we get
1261 // freq(BB->Succ) > 2 * freq(BB->Pred), i.e.,
1262 // prob(BB->Succ) > 2 * prob(BB->Pred)
1263 //
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001264 // When real profile data is available, we can precisely compute the
1265 // probability threshold that is needed for edge BB->Succ to be considered.
1266 // Without profile data, the heuristic requires the branch bias to be
Xinliang David Licbf12142016-06-13 20:24:19 +00001267 // a lot larger to make sure the signal is very strong (e.g. 80% default).
1268 // -----------------------------------------------------------------
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001269 // Case 2: diamond like CFG (if-then-else):
Xinliang David Licbf12142016-06-13 20:24:19 +00001270 // S
1271 // / \
1272 // | \
1273 // BB Pred
1274 // \ /
1275 // Succ
1276 // ..
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001277 //
1278 // The current block is BB and edge BB->Succ is now being evaluated.
1279 // Note that edge S->BB was previously already selected because
1280 // prob(S->BB) > prob(S->Pred).
1281 // At this point, 2 blocks can be placed after BB: Pred or Succ. If we
1282 // choose Pred, we will have a topological ordering as shown on the left
1283 // in the picture below. If we choose Succ, we have the solution as shown
1284 // on the right:
1285 //
1286 // topo-order:
1287 //
1288 // S----- ---S
1289 // | | | |
1290 // ---BB | | BB
1291 // | | | |
1292 // | pred-- | Succ--
1293 // | | | |
1294 // ---succ ---pred--
1295 //
1296 // cost = freq(S->Pred) + freq(BB->Succ) cost = 2 * freq (S->Pred)
1297 // = freq(S->Pred) + freq(S->BB)
1298 //
1299 // If we have profile data (i.e, branch probabilities can be trusted), the
1300 // cost (number of taken branches) with layout S->BB->Succ->Pred is 2 *
1301 // freq(S->Pred) while the cost of topo order is freq(S->Pred) + freq(S->BB).
1302 // We know Prob(S->BB) > Prob(S->Pred), so freq(S->BB) > freq(S->Pred), which
1303 // means the cost of topological order is greater.
Xinliang David Licbf12142016-06-13 20:24:19 +00001304 // When profile data is not available, however, we need to be more
1305 // conservative. If the branch prediction is wrong, breaking the topo-order
1306 // will actually yield a layout with large cost. For this reason, we need
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001307 // strong biased branch at block S with Prob(S->BB) in order to select
1308 // BB->Succ. This is equivalent to looking the CFG backward with backward
Xinliang David Licbf12142016-06-13 20:24:19 +00001309 // edge: Prob(Succ->BB) needs to >= HotProb in order to be selected (without
1310 // profile data).
Kyle Butt02d8d052016-07-29 18:09:28 +00001311 // --------------------------------------------------------------------------
1312 // Case 3: forked diamond
1313 // S
1314 // / \
1315 // / \
1316 // BB Pred
1317 // | \ / |
1318 // | \ / |
1319 // | X |
1320 // | / \ |
1321 // | / \ |
1322 // S1 S2
1323 //
1324 // The current block is BB and edge BB->S1 is now being evaluated.
1325 // As above S->BB was already selected because
1326 // prob(S->BB) > prob(S->Pred). Assume that prob(BB->S1) >= prob(BB->S2).
1327 //
1328 // topo-order:
1329 //
1330 // S-------| ---S
1331 // | | | |
1332 // ---BB | | BB
1333 // | | | |
1334 // | Pred----| | S1----
1335 // | | | |
1336 // --(S1 or S2) ---Pred--
Kyle Butt7fbec9b2017-02-15 19:49:14 +00001337 // |
1338 // S2
Kyle Butt02d8d052016-07-29 18:09:28 +00001339 //
1340 // topo-cost = freq(S->Pred) + freq(BB->S1) + freq(BB->S2)
1341 // + min(freq(Pred->S1), freq(Pred->S2))
1342 // Non-topo-order cost:
Kyle Butt02d8d052016-07-29 18:09:28 +00001343 // non-topo-cost = 2 * freq(S->Pred) + freq(BB->S2).
1344 // To be conservative, we can assume that min(freq(Pred->S1), freq(Pred->S2))
1345 // is 0. Then the non topo layout is better when
1346 // freq(S->Pred) < freq(BB->S1).
1347 // This is exactly what is checked below.
1348 // Note there are other shapes that apply (Pred may not be a single block,
1349 // but they all fit this general pattern.)
Dehao Chen9f2bdfb2016-06-14 22:27:17 +00001350 BranchProbability HotProb = getLayoutSuccessorProbThreshold(BB);
Xinliang David Licbf12142016-06-13 20:24:19 +00001351
Xinliang David Licbf12142016-06-13 20:24:19 +00001352 // Make sure that a hot successor doesn't have a globally more
1353 // important predecessor.
1354 BlockFrequency CandidateEdgeFreq = MBFI->getBlockFreq(BB) * RealSuccProb;
1355 bool BadCFGConflict = false;
1356
1357 for (MachineBasicBlock *Pred : Succ->predecessors()) {
1358 if (Pred == Succ || BlockToChain[Pred] == &SuccChain ||
1359 (BlockFilter && !BlockFilter->count(Pred)) ||
Kyle Buttb15c0662017-01-31 23:48:32 +00001360 BlockToChain[Pred] == &Chain ||
1361 // This check is redundant except for look ahead. This function is
1362 // called for lookahead by isProfitableToTailDup when BB hasn't been
1363 // placed yet.
1364 (Pred == BB))
Xinliang David Licbf12142016-06-13 20:24:19 +00001365 continue;
Kyle Butt02d8d052016-07-29 18:09:28 +00001366 // Do backward checking.
1367 // For all cases above, we need a backward checking to filter out edges that
Kyle Buttb15c0662017-01-31 23:48:32 +00001368 // are not 'strongly' biased.
Xinliang David Licbf12142016-06-13 20:24:19 +00001369 // BB Pred
1370 // \ /
1371 // Succ
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001372 // We select edge BB->Succ if
Xinliang David Licbf12142016-06-13 20:24:19 +00001373 // freq(BB->Succ) > freq(Succ) * HotProb
1374 // i.e. freq(BB->Succ) > freq(BB->Succ) * HotProb + freq(Pred->Succ) *
1375 // HotProb
1376 // i.e. freq((BB->Succ) * (1 - HotProb) > freq(Pred->Succ) * HotProb
Kyle Butt02d8d052016-07-29 18:09:28 +00001377 // Case 1 is covered too, because the first equation reduces to:
1378 // prob(BB->Succ) > HotProb. (freq(Succ) = freq(BB) for a triangle)
Xinliang David Licbf12142016-06-13 20:24:19 +00001379 BlockFrequency PredEdgeFreq =
1380 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
1381 if (PredEdgeFreq * HotProb >= CandidateEdgeFreq * HotProb.getCompl()) {
1382 BadCFGConflict = true;
1383 break;
1384 }
1385 }
1386
1387 if (BadCFGConflict) {
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001388 DEBUG(dbgs() << " Not a candidate: " << getBlockName(Succ) << " -> " << SuccProb
Xinliang David Licbf12142016-06-13 20:24:19 +00001389 << " (prob) (non-cold CFG conflict)\n");
1390 return true;
1391 }
1392
1393 return false;
1394}
1395
Xinliang David Li594ffa32016-06-11 18:35:40 +00001396/// \brief Select the best successor for a block.
1397///
1398/// This looks across all successors of a particular block and attempts to
1399/// select the "best" one to be the layout successor. It only considers direct
1400/// successors which also pass the block filter. It will attempt to avoid
1401/// breaking CFG structure, but cave and break such structures in the case of
1402/// very hot successor edges.
1403///
Kyle Buttb15c0662017-01-31 23:48:32 +00001404/// \returns The best successor block found, or null if none are viable, along
1405/// with a boolean indicating if tail duplication is necessary.
1406MachineBlockPlacement::BlockAndTailDupResult
Kyle Butte9425c4f2017-02-04 02:26:32 +00001407MachineBlockPlacement::selectBestSuccessor(
1408 const MachineBasicBlock *BB, const BlockChain &Chain,
1409 const BlockFilterSet *BlockFilter) {
Xinliang David Li594ffa32016-06-11 18:35:40 +00001410 const BranchProbability HotProb(StaticLikelyProb, 100);
1411
Kyle Buttb15c0662017-01-31 23:48:32 +00001412 BlockAndTailDupResult BestSucc = { nullptr, false };
Xinliang David Li594ffa32016-06-11 18:35:40 +00001413 auto BestProb = BranchProbability::getZero();
1414
1415 SmallVector<MachineBasicBlock *, 4> Successors;
1416 auto AdjustedSumProb =
1417 collectViableSuccessors(BB, Chain, BlockFilter, Successors);
1418
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001419 DEBUG(dbgs() << "Selecting best successor for: " << getBlockName(BB) << "\n");
Kyle Buttb15c0662017-01-31 23:48:32 +00001420
Kyle Buttebe6cc42017-02-23 21:22:24 +00001421 // if we already precomputed the best successor for BB, return that if still
1422 // applicable.
1423 auto FoundEdge = ComputedEdges.find(BB);
1424 if (FoundEdge != ComputedEdges.end()) {
1425 MachineBasicBlock *Succ = FoundEdge->second.BB;
1426 ComputedEdges.erase(FoundEdge);
Kyle Butt7fbec9b2017-02-15 19:49:14 +00001427 BlockChain *SuccChain = BlockToChain[Succ];
1428 if (BB->isSuccessor(Succ) && (!BlockFilter || BlockFilter->count(Succ)) &&
Kyle Buttebe6cc42017-02-23 21:22:24 +00001429 SuccChain != &Chain && Succ == *SuccChain->begin())
1430 return FoundEdge->second;
Kyle Butt7fbec9b2017-02-15 19:49:14 +00001431 }
1432
1433 // if BB is part of a trellis, Use the trellis to determine the optimal
1434 // fallthrough edges
1435 if (isTrellis(BB, Successors, Chain, BlockFilter))
1436 return getBestTrellisSuccessor(BB, Successors, AdjustedSumProb, Chain,
1437 BlockFilter);
1438
Kyle Buttb15c0662017-01-31 23:48:32 +00001439 // For blocks with CFG violations, we may be able to lay them out anyway with
1440 // tail-duplication. We keep this vector so we can perform the probability
1441 // calculations the minimum number of times.
1442 SmallVector<std::tuple<BranchProbability, MachineBasicBlock *>, 4>
1443 DupCandidates;
Cong Hou41cf1a52015-11-18 00:52:52 +00001444 for (MachineBasicBlock *Succ : Successors) {
Xinliang David Li594ffa32016-06-11 18:35:40 +00001445 auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ);
1446 BranchProbability SuccProb =
1447 getAdjustedProbability(RealSuccProb, AdjustedSumProb);
Chandler Carruthb3361722011-11-13 11:34:53 +00001448
Cong Hou41cf1a52015-11-18 00:52:52 +00001449 BlockChain &SuccChain = *BlockToChain[Succ];
Xinliang David Licbf12142016-06-13 20:24:19 +00001450 // Skip the edge \c BB->Succ if block \c Succ has a better layout
1451 // predecessor that yields lower global cost.
1452 if (hasBetterLayoutPredecessor(BB, Succ, SuccChain, SuccProb, RealSuccProb,
Kyle Buttb15c0662017-01-31 23:48:32 +00001453 Chain, BlockFilter)) {
1454 // If tail duplication would make Succ profitable, place it.
1455 if (TailDupPlacement && shouldTailDuplicate(Succ))
1456 DupCandidates.push_back(std::make_tuple(SuccProb, Succ));
Xinliang David Licbf12142016-06-13 20:24:19 +00001457 continue;
Kyle Buttb15c0662017-01-31 23:48:32 +00001458 }
Chandler Carruth18dfac32011-11-20 11:22:06 +00001459
Xinliang David Licbf12142016-06-13 20:24:19 +00001460 DEBUG(
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001461 dbgs() << " Candidate: " << getBlockName(Succ) << ", probability: "
1462 << SuccProb
Xinliang David Licbf12142016-06-13 20:24:19 +00001463 << (SuccChain.UnscheduledPredecessors != 0 ? " (CFG break)" : "")
1464 << "\n");
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001465
Kyle Buttb15c0662017-01-31 23:48:32 +00001466 if (BestSucc.BB && BestProb >= SuccProb) {
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001467 DEBUG(dbgs() << " Not the best candidate, continuing\n");
Chandler Carruthb3361722011-11-13 11:34:53 +00001468 continue;
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001469 }
1470
1471 DEBUG(dbgs() << " Setting it as best candidate\n");
Kyle Buttb15c0662017-01-31 23:48:32 +00001472 BestSucc.BB = Succ;
Cong Houd97c1002015-12-01 05:29:22 +00001473 BestProb = SuccProb;
Chandler Carruthb3361722011-11-13 11:34:53 +00001474 }
Kyle Buttb15c0662017-01-31 23:48:32 +00001475 // Handle the tail duplication candidates in order of decreasing probability.
1476 // Stop at the first one that is profitable. Also stop if they are less
1477 // profitable than BestSucc. Position is important because we preserve it and
1478 // prefer first best match. Here we aren't comparing in order, so we capture
1479 // the position instead.
1480 if (DupCandidates.size() != 0) {
1481 auto cmp =
1482 [](const std::tuple<BranchProbability, MachineBasicBlock *> &a,
1483 const std::tuple<BranchProbability, MachineBasicBlock *> &b) {
1484 return std::get<0>(a) > std::get<0>(b);
1485 };
1486 std::stable_sort(DupCandidates.begin(), DupCandidates.end(), cmp);
1487 }
1488 for(auto &Tup : DupCandidates) {
1489 BranchProbability DupProb;
1490 MachineBasicBlock *Succ;
1491 std::tie(DupProb, Succ) = Tup;
1492 if (DupProb < BestProb)
1493 break;
1494 if (canTailDuplicateUnplacedPreds(BB, Succ, Chain, BlockFilter)
Kyle Butt7e8be282017-04-10 22:28:22 +00001495 && (isProfitableToTailDup(BB, Succ, BestProb, Chain, BlockFilter))) {
Kyle Buttb15c0662017-01-31 23:48:32 +00001496 DEBUG(
1497 dbgs() << " Candidate: " << getBlockName(Succ) << ", probability: "
1498 << DupProb
1499 << " (Tail Duplicate)\n");
1500 BestSucc.BB = Succ;
1501 BestSucc.ShouldTailDup = true;
1502 break;
1503 }
1504 }
1505
1506 if (BestSucc.BB)
1507 DEBUG(dbgs() << " Selected: " << getBlockName(BestSucc.BB) << "\n");
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001508
Chandler Carruthb3361722011-11-13 11:34:53 +00001509 return BestSucc;
1510}
1511
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001512/// \brief Select the best block from a worklist.
1513///
1514/// This looks through the provided worklist as a list of candidate basic
1515/// blocks and select the most profitable one to place. The definition of
1516/// profitable only really makes sense in the context of a loop. This returns
1517/// the most frequently visited block in the worklist, which in the case of
1518/// a loop, is the one most desirable to be physically close to the rest of the
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001519/// loop body in order to improve i-cache behavior.
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001520///
1521/// \returns The best block found, or null if none are viable.
1522MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
Kyle Butte9425c4f2017-02-04 02:26:32 +00001523 const BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList) {
Chandler Carruth0af6a0b2011-11-14 09:46:33 +00001524 // Once we need to walk the worklist looking for a candidate, cleanup the
1525 // worklist of already placed entries.
1526 // FIXME: If this shows up on profiles, it could be folded (at the cost of
1527 // some code complexity) into the loop below.
David Majnemerc7004902016-08-12 04:32:37 +00001528 WorkList.erase(remove_if(WorkList,
1529 [&](MachineBasicBlock *BB) {
1530 return BlockToChain.lookup(BB) == &Chain;
1531 }),
Chandler Carruth0af6a0b2011-11-14 09:46:33 +00001532 WorkList.end());
1533
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001534 if (WorkList.empty())
1535 return nullptr;
1536
1537 bool IsEHPad = WorkList[0]->isEHPad();
1538
Craig Topperc0196b12014-04-14 00:51:57 +00001539 MachineBasicBlock *BestBlock = nullptr;
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001540 BlockFrequency BestFreq;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001541 for (MachineBasicBlock *MBB : WorkList) {
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001542 assert(MBB->isEHPad() == IsEHPad);
1543
Chandler Carruth7a715da2015-03-05 03:19:05 +00001544 BlockChain &SuccChain = *BlockToChain[MBB];
Philip Reames02e11322016-03-02 22:40:51 +00001545 if (&SuccChain == &Chain)
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001546 continue;
Junmo Park4ba6cf62016-03-11 05:07:07 +00001547
Philip Reamesae27b232016-03-03 00:58:43 +00001548 assert(SuccChain.UnscheduledPredecessors == 0 && "Found CFG-violating block");
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001549
Chandler Carruth7a715da2015-03-05 03:19:05 +00001550 BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
1551 DEBUG(dbgs() << " " << getBlockName(MBB) << " -> ";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001552 MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001553
1554 // For ehpad, we layout the least probable first as to avoid jumping back
1555 // from least probable landingpads to more probable ones.
1556 //
1557 // FIXME: Using probability is probably (!) not the best way to achieve
1558 // this. We should probably have a more principled approach to layout
1559 // cleanup code.
1560 //
1561 // The goal is to get:
1562 //
1563 // +--------------------------+
1564 // | V
1565 // InnerLp -> InnerCleanup OuterLp -> OuterCleanup -> Resume
1566 //
1567 // Rather than:
1568 //
1569 // +-------------------------------------+
1570 // V |
1571 // OuterLp -> OuterCleanup -> Resume InnerLp -> InnerCleanup
1572 if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq)))
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001573 continue;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001574
Chandler Carruth7a715da2015-03-05 03:19:05 +00001575 BestBlock = MBB;
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001576 BestFreq = CandidateFreq;
1577 }
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001578
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001579 return BestBlock;
1580}
1581
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001582/// \brief Retrieve the first unplaced basic block.
1583///
1584/// This routine is called when we are unable to use the CFG to walk through
1585/// all of the basic blocks and form a chain due to unnatural loops in the CFG.
Chandler Carruth9b548a7f2011-11-15 06:26:43 +00001586/// We walk through the function's blocks in order, starting from the
1587/// LastUnplacedBlockIt. We update this iterator on each call to avoid
1588/// re-scanning the entire sequence on repeated calls to this routine.
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001589MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
Xinliang David Li52530a72016-06-13 22:23:44 +00001590 const BlockChain &PlacedChain,
Chandler Carruth9b548a7f2011-11-15 06:26:43 +00001591 MachineFunction::iterator &PrevUnplacedBlockIt,
Jakub Staszak90616162011-12-21 23:02:08 +00001592 const BlockFilterSet *BlockFilter) {
Xinliang David Li52530a72016-06-13 22:23:44 +00001593 for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F->end(); I != E;
Chandler Carruth9b548a7f2011-11-15 06:26:43 +00001594 ++I) {
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001595 if (BlockFilter && !BlockFilter->count(&*I))
Chandler Carruth9b548a7f2011-11-15 06:26:43 +00001596 continue;
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001597 if (BlockToChain[&*I] != &PlacedChain) {
Chandler Carruth9b548a7f2011-11-15 06:26:43 +00001598 PrevUnplacedBlockIt = I;
Chandler Carruth4a87aa02011-11-23 03:03:21 +00001599 // Now select the head of the chain to which the unplaced block belongs
1600 // as the block to place. This will force the entire chain to be placed,
1601 // and satisfies the requirements of merging chains.
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001602 return *BlockToChain[&*I]->begin();
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001603 }
1604 }
Craig Topperc0196b12014-04-14 00:51:57 +00001605 return nullptr;
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001606}
1607
Amaury Secheteae09c22016-03-14 21:24:11 +00001608void MachineBlockPlacement::fillWorkLists(
Kyle Butte9425c4f2017-02-04 02:26:32 +00001609 const MachineBasicBlock *MBB,
Amaury Secheteae09c22016-03-14 21:24:11 +00001610 SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
Amaury Secheteae09c22016-03-14 21:24:11 +00001611 const BlockFilterSet *BlockFilter = nullptr) {
1612 BlockChain &Chain = *BlockToChain[MBB];
1613 if (!UpdatedPreds.insert(&Chain).second)
1614 return;
1615
1616 assert(Chain.UnscheduledPredecessors == 0);
1617 for (MachineBasicBlock *ChainBB : Chain) {
1618 assert(BlockToChain[ChainBB] == &Chain);
1619 for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
1620 if (BlockFilter && !BlockFilter->count(Pred))
1621 continue;
1622 if (BlockToChain[Pred] == &Chain)
1623 continue;
1624 ++Chain.UnscheduledPredecessors;
1625 }
1626 }
1627
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001628 if (Chain.UnscheduledPredecessors != 0)
1629 return;
1630
Kyle Butte9425c4f2017-02-04 02:26:32 +00001631 MachineBasicBlock *BB = *Chain.begin();
1632 if (BB->isEHPad())
1633 EHPadWorkList.push_back(BB);
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001634 else
Kyle Butte9425c4f2017-02-04 02:26:32 +00001635 BlockWorkList.push_back(BB);
Amaury Secheteae09c22016-03-14 21:24:11 +00001636}
1637
Chandler Carruth8d150782011-11-13 11:20:44 +00001638void MachineBlockPlacement::buildChain(
Kyle Butte9425c4f2017-02-04 02:26:32 +00001639 const MachineBasicBlock *HeadBB, BlockChain &Chain,
Kyle Butt0846e562016-10-11 20:36:43 +00001640 BlockFilterSet *BlockFilter) {
Kyle Butte9425c4f2017-02-04 02:26:32 +00001641 assert(HeadBB && "BB must not be null.\n");
1642 assert(BlockToChain[HeadBB] == &Chain && "BlockToChainMap mis-match.\n");
Xinliang David Li52530a72016-06-13 22:23:44 +00001643 MachineFunction::iterator PrevUnplacedBlockIt = F->begin();
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001644
Kyle Butte9425c4f2017-02-04 02:26:32 +00001645 const MachineBasicBlock *LoopHeaderBB = HeadBB;
Xinliang David Li93926ac2016-07-01 05:46:48 +00001646 markChainSuccessors(Chain, LoopHeaderBB, BlockFilter);
Kyle Butte9425c4f2017-02-04 02:26:32 +00001647 MachineBasicBlock *BB = *std::prev(Chain.end());
Chandler Carruth8d150782011-11-13 11:20:44 +00001648 for (;;) {
Kyle Butt82c22902016-06-28 22:50:54 +00001649 assert(BB && "null block found at end of chain in loop.");
1650 assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match in loop.");
1651 assert(*std::prev(Chain.end()) == BB && "BB Not found at end of chain.");
1652
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001653
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001654 // Look for the best viable successor if there is one to place immediately
1655 // after this block.
Kyle Buttb15c0662017-01-31 23:48:32 +00001656 auto Result = selectBestSuccessor(BB, Chain, BlockFilter);
1657 MachineBasicBlock* BestSucc = Result.BB;
1658 bool ShouldTailDup = Result.ShouldTailDup;
1659 if (TailDupPlacement)
1660 ShouldTailDup |= (BestSucc && shouldTailDuplicate(BestSucc));
Chandler Carruth8d150782011-11-13 11:20:44 +00001661
1662 // If an immediate successor isn't available, look for the best viable
1663 // block among those we've identified as not violating the loop's CFG at
1664 // this point. This won't be a fallthrough, but it will increase locality.
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001665 if (!BestSucc)
Amaury Sechet9ee4ddd2016-04-07 06:34:47 +00001666 BestSucc = selectBestCandidateBlock(Chain, BlockWorkList);
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001667 if (!BestSucc)
1668 BestSucc = selectBestCandidateBlock(Chain, EHPadWorkList);
Chandler Carruth8d150782011-11-13 11:20:44 +00001669
Chandler Carruth8d150782011-11-13 11:20:44 +00001670 if (!BestSucc) {
Xinliang David Li52530a72016-06-13 22:23:44 +00001671 BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockIt, BlockFilter);
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001672 if (!BestSucc)
1673 break;
1674
1675 DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
1676 "layout successor until the CFG reduces\n");
Chandler Carruth8d150782011-11-13 11:20:44 +00001677 }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001678
Kyle Butt0846e562016-10-11 20:36:43 +00001679 // Placement may have changed tail duplication opportunities.
1680 // Check for that now.
Kyle Buttb15c0662017-01-31 23:48:32 +00001681 if (TailDupPlacement && BestSucc && ShouldTailDup) {
Kyle Butt0846e562016-10-11 20:36:43 +00001682 // If the chosen successor was duplicated into all its predecessors,
1683 // don't bother laying it out, just go round the loop again with BB as
1684 // the chain end.
1685 if (repeatedlyTailDuplicateBlock(BestSucc, BB, LoopHeaderBB, Chain,
1686 BlockFilter, PrevUnplacedBlockIt))
1687 continue;
1688 }
1689
Chandler Carruth8d150782011-11-13 11:20:44 +00001690 // Place this block, updating the datastructures to reflect its placement.
Jakub Staszak90616162011-12-21 23:02:08 +00001691 BlockChain &SuccChain = *BlockToChain[BestSucc];
Philip Reamesae27b232016-03-03 00:58:43 +00001692 // Zero out UnscheduledPredecessors for the successor we're about to merge in case
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001693 // we selected a successor that didn't fit naturally into the CFG.
Philip Reamesae27b232016-03-03 00:58:43 +00001694 SuccChain.UnscheduledPredecessors = 0;
Philip Reamesb9688f42016-03-02 21:45:13 +00001695 DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to "
1696 << getBlockName(BestSucc) << "\n");
Xinliang David Li93926ac2016-07-01 05:46:48 +00001697 markChainSuccessors(SuccChain, LoopHeaderBB, BlockFilter);
Chandler Carruth8d150782011-11-13 11:20:44 +00001698 Chain.merge(BestSucc, &SuccChain);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001699 BB = *std::prev(Chain.end());
Jakub Staszak190c7122011-12-07 19:46:10 +00001700 }
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001701
1702 DEBUG(dbgs() << "Finished forming chain for header block "
Philip Reamesb9688f42016-03-02 21:45:13 +00001703 << getBlockName(*Chain.begin()) << "\n");
Chandler Carruth10281422011-10-21 06:46:38 +00001704}
1705
Chandler Carruth03adbd42011-11-27 13:34:33 +00001706/// \brief Find the best loop top block for layout.
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001707///
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001708/// Look for a block which is strictly better than the loop header for laying
1709/// out at the top of the loop. This looks for one and only one pattern:
1710/// a latch block with no conditional exit. This block will cause a conditional
1711/// jump around it or will be the bottom of the loop if we lay it out in place,
1712/// but if it it doesn't end up at the bottom of the loop for any reason,
1713/// rotation alone won't fix it. Because such a block will always result in an
1714/// unconditional jump (for the backedge) rotating it in front of the loop
1715/// header is always profitable.
1716MachineBasicBlock *
Kyle Butte9425c4f2017-02-04 02:26:32 +00001717MachineBlockPlacement::findBestLoopTop(const MachineLoop &L,
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001718 const BlockFilterSet &LoopBlockSet) {
Sjoerd Meijer15c81b02016-08-16 19:50:33 +00001719 // Placing the latch block before the header may introduce an extra branch
1720 // that skips this block the first time the loop is executed, which we want
1721 // to avoid when optimising for size.
1722 // FIXME: in theory there is a case that does not introduce a new branch,
1723 // i.e. when the layout predecessor does not fallthrough to the loop header.
1724 // In practice this never happens though: there always seems to be a preheader
1725 // that can fallthrough and that is also placed before the header.
1726 if (F->getFunction()->optForSize())
1727 return L.getHeader();
1728
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001729 // Check that the header hasn't been fused with a preheader block due to
1730 // crazy branches. If it has, we need to start with the header at the top to
1731 // prevent pulling the preheader into the loop body.
1732 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
1733 if (!LoopBlockSet.count(*HeaderChain.begin()))
1734 return L.getHeader();
1735
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001736 DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(L.getHeader())
1737 << "\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001738
1739 BlockFrequency BestPredFreq;
Craig Topperc0196b12014-04-14 00:51:57 +00001740 MachineBasicBlock *BestPred = nullptr;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001741 for (MachineBasicBlock *Pred : L.getHeader()->predecessors()) {
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001742 if (!LoopBlockSet.count(Pred))
1743 continue;
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001744 DEBUG(dbgs() << " header pred: " << getBlockName(Pred) << ", has "
Michael Gottesmanb78dec82013-12-14 00:25:45 +00001745 << Pred->succ_size() << " successors, ";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001746 MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001747 if (Pred->succ_size() > 1)
1748 continue;
1749
1750 BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
1751 if (!BestPred || PredFreq > BestPredFreq ||
1752 (!(PredFreq < BestPredFreq) &&
1753 Pred->isLayoutSuccessor(L.getHeader()))) {
1754 BestPred = Pred;
1755 BestPredFreq = PredFreq;
1756 }
1757 }
1758
1759 // If no direct predecessor is fine, just use the loop header.
Philip Reamesb9688f42016-03-02 21:45:13 +00001760 if (!BestPred) {
1761 DEBUG(dbgs() << " final top unchanged\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001762 return L.getHeader();
Philip Reamesb9688f42016-03-02 21:45:13 +00001763 }
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001764
1765 // Walk backwards through any straight line of predecessors.
1766 while (BestPred->pred_size() == 1 &&
1767 (*BestPred->pred_begin())->succ_size() == 1 &&
1768 *BestPred->pred_begin() != L.getHeader())
1769 BestPred = *BestPred->pred_begin();
1770
1771 DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n");
1772 return BestPred;
1773}
1774
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001775/// \brief Find the best loop exiting block for layout.
1776///
Chandler Carruth03adbd42011-11-27 13:34:33 +00001777/// This routine implements the logic to analyze the loop looking for the best
1778/// block to layout at the top of the loop. Typically this is done to maximize
1779/// fallthrough opportunities.
1780MachineBasicBlock *
Kyle Butte9425c4f2017-02-04 02:26:32 +00001781MachineBlockPlacement::findBestLoopExit(const MachineLoop &L,
Chandler Carruthccc7e422012-04-16 01:12:56 +00001782 const BlockFilterSet &LoopBlockSet) {
Chandler Carruth68062612012-04-10 13:35:57 +00001783 // We don't want to layout the loop linearly in all cases. If the loop header
1784 // is just a normal basic block in the loop, we want to look for what block
1785 // within the loop is the best one to layout at the top. However, if the loop
1786 // header has be pre-merged into a chain due to predecessors not having
1787 // analyzable branches, *and* the predecessor it is merged with is *not* part
1788 // of the loop, rotating the header into the middle of the loop will create
1789 // a non-contiguous range of blocks which is Very Bad. So start with the
1790 // header and only rotate if safe.
1791 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
1792 if (!LoopBlockSet.count(*HeaderChain.begin()))
Craig Topperc0196b12014-04-14 00:51:57 +00001793 return nullptr;
Chandler Carruth68062612012-04-10 13:35:57 +00001794
Chandler Carruth03adbd42011-11-27 13:34:33 +00001795 BlockFrequency BestExitEdgeFreq;
Chandler Carruthccc7e422012-04-16 01:12:56 +00001796 unsigned BestExitLoopDepth = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00001797 MachineBasicBlock *ExitingBB = nullptr;
Chandler Carruth4f567202011-11-27 20:18:00 +00001798 // If there are exits to outer loops, loop rotation can severely limit
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001799 // fallthrough opportunities unless it selects such an exit. Keep a set of
Chandler Carruth4f567202011-11-27 20:18:00 +00001800 // blocks where rotating to exit with that block will reach an outer loop.
1801 SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
1802
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001803 DEBUG(dbgs() << "Finding best loop exit for: " << getBlockName(L.getHeader())
1804 << "\n");
Chandler Carruth7a715da2015-03-05 03:19:05 +00001805 for (MachineBasicBlock *MBB : L.getBlocks()) {
1806 BlockChain &Chain = *BlockToChain[MBB];
Chandler Carruth03adbd42011-11-27 13:34:33 +00001807 // Ensure that this block is at the end of a chain; otherwise it could be
Chandler Carruth9a512a42015-04-15 13:19:54 +00001808 // mid-way through an inner loop or a successor of an unanalyzable branch.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001809 if (MBB != *std::prev(Chain.end()))
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001810 continue;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001811
Chandler Carruth03adbd42011-11-27 13:34:33 +00001812 // Now walk the successors. We need to establish whether this has a viable
1813 // exiting successor and whether it has a viable non-exiting successor.
1814 // We store the old exiting state and restore it if a viable looping
1815 // successor isn't found.
1816 MachineBasicBlock *OldExitingBB = ExitingBB;
1817 BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
Chandler Carruthccc7e422012-04-16 01:12:56 +00001818 bool HasLoopingSucc = false;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001819 for (MachineBasicBlock *Succ : MBB->successors()) {
Reid Kleckner0e288232015-08-27 23:27:47 +00001820 if (Succ->isEHPad())
Chandler Carruth03adbd42011-11-27 13:34:33 +00001821 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001822 if (Succ == MBB)
Chandler Carruth03adbd42011-11-27 13:34:33 +00001823 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001824 BlockChain &SuccChain = *BlockToChain[Succ];
Chandler Carruth03adbd42011-11-27 13:34:33 +00001825 // Don't split chains, either this chain or the successor's chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +00001826 if (&Chain == &SuccChain) {
Chandler Carruth7a715da2015-03-05 03:19:05 +00001827 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
1828 << getBlockName(Succ) << " (chain conflict)\n");
Chandler Carruth03adbd42011-11-27 13:34:33 +00001829 continue;
1830 }
1831
Cong Houd97c1002015-12-01 05:29:22 +00001832 auto SuccProb = MBPI->getEdgeProbability(MBB, Succ);
Chandler Carruth7a715da2015-03-05 03:19:05 +00001833 if (LoopBlockSet.count(Succ)) {
1834 DEBUG(dbgs() << " looping: " << getBlockName(MBB) << " -> "
Cong Houd97c1002015-12-01 05:29:22 +00001835 << getBlockName(Succ) << " (" << SuccProb << ")\n");
Chandler Carruthccc7e422012-04-16 01:12:56 +00001836 HasLoopingSucc = true;
Chandler Carruth03adbd42011-11-27 13:34:33 +00001837 continue;
1838 }
1839
Chandler Carruthccc7e422012-04-16 01:12:56 +00001840 unsigned SuccLoopDepth = 0;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001841 if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
Chandler Carruthccc7e422012-04-16 01:12:56 +00001842 SuccLoopDepth = ExitLoop->getLoopDepth();
1843 if (ExitLoop->contains(&L))
Chandler Carruth7a715da2015-03-05 03:19:05 +00001844 BlocksExitingToOuterLoop.insert(MBB);
Chandler Carruthccc7e422012-04-16 01:12:56 +00001845 }
1846
Chandler Carruth7a715da2015-03-05 03:19:05 +00001847 BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
1848 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
1849 << getBlockName(Succ) << " [L:" << SuccLoopDepth << "] (";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001850 MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
Benjamin Kramerc8160d62013-11-20 19:08:44 +00001851 // Note that we bias this toward an existing layout successor to retain
1852 // incoming order in the absence of better information. The exit must have
1853 // a frequency higher than the current exit before we consider breaking
1854 // the layout.
1855 BranchProbability Bias(100 - ExitBlockBias, 100);
Chandler Carruth26d30172015-04-15 13:39:42 +00001856 if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
Chandler Carruthccc7e422012-04-16 01:12:56 +00001857 ExitEdgeFreq > BestExitEdgeFreq ||
Chandler Carruth7a715da2015-03-05 03:19:05 +00001858 (MBB->isLayoutSuccessor(Succ) &&
Benjamin Kramerc8160d62013-11-20 19:08:44 +00001859 !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
Chandler Carruth03adbd42011-11-27 13:34:33 +00001860 BestExitEdgeFreq = ExitEdgeFreq;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001861 ExitingBB = MBB;
Chandler Carrutha0545802011-11-27 09:22:53 +00001862 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001863 }
Chandler Carruth03adbd42011-11-27 13:34:33 +00001864
Chandler Carruthccc7e422012-04-16 01:12:56 +00001865 if (!HasLoopingSucc) {
Chandler Carruthcfb2b9d2015-04-15 13:26:41 +00001866 // Restore the old exiting state, no viable looping successor was found.
Chandler Carruth03adbd42011-11-27 13:34:33 +00001867 ExitingBB = OldExitingBB;
1868 BestExitEdgeFreq = OldBestExitEdgeFreq;
Chandler Carruth03adbd42011-11-27 13:34:33 +00001869 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001870 }
Chandler Carruthccc7e422012-04-16 01:12:56 +00001871 // Without a candidate exiting block or with only a single block in the
Chandler Carruth03adbd42011-11-27 13:34:33 +00001872 // loop, just use the loop header to layout the loop.
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001873 if (!ExitingBB) {
1874 DEBUG(dbgs() << " No other candidate exit blocks, using loop header\n");
Craig Topperc0196b12014-04-14 00:51:57 +00001875 return nullptr;
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001876 }
1877 if (L.getNumBlocks() == 1) {
1878 DEBUG(dbgs() << " Loop has 1 block, using loop header as exit\n");
1879 return nullptr;
1880 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001881
Chandler Carruth4f567202011-11-27 20:18:00 +00001882 // Also, if we have exit blocks which lead to outer loops but didn't select
1883 // one of them as the exiting block we are rotating toward, disable loop
1884 // rotation altogether.
1885 if (!BlocksExitingToOuterLoop.empty() &&
1886 !BlocksExitingToOuterLoop.count(ExitingBB))
Craig Topperc0196b12014-04-14 00:51:57 +00001887 return nullptr;
Chandler Carruth4f567202011-11-27 20:18:00 +00001888
Chandler Carruth03adbd42011-11-27 13:34:33 +00001889 DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB) << "\n");
Chandler Carruthccc7e422012-04-16 01:12:56 +00001890 return ExitingBB;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001891}
1892
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001893/// \brief Attempt to rotate an exiting block to the bottom of the loop.
1894///
1895/// Once we have built a chain, try to rotate it to line up the hot exit block
1896/// with fallthrough out of the loop if doing so doesn't introduce unnecessary
1897/// branches. For example, if the loop has fallthrough into its header and out
1898/// of its bottom already, don't rotate it.
1899void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
Kyle Butte9425c4f2017-02-04 02:26:32 +00001900 const MachineBasicBlock *ExitingBB,
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001901 const BlockFilterSet &LoopBlockSet) {
1902 if (!ExitingBB)
1903 return;
1904
1905 MachineBasicBlock *Top = *LoopChain.begin();
1906 bool ViableTopFallthrough = false;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001907 for (MachineBasicBlock *Pred : Top->predecessors()) {
1908 BlockChain *PredChain = BlockToChain[Pred];
1909 if (!LoopBlockSet.count(Pred) &&
1910 (!PredChain || Pred == *std::prev(PredChain->end()))) {
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001911 ViableTopFallthrough = true;
1912 break;
1913 }
1914 }
1915
1916 // If the header has viable fallthrough, check whether the current loop
1917 // bottom is a viable exiting block. If so, bail out as rotating will
1918 // introduce an unnecessary branch.
1919 if (ViableTopFallthrough) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001920 MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
Chandler Carruth7a715da2015-03-05 03:19:05 +00001921 for (MachineBasicBlock *Succ : Bottom->successors()) {
1922 BlockChain *SuccChain = BlockToChain[Succ];
1923 if (!LoopBlockSet.count(Succ) &&
1924 (!SuccChain || Succ == *SuccChain->begin()))
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001925 return;
1926 }
1927 }
1928
David Majnemer0d955d02016-08-11 22:21:41 +00001929 BlockChain::iterator ExitIt = find(LoopChain, ExitingBB);
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001930 if (ExitIt == LoopChain.end())
1931 return;
1932
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001933 std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001934}
1935
Cong Hou7745dbc2015-10-19 23:16:40 +00001936/// \brief Attempt to rotate a loop based on profile data to reduce branch cost.
1937///
1938/// With profile data, we can determine the cost in terms of missed fall through
1939/// opportunities when rotating a loop chain and select the best rotation.
1940/// Basically, there are three kinds of cost to consider for each rotation:
1941/// 1. The possibly missed fall through edge (if it exists) from BB out of
1942/// the loop to the loop header.
1943/// 2. The possibly missed fall through edges (if they exist) from the loop
1944/// exits to BB out of the loop.
1945/// 3. The missed fall through edge (if it exists) from the last BB to the
1946/// first BB in the loop chain.
1947/// Therefore, the cost for a given rotation is the sum of costs listed above.
1948/// We select the best rotation with the smallest cost.
1949void MachineBlockPlacement::rotateLoopWithProfile(
Kyle Butte9425c4f2017-02-04 02:26:32 +00001950 BlockChain &LoopChain, const MachineLoop &L,
1951 const BlockFilterSet &LoopBlockSet) {
Cong Hou7745dbc2015-10-19 23:16:40 +00001952 auto HeaderBB = L.getHeader();
David Majnemer0d955d02016-08-11 22:21:41 +00001953 auto HeaderIter = find(LoopChain, HeaderBB);
Cong Hou7745dbc2015-10-19 23:16:40 +00001954 auto RotationPos = LoopChain.end();
1955
1956 BlockFrequency SmallestRotationCost = BlockFrequency::getMaxFrequency();
1957
1958 // A utility lambda that scales up a block frequency by dividing it by a
1959 // branch probability which is the reciprocal of the scale.
1960 auto ScaleBlockFrequency = [](BlockFrequency Freq,
1961 unsigned Scale) -> BlockFrequency {
1962 if (Scale == 0)
1963 return 0;
1964 // Use operator / between BlockFrequency and BranchProbability to implement
1965 // saturating multiplication.
1966 return Freq / BranchProbability(1, Scale);
1967 };
1968
1969 // Compute the cost of the missed fall-through edge to the loop header if the
1970 // chain head is not the loop header. As we only consider natural loops with
1971 // single header, this computation can be done only once.
1972 BlockFrequency HeaderFallThroughCost(0);
1973 for (auto *Pred : HeaderBB->predecessors()) {
1974 BlockChain *PredChain = BlockToChain[Pred];
1975 if (!LoopBlockSet.count(Pred) &&
1976 (!PredChain || Pred == *std::prev(PredChain->end()))) {
1977 auto EdgeFreq =
1978 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, HeaderBB);
1979 auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost);
1980 // If the predecessor has only an unconditional jump to the header, we
1981 // need to consider the cost of this jump.
1982 if (Pred->succ_size() == 1)
1983 FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost);
1984 HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost);
1985 }
1986 }
1987
1988 // Here we collect all exit blocks in the loop, and for each exit we find out
1989 // its hottest exit edge. For each loop rotation, we define the loop exit cost
1990 // as the sum of frequencies of exit edges we collect here, excluding the exit
1991 // edge from the tail of the loop chain.
1992 SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq;
1993 for (auto BB : LoopChain) {
Cong Houd97c1002015-12-01 05:29:22 +00001994 auto LargestExitEdgeProb = BranchProbability::getZero();
Cong Hou7745dbc2015-10-19 23:16:40 +00001995 for (auto *Succ : BB->successors()) {
1996 BlockChain *SuccChain = BlockToChain[Succ];
1997 if (!LoopBlockSet.count(Succ) &&
1998 (!SuccChain || Succ == *SuccChain->begin())) {
Cong Houd97c1002015-12-01 05:29:22 +00001999 auto SuccProb = MBPI->getEdgeProbability(BB, Succ);
2000 LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb);
Cong Hou7745dbc2015-10-19 23:16:40 +00002001 }
2002 }
Cong Houd97c1002015-12-01 05:29:22 +00002003 if (LargestExitEdgeProb > BranchProbability::getZero()) {
2004 auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb;
Cong Hou7745dbc2015-10-19 23:16:40 +00002005 ExitsWithFreq.emplace_back(BB, ExitFreq);
2006 }
2007 }
2008
2009 // In this loop we iterate every block in the loop chain and calculate the
2010 // cost assuming the block is the head of the loop chain. When the loop ends,
2011 // we should have found the best candidate as the loop chain's head.
2012 for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()),
2013 EndIter = LoopChain.end();
2014 Iter != EndIter; Iter++, TailIter++) {
2015 // TailIter is used to track the tail of the loop chain if the block we are
2016 // checking (pointed by Iter) is the head of the chain.
2017 if (TailIter == LoopChain.end())
2018 TailIter = LoopChain.begin();
2019
2020 auto TailBB = *TailIter;
2021
2022 // Calculate the cost by putting this BB to the top.
2023 BlockFrequency Cost = 0;
2024
2025 // If the current BB is the loop header, we need to take into account the
2026 // cost of the missed fall through edge from outside of the loop to the
2027 // header.
2028 if (Iter != HeaderIter)
2029 Cost += HeaderFallThroughCost;
2030
2031 // Collect the loop exit cost by summing up frequencies of all exit edges
2032 // except the one from the chain tail.
2033 for (auto &ExitWithFreq : ExitsWithFreq)
2034 if (TailBB != ExitWithFreq.first)
2035 Cost += ExitWithFreq.second;
2036
2037 // The cost of breaking the once fall-through edge from the tail to the top
2038 // of the loop chain. Here we need to consider three cases:
2039 // 1. If the tail node has only one successor, then we will get an
2040 // additional jmp instruction. So the cost here is (MisfetchCost +
2041 // JumpInstCost) * tail node frequency.
2042 // 2. If the tail node has two successors, then we may still get an
2043 // additional jmp instruction if the layout successor after the loop
2044 // chain is not its CFG successor. Note that the more frequently executed
2045 // jmp instruction will be put ahead of the other one. Assume the
2046 // frequency of those two branches are x and y, where x is the frequency
2047 // of the edge to the chain head, then the cost will be
2048 // (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency.
2049 // 3. If the tail node has more than two successors (this rarely happens),
2050 // we won't consider any additional cost.
2051 if (TailBB->isSuccessor(*Iter)) {
2052 auto TailBBFreq = MBFI->getBlockFreq(TailBB);
2053 if (TailBB->succ_size() == 1)
2054 Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(),
2055 MisfetchCost + JumpInstCost);
2056 else if (TailBB->succ_size() == 2) {
2057 auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter);
2058 auto TailToHeadFreq = TailBBFreq * TailToHeadProb;
2059 auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2)
2060 ? TailBBFreq * TailToHeadProb.getCompl()
2061 : TailToHeadFreq;
2062 Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) +
2063 ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost);
2064 }
2065 }
2066
Philip Reamesb9688f42016-03-02 21:45:13 +00002067 DEBUG(dbgs() << "The cost of loop rotation by making " << getBlockName(*Iter)
Cong Hou7745dbc2015-10-19 23:16:40 +00002068 << " to the top: " << Cost.getFrequency() << "\n");
2069
2070 if (Cost < SmallestRotationCost) {
2071 SmallestRotationCost = Cost;
2072 RotationPos = Iter;
2073 }
2074 }
2075
2076 if (RotationPos != LoopChain.end()) {
Philip Reamesb9688f42016-03-02 21:45:13 +00002077 DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos)
Cong Hou7745dbc2015-10-19 23:16:40 +00002078 << " to the top\n");
2079 std::rotate(LoopChain.begin(), RotationPos, LoopChain.end());
2080 }
2081}
2082
Cong Houb90b9e02015-11-02 21:24:00 +00002083/// \brief Collect blocks in the given loop that are to be placed.
2084///
2085/// When profile data is available, exclude cold blocks from the returned set;
2086/// otherwise, collect all blocks in the loop.
2087MachineBlockPlacement::BlockFilterSet
Kyle Butte9425c4f2017-02-04 02:26:32 +00002088MachineBlockPlacement::collectLoopBlockSet(const MachineLoop &L) {
Cong Houb90b9e02015-11-02 21:24:00 +00002089 BlockFilterSet LoopBlockSet;
2090
2091 // Filter cold blocks off from LoopBlockSet when profile data is available.
2092 // Collect the sum of frequencies of incoming edges to the loop header from
2093 // outside. If we treat the loop as a super block, this is the frequency of
2094 // the loop. Then for each block in the loop, we calculate the ratio between
2095 // its frequency and the frequency of the loop block. When it is too small,
2096 // don't add it to the loop chain. If there are outer loops, then this block
2097 // will be merged into the first outer loop chain for which this block is not
2098 // cold anymore. This needs precise profile data and we only do this when
2099 // profile data is available.
Xinliang David Li52530a72016-06-13 22:23:44 +00002100 if (F->getFunction()->getEntryCount()) {
Cong Houb90b9e02015-11-02 21:24:00 +00002101 BlockFrequency LoopFreq(0);
2102 for (auto LoopPred : L.getHeader()->predecessors())
2103 if (!L.contains(LoopPred))
2104 LoopFreq += MBFI->getBlockFreq(LoopPred) *
2105 MBPI->getEdgeProbability(LoopPred, L.getHeader());
2106
2107 for (MachineBasicBlock *LoopBB : L.getBlocks()) {
2108 auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency();
2109 if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio)
2110 continue;
2111 LoopBlockSet.insert(LoopBB);
2112 }
2113 } else
2114 LoopBlockSet.insert(L.block_begin(), L.block_end());
2115
2116 return LoopBlockSet;
2117}
2118
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00002119/// \brief Forms basic block chains from the natural loop structures.
Chandler Carruth10281422011-10-21 06:46:38 +00002120///
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00002121/// These chains are designed to preserve the existing *structure* of the code
2122/// as much as possible. We can then stitch the chains together in a way which
2123/// both preserves the topological structure and minimizes taken conditional
2124/// branches.
Kyle Butte9425c4f2017-02-04 02:26:32 +00002125void MachineBlockPlacement::buildLoopChains(const MachineLoop &L) {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00002126 // First recurse through any nested loops, building chains for those inner
2127 // loops.
Kyle Butte9425c4f2017-02-04 02:26:32 +00002128 for (const MachineLoop *InnerLoop : L)
Xinliang David Li52530a72016-06-13 22:23:44 +00002129 buildLoopChains(*InnerLoop);
Chandler Carruth10281422011-10-21 06:46:38 +00002130
Xinliang David Li93926ac2016-07-01 05:46:48 +00002131 assert(BlockWorkList.empty());
2132 assert(EHPadWorkList.empty());
Xinliang David Li52530a72016-06-13 22:23:44 +00002133 BlockFilterSet LoopBlockSet = collectLoopBlockSet(L);
Chandler Carruth03adbd42011-11-27 13:34:33 +00002134
Cong Hou7745dbc2015-10-19 23:16:40 +00002135 // Check if we have profile data for this function. If yes, we will rotate
2136 // this loop by modeling costs more precisely which requires the profile data
2137 // for better layout.
2138 bool RotateLoopWithProfile =
Xinliang David Lif0ab6df2016-05-12 02:04:41 +00002139 ForcePreciseRotationCost ||
Xinliang David Li52530a72016-06-13 22:23:44 +00002140 (PreciseRotationCost && F->getFunction()->getEntryCount());
Cong Hou7745dbc2015-10-19 23:16:40 +00002141
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00002142 // First check to see if there is an obviously preferable top block for the
2143 // loop. This will default to the header, but may end up as one of the
2144 // predecessors to the header if there is one which will result in strictly
2145 // fewer branches in the loop body.
Cong Hou7745dbc2015-10-19 23:16:40 +00002146 // When we use profile data to rotate the loop, this is unnecessary.
2147 MachineBasicBlock *LoopTop =
2148 RotateLoopWithProfile ? L.getHeader() : findBestLoopTop(L, LoopBlockSet);
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00002149
2150 // If we selected just the header for the loop top, look for a potentially
2151 // profitable exit block in the event that rotating the loop can eliminate
2152 // branches by placing an exit edge at the bottom.
Cong Hou7745dbc2015-10-19 23:16:40 +00002153 if (!RotateLoopWithProfile && LoopTop == L.getHeader())
Kyle Buttab9cca72016-10-27 21:37:20 +00002154 PreferredLoopExit = findBestLoopExit(L, LoopBlockSet);
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00002155
2156 BlockChain &LoopChain = *BlockToChain[LoopTop];
Chandler Carruth10281422011-10-21 06:46:38 +00002157
Chandler Carruth8d150782011-11-13 11:20:44 +00002158 // FIXME: This is a really lame way of walking the chains in the loop: we
2159 // walk the blocks, and use a set to prevent visiting a particular chain
2160 // twice.
Jakub Staszak90616162011-12-21 23:02:08 +00002161 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
Philip Reamesae27b232016-03-03 00:58:43 +00002162 assert(LoopChain.UnscheduledPredecessors == 0);
Jakub Staszak190c7122011-12-07 19:46:10 +00002163 UpdatedPreds.insert(&LoopChain);
Cong Houb90b9e02015-11-02 21:24:00 +00002164
Kyle Butte9425c4f2017-02-04 02:26:32 +00002165 for (const MachineBasicBlock *LoopBB : LoopBlockSet)
Xinliang David Li93926ac2016-07-01 05:46:48 +00002166 fillWorkLists(LoopBB, UpdatedPreds, &LoopBlockSet);
Chandler Carruth8d150782011-11-13 11:20:44 +00002167
Xinliang David Li93926ac2016-07-01 05:46:48 +00002168 buildChain(LoopTop, LoopChain, &LoopBlockSet);
Cong Hou7745dbc2015-10-19 23:16:40 +00002169
2170 if (RotateLoopWithProfile)
2171 rotateLoopWithProfile(LoopChain, L, LoopBlockSet);
2172 else
Kyle Buttab9cca72016-10-27 21:37:20 +00002173 rotateLoop(LoopChain, PreferredLoopExit, LoopBlockSet);
Chandler Carruth8d150782011-11-13 11:20:44 +00002174
2175 DEBUG({
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002176 // Crash at the end so we get all of the debugging output first.
2177 bool BadLoop = false;
Philip Reamesae27b232016-03-03 00:58:43 +00002178 if (LoopChain.UnscheduledPredecessors) {
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002179 BadLoop = true;
Chandler Carruth8d150782011-11-13 11:20:44 +00002180 dbgs() << "Loop chain contains a block without its preds placed!\n"
2181 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
2182 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002183 }
Chandler Carruth7a715da2015-03-05 03:19:05 +00002184 for (MachineBasicBlock *ChainBB : LoopChain) {
2185 dbgs() << " ... " << getBlockName(ChainBB) << "\n";
Rong Xu66827422016-11-16 20:50:06 +00002186 if (!LoopBlockSet.remove(ChainBB)) {
Chandler Carruth0a31d142011-11-14 10:55:53 +00002187 // We don't mark the loop as bad here because there are real situations
2188 // where this can occur. For example, with an unanalyzable fallthrough
Chandler Carruth99fe42f2011-11-23 10:35:36 +00002189 // from a loop block to a non-loop block or vice versa.
Chandler Carruth8d150782011-11-13 11:20:44 +00002190 dbgs() << "Loop chain contains a block not contained by the loop!\n"
2191 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
2192 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00002193 << " Bad block: " << getBlockName(ChainBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002194 }
Chandler Carruthccc7e422012-04-16 01:12:56 +00002195 }
Chandler Carruth8d150782011-11-13 11:20:44 +00002196
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002197 if (!LoopBlockSet.empty()) {
2198 BadLoop = true;
Kyle Butte9425c4f2017-02-04 02:26:32 +00002199 for (const MachineBasicBlock *LoopBB : LoopBlockSet)
Chandler Carruth8d150782011-11-13 11:20:44 +00002200 dbgs() << "Loop contains blocks never placed into a chain!\n"
2201 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
2202 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00002203 << " Bad block: " << getBlockName(LoopBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002204 }
2205 assert(!BadLoop && "Detected problems with the placement of this loop.");
Chandler Carruth8d150782011-11-13 11:20:44 +00002206 });
Xinliang David Li93926ac2016-07-01 05:46:48 +00002207
2208 BlockWorkList.clear();
2209 EHPadWorkList.clear();
Chandler Carruth10281422011-10-21 06:46:38 +00002210}
2211
Xinliang David Li52530a72016-06-13 22:23:44 +00002212void MachineBlockPlacement::buildCFGChains() {
Chandler Carruth8d150782011-11-13 11:20:44 +00002213 // Ensure that every BB in the function has an associated chain to simplify
2214 // the assumptions of the remaining algorithm.
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00002215 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
Xinliang David Li52530a72016-06-13 22:23:44 +00002216 for (MachineFunction::iterator FI = F->begin(), FE = F->end(); FI != FE;
2217 ++FI) {
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00002218 MachineBasicBlock *BB = &*FI;
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00002219 BlockChain *Chain =
2220 new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00002221 // Also, merge any blocks which we cannot reason about and must preserve
2222 // the exact fallthrough behavior for.
2223 for (;;) {
2224 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00002225 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002226 if (!TII->analyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00002227 break;
2228
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00002229 MachineFunction::iterator NextFI = std::next(FI);
2230 MachineBasicBlock *NextBB = &*NextFI;
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00002231 // Ensure that the layout successor is a viable block, as we know that
2232 // fallthrough is a possibility.
2233 assert(NextFI != FE && "Can't fallthrough past the last block.");
2234 DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
2235 << getBlockName(BB) << " -> " << getBlockName(NextBB)
2236 << "\n");
Craig Topperc0196b12014-04-14 00:51:57 +00002237 Chain->merge(NextBB, nullptr);
Hal Finkel34f9d6a2016-12-15 05:33:19 +00002238#ifndef NDEBUG
Sanjoy Dasd7389d62016-12-15 05:08:57 +00002239 BlocksWithUnanalyzableExits.insert(&*BB);
Hal Finkel34f9d6a2016-12-15 05:33:19 +00002240#endif
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00002241 FI = NextFI;
2242 BB = NextBB;
2243 }
2244 }
Chandler Carruth8d150782011-11-13 11:20:44 +00002245
2246 // Build any loop-based chains.
Sam McCall2a36eee2016-11-01 22:02:14 +00002247 PreferredLoopExit = nullptr;
Chandler Carruth7a715da2015-03-05 03:19:05 +00002248 for (MachineLoop *L : *MLI)
Xinliang David Li52530a72016-06-13 22:23:44 +00002249 buildLoopChains(*L);
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00002250
Xinliang David Li93926ac2016-07-01 05:46:48 +00002251 assert(BlockWorkList.empty());
2252 assert(EHPadWorkList.empty());
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00002253
Chandler Carruth8d150782011-11-13 11:20:44 +00002254 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
Xinliang David Li52530a72016-06-13 22:23:44 +00002255 for (MachineBasicBlock &MBB : *F)
Xinliang David Li93926ac2016-07-01 05:46:48 +00002256 fillWorkLists(&MBB, UpdatedPreds);
Chandler Carruth8d150782011-11-13 11:20:44 +00002257
Xinliang David Li52530a72016-06-13 22:23:44 +00002258 BlockChain &FunctionChain = *BlockToChain[&F->front()];
Xinliang David Li93926ac2016-07-01 05:46:48 +00002259 buildChain(&F->front(), FunctionChain);
Chandler Carruth8d150782011-11-13 11:20:44 +00002260
Matt Arsenault0f5f0152013-12-10 18:55:37 +00002261#ifndef NDEBUG
Matt Arsenault79d55f52013-12-05 20:02:18 +00002262 typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType;
Matt Arsenault0f5f0152013-12-10 18:55:37 +00002263#endif
Chandler Carruth8d150782011-11-13 11:20:44 +00002264 DEBUG({
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002265 // Crash at the end so we get all of the debugging output first.
2266 bool BadFunc = false;
Chandler Carruth8d150782011-11-13 11:20:44 +00002267 FunctionBlockSetType FunctionBlockSet;
Xinliang David Li52530a72016-06-13 22:23:44 +00002268 for (MachineBasicBlock &MBB : *F)
Chandler Carruth7a715da2015-03-05 03:19:05 +00002269 FunctionBlockSet.insert(&MBB);
Chandler Carruth8d150782011-11-13 11:20:44 +00002270
Chandler Carruth7a715da2015-03-05 03:19:05 +00002271 for (MachineBasicBlock *ChainBB : FunctionChain)
2272 if (!FunctionBlockSet.erase(ChainBB)) {
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002273 BadFunc = true;
Chandler Carruth8d150782011-11-13 11:20:44 +00002274 dbgs() << "Function chain contains a block not in the function!\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00002275 << " Bad block: " << getBlockName(ChainBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002276 }
Chandler Carruth8d150782011-11-13 11:20:44 +00002277
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002278 if (!FunctionBlockSet.empty()) {
2279 BadFunc = true;
Chandler Carruth7a715da2015-03-05 03:19:05 +00002280 for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
Chandler Carruth8d150782011-11-13 11:20:44 +00002281 dbgs() << "Function contains blocks never placed into a chain!\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00002282 << " Bad block: " << getBlockName(RemainingBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002283 }
2284 assert(!BadFunc && "Detected problems with the block placement.");
Chandler Carruth8d150782011-11-13 11:20:44 +00002285 });
2286
2287 // Splice the blocks into place.
Xinliang David Li52530a72016-06-13 22:23:44 +00002288 MachineFunction::iterator InsertPos = F->begin();
Xinliang David Li449cdfd2016-06-24 22:54:21 +00002289 DEBUG(dbgs() << "[MBP] Function: "<< F->getName() << "\n");
Chandler Carruth7a715da2015-03-05 03:19:05 +00002290 for (MachineBasicBlock *ChainBB : FunctionChain) {
2291 DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
2292 : " ... ")
2293 << getBlockName(ChainBB) << "\n");
2294 if (InsertPos != MachineFunction::iterator(ChainBB))
Xinliang David Li52530a72016-06-13 22:23:44 +00002295 F->splice(InsertPos, ChainBB);
Chandler Carruth8d150782011-11-13 11:20:44 +00002296 else
2297 ++InsertPos;
2298
2299 // Update the terminator of the previous block.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002300 if (ChainBB == *FunctionChain.begin())
Chandler Carruth8d150782011-11-13 11:20:44 +00002301 continue;
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00002302 MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB));
Chandler Carruth8d150782011-11-13 11:20:44 +00002303
Chandler Carruth10281422011-10-21 06:46:38 +00002304 // FIXME: It would be awesome of updateTerminator would just return rather
2305 // than assert when the branch cannot be analyzed in order to remove this
2306 // boiler plate.
2307 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00002308 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Shuxin Yang8b8fd212013-06-04 01:00:57 +00002309
Sanjoy Dasd7389d62016-12-15 05:08:57 +00002310#ifndef NDEBUG
2311 if (!BlocksWithUnanalyzableExits.count(PrevBB)) {
2312 // Given the exact block placement we chose, we may actually not _need_ to
2313 // be able to edit PrevBB's terminator sequence, but not being _able_ to
2314 // do that at this point is a bug.
2315 assert((!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond) ||
2316 !PrevBB->canFallThrough()) &&
2317 "Unexpected block with un-analyzable fallthrough!");
2318 Cond.clear();
2319 TBB = FBB = nullptr;
2320 }
2321#endif
2322
Haicheng Wu90a55652016-05-24 22:16:14 +00002323 // The "PrevBB" is not yet updated to reflect current code layout, so,
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00002324 // o. it may fall-through to a block without explicit "goto" instruction
Haicheng Wu90a55652016-05-24 22:16:14 +00002325 // before layout, and no longer fall-through it after layout; or
2326 // o. just opposite.
2327 //
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002328 // analyzeBranch() may return erroneous value for FBB when these two
Haicheng Wu90a55652016-05-24 22:16:14 +00002329 // situations take place. For the first scenario FBB is mistakenly set NULL;
2330 // for the 2nd scenario, the FBB, which is expected to be NULL, is
2331 // mistakenly pointing to "*BI".
2332 // Thus, if the future change needs to use FBB before the layout is set, it
2333 // has to correct FBB first by using the code similar to the following:
2334 //
2335 // if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
2336 // PrevBB->updateTerminator();
2337 // Cond.clear();
2338 // TBB = FBB = nullptr;
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002339 // if (TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) {
Haicheng Wu90a55652016-05-24 22:16:14 +00002340 // // FIXME: This should never take place.
2341 // TBB = FBB = nullptr;
2342 // }
2343 // }
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002344 if (!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond))
Haicheng Wu90a55652016-05-24 22:16:14 +00002345 PrevBB->updateTerminator();
Chandler Carruth10281422011-10-21 06:46:38 +00002346 }
Chandler Carruth8d150782011-11-13 11:20:44 +00002347
2348 // Fixup the last block.
2349 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00002350 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002351 if (!TII->analyzeBranch(F->back(), TBB, FBB, Cond))
Xinliang David Li52530a72016-06-13 22:23:44 +00002352 F->back().updateTerminator();
Xinliang David Li93926ac2016-07-01 05:46:48 +00002353
2354 BlockWorkList.clear();
2355 EHPadWorkList.clear();
Haicheng Wu90a55652016-05-24 22:16:14 +00002356}
2357
Xinliang David Li52530a72016-06-13 22:23:44 +00002358void MachineBlockPlacement::optimizeBranches() {
2359 BlockChain &FunctionChain = *BlockToChain[&F->front()];
Haicheng Wu90a55652016-05-24 22:16:14 +00002360 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
Quentin Colombet776e6de2016-05-02 22:58:59 +00002361
2362 // Now that all the basic blocks in the chain have the proper layout,
2363 // make a final call to AnalyzeBranch with AllowModify set.
2364 // Indeed, the target may be able to optimize the branches in a way we
2365 // cannot because all branches may not be analyzable.
2366 // E.g., the target may be able to remove an unconditional branch to
2367 // a fallthrough when it occurs after predicated terminators.
2368 for (MachineBasicBlock *ChainBB : FunctionChain) {
2369 Cond.clear();
Haicheng Wu90a55652016-05-24 22:16:14 +00002370 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002371 if (!TII->analyzeBranch(*ChainBB, TBB, FBB, Cond, /*AllowModify*/ true)) {
Haicheng Wu90a55652016-05-24 22:16:14 +00002372 // If PrevBB has a two-way branch, try to re-order the branches
2373 // such that we branch to the successor with higher probability first.
2374 if (TBB && !Cond.empty() && FBB &&
2375 MBPI->getEdgeProbability(ChainBB, FBB) >
2376 MBPI->getEdgeProbability(ChainBB, TBB) &&
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00002377 !TII->reverseBranchCondition(Cond)) {
Haicheng Wu90a55652016-05-24 22:16:14 +00002378 DEBUG(dbgs() << "Reverse order of the two branches: "
2379 << getBlockName(ChainBB) << "\n");
2380 DEBUG(dbgs() << " Edge probability: "
2381 << MBPI->getEdgeProbability(ChainBB, FBB) << " vs "
2382 << MBPI->getEdgeProbability(ChainBB, TBB) << "\n");
2383 DebugLoc dl; // FIXME: this is nowhere
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00002384 TII->removeBranch(*ChainBB);
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00002385 TII->insertBranch(*ChainBB, FBB, TBB, Cond, dl);
Haicheng Wu90a55652016-05-24 22:16:14 +00002386 ChainBB->updateTerminator();
2387 }
2388 }
Quentin Colombet776e6de2016-05-02 22:58:59 +00002389 }
Haicheng Wue749ce52016-04-29 17:06:44 +00002390}
Chandler Carruth10281422011-10-21 06:46:38 +00002391
Xinliang David Li52530a72016-06-13 22:23:44 +00002392void MachineBlockPlacement::alignBlocks() {
Chandler Carruthccc7e422012-04-16 01:12:56 +00002393 // Walk through the backedges of the function now that we have fully laid out
2394 // the basic blocks and align the destination of each backedge. We don't rely
Chandler Carruth881d0a72012-08-07 09:45:24 +00002395 // exclusively on the loop info here so that we can align backedges in
2396 // unnatural CFGs and backedges that were introduced purely because of the
2397 // loop rotations done during this layout pass.
Xinliang David Li52530a72016-06-13 22:23:44 +00002398 if (F->getFunction()->optForSize())
Chandler Carruth8b9737c2011-10-21 08:57:37 +00002399 return;
Xinliang David Li52530a72016-06-13 22:23:44 +00002400 BlockChain &FunctionChain = *BlockToChain[&F->front()];
Chandler Carruth881d0a72012-08-07 09:45:24 +00002401 if (FunctionChain.begin() == FunctionChain.end())
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00002402 return; // Empty chain.
Chandler Carruth8b9737c2011-10-21 08:57:37 +00002403
Chandler Carruth881d0a72012-08-07 09:45:24 +00002404 const BranchProbability ColdProb(1, 5); // 20%
Xinliang David Li52530a72016-06-13 22:23:44 +00002405 BlockFrequency EntryFreq = MBFI->getBlockFreq(&F->front());
Chandler Carruth881d0a72012-08-07 09:45:24 +00002406 BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
Chandler Carruth7a715da2015-03-05 03:19:05 +00002407 for (MachineBasicBlock *ChainBB : FunctionChain) {
2408 if (ChainBB == *FunctionChain.begin())
2409 continue;
2410
Chandler Carruth881d0a72012-08-07 09:45:24 +00002411 // Don't align non-looping basic blocks. These are unlikely to execute
2412 // enough times to matter in practice. Note that we'll still handle
2413 // unnatural CFGs inside of a natural outer loop (the common case) and
2414 // rotated loops.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002415 MachineLoop *L = MLI->getLoopFor(ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00002416 if (!L)
2417 continue;
2418
Hal Finkel57725662015-01-03 17:58:24 +00002419 unsigned Align = TLI->getPrefLoopAlignment(L);
2420 if (!Align)
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00002421 continue; // Don't care about loop alignment.
Hal Finkel57725662015-01-03 17:58:24 +00002422
Chandler Carruth881d0a72012-08-07 09:45:24 +00002423 // If the block is cold relative to the function entry don't waste space
2424 // aligning it.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002425 BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00002426 if (Freq < WeightedEntryFreq)
2427 continue;
2428
2429 // If the block is cold relative to its loop header, don't align it
2430 // regardless of what edges into the block exist.
2431 MachineBasicBlock *LoopHeader = L->getHeader();
2432 BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
2433 if (Freq < (LoopHeaderFreq * ColdProb))
2434 continue;
2435
2436 // Check for the existence of a non-layout predecessor which would benefit
2437 // from aligning this block.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002438 MachineBasicBlock *LayoutPred =
2439 &*std::prev(MachineFunction::iterator(ChainBB));
Chandler Carruth881d0a72012-08-07 09:45:24 +00002440
2441 // Force alignment if all the predecessors are jumps. We already checked
2442 // that the block isn't cold above.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002443 if (!LayoutPred->isSuccessor(ChainBB)) {
2444 ChainBB->setAlignment(Align);
Chandler Carruth881d0a72012-08-07 09:45:24 +00002445 continue;
2446 }
2447
2448 // Align this block if the layout predecessor's edge into this block is
Nadav Rotem6036f582013-03-29 16:34:23 +00002449 // cold relative to the block. When this is true, other predecessors make up
Chandler Carruth881d0a72012-08-07 09:45:24 +00002450 // all of the hot entries into the block and thus alignment is likely to be
2451 // important.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002452 BranchProbability LayoutProb =
2453 MBPI->getEdgeProbability(LayoutPred, ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00002454 BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
2455 if (LayoutEdgeFreq <= (Freq * ColdProb))
Chandler Carruth7a715da2015-03-05 03:19:05 +00002456 ChainBB->setAlignment(Align);
Chandler Carruthccc7e422012-04-16 01:12:56 +00002457 }
Chandler Carruth8b9737c2011-10-21 08:57:37 +00002458}
2459
Kyle Butt0846e562016-10-11 20:36:43 +00002460/// Tail duplicate \p BB into (some) predecessors if profitable, repeating if
2461/// it was duplicated into its chain predecessor and removed.
2462/// \p BB - Basic block that may be duplicated.
2463///
2464/// \p LPred - Chosen layout predecessor of \p BB.
2465/// Updated to be the chain end if LPred is removed.
2466/// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
2467/// \p BlockFilter - Set of blocks that belong to the loop being laid out.
2468/// Used to identify which blocks to update predecessor
2469/// counts.
2470/// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
2471/// chosen in the given order due to unnatural CFG
2472/// only needed if \p BB is removed and
2473/// \p PrevUnplacedBlockIt pointed to \p BB.
2474/// @return true if \p BB was removed.
2475bool MachineBlockPlacement::repeatedlyTailDuplicateBlock(
2476 MachineBasicBlock *BB, MachineBasicBlock *&LPred,
Kyle Butte9425c4f2017-02-04 02:26:32 +00002477 const MachineBasicBlock *LoopHeaderBB,
Kyle Butt0846e562016-10-11 20:36:43 +00002478 BlockChain &Chain, BlockFilterSet *BlockFilter,
2479 MachineFunction::iterator &PrevUnplacedBlockIt) {
2480 bool Removed, DuplicatedToLPred;
2481 bool DuplicatedToOriginalLPred;
2482 Removed = maybeTailDuplicateBlock(BB, LPred, Chain, BlockFilter,
2483 PrevUnplacedBlockIt,
2484 DuplicatedToLPred);
2485 if (!Removed)
2486 return false;
2487 DuplicatedToOriginalLPred = DuplicatedToLPred;
2488 // Iteratively try to duplicate again. It can happen that a block that is
2489 // duplicated into is still small enough to be duplicated again.
2490 // No need to call markBlockSuccessors in this case, as the blocks being
2491 // duplicated from here on are already scheduled.
2492 // Note that DuplicatedToLPred always implies Removed.
2493 while (DuplicatedToLPred) {
2494 assert (Removed && "Block must have been removed to be duplicated into its "
2495 "layout predecessor.");
2496 MachineBasicBlock *DupBB, *DupPred;
2497 // The removal callback causes Chain.end() to be updated when a block is
2498 // removed. On the first pass through the loop, the chain end should be the
2499 // same as it was on function entry. On subsequent passes, because we are
2500 // duplicating the block at the end of the chain, if it is removed the
2501 // chain will have shrunk by one block.
2502 BlockChain::iterator ChainEnd = Chain.end();
2503 DupBB = *(--ChainEnd);
2504 // Now try to duplicate again.
2505 if (ChainEnd == Chain.begin())
2506 break;
2507 DupPred = *std::prev(ChainEnd);
2508 Removed = maybeTailDuplicateBlock(DupBB, DupPred, Chain, BlockFilter,
2509 PrevUnplacedBlockIt,
2510 DuplicatedToLPred);
2511 }
2512 // If BB was duplicated into LPred, it is now scheduled. But because it was
2513 // removed, markChainSuccessors won't be called for its chain. Instead we
2514 // call markBlockSuccessors for LPred to achieve the same effect. This must go
2515 // at the end because repeating the tail duplication can increase the number
2516 // of unscheduled predecessors.
2517 LPred = *std::prev(Chain.end());
2518 if (DuplicatedToOriginalLPred)
2519 markBlockSuccessors(Chain, LPred, LoopHeaderBB, BlockFilter);
2520 return true;
2521}
2522
2523/// Tail duplicate \p BB into (some) predecessors if profitable.
2524/// \p BB - Basic block that may be duplicated
2525/// \p LPred - Chosen layout predecessor of \p BB
2526/// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
2527/// \p BlockFilter - Set of blocks that belong to the loop being laid out.
2528/// Used to identify which blocks to update predecessor
2529/// counts.
2530/// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
2531/// chosen in the given order due to unnatural CFG
2532/// only needed if \p BB is removed and
2533/// \p PrevUnplacedBlockIt pointed to \p BB.
2534/// \p DuplicatedToLPred - True if the block was duplicated into LPred. Will
2535/// only be true if the block was removed.
2536/// \return - True if the block was duplicated into all preds and removed.
2537bool MachineBlockPlacement::maybeTailDuplicateBlock(
2538 MachineBasicBlock *BB, MachineBasicBlock *LPred,
Kyle Butte9425c4f2017-02-04 02:26:32 +00002539 BlockChain &Chain, BlockFilterSet *BlockFilter,
Kyle Butt0846e562016-10-11 20:36:43 +00002540 MachineFunction::iterator &PrevUnplacedBlockIt,
2541 bool &DuplicatedToLPred) {
Kyle Butt0846e562016-10-11 20:36:43 +00002542 DuplicatedToLPred = false;
Kyle Buttc7d67eef2017-02-04 02:26:34 +00002543 if (!shouldTailDuplicate(BB))
2544 return false;
2545
Kyle Butt0846e562016-10-11 20:36:43 +00002546 DEBUG(dbgs() << "Redoing tail duplication for Succ#"
2547 << BB->getNumber() << "\n");
Kyle Buttb15c0662017-01-31 23:48:32 +00002548
Kyle Butt0846e562016-10-11 20:36:43 +00002549 // This has to be a callback because none of it can be done after
2550 // BB is deleted.
2551 bool Removed = false;
2552 auto RemovalCallback =
2553 [&](MachineBasicBlock *RemBB) {
2554 // Signal to outer function
2555 Removed = true;
2556
2557 // Conservative default.
2558 bool InWorkList = true;
2559 // Remove from the Chain and Chain Map
2560 if (BlockToChain.count(RemBB)) {
2561 BlockChain *Chain = BlockToChain[RemBB];
2562 InWorkList = Chain->UnscheduledPredecessors == 0;
2563 Chain->remove(RemBB);
2564 BlockToChain.erase(RemBB);
2565 }
2566
2567 // Handle the unplaced block iterator
2568 if (&(*PrevUnplacedBlockIt) == RemBB) {
2569 PrevUnplacedBlockIt++;
2570 }
2571
2572 // Handle the Work Lists
2573 if (InWorkList) {
2574 SmallVectorImpl<MachineBasicBlock *> &RemoveList = BlockWorkList;
2575 if (RemBB->isEHPad())
2576 RemoveList = EHPadWorkList;
2577 RemoveList.erase(
2578 remove_if(RemoveList,
2579 [RemBB](MachineBasicBlock *BB) {return BB == RemBB;}),
2580 RemoveList.end());
2581 }
2582
2583 // Handle the filter set
2584 if (BlockFilter) {
Rong Xu66827422016-11-16 20:50:06 +00002585 BlockFilter->remove(RemBB);
Kyle Butt0846e562016-10-11 20:36:43 +00002586 }
2587
2588 // Remove the block from loop info.
2589 MLI->removeBlock(RemBB);
Kyle Buttab9cca72016-10-27 21:37:20 +00002590 if (RemBB == PreferredLoopExit)
2591 PreferredLoopExit = nullptr;
Kyle Butt0846e562016-10-11 20:36:43 +00002592
Kyle Butt0846e562016-10-11 20:36:43 +00002593 DEBUG(dbgs() << "TailDuplicator deleted block: "
2594 << getBlockName(RemBB) << "\n");
2595 };
2596 auto RemovalCallbackRef =
2597 llvm::function_ref<void(MachineBasicBlock*)>(RemovalCallback);
2598
2599 SmallVector<MachineBasicBlock *, 8> DuplicatedPreds;
Kyle Buttb15c0662017-01-31 23:48:32 +00002600 bool IsSimple = TailDup.isSimpleBB(BB);
Kyle Butt0846e562016-10-11 20:36:43 +00002601 TailDup.tailDuplicateAndUpdate(IsSimple, BB, LPred,
2602 &DuplicatedPreds, &RemovalCallbackRef);
2603
2604 // Update UnscheduledPredecessors to reflect tail-duplication.
2605 DuplicatedToLPred = false;
2606 for (MachineBasicBlock *Pred : DuplicatedPreds) {
2607 // We're only looking for unscheduled predecessors that match the filter.
2608 BlockChain* PredChain = BlockToChain[Pred];
2609 if (Pred == LPred)
2610 DuplicatedToLPred = true;
2611 if (Pred == LPred || (BlockFilter && !BlockFilter->count(Pred))
2612 || PredChain == &Chain)
2613 continue;
2614 for (MachineBasicBlock *NewSucc : Pred->successors()) {
2615 if (BlockFilter && !BlockFilter->count(NewSucc))
2616 continue;
2617 BlockChain *NewChain = BlockToChain[NewSucc];
2618 if (NewChain != &Chain && NewChain != PredChain)
2619 NewChain->UnscheduledPredecessors++;
2620 }
2621 }
2622 return Removed;
2623}
2624
Xinliang David Li52530a72016-06-13 22:23:44 +00002625bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &MF) {
2626 if (skipFunction(*MF.getFunction()))
Andrew Kaylor50271f72016-05-03 22:32:30 +00002627 return false;
2628
Chandler Carruth10281422011-10-21 06:46:38 +00002629 // Check for single-block functions and skip them.
Xinliang David Li52530a72016-06-13 22:23:44 +00002630 if (std::next(MF.begin()) == MF.end())
Chandler Carruth10281422011-10-21 06:46:38 +00002631 return false;
2632
Xinliang David Li52530a72016-06-13 22:23:44 +00002633 F = &MF;
Chandler Carruth10281422011-10-21 06:46:38 +00002634 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002635 MBFI = llvm::make_unique<BranchFolder::MBFIWrapper>(
2636 getAnalysis<MachineBlockFrequencyInfo>());
Chandler Carruth8b9737c2011-10-21 08:57:37 +00002637 MLI = &getAnalysis<MachineLoopInfo>();
Xinliang David Li52530a72016-06-13 22:23:44 +00002638 TII = MF.getSubtarget().getInstrInfo();
2639 TLI = MF.getSubtarget().getTargetLowering();
Kyle Buttb15c0662017-01-31 23:48:32 +00002640 MPDT = nullptr;
Eric Christopher690f8e52016-11-01 22:15:50 +00002641
2642 // Initialize PreferredLoopExit to nullptr here since it may never be set if
2643 // there are no MachineLoops.
2644 PreferredLoopExit = nullptr;
2645
Kyle Butt04300b032017-04-12 03:18:20 +00002646 assert(BlockToChain.empty());
2647 assert(ComputedEdges.empty());
2648
Kyle Butt0846e562016-10-11 20:36:43 +00002649 if (TailDupPlacement) {
Kyle Buttb15c0662017-01-31 23:48:32 +00002650 MPDT = &getAnalysis<MachinePostDominatorTree>();
2651 unsigned TailDupSize = TailDupPlacementThreshold;
Kyle Butt0846e562016-10-11 20:36:43 +00002652 if (MF.getFunction()->optForSize())
2653 TailDupSize = 1;
2654 TailDup.initMF(MF, MBPI, /* LayoutMode */ true, TailDupSize);
Kyle Butt1fa60302017-03-03 01:00:22 +00002655 precomputeTriangleChains();
Kyle Butt0846e562016-10-11 20:36:43 +00002656 }
2657
Xinliang David Li52530a72016-06-13 22:23:44 +00002658 buildCFGChains();
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002659
2660 // Changing the layout can create new tail merging opportunities.
2661 TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
2662 // TailMerge can create jump into if branches that make CFG irreducible for
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00002663 // HW that requires structured CFG.
Xinliang David Li52530a72016-06-13 22:23:44 +00002664 bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002665 PassConfig->getEnableTailMerge() &&
2666 BranchFoldPlacement;
2667 // No tail merging opportunities if the block number is less than four.
Xinliang David Li52530a72016-06-13 22:23:44 +00002668 if (MF.size() > 3 && EnableTailMerge) {
Kyle Buttb15c0662017-01-31 23:48:32 +00002669 unsigned TailMergeSize = TailDupPlacementThreshold + 1;
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002670 BranchFolder BF(/*EnableTailMerge=*/true, /*CommonHoist=*/false, *MBFI,
Kyle Butt64e42812016-08-18 18:57:29 +00002671 *MBPI, TailMergeSize);
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002672
Xinliang David Li52530a72016-06-13 22:23:44 +00002673 if (BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002674 getAnalysisIfAvailable<MachineModuleInfo>(), MLI,
2675 /*AfterBlockPlacement=*/true)) {
2676 // Redo the layout if tail merging creates/removes/moves blocks.
2677 BlockToChain.clear();
Kyle Butt04300b032017-04-12 03:18:20 +00002678 ComputedEdges.clear();
Kyle Butt13937612017-03-02 21:44:24 +00002679 // Must redo the post-dominator tree if blocks were changed.
Kyle Buttb15c0662017-01-31 23:48:32 +00002680 if (MPDT)
2681 MPDT->runOnMachineFunction(MF);
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002682 ChainAllocator.DestroyAll();
Xinliang David Li52530a72016-06-13 22:23:44 +00002683 buildCFGChains();
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002684 }
2685 }
2686
Xinliang David Li52530a72016-06-13 22:23:44 +00002687 optimizeBranches();
2688 alignBlocks();
Chandler Carruth10281422011-10-21 06:46:38 +00002689
Chandler Carruth10281422011-10-21 06:46:38 +00002690 BlockToChain.clear();
Kyle Butt04300b032017-04-12 03:18:20 +00002691 ComputedEdges.clear();
Chandler Carruthfd9b4d92011-11-14 10:57:23 +00002692 ChainAllocator.DestroyAll();
Chandler Carruth10281422011-10-21 06:46:38 +00002693
Nadav Rotemc0adc9f2013-04-12 01:24:16 +00002694 if (AlignAllBlock)
2695 // Align all of the blocks in the function to a specific alignment.
Xinliang David Li52530a72016-06-13 22:23:44 +00002696 for (MachineBasicBlock &MBB : MF)
Chandler Carruth7a715da2015-03-05 03:19:05 +00002697 MBB.setAlignment(AlignAllBlock);
Geoff Berry10494ac2016-01-21 17:25:52 +00002698 else if (AlignAllNonFallThruBlocks) {
2699 // Align all of the blocks that have no fall-through predecessors to a
2700 // specific alignment.
Xinliang David Li52530a72016-06-13 22:23:44 +00002701 for (auto MBI = std::next(MF.begin()), MBE = MF.end(); MBI != MBE; ++MBI) {
Geoff Berry10494ac2016-01-21 17:25:52 +00002702 auto LayoutPred = std::prev(MBI);
2703 if (!LayoutPred->isSuccessor(&*MBI))
2704 MBI->setAlignment(AlignAllNonFallThruBlocks);
2705 }
2706 }
Xinliang David Lifd3f6452017-01-29 01:57:02 +00002707 if (ViewBlockLayoutWithBFI != GVDT_None &&
2708 (ViewBlockFreqFuncName.empty() ||
2709 F->getFunction()->getName().equals(ViewBlockFreqFuncName))) {
Xinliang David Li538d6662017-02-15 19:21:04 +00002710 MBFI->view("MBP." + MF.getName(), false);
Xinliang David Lifd3f6452017-01-29 01:57:02 +00002711 }
Xinliang David Lifd3f6452017-01-29 01:57:02 +00002712
Nadav Rotemc0adc9f2013-04-12 01:24:16 +00002713
Chandler Carruth10281422011-10-21 06:46:38 +00002714 // We always return true as we have no way to track whether the final order
2715 // differs from the original order.
2716 return true;
2717}
Chandler Carruthae4e8002011-11-02 07:17:12 +00002718
2719namespace {
2720/// \brief A pass to compute block placement statistics.
2721///
2722/// A separate pass to compute interesting statistics for evaluating block
2723/// placement. This is separate from the actual placement pass so that they can
Benjamin Kramerbde91762012-06-02 10:20:22 +00002724/// be computed in the absence of any placement transformations or when using
Chandler Carruthae4e8002011-11-02 07:17:12 +00002725/// alternative placement strategies.
2726class MachineBlockPlacementStats : public MachineFunctionPass {
2727 /// \brief A handle to the branch probability pass.
2728 const MachineBranchProbabilityInfo *MBPI;
2729
2730 /// \brief A handle to the function-wide block frequency pass.
2731 const MachineBlockFrequencyInfo *MBFI;
2732
2733public:
2734 static char ID; // Pass identification, replacement for typeid
2735 MachineBlockPlacementStats() : MachineFunctionPass(ID) {
2736 initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
2737 }
2738
Craig Topper4584cd52014-03-07 09:26:03 +00002739 bool runOnMachineFunction(MachineFunction &F) override;
Chandler Carruthae4e8002011-11-02 07:17:12 +00002740
Craig Topper4584cd52014-03-07 09:26:03 +00002741 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruthae4e8002011-11-02 07:17:12 +00002742 AU.addRequired<MachineBranchProbabilityInfo>();
2743 AU.addRequired<MachineBlockFrequencyInfo>();
2744 AU.setPreservesAll();
2745 MachineFunctionPass::getAnalysisUsage(AU);
2746 }
Chandler Carruthae4e8002011-11-02 07:17:12 +00002747};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00002748}
Chandler Carruthae4e8002011-11-02 07:17:12 +00002749
2750char MachineBlockPlacementStats::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +00002751char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
Chandler Carruthae4e8002011-11-02 07:17:12 +00002752INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
2753 "Basic Block Placement Stats", false, false)
2754INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
2755INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
2756INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
2757 "Basic Block Placement Stats", false, false)
2758
Chandler Carruthae4e8002011-11-02 07:17:12 +00002759bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
2760 // Check for single-block functions and skip them.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002761 if (std::next(F.begin()) == F.end())
Chandler Carruthae4e8002011-11-02 07:17:12 +00002762 return false;
2763
2764 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
2765 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
2766
Chandler Carruth7a715da2015-03-05 03:19:05 +00002767 for (MachineBasicBlock &MBB : F) {
2768 BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00002769 Statistic &NumBranches =
Chandler Carruth7a715da2015-03-05 03:19:05 +00002770 (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00002771 Statistic &BranchTakenFreq =
Chandler Carruth7a715da2015-03-05 03:19:05 +00002772 (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
2773 for (MachineBasicBlock *Succ : MBB.successors()) {
Chandler Carruthae4e8002011-11-02 07:17:12 +00002774 // Skip if this successor is a fallthrough.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002775 if (MBB.isLayoutSuccessor(Succ))
Chandler Carruthae4e8002011-11-02 07:17:12 +00002776 continue;
2777
Chandler Carruth7a715da2015-03-05 03:19:05 +00002778 BlockFrequency EdgeFreq =
2779 BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
Chandler Carruthae4e8002011-11-02 07:17:12 +00002780 ++NumBranches;
2781 BranchTakenFreq += EdgeFreq.getFrequency();
2782 }
2783 }
2784
2785 return false;
2786}