blob: ad73449f97259edb28370726204cc0e4cc06fc8d [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"
29#include "llvm/ADT/DenseMap.h"
30#include "llvm/ADT/SmallPtrSet.h"
31#include "llvm/ADT/SmallVector.h"
32#include "llvm/ADT/Statistic.h"
Chandler Carruth8b9737c2011-10-21 08:57:37 +000033#include "llvm/CodeGen/MachineBasicBlock.h"
Chandler Carruth10281422011-10-21 06:46:38 +000034#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
35#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Daniel Jasper471e8562015-03-04 11:05:34 +000036#include "llvm/CodeGen/MachineDominators.h"
Chandler Carruth10281422011-10-21 06:46:38 +000037#include "llvm/CodeGen/MachineFunction.h"
Chandler Carruth10281422011-10-21 06:46:38 +000038#include "llvm/CodeGen/MachineFunctionPass.h"
Chandler Carruth8b9737c2011-10-21 08:57:37 +000039#include "llvm/CodeGen/MachineLoopInfo.h"
40#include "llvm/CodeGen/MachineModuleInfo.h"
Chandler Carruth10281422011-10-21 06:46:38 +000041#include "llvm/Support/Allocator.h"
Nadav Rotemc3b0f502013-04-12 00:48:32 +000042#include "llvm/Support/CommandLine.h"
Chandler Carruthbd1be4d2011-10-23 09:18:45 +000043#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000044#include "llvm/Support/raw_ostream.h"
Chandler Carruth10281422011-10-21 06:46:38 +000045#include "llvm/Target/TargetInstrInfo.h"
Chandler Carruth8b9737c2011-10-21 08:57:37 +000046#include "llvm/Target/TargetLowering.h"
Eric Christopherd9134482014-08-04 21:25:23 +000047#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruth10281422011-10-21 06:46:38 +000048#include <algorithm>
49using namespace llvm;
50
Chandler Carruthd0dced52015-03-05 02:28:25 +000051#define DEBUG_TYPE "block-placement"
Chandler Carruth1b9dde02014-04-22 02:02:50 +000052
Chandler Carruthae4e8002011-11-02 07:17:12 +000053STATISTIC(NumCondBranches, "Number of conditional branches");
Craig Topper77ec0772015-09-16 03:52:32 +000054STATISTIC(NumUncondBranches, "Number of unconditional branches");
Chandler Carruthae4e8002011-11-02 07:17:12 +000055STATISTIC(CondBranchTakenFreq,
56 "Potential frequency of taking conditional branches");
57STATISTIC(UncondBranchTakenFreq,
58 "Potential frequency of taking unconditional branches");
59
Nadav Rotemc3b0f502013-04-12 00:48:32 +000060static cl::opt<unsigned> AlignAllBlock("align-all-blocks",
61 cl::desc("Force the alignment of all "
62 "blocks in the function."),
63 cl::init(0), cl::Hidden);
64
Geoff Berry10494ac2016-01-21 17:25:52 +000065static cl::opt<unsigned> AlignAllNonFallThruBlocks(
66 "align-all-nofallthru-blocks",
67 cl::desc("Force the alignment of all "
68 "blocks that have no fall-through predecessors (i.e. don't add "
69 "nops that are executed)."),
70 cl::init(0), cl::Hidden);
71
Benjamin Kramerc8160d62013-11-20 19:08:44 +000072// FIXME: Find a good default for this flag and remove the flag.
Chandler Carruth2fc3fe12015-03-05 02:35:31 +000073static cl::opt<unsigned> ExitBlockBias(
74 "block-placement-exit-block-bias",
75 cl::desc("Block frequency percentage a loop exit block needs "
76 "over the original exit to be considered the new exit."),
77 cl::init(0), cl::Hidden);
Benjamin Kramerc8160d62013-11-20 19:08:44 +000078
Daniel Jasper471e8562015-03-04 11:05:34 +000079static cl::opt<bool> OutlineOptionalBranches(
80 "outline-optional-branches",
81 cl::desc("Put completely optional branches, i.e. branches with a common "
82 "post dominator, out of line."),
83 cl::init(false), cl::Hidden);
84
Daniel Jasper214997c2015-03-20 10:00:37 +000085static cl::opt<unsigned> OutlineOptionalThreshold(
86 "outline-optional-threshold",
87 cl::desc("Don't outline optional branches that are a single block with an "
88 "instruction count below this threshold"),
89 cl::init(4), cl::Hidden);
90
Cong Houb90b9e02015-11-02 21:24:00 +000091static cl::opt<unsigned> LoopToColdBlockRatio(
92 "loop-to-cold-block-ratio",
93 cl::desc("Outline loop blocks from loop chain if (frequency of loop) / "
94 "(frequency of block) is greater than this ratio"),
95 cl::init(5), cl::Hidden);
96
Cong Hou7745dbc2015-10-19 23:16:40 +000097static cl::opt<bool>
98 PreciseRotationCost("precise-rotation-cost",
99 cl::desc("Model the cost of loop rotation more "
100 "precisely by using profile data."),
101 cl::init(false), cl::Hidden);
Xinliang David Lif0ab6df2016-05-12 02:04:41 +0000102static cl::opt<bool>
103 ForcePreciseRotationCost("force-precise-rotation-cost",
104 cl::desc("Model the cost of loop rotation more "
105 "precisely by using profile data."),
106 cl::init(false), cl::Hidden);
Cong Hou7745dbc2015-10-19 23:16:40 +0000107
108static cl::opt<unsigned> MisfetchCost(
109 "misfetch-cost",
110 cl::desc("Cost that models the probablistic risk of an instruction "
111 "misfetch due to a jump comparing to falling through, whose cost "
112 "is zero."),
113 cl::init(1), cl::Hidden);
114
115static cl::opt<unsigned> JumpInstCost("jump-inst-cost",
116 cl::desc("Cost of jump instructions."),
117 cl::init(1), cl::Hidden);
118
Chandler Carruth10281422011-10-21 06:46:38 +0000119namespace {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000120class BlockChain;
Chandler Carruth10281422011-10-21 06:46:38 +0000121/// \brief Type for our function-wide basic block -> block chain mapping.
122typedef DenseMap<MachineBasicBlock *, BlockChain *> BlockToChainMapType;
123}
124
125namespace {
126/// \brief A chain of blocks which will be laid out contiguously.
127///
128/// This is the datastructure representing a chain of consecutive blocks that
129/// are profitable to layout together in order to maximize fallthrough
Chandler Carruth9139f442012-06-26 05:16:37 +0000130/// probabilities and code locality. We also can use a block chain to represent
131/// a sequence of basic blocks which have some external (correctness)
132/// requirement for sequential layout.
Chandler Carruth10281422011-10-21 06:46:38 +0000133///
Chandler Carruth9139f442012-06-26 05:16:37 +0000134/// Chains can be built around a single basic block and can be merged to grow
135/// them. They participate in a block-to-chain mapping, which is updated
136/// automatically as chains are merged together.
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000137class BlockChain {
138 /// \brief The sequence of blocks belonging to this chain.
Chandler Carruth10281422011-10-21 06:46:38 +0000139 ///
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000140 /// This is the sequence of blocks for a particular chain. These will be laid
141 /// out in-order within the function.
142 SmallVector<MachineBasicBlock *, 4> Blocks;
Chandler Carruth10281422011-10-21 06:46:38 +0000143
144 /// \brief A handle to the function-wide basic block to block chain mapping.
145 ///
146 /// This is retained in each block chain to simplify the computation of child
147 /// block chains for SCC-formation and iteration. We store the edges to child
148 /// basic blocks, and map them back to their associated chains using this
149 /// structure.
150 BlockToChainMapType &BlockToChain;
151
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000152public:
Chandler Carruth10281422011-10-21 06:46:38 +0000153 /// \brief Construct a new BlockChain.
154 ///
155 /// This builds a new block chain representing a single basic block in the
156 /// function. It also registers itself as the chain that block participates
157 /// in with the BlockToChain mapping.
158 BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
Philip Reamesae27b232016-03-03 00:58:43 +0000159 : Blocks(1, BB), BlockToChain(BlockToChain), UnscheduledPredecessors(0) {
Chandler Carruth10281422011-10-21 06:46:38 +0000160 assert(BB && "Cannot create a chain with a null basic block");
161 BlockToChain[BB] = this;
162 }
163
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000164 /// \brief Iterator over blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000165 typedef SmallVectorImpl<MachineBasicBlock *>::iterator iterator;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000166
167 /// \brief Beginning of blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000168 iterator begin() { return Blocks.begin(); }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000169
170 /// \brief End of blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000171 iterator end() { return Blocks.end(); }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000172
173 /// \brief Merge a block chain into this one.
Chandler Carruth10281422011-10-21 06:46:38 +0000174 ///
175 /// This routine merges a block chain into this one. It takes care of forming
176 /// a contiguous sequence of basic blocks, updating the edge list, and
177 /// updating the block -> chain mapping. It does not free or tear down the
178 /// old chain, but the old chain's block list is no longer valid.
Jakub Staszak90616162011-12-21 23:02:08 +0000179 void merge(MachineBasicBlock *BB, BlockChain *Chain) {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000180 assert(BB);
181 assert(!Blocks.empty());
Chandler Carruth10281422011-10-21 06:46:38 +0000182
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000183 // Fast path in case we don't have a chain already.
184 if (!Chain) {
185 assert(!BlockToChain[BB]);
186 Blocks.push_back(BB);
187 BlockToChain[BB] = this;
188 return;
Chandler Carruth10281422011-10-21 06:46:38 +0000189 }
190
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000191 assert(BB == *Chain->begin());
192 assert(Chain->begin() != Chain->end());
Chandler Carruth10281422011-10-21 06:46:38 +0000193
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000194 // Update the incoming blocks to point to this chain, and add them to the
195 // chain structure.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000196 for (MachineBasicBlock *ChainBB : *Chain) {
197 Blocks.push_back(ChainBB);
198 assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain");
199 BlockToChain[ChainBB] = this;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000200 }
Chandler Carruth10281422011-10-21 06:46:38 +0000201 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000202
Chandler Carruth49158902012-04-08 14:37:01 +0000203#ifndef NDEBUG
204 /// \brief Dump the blocks in this chain.
Nico Weber7408c702014-01-03 22:53:37 +0000205 LLVM_DUMP_METHOD void dump() {
Chandler Carruth7a715da2015-03-05 03:19:05 +0000206 for (MachineBasicBlock *MBB : *this)
207 MBB->dump();
Chandler Carruth49158902012-04-08 14:37:01 +0000208 }
209#endif // NDEBUG
210
Philip Reamesae27b232016-03-03 00:58:43 +0000211 /// \brief Count of predecessors of any block within the chain which have not
212 /// yet been scheduled. In general, we will delay scheduling this chain
213 /// until those predecessors are scheduled (or we find a sufficiently good
214 /// reason to override this heuristic.) Note that when forming loop chains,
215 /// blocks outside the loop are ignored and treated as if they were already
216 /// scheduled.
Chandler Carruth8d150782011-11-13 11:20:44 +0000217 ///
Philip Reamesae27b232016-03-03 00:58:43 +0000218 /// Note: This field is reinitialized multiple times - once for each loop,
219 /// and then once for the function as a whole.
220 unsigned UnscheduledPredecessors;
Chandler Carruth10281422011-10-21 06:46:38 +0000221};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000222}
Chandler Carruth10281422011-10-21 06:46:38 +0000223
224namespace {
225class MachineBlockPlacement : public MachineFunctionPass {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000226 /// \brief A typedef for a block filter set.
227 typedef SmallPtrSet<MachineBasicBlock *, 16> BlockFilterSet;
228
Chandler Carruth10281422011-10-21 06:46:38 +0000229 /// \brief A handle to the branch probability pass.
230 const MachineBranchProbabilityInfo *MBPI;
231
232 /// \brief A handle to the function-wide block frequency pass.
233 const MachineBlockFrequencyInfo *MBFI;
234
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000235 /// \brief A handle to the loop info.
236 const MachineLoopInfo *MLI;
237
Chandler Carruth10281422011-10-21 06:46:38 +0000238 /// \brief A handle to the target's instruction info.
239 const TargetInstrInfo *TII;
240
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000241 /// \brief A handle to the target's lowering info.
Benjamin Kramer56b31bd2013-01-11 20:05:37 +0000242 const TargetLoweringBase *TLI;
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000243
Daniel Jasper471e8562015-03-04 11:05:34 +0000244 /// \brief A handle to the post dominator tree.
245 MachineDominatorTree *MDT;
246
247 /// \brief A set of blocks that are unavoidably execute, i.e. they dominate
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000248 /// all terminators of the MachineFunction.
Daniel Jasper471e8562015-03-04 11:05:34 +0000249 SmallPtrSet<MachineBasicBlock *, 4> UnavoidableBlocks;
250
Chandler Carruth10281422011-10-21 06:46:38 +0000251 /// \brief Allocator and owner of BlockChain structures.
252 ///
Chandler Carruth9139f442012-06-26 05:16:37 +0000253 /// We build BlockChains lazily while processing the loop structure of
254 /// a function. To reduce malloc traffic, we allocate them using this
255 /// slab-like allocator, and destroy them after the pass completes. An
256 /// important guarantee is that this allocator produces stable pointers to
257 /// the chains.
Chandler Carruth10281422011-10-21 06:46:38 +0000258 SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
259
260 /// \brief Function wide BasicBlock to BlockChain mapping.
261 ///
262 /// This mapping allows efficiently moving from any given basic block to the
263 /// BlockChain it participates in, if any. We use it to, among other things,
264 /// allow implicitly defining edges between chains as the existing edges
265 /// between basic blocks.
266 DenseMap<MachineBasicBlock *, BlockChain *> BlockToChain;
267
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000268 void markChainSuccessors(BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000269 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000270 SmallVectorImpl<MachineBasicBlock *> &EHPadWorkList,
Craig Topperc0196b12014-04-14 00:51:57 +0000271 const BlockFilterSet *BlockFilter = nullptr);
Jakub Staszak90616162011-12-21 23:02:08 +0000272 MachineBasicBlock *selectBestSuccessor(MachineBasicBlock *BB,
273 BlockChain &Chain,
274 const BlockFilterSet *BlockFilter);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000275 MachineBasicBlock *
276 selectBestCandidateBlock(BlockChain &Chain,
Amaury Sechet9ee4ddd2016-04-07 06:34:47 +0000277 SmallVectorImpl<MachineBasicBlock *> &WorkList);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000278 MachineBasicBlock *
279 getFirstUnplacedBlock(MachineFunction &F, const BlockChain &PlacedChain,
280 MachineFunction::iterator &PrevUnplacedBlockIt,
281 const BlockFilterSet *BlockFilter);
Amaury Secheteae09c22016-03-14 21:24:11 +0000282
283 /// \brief Add a basic block to the work list if it is apropriate.
284 ///
285 /// If the optional parameter BlockFilter is provided, only MBB
286 /// present in the set will be added to the worklist. If nullptr
287 /// is provided, no filtering occurs.
288 void fillWorkLists(MachineBasicBlock *MBB,
289 SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
290 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000291 SmallVectorImpl<MachineBasicBlock *> &EHPadWorkList,
Amaury Secheteae09c22016-03-14 21:24:11 +0000292 const BlockFilterSet *BlockFilter);
Chandler Carruth8d150782011-11-13 11:20:44 +0000293 void buildChain(MachineBasicBlock *BB, BlockChain &Chain,
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000294 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000295 SmallVectorImpl<MachineBasicBlock *> &EHPadWorkList,
Craig Topperc0196b12014-04-14 00:51:57 +0000296 const BlockFilterSet *BlockFilter = nullptr);
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000297 MachineBasicBlock *findBestLoopTop(MachineLoop &L,
298 const BlockFilterSet &LoopBlockSet);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000299 MachineBasicBlock *findBestLoopExit(MachineFunction &F, MachineLoop &L,
Chandler Carruthccc7e422012-04-16 01:12:56 +0000300 const BlockFilterSet &LoopBlockSet);
Cong Houb90b9e02015-11-02 21:24:00 +0000301 BlockFilterSet collectLoopBlockSet(MachineFunction &F, MachineLoop &L);
Jakub Staszak90616162011-12-21 23:02:08 +0000302 void buildLoopChains(MachineFunction &F, MachineLoop &L);
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000303 void rotateLoop(BlockChain &LoopChain, MachineBasicBlock *ExitingBB,
304 const BlockFilterSet &LoopBlockSet);
Cong Hou7745dbc2015-10-19 23:16:40 +0000305 void rotateLoopWithProfile(BlockChain &LoopChain, MachineLoop &L,
306 const BlockFilterSet &LoopBlockSet);
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000307 void buildCFGChains(MachineFunction &F);
Haicheng Wue749ce52016-04-29 17:06:44 +0000308 void alignBlocks(MachineFunction &F);
Chandler Carruth10281422011-10-21 06:46:38 +0000309
310public:
311 static char ID; // Pass identification, replacement for typeid
312 MachineBlockPlacement() : MachineFunctionPass(ID) {
313 initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
314 }
315
Craig Topper4584cd52014-03-07 09:26:03 +0000316 bool runOnMachineFunction(MachineFunction &F) override;
Chandler Carruth10281422011-10-21 06:46:38 +0000317
Craig Topper4584cd52014-03-07 09:26:03 +0000318 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth10281422011-10-21 06:46:38 +0000319 AU.addRequired<MachineBranchProbabilityInfo>();
320 AU.addRequired<MachineBlockFrequencyInfo>();
Daniel Jasper471e8562015-03-04 11:05:34 +0000321 AU.addRequired<MachineDominatorTree>();
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000322 AU.addRequired<MachineLoopInfo>();
Chandler Carruth10281422011-10-21 06:46:38 +0000323 MachineFunctionPass::getAnalysisUsage(AU);
324 }
Chandler Carruth10281422011-10-21 06:46:38 +0000325};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000326}
Chandler Carruth10281422011-10-21 06:46:38 +0000327
328char MachineBlockPlacement::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000329char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
Chandler Carruthd0dced52015-03-05 02:28:25 +0000330INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement",
Chandler Carruth10281422011-10-21 06:46:38 +0000331 "Branch Probability Basic Block Placement", false, false)
332INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
333INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
Daniel Jasper471e8562015-03-04 11:05:34 +0000334INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000335INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
Chandler Carruthd0dced52015-03-05 02:28:25 +0000336INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement",
Chandler Carruth10281422011-10-21 06:46:38 +0000337 "Branch Probability Basic Block Placement", false, false)
338
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000339#ifndef NDEBUG
340/// \brief Helper to print the name of a MBB.
341///
342/// Only used by debug logging.
Jakub Staszak90616162011-12-21 23:02:08 +0000343static std::string getBlockName(MachineBasicBlock *BB) {
Alp Tokere69170a2014-06-26 22:52:05 +0000344 std::string Result;
345 raw_string_ostream OS(Result);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000346 OS << "BB#" << BB->getNumber();
Philip Reamesb9688f42016-03-02 21:45:13 +0000347 OS << " ('" << BB->getName() << "')";
Alp Tokere69170a2014-06-26 22:52:05 +0000348 OS.flush();
349 return Result;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000350}
351#endif
352
Chandler Carrutheb4ec3a2011-11-13 11:34:55 +0000353/// \brief Mark a chain's successors as having one fewer preds.
354///
355/// When a chain is being merged into the "placed" chain, this routine will
356/// quickly walk the successors of each block in the chain and mark them as
357/// having one fewer active predecessor. It also adds any successors of this
358/// chain which reach the zero-predecessor state to the worklist passed in.
Chandler Carruth8d150782011-11-13 11:20:44 +0000359void MachineBlockPlacement::markChainSuccessors(
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000360 BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
Chandler Carruth8d150782011-11-13 11:20:44 +0000361 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000362 SmallVectorImpl<MachineBasicBlock *> &EHPadWorkList,
Jakub Staszak90616162011-12-21 23:02:08 +0000363 const BlockFilterSet *BlockFilter) {
Chandler Carruth8d150782011-11-13 11:20:44 +0000364 // Walk all the blocks in this chain, marking their successors as having
365 // a predecessor placed.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000366 for (MachineBasicBlock *MBB : Chain) {
Chandler Carruth8d150782011-11-13 11:20:44 +0000367 // Add any successors for which this is the only un-placed in-loop
368 // predecessor to the worklist as a viable candidate for CFG-neutral
369 // placement. No subsequent placement of this block will violate the CFG
370 // shape, so we get to use heuristics to choose a favorable placement.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000371 for (MachineBasicBlock *Succ : MBB->successors()) {
372 if (BlockFilter && !BlockFilter->count(Succ))
Chandler Carruth8d150782011-11-13 11:20:44 +0000373 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000374 BlockChain &SuccChain = *BlockToChain[Succ];
Chandler Carruth8d150782011-11-13 11:20:44 +0000375 // Disregard edges within a fixed chain, or edges to the loop header.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000376 if (&Chain == &SuccChain || Succ == LoopHeaderBB)
Chandler Carruth8d150782011-11-13 11:20:44 +0000377 continue;
Chandler Carruth10281422011-10-21 06:46:38 +0000378
Chandler Carruth8d150782011-11-13 11:20:44 +0000379 // This is a cross-chain edge that is within the loop, so decrement the
380 // loop predecessor count of the destination chain.
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000381 if (SuccChain.UnscheduledPredecessors == 0 ||
382 --SuccChain.UnscheduledPredecessors > 0)
383 continue;
384
385 auto *MBB = *SuccChain.begin();
386 if (MBB->isEHPad())
387 EHPadWorkList.push_back(MBB);
388 else
389 BlockWorkList.push_back(MBB);
Chandler Carruth10281422011-10-21 06:46:38 +0000390 }
391 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000392}
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000393
Chandler Carruthb3361722011-11-13 11:34:53 +0000394/// \brief Select the best successor for a block.
395///
396/// This looks across all successors of a particular block and attempts to
397/// select the "best" one to be the layout successor. It only considers direct
398/// successors which also pass the block filter. It will attempt to avoid
399/// breaking CFG structure, but cave and break such structures in the case of
400/// very hot successor edges.
401///
402/// \returns The best successor block found, or null if none are viable.
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000403MachineBasicBlock *
404MachineBlockPlacement::selectBestSuccessor(MachineBasicBlock *BB,
405 BlockChain &Chain,
406 const BlockFilterSet *BlockFilter) {
Chandler Carruthb3361722011-11-13 11:34:53 +0000407 const BranchProbability HotProb(4, 5); // 80%
408
Craig Topperc0196b12014-04-14 00:51:57 +0000409 MachineBasicBlock *BestSucc = nullptr;
Cong Houd97c1002015-12-01 05:29:22 +0000410 auto BestProb = BranchProbability::getZero();
Chandler Carruthb3361722011-11-13 11:34:53 +0000411
Cong Houd97c1002015-12-01 05:29:22 +0000412 // Adjust edge probabilities by excluding edges pointing to blocks that is
413 // either not in BlockFilter or is already in the current chain. Consider the
414 // following CFG:
Cong Hou41cf1a52015-11-18 00:52:52 +0000415 //
416 // --->A
417 // | / \
418 // | B C
419 // | \ / \
420 // ----D E
421 //
422 // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after
423 // A->C is chosen as a fall-through, D won't be selected as a successor of C
424 // due to CFG constraint (the probability of C->D is not greater than
425 // HotProb). If we exclude E that is not in BlockFilter when calculating the
426 // probability of C->D, D will be selected and we will get A C D B as the
427 // layout of this loop.
Cong Houd97c1002015-12-01 05:29:22 +0000428 auto AdjustedSumProb = BranchProbability::getOne();
Cong Hou41cf1a52015-11-18 00:52:52 +0000429 SmallVector<MachineBasicBlock *, 4> Successors;
430 for (MachineBasicBlock *Succ : BB->successors()) {
431 bool SkipSucc = false;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000432 if (Succ->isEHPad() || (BlockFilter && !BlockFilter->count(Succ))) {
Cong Hou41cf1a52015-11-18 00:52:52 +0000433 SkipSucc = true;
434 } else {
435 BlockChain *SuccChain = BlockToChain[Succ];
436 if (SuccChain == &Chain) {
Cong Hou41cf1a52015-11-18 00:52:52 +0000437 SkipSucc = true;
438 } else if (Succ != *SuccChain->begin()) {
439 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> Mid chain!\n");
440 continue;
441 }
442 }
443 if (SkipSucc)
Cong Houd97c1002015-12-01 05:29:22 +0000444 AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ);
Cong Hou41cf1a52015-11-18 00:52:52 +0000445 else
446 Successors.push_back(Succ);
447 }
448
449 DEBUG(dbgs() << "Attempting merge from: " << getBlockName(BB) << "\n");
450 for (MachineBasicBlock *Succ : Successors) {
Cong Houd97c1002015-12-01 05:29:22 +0000451 BranchProbability SuccProb;
452 uint32_t SuccProbN = MBPI->getEdgeProbability(BB, Succ).getNumerator();
453 uint32_t SuccProbD = AdjustedSumProb.getNumerator();
454 if (SuccProbN >= SuccProbD)
455 SuccProb = BranchProbability::getOne();
456 else
457 SuccProb = BranchProbability(SuccProbN, SuccProbD);
Chandler Carruthb3361722011-11-13 11:34:53 +0000458
Daniel Jasper471e8562015-03-04 11:05:34 +0000459 // If we outline optional branches, look whether Succ is unavoidable, i.e.
460 // dominates all terminators of the MachineFunction. If it does, other
461 // successors must be optional. Don't do this for cold branches.
462 if (OutlineOptionalBranches && SuccProb > HotProb.getCompl() &&
Daniel Jasper214997c2015-03-20 10:00:37 +0000463 UnavoidableBlocks.count(Succ) > 0) {
464 auto HasShortOptionalBranch = [&]() {
465 for (MachineBasicBlock *Pred : Succ->predecessors()) {
466 // Check whether there is an unplaced optional branch.
467 if (Pred == Succ || (BlockFilter && !BlockFilter->count(Pred)) ||
468 BlockToChain[Pred] == &Chain)
469 continue;
470 // Check whether the optional branch has exactly one BB.
471 if (Pred->pred_size() > 1 || *Pred->pred_begin() != BB)
472 continue;
473 // Check whether the optional branch is small.
474 if (Pred->size() < OutlineOptionalThreshold)
475 return true;
476 }
477 return false;
478 };
479 if (!HasShortOptionalBranch())
480 return Succ;
481 }
Daniel Jasper471e8562015-03-04 11:05:34 +0000482
Chandler Carruthb3361722011-11-13 11:34:53 +0000483 // Only consider successors which are either "hot", or wouldn't violate
484 // any CFG constraints.
Cong Hou41cf1a52015-11-18 00:52:52 +0000485 BlockChain &SuccChain = *BlockToChain[Succ];
Philip Reamesae27b232016-03-03 00:58:43 +0000486 if (SuccChain.UnscheduledPredecessors != 0) {
Chandler Carruth18dfac32011-11-20 11:22:06 +0000487 if (SuccProb < HotProb) {
Daniel Jaspered9eb722015-02-18 08:19:16 +0000488 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
Chandler Carruth260258b2013-11-25 00:43:41 +0000489 << " (prob) (CFG conflict)\n");
Chandler Carruth18dfac32011-11-20 11:22:06 +0000490 continue;
491 }
492
Daniel Jasper4d7b0432015-02-18 08:18:07 +0000493 // Make sure that a hot successor doesn't have a globally more
494 // important predecessor.
Cong Houd97c1002015-12-01 05:29:22 +0000495 auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ);
Daniel Jasper4d7b0432015-02-18 08:18:07 +0000496 BlockFrequency CandidateEdgeFreq =
Cong Hou41cf1a52015-11-18 00:52:52 +0000497 MBFI->getBlockFreq(BB) * RealSuccProb * HotProb.getCompl();
Daniel Jasper4d7b0432015-02-18 08:18:07 +0000498 bool BadCFGConflict = false;
Daniel Jaspered9eb722015-02-18 08:19:16 +0000499 for (MachineBasicBlock *Pred : Succ->predecessors()) {
Philip Reames23d93392016-03-03 00:01:42 +0000500 if (Pred == Succ || BlockToChain[Pred] == &SuccChain ||
501 (BlockFilter && !BlockFilter->count(Pred)) ||
Daniel Jaspered9eb722015-02-18 08:19:16 +0000502 BlockToChain[Pred] == &Chain)
Chandler Carruthe3288142015-01-14 20:19:29 +0000503 continue;
Daniel Jasper4d7b0432015-02-18 08:18:07 +0000504 BlockFrequency PredEdgeFreq =
Daniel Jaspered9eb722015-02-18 08:19:16 +0000505 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
Daniel Jasper4d7b0432015-02-18 08:18:07 +0000506 if (PredEdgeFreq >= CandidateEdgeFreq) {
507 BadCFGConflict = true;
508 break;
Chandler Carruthe3288142015-01-14 20:19:29 +0000509 }
Chandler Carruth18dfac32011-11-20 11:22:06 +0000510 }
Daniel Jasper4d7b0432015-02-18 08:18:07 +0000511 if (BadCFGConflict) {
Daniel Jaspered9eb722015-02-18 08:19:16 +0000512 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
Daniel Jasper4d7b0432015-02-18 08:18:07 +0000513 << " (prob) (non-cold CFG conflict)\n");
514 continue;
515 }
Chandler Carruthb3361722011-11-13 11:34:53 +0000516 }
517
Daniel Jaspered9eb722015-02-18 08:19:16 +0000518 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
Chandler Carruthb3361722011-11-13 11:34:53 +0000519 << " (prob)"
Philip Reamesae27b232016-03-03 00:58:43 +0000520 << (SuccChain.UnscheduledPredecessors != 0 ? " (CFG break)" : "")
Chandler Carruthb3361722011-11-13 11:34:53 +0000521 << "\n");
Cong Houd97c1002015-12-01 05:29:22 +0000522 if (BestSucc && BestProb >= SuccProb)
Chandler Carruthb3361722011-11-13 11:34:53 +0000523 continue;
Daniel Jaspered9eb722015-02-18 08:19:16 +0000524 BestSucc = Succ;
Cong Houd97c1002015-12-01 05:29:22 +0000525 BestProb = SuccProb;
Chandler Carruthb3361722011-11-13 11:34:53 +0000526 }
527 return BestSucc;
528}
529
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000530/// \brief Select the best block from a worklist.
531///
532/// This looks through the provided worklist as a list of candidate basic
533/// blocks and select the most profitable one to place. The definition of
534/// profitable only really makes sense in the context of a loop. This returns
535/// the most frequently visited block in the worklist, which in the case of
536/// a loop, is the one most desirable to be physically close to the rest of the
537/// loop body in order to improve icache behavior.
538///
539/// \returns The best block found, or null if none are viable.
540MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
Amaury Sechet9ee4ddd2016-04-07 06:34:47 +0000541 BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList) {
Chandler Carruth0af6a0b2011-11-14 09:46:33 +0000542 // Once we need to walk the worklist looking for a candidate, cleanup the
543 // worklist of already placed entries.
544 // FIXME: If this shows up on profiles, it could be folded (at the cost of
545 // some code complexity) into the loop below.
546 WorkList.erase(std::remove_if(WorkList.begin(), WorkList.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000547 [&](MachineBasicBlock *BB) {
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000548 return BlockToChain.lookup(BB) == &Chain;
549 }),
Chandler Carruth0af6a0b2011-11-14 09:46:33 +0000550 WorkList.end());
551
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000552 if (WorkList.empty())
553 return nullptr;
554
555 bool IsEHPad = WorkList[0]->isEHPad();
556
Craig Topperc0196b12014-04-14 00:51:57 +0000557 MachineBasicBlock *BestBlock = nullptr;
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000558 BlockFrequency BestFreq;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000559 for (MachineBasicBlock *MBB : WorkList) {
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000560 assert(MBB->isEHPad() == IsEHPad);
561
Chandler Carruth7a715da2015-03-05 03:19:05 +0000562 BlockChain &SuccChain = *BlockToChain[MBB];
Philip Reames02e11322016-03-02 22:40:51 +0000563 if (&SuccChain == &Chain)
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000564 continue;
Junmo Park4ba6cf62016-03-11 05:07:07 +0000565
Philip Reamesae27b232016-03-03 00:58:43 +0000566 assert(SuccChain.UnscheduledPredecessors == 0 && "Found CFG-violating block");
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000567
Chandler Carruth7a715da2015-03-05 03:19:05 +0000568 BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
569 DEBUG(dbgs() << " " << getBlockName(MBB) << " -> ";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000570 MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000571
572 // For ehpad, we layout the least probable first as to avoid jumping back
573 // from least probable landingpads to more probable ones.
574 //
575 // FIXME: Using probability is probably (!) not the best way to achieve
576 // this. We should probably have a more principled approach to layout
577 // cleanup code.
578 //
579 // The goal is to get:
580 //
581 // +--------------------------+
582 // | V
583 // InnerLp -> InnerCleanup OuterLp -> OuterCleanup -> Resume
584 //
585 // Rather than:
586 //
587 // +-------------------------------------+
588 // V |
589 // OuterLp -> OuterCleanup -> Resume InnerLp -> InnerCleanup
590 if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq)))
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000591 continue;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000592
Chandler Carruth7a715da2015-03-05 03:19:05 +0000593 BestBlock = MBB;
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000594 BestFreq = CandidateFreq;
595 }
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000596
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000597 return BestBlock;
598}
599
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000600/// \brief Retrieve the first unplaced basic block.
601///
602/// This routine is called when we are unable to use the CFG to walk through
603/// all of the basic blocks and form a chain due to unnatural loops in the CFG.
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000604/// We walk through the function's blocks in order, starting from the
605/// LastUnplacedBlockIt. We update this iterator on each call to avoid
606/// re-scanning the entire sequence on repeated calls to this routine.
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000607MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000608 MachineFunction &F, const BlockChain &PlacedChain,
609 MachineFunction::iterator &PrevUnplacedBlockIt,
Jakub Staszak90616162011-12-21 23:02:08 +0000610 const BlockFilterSet *BlockFilter) {
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000611 for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F.end(); I != E;
612 ++I) {
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +0000613 if (BlockFilter && !BlockFilter->count(&*I))
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000614 continue;
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +0000615 if (BlockToChain[&*I] != &PlacedChain) {
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000616 PrevUnplacedBlockIt = I;
Chandler Carruth4a87aa02011-11-23 03:03:21 +0000617 // Now select the head of the chain to which the unplaced block belongs
618 // as the block to place. This will force the entire chain to be placed,
619 // and satisfies the requirements of merging chains.
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +0000620 return *BlockToChain[&*I]->begin();
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000621 }
622 }
Craig Topperc0196b12014-04-14 00:51:57 +0000623 return nullptr;
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000624}
625
Amaury Secheteae09c22016-03-14 21:24:11 +0000626void MachineBlockPlacement::fillWorkLists(
627 MachineBasicBlock *MBB,
628 SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
629 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000630 SmallVectorImpl<MachineBasicBlock *> &EHPadWorkList,
Amaury Secheteae09c22016-03-14 21:24:11 +0000631 const BlockFilterSet *BlockFilter = nullptr) {
632 BlockChain &Chain = *BlockToChain[MBB];
633 if (!UpdatedPreds.insert(&Chain).second)
634 return;
635
636 assert(Chain.UnscheduledPredecessors == 0);
637 for (MachineBasicBlock *ChainBB : Chain) {
638 assert(BlockToChain[ChainBB] == &Chain);
639 for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
640 if (BlockFilter && !BlockFilter->count(Pred))
641 continue;
642 if (BlockToChain[Pred] == &Chain)
643 continue;
644 ++Chain.UnscheduledPredecessors;
645 }
646 }
647
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000648 if (Chain.UnscheduledPredecessors != 0)
649 return;
650
651 MBB = *Chain.begin();
652 if (MBB->isEHPad())
653 EHPadWorkList.push_back(MBB);
654 else
655 BlockWorkList.push_back(MBB);
Amaury Secheteae09c22016-03-14 21:24:11 +0000656}
657
Chandler Carruth8d150782011-11-13 11:20:44 +0000658void MachineBlockPlacement::buildChain(
Daniel Jasper471e8562015-03-04 11:05:34 +0000659 MachineBasicBlock *BB, BlockChain &Chain,
Chandler Carruth8d150782011-11-13 11:20:44 +0000660 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000661 SmallVectorImpl<MachineBasicBlock *> &EHPadWorkList,
Jakub Staszak90616162011-12-21 23:02:08 +0000662 const BlockFilterSet *BlockFilter) {
Chandler Carruth8d150782011-11-13 11:20:44 +0000663 assert(BB);
Jakub Staszak90616162011-12-21 23:02:08 +0000664 assert(BlockToChain[BB] == &Chain);
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000665 MachineFunction &F = *BB->getParent();
666 MachineFunction::iterator PrevUnplacedBlockIt = F.begin();
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000667
Chandler Carruth8d150782011-11-13 11:20:44 +0000668 MachineBasicBlock *LoopHeaderBB = BB;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000669 markChainSuccessors(Chain, LoopHeaderBB, BlockWorkList, EHPadWorkList,
670 BlockFilter);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000671 BB = *std::prev(Chain.end());
Chandler Carruth8d150782011-11-13 11:20:44 +0000672 for (;;) {
673 assert(BB);
Jakub Staszak90616162011-12-21 23:02:08 +0000674 assert(BlockToChain[BB] == &Chain);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000675 assert(*std::prev(Chain.end()) == BB);
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000676
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +0000677 // Look for the best viable successor if there is one to place immediately
678 // after this block.
Duncan Sands291d47e2012-09-14 09:00:11 +0000679 MachineBasicBlock *BestSucc = selectBestSuccessor(BB, Chain, BlockFilter);
Chandler Carruth8d150782011-11-13 11:20:44 +0000680
681 // If an immediate successor isn't available, look for the best viable
682 // block among those we've identified as not violating the loop's CFG at
683 // this point. This won't be a fallthrough, but it will increase locality.
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000684 if (!BestSucc)
Amaury Sechet9ee4ddd2016-04-07 06:34:47 +0000685 BestSucc = selectBestCandidateBlock(Chain, BlockWorkList);
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000686 if (!BestSucc)
687 BestSucc = selectBestCandidateBlock(Chain, EHPadWorkList);
Chandler Carruth8d150782011-11-13 11:20:44 +0000688
Chandler Carruth8d150782011-11-13 11:20:44 +0000689 if (!BestSucc) {
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000690 BestSucc =
691 getFirstUnplacedBlock(F, Chain, PrevUnplacedBlockIt, BlockFilter);
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000692 if (!BestSucc)
693 break;
694
695 DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
696 "layout successor until the CFG reduces\n");
Chandler Carruth8d150782011-11-13 11:20:44 +0000697 }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000698
Chandler Carruth8d150782011-11-13 11:20:44 +0000699 // Place this block, updating the datastructures to reflect its placement.
Jakub Staszak90616162011-12-21 23:02:08 +0000700 BlockChain &SuccChain = *BlockToChain[BestSucc];
Philip Reamesae27b232016-03-03 00:58:43 +0000701 // Zero out UnscheduledPredecessors for the successor we're about to merge in case
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000702 // we selected a successor that didn't fit naturally into the CFG.
Philip Reamesae27b232016-03-03 00:58:43 +0000703 SuccChain.UnscheduledPredecessors = 0;
Philip Reamesb9688f42016-03-02 21:45:13 +0000704 DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to "
705 << getBlockName(BestSucc) << "\n");
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000706 markChainSuccessors(SuccChain, LoopHeaderBB, BlockWorkList, EHPadWorkList,
707 BlockFilter);
Chandler Carruth8d150782011-11-13 11:20:44 +0000708 Chain.merge(BestSucc, &SuccChain);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000709 BB = *std::prev(Chain.end());
Jakub Staszak190c7122011-12-07 19:46:10 +0000710 }
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000711
712 DEBUG(dbgs() << "Finished forming chain for header block "
Philip Reamesb9688f42016-03-02 21:45:13 +0000713 << getBlockName(*Chain.begin()) << "\n");
Chandler Carruth10281422011-10-21 06:46:38 +0000714}
715
Chandler Carruth03adbd42011-11-27 13:34:33 +0000716/// \brief Find the best loop top block for layout.
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000717///
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000718/// Look for a block which is strictly better than the loop header for laying
719/// out at the top of the loop. This looks for one and only one pattern:
720/// a latch block with no conditional exit. This block will cause a conditional
721/// jump around it or will be the bottom of the loop if we lay it out in place,
722/// but if it it doesn't end up at the bottom of the loop for any reason,
723/// rotation alone won't fix it. Because such a block will always result in an
724/// unconditional jump (for the backedge) rotating it in front of the loop
725/// header is always profitable.
726MachineBasicBlock *
727MachineBlockPlacement::findBestLoopTop(MachineLoop &L,
728 const BlockFilterSet &LoopBlockSet) {
729 // Check that the header hasn't been fused with a preheader block due to
730 // crazy branches. If it has, we need to start with the header at the top to
731 // prevent pulling the preheader into the loop body.
732 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
733 if (!LoopBlockSet.count(*HeaderChain.begin()))
734 return L.getHeader();
735
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000736 DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(L.getHeader())
737 << "\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000738
739 BlockFrequency BestPredFreq;
Craig Topperc0196b12014-04-14 00:51:57 +0000740 MachineBasicBlock *BestPred = nullptr;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000741 for (MachineBasicBlock *Pred : L.getHeader()->predecessors()) {
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000742 if (!LoopBlockSet.count(Pred))
743 continue;
744 DEBUG(dbgs() << " header pred: " << getBlockName(Pred) << ", "
Michael Gottesmanb78dec82013-12-14 00:25:45 +0000745 << Pred->succ_size() << " successors, ";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000746 MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000747 if (Pred->succ_size() > 1)
748 continue;
749
750 BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
751 if (!BestPred || PredFreq > BestPredFreq ||
752 (!(PredFreq < BestPredFreq) &&
753 Pred->isLayoutSuccessor(L.getHeader()))) {
754 BestPred = Pred;
755 BestPredFreq = PredFreq;
756 }
757 }
758
759 // If no direct predecessor is fine, just use the loop header.
Philip Reamesb9688f42016-03-02 21:45:13 +0000760 if (!BestPred) {
761 DEBUG(dbgs() << " final top unchanged\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000762 return L.getHeader();
Philip Reamesb9688f42016-03-02 21:45:13 +0000763 }
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000764
765 // Walk backwards through any straight line of predecessors.
766 while (BestPred->pred_size() == 1 &&
767 (*BestPred->pred_begin())->succ_size() == 1 &&
768 *BestPred->pred_begin() != L.getHeader())
769 BestPred = *BestPred->pred_begin();
770
771 DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n");
772 return BestPred;
773}
774
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000775/// \brief Find the best loop exiting block for layout.
776///
Chandler Carruth03adbd42011-11-27 13:34:33 +0000777/// This routine implements the logic to analyze the loop looking for the best
778/// block to layout at the top of the loop. Typically this is done to maximize
779/// fallthrough opportunities.
780MachineBasicBlock *
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000781MachineBlockPlacement::findBestLoopExit(MachineFunction &F, MachineLoop &L,
Chandler Carruthccc7e422012-04-16 01:12:56 +0000782 const BlockFilterSet &LoopBlockSet) {
Chandler Carruth68062612012-04-10 13:35:57 +0000783 // We don't want to layout the loop linearly in all cases. If the loop header
784 // is just a normal basic block in the loop, we want to look for what block
785 // within the loop is the best one to layout at the top. However, if the loop
786 // header has be pre-merged into a chain due to predecessors not having
787 // analyzable branches, *and* the predecessor it is merged with is *not* part
788 // of the loop, rotating the header into the middle of the loop will create
789 // a non-contiguous range of blocks which is Very Bad. So start with the
790 // header and only rotate if safe.
791 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
792 if (!LoopBlockSet.count(*HeaderChain.begin()))
Craig Topperc0196b12014-04-14 00:51:57 +0000793 return nullptr;
Chandler Carruth68062612012-04-10 13:35:57 +0000794
Chandler Carruth03adbd42011-11-27 13:34:33 +0000795 BlockFrequency BestExitEdgeFreq;
Chandler Carruthccc7e422012-04-16 01:12:56 +0000796 unsigned BestExitLoopDepth = 0;
Craig Topperc0196b12014-04-14 00:51:57 +0000797 MachineBasicBlock *ExitingBB = nullptr;
Chandler Carruth4f567202011-11-27 20:18:00 +0000798 // If there are exits to outer loops, loop rotation can severely limit
799 // fallthrough opportunites unless it selects such an exit. Keep a set of
800 // blocks where rotating to exit with that block will reach an outer loop.
801 SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
802
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000803 DEBUG(dbgs() << "Finding best loop exit for: " << getBlockName(L.getHeader())
804 << "\n");
Chandler Carruth7a715da2015-03-05 03:19:05 +0000805 for (MachineBasicBlock *MBB : L.getBlocks()) {
806 BlockChain &Chain = *BlockToChain[MBB];
Chandler Carruth03adbd42011-11-27 13:34:33 +0000807 // Ensure that this block is at the end of a chain; otherwise it could be
Chandler Carruth9a512a42015-04-15 13:19:54 +0000808 // mid-way through an inner loop or a successor of an unanalyzable branch.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000809 if (MBB != *std::prev(Chain.end()))
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000810 continue;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000811
Chandler Carruth03adbd42011-11-27 13:34:33 +0000812 // Now walk the successors. We need to establish whether this has a viable
813 // exiting successor and whether it has a viable non-exiting successor.
814 // We store the old exiting state and restore it if a viable looping
815 // successor isn't found.
816 MachineBasicBlock *OldExitingBB = ExitingBB;
817 BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
Chandler Carruthccc7e422012-04-16 01:12:56 +0000818 bool HasLoopingSucc = false;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000819 for (MachineBasicBlock *Succ : MBB->successors()) {
Reid Kleckner0e288232015-08-27 23:27:47 +0000820 if (Succ->isEHPad())
Chandler Carruth03adbd42011-11-27 13:34:33 +0000821 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000822 if (Succ == MBB)
Chandler Carruth03adbd42011-11-27 13:34:33 +0000823 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000824 BlockChain &SuccChain = *BlockToChain[Succ];
Chandler Carruth03adbd42011-11-27 13:34:33 +0000825 // Don't split chains, either this chain or the successor's chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000826 if (&Chain == &SuccChain) {
Chandler Carruth7a715da2015-03-05 03:19:05 +0000827 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
828 << getBlockName(Succ) << " (chain conflict)\n");
Chandler Carruth03adbd42011-11-27 13:34:33 +0000829 continue;
830 }
831
Cong Houd97c1002015-12-01 05:29:22 +0000832 auto SuccProb = MBPI->getEdgeProbability(MBB, Succ);
Chandler Carruth7a715da2015-03-05 03:19:05 +0000833 if (LoopBlockSet.count(Succ)) {
834 DEBUG(dbgs() << " looping: " << getBlockName(MBB) << " -> "
Cong Houd97c1002015-12-01 05:29:22 +0000835 << getBlockName(Succ) << " (" << SuccProb << ")\n");
Chandler Carruthccc7e422012-04-16 01:12:56 +0000836 HasLoopingSucc = true;
Chandler Carruth03adbd42011-11-27 13:34:33 +0000837 continue;
838 }
839
Chandler Carruthccc7e422012-04-16 01:12:56 +0000840 unsigned SuccLoopDepth = 0;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000841 if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
Chandler Carruthccc7e422012-04-16 01:12:56 +0000842 SuccLoopDepth = ExitLoop->getLoopDepth();
843 if (ExitLoop->contains(&L))
Chandler Carruth7a715da2015-03-05 03:19:05 +0000844 BlocksExitingToOuterLoop.insert(MBB);
Chandler Carruthccc7e422012-04-16 01:12:56 +0000845 }
846
Chandler Carruth7a715da2015-03-05 03:19:05 +0000847 BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
848 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
849 << getBlockName(Succ) << " [L:" << SuccLoopDepth << "] (";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000850 MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
Benjamin Kramerc8160d62013-11-20 19:08:44 +0000851 // Note that we bias this toward an existing layout successor to retain
852 // incoming order in the absence of better information. The exit must have
853 // a frequency higher than the current exit before we consider breaking
854 // the layout.
855 BranchProbability Bias(100 - ExitBlockBias, 100);
Chandler Carruth26d30172015-04-15 13:39:42 +0000856 if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
Chandler Carruthccc7e422012-04-16 01:12:56 +0000857 ExitEdgeFreq > BestExitEdgeFreq ||
Chandler Carruth7a715da2015-03-05 03:19:05 +0000858 (MBB->isLayoutSuccessor(Succ) &&
Benjamin Kramerc8160d62013-11-20 19:08:44 +0000859 !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
Chandler Carruth03adbd42011-11-27 13:34:33 +0000860 BestExitEdgeFreq = ExitEdgeFreq;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000861 ExitingBB = MBB;
Chandler Carrutha0545802011-11-27 09:22:53 +0000862 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000863 }
Chandler Carruth03adbd42011-11-27 13:34:33 +0000864
Chandler Carruthccc7e422012-04-16 01:12:56 +0000865 if (!HasLoopingSucc) {
Chandler Carruthcfb2b9d2015-04-15 13:26:41 +0000866 // Restore the old exiting state, no viable looping successor was found.
Chandler Carruth03adbd42011-11-27 13:34:33 +0000867 ExitingBB = OldExitingBB;
868 BestExitEdgeFreq = OldBestExitEdgeFreq;
Chandler Carruth03adbd42011-11-27 13:34:33 +0000869 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000870 }
Chandler Carruthccc7e422012-04-16 01:12:56 +0000871 // Without a candidate exiting block or with only a single block in the
Chandler Carruth03adbd42011-11-27 13:34:33 +0000872 // loop, just use the loop header to layout the loop.
873 if (!ExitingBB || L.getNumBlocks() == 1)
Craig Topperc0196b12014-04-14 00:51:57 +0000874 return nullptr;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000875
Chandler Carruth4f567202011-11-27 20:18:00 +0000876 // Also, if we have exit blocks which lead to outer loops but didn't select
877 // one of them as the exiting block we are rotating toward, disable loop
878 // rotation altogether.
879 if (!BlocksExitingToOuterLoop.empty() &&
880 !BlocksExitingToOuterLoop.count(ExitingBB))
Craig Topperc0196b12014-04-14 00:51:57 +0000881 return nullptr;
Chandler Carruth4f567202011-11-27 20:18:00 +0000882
Chandler Carruth03adbd42011-11-27 13:34:33 +0000883 DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB) << "\n");
Chandler Carruthccc7e422012-04-16 01:12:56 +0000884 return ExitingBB;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000885}
886
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000887/// \brief Attempt to rotate an exiting block to the bottom of the loop.
888///
889/// Once we have built a chain, try to rotate it to line up the hot exit block
890/// with fallthrough out of the loop if doing so doesn't introduce unnecessary
891/// branches. For example, if the loop has fallthrough into its header and out
892/// of its bottom already, don't rotate it.
893void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
894 MachineBasicBlock *ExitingBB,
895 const BlockFilterSet &LoopBlockSet) {
896 if (!ExitingBB)
897 return;
898
899 MachineBasicBlock *Top = *LoopChain.begin();
900 bool ViableTopFallthrough = false;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000901 for (MachineBasicBlock *Pred : Top->predecessors()) {
902 BlockChain *PredChain = BlockToChain[Pred];
903 if (!LoopBlockSet.count(Pred) &&
904 (!PredChain || Pred == *std::prev(PredChain->end()))) {
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000905 ViableTopFallthrough = true;
906 break;
907 }
908 }
909
910 // If the header has viable fallthrough, check whether the current loop
911 // bottom is a viable exiting block. If so, bail out as rotating will
912 // introduce an unnecessary branch.
913 if (ViableTopFallthrough) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000914 MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
Chandler Carruth7a715da2015-03-05 03:19:05 +0000915 for (MachineBasicBlock *Succ : Bottom->successors()) {
916 BlockChain *SuccChain = BlockToChain[Succ];
917 if (!LoopBlockSet.count(Succ) &&
918 (!SuccChain || Succ == *SuccChain->begin()))
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000919 return;
920 }
921 }
922
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000923 BlockChain::iterator ExitIt =
924 std::find(LoopChain.begin(), LoopChain.end(), ExitingBB);
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000925 if (ExitIt == LoopChain.end())
926 return;
927
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000928 std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000929}
930
Cong Hou7745dbc2015-10-19 23:16:40 +0000931/// \brief Attempt to rotate a loop based on profile data to reduce branch cost.
932///
933/// With profile data, we can determine the cost in terms of missed fall through
934/// opportunities when rotating a loop chain and select the best rotation.
935/// Basically, there are three kinds of cost to consider for each rotation:
936/// 1. The possibly missed fall through edge (if it exists) from BB out of
937/// the loop to the loop header.
938/// 2. The possibly missed fall through edges (if they exist) from the loop
939/// exits to BB out of the loop.
940/// 3. The missed fall through edge (if it exists) from the last BB to the
941/// first BB in the loop chain.
942/// Therefore, the cost for a given rotation is the sum of costs listed above.
943/// We select the best rotation with the smallest cost.
944void MachineBlockPlacement::rotateLoopWithProfile(
945 BlockChain &LoopChain, MachineLoop &L, const BlockFilterSet &LoopBlockSet) {
946 auto HeaderBB = L.getHeader();
947 auto HeaderIter = std::find(LoopChain.begin(), LoopChain.end(), HeaderBB);
948 auto RotationPos = LoopChain.end();
949
950 BlockFrequency SmallestRotationCost = BlockFrequency::getMaxFrequency();
951
952 // A utility lambda that scales up a block frequency by dividing it by a
953 // branch probability which is the reciprocal of the scale.
954 auto ScaleBlockFrequency = [](BlockFrequency Freq,
955 unsigned Scale) -> BlockFrequency {
956 if (Scale == 0)
957 return 0;
958 // Use operator / between BlockFrequency and BranchProbability to implement
959 // saturating multiplication.
960 return Freq / BranchProbability(1, Scale);
961 };
962
963 // Compute the cost of the missed fall-through edge to the loop header if the
964 // chain head is not the loop header. As we only consider natural loops with
965 // single header, this computation can be done only once.
966 BlockFrequency HeaderFallThroughCost(0);
967 for (auto *Pred : HeaderBB->predecessors()) {
968 BlockChain *PredChain = BlockToChain[Pred];
969 if (!LoopBlockSet.count(Pred) &&
970 (!PredChain || Pred == *std::prev(PredChain->end()))) {
971 auto EdgeFreq =
972 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, HeaderBB);
973 auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost);
974 // If the predecessor has only an unconditional jump to the header, we
975 // need to consider the cost of this jump.
976 if (Pred->succ_size() == 1)
977 FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost);
978 HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost);
979 }
980 }
981
982 // Here we collect all exit blocks in the loop, and for each exit we find out
983 // its hottest exit edge. For each loop rotation, we define the loop exit cost
984 // as the sum of frequencies of exit edges we collect here, excluding the exit
985 // edge from the tail of the loop chain.
986 SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq;
987 for (auto BB : LoopChain) {
Cong Houd97c1002015-12-01 05:29:22 +0000988 auto LargestExitEdgeProb = BranchProbability::getZero();
Cong Hou7745dbc2015-10-19 23:16:40 +0000989 for (auto *Succ : BB->successors()) {
990 BlockChain *SuccChain = BlockToChain[Succ];
991 if (!LoopBlockSet.count(Succ) &&
992 (!SuccChain || Succ == *SuccChain->begin())) {
Cong Houd97c1002015-12-01 05:29:22 +0000993 auto SuccProb = MBPI->getEdgeProbability(BB, Succ);
994 LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb);
Cong Hou7745dbc2015-10-19 23:16:40 +0000995 }
996 }
Cong Houd97c1002015-12-01 05:29:22 +0000997 if (LargestExitEdgeProb > BranchProbability::getZero()) {
998 auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb;
Cong Hou7745dbc2015-10-19 23:16:40 +0000999 ExitsWithFreq.emplace_back(BB, ExitFreq);
1000 }
1001 }
1002
1003 // In this loop we iterate every block in the loop chain and calculate the
1004 // cost assuming the block is the head of the loop chain. When the loop ends,
1005 // we should have found the best candidate as the loop chain's head.
1006 for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()),
1007 EndIter = LoopChain.end();
1008 Iter != EndIter; Iter++, TailIter++) {
1009 // TailIter is used to track the tail of the loop chain if the block we are
1010 // checking (pointed by Iter) is the head of the chain.
1011 if (TailIter == LoopChain.end())
1012 TailIter = LoopChain.begin();
1013
1014 auto TailBB = *TailIter;
1015
1016 // Calculate the cost by putting this BB to the top.
1017 BlockFrequency Cost = 0;
1018
1019 // If the current BB is the loop header, we need to take into account the
1020 // cost of the missed fall through edge from outside of the loop to the
1021 // header.
1022 if (Iter != HeaderIter)
1023 Cost += HeaderFallThroughCost;
1024
1025 // Collect the loop exit cost by summing up frequencies of all exit edges
1026 // except the one from the chain tail.
1027 for (auto &ExitWithFreq : ExitsWithFreq)
1028 if (TailBB != ExitWithFreq.first)
1029 Cost += ExitWithFreq.second;
1030
1031 // The cost of breaking the once fall-through edge from the tail to the top
1032 // of the loop chain. Here we need to consider three cases:
1033 // 1. If the tail node has only one successor, then we will get an
1034 // additional jmp instruction. So the cost here is (MisfetchCost +
1035 // JumpInstCost) * tail node frequency.
1036 // 2. If the tail node has two successors, then we may still get an
1037 // additional jmp instruction if the layout successor after the loop
1038 // chain is not its CFG successor. Note that the more frequently executed
1039 // jmp instruction will be put ahead of the other one. Assume the
1040 // frequency of those two branches are x and y, where x is the frequency
1041 // of the edge to the chain head, then the cost will be
1042 // (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency.
1043 // 3. If the tail node has more than two successors (this rarely happens),
1044 // we won't consider any additional cost.
1045 if (TailBB->isSuccessor(*Iter)) {
1046 auto TailBBFreq = MBFI->getBlockFreq(TailBB);
1047 if (TailBB->succ_size() == 1)
1048 Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(),
1049 MisfetchCost + JumpInstCost);
1050 else if (TailBB->succ_size() == 2) {
1051 auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter);
1052 auto TailToHeadFreq = TailBBFreq * TailToHeadProb;
1053 auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2)
1054 ? TailBBFreq * TailToHeadProb.getCompl()
1055 : TailToHeadFreq;
1056 Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) +
1057 ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost);
1058 }
1059 }
1060
Philip Reamesb9688f42016-03-02 21:45:13 +00001061 DEBUG(dbgs() << "The cost of loop rotation by making " << getBlockName(*Iter)
Cong Hou7745dbc2015-10-19 23:16:40 +00001062 << " to the top: " << Cost.getFrequency() << "\n");
1063
1064 if (Cost < SmallestRotationCost) {
1065 SmallestRotationCost = Cost;
1066 RotationPos = Iter;
1067 }
1068 }
1069
1070 if (RotationPos != LoopChain.end()) {
Philip Reamesb9688f42016-03-02 21:45:13 +00001071 DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos)
Cong Hou7745dbc2015-10-19 23:16:40 +00001072 << " to the top\n");
1073 std::rotate(LoopChain.begin(), RotationPos, LoopChain.end());
1074 }
1075}
1076
Cong Houb90b9e02015-11-02 21:24:00 +00001077/// \brief Collect blocks in the given loop that are to be placed.
1078///
1079/// When profile data is available, exclude cold blocks from the returned set;
1080/// otherwise, collect all blocks in the loop.
1081MachineBlockPlacement::BlockFilterSet
1082MachineBlockPlacement::collectLoopBlockSet(MachineFunction &F, MachineLoop &L) {
1083 BlockFilterSet LoopBlockSet;
1084
1085 // Filter cold blocks off from LoopBlockSet when profile data is available.
1086 // Collect the sum of frequencies of incoming edges to the loop header from
1087 // outside. If we treat the loop as a super block, this is the frequency of
1088 // the loop. Then for each block in the loop, we calculate the ratio between
1089 // its frequency and the frequency of the loop block. When it is too small,
1090 // don't add it to the loop chain. If there are outer loops, then this block
1091 // will be merged into the first outer loop chain for which this block is not
1092 // cold anymore. This needs precise profile data and we only do this when
1093 // profile data is available.
1094 if (F.getFunction()->getEntryCount()) {
1095 BlockFrequency LoopFreq(0);
1096 for (auto LoopPred : L.getHeader()->predecessors())
1097 if (!L.contains(LoopPred))
1098 LoopFreq += MBFI->getBlockFreq(LoopPred) *
1099 MBPI->getEdgeProbability(LoopPred, L.getHeader());
1100
1101 for (MachineBasicBlock *LoopBB : L.getBlocks()) {
1102 auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency();
1103 if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio)
1104 continue;
1105 LoopBlockSet.insert(LoopBB);
1106 }
1107 } else
1108 LoopBlockSet.insert(L.block_begin(), L.block_end());
1109
1110 return LoopBlockSet;
1111}
1112
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001113/// \brief Forms basic block chains from the natural loop structures.
Chandler Carruth10281422011-10-21 06:46:38 +00001114///
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001115/// These chains are designed to preserve the existing *structure* of the code
1116/// as much as possible. We can then stitch the chains together in a way which
1117/// both preserves the topological structure and minimizes taken conditional
1118/// branches.
Chandler Carruth8d150782011-11-13 11:20:44 +00001119void MachineBlockPlacement::buildLoopChains(MachineFunction &F,
Jakub Staszak90616162011-12-21 23:02:08 +00001120 MachineLoop &L) {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001121 // First recurse through any nested loops, building chains for those inner
1122 // loops.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001123 for (MachineLoop *InnerLoop : L)
1124 buildLoopChains(F, *InnerLoop);
Chandler Carruth10281422011-10-21 06:46:38 +00001125
Chandler Carruth8d150782011-11-13 11:20:44 +00001126 SmallVector<MachineBasicBlock *, 16> BlockWorkList;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001127 SmallVector<MachineBasicBlock *, 16> EHPadWorkList;
Cong Houb90b9e02015-11-02 21:24:00 +00001128 BlockFilterSet LoopBlockSet = collectLoopBlockSet(F, L);
Chandler Carruth03adbd42011-11-27 13:34:33 +00001129
Cong Hou7745dbc2015-10-19 23:16:40 +00001130 // Check if we have profile data for this function. If yes, we will rotate
1131 // this loop by modeling costs more precisely which requires the profile data
1132 // for better layout.
1133 bool RotateLoopWithProfile =
Xinliang David Lif0ab6df2016-05-12 02:04:41 +00001134 ForcePreciseRotationCost ||
1135 (PreciseRotationCost && F.getFunction()->getEntryCount());
Cong Hou7745dbc2015-10-19 23:16:40 +00001136
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001137 // First check to see if there is an obviously preferable top block for the
1138 // loop. This will default to the header, but may end up as one of the
1139 // predecessors to the header if there is one which will result in strictly
1140 // fewer branches in the loop body.
Cong Hou7745dbc2015-10-19 23:16:40 +00001141 // When we use profile data to rotate the loop, this is unnecessary.
1142 MachineBasicBlock *LoopTop =
1143 RotateLoopWithProfile ? L.getHeader() : findBestLoopTop(L, LoopBlockSet);
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001144
1145 // If we selected just the header for the loop top, look for a potentially
1146 // profitable exit block in the event that rotating the loop can eliminate
1147 // branches by placing an exit edge at the bottom.
Craig Topperc0196b12014-04-14 00:51:57 +00001148 MachineBasicBlock *ExitingBB = nullptr;
Cong Hou7745dbc2015-10-19 23:16:40 +00001149 if (!RotateLoopWithProfile && LoopTop == L.getHeader())
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001150 ExitingBB = findBestLoopExit(F, L, LoopBlockSet);
1151
1152 BlockChain &LoopChain = *BlockToChain[LoopTop];
Chandler Carruth10281422011-10-21 06:46:38 +00001153
Chandler Carruth8d150782011-11-13 11:20:44 +00001154 // FIXME: This is a really lame way of walking the chains in the loop: we
1155 // walk the blocks, and use a set to prevent visiting a particular chain
1156 // twice.
Jakub Staszak90616162011-12-21 23:02:08 +00001157 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
Philip Reamesae27b232016-03-03 00:58:43 +00001158 assert(LoopChain.UnscheduledPredecessors == 0);
Jakub Staszak190c7122011-12-07 19:46:10 +00001159 UpdatedPreds.insert(&LoopChain);
Cong Houb90b9e02015-11-02 21:24:00 +00001160
Amaury Secheteae09c22016-03-14 21:24:11 +00001161 for (MachineBasicBlock *LoopBB : LoopBlockSet)
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001162 fillWorkLists(LoopBB, UpdatedPreds, BlockWorkList, EHPadWorkList,
1163 &LoopBlockSet);
Chandler Carruth8d150782011-11-13 11:20:44 +00001164
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001165 buildChain(LoopTop, LoopChain, BlockWorkList, EHPadWorkList, &LoopBlockSet);
Cong Hou7745dbc2015-10-19 23:16:40 +00001166
1167 if (RotateLoopWithProfile)
1168 rotateLoopWithProfile(LoopChain, L, LoopBlockSet);
1169 else
1170 rotateLoop(LoopChain, ExitingBB, LoopBlockSet);
Chandler Carruth8d150782011-11-13 11:20:44 +00001171
1172 DEBUG({
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001173 // Crash at the end so we get all of the debugging output first.
1174 bool BadLoop = false;
Philip Reamesae27b232016-03-03 00:58:43 +00001175 if (LoopChain.UnscheduledPredecessors) {
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001176 BadLoop = true;
Chandler Carruth8d150782011-11-13 11:20:44 +00001177 dbgs() << "Loop chain contains a block without its preds placed!\n"
1178 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
1179 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001180 }
Chandler Carruth7a715da2015-03-05 03:19:05 +00001181 for (MachineBasicBlock *ChainBB : LoopChain) {
1182 dbgs() << " ... " << getBlockName(ChainBB) << "\n";
1183 if (!LoopBlockSet.erase(ChainBB)) {
Chandler Carruth0a31d142011-11-14 10:55:53 +00001184 // We don't mark the loop as bad here because there are real situations
1185 // where this can occur. For example, with an unanalyzable fallthrough
Chandler Carruth99fe42f2011-11-23 10:35:36 +00001186 // from a loop block to a non-loop block or vice versa.
Chandler Carruth8d150782011-11-13 11:20:44 +00001187 dbgs() << "Loop chain contains a block not contained by the loop!\n"
1188 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
1189 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00001190 << " Bad block: " << getBlockName(ChainBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001191 }
Chandler Carruthccc7e422012-04-16 01:12:56 +00001192 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001193
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001194 if (!LoopBlockSet.empty()) {
1195 BadLoop = true;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001196 for (MachineBasicBlock *LoopBB : LoopBlockSet)
Chandler Carruth8d150782011-11-13 11:20:44 +00001197 dbgs() << "Loop contains blocks never placed into a chain!\n"
1198 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
1199 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00001200 << " Bad block: " << getBlockName(LoopBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001201 }
1202 assert(!BadLoop && "Detected problems with the placement of this loop.");
Chandler Carruth8d150782011-11-13 11:20:44 +00001203 });
Chandler Carruth10281422011-10-21 06:46:38 +00001204}
1205
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001206void MachineBlockPlacement::buildCFGChains(MachineFunction &F) {
Chandler Carruth8d150782011-11-13 11:20:44 +00001207 // Ensure that every BB in the function has an associated chain to simplify
1208 // the assumptions of the remaining algorithm.
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001209 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
1210 for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001211 MachineBasicBlock *BB = &*FI;
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001212 BlockChain *Chain =
1213 new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001214 // Also, merge any blocks which we cannot reason about and must preserve
1215 // the exact fallthrough behavior for.
1216 for (;;) {
1217 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001218 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001219 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
1220 break;
1221
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001222 MachineFunction::iterator NextFI = std::next(FI);
1223 MachineBasicBlock *NextBB = &*NextFI;
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001224 // Ensure that the layout successor is a viable block, as we know that
1225 // fallthrough is a possibility.
1226 assert(NextFI != FE && "Can't fallthrough past the last block.");
1227 DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
1228 << getBlockName(BB) << " -> " << getBlockName(NextBB)
1229 << "\n");
Craig Topperc0196b12014-04-14 00:51:57 +00001230 Chain->merge(NextBB, nullptr);
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001231 FI = NextFI;
1232 BB = NextBB;
1233 }
1234 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001235
Daniel Jasper471e8562015-03-04 11:05:34 +00001236 if (OutlineOptionalBranches) {
1237 // Find the nearest common dominator of all of F's terminators.
1238 MachineBasicBlock *Terminator = nullptr;
1239 for (MachineBasicBlock &MBB : F) {
1240 if (MBB.succ_size() == 0) {
1241 if (Terminator == nullptr)
1242 Terminator = &MBB;
1243 else
1244 Terminator = MDT->findNearestCommonDominator(Terminator, &MBB);
1245 }
1246 }
1247
1248 // MBBs dominating this common dominator are unavoidable.
1249 UnavoidableBlocks.clear();
1250 for (MachineBasicBlock &MBB : F) {
1251 if (MDT->dominates(&MBB, Terminator)) {
1252 UnavoidableBlocks.insert(&MBB);
1253 }
1254 }
1255 }
1256
Chandler Carruth8d150782011-11-13 11:20:44 +00001257 // Build any loop-based chains.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001258 for (MachineLoop *L : *MLI)
1259 buildLoopChains(F, *L);
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001260
Chandler Carruth8d150782011-11-13 11:20:44 +00001261 SmallVector<MachineBasicBlock *, 16> BlockWorkList;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001262 SmallVector<MachineBasicBlock *, 16> EHPadWorkList;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001263
Chandler Carruth8d150782011-11-13 11:20:44 +00001264 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
Amaury Secheteae09c22016-03-14 21:24:11 +00001265 for (MachineBasicBlock &MBB : F)
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001266 fillWorkLists(&MBB, UpdatedPreds, BlockWorkList, EHPadWorkList);
Chandler Carruth8d150782011-11-13 11:20:44 +00001267
1268 BlockChain &FunctionChain = *BlockToChain[&F.front()];
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001269 buildChain(&F.front(), FunctionChain, BlockWorkList, EHPadWorkList);
Chandler Carruth8d150782011-11-13 11:20:44 +00001270
Matt Arsenault0f5f0152013-12-10 18:55:37 +00001271#ifndef NDEBUG
Matt Arsenault79d55f52013-12-05 20:02:18 +00001272 typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType;
Matt Arsenault0f5f0152013-12-10 18:55:37 +00001273#endif
Chandler Carruth8d150782011-11-13 11:20:44 +00001274 DEBUG({
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001275 // Crash at the end so we get all of the debugging output first.
1276 bool BadFunc = false;
Chandler Carruth8d150782011-11-13 11:20:44 +00001277 FunctionBlockSetType FunctionBlockSet;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001278 for (MachineBasicBlock &MBB : F)
1279 FunctionBlockSet.insert(&MBB);
Chandler Carruth8d150782011-11-13 11:20:44 +00001280
Chandler Carruth7a715da2015-03-05 03:19:05 +00001281 for (MachineBasicBlock *ChainBB : FunctionChain)
1282 if (!FunctionBlockSet.erase(ChainBB)) {
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001283 BadFunc = true;
Chandler Carruth8d150782011-11-13 11:20:44 +00001284 dbgs() << "Function chain contains a block not in the function!\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00001285 << " Bad block: " << getBlockName(ChainBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001286 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001287
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001288 if (!FunctionBlockSet.empty()) {
1289 BadFunc = true;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001290 for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
Chandler Carruth8d150782011-11-13 11:20:44 +00001291 dbgs() << "Function contains blocks never placed into a chain!\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00001292 << " Bad block: " << getBlockName(RemainingBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001293 }
1294 assert(!BadFunc && "Detected problems with the block placement.");
Chandler Carruth8d150782011-11-13 11:20:44 +00001295 });
1296
1297 // Splice the blocks into place.
1298 MachineFunction::iterator InsertPos = F.begin();
Chandler Carruth7a715da2015-03-05 03:19:05 +00001299 for (MachineBasicBlock *ChainBB : FunctionChain) {
1300 DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
1301 : " ... ")
1302 << getBlockName(ChainBB) << "\n");
1303 if (InsertPos != MachineFunction::iterator(ChainBB))
1304 F.splice(InsertPos, ChainBB);
Chandler Carruth8d150782011-11-13 11:20:44 +00001305 else
1306 ++InsertPos;
1307
1308 // Update the terminator of the previous block.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001309 if (ChainBB == *FunctionChain.begin())
Chandler Carruth8d150782011-11-13 11:20:44 +00001310 continue;
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001311 MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB));
Chandler Carruth8d150782011-11-13 11:20:44 +00001312
Chandler Carruth10281422011-10-21 06:46:38 +00001313 // FIXME: It would be awesome of updateTerminator would just return rather
1314 // than assert when the branch cannot be analyzed in order to remove this
1315 // boiler plate.
1316 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001317 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Manman Ren2b6a0df2012-07-31 01:11:07 +00001318 if (!TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001319 // The "PrevBB" is not yet updated to reflect current code layout, so,
1320 // o. it may fall-through to a block without explict "goto" instruction
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001321 // before layout, and no longer fall-through it after layout; or
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001322 // o. just opposite.
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001323 //
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001324 // AnalyzeBranch() may return erroneous value for FBB when these two
1325 // situations take place. For the first scenario FBB is mistakenly set
1326 // NULL; for the 2nd scenario, the FBB, which is expected to be NULL,
1327 // is mistakenly pointing to "*BI".
1328 //
1329 bool needUpdateBr = true;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001330 if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001331 PrevBB->updateTerminator();
1332 needUpdateBr = false;
1333 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001334 TBB = FBB = nullptr;
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001335 if (TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
1336 // FIXME: This should never take place.
Craig Topperc0196b12014-04-14 00:51:57 +00001337 TBB = FBB = nullptr;
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001338 }
1339 }
1340
Manman Ren2b6a0df2012-07-31 01:11:07 +00001341 // If PrevBB has a two-way branch, try to re-order the branches
Cong Houd97c1002015-12-01 05:29:22 +00001342 // such that we branch to the successor with higher probability first.
Manman Ren2b6a0df2012-07-31 01:11:07 +00001343 if (TBB && !Cond.empty() && FBB &&
Cong Houd97c1002015-12-01 05:29:22 +00001344 MBPI->getEdgeProbability(PrevBB, FBB) >
1345 MBPI->getEdgeProbability(PrevBB, TBB) &&
Manman Ren2b6a0df2012-07-31 01:11:07 +00001346 !TII->ReverseBranchCondition(Cond)) {
1347 DEBUG(dbgs() << "Reverse order of the two branches: "
1348 << getBlockName(PrevBB) << "\n");
Cong Houd97c1002015-12-01 05:29:22 +00001349 DEBUG(dbgs() << " Edge probability: "
1350 << MBPI->getEdgeProbability(PrevBB, FBB) << " vs "
1351 << MBPI->getEdgeProbability(PrevBB, TBB) << "\n");
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001352 DebugLoc dl; // FIXME: this is nowhere
Manman Ren2b6a0df2012-07-31 01:11:07 +00001353 TII->RemoveBranch(*PrevBB);
1354 TII->InsertBranch(*PrevBB, FBB, TBB, Cond, dl);
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001355 needUpdateBr = true;
Manman Ren2b6a0df2012-07-31 01:11:07 +00001356 }
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001357 if (needUpdateBr)
1358 PrevBB->updateTerminator();
Manman Ren2b6a0df2012-07-31 01:11:07 +00001359 }
Chandler Carruth10281422011-10-21 06:46:38 +00001360 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001361
1362 // Fixup the last block.
1363 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001364 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Chandler Carruth8d150782011-11-13 11:20:44 +00001365 if (!TII->AnalyzeBranch(F.back(), TBB, FBB, Cond))
1366 F.back().updateTerminator();
Quentin Colombet776e6de2016-05-02 22:58:59 +00001367
1368 // Now that all the basic blocks in the chain have the proper layout,
1369 // make a final call to AnalyzeBranch with AllowModify set.
1370 // Indeed, the target may be able to optimize the branches in a way we
1371 // cannot because all branches may not be analyzable.
1372 // E.g., the target may be able to remove an unconditional branch to
1373 // a fallthrough when it occurs after predicated terminators.
1374 for (MachineBasicBlock *ChainBB : FunctionChain) {
1375 Cond.clear();
1376 TBB = nullptr;
1377 FBB = nullptr; // For AnalyzeBranch.
1378 (void)TII->AnalyzeBranch(*ChainBB, TBB, FBB, Cond, /*AllowModify*/ true);
1379 }
Haicheng Wue749ce52016-04-29 17:06:44 +00001380}
Chandler Carruth10281422011-10-21 06:46:38 +00001381
Haicheng Wue749ce52016-04-29 17:06:44 +00001382void MachineBlockPlacement::alignBlocks(MachineFunction &F) {
Chandler Carruthccc7e422012-04-16 01:12:56 +00001383 // Walk through the backedges of the function now that we have fully laid out
1384 // the basic blocks and align the destination of each backedge. We don't rely
Chandler Carruth881d0a72012-08-07 09:45:24 +00001385 // exclusively on the loop info here so that we can align backedges in
1386 // unnatural CFGs and backedges that were introduced purely because of the
1387 // loop rotations done during this layout pass.
Haicheng Wu4afe0422016-04-29 22:01:10 +00001388 if (F.getFunction()->optForSize())
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001389 return;
Haicheng Wue749ce52016-04-29 17:06:44 +00001390 BlockChain &FunctionChain = *BlockToChain[&F.front()];
Chandler Carruth881d0a72012-08-07 09:45:24 +00001391 if (FunctionChain.begin() == FunctionChain.end())
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001392 return; // Empty chain.
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001393
Chandler Carruth881d0a72012-08-07 09:45:24 +00001394 const BranchProbability ColdProb(1, 5); // 20%
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001395 BlockFrequency EntryFreq = MBFI->getBlockFreq(&F.front());
Chandler Carruth881d0a72012-08-07 09:45:24 +00001396 BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001397 for (MachineBasicBlock *ChainBB : FunctionChain) {
1398 if (ChainBB == *FunctionChain.begin())
1399 continue;
1400
Chandler Carruth881d0a72012-08-07 09:45:24 +00001401 // Don't align non-looping basic blocks. These are unlikely to execute
1402 // enough times to matter in practice. Note that we'll still handle
1403 // unnatural CFGs inside of a natural outer loop (the common case) and
1404 // rotated loops.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001405 MachineLoop *L = MLI->getLoopFor(ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001406 if (!L)
1407 continue;
1408
Hal Finkel57725662015-01-03 17:58:24 +00001409 unsigned Align = TLI->getPrefLoopAlignment(L);
1410 if (!Align)
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001411 continue; // Don't care about loop alignment.
Hal Finkel57725662015-01-03 17:58:24 +00001412
Chandler Carruth881d0a72012-08-07 09:45:24 +00001413 // If the block is cold relative to the function entry don't waste space
1414 // aligning it.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001415 BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001416 if (Freq < WeightedEntryFreq)
1417 continue;
1418
1419 // If the block is cold relative to its loop header, don't align it
1420 // regardless of what edges into the block exist.
1421 MachineBasicBlock *LoopHeader = L->getHeader();
1422 BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
1423 if (Freq < (LoopHeaderFreq * ColdProb))
1424 continue;
1425
1426 // Check for the existence of a non-layout predecessor which would benefit
1427 // from aligning this block.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001428 MachineBasicBlock *LayoutPred =
1429 &*std::prev(MachineFunction::iterator(ChainBB));
Chandler Carruth881d0a72012-08-07 09:45:24 +00001430
1431 // Force alignment if all the predecessors are jumps. We already checked
1432 // that the block isn't cold above.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001433 if (!LayoutPred->isSuccessor(ChainBB)) {
1434 ChainBB->setAlignment(Align);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001435 continue;
1436 }
1437
1438 // Align this block if the layout predecessor's edge into this block is
Nadav Rotem6036f582013-03-29 16:34:23 +00001439 // cold relative to the block. When this is true, other predecessors make up
Chandler Carruth881d0a72012-08-07 09:45:24 +00001440 // all of the hot entries into the block and thus alignment is likely to be
1441 // important.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001442 BranchProbability LayoutProb =
1443 MBPI->getEdgeProbability(LayoutPred, ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001444 BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
1445 if (LayoutEdgeFreq <= (Freq * ColdProb))
Chandler Carruth7a715da2015-03-05 03:19:05 +00001446 ChainBB->setAlignment(Align);
Chandler Carruthccc7e422012-04-16 01:12:56 +00001447 }
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001448}
1449
Chandler Carruth10281422011-10-21 06:46:38 +00001450bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &F) {
Andrew Kaylor50271f72016-05-03 22:32:30 +00001451 if (skipFunction(*F.getFunction()))
1452 return false;
1453
Chandler Carruth10281422011-10-21 06:46:38 +00001454 // Check for single-block functions and skip them.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001455 if (std::next(F.begin()) == F.end())
Chandler Carruth10281422011-10-21 06:46:38 +00001456 return false;
1457
Andrew Kayloraa641a52016-04-22 22:06:11 +00001458 if (skipFunction(*F.getFunction()))
Paul Robinson7c99ec52014-03-31 17:43:35 +00001459 return false;
1460
Chandler Carruth10281422011-10-21 06:46:38 +00001461 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1462 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001463 MLI = &getAnalysis<MachineLoopInfo>();
Eric Christopherfc6de422014-08-05 02:39:49 +00001464 TII = F.getSubtarget().getInstrInfo();
1465 TLI = F.getSubtarget().getTargetLowering();
Daniel Jasper471e8562015-03-04 11:05:34 +00001466 MDT = &getAnalysis<MachineDominatorTree>();
Chandler Carruth10281422011-10-21 06:46:38 +00001467 assert(BlockToChain.empty());
Chandler Carruth10281422011-10-21 06:46:38 +00001468
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001469 buildCFGChains(F);
Haicheng Wue749ce52016-04-29 17:06:44 +00001470 alignBlocks(F);
Chandler Carruth10281422011-10-21 06:46:38 +00001471
Chandler Carruth10281422011-10-21 06:46:38 +00001472 BlockToChain.clear();
Chandler Carruthfd9b4d92011-11-14 10:57:23 +00001473 ChainAllocator.DestroyAll();
Chandler Carruth10281422011-10-21 06:46:38 +00001474
Nadav Rotemc0adc9f2013-04-12 01:24:16 +00001475 if (AlignAllBlock)
1476 // Align all of the blocks in the function to a specific alignment.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001477 for (MachineBasicBlock &MBB : F)
1478 MBB.setAlignment(AlignAllBlock);
Geoff Berry10494ac2016-01-21 17:25:52 +00001479 else if (AlignAllNonFallThruBlocks) {
1480 // Align all of the blocks that have no fall-through predecessors to a
1481 // specific alignment.
1482 for (auto MBI = std::next(F.begin()), MBE = F.end(); MBI != MBE; ++MBI) {
1483 auto LayoutPred = std::prev(MBI);
1484 if (!LayoutPred->isSuccessor(&*MBI))
1485 MBI->setAlignment(AlignAllNonFallThruBlocks);
1486 }
1487 }
Nadav Rotemc0adc9f2013-04-12 01:24:16 +00001488
Chandler Carruth10281422011-10-21 06:46:38 +00001489 // We always return true as we have no way to track whether the final order
1490 // differs from the original order.
1491 return true;
1492}
Chandler Carruthae4e8002011-11-02 07:17:12 +00001493
1494namespace {
1495/// \brief A pass to compute block placement statistics.
1496///
1497/// A separate pass to compute interesting statistics for evaluating block
1498/// placement. This is separate from the actual placement pass so that they can
Benjamin Kramerbde91762012-06-02 10:20:22 +00001499/// be computed in the absence of any placement transformations or when using
Chandler Carruthae4e8002011-11-02 07:17:12 +00001500/// alternative placement strategies.
1501class MachineBlockPlacementStats : public MachineFunctionPass {
1502 /// \brief A handle to the branch probability pass.
1503 const MachineBranchProbabilityInfo *MBPI;
1504
1505 /// \brief A handle to the function-wide block frequency pass.
1506 const MachineBlockFrequencyInfo *MBFI;
1507
1508public:
1509 static char ID; // Pass identification, replacement for typeid
1510 MachineBlockPlacementStats() : MachineFunctionPass(ID) {
1511 initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
1512 }
1513
Craig Topper4584cd52014-03-07 09:26:03 +00001514 bool runOnMachineFunction(MachineFunction &F) override;
Chandler Carruthae4e8002011-11-02 07:17:12 +00001515
Craig Topper4584cd52014-03-07 09:26:03 +00001516 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruthae4e8002011-11-02 07:17:12 +00001517 AU.addRequired<MachineBranchProbabilityInfo>();
1518 AU.addRequired<MachineBlockFrequencyInfo>();
1519 AU.setPreservesAll();
1520 MachineFunctionPass::getAnalysisUsage(AU);
1521 }
Chandler Carruthae4e8002011-11-02 07:17:12 +00001522};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001523}
Chandler Carruthae4e8002011-11-02 07:17:12 +00001524
1525char MachineBlockPlacementStats::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +00001526char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
Chandler Carruthae4e8002011-11-02 07:17:12 +00001527INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
1528 "Basic Block Placement Stats", false, false)
1529INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
1530INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
1531INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
1532 "Basic Block Placement Stats", false, false)
1533
Chandler Carruthae4e8002011-11-02 07:17:12 +00001534bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
1535 // Check for single-block functions and skip them.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001536 if (std::next(F.begin()) == F.end())
Chandler Carruthae4e8002011-11-02 07:17:12 +00001537 return false;
1538
1539 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1540 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1541
Chandler Carruth7a715da2015-03-05 03:19:05 +00001542 for (MachineBasicBlock &MBB : F) {
1543 BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001544 Statistic &NumBranches =
Chandler Carruth7a715da2015-03-05 03:19:05 +00001545 (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001546 Statistic &BranchTakenFreq =
Chandler Carruth7a715da2015-03-05 03:19:05 +00001547 (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
1548 for (MachineBasicBlock *Succ : MBB.successors()) {
Chandler Carruthae4e8002011-11-02 07:17:12 +00001549 // Skip if this successor is a fallthrough.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001550 if (MBB.isLayoutSuccessor(Succ))
Chandler Carruthae4e8002011-11-02 07:17:12 +00001551 continue;
1552
Chandler Carruth7a715da2015-03-05 03:19:05 +00001553 BlockFrequency EdgeFreq =
1554 BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
Chandler Carruthae4e8002011-11-02 07:17:12 +00001555 ++NumBranches;
1556 BranchTakenFreq += EdgeFreq.getFrequency();
1557 }
1558 }
1559
1560 return false;
1561}