blob: 69c0a53fc92733071b3876353cb2febc69c571d9 [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);
102
103static cl::opt<unsigned> MisfetchCost(
104 "misfetch-cost",
105 cl::desc("Cost that models the probablistic risk of an instruction "
106 "misfetch due to a jump comparing to falling through, whose cost "
107 "is zero."),
108 cl::init(1), cl::Hidden);
109
110static cl::opt<unsigned> JumpInstCost("jump-inst-cost",
111 cl::desc("Cost of jump instructions."),
112 cl::init(1), cl::Hidden);
113
Chandler Carruth10281422011-10-21 06:46:38 +0000114namespace {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000115class BlockChain;
Chandler Carruth10281422011-10-21 06:46:38 +0000116/// \brief Type for our function-wide basic block -> block chain mapping.
117typedef DenseMap<MachineBasicBlock *, BlockChain *> BlockToChainMapType;
118}
119
120namespace {
121/// \brief A chain of blocks which will be laid out contiguously.
122///
123/// This is the datastructure representing a chain of consecutive blocks that
124/// are profitable to layout together in order to maximize fallthrough
Chandler Carruth9139f442012-06-26 05:16:37 +0000125/// probabilities and code locality. We also can use a block chain to represent
126/// a sequence of basic blocks which have some external (correctness)
127/// requirement for sequential layout.
Chandler Carruth10281422011-10-21 06:46:38 +0000128///
Chandler Carruth9139f442012-06-26 05:16:37 +0000129/// Chains can be built around a single basic block and can be merged to grow
130/// them. They participate in a block-to-chain mapping, which is updated
131/// automatically as chains are merged together.
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000132class BlockChain {
133 /// \brief The sequence of blocks belonging to this chain.
Chandler Carruth10281422011-10-21 06:46:38 +0000134 ///
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000135 /// This is the sequence of blocks for a particular chain. These will be laid
136 /// out in-order within the function.
137 SmallVector<MachineBasicBlock *, 4> Blocks;
Chandler Carruth10281422011-10-21 06:46:38 +0000138
139 /// \brief A handle to the function-wide basic block to block chain mapping.
140 ///
141 /// This is retained in each block chain to simplify the computation of child
142 /// block chains for SCC-formation and iteration. We store the edges to child
143 /// basic blocks, and map them back to their associated chains using this
144 /// structure.
145 BlockToChainMapType &BlockToChain;
146
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000147public:
Chandler Carruth10281422011-10-21 06:46:38 +0000148 /// \brief Construct a new BlockChain.
149 ///
150 /// This builds a new block chain representing a single basic block in the
151 /// function. It also registers itself as the chain that block participates
152 /// in with the BlockToChain mapping.
153 BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
Philip Reamesae27b232016-03-03 00:58:43 +0000154 : Blocks(1, BB), BlockToChain(BlockToChain), UnscheduledPredecessors(0) {
Chandler Carruth10281422011-10-21 06:46:38 +0000155 assert(BB && "Cannot create a chain with a null basic block");
156 BlockToChain[BB] = this;
157 }
158
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000159 /// \brief Iterator over blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000160 typedef SmallVectorImpl<MachineBasicBlock *>::iterator iterator;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000161
162 /// \brief Beginning of blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000163 iterator begin() { return Blocks.begin(); }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000164
165 /// \brief End of blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000166 iterator end() { return Blocks.end(); }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000167
168 /// \brief Merge a block chain into this one.
Chandler Carruth10281422011-10-21 06:46:38 +0000169 ///
170 /// This routine merges a block chain into this one. It takes care of forming
171 /// a contiguous sequence of basic blocks, updating the edge list, and
172 /// updating the block -> chain mapping. It does not free or tear down the
173 /// old chain, but the old chain's block list is no longer valid.
Jakub Staszak90616162011-12-21 23:02:08 +0000174 void merge(MachineBasicBlock *BB, BlockChain *Chain) {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000175 assert(BB);
176 assert(!Blocks.empty());
Chandler Carruth10281422011-10-21 06:46:38 +0000177
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000178 // Fast path in case we don't have a chain already.
179 if (!Chain) {
180 assert(!BlockToChain[BB]);
181 Blocks.push_back(BB);
182 BlockToChain[BB] = this;
183 return;
Chandler Carruth10281422011-10-21 06:46:38 +0000184 }
185
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000186 assert(BB == *Chain->begin());
187 assert(Chain->begin() != Chain->end());
Chandler Carruth10281422011-10-21 06:46:38 +0000188
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000189 // Update the incoming blocks to point to this chain, and add them to the
190 // chain structure.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000191 for (MachineBasicBlock *ChainBB : *Chain) {
192 Blocks.push_back(ChainBB);
193 assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain");
194 BlockToChain[ChainBB] = this;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000195 }
Chandler Carruth10281422011-10-21 06:46:38 +0000196 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000197
Chandler Carruth49158902012-04-08 14:37:01 +0000198#ifndef NDEBUG
199 /// \brief Dump the blocks in this chain.
Nico Weber7408c702014-01-03 22:53:37 +0000200 LLVM_DUMP_METHOD void dump() {
Chandler Carruth7a715da2015-03-05 03:19:05 +0000201 for (MachineBasicBlock *MBB : *this)
202 MBB->dump();
Chandler Carruth49158902012-04-08 14:37:01 +0000203 }
204#endif // NDEBUG
205
Philip Reamesae27b232016-03-03 00:58:43 +0000206 /// \brief Count of predecessors of any block within the chain which have not
207 /// yet been scheduled. In general, we will delay scheduling this chain
208 /// until those predecessors are scheduled (or we find a sufficiently good
209 /// reason to override this heuristic.) Note that when forming loop chains,
210 /// blocks outside the loop are ignored and treated as if they were already
211 /// scheduled.
Chandler Carruth8d150782011-11-13 11:20:44 +0000212 ///
Philip Reamesae27b232016-03-03 00:58:43 +0000213 /// Note: This field is reinitialized multiple times - once for each loop,
214 /// and then once for the function as a whole.
215 unsigned UnscheduledPredecessors;
Chandler Carruth10281422011-10-21 06:46:38 +0000216};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000217}
Chandler Carruth10281422011-10-21 06:46:38 +0000218
219namespace {
220class MachineBlockPlacement : public MachineFunctionPass {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000221 /// \brief A typedef for a block filter set.
222 typedef SmallPtrSet<MachineBasicBlock *, 16> BlockFilterSet;
223
Chandler Carruth10281422011-10-21 06:46:38 +0000224 /// \brief A handle to the branch probability pass.
225 const MachineBranchProbabilityInfo *MBPI;
226
227 /// \brief A handle to the function-wide block frequency pass.
228 const MachineBlockFrequencyInfo *MBFI;
229
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000230 /// \brief A handle to the loop info.
231 const MachineLoopInfo *MLI;
232
Chandler Carruth10281422011-10-21 06:46:38 +0000233 /// \brief A handle to the target's instruction info.
234 const TargetInstrInfo *TII;
235
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000236 /// \brief A handle to the target's lowering info.
Benjamin Kramer56b31bd2013-01-11 20:05:37 +0000237 const TargetLoweringBase *TLI;
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000238
Daniel Jasper471e8562015-03-04 11:05:34 +0000239 /// \brief A handle to the post dominator tree.
240 MachineDominatorTree *MDT;
241
242 /// \brief A set of blocks that are unavoidably execute, i.e. they dominate
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000243 /// all terminators of the MachineFunction.
Daniel Jasper471e8562015-03-04 11:05:34 +0000244 SmallPtrSet<MachineBasicBlock *, 4> UnavoidableBlocks;
245
Chandler Carruth10281422011-10-21 06:46:38 +0000246 /// \brief Allocator and owner of BlockChain structures.
247 ///
Chandler Carruth9139f442012-06-26 05:16:37 +0000248 /// We build BlockChains lazily while processing the loop structure of
249 /// a function. To reduce malloc traffic, we allocate them using this
250 /// slab-like allocator, and destroy them after the pass completes. An
251 /// important guarantee is that this allocator produces stable pointers to
252 /// the chains.
Chandler Carruth10281422011-10-21 06:46:38 +0000253 SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
254
255 /// \brief Function wide BasicBlock to BlockChain mapping.
256 ///
257 /// This mapping allows efficiently moving from any given basic block to the
258 /// BlockChain it participates in, if any. We use it to, among other things,
259 /// allow implicitly defining edges between chains as the existing edges
260 /// between basic blocks.
261 DenseMap<MachineBasicBlock *, BlockChain *> BlockToChain;
262
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000263 void markChainSuccessors(BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000264 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
Craig Topperc0196b12014-04-14 00:51:57 +0000265 const BlockFilterSet *BlockFilter = nullptr);
Jakub Staszak90616162011-12-21 23:02:08 +0000266 MachineBasicBlock *selectBestSuccessor(MachineBasicBlock *BB,
267 BlockChain &Chain,
268 const BlockFilterSet *BlockFilter);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000269 MachineBasicBlock *
270 selectBestCandidateBlock(BlockChain &Chain,
Haicheng Wu1951cf22016-04-06 20:38:20 +0000271 SmallVectorImpl<MachineBasicBlock *> &WorkList);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000272 MachineBasicBlock *
273 getFirstUnplacedBlock(MachineFunction &F, const BlockChain &PlacedChain,
274 MachineFunction::iterator &PrevUnplacedBlockIt,
275 const BlockFilterSet *BlockFilter);
Amaury Secheteae09c22016-03-14 21:24:11 +0000276
277 /// \brief Add a basic block to the work list if it is apropriate.
278 ///
279 /// If the optional parameter BlockFilter is provided, only MBB
280 /// present in the set will be added to the worklist. If nullptr
281 /// is provided, no filtering occurs.
282 void fillWorkLists(MachineBasicBlock *MBB,
283 SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
284 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
285 const BlockFilterSet *BlockFilter);
Chandler Carruth8d150782011-11-13 11:20:44 +0000286 void buildChain(MachineBasicBlock *BB, BlockChain &Chain,
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000287 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
Craig Topperc0196b12014-04-14 00:51:57 +0000288 const BlockFilterSet *BlockFilter = nullptr);
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000289 MachineBasicBlock *findBestLoopTop(MachineLoop &L,
290 const BlockFilterSet &LoopBlockSet);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000291 MachineBasicBlock *findBestLoopExit(MachineFunction &F, MachineLoop &L,
Chandler Carruthccc7e422012-04-16 01:12:56 +0000292 const BlockFilterSet &LoopBlockSet);
Cong Houb90b9e02015-11-02 21:24:00 +0000293 BlockFilterSet collectLoopBlockSet(MachineFunction &F, MachineLoop &L);
Jakub Staszak90616162011-12-21 23:02:08 +0000294 void buildLoopChains(MachineFunction &F, MachineLoop &L);
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000295 void rotateLoop(BlockChain &LoopChain, MachineBasicBlock *ExitingBB,
296 const BlockFilterSet &LoopBlockSet);
Cong Hou7745dbc2015-10-19 23:16:40 +0000297 void rotateLoopWithProfile(BlockChain &LoopChain, MachineLoop &L,
298 const BlockFilterSet &LoopBlockSet);
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000299 void buildCFGChains(MachineFunction &F);
Chandler Carruth10281422011-10-21 06:46:38 +0000300
301public:
302 static char ID; // Pass identification, replacement for typeid
303 MachineBlockPlacement() : MachineFunctionPass(ID) {
304 initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
305 }
306
Craig Topper4584cd52014-03-07 09:26:03 +0000307 bool runOnMachineFunction(MachineFunction &F) override;
Chandler Carruth10281422011-10-21 06:46:38 +0000308
Craig Topper4584cd52014-03-07 09:26:03 +0000309 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth10281422011-10-21 06:46:38 +0000310 AU.addRequired<MachineBranchProbabilityInfo>();
311 AU.addRequired<MachineBlockFrequencyInfo>();
Daniel Jasper471e8562015-03-04 11:05:34 +0000312 AU.addRequired<MachineDominatorTree>();
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000313 AU.addRequired<MachineLoopInfo>();
Chandler Carruth10281422011-10-21 06:46:38 +0000314 MachineFunctionPass::getAnalysisUsage(AU);
315 }
Chandler Carruth10281422011-10-21 06:46:38 +0000316};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000317}
Chandler Carruth10281422011-10-21 06:46:38 +0000318
319char MachineBlockPlacement::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000320char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
Chandler Carruthd0dced52015-03-05 02:28:25 +0000321INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement",
Chandler Carruth10281422011-10-21 06:46:38 +0000322 "Branch Probability Basic Block Placement", false, false)
323INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
324INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
Daniel Jasper471e8562015-03-04 11:05:34 +0000325INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000326INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
Chandler Carruthd0dced52015-03-05 02:28:25 +0000327INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement",
Chandler Carruth10281422011-10-21 06:46:38 +0000328 "Branch Probability Basic Block Placement", false, false)
329
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000330#ifndef NDEBUG
331/// \brief Helper to print the name of a MBB.
332///
333/// Only used by debug logging.
Jakub Staszak90616162011-12-21 23:02:08 +0000334static std::string getBlockName(MachineBasicBlock *BB) {
Alp Tokere69170a2014-06-26 22:52:05 +0000335 std::string Result;
336 raw_string_ostream OS(Result);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000337 OS << "BB#" << BB->getNumber();
Philip Reamesb9688f42016-03-02 21:45:13 +0000338 OS << " ('" << BB->getName() << "')";
Alp Tokere69170a2014-06-26 22:52:05 +0000339 OS.flush();
340 return Result;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000341}
342#endif
343
Chandler Carrutheb4ec3a2011-11-13 11:34:55 +0000344/// \brief Mark a chain's successors as having one fewer preds.
345///
346/// When a chain is being merged into the "placed" chain, this routine will
347/// quickly walk the successors of each block in the chain and mark them as
348/// having one fewer active predecessor. It also adds any successors of this
349/// chain which reach the zero-predecessor state to the worklist passed in.
Chandler Carruth8d150782011-11-13 11:20:44 +0000350void MachineBlockPlacement::markChainSuccessors(
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000351 BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
Chandler Carruth8d150782011-11-13 11:20:44 +0000352 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
Jakub Staszak90616162011-12-21 23:02:08 +0000353 const BlockFilterSet *BlockFilter) {
Chandler Carruth8d150782011-11-13 11:20:44 +0000354 // Walk all the blocks in this chain, marking their successors as having
355 // a predecessor placed.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000356 for (MachineBasicBlock *MBB : Chain) {
Chandler Carruth8d150782011-11-13 11:20:44 +0000357 // Add any successors for which this is the only un-placed in-loop
358 // predecessor to the worklist as a viable candidate for CFG-neutral
359 // placement. No subsequent placement of this block will violate the CFG
360 // shape, so we get to use heuristics to choose a favorable placement.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000361 for (MachineBasicBlock *Succ : MBB->successors()) {
362 if (BlockFilter && !BlockFilter->count(Succ))
Chandler Carruth8d150782011-11-13 11:20:44 +0000363 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000364 BlockChain &SuccChain = *BlockToChain[Succ];
Chandler Carruth8d150782011-11-13 11:20:44 +0000365 // Disregard edges within a fixed chain, or edges to the loop header.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000366 if (&Chain == &SuccChain || Succ == LoopHeaderBB)
Chandler Carruth8d150782011-11-13 11:20:44 +0000367 continue;
Chandler Carruth10281422011-10-21 06:46:38 +0000368
Chandler Carruth8d150782011-11-13 11:20:44 +0000369 // This is a cross-chain edge that is within the loop, so decrement the
370 // loop predecessor count of the destination chain.
Philip Reamesae27b232016-03-03 00:58:43 +0000371 if (SuccChain.UnscheduledPredecessors > 0 && --SuccChain.UnscheduledPredecessors == 0)
Chandler Carruthd394baf2011-11-24 08:46:04 +0000372 BlockWorkList.push_back(*SuccChain.begin());
Chandler Carruth10281422011-10-21 06:46:38 +0000373 }
374 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000375}
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000376
Chandler Carruthb3361722011-11-13 11:34:53 +0000377/// \brief Select the best successor for a block.
378///
379/// This looks across all successors of a particular block and attempts to
380/// select the "best" one to be the layout successor. It only considers direct
381/// successors which also pass the block filter. It will attempt to avoid
382/// breaking CFG structure, but cave and break such structures in the case of
383/// very hot successor edges.
384///
385/// \returns The best successor block found, or null if none are viable.
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000386MachineBasicBlock *
387MachineBlockPlacement::selectBestSuccessor(MachineBasicBlock *BB,
388 BlockChain &Chain,
389 const BlockFilterSet *BlockFilter) {
Chandler Carruthb3361722011-11-13 11:34:53 +0000390 const BranchProbability HotProb(4, 5); // 80%
391
Craig Topperc0196b12014-04-14 00:51:57 +0000392 MachineBasicBlock *BestSucc = nullptr;
Cong Houd97c1002015-12-01 05:29:22 +0000393 auto BestProb = BranchProbability::getZero();
Chandler Carruthb3361722011-11-13 11:34:53 +0000394
Cong Houd97c1002015-12-01 05:29:22 +0000395 // Adjust edge probabilities by excluding edges pointing to blocks that is
396 // either not in BlockFilter or is already in the current chain. Consider the
397 // following CFG:
Cong Hou41cf1a52015-11-18 00:52:52 +0000398 //
399 // --->A
400 // | / \
401 // | B C
402 // | \ / \
403 // ----D E
404 //
405 // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after
406 // A->C is chosen as a fall-through, D won't be selected as a successor of C
407 // due to CFG constraint (the probability of C->D is not greater than
408 // HotProb). If we exclude E that is not in BlockFilter when calculating the
409 // probability of C->D, D will be selected and we will get A C D B as the
410 // layout of this loop.
Cong Houd97c1002015-12-01 05:29:22 +0000411 auto AdjustedSumProb = BranchProbability::getOne();
Cong Hou41cf1a52015-11-18 00:52:52 +0000412 SmallVector<MachineBasicBlock *, 4> Successors;
413 for (MachineBasicBlock *Succ : BB->successors()) {
414 bool SkipSucc = false;
415 if (BlockFilter && !BlockFilter->count(Succ)) {
416 SkipSucc = true;
417 } else {
418 BlockChain *SuccChain = BlockToChain[Succ];
419 if (SuccChain == &Chain) {
Cong Hou41cf1a52015-11-18 00:52:52 +0000420 SkipSucc = true;
421 } else if (Succ != *SuccChain->begin()) {
422 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> Mid chain!\n");
423 continue;
424 }
425 }
426 if (SkipSucc)
Cong Houd97c1002015-12-01 05:29:22 +0000427 AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ);
Cong Hou41cf1a52015-11-18 00:52:52 +0000428 else
429 Successors.push_back(Succ);
430 }
431
432 DEBUG(dbgs() << "Attempting merge from: " << getBlockName(BB) << "\n");
433 for (MachineBasicBlock *Succ : Successors) {
Cong Houd97c1002015-12-01 05:29:22 +0000434 BranchProbability SuccProb;
435 uint32_t SuccProbN = MBPI->getEdgeProbability(BB, Succ).getNumerator();
436 uint32_t SuccProbD = AdjustedSumProb.getNumerator();
437 if (SuccProbN >= SuccProbD)
438 SuccProb = BranchProbability::getOne();
439 else
440 SuccProb = BranchProbability(SuccProbN, SuccProbD);
Chandler Carruthb3361722011-11-13 11:34:53 +0000441
Daniel Jasper471e8562015-03-04 11:05:34 +0000442 // If we outline optional branches, look whether Succ is unavoidable, i.e.
443 // dominates all terminators of the MachineFunction. If it does, other
444 // successors must be optional. Don't do this for cold branches.
445 if (OutlineOptionalBranches && SuccProb > HotProb.getCompl() &&
Daniel Jasper214997c2015-03-20 10:00:37 +0000446 UnavoidableBlocks.count(Succ) > 0) {
447 auto HasShortOptionalBranch = [&]() {
448 for (MachineBasicBlock *Pred : Succ->predecessors()) {
449 // Check whether there is an unplaced optional branch.
450 if (Pred == Succ || (BlockFilter && !BlockFilter->count(Pred)) ||
451 BlockToChain[Pred] == &Chain)
452 continue;
453 // Check whether the optional branch has exactly one BB.
454 if (Pred->pred_size() > 1 || *Pred->pred_begin() != BB)
455 continue;
456 // Check whether the optional branch is small.
457 if (Pred->size() < OutlineOptionalThreshold)
458 return true;
459 }
460 return false;
461 };
462 if (!HasShortOptionalBranch())
463 return Succ;
464 }
Daniel Jasper471e8562015-03-04 11:05:34 +0000465
Chandler Carruthb3361722011-11-13 11:34:53 +0000466 // Only consider successors which are either "hot", or wouldn't violate
467 // any CFG constraints.
Cong Hou41cf1a52015-11-18 00:52:52 +0000468 BlockChain &SuccChain = *BlockToChain[Succ];
Philip Reamesae27b232016-03-03 00:58:43 +0000469 if (SuccChain.UnscheduledPredecessors != 0) {
Chandler Carruth18dfac32011-11-20 11:22:06 +0000470 if (SuccProb < HotProb) {
Daniel Jaspered9eb722015-02-18 08:19:16 +0000471 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
Chandler Carruth260258b2013-11-25 00:43:41 +0000472 << " (prob) (CFG conflict)\n");
Chandler Carruth18dfac32011-11-20 11:22:06 +0000473 continue;
474 }
475
Daniel Jasper4d7b0432015-02-18 08:18:07 +0000476 // Make sure that a hot successor doesn't have a globally more
477 // important predecessor.
Cong Houd97c1002015-12-01 05:29:22 +0000478 auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ);
Daniel Jasper4d7b0432015-02-18 08:18:07 +0000479 BlockFrequency CandidateEdgeFreq =
Cong Hou41cf1a52015-11-18 00:52:52 +0000480 MBFI->getBlockFreq(BB) * RealSuccProb * HotProb.getCompl();
Daniel Jasper4d7b0432015-02-18 08:18:07 +0000481 bool BadCFGConflict = false;
Daniel Jaspered9eb722015-02-18 08:19:16 +0000482 for (MachineBasicBlock *Pred : Succ->predecessors()) {
Philip Reames23d93392016-03-03 00:01:42 +0000483 if (Pred == Succ || BlockToChain[Pred] == &SuccChain ||
484 (BlockFilter && !BlockFilter->count(Pred)) ||
Daniel Jaspered9eb722015-02-18 08:19:16 +0000485 BlockToChain[Pred] == &Chain)
Chandler Carruthe3288142015-01-14 20:19:29 +0000486 continue;
Daniel Jasper4d7b0432015-02-18 08:18:07 +0000487 BlockFrequency PredEdgeFreq =
Daniel Jaspered9eb722015-02-18 08:19:16 +0000488 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
Daniel Jasper4d7b0432015-02-18 08:18:07 +0000489 if (PredEdgeFreq >= CandidateEdgeFreq) {
490 BadCFGConflict = true;
491 break;
Chandler Carruthe3288142015-01-14 20:19:29 +0000492 }
Chandler Carruth18dfac32011-11-20 11:22:06 +0000493 }
Daniel Jasper4d7b0432015-02-18 08:18:07 +0000494 if (BadCFGConflict) {
Daniel Jaspered9eb722015-02-18 08:19:16 +0000495 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
Daniel Jasper4d7b0432015-02-18 08:18:07 +0000496 << " (prob) (non-cold CFG conflict)\n");
497 continue;
498 }
Chandler Carruthb3361722011-11-13 11:34:53 +0000499 }
500
Daniel Jaspered9eb722015-02-18 08:19:16 +0000501 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
Chandler Carruthb3361722011-11-13 11:34:53 +0000502 << " (prob)"
Philip Reamesae27b232016-03-03 00:58:43 +0000503 << (SuccChain.UnscheduledPredecessors != 0 ? " (CFG break)" : "")
Chandler Carruthb3361722011-11-13 11:34:53 +0000504 << "\n");
Cong Houd97c1002015-12-01 05:29:22 +0000505 if (BestSucc && BestProb >= SuccProb)
Chandler Carruthb3361722011-11-13 11:34:53 +0000506 continue;
Daniel Jaspered9eb722015-02-18 08:19:16 +0000507 BestSucc = Succ;
Cong Houd97c1002015-12-01 05:29:22 +0000508 BestProb = SuccProb;
Chandler Carruthb3361722011-11-13 11:34:53 +0000509 }
510 return BestSucc;
511}
512
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000513/// \brief Select the best block from a worklist.
514///
515/// This looks through the provided worklist as a list of candidate basic
516/// blocks and select the most profitable one to place. The definition of
517/// profitable only really makes sense in the context of a loop. This returns
518/// the most frequently visited block in the worklist, which in the case of
519/// a loop, is the one most desirable to be physically close to the rest of the
520/// loop body in order to improve icache behavior.
521///
522/// \returns The best block found, or null if none are viable.
523MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
Haicheng Wu1951cf22016-04-06 20:38:20 +0000524 BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList) {
Chandler Carruth0af6a0b2011-11-14 09:46:33 +0000525 // Once we need to walk the worklist looking for a candidate, cleanup the
526 // worklist of already placed entries.
527 // FIXME: If this shows up on profiles, it could be folded (at the cost of
528 // some code complexity) into the loop below.
529 WorkList.erase(std::remove_if(WorkList.begin(), WorkList.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000530 [&](MachineBasicBlock *BB) {
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000531 return BlockToChain.lookup(BB) == &Chain;
532 }),
Chandler Carruth0af6a0b2011-11-14 09:46:33 +0000533 WorkList.end());
534
Craig Topperc0196b12014-04-14 00:51:57 +0000535 MachineBasicBlock *BestBlock = nullptr;
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000536 BlockFrequency BestFreq;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000537 for (MachineBasicBlock *MBB : WorkList) {
538 BlockChain &SuccChain = *BlockToChain[MBB];
Philip Reames02e11322016-03-02 22:40:51 +0000539 if (&SuccChain == &Chain)
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000540 continue;
Junmo Park4ba6cf62016-03-11 05:07:07 +0000541
Philip Reamesae27b232016-03-03 00:58:43 +0000542 assert(SuccChain.UnscheduledPredecessors == 0 && "Found CFG-violating block");
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000543
Chandler Carruth7a715da2015-03-05 03:19:05 +0000544 BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
545 DEBUG(dbgs() << " " << getBlockName(MBB) << " -> ";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000546 MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000547 if (BestBlock && BestFreq >= CandidateFreq)
548 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000549 BestBlock = MBB;
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000550 BestFreq = CandidateFreq;
551 }
552 return BestBlock;
553}
554
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000555/// \brief Retrieve the first unplaced basic block.
556///
557/// This routine is called when we are unable to use the CFG to walk through
558/// all of the basic blocks and form a chain due to unnatural loops in the CFG.
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000559/// We walk through the function's blocks in order, starting from the
560/// LastUnplacedBlockIt. We update this iterator on each call to avoid
561/// re-scanning the entire sequence on repeated calls to this routine.
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000562MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000563 MachineFunction &F, const BlockChain &PlacedChain,
564 MachineFunction::iterator &PrevUnplacedBlockIt,
Jakub Staszak90616162011-12-21 23:02:08 +0000565 const BlockFilterSet *BlockFilter) {
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000566 for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F.end(); I != E;
567 ++I) {
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +0000568 if (BlockFilter && !BlockFilter->count(&*I))
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000569 continue;
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +0000570 if (BlockToChain[&*I] != &PlacedChain) {
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000571 PrevUnplacedBlockIt = I;
Chandler Carruth4a87aa02011-11-23 03:03:21 +0000572 // Now select the head of the chain to which the unplaced block belongs
573 // as the block to place. This will force the entire chain to be placed,
574 // and satisfies the requirements of merging chains.
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +0000575 return *BlockToChain[&*I]->begin();
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000576 }
577 }
Craig Topperc0196b12014-04-14 00:51:57 +0000578 return nullptr;
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000579}
580
Amaury Secheteae09c22016-03-14 21:24:11 +0000581void MachineBlockPlacement::fillWorkLists(
582 MachineBasicBlock *MBB,
583 SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
584 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
585 const BlockFilterSet *BlockFilter = nullptr) {
586 BlockChain &Chain = *BlockToChain[MBB];
587 if (!UpdatedPreds.insert(&Chain).second)
588 return;
589
590 assert(Chain.UnscheduledPredecessors == 0);
591 for (MachineBasicBlock *ChainBB : Chain) {
592 assert(BlockToChain[ChainBB] == &Chain);
593 for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
594 if (BlockFilter && !BlockFilter->count(Pred))
595 continue;
596 if (BlockToChain[Pred] == &Chain)
597 continue;
598 ++Chain.UnscheduledPredecessors;
599 }
600 }
601
602 if (Chain.UnscheduledPredecessors == 0)
603 BlockWorkList.push_back(*Chain.begin());
604}
605
Chandler Carruth8d150782011-11-13 11:20:44 +0000606void MachineBlockPlacement::buildChain(
Daniel Jasper471e8562015-03-04 11:05:34 +0000607 MachineBasicBlock *BB, BlockChain &Chain,
Chandler Carruth8d150782011-11-13 11:20:44 +0000608 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
Jakub Staszak90616162011-12-21 23:02:08 +0000609 const BlockFilterSet *BlockFilter) {
Chandler Carruth8d150782011-11-13 11:20:44 +0000610 assert(BB);
Jakub Staszak90616162011-12-21 23:02:08 +0000611 assert(BlockToChain[BB] == &Chain);
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000612 MachineFunction &F = *BB->getParent();
613 MachineFunction::iterator PrevUnplacedBlockIt = F.begin();
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000614
Chandler Carruth8d150782011-11-13 11:20:44 +0000615 MachineBasicBlock *LoopHeaderBB = BB;
616 markChainSuccessors(Chain, LoopHeaderBB, BlockWorkList, BlockFilter);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000617 BB = *std::prev(Chain.end());
Chandler Carruth8d150782011-11-13 11:20:44 +0000618 for (;;) {
619 assert(BB);
Jakub Staszak90616162011-12-21 23:02:08 +0000620 assert(BlockToChain[BB] == &Chain);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000621 assert(*std::prev(Chain.end()) == BB);
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000622
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +0000623 // Look for the best viable successor if there is one to place immediately
624 // after this block.
Duncan Sands291d47e2012-09-14 09:00:11 +0000625 MachineBasicBlock *BestSucc = selectBestSuccessor(BB, Chain, BlockFilter);
Chandler Carruth8d150782011-11-13 11:20:44 +0000626
627 // If an immediate successor isn't available, look for the best viable
628 // block among those we've identified as not violating the loop's CFG at
629 // this point. This won't be a fallthrough, but it will increase locality.
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000630 if (!BestSucc)
Haicheng Wu1951cf22016-04-06 20:38:20 +0000631 BestSucc = selectBestCandidateBlock(Chain, BlockWorkList);
Chandler Carruth8d150782011-11-13 11:20:44 +0000632
Chandler Carruth8d150782011-11-13 11:20:44 +0000633 if (!BestSucc) {
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000634 BestSucc =
635 getFirstUnplacedBlock(F, Chain, PrevUnplacedBlockIt, BlockFilter);
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000636 if (!BestSucc)
637 break;
638
639 DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
640 "layout successor until the CFG reduces\n");
Chandler Carruth8d150782011-11-13 11:20:44 +0000641 }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000642
Chandler Carruth8d150782011-11-13 11:20:44 +0000643 // Place this block, updating the datastructures to reflect its placement.
Jakub Staszak90616162011-12-21 23:02:08 +0000644 BlockChain &SuccChain = *BlockToChain[BestSucc];
Philip Reamesae27b232016-03-03 00:58:43 +0000645 // Zero out UnscheduledPredecessors for the successor we're about to merge in case
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000646 // we selected a successor that didn't fit naturally into the CFG.
Philip Reamesae27b232016-03-03 00:58:43 +0000647 SuccChain.UnscheduledPredecessors = 0;
Philip Reamesb9688f42016-03-02 21:45:13 +0000648 DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to "
649 << getBlockName(BestSucc) << "\n");
Chandler Carruth8d150782011-11-13 11:20:44 +0000650 markChainSuccessors(SuccChain, LoopHeaderBB, BlockWorkList, BlockFilter);
651 Chain.merge(BestSucc, &SuccChain);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000652 BB = *std::prev(Chain.end());
Jakub Staszak190c7122011-12-07 19:46:10 +0000653 }
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000654
655 DEBUG(dbgs() << "Finished forming chain for header block "
Philip Reamesb9688f42016-03-02 21:45:13 +0000656 << getBlockName(*Chain.begin()) << "\n");
Chandler Carruth10281422011-10-21 06:46:38 +0000657}
658
Chandler Carruth03adbd42011-11-27 13:34:33 +0000659/// \brief Find the best loop top block for layout.
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000660///
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000661/// Look for a block which is strictly better than the loop header for laying
662/// out at the top of the loop. This looks for one and only one pattern:
663/// a latch block with no conditional exit. This block will cause a conditional
664/// jump around it or will be the bottom of the loop if we lay it out in place,
665/// but if it it doesn't end up at the bottom of the loop for any reason,
666/// rotation alone won't fix it. Because such a block will always result in an
667/// unconditional jump (for the backedge) rotating it in front of the loop
668/// header is always profitable.
669MachineBasicBlock *
670MachineBlockPlacement::findBestLoopTop(MachineLoop &L,
671 const BlockFilterSet &LoopBlockSet) {
672 // Check that the header hasn't been fused with a preheader block due to
673 // crazy branches. If it has, we need to start with the header at the top to
674 // prevent pulling the preheader into the loop body.
675 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
676 if (!LoopBlockSet.count(*HeaderChain.begin()))
677 return L.getHeader();
678
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000679 DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(L.getHeader())
680 << "\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000681
682 BlockFrequency BestPredFreq;
Craig Topperc0196b12014-04-14 00:51:57 +0000683 MachineBasicBlock *BestPred = nullptr;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000684 for (MachineBasicBlock *Pred : L.getHeader()->predecessors()) {
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000685 if (!LoopBlockSet.count(Pred))
686 continue;
687 DEBUG(dbgs() << " header pred: " << getBlockName(Pred) << ", "
Michael Gottesmanb78dec82013-12-14 00:25:45 +0000688 << Pred->succ_size() << " successors, ";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000689 MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000690 if (Pred->succ_size() > 1)
691 continue;
692
693 BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
694 if (!BestPred || PredFreq > BestPredFreq ||
695 (!(PredFreq < BestPredFreq) &&
696 Pred->isLayoutSuccessor(L.getHeader()))) {
697 BestPred = Pred;
698 BestPredFreq = PredFreq;
699 }
700 }
701
702 // If no direct predecessor is fine, just use the loop header.
Philip Reamesb9688f42016-03-02 21:45:13 +0000703 if (!BestPred) {
704 DEBUG(dbgs() << " final top unchanged\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000705 return L.getHeader();
Philip Reamesb9688f42016-03-02 21:45:13 +0000706 }
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000707
708 // Walk backwards through any straight line of predecessors.
709 while (BestPred->pred_size() == 1 &&
710 (*BestPred->pred_begin())->succ_size() == 1 &&
711 *BestPred->pred_begin() != L.getHeader())
712 BestPred = *BestPred->pred_begin();
713
714 DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n");
715 return BestPred;
716}
717
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000718/// \brief Find the best loop exiting block for layout.
719///
Chandler Carruth03adbd42011-11-27 13:34:33 +0000720/// This routine implements the logic to analyze the loop looking for the best
721/// block to layout at the top of the loop. Typically this is done to maximize
722/// fallthrough opportunities.
723MachineBasicBlock *
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000724MachineBlockPlacement::findBestLoopExit(MachineFunction &F, MachineLoop &L,
Chandler Carruthccc7e422012-04-16 01:12:56 +0000725 const BlockFilterSet &LoopBlockSet) {
Chandler Carruth68062612012-04-10 13:35:57 +0000726 // We don't want to layout the loop linearly in all cases. If the loop header
727 // is just a normal basic block in the loop, we want to look for what block
728 // within the loop is the best one to layout at the top. However, if the loop
729 // header has be pre-merged into a chain due to predecessors not having
730 // analyzable branches, *and* the predecessor it is merged with is *not* part
731 // of the loop, rotating the header into the middle of the loop will create
732 // a non-contiguous range of blocks which is Very Bad. So start with the
733 // header and only rotate if safe.
734 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
735 if (!LoopBlockSet.count(*HeaderChain.begin()))
Craig Topperc0196b12014-04-14 00:51:57 +0000736 return nullptr;
Chandler Carruth68062612012-04-10 13:35:57 +0000737
Chandler Carruth03adbd42011-11-27 13:34:33 +0000738 BlockFrequency BestExitEdgeFreq;
Chandler Carruthccc7e422012-04-16 01:12:56 +0000739 unsigned BestExitLoopDepth = 0;
Craig Topperc0196b12014-04-14 00:51:57 +0000740 MachineBasicBlock *ExitingBB = nullptr;
Chandler Carruth4f567202011-11-27 20:18:00 +0000741 // If there are exits to outer loops, loop rotation can severely limit
742 // fallthrough opportunites unless it selects such an exit. Keep a set of
743 // blocks where rotating to exit with that block will reach an outer loop.
744 SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
745
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000746 DEBUG(dbgs() << "Finding best loop exit for: " << getBlockName(L.getHeader())
747 << "\n");
Chandler Carruth7a715da2015-03-05 03:19:05 +0000748 for (MachineBasicBlock *MBB : L.getBlocks()) {
749 BlockChain &Chain = *BlockToChain[MBB];
Chandler Carruth03adbd42011-11-27 13:34:33 +0000750 // Ensure that this block is at the end of a chain; otherwise it could be
Chandler Carruth9a512a42015-04-15 13:19:54 +0000751 // mid-way through an inner loop or a successor of an unanalyzable branch.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000752 if (MBB != *std::prev(Chain.end()))
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000753 continue;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000754
Chandler Carruth03adbd42011-11-27 13:34:33 +0000755 // Now walk the successors. We need to establish whether this has a viable
756 // exiting successor and whether it has a viable non-exiting successor.
757 // We store the old exiting state and restore it if a viable looping
758 // successor isn't found.
759 MachineBasicBlock *OldExitingBB = ExitingBB;
760 BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
Chandler Carruthccc7e422012-04-16 01:12:56 +0000761 bool HasLoopingSucc = false;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000762 for (MachineBasicBlock *Succ : MBB->successors()) {
Reid Kleckner0e288232015-08-27 23:27:47 +0000763 if (Succ->isEHPad())
Chandler Carruth03adbd42011-11-27 13:34:33 +0000764 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000765 if (Succ == MBB)
Chandler Carruth03adbd42011-11-27 13:34:33 +0000766 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000767 BlockChain &SuccChain = *BlockToChain[Succ];
Chandler Carruth03adbd42011-11-27 13:34:33 +0000768 // Don't split chains, either this chain or the successor's chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000769 if (&Chain == &SuccChain) {
Chandler Carruth7a715da2015-03-05 03:19:05 +0000770 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
771 << getBlockName(Succ) << " (chain conflict)\n");
Chandler Carruth03adbd42011-11-27 13:34:33 +0000772 continue;
773 }
774
Cong Houd97c1002015-12-01 05:29:22 +0000775 auto SuccProb = MBPI->getEdgeProbability(MBB, Succ);
Chandler Carruth7a715da2015-03-05 03:19:05 +0000776 if (LoopBlockSet.count(Succ)) {
777 DEBUG(dbgs() << " looping: " << getBlockName(MBB) << " -> "
Cong Houd97c1002015-12-01 05:29:22 +0000778 << getBlockName(Succ) << " (" << SuccProb << ")\n");
Chandler Carruthccc7e422012-04-16 01:12:56 +0000779 HasLoopingSucc = true;
Chandler Carruth03adbd42011-11-27 13:34:33 +0000780 continue;
781 }
782
Chandler Carruthccc7e422012-04-16 01:12:56 +0000783 unsigned SuccLoopDepth = 0;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000784 if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
Chandler Carruthccc7e422012-04-16 01:12:56 +0000785 SuccLoopDepth = ExitLoop->getLoopDepth();
786 if (ExitLoop->contains(&L))
Chandler Carruth7a715da2015-03-05 03:19:05 +0000787 BlocksExitingToOuterLoop.insert(MBB);
Chandler Carruthccc7e422012-04-16 01:12:56 +0000788 }
789
Chandler Carruth7a715da2015-03-05 03:19:05 +0000790 BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
791 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
792 << getBlockName(Succ) << " [L:" << SuccLoopDepth << "] (";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000793 MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
Benjamin Kramerc8160d62013-11-20 19:08:44 +0000794 // Note that we bias this toward an existing layout successor to retain
795 // incoming order in the absence of better information. The exit must have
796 // a frequency higher than the current exit before we consider breaking
797 // the layout.
798 BranchProbability Bias(100 - ExitBlockBias, 100);
Chandler Carruth26d30172015-04-15 13:39:42 +0000799 if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
Chandler Carruthccc7e422012-04-16 01:12:56 +0000800 ExitEdgeFreq > BestExitEdgeFreq ||
Chandler Carruth7a715da2015-03-05 03:19:05 +0000801 (MBB->isLayoutSuccessor(Succ) &&
Benjamin Kramerc8160d62013-11-20 19:08:44 +0000802 !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
Chandler Carruth03adbd42011-11-27 13:34:33 +0000803 BestExitEdgeFreq = ExitEdgeFreq;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000804 ExitingBB = MBB;
Chandler Carrutha0545802011-11-27 09:22:53 +0000805 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000806 }
Chandler Carruth03adbd42011-11-27 13:34:33 +0000807
Chandler Carruthccc7e422012-04-16 01:12:56 +0000808 if (!HasLoopingSucc) {
Chandler Carruthcfb2b9d2015-04-15 13:26:41 +0000809 // Restore the old exiting state, no viable looping successor was found.
Chandler Carruth03adbd42011-11-27 13:34:33 +0000810 ExitingBB = OldExitingBB;
811 BestExitEdgeFreq = OldBestExitEdgeFreq;
Chandler Carruth03adbd42011-11-27 13:34:33 +0000812 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000813 }
Chandler Carruthccc7e422012-04-16 01:12:56 +0000814 // Without a candidate exiting block or with only a single block in the
Chandler Carruth03adbd42011-11-27 13:34:33 +0000815 // loop, just use the loop header to layout the loop.
816 if (!ExitingBB || L.getNumBlocks() == 1)
Craig Topperc0196b12014-04-14 00:51:57 +0000817 return nullptr;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000818
Chandler Carruth4f567202011-11-27 20:18:00 +0000819 // Also, if we have exit blocks which lead to outer loops but didn't select
820 // one of them as the exiting block we are rotating toward, disable loop
821 // rotation altogether.
822 if (!BlocksExitingToOuterLoop.empty() &&
823 !BlocksExitingToOuterLoop.count(ExitingBB))
Craig Topperc0196b12014-04-14 00:51:57 +0000824 return nullptr;
Chandler Carruth4f567202011-11-27 20:18:00 +0000825
Chandler Carruth03adbd42011-11-27 13:34:33 +0000826 DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB) << "\n");
Chandler Carruthccc7e422012-04-16 01:12:56 +0000827 return ExitingBB;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000828}
829
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000830/// \brief Attempt to rotate an exiting block to the bottom of the loop.
831///
832/// Once we have built a chain, try to rotate it to line up the hot exit block
833/// with fallthrough out of the loop if doing so doesn't introduce unnecessary
834/// branches. For example, if the loop has fallthrough into its header and out
835/// of its bottom already, don't rotate it.
836void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
837 MachineBasicBlock *ExitingBB,
838 const BlockFilterSet &LoopBlockSet) {
839 if (!ExitingBB)
840 return;
841
842 MachineBasicBlock *Top = *LoopChain.begin();
843 bool ViableTopFallthrough = false;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000844 for (MachineBasicBlock *Pred : Top->predecessors()) {
845 BlockChain *PredChain = BlockToChain[Pred];
846 if (!LoopBlockSet.count(Pred) &&
847 (!PredChain || Pred == *std::prev(PredChain->end()))) {
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000848 ViableTopFallthrough = true;
849 break;
850 }
851 }
852
853 // If the header has viable fallthrough, check whether the current loop
854 // bottom is a viable exiting block. If so, bail out as rotating will
855 // introduce an unnecessary branch.
856 if (ViableTopFallthrough) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000857 MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
Chandler Carruth7a715da2015-03-05 03:19:05 +0000858 for (MachineBasicBlock *Succ : Bottom->successors()) {
859 BlockChain *SuccChain = BlockToChain[Succ];
860 if (!LoopBlockSet.count(Succ) &&
861 (!SuccChain || Succ == *SuccChain->begin()))
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000862 return;
863 }
864 }
865
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000866 BlockChain::iterator ExitIt =
867 std::find(LoopChain.begin(), LoopChain.end(), ExitingBB);
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000868 if (ExitIt == LoopChain.end())
869 return;
870
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000871 std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000872}
873
Cong Hou7745dbc2015-10-19 23:16:40 +0000874/// \brief Attempt to rotate a loop based on profile data to reduce branch cost.
875///
876/// With profile data, we can determine the cost in terms of missed fall through
877/// opportunities when rotating a loop chain and select the best rotation.
878/// Basically, there are three kinds of cost to consider for each rotation:
879/// 1. The possibly missed fall through edge (if it exists) from BB out of
880/// the loop to the loop header.
881/// 2. The possibly missed fall through edges (if they exist) from the loop
882/// exits to BB out of the loop.
883/// 3. The missed fall through edge (if it exists) from the last BB to the
884/// first BB in the loop chain.
885/// Therefore, the cost for a given rotation is the sum of costs listed above.
886/// We select the best rotation with the smallest cost.
887void MachineBlockPlacement::rotateLoopWithProfile(
888 BlockChain &LoopChain, MachineLoop &L, const BlockFilterSet &LoopBlockSet) {
889 auto HeaderBB = L.getHeader();
890 auto HeaderIter = std::find(LoopChain.begin(), LoopChain.end(), HeaderBB);
891 auto RotationPos = LoopChain.end();
892
893 BlockFrequency SmallestRotationCost = BlockFrequency::getMaxFrequency();
894
895 // A utility lambda that scales up a block frequency by dividing it by a
896 // branch probability which is the reciprocal of the scale.
897 auto ScaleBlockFrequency = [](BlockFrequency Freq,
898 unsigned Scale) -> BlockFrequency {
899 if (Scale == 0)
900 return 0;
901 // Use operator / between BlockFrequency and BranchProbability to implement
902 // saturating multiplication.
903 return Freq / BranchProbability(1, Scale);
904 };
905
906 // Compute the cost of the missed fall-through edge to the loop header if the
907 // chain head is not the loop header. As we only consider natural loops with
908 // single header, this computation can be done only once.
909 BlockFrequency HeaderFallThroughCost(0);
910 for (auto *Pred : HeaderBB->predecessors()) {
911 BlockChain *PredChain = BlockToChain[Pred];
912 if (!LoopBlockSet.count(Pred) &&
913 (!PredChain || Pred == *std::prev(PredChain->end()))) {
914 auto EdgeFreq =
915 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, HeaderBB);
916 auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost);
917 // If the predecessor has only an unconditional jump to the header, we
918 // need to consider the cost of this jump.
919 if (Pred->succ_size() == 1)
920 FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost);
921 HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost);
922 }
923 }
924
925 // Here we collect all exit blocks in the loop, and for each exit we find out
926 // its hottest exit edge. For each loop rotation, we define the loop exit cost
927 // as the sum of frequencies of exit edges we collect here, excluding the exit
928 // edge from the tail of the loop chain.
929 SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq;
930 for (auto BB : LoopChain) {
Cong Houd97c1002015-12-01 05:29:22 +0000931 auto LargestExitEdgeProb = BranchProbability::getZero();
Cong Hou7745dbc2015-10-19 23:16:40 +0000932 for (auto *Succ : BB->successors()) {
933 BlockChain *SuccChain = BlockToChain[Succ];
934 if (!LoopBlockSet.count(Succ) &&
935 (!SuccChain || Succ == *SuccChain->begin())) {
Cong Houd97c1002015-12-01 05:29:22 +0000936 auto SuccProb = MBPI->getEdgeProbability(BB, Succ);
937 LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb);
Cong Hou7745dbc2015-10-19 23:16:40 +0000938 }
939 }
Cong Houd97c1002015-12-01 05:29:22 +0000940 if (LargestExitEdgeProb > BranchProbability::getZero()) {
941 auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb;
Cong Hou7745dbc2015-10-19 23:16:40 +0000942 ExitsWithFreq.emplace_back(BB, ExitFreq);
943 }
944 }
945
946 // In this loop we iterate every block in the loop chain and calculate the
947 // cost assuming the block is the head of the loop chain. When the loop ends,
948 // we should have found the best candidate as the loop chain's head.
949 for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()),
950 EndIter = LoopChain.end();
951 Iter != EndIter; Iter++, TailIter++) {
952 // TailIter is used to track the tail of the loop chain if the block we are
953 // checking (pointed by Iter) is the head of the chain.
954 if (TailIter == LoopChain.end())
955 TailIter = LoopChain.begin();
956
957 auto TailBB = *TailIter;
958
959 // Calculate the cost by putting this BB to the top.
960 BlockFrequency Cost = 0;
961
962 // If the current BB is the loop header, we need to take into account the
963 // cost of the missed fall through edge from outside of the loop to the
964 // header.
965 if (Iter != HeaderIter)
966 Cost += HeaderFallThroughCost;
967
968 // Collect the loop exit cost by summing up frequencies of all exit edges
969 // except the one from the chain tail.
970 for (auto &ExitWithFreq : ExitsWithFreq)
971 if (TailBB != ExitWithFreq.first)
972 Cost += ExitWithFreq.second;
973
974 // The cost of breaking the once fall-through edge from the tail to the top
975 // of the loop chain. Here we need to consider three cases:
976 // 1. If the tail node has only one successor, then we will get an
977 // additional jmp instruction. So the cost here is (MisfetchCost +
978 // JumpInstCost) * tail node frequency.
979 // 2. If the tail node has two successors, then we may still get an
980 // additional jmp instruction if the layout successor after the loop
981 // chain is not its CFG successor. Note that the more frequently executed
982 // jmp instruction will be put ahead of the other one. Assume the
983 // frequency of those two branches are x and y, where x is the frequency
984 // of the edge to the chain head, then the cost will be
985 // (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency.
986 // 3. If the tail node has more than two successors (this rarely happens),
987 // we won't consider any additional cost.
988 if (TailBB->isSuccessor(*Iter)) {
989 auto TailBBFreq = MBFI->getBlockFreq(TailBB);
990 if (TailBB->succ_size() == 1)
991 Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(),
992 MisfetchCost + JumpInstCost);
993 else if (TailBB->succ_size() == 2) {
994 auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter);
995 auto TailToHeadFreq = TailBBFreq * TailToHeadProb;
996 auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2)
997 ? TailBBFreq * TailToHeadProb.getCompl()
998 : TailToHeadFreq;
999 Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) +
1000 ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost);
1001 }
1002 }
1003
Philip Reamesb9688f42016-03-02 21:45:13 +00001004 DEBUG(dbgs() << "The cost of loop rotation by making " << getBlockName(*Iter)
Cong Hou7745dbc2015-10-19 23:16:40 +00001005 << " to the top: " << Cost.getFrequency() << "\n");
1006
1007 if (Cost < SmallestRotationCost) {
1008 SmallestRotationCost = Cost;
1009 RotationPos = Iter;
1010 }
1011 }
1012
1013 if (RotationPos != LoopChain.end()) {
Philip Reamesb9688f42016-03-02 21:45:13 +00001014 DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos)
Cong Hou7745dbc2015-10-19 23:16:40 +00001015 << " to the top\n");
1016 std::rotate(LoopChain.begin(), RotationPos, LoopChain.end());
1017 }
1018}
1019
Cong Houb90b9e02015-11-02 21:24:00 +00001020/// \brief Collect blocks in the given loop that are to be placed.
1021///
1022/// When profile data is available, exclude cold blocks from the returned set;
1023/// otherwise, collect all blocks in the loop.
1024MachineBlockPlacement::BlockFilterSet
1025MachineBlockPlacement::collectLoopBlockSet(MachineFunction &F, MachineLoop &L) {
1026 BlockFilterSet LoopBlockSet;
1027
1028 // Filter cold blocks off from LoopBlockSet when profile data is available.
1029 // Collect the sum of frequencies of incoming edges to the loop header from
1030 // outside. If we treat the loop as a super block, this is the frequency of
1031 // the loop. Then for each block in the loop, we calculate the ratio between
1032 // its frequency and the frequency of the loop block. When it is too small,
1033 // don't add it to the loop chain. If there are outer loops, then this block
1034 // will be merged into the first outer loop chain for which this block is not
1035 // cold anymore. This needs precise profile data and we only do this when
1036 // profile data is available.
1037 if (F.getFunction()->getEntryCount()) {
1038 BlockFrequency LoopFreq(0);
1039 for (auto LoopPred : L.getHeader()->predecessors())
1040 if (!L.contains(LoopPred))
1041 LoopFreq += MBFI->getBlockFreq(LoopPred) *
1042 MBPI->getEdgeProbability(LoopPred, L.getHeader());
1043
1044 for (MachineBasicBlock *LoopBB : L.getBlocks()) {
1045 auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency();
1046 if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio)
1047 continue;
1048 LoopBlockSet.insert(LoopBB);
1049 }
1050 } else
1051 LoopBlockSet.insert(L.block_begin(), L.block_end());
1052
1053 return LoopBlockSet;
1054}
1055
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001056/// \brief Forms basic block chains from the natural loop structures.
Chandler Carruth10281422011-10-21 06:46:38 +00001057///
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001058/// These chains are designed to preserve the existing *structure* of the code
1059/// as much as possible. We can then stitch the chains together in a way which
1060/// both preserves the topological structure and minimizes taken conditional
1061/// branches.
Chandler Carruth8d150782011-11-13 11:20:44 +00001062void MachineBlockPlacement::buildLoopChains(MachineFunction &F,
Jakub Staszak90616162011-12-21 23:02:08 +00001063 MachineLoop &L) {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001064 // First recurse through any nested loops, building chains for those inner
1065 // loops.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001066 for (MachineLoop *InnerLoop : L)
1067 buildLoopChains(F, *InnerLoop);
Chandler Carruth10281422011-10-21 06:46:38 +00001068
Chandler Carruth8d150782011-11-13 11:20:44 +00001069 SmallVector<MachineBasicBlock *, 16> BlockWorkList;
Cong Houb90b9e02015-11-02 21:24:00 +00001070 BlockFilterSet LoopBlockSet = collectLoopBlockSet(F, L);
Chandler Carruth03adbd42011-11-27 13:34:33 +00001071
Cong Hou7745dbc2015-10-19 23:16:40 +00001072 // Check if we have profile data for this function. If yes, we will rotate
1073 // this loop by modeling costs more precisely which requires the profile data
1074 // for better layout.
1075 bool RotateLoopWithProfile =
1076 PreciseRotationCost && F.getFunction()->getEntryCount();
1077
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001078 // First check to see if there is an obviously preferable top block for the
1079 // loop. This will default to the header, but may end up as one of the
1080 // predecessors to the header if there is one which will result in strictly
1081 // fewer branches in the loop body.
Cong Hou7745dbc2015-10-19 23:16:40 +00001082 // When we use profile data to rotate the loop, this is unnecessary.
1083 MachineBasicBlock *LoopTop =
1084 RotateLoopWithProfile ? L.getHeader() : findBestLoopTop(L, LoopBlockSet);
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001085
1086 // If we selected just the header for the loop top, look for a potentially
1087 // profitable exit block in the event that rotating the loop can eliminate
1088 // branches by placing an exit edge at the bottom.
Craig Topperc0196b12014-04-14 00:51:57 +00001089 MachineBasicBlock *ExitingBB = nullptr;
Cong Hou7745dbc2015-10-19 23:16:40 +00001090 if (!RotateLoopWithProfile && LoopTop == L.getHeader())
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001091 ExitingBB = findBestLoopExit(F, L, LoopBlockSet);
1092
1093 BlockChain &LoopChain = *BlockToChain[LoopTop];
Chandler Carruth10281422011-10-21 06:46:38 +00001094
Chandler Carruth8d150782011-11-13 11:20:44 +00001095 // FIXME: This is a really lame way of walking the chains in the loop: we
1096 // walk the blocks, and use a set to prevent visiting a particular chain
1097 // twice.
Jakub Staszak90616162011-12-21 23:02:08 +00001098 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
Philip Reamesae27b232016-03-03 00:58:43 +00001099 assert(LoopChain.UnscheduledPredecessors == 0);
Jakub Staszak190c7122011-12-07 19:46:10 +00001100 UpdatedPreds.insert(&LoopChain);
Cong Houb90b9e02015-11-02 21:24:00 +00001101
Amaury Secheteae09c22016-03-14 21:24:11 +00001102 for (MachineBasicBlock *LoopBB : LoopBlockSet)
1103 fillWorkLists(LoopBB, UpdatedPreds, BlockWorkList, &LoopBlockSet);
Chandler Carruth8d150782011-11-13 11:20:44 +00001104
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001105 buildChain(LoopTop, LoopChain, BlockWorkList, &LoopBlockSet);
Cong Hou7745dbc2015-10-19 23:16:40 +00001106
1107 if (RotateLoopWithProfile)
1108 rotateLoopWithProfile(LoopChain, L, LoopBlockSet);
1109 else
1110 rotateLoop(LoopChain, ExitingBB, LoopBlockSet);
Chandler Carruth8d150782011-11-13 11:20:44 +00001111
1112 DEBUG({
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001113 // Crash at the end so we get all of the debugging output first.
1114 bool BadLoop = false;
Philip Reamesae27b232016-03-03 00:58:43 +00001115 if (LoopChain.UnscheduledPredecessors) {
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001116 BadLoop = true;
Chandler Carruth8d150782011-11-13 11:20:44 +00001117 dbgs() << "Loop chain contains a block without its preds placed!\n"
1118 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
1119 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001120 }
Chandler Carruth7a715da2015-03-05 03:19:05 +00001121 for (MachineBasicBlock *ChainBB : LoopChain) {
1122 dbgs() << " ... " << getBlockName(ChainBB) << "\n";
1123 if (!LoopBlockSet.erase(ChainBB)) {
Chandler Carruth0a31d142011-11-14 10:55:53 +00001124 // We don't mark the loop as bad here because there are real situations
1125 // where this can occur. For example, with an unanalyzable fallthrough
Chandler Carruth99fe42f2011-11-23 10:35:36 +00001126 // from a loop block to a non-loop block or vice versa.
Chandler Carruth8d150782011-11-13 11:20:44 +00001127 dbgs() << "Loop chain contains a block not contained by the loop!\n"
1128 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
1129 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00001130 << " Bad block: " << getBlockName(ChainBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001131 }
Chandler Carruthccc7e422012-04-16 01:12:56 +00001132 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001133
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001134 if (!LoopBlockSet.empty()) {
1135 BadLoop = true;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001136 for (MachineBasicBlock *LoopBB : LoopBlockSet)
Chandler Carruth8d150782011-11-13 11:20:44 +00001137 dbgs() << "Loop contains blocks never placed into a chain!\n"
1138 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
1139 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00001140 << " Bad block: " << getBlockName(LoopBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001141 }
1142 assert(!BadLoop && "Detected problems with the placement of this loop.");
Chandler Carruth8d150782011-11-13 11:20:44 +00001143 });
Chandler Carruth10281422011-10-21 06:46:38 +00001144}
1145
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001146void MachineBlockPlacement::buildCFGChains(MachineFunction &F) {
Chandler Carruth8d150782011-11-13 11:20:44 +00001147 // Ensure that every BB in the function has an associated chain to simplify
1148 // the assumptions of the remaining algorithm.
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001149 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
1150 for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001151 MachineBasicBlock *BB = &*FI;
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001152 BlockChain *Chain =
1153 new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001154 // Also, merge any blocks which we cannot reason about and must preserve
1155 // the exact fallthrough behavior for.
1156 for (;;) {
1157 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001158 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001159 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
1160 break;
1161
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001162 MachineFunction::iterator NextFI = std::next(FI);
1163 MachineBasicBlock *NextBB = &*NextFI;
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001164 // Ensure that the layout successor is a viable block, as we know that
1165 // fallthrough is a possibility.
1166 assert(NextFI != FE && "Can't fallthrough past the last block.");
1167 DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
1168 << getBlockName(BB) << " -> " << getBlockName(NextBB)
1169 << "\n");
Craig Topperc0196b12014-04-14 00:51:57 +00001170 Chain->merge(NextBB, nullptr);
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001171 FI = NextFI;
1172 BB = NextBB;
1173 }
1174 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001175
Daniel Jasper471e8562015-03-04 11:05:34 +00001176 if (OutlineOptionalBranches) {
1177 // Find the nearest common dominator of all of F's terminators.
1178 MachineBasicBlock *Terminator = nullptr;
1179 for (MachineBasicBlock &MBB : F) {
1180 if (MBB.succ_size() == 0) {
1181 if (Terminator == nullptr)
1182 Terminator = &MBB;
1183 else
1184 Terminator = MDT->findNearestCommonDominator(Terminator, &MBB);
1185 }
1186 }
1187
1188 // MBBs dominating this common dominator are unavoidable.
1189 UnavoidableBlocks.clear();
1190 for (MachineBasicBlock &MBB : F) {
1191 if (MDT->dominates(&MBB, Terminator)) {
1192 UnavoidableBlocks.insert(&MBB);
1193 }
1194 }
1195 }
1196
Chandler Carruth8d150782011-11-13 11:20:44 +00001197 // Build any loop-based chains.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001198 for (MachineLoop *L : *MLI)
1199 buildLoopChains(F, *L);
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001200
Chandler Carruth8d150782011-11-13 11:20:44 +00001201 SmallVector<MachineBasicBlock *, 16> BlockWorkList;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001202
Chandler Carruth8d150782011-11-13 11:20:44 +00001203 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
Amaury Secheteae09c22016-03-14 21:24:11 +00001204 for (MachineBasicBlock &MBB : F)
1205 fillWorkLists(&MBB, UpdatedPreds, BlockWorkList);
Chandler Carruth8d150782011-11-13 11:20:44 +00001206
1207 BlockChain &FunctionChain = *BlockToChain[&F.front()];
Chandler Carruth9b548a7f2011-11-15 06:26:43 +00001208 buildChain(&F.front(), FunctionChain, BlockWorkList);
Chandler Carruth8d150782011-11-13 11:20:44 +00001209
Matt Arsenault0f5f0152013-12-10 18:55:37 +00001210#ifndef NDEBUG
Matt Arsenault79d55f52013-12-05 20:02:18 +00001211 typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType;
Matt Arsenault0f5f0152013-12-10 18:55:37 +00001212#endif
Chandler Carruth8d150782011-11-13 11:20:44 +00001213 DEBUG({
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001214 // Crash at the end so we get all of the debugging output first.
1215 bool BadFunc = false;
Chandler Carruth8d150782011-11-13 11:20:44 +00001216 FunctionBlockSetType FunctionBlockSet;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001217 for (MachineBasicBlock &MBB : F)
1218 FunctionBlockSet.insert(&MBB);
Chandler Carruth8d150782011-11-13 11:20:44 +00001219
Chandler Carruth7a715da2015-03-05 03:19:05 +00001220 for (MachineBasicBlock *ChainBB : FunctionChain)
1221 if (!FunctionBlockSet.erase(ChainBB)) {
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001222 BadFunc = true;
Chandler Carruth8d150782011-11-13 11:20:44 +00001223 dbgs() << "Function chain contains a block not in the function!\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00001224 << " Bad block: " << getBlockName(ChainBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001225 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001226
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001227 if (!FunctionBlockSet.empty()) {
1228 BadFunc = true;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001229 for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
Chandler Carruth8d150782011-11-13 11:20:44 +00001230 dbgs() << "Function contains blocks never placed into a chain!\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00001231 << " Bad block: " << getBlockName(RemainingBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001232 }
1233 assert(!BadFunc && "Detected problems with the block placement.");
Chandler Carruth8d150782011-11-13 11:20:44 +00001234 });
1235
1236 // Splice the blocks into place.
1237 MachineFunction::iterator InsertPos = F.begin();
Chandler Carruth7a715da2015-03-05 03:19:05 +00001238 for (MachineBasicBlock *ChainBB : FunctionChain) {
1239 DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
1240 : " ... ")
1241 << getBlockName(ChainBB) << "\n");
1242 if (InsertPos != MachineFunction::iterator(ChainBB))
1243 F.splice(InsertPos, ChainBB);
Chandler Carruth8d150782011-11-13 11:20:44 +00001244 else
1245 ++InsertPos;
1246
1247 // Update the terminator of the previous block.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001248 if (ChainBB == *FunctionChain.begin())
Chandler Carruth8d150782011-11-13 11:20:44 +00001249 continue;
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001250 MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB));
Chandler Carruth8d150782011-11-13 11:20:44 +00001251
Chandler Carruth10281422011-10-21 06:46:38 +00001252 // FIXME: It would be awesome of updateTerminator would just return rather
1253 // than assert when the branch cannot be analyzed in order to remove this
1254 // boiler plate.
1255 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001256 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Manman Ren2b6a0df2012-07-31 01:11:07 +00001257 if (!TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001258 // The "PrevBB" is not yet updated to reflect current code layout, so,
1259 // o. it may fall-through to a block without explict "goto" instruction
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001260 // before layout, and no longer fall-through it after layout; or
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001261 // o. just opposite.
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001262 //
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001263 // AnalyzeBranch() may return erroneous value for FBB when these two
1264 // situations take place. For the first scenario FBB is mistakenly set
1265 // NULL; for the 2nd scenario, the FBB, which is expected to be NULL,
1266 // is mistakenly pointing to "*BI".
1267 //
1268 bool needUpdateBr = true;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001269 if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001270 PrevBB->updateTerminator();
1271 needUpdateBr = false;
1272 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001273 TBB = FBB = nullptr;
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001274 if (TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
1275 // FIXME: This should never take place.
Craig Topperc0196b12014-04-14 00:51:57 +00001276 TBB = FBB = nullptr;
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001277 }
1278 }
1279
Manman Ren2b6a0df2012-07-31 01:11:07 +00001280 // If PrevBB has a two-way branch, try to re-order the branches
Cong Houd97c1002015-12-01 05:29:22 +00001281 // such that we branch to the successor with higher probability first.
Manman Ren2b6a0df2012-07-31 01:11:07 +00001282 if (TBB && !Cond.empty() && FBB &&
Cong Houd97c1002015-12-01 05:29:22 +00001283 MBPI->getEdgeProbability(PrevBB, FBB) >
1284 MBPI->getEdgeProbability(PrevBB, TBB) &&
Manman Ren2b6a0df2012-07-31 01:11:07 +00001285 !TII->ReverseBranchCondition(Cond)) {
1286 DEBUG(dbgs() << "Reverse order of the two branches: "
1287 << getBlockName(PrevBB) << "\n");
Cong Houd97c1002015-12-01 05:29:22 +00001288 DEBUG(dbgs() << " Edge probability: "
1289 << MBPI->getEdgeProbability(PrevBB, FBB) << " vs "
1290 << MBPI->getEdgeProbability(PrevBB, TBB) << "\n");
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001291 DebugLoc dl; // FIXME: this is nowhere
Manman Ren2b6a0df2012-07-31 01:11:07 +00001292 TII->RemoveBranch(*PrevBB);
1293 TII->InsertBranch(*PrevBB, FBB, TBB, Cond, dl);
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001294 needUpdateBr = true;
Manman Ren2b6a0df2012-07-31 01:11:07 +00001295 }
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001296 if (needUpdateBr)
1297 PrevBB->updateTerminator();
Manman Ren2b6a0df2012-07-31 01:11:07 +00001298 }
Chandler Carruth10281422011-10-21 06:46:38 +00001299 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001300
1301 // Fixup the last block.
1302 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001303 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Chandler Carruth8d150782011-11-13 11:20:44 +00001304 if (!TII->AnalyzeBranch(F.back(), TBB, FBB, Cond))
1305 F.back().updateTerminator();
Chandler Carruth10281422011-10-21 06:46:38 +00001306
Chandler Carruthccc7e422012-04-16 01:12:56 +00001307 // Walk through the backedges of the function now that we have fully laid out
1308 // the basic blocks and align the destination of each backedge. We don't rely
Chandler Carruth881d0a72012-08-07 09:45:24 +00001309 // exclusively on the loop info here so that we can align backedges in
1310 // unnatural CFGs and backedges that were introduced purely because of the
1311 // loop rotations done during this layout pass.
Sanjay Patel924879a2015-08-04 15:49:57 +00001312 // FIXME: Use Function::optForSize().
Duncan P. N. Exon Smith70eb9c52015-02-14 01:44:41 +00001313 if (F.getFunction()->hasFnAttribute(Attribute::OptimizeForSize))
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001314 return;
Chandler Carruth881d0a72012-08-07 09:45:24 +00001315 if (FunctionChain.begin() == FunctionChain.end())
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001316 return; // Empty chain.
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001317
Chandler Carruth881d0a72012-08-07 09:45:24 +00001318 const BranchProbability ColdProb(1, 5); // 20%
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001319 BlockFrequency EntryFreq = MBFI->getBlockFreq(&F.front());
Chandler Carruth881d0a72012-08-07 09:45:24 +00001320 BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001321 for (MachineBasicBlock *ChainBB : FunctionChain) {
1322 if (ChainBB == *FunctionChain.begin())
1323 continue;
1324
Chandler Carruth881d0a72012-08-07 09:45:24 +00001325 // Don't align non-looping basic blocks. These are unlikely to execute
1326 // enough times to matter in practice. Note that we'll still handle
1327 // unnatural CFGs inside of a natural outer loop (the common case) and
1328 // rotated loops.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001329 MachineLoop *L = MLI->getLoopFor(ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001330 if (!L)
1331 continue;
1332
Hal Finkel57725662015-01-03 17:58:24 +00001333 unsigned Align = TLI->getPrefLoopAlignment(L);
1334 if (!Align)
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001335 continue; // Don't care about loop alignment.
Hal Finkel57725662015-01-03 17:58:24 +00001336
Chandler Carruth881d0a72012-08-07 09:45:24 +00001337 // If the block is cold relative to the function entry don't waste space
1338 // aligning it.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001339 BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001340 if (Freq < WeightedEntryFreq)
1341 continue;
1342
1343 // If the block is cold relative to its loop header, don't align it
1344 // regardless of what edges into the block exist.
1345 MachineBasicBlock *LoopHeader = L->getHeader();
1346 BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
1347 if (Freq < (LoopHeaderFreq * ColdProb))
1348 continue;
1349
1350 // Check for the existence of a non-layout predecessor which would benefit
1351 // from aligning this block.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001352 MachineBasicBlock *LayoutPred =
1353 &*std::prev(MachineFunction::iterator(ChainBB));
Chandler Carruth881d0a72012-08-07 09:45:24 +00001354
1355 // Force alignment if all the predecessors are jumps. We already checked
1356 // that the block isn't cold above.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001357 if (!LayoutPred->isSuccessor(ChainBB)) {
1358 ChainBB->setAlignment(Align);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001359 continue;
1360 }
1361
1362 // Align this block if the layout predecessor's edge into this block is
Nadav Rotem6036f582013-03-29 16:34:23 +00001363 // cold relative to the block. When this is true, other predecessors make up
Chandler Carruth881d0a72012-08-07 09:45:24 +00001364 // all of the hot entries into the block and thus alignment is likely to be
1365 // important.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001366 BranchProbability LayoutProb =
1367 MBPI->getEdgeProbability(LayoutPred, ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001368 BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
1369 if (LayoutEdgeFreq <= (Freq * ColdProb))
Chandler Carruth7a715da2015-03-05 03:19:05 +00001370 ChainBB->setAlignment(Align);
Chandler Carruthccc7e422012-04-16 01:12:56 +00001371 }
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001372}
1373
Chandler Carruth10281422011-10-21 06:46:38 +00001374bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &F) {
1375 // Check for single-block functions and skip them.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001376 if (std::next(F.begin()) == F.end())
Chandler Carruth10281422011-10-21 06:46:38 +00001377 return false;
1378
Paul Robinson7c99ec52014-03-31 17:43:35 +00001379 if (skipOptnoneFunction(*F.getFunction()))
1380 return false;
1381
Chandler Carruth10281422011-10-21 06:46:38 +00001382 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1383 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001384 MLI = &getAnalysis<MachineLoopInfo>();
Eric Christopherfc6de422014-08-05 02:39:49 +00001385 TII = F.getSubtarget().getInstrInfo();
1386 TLI = F.getSubtarget().getTargetLowering();
Daniel Jasper471e8562015-03-04 11:05:34 +00001387 MDT = &getAnalysis<MachineDominatorTree>();
Chandler Carruth10281422011-10-21 06:46:38 +00001388 assert(BlockToChain.empty());
Chandler Carruth10281422011-10-21 06:46:38 +00001389
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001390 buildCFGChains(F);
Chandler Carruth10281422011-10-21 06:46:38 +00001391
Chandler Carruth10281422011-10-21 06:46:38 +00001392 BlockToChain.clear();
Chandler Carruthfd9b4d92011-11-14 10:57:23 +00001393 ChainAllocator.DestroyAll();
Chandler Carruth10281422011-10-21 06:46:38 +00001394
Nadav Rotemc0adc9f2013-04-12 01:24:16 +00001395 if (AlignAllBlock)
1396 // Align all of the blocks in the function to a specific alignment.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001397 for (MachineBasicBlock &MBB : F)
1398 MBB.setAlignment(AlignAllBlock);
Geoff Berry10494ac2016-01-21 17:25:52 +00001399 else if (AlignAllNonFallThruBlocks) {
1400 // Align all of the blocks that have no fall-through predecessors to a
1401 // specific alignment.
1402 for (auto MBI = std::next(F.begin()), MBE = F.end(); MBI != MBE; ++MBI) {
1403 auto LayoutPred = std::prev(MBI);
1404 if (!LayoutPred->isSuccessor(&*MBI))
1405 MBI->setAlignment(AlignAllNonFallThruBlocks);
1406 }
1407 }
Nadav Rotemc0adc9f2013-04-12 01:24:16 +00001408
Chandler Carruth10281422011-10-21 06:46:38 +00001409 // We always return true as we have no way to track whether the final order
1410 // differs from the original order.
1411 return true;
1412}
Chandler Carruthae4e8002011-11-02 07:17:12 +00001413
1414namespace {
1415/// \brief A pass to compute block placement statistics.
1416///
1417/// A separate pass to compute interesting statistics for evaluating block
1418/// placement. This is separate from the actual placement pass so that they can
Benjamin Kramerbde91762012-06-02 10:20:22 +00001419/// be computed in the absence of any placement transformations or when using
Chandler Carruthae4e8002011-11-02 07:17:12 +00001420/// alternative placement strategies.
1421class MachineBlockPlacementStats : public MachineFunctionPass {
1422 /// \brief A handle to the branch probability pass.
1423 const MachineBranchProbabilityInfo *MBPI;
1424
1425 /// \brief A handle to the function-wide block frequency pass.
1426 const MachineBlockFrequencyInfo *MBFI;
1427
1428public:
1429 static char ID; // Pass identification, replacement for typeid
1430 MachineBlockPlacementStats() : MachineFunctionPass(ID) {
1431 initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
1432 }
1433
Craig Topper4584cd52014-03-07 09:26:03 +00001434 bool runOnMachineFunction(MachineFunction &F) override;
Chandler Carruthae4e8002011-11-02 07:17:12 +00001435
Craig Topper4584cd52014-03-07 09:26:03 +00001436 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruthae4e8002011-11-02 07:17:12 +00001437 AU.addRequired<MachineBranchProbabilityInfo>();
1438 AU.addRequired<MachineBlockFrequencyInfo>();
1439 AU.setPreservesAll();
1440 MachineFunctionPass::getAnalysisUsage(AU);
1441 }
Chandler Carruthae4e8002011-11-02 07:17:12 +00001442};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001443}
Chandler Carruthae4e8002011-11-02 07:17:12 +00001444
1445char MachineBlockPlacementStats::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +00001446char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
Chandler Carruthae4e8002011-11-02 07:17:12 +00001447INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
1448 "Basic Block Placement Stats", false, false)
1449INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
1450INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
1451INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
1452 "Basic Block Placement Stats", false, false)
1453
Chandler Carruthae4e8002011-11-02 07:17:12 +00001454bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
1455 // Check for single-block functions and skip them.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001456 if (std::next(F.begin()) == F.end())
Chandler Carruthae4e8002011-11-02 07:17:12 +00001457 return false;
1458
1459 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1460 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1461
Chandler Carruth7a715da2015-03-05 03:19:05 +00001462 for (MachineBasicBlock &MBB : F) {
1463 BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001464 Statistic &NumBranches =
Chandler Carruth7a715da2015-03-05 03:19:05 +00001465 (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001466 Statistic &BranchTakenFreq =
Chandler Carruth7a715da2015-03-05 03:19:05 +00001467 (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
1468 for (MachineBasicBlock *Succ : MBB.successors()) {
Chandler Carruthae4e8002011-11-02 07:17:12 +00001469 // Skip if this successor is a fallthrough.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001470 if (MBB.isLayoutSuccessor(Succ))
Chandler Carruthae4e8002011-11-02 07:17:12 +00001471 continue;
1472
Chandler Carruth7a715da2015-03-05 03:19:05 +00001473 BlockFrequency EdgeFreq =
1474 BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
Chandler Carruthae4e8002011-11-02 07:17:12 +00001475 ++NumBranches;
1476 BranchTakenFreq += EdgeFreq.getFrequency();
1477 }
1478 }
1479
1480 return false;
1481}