blob: 779b84e99b8ddff0cf6029f07c22d6f14e5af4db [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"
36#include "llvm/CodeGen/MachineFunction.h"
Chandler Carruth10281422011-10-21 06:46:38 +000037#include "llvm/CodeGen/MachineFunctionPass.h"
Chandler Carruth8b9737c2011-10-21 08:57:37 +000038#include "llvm/CodeGen/MachineLoopInfo.h"
39#include "llvm/CodeGen/MachineModuleInfo.h"
Chandler Carruth10281422011-10-21 06:46:38 +000040#include "llvm/Support/Allocator.h"
Nadav Rotemc3b0f502013-04-12 00:48:32 +000041#include "llvm/Support/CommandLine.h"
Chandler Carruthbd1be4d2011-10-23 09:18:45 +000042#include "llvm/Support/Debug.h"
Chandler Carruth10281422011-10-21 06:46:38 +000043#include "llvm/Target/TargetInstrInfo.h"
Chandler Carruth8b9737c2011-10-21 08:57:37 +000044#include "llvm/Target/TargetLowering.h"
Eric Christopherd9134482014-08-04 21:25:23 +000045#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruth10281422011-10-21 06:46:38 +000046#include <algorithm>
47using namespace llvm;
48
Chandler Carruth1b9dde02014-04-22 02:02:50 +000049#define DEBUG_TYPE "block-placement2"
50
Chandler Carruthae4e8002011-11-02 07:17:12 +000051STATISTIC(NumCondBranches, "Number of conditional branches");
52STATISTIC(NumUncondBranches, "Number of uncondittional branches");
53STATISTIC(CondBranchTakenFreq,
54 "Potential frequency of taking conditional branches");
55STATISTIC(UncondBranchTakenFreq,
56 "Potential frequency of taking unconditional branches");
57
Nadav Rotemc3b0f502013-04-12 00:48:32 +000058static cl::opt<unsigned> AlignAllBlock("align-all-blocks",
59 cl::desc("Force the alignment of all "
60 "blocks in the function."),
61 cl::init(0), cl::Hidden);
62
Chandler Carruthe3288142015-01-14 20:19:29 +000063static cl::opt<bool> OnlyHotBadCFGConflictCheck(
64 "only-hot-bad-cfg-conflict-check",
65 cl::desc("Only check that a hot successor doesn't have a hot predecessor."),
66 cl::init(false), cl::Hidden);
67
68static cl::opt<bool> NoBadCFGConflictCheck(
69 "no-bad-cfg-conflict-check",
70 cl::desc("Don't check whether a hot successor has a more important "
71 "predecessor."),
72 cl::init(false), cl::Hidden);
73
Benjamin Kramerc8160d62013-11-20 19:08:44 +000074// FIXME: Find a good default for this flag and remove the flag.
75static cl::opt<unsigned>
76ExitBlockBias("block-placement-exit-block-bias",
77 cl::desc("Block frequency percentage a loop exit block needs "
78 "over the original exit to be considered the new exit."),
79 cl::init(0), cl::Hidden);
80
Chandler Carruth10281422011-10-21 06:46:38 +000081namespace {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +000082class BlockChain;
Chandler Carruth10281422011-10-21 06:46:38 +000083/// \brief Type for our function-wide basic block -> block chain mapping.
84typedef DenseMap<MachineBasicBlock *, BlockChain *> BlockToChainMapType;
85}
86
87namespace {
88/// \brief A chain of blocks which will be laid out contiguously.
89///
90/// This is the datastructure representing a chain of consecutive blocks that
91/// are profitable to layout together in order to maximize fallthrough
Chandler Carruth9139f442012-06-26 05:16:37 +000092/// probabilities and code locality. We also can use a block chain to represent
93/// a sequence of basic blocks which have some external (correctness)
94/// requirement for sequential layout.
Chandler Carruth10281422011-10-21 06:46:38 +000095///
Chandler Carruth9139f442012-06-26 05:16:37 +000096/// Chains can be built around a single basic block and can be merged to grow
97/// them. They participate in a block-to-chain mapping, which is updated
98/// automatically as chains are merged together.
Chandler Carruthbd1be4d2011-10-23 09:18:45 +000099class BlockChain {
100 /// \brief The sequence of blocks belonging to this chain.
Chandler Carruth10281422011-10-21 06:46:38 +0000101 ///
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000102 /// This is the sequence of blocks for a particular chain. These will be laid
103 /// out in-order within the function.
104 SmallVector<MachineBasicBlock *, 4> Blocks;
Chandler Carruth10281422011-10-21 06:46:38 +0000105
106 /// \brief A handle to the function-wide basic block to block chain mapping.
107 ///
108 /// This is retained in each block chain to simplify the computation of child
109 /// block chains for SCC-formation and iteration. We store the edges to child
110 /// basic blocks, and map them back to their associated chains using this
111 /// structure.
112 BlockToChainMapType &BlockToChain;
113
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000114public:
Chandler Carruth10281422011-10-21 06:46:38 +0000115 /// \brief Construct a new BlockChain.
116 ///
117 /// This builds a new block chain representing a single basic block in the
118 /// function. It also registers itself as the chain that block participates
119 /// in with the BlockToChain mapping.
120 BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
Chandler Carruth8d150782011-11-13 11:20:44 +0000121 : Blocks(1, BB), BlockToChain(BlockToChain), LoopPredecessors(0) {
Chandler Carruth10281422011-10-21 06:46:38 +0000122 assert(BB && "Cannot create a chain with a null basic block");
123 BlockToChain[BB] = this;
124 }
125
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000126 /// \brief Iterator over blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000127 typedef SmallVectorImpl<MachineBasicBlock *>::iterator iterator;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000128
129 /// \brief Beginning of blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000130 iterator begin() { return Blocks.begin(); }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000131
132 /// \brief End of blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000133 iterator end() { return Blocks.end(); }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000134
135 /// \brief Merge a block chain into this one.
Chandler Carruth10281422011-10-21 06:46:38 +0000136 ///
137 /// This routine merges a block chain into this one. It takes care of forming
138 /// a contiguous sequence of basic blocks, updating the edge list, and
139 /// updating the block -> chain mapping. It does not free or tear down the
140 /// old chain, but the old chain's block list is no longer valid.
Jakub Staszak90616162011-12-21 23:02:08 +0000141 void merge(MachineBasicBlock *BB, BlockChain *Chain) {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000142 assert(BB);
143 assert(!Blocks.empty());
Chandler Carruth10281422011-10-21 06:46:38 +0000144
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000145 // Fast path in case we don't have a chain already.
146 if (!Chain) {
147 assert(!BlockToChain[BB]);
148 Blocks.push_back(BB);
149 BlockToChain[BB] = this;
150 return;
Chandler Carruth10281422011-10-21 06:46:38 +0000151 }
152
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000153 assert(BB == *Chain->begin());
154 assert(Chain->begin() != Chain->end());
Chandler Carruth10281422011-10-21 06:46:38 +0000155
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000156 // Update the incoming blocks to point to this chain, and add them to the
157 // chain structure.
158 for (BlockChain::iterator BI = Chain->begin(), BE = Chain->end();
159 BI != BE; ++BI) {
160 Blocks.push_back(*BI);
161 assert(BlockToChain[*BI] == Chain && "Incoming blocks not in chain");
162 BlockToChain[*BI] = this;
163 }
Chandler Carruth10281422011-10-21 06:46:38 +0000164 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000165
Chandler Carruth49158902012-04-08 14:37:01 +0000166#ifndef NDEBUG
167 /// \brief Dump the blocks in this chain.
Nico Weber7408c702014-01-03 22:53:37 +0000168 LLVM_DUMP_METHOD void dump() {
Chandler Carruth49158902012-04-08 14:37:01 +0000169 for (iterator I = begin(), E = end(); I != E; ++I)
170 (*I)->dump();
171 }
172#endif // NDEBUG
173
Chandler Carruth8d150782011-11-13 11:20:44 +0000174 /// \brief Count of predecessors within the loop currently being processed.
175 ///
176 /// This count is updated at each loop we process to represent the number of
177 /// in-loop predecessors of this chain.
178 unsigned LoopPredecessors;
Chandler Carruth10281422011-10-21 06:46:38 +0000179};
180}
181
182namespace {
183class MachineBlockPlacement : public MachineFunctionPass {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000184 /// \brief A typedef for a block filter set.
185 typedef SmallPtrSet<MachineBasicBlock *, 16> BlockFilterSet;
186
Chandler Carruth10281422011-10-21 06:46:38 +0000187 /// \brief A handle to the branch probability pass.
188 const MachineBranchProbabilityInfo *MBPI;
189
190 /// \brief A handle to the function-wide block frequency pass.
191 const MachineBlockFrequencyInfo *MBFI;
192
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000193 /// \brief A handle to the loop info.
194 const MachineLoopInfo *MLI;
195
Chandler Carruth10281422011-10-21 06:46:38 +0000196 /// \brief A handle to the target's instruction info.
197 const TargetInstrInfo *TII;
198
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000199 /// \brief A handle to the target's lowering info.
Benjamin Kramer56b31bd2013-01-11 20:05:37 +0000200 const TargetLoweringBase *TLI;
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000201
Chandler Carruth10281422011-10-21 06:46:38 +0000202 /// \brief Allocator and owner of BlockChain structures.
203 ///
Chandler Carruth9139f442012-06-26 05:16:37 +0000204 /// We build BlockChains lazily while processing the loop structure of
205 /// a function. To reduce malloc traffic, we allocate them using this
206 /// slab-like allocator, and destroy them after the pass completes. An
207 /// important guarantee is that this allocator produces stable pointers to
208 /// the chains.
Chandler Carruth10281422011-10-21 06:46:38 +0000209 SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
210
211 /// \brief Function wide BasicBlock to BlockChain mapping.
212 ///
213 /// This mapping allows efficiently moving from any given basic block to the
214 /// BlockChain it participates in, if any. We use it to, among other things,
215 /// allow implicitly defining edges between chains as the existing edges
216 /// between basic blocks.
217 DenseMap<MachineBasicBlock *, BlockChain *> BlockToChain;
218
Jakub Staszak90616162011-12-21 23:02:08 +0000219 void markChainSuccessors(BlockChain &Chain,
220 MachineBasicBlock *LoopHeaderBB,
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000221 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
Craig Topperc0196b12014-04-14 00:51:57 +0000222 const BlockFilterSet *BlockFilter = nullptr);
Jakub Staszak90616162011-12-21 23:02:08 +0000223 MachineBasicBlock *selectBestSuccessor(MachineBasicBlock *BB,
224 BlockChain &Chain,
225 const BlockFilterSet *BlockFilter);
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000226 MachineBasicBlock *selectBestCandidateBlock(
Jakub Staszak90616162011-12-21 23:02:08 +0000227 BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList,
228 const BlockFilterSet *BlockFilter);
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000229 MachineBasicBlock *getFirstUnplacedBlock(
230 MachineFunction &F,
231 const BlockChain &PlacedChain,
232 MachineFunction::iterator &PrevUnplacedBlockIt,
Jakub Staszak90616162011-12-21 23:02:08 +0000233 const BlockFilterSet *BlockFilter);
Chandler Carruth8d150782011-11-13 11:20:44 +0000234 void buildChain(MachineBasicBlock *BB, BlockChain &Chain,
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000235 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
Craig Topperc0196b12014-04-14 00:51:57 +0000236 const BlockFilterSet *BlockFilter = nullptr);
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000237 MachineBasicBlock *findBestLoopTop(MachineLoop &L,
238 const BlockFilterSet &LoopBlockSet);
Chandler Carruthccc7e422012-04-16 01:12:56 +0000239 MachineBasicBlock *findBestLoopExit(MachineFunction &F,
240 MachineLoop &L,
241 const BlockFilterSet &LoopBlockSet);
Jakub Staszak90616162011-12-21 23:02:08 +0000242 void buildLoopChains(MachineFunction &F, MachineLoop &L);
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000243 void rotateLoop(BlockChain &LoopChain, MachineBasicBlock *ExitingBB,
244 const BlockFilterSet &LoopBlockSet);
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000245 void buildCFGChains(MachineFunction &F);
Chandler Carruth10281422011-10-21 06:46:38 +0000246
247public:
248 static char ID; // Pass identification, replacement for typeid
249 MachineBlockPlacement() : MachineFunctionPass(ID) {
250 initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
251 }
252
Craig Topper4584cd52014-03-07 09:26:03 +0000253 bool runOnMachineFunction(MachineFunction &F) override;
Chandler Carruth10281422011-10-21 06:46:38 +0000254
Craig Topper4584cd52014-03-07 09:26:03 +0000255 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth10281422011-10-21 06:46:38 +0000256 AU.addRequired<MachineBranchProbabilityInfo>();
257 AU.addRequired<MachineBlockFrequencyInfo>();
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000258 AU.addRequired<MachineLoopInfo>();
Chandler Carruth10281422011-10-21 06:46:38 +0000259 MachineFunctionPass::getAnalysisUsage(AU);
260 }
Chandler Carruth10281422011-10-21 06:46:38 +0000261};
262}
263
264char MachineBlockPlacement::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000265char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
Chandler Carruth10281422011-10-21 06:46:38 +0000266INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement2",
267 "Branch Probability Basic Block Placement", false, false)
268INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
269INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000270INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
Chandler Carruth10281422011-10-21 06:46:38 +0000271INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement2",
272 "Branch Probability Basic Block Placement", false, false)
273
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000274#ifndef NDEBUG
275/// \brief Helper to print the name of a MBB.
276///
277/// Only used by debug logging.
Jakub Staszak90616162011-12-21 23:02:08 +0000278static std::string getBlockName(MachineBasicBlock *BB) {
Alp Tokere69170a2014-06-26 22:52:05 +0000279 std::string Result;
280 raw_string_ostream OS(Result);
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000281 OS << "BB#" << BB->getNumber()
282 << " (derived from LLVM BB '" << BB->getName() << "')";
Alp Tokere69170a2014-06-26 22:52:05 +0000283 OS.flush();
284 return Result;
Chandler Carruth10281422011-10-21 06:46:38 +0000285}
286
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000287/// \brief Helper to print the number of a MBB.
288///
289/// Only used by debug logging.
Jakub Staszak90616162011-12-21 23:02:08 +0000290static std::string getBlockNum(MachineBasicBlock *BB) {
Alp Tokere69170a2014-06-26 22:52:05 +0000291 std::string Result;
292 raw_string_ostream OS(Result);
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000293 OS << "BB#" << BB->getNumber();
Alp Tokere69170a2014-06-26 22:52:05 +0000294 OS.flush();
295 return Result;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000296}
297#endif
298
Chandler Carrutheb4ec3a2011-11-13 11:34:55 +0000299/// \brief Mark a chain's successors as having one fewer preds.
300///
301/// When a chain is being merged into the "placed" chain, this routine will
302/// quickly walk the successors of each block in the chain and mark them as
303/// having one fewer active predecessor. It also adds any successors of this
304/// chain which reach the zero-predecessor state to the worklist passed in.
Chandler Carruth8d150782011-11-13 11:20:44 +0000305void MachineBlockPlacement::markChainSuccessors(
Jakub Staszak90616162011-12-21 23:02:08 +0000306 BlockChain &Chain,
307 MachineBasicBlock *LoopHeaderBB,
Chandler Carruth8d150782011-11-13 11:20:44 +0000308 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
Jakub Staszak90616162011-12-21 23:02:08 +0000309 const BlockFilterSet *BlockFilter) {
Chandler Carruth8d150782011-11-13 11:20:44 +0000310 // Walk all the blocks in this chain, marking their successors as having
311 // a predecessor placed.
312 for (BlockChain::iterator CBI = Chain.begin(), CBE = Chain.end();
313 CBI != CBE; ++CBI) {
314 // Add any successors for which this is the only un-placed in-loop
315 // predecessor to the worklist as a viable candidate for CFG-neutral
316 // placement. No subsequent placement of this block will violate the CFG
317 // shape, so we get to use heuristics to choose a favorable placement.
318 for (MachineBasicBlock::succ_iterator SI = (*CBI)->succ_begin(),
319 SE = (*CBI)->succ_end();
320 SI != SE; ++SI) {
321 if (BlockFilter && !BlockFilter->count(*SI))
322 continue;
Jakub Staszak90616162011-12-21 23:02:08 +0000323 BlockChain &SuccChain = *BlockToChain[*SI];
Chandler Carruth8d150782011-11-13 11:20:44 +0000324 // Disregard edges within a fixed chain, or edges to the loop header.
325 if (&Chain == &SuccChain || *SI == LoopHeaderBB)
326 continue;
Chandler Carruth10281422011-10-21 06:46:38 +0000327
Chandler Carruth8d150782011-11-13 11:20:44 +0000328 // This is a cross-chain edge that is within the loop, so decrement the
329 // loop predecessor count of the destination chain.
330 if (SuccChain.LoopPredecessors > 0 && --SuccChain.LoopPredecessors == 0)
Chandler Carruthd394baf2011-11-24 08:46:04 +0000331 BlockWorkList.push_back(*SuccChain.begin());
Chandler Carruth10281422011-10-21 06:46:38 +0000332 }
333 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000334}
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000335
Chandler Carruthb3361722011-11-13 11:34:53 +0000336/// \brief Select the best successor for a block.
337///
338/// This looks across all successors of a particular block and attempts to
339/// select the "best" one to be the layout successor. It only considers direct
340/// successors which also pass the block filter. It will attempt to avoid
341/// breaking CFG structure, but cave and break such structures in the case of
342/// very hot successor edges.
343///
344/// \returns The best successor block found, or null if none are viable.
345MachineBasicBlock *MachineBlockPlacement::selectBestSuccessor(
Jakub Staszak90616162011-12-21 23:02:08 +0000346 MachineBasicBlock *BB, BlockChain &Chain,
347 const BlockFilterSet *BlockFilter) {
Chandler Carruthb3361722011-11-13 11:34:53 +0000348 const BranchProbability HotProb(4, 5); // 80%
349
Craig Topperc0196b12014-04-14 00:51:57 +0000350 MachineBasicBlock *BestSucc = nullptr;
Chandler Carruth84cd44c2011-11-14 09:12:57 +0000351 // FIXME: Due to the performance of the probability and weight routines in
352 // the MBPI analysis, we manually compute probabilities using the edge
353 // weights. This is suboptimal as it means that the somewhat subtle
354 // definition of edge weight semantics is encoded here as well. We should
Benjamin Kramerbde91762012-06-02 10:20:22 +0000355 // improve the MBPI interface to efficiently support query patterns such as
Chandler Carruth84cd44c2011-11-14 09:12:57 +0000356 // this.
357 uint32_t BestWeight = 0;
358 uint32_t WeightScale = 0;
359 uint32_t SumWeight = MBPI->getSumForBlock(BB, WeightScale);
Chandler Carruthb3361722011-11-13 11:34:53 +0000360 DEBUG(dbgs() << "Attempting merge from: " << getBlockName(BB) << "\n");
Jakub Staszak90616162011-12-21 23:02:08 +0000361 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
362 SE = BB->succ_end();
363 SI != SE; ++SI) {
Chandler Carruthb3361722011-11-13 11:34:53 +0000364 if (BlockFilter && !BlockFilter->count(*SI))
365 continue;
Jakub Staszak90616162011-12-21 23:02:08 +0000366 BlockChain &SuccChain = *BlockToChain[*SI];
Chandler Carruthb3361722011-11-13 11:34:53 +0000367 if (&SuccChain == &Chain) {
368 DEBUG(dbgs() << " " << getBlockName(*SI) << " -> Already merged!\n");
369 continue;
370 }
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +0000371 if (*SI != *SuccChain.begin()) {
372 DEBUG(dbgs() << " " << getBlockName(*SI) << " -> Mid chain!\n");
373 continue;
374 }
Chandler Carruthb3361722011-11-13 11:34:53 +0000375
Chandler Carruth84cd44c2011-11-14 09:12:57 +0000376 uint32_t SuccWeight = MBPI->getEdgeWeight(BB, *SI);
377 BranchProbability SuccProb(SuccWeight / WeightScale, SumWeight);
Chandler Carruthb3361722011-11-13 11:34:53 +0000378
379 // Only consider successors which are either "hot", or wouldn't violate
380 // any CFG constraints.
Chandler Carruth18dfac32011-11-20 11:22:06 +0000381 if (SuccChain.LoopPredecessors != 0) {
382 if (SuccProb < HotProb) {
Chandler Carruth260258b2013-11-25 00:43:41 +0000383 DEBUG(dbgs() << " " << getBlockName(*SI) << " -> " << SuccProb
384 << " (prob) (CFG conflict)\n");
Chandler Carruth18dfac32011-11-20 11:22:06 +0000385 continue;
386 }
387
Chandler Carruthe3288142015-01-14 20:19:29 +0000388 if (!NoBadCFGConflictCheck) {
389 // Make sure that a hot successor doesn't have a globally more
390 // important predecessor.
391 BlockFrequency CandidateEdgeFreq =
392 OnlyHotBadCFGConflictCheck
393 ? MBFI->getBlockFreq(BB) * SuccProb
394 : MBFI->getBlockFreq(BB) * SuccProb * HotProb.getCompl();
395 bool BadCFGConflict = false;
396 for (MachineBasicBlock::pred_iterator PI = (*SI)->pred_begin(),
397 PE = (*SI)->pred_end();
398 PI != PE; ++PI) {
399 if (*PI == *SI || (BlockFilter && !BlockFilter->count(*PI)) ||
400 BlockToChain[*PI] == &Chain)
401 continue;
402 BlockFrequency PredEdgeFreq =
403 MBFI->getBlockFreq(*PI) * MBPI->getEdgeProbability(*PI, *SI);
404 if (PredEdgeFreq >= CandidateEdgeFreq) {
405 BadCFGConflict = true;
406 break;
407 }
Chandler Carruth18dfac32011-11-20 11:22:06 +0000408 }
Chandler Carruthe3288142015-01-14 20:19:29 +0000409 if (BadCFGConflict) {
410 DEBUG(dbgs() << " " << getBlockName(*SI) << " -> " << SuccProb
411 << " (prob) (non-cold CFG conflict)\n");
412 continue;
413 }
Chandler Carruth18dfac32011-11-20 11:22:06 +0000414 }
Chandler Carruthb3361722011-11-13 11:34:53 +0000415 }
416
417 DEBUG(dbgs() << " " << getBlockName(*SI) << " -> " << SuccProb
418 << " (prob)"
419 << (SuccChain.LoopPredecessors != 0 ? " (CFG break)" : "")
420 << "\n");
Chandler Carruth84cd44c2011-11-14 09:12:57 +0000421 if (BestSucc && BestWeight >= SuccWeight)
Chandler Carruthb3361722011-11-13 11:34:53 +0000422 continue;
423 BestSucc = *SI;
Chandler Carruth84cd44c2011-11-14 09:12:57 +0000424 BestWeight = SuccWeight;
Chandler Carruthb3361722011-11-13 11:34:53 +0000425 }
426 return BestSucc;
427}
428
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000429/// \brief Select the best block from a worklist.
430///
431/// This looks through the provided worklist as a list of candidate basic
432/// blocks and select the most profitable one to place. The definition of
433/// profitable only really makes sense in the context of a loop. This returns
434/// the most frequently visited block in the worklist, which in the case of
435/// a loop, is the one most desirable to be physically close to the rest of the
436/// loop body in order to improve icache behavior.
437///
438/// \returns The best block found, or null if none are viable.
439MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
Jakub Staszak90616162011-12-21 23:02:08 +0000440 BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList,
441 const BlockFilterSet *BlockFilter) {
Chandler Carruth0af6a0b2011-11-14 09:46:33 +0000442 // Once we need to walk the worklist looking for a candidate, cleanup the
443 // worklist of already placed entries.
444 // FIXME: If this shows up on profiles, it could be folded (at the cost of
445 // some code complexity) into the loop below.
446 WorkList.erase(std::remove_if(WorkList.begin(), WorkList.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000447 [&](MachineBasicBlock *BB) {
448 return BlockToChain.lookup(BB) == &Chain;
449 }),
Chandler Carruth0af6a0b2011-11-14 09:46:33 +0000450 WorkList.end());
451
Craig Topperc0196b12014-04-14 00:51:57 +0000452 MachineBasicBlock *BestBlock = nullptr;
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000453 BlockFrequency BestFreq;
454 for (SmallVectorImpl<MachineBasicBlock *>::iterator WBI = WorkList.begin(),
455 WBE = WorkList.end();
456 WBI != WBE; ++WBI) {
Jakub Staszak90616162011-12-21 23:02:08 +0000457 BlockChain &SuccChain = *BlockToChain[*WBI];
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000458 if (&SuccChain == &Chain) {
459 DEBUG(dbgs() << " " << getBlockName(*WBI)
460 << " -> Already merged!\n");
461 continue;
462 }
463 assert(SuccChain.LoopPredecessors == 0 && "Found CFG-violating block");
464
465 BlockFrequency CandidateFreq = MBFI->getBlockFreq(*WBI);
Michael Gottesmanb78dec82013-12-14 00:25:45 +0000466 DEBUG(dbgs() << " " << getBlockName(*WBI) << " -> ";
467 MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000468 if (BestBlock && BestFreq >= CandidateFreq)
469 continue;
470 BestBlock = *WBI;
471 BestFreq = CandidateFreq;
472 }
473 return BestBlock;
474}
475
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000476/// \brief Retrieve the first unplaced basic block.
477///
478/// This routine is called when we are unable to use the CFG to walk through
479/// all of the basic blocks and form a chain due to unnatural loops in the CFG.
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000480/// We walk through the function's blocks in order, starting from the
481/// LastUnplacedBlockIt. We update this iterator on each call to avoid
482/// re-scanning the entire sequence on repeated calls to this routine.
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000483MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000484 MachineFunction &F, const BlockChain &PlacedChain,
485 MachineFunction::iterator &PrevUnplacedBlockIt,
Jakub Staszak90616162011-12-21 23:02:08 +0000486 const BlockFilterSet *BlockFilter) {
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000487 for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F.end(); I != E;
488 ++I) {
489 if (BlockFilter && !BlockFilter->count(I))
490 continue;
Jakub Staszak90616162011-12-21 23:02:08 +0000491 if (BlockToChain[I] != &PlacedChain) {
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000492 PrevUnplacedBlockIt = I;
Chandler Carruth4a87aa02011-11-23 03:03:21 +0000493 // Now select the head of the chain to which the unplaced block belongs
494 // as the block to place. This will force the entire chain to be placed,
495 // and satisfies the requirements of merging chains.
Jakub Staszak90616162011-12-21 23:02:08 +0000496 return *BlockToChain[I]->begin();
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000497 }
498 }
Craig Topperc0196b12014-04-14 00:51:57 +0000499 return nullptr;
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000500}
501
Chandler Carruth8d150782011-11-13 11:20:44 +0000502void MachineBlockPlacement::buildChain(
503 MachineBasicBlock *BB,
504 BlockChain &Chain,
505 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
Jakub Staszak90616162011-12-21 23:02:08 +0000506 const BlockFilterSet *BlockFilter) {
Chandler Carruth8d150782011-11-13 11:20:44 +0000507 assert(BB);
Jakub Staszak90616162011-12-21 23:02:08 +0000508 assert(BlockToChain[BB] == &Chain);
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000509 MachineFunction &F = *BB->getParent();
510 MachineFunction::iterator PrevUnplacedBlockIt = F.begin();
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000511
Chandler Carruth8d150782011-11-13 11:20:44 +0000512 MachineBasicBlock *LoopHeaderBB = BB;
513 markChainSuccessors(Chain, LoopHeaderBB, BlockWorkList, BlockFilter);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000514 BB = *std::prev(Chain.end());
Chandler Carruth8d150782011-11-13 11:20:44 +0000515 for (;;) {
516 assert(BB);
Jakub Staszak90616162011-12-21 23:02:08 +0000517 assert(BlockToChain[BB] == &Chain);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000518 assert(*std::prev(Chain.end()) == BB);
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000519
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +0000520 // Look for the best viable successor if there is one to place immediately
521 // after this block.
Duncan Sands291d47e2012-09-14 09:00:11 +0000522 MachineBasicBlock *BestSucc = selectBestSuccessor(BB, Chain, BlockFilter);
Chandler Carruth8d150782011-11-13 11:20:44 +0000523
524 // If an immediate successor isn't available, look for the best viable
525 // block among those we've identified as not violating the loop's CFG at
526 // this point. This won't be a fallthrough, but it will increase locality.
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000527 if (!BestSucc)
528 BestSucc = selectBestCandidateBlock(Chain, BlockWorkList, BlockFilter);
Chandler Carruth8d150782011-11-13 11:20:44 +0000529
Chandler Carruth8d150782011-11-13 11:20:44 +0000530 if (!BestSucc) {
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000531 BestSucc = getFirstUnplacedBlock(F, Chain, PrevUnplacedBlockIt,
532 BlockFilter);
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000533 if (!BestSucc)
534 break;
535
536 DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
537 "layout successor until the CFG reduces\n");
Chandler Carruth8d150782011-11-13 11:20:44 +0000538 }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000539
Chandler Carruth8d150782011-11-13 11:20:44 +0000540 // Place this block, updating the datastructures to reflect its placement.
Jakub Staszak90616162011-12-21 23:02:08 +0000541 BlockChain &SuccChain = *BlockToChain[BestSucc];
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000542 // Zero out LoopPredecessors for the successor we're about to merge in case
543 // we selected a successor that didn't fit naturally into the CFG.
544 SuccChain.LoopPredecessors = 0;
Chandler Carruth8d150782011-11-13 11:20:44 +0000545 DEBUG(dbgs() << "Merging from " << getBlockNum(BB)
546 << " to " << getBlockNum(BestSucc) << "\n");
547 markChainSuccessors(SuccChain, LoopHeaderBB, BlockWorkList, BlockFilter);
548 Chain.merge(BestSucc, &SuccChain);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000549 BB = *std::prev(Chain.end());
Jakub Staszak190c7122011-12-07 19:46:10 +0000550 }
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000551
552 DEBUG(dbgs() << "Finished forming chain for header block "
553 << getBlockNum(*Chain.begin()) << "\n");
Chandler Carruth10281422011-10-21 06:46:38 +0000554}
555
Chandler Carruth03adbd42011-11-27 13:34:33 +0000556/// \brief Find the best loop top block for layout.
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000557///
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000558/// Look for a block which is strictly better than the loop header for laying
559/// out at the top of the loop. This looks for one and only one pattern:
560/// a latch block with no conditional exit. This block will cause a conditional
561/// jump around it or will be the bottom of the loop if we lay it out in place,
562/// but if it it doesn't end up at the bottom of the loop for any reason,
563/// rotation alone won't fix it. Because such a block will always result in an
564/// unconditional jump (for the backedge) rotating it in front of the loop
565/// header is always profitable.
566MachineBasicBlock *
567MachineBlockPlacement::findBestLoopTop(MachineLoop &L,
568 const BlockFilterSet &LoopBlockSet) {
569 // Check that the header hasn't been fused with a preheader block due to
570 // crazy branches. If it has, we need to start with the header at the top to
571 // prevent pulling the preheader into the loop body.
572 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
573 if (!LoopBlockSet.count(*HeaderChain.begin()))
574 return L.getHeader();
575
576 DEBUG(dbgs() << "Finding best loop top for: "
577 << getBlockName(L.getHeader()) << "\n");
578
579 BlockFrequency BestPredFreq;
Craig Topperc0196b12014-04-14 00:51:57 +0000580 MachineBasicBlock *BestPred = nullptr;
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000581 for (MachineBasicBlock::pred_iterator PI = L.getHeader()->pred_begin(),
582 PE = L.getHeader()->pred_end();
583 PI != PE; ++PI) {
584 MachineBasicBlock *Pred = *PI;
585 if (!LoopBlockSet.count(Pred))
586 continue;
587 DEBUG(dbgs() << " header pred: " << getBlockName(Pred) << ", "
Michael Gottesmanb78dec82013-12-14 00:25:45 +0000588 << Pred->succ_size() << " successors, ";
589 MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000590 if (Pred->succ_size() > 1)
591 continue;
592
593 BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
594 if (!BestPred || PredFreq > BestPredFreq ||
595 (!(PredFreq < BestPredFreq) &&
596 Pred->isLayoutSuccessor(L.getHeader()))) {
597 BestPred = Pred;
598 BestPredFreq = PredFreq;
599 }
600 }
601
602 // If no direct predecessor is fine, just use the loop header.
603 if (!BestPred)
604 return L.getHeader();
605
606 // Walk backwards through any straight line of predecessors.
607 while (BestPred->pred_size() == 1 &&
608 (*BestPred->pred_begin())->succ_size() == 1 &&
609 *BestPred->pred_begin() != L.getHeader())
610 BestPred = *BestPred->pred_begin();
611
612 DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n");
613 return BestPred;
614}
615
616
617/// \brief Find the best loop exiting block for layout.
618///
Chandler Carruth03adbd42011-11-27 13:34:33 +0000619/// This routine implements the logic to analyze the loop looking for the best
620/// block to layout at the top of the loop. Typically this is done to maximize
621/// fallthrough opportunities.
622MachineBasicBlock *
Chandler Carruthccc7e422012-04-16 01:12:56 +0000623MachineBlockPlacement::findBestLoopExit(MachineFunction &F,
624 MachineLoop &L,
625 const BlockFilterSet &LoopBlockSet) {
Chandler Carruth68062612012-04-10 13:35:57 +0000626 // We don't want to layout the loop linearly in all cases. If the loop header
627 // is just a normal basic block in the loop, we want to look for what block
628 // within the loop is the best one to layout at the top. However, if the loop
629 // header has be pre-merged into a chain due to predecessors not having
630 // analyzable branches, *and* the predecessor it is merged with is *not* part
631 // of the loop, rotating the header into the middle of the loop will create
632 // a non-contiguous range of blocks which is Very Bad. So start with the
633 // header and only rotate if safe.
634 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
635 if (!LoopBlockSet.count(*HeaderChain.begin()))
Craig Topperc0196b12014-04-14 00:51:57 +0000636 return nullptr;
Chandler Carruth68062612012-04-10 13:35:57 +0000637
Chandler Carruth03adbd42011-11-27 13:34:33 +0000638 BlockFrequency BestExitEdgeFreq;
Chandler Carruthccc7e422012-04-16 01:12:56 +0000639 unsigned BestExitLoopDepth = 0;
Craig Topperc0196b12014-04-14 00:51:57 +0000640 MachineBasicBlock *ExitingBB = nullptr;
Chandler Carruth4f567202011-11-27 20:18:00 +0000641 // If there are exits to outer loops, loop rotation can severely limit
642 // fallthrough opportunites unless it selects such an exit. Keep a set of
643 // blocks where rotating to exit with that block will reach an outer loop.
644 SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
645
Chandler Carruth03adbd42011-11-27 13:34:33 +0000646 DEBUG(dbgs() << "Finding best loop exit for: "
647 << getBlockName(L.getHeader()) << "\n");
648 for (MachineLoop::block_iterator I = L.block_begin(),
649 E = L.block_end();
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000650 I != E; ++I) {
Jakub Staszak90616162011-12-21 23:02:08 +0000651 BlockChain &Chain = *BlockToChain[*I];
Chandler Carruth03adbd42011-11-27 13:34:33 +0000652 // Ensure that this block is at the end of a chain; otherwise it could be
653 // mid-way through an inner loop or a successor of an analyzable branch.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000654 if (*I != *std::prev(Chain.end()))
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000655 continue;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000656
Chandler Carruth03adbd42011-11-27 13:34:33 +0000657 // Now walk the successors. We need to establish whether this has a viable
658 // exiting successor and whether it has a viable non-exiting successor.
659 // We store the old exiting state and restore it if a viable looping
660 // successor isn't found.
661 MachineBasicBlock *OldExitingBB = ExitingBB;
662 BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
Chandler Carruthccc7e422012-04-16 01:12:56 +0000663 bool HasLoopingSucc = false;
Chandler Carruth03adbd42011-11-27 13:34:33 +0000664 // FIXME: Due to the performance of the probability and weight routines in
Chandler Carruthccc7e422012-04-16 01:12:56 +0000665 // the MBPI analysis, we use the internal weights and manually compute the
666 // probabilities to avoid quadratic behavior.
Chandler Carruth03adbd42011-11-27 13:34:33 +0000667 uint32_t WeightScale = 0;
668 uint32_t SumWeight = MBPI->getSumForBlock(*I, WeightScale);
669 for (MachineBasicBlock::succ_iterator SI = (*I)->succ_begin(),
670 SE = (*I)->succ_end();
Chandler Carrutha0545802011-11-27 09:22:53 +0000671 SI != SE; ++SI) {
Chandler Carruth03adbd42011-11-27 13:34:33 +0000672 if ((*SI)->isLandingPad())
673 continue;
674 if (*SI == *I)
675 continue;
Jakub Staszak90616162011-12-21 23:02:08 +0000676 BlockChain &SuccChain = *BlockToChain[*SI];
Chandler Carruth03adbd42011-11-27 13:34:33 +0000677 // Don't split chains, either this chain or the successor's chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000678 if (&Chain == &SuccChain) {
679 DEBUG(dbgs() << " exiting: " << getBlockName(*I) << " -> "
Chandler Carruth03adbd42011-11-27 13:34:33 +0000680 << getBlockName(*SI) << " (chain conflict)\n");
681 continue;
682 }
683
684 uint32_t SuccWeight = MBPI->getEdgeWeight(*I, *SI);
685 if (LoopBlockSet.count(*SI)) {
686 DEBUG(dbgs() << " looping: " << getBlockName(*I) << " -> "
687 << getBlockName(*SI) << " (" << SuccWeight << ")\n");
Chandler Carruthccc7e422012-04-16 01:12:56 +0000688 HasLoopingSucc = true;
Chandler Carruth03adbd42011-11-27 13:34:33 +0000689 continue;
690 }
691
Chandler Carruthccc7e422012-04-16 01:12:56 +0000692 unsigned SuccLoopDepth = 0;
693 if (MachineLoop *ExitLoop = MLI->getLoopFor(*SI)) {
694 SuccLoopDepth = ExitLoop->getLoopDepth();
695 if (ExitLoop->contains(&L))
696 BlocksExitingToOuterLoop.insert(*I);
697 }
698
Chandler Carruth03adbd42011-11-27 13:34:33 +0000699 BranchProbability SuccProb(SuccWeight / WeightScale, SumWeight);
700 BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(*I) * SuccProb;
701 DEBUG(dbgs() << " exiting: " << getBlockName(*I) << " -> "
Chandler Carruthccc7e422012-04-16 01:12:56 +0000702 << getBlockName(*SI) << " [L:" << SuccLoopDepth
Michael Gottesmanb78dec82013-12-14 00:25:45 +0000703 << "] (";
704 MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
Benjamin Kramerc8160d62013-11-20 19:08:44 +0000705 // Note that we bias this toward an existing layout successor to retain
706 // incoming order in the absence of better information. The exit must have
707 // a frequency higher than the current exit before we consider breaking
708 // the layout.
709 BranchProbability Bias(100 - ExitBlockBias, 100);
Chandler Carruthccc7e422012-04-16 01:12:56 +0000710 if (!ExitingBB || BestExitLoopDepth < SuccLoopDepth ||
711 ExitEdgeFreq > BestExitEdgeFreq ||
Chandler Carruth03adbd42011-11-27 13:34:33 +0000712 ((*I)->isLayoutSuccessor(*SI) &&
Benjamin Kramerc8160d62013-11-20 19:08:44 +0000713 !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
Chandler Carruth03adbd42011-11-27 13:34:33 +0000714 BestExitEdgeFreq = ExitEdgeFreq;
715 ExitingBB = *I;
Chandler Carrutha0545802011-11-27 09:22:53 +0000716 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000717 }
Chandler Carruth03adbd42011-11-27 13:34:33 +0000718
719 // Restore the old exiting state, no viable looping successor was found.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000720 if (!HasLoopingSucc) {
Chandler Carruth03adbd42011-11-27 13:34:33 +0000721 ExitingBB = OldExitingBB;
722 BestExitEdgeFreq = OldBestExitEdgeFreq;
Chandler Carrutha0545802011-11-27 09:22:53 +0000723 continue;
Chandler Carruth03adbd42011-11-27 13:34:33 +0000724 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000725 }
Chandler Carruthccc7e422012-04-16 01:12:56 +0000726 // Without a candidate exiting block or with only a single block in the
Chandler Carruth03adbd42011-11-27 13:34:33 +0000727 // loop, just use the loop header to layout the loop.
728 if (!ExitingBB || L.getNumBlocks() == 1)
Craig Topperc0196b12014-04-14 00:51:57 +0000729 return nullptr;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000730
Chandler Carruth4f567202011-11-27 20:18:00 +0000731 // Also, if we have exit blocks which lead to outer loops but didn't select
732 // one of them as the exiting block we are rotating toward, disable loop
733 // rotation altogether.
734 if (!BlocksExitingToOuterLoop.empty() &&
735 !BlocksExitingToOuterLoop.count(ExitingBB))
Craig Topperc0196b12014-04-14 00:51:57 +0000736 return nullptr;
Chandler Carruth4f567202011-11-27 20:18:00 +0000737
Chandler Carruth03adbd42011-11-27 13:34:33 +0000738 DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB) << "\n");
Chandler Carruthccc7e422012-04-16 01:12:56 +0000739 return ExitingBB;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000740}
741
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000742/// \brief Attempt to rotate an exiting block to the bottom of the loop.
743///
744/// Once we have built a chain, try to rotate it to line up the hot exit block
745/// with fallthrough out of the loop if doing so doesn't introduce unnecessary
746/// branches. For example, if the loop has fallthrough into its header and out
747/// of its bottom already, don't rotate it.
748void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
749 MachineBasicBlock *ExitingBB,
750 const BlockFilterSet &LoopBlockSet) {
751 if (!ExitingBB)
752 return;
753
754 MachineBasicBlock *Top = *LoopChain.begin();
755 bool ViableTopFallthrough = false;
756 for (MachineBasicBlock::pred_iterator PI = Top->pred_begin(),
757 PE = Top->pred_end();
758 PI != PE; ++PI) {
759 BlockChain *PredChain = BlockToChain[*PI];
760 if (!LoopBlockSet.count(*PI) &&
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000761 (!PredChain || *PI == *std::prev(PredChain->end()))) {
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000762 ViableTopFallthrough = true;
763 break;
764 }
765 }
766
767 // If the header has viable fallthrough, check whether the current loop
768 // bottom is a viable exiting block. If so, bail out as rotating will
769 // introduce an unnecessary branch.
770 if (ViableTopFallthrough) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000771 MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000772 for (MachineBasicBlock::succ_iterator SI = Bottom->succ_begin(),
773 SE = Bottom->succ_end();
774 SI != SE; ++SI) {
775 BlockChain *SuccChain = BlockToChain[*SI];
776 if (!LoopBlockSet.count(*SI) &&
777 (!SuccChain || *SI == *SuccChain->begin()))
778 return;
779 }
780 }
781
782 BlockChain::iterator ExitIt = std::find(LoopChain.begin(), LoopChain.end(),
783 ExitingBB);
784 if (ExitIt == LoopChain.end())
785 return;
786
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000787 std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000788}
789
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000790/// \brief Forms basic block chains from the natural loop structures.
Chandler Carruth10281422011-10-21 06:46:38 +0000791///
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000792/// These chains are designed to preserve the existing *structure* of the code
793/// as much as possible. We can then stitch the chains together in a way which
794/// both preserves the topological structure and minimizes taken conditional
795/// branches.
Chandler Carruth8d150782011-11-13 11:20:44 +0000796void MachineBlockPlacement::buildLoopChains(MachineFunction &F,
Jakub Staszak90616162011-12-21 23:02:08 +0000797 MachineLoop &L) {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000798 // First recurse through any nested loops, building chains for those inner
799 // loops.
800 for (MachineLoop::iterator LI = L.begin(), LE = L.end(); LI != LE; ++LI)
801 buildLoopChains(F, **LI);
Chandler Carruth10281422011-10-21 06:46:38 +0000802
Chandler Carruth8d150782011-11-13 11:20:44 +0000803 SmallVector<MachineBasicBlock *, 16> BlockWorkList;
804 BlockFilterSet LoopBlockSet(L.block_begin(), L.block_end());
Chandler Carruth03adbd42011-11-27 13:34:33 +0000805
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000806 // First check to see if there is an obviously preferable top block for the
807 // loop. This will default to the header, but may end up as one of the
808 // predecessors to the header if there is one which will result in strictly
809 // fewer branches in the loop body.
810 MachineBasicBlock *LoopTop = findBestLoopTop(L, LoopBlockSet);
811
812 // If we selected just the header for the loop top, look for a potentially
813 // profitable exit block in the event that rotating the loop can eliminate
814 // branches by placing an exit edge at the bottom.
Craig Topperc0196b12014-04-14 00:51:57 +0000815 MachineBasicBlock *ExitingBB = nullptr;
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000816 if (LoopTop == L.getHeader())
817 ExitingBB = findBestLoopExit(F, L, LoopBlockSet);
818
819 BlockChain &LoopChain = *BlockToChain[LoopTop];
Chandler Carruth10281422011-10-21 06:46:38 +0000820
Chandler Carruth8d150782011-11-13 11:20:44 +0000821 // FIXME: This is a really lame way of walking the chains in the loop: we
822 // walk the blocks, and use a set to prevent visiting a particular chain
823 // twice.
Jakub Staszak90616162011-12-21 23:02:08 +0000824 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
Jakub Staszak190c7122011-12-07 19:46:10 +0000825 assert(LoopChain.LoopPredecessors == 0);
826 UpdatedPreds.insert(&LoopChain);
Chandler Carruth8d150782011-11-13 11:20:44 +0000827 for (MachineLoop::block_iterator BI = L.block_begin(),
828 BE = L.block_end();
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000829 BI != BE; ++BI) {
Jakub Staszak90616162011-12-21 23:02:08 +0000830 BlockChain &Chain = *BlockToChain[*BI];
David Blaikie70573dc2014-11-19 07:49:26 +0000831 if (!UpdatedPreds.insert(&Chain).second)
Chandler Carruth8d150782011-11-13 11:20:44 +0000832 continue;
833
834 assert(Chain.LoopPredecessors == 0);
835 for (BlockChain::iterator BCI = Chain.begin(), BCE = Chain.end();
836 BCI != BCE; ++BCI) {
Jakub Staszak90616162011-12-21 23:02:08 +0000837 assert(BlockToChain[*BCI] == &Chain);
Chandler Carruth8d150782011-11-13 11:20:44 +0000838 for (MachineBasicBlock::pred_iterator PI = (*BCI)->pred_begin(),
839 PE = (*BCI)->pred_end();
840 PI != PE; ++PI) {
Jakub Staszak90616162011-12-21 23:02:08 +0000841 if (BlockToChain[*PI] == &Chain || !LoopBlockSet.count(*PI))
Chandler Carruth8d150782011-11-13 11:20:44 +0000842 continue;
843 ++Chain.LoopPredecessors;
844 }
845 }
846
847 if (Chain.LoopPredecessors == 0)
Chandler Carruthd394baf2011-11-24 08:46:04 +0000848 BlockWorkList.push_back(*Chain.begin());
Chandler Carruth10281422011-10-21 06:46:38 +0000849 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000850
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000851 buildChain(LoopTop, LoopChain, BlockWorkList, &LoopBlockSet);
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000852 rotateLoop(LoopChain, ExitingBB, LoopBlockSet);
Chandler Carruth8d150782011-11-13 11:20:44 +0000853
854 DEBUG({
Chandler Carruth8e1d9062011-11-13 21:39:51 +0000855 // Crash at the end so we get all of the debugging output first.
856 bool BadLoop = false;
857 if (LoopChain.LoopPredecessors) {
858 BadLoop = true;
Chandler Carruth8d150782011-11-13 11:20:44 +0000859 dbgs() << "Loop chain contains a block without its preds placed!\n"
860 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
861 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +0000862 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000863 for (BlockChain::iterator BCI = LoopChain.begin(), BCE = LoopChain.end();
Chandler Carruthccc7e422012-04-16 01:12:56 +0000864 BCI != BCE; ++BCI) {
865 dbgs() << " ... " << getBlockName(*BCI) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +0000866 if (!LoopBlockSet.erase(*BCI)) {
Chandler Carruth0a31d142011-11-14 10:55:53 +0000867 // We don't mark the loop as bad here because there are real situations
868 // where this can occur. For example, with an unanalyzable fallthrough
Chandler Carruth99fe42f2011-11-23 10:35:36 +0000869 // from a loop block to a non-loop block or vice versa.
Chandler Carruth8d150782011-11-13 11:20:44 +0000870 dbgs() << "Loop chain contains a block not contained by the loop!\n"
871 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
872 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
873 << " Bad block: " << getBlockName(*BCI) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +0000874 }
Chandler Carruthccc7e422012-04-16 01:12:56 +0000875 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000876
Chandler Carruth8e1d9062011-11-13 21:39:51 +0000877 if (!LoopBlockSet.empty()) {
878 BadLoop = true;
Chandler Carruthc4a2cb32011-11-13 22:50:09 +0000879 for (BlockFilterSet::iterator LBI = LoopBlockSet.begin(),
880 LBE = LoopBlockSet.end();
Chandler Carruth8d150782011-11-13 11:20:44 +0000881 LBI != LBE; ++LBI)
882 dbgs() << "Loop contains blocks never placed into a chain!\n"
883 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
884 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
885 << " Bad block: " << getBlockName(*LBI) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +0000886 }
887 assert(!BadLoop && "Detected problems with the placement of this loop.");
Chandler Carruth8d150782011-11-13 11:20:44 +0000888 });
Chandler Carruth10281422011-10-21 06:46:38 +0000889}
890
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000891void MachineBlockPlacement::buildCFGChains(MachineFunction &F) {
Chandler Carruth8d150782011-11-13 11:20:44 +0000892 // Ensure that every BB in the function has an associated chain to simplify
893 // the assumptions of the remaining algorithm.
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +0000894 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
895 for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
896 MachineBasicBlock *BB = FI;
Chandler Carruth7adee1a2011-11-24 11:23:15 +0000897 BlockChain *Chain
898 = new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +0000899 // Also, merge any blocks which we cannot reason about and must preserve
900 // the exact fallthrough behavior for.
901 for (;;) {
902 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +0000903 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +0000904 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
905 break;
906
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000907 MachineFunction::iterator NextFI(std::next(FI));
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +0000908 MachineBasicBlock *NextBB = NextFI;
909 // Ensure that the layout successor is a viable block, as we know that
910 // fallthrough is a possibility.
911 assert(NextFI != FE && "Can't fallthrough past the last block.");
912 DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
913 << getBlockName(BB) << " -> " << getBlockName(NextBB)
914 << "\n");
Craig Topperc0196b12014-04-14 00:51:57 +0000915 Chain->merge(NextBB, nullptr);
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +0000916 FI = NextFI;
917 BB = NextBB;
918 }
919 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000920
921 // Build any loop-based chains.
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000922 for (MachineLoopInfo::iterator LI = MLI->begin(), LE = MLI->end(); LI != LE;
923 ++LI)
924 buildLoopChains(F, **LI);
925
Chandler Carruth8d150782011-11-13 11:20:44 +0000926 SmallVector<MachineBasicBlock *, 16> BlockWorkList;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000927
Chandler Carruth8d150782011-11-13 11:20:44 +0000928 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
Chandler Carruth10281422011-10-21 06:46:38 +0000929 for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
Chandler Carruth8d150782011-11-13 11:20:44 +0000930 MachineBasicBlock *BB = &*FI;
931 BlockChain &Chain = *BlockToChain[BB];
David Blaikie70573dc2014-11-19 07:49:26 +0000932 if (!UpdatedPreds.insert(&Chain).second)
Chandler Carruth8d150782011-11-13 11:20:44 +0000933 continue;
934
935 assert(Chain.LoopPredecessors == 0);
936 for (BlockChain::iterator BCI = Chain.begin(), BCE = Chain.end();
937 BCI != BCE; ++BCI) {
938 assert(BlockToChain[*BCI] == &Chain);
939 for (MachineBasicBlock::pred_iterator PI = (*BCI)->pred_begin(),
940 PE = (*BCI)->pred_end();
941 PI != PE; ++PI) {
942 if (BlockToChain[*PI] == &Chain)
943 continue;
944 ++Chain.LoopPredecessors;
945 }
946 }
947
948 if (Chain.LoopPredecessors == 0)
Chandler Carruthd394baf2011-11-24 08:46:04 +0000949 BlockWorkList.push_back(*Chain.begin());
Chandler Carruth8d150782011-11-13 11:20:44 +0000950 }
951
952 BlockChain &FunctionChain = *BlockToChain[&F.front()];
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000953 buildChain(&F.front(), FunctionChain, BlockWorkList);
Chandler Carruth8d150782011-11-13 11:20:44 +0000954
Matt Arsenault0f5f0152013-12-10 18:55:37 +0000955#ifndef NDEBUG
Matt Arsenault79d55f52013-12-05 20:02:18 +0000956 typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType;
Matt Arsenault0f5f0152013-12-10 18:55:37 +0000957#endif
Chandler Carruth8d150782011-11-13 11:20:44 +0000958 DEBUG({
Chandler Carruth8e1d9062011-11-13 21:39:51 +0000959 // Crash at the end so we get all of the debugging output first.
960 bool BadFunc = false;
Chandler Carruth8d150782011-11-13 11:20:44 +0000961 FunctionBlockSetType FunctionBlockSet;
962 for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
963 FunctionBlockSet.insert(FI);
964
Chandler Carruthc4a2cb32011-11-13 22:50:09 +0000965 for (BlockChain::iterator BCI = FunctionChain.begin(),
966 BCE = FunctionChain.end();
Chandler Carruth8d150782011-11-13 11:20:44 +0000967 BCI != BCE; ++BCI)
Chandler Carruth8e1d9062011-11-13 21:39:51 +0000968 if (!FunctionBlockSet.erase(*BCI)) {
969 BadFunc = true;
Chandler Carruth8d150782011-11-13 11:20:44 +0000970 dbgs() << "Function chain contains a block not in the function!\n"
971 << " Bad block: " << getBlockName(*BCI) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +0000972 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000973
Chandler Carruth8e1d9062011-11-13 21:39:51 +0000974 if (!FunctionBlockSet.empty()) {
975 BadFunc = true;
Chandler Carruthc4a2cb32011-11-13 22:50:09 +0000976 for (FunctionBlockSetType::iterator FBI = FunctionBlockSet.begin(),
977 FBE = FunctionBlockSet.end();
978 FBI != FBE; ++FBI)
Chandler Carruth8d150782011-11-13 11:20:44 +0000979 dbgs() << "Function contains blocks never placed into a chain!\n"
980 << " Bad block: " << getBlockName(*FBI) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +0000981 }
982 assert(!BadFunc && "Detected problems with the block placement.");
Chandler Carruth8d150782011-11-13 11:20:44 +0000983 });
984
985 // Splice the blocks into place.
986 MachineFunction::iterator InsertPos = F.begin();
Chandler Carruthc4a2cb32011-11-13 22:50:09 +0000987 for (BlockChain::iterator BI = FunctionChain.begin(),
988 BE = FunctionChain.end();
Chandler Carruth8d150782011-11-13 11:20:44 +0000989 BI != BE; ++BI) {
990 DEBUG(dbgs() << (BI == FunctionChain.begin() ? "Placing chain "
991 : " ... ")
992 << getBlockName(*BI) << "\n");
993 if (InsertPos != MachineFunction::iterator(*BI))
994 F.splice(InsertPos, *BI);
995 else
996 ++InsertPos;
997
998 // Update the terminator of the previous block.
999 if (BI == FunctionChain.begin())
1000 continue;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001001 MachineBasicBlock *PrevBB = std::prev(MachineFunction::iterator(*BI));
Chandler Carruth8d150782011-11-13 11:20:44 +00001002
Chandler Carruth10281422011-10-21 06:46:38 +00001003 // FIXME: It would be awesome of updateTerminator would just return rather
1004 // than assert when the branch cannot be analyzed in order to remove this
1005 // boiler plate.
1006 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001007 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Manman Ren2b6a0df2012-07-31 01:11:07 +00001008 if (!TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001009 // The "PrevBB" is not yet updated to reflect current code layout, so,
1010 // o. it may fall-through to a block without explict "goto" instruction
1011 // before layout, and no longer fall-through it after layout; or
1012 // o. just opposite.
1013 //
1014 // AnalyzeBranch() may return erroneous value for FBB when these two
1015 // situations take place. For the first scenario FBB is mistakenly set
1016 // NULL; for the 2nd scenario, the FBB, which is expected to be NULL,
1017 // is mistakenly pointing to "*BI".
1018 //
1019 bool needUpdateBr = true;
1020 if (!Cond.empty() && (!FBB || FBB == *BI)) {
1021 PrevBB->updateTerminator();
1022 needUpdateBr = false;
1023 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001024 TBB = FBB = nullptr;
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001025 if (TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
1026 // FIXME: This should never take place.
Craig Topperc0196b12014-04-14 00:51:57 +00001027 TBB = FBB = nullptr;
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001028 }
1029 }
1030
Manman Ren2b6a0df2012-07-31 01:11:07 +00001031 // If PrevBB has a two-way branch, try to re-order the branches
1032 // such that we branch to the successor with higher weight first.
1033 if (TBB && !Cond.empty() && FBB &&
1034 MBPI->getEdgeWeight(PrevBB, FBB) > MBPI->getEdgeWeight(PrevBB, TBB) &&
1035 !TII->ReverseBranchCondition(Cond)) {
1036 DEBUG(dbgs() << "Reverse order of the two branches: "
1037 << getBlockName(PrevBB) << "\n");
1038 DEBUG(dbgs() << " Edge weight: " << MBPI->getEdgeWeight(PrevBB, FBB)
1039 << " vs " << MBPI->getEdgeWeight(PrevBB, TBB) << "\n");
1040 DebugLoc dl; // FIXME: this is nowhere
1041 TII->RemoveBranch(*PrevBB);
1042 TII->InsertBranch(*PrevBB, FBB, TBB, Cond, dl);
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001043 needUpdateBr = true;
Manman Ren2b6a0df2012-07-31 01:11:07 +00001044 }
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001045 if (needUpdateBr)
1046 PrevBB->updateTerminator();
Manman Ren2b6a0df2012-07-31 01:11:07 +00001047 }
Chandler Carruth10281422011-10-21 06:46:38 +00001048 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001049
1050 // Fixup the last block.
1051 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001052 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Chandler Carruth8d150782011-11-13 11:20:44 +00001053 if (!TII->AnalyzeBranch(F.back(), TBB, FBB, Cond))
1054 F.back().updateTerminator();
Chandler Carruth10281422011-10-21 06:46:38 +00001055
Chandler Carruthccc7e422012-04-16 01:12:56 +00001056 // Walk through the backedges of the function now that we have fully laid out
1057 // the basic blocks and align the destination of each backedge. We don't rely
Chandler Carruth881d0a72012-08-07 09:45:24 +00001058 // exclusively on the loop info here so that we can align backedges in
1059 // unnatural CFGs and backedges that were introduced purely because of the
1060 // loop rotations done during this layout pass.
Bill Wendling698e84f2012-12-30 10:32:01 +00001061 if (F.getFunction()->getAttributes().
1062 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize))
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001063 return;
Chandler Carruth881d0a72012-08-07 09:45:24 +00001064 if (FunctionChain.begin() == FunctionChain.end())
1065 return; // Empty chain.
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001066
Chandler Carruth881d0a72012-08-07 09:45:24 +00001067 const BranchProbability ColdProb(1, 5); // 20%
1068 BlockFrequency EntryFreq = MBFI->getBlockFreq(F.begin());
1069 BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001070 for (BlockChain::iterator BI = std::next(FunctionChain.begin()),
Chandler Carruthccc7e422012-04-16 01:12:56 +00001071 BE = FunctionChain.end();
1072 BI != BE; ++BI) {
Chandler Carruth881d0a72012-08-07 09:45:24 +00001073 // Don't align non-looping basic blocks. These are unlikely to execute
1074 // enough times to matter in practice. Note that we'll still handle
1075 // unnatural CFGs inside of a natural outer loop (the common case) and
1076 // rotated loops.
1077 MachineLoop *L = MLI->getLoopFor(*BI);
1078 if (!L)
1079 continue;
1080
Hal Finkel57725662015-01-03 17:58:24 +00001081 unsigned Align = TLI->getPrefLoopAlignment(L);
1082 if (!Align)
1083 continue; // Don't care about loop alignment.
1084
Chandler Carruth881d0a72012-08-07 09:45:24 +00001085 // If the block is cold relative to the function entry don't waste space
1086 // aligning it.
1087 BlockFrequency Freq = MBFI->getBlockFreq(*BI);
1088 if (Freq < WeightedEntryFreq)
1089 continue;
1090
1091 // If the block is cold relative to its loop header, don't align it
1092 // regardless of what edges into the block exist.
1093 MachineBasicBlock *LoopHeader = L->getHeader();
1094 BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
1095 if (Freq < (LoopHeaderFreq * ColdProb))
1096 continue;
1097
1098 // Check for the existence of a non-layout predecessor which would benefit
1099 // from aligning this block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001100 MachineBasicBlock *LayoutPred = *std::prev(BI);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001101
1102 // Force alignment if all the predecessors are jumps. We already checked
1103 // that the block isn't cold above.
1104 if (!LayoutPred->isSuccessor(*BI)) {
1105 (*BI)->setAlignment(Align);
1106 continue;
1107 }
1108
1109 // Align this block if the layout predecessor's edge into this block is
Nadav Rotem6036f582013-03-29 16:34:23 +00001110 // cold relative to the block. When this is true, other predecessors make up
Chandler Carruth881d0a72012-08-07 09:45:24 +00001111 // all of the hot entries into the block and thus alignment is likely to be
1112 // important.
1113 BranchProbability LayoutProb = MBPI->getEdgeProbability(LayoutPred, *BI);
1114 BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
1115 if (LayoutEdgeFreq <= (Freq * ColdProb))
1116 (*BI)->setAlignment(Align);
Chandler Carruthccc7e422012-04-16 01:12:56 +00001117 }
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001118}
1119
Chandler Carruth10281422011-10-21 06:46:38 +00001120bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &F) {
1121 // Check for single-block functions and skip them.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001122 if (std::next(F.begin()) == F.end())
Chandler Carruth10281422011-10-21 06:46:38 +00001123 return false;
1124
Paul Robinson7c99ec52014-03-31 17:43:35 +00001125 if (skipOptnoneFunction(*F.getFunction()))
1126 return false;
1127
Chandler Carruth10281422011-10-21 06:46:38 +00001128 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1129 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001130 MLI = &getAnalysis<MachineLoopInfo>();
Eric Christopherfc6de422014-08-05 02:39:49 +00001131 TII = F.getSubtarget().getInstrInfo();
1132 TLI = F.getSubtarget().getTargetLowering();
Chandler Carruth10281422011-10-21 06:46:38 +00001133 assert(BlockToChain.empty());
Chandler Carruth10281422011-10-21 06:46:38 +00001134
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001135 buildCFGChains(F);
Chandler Carruth10281422011-10-21 06:46:38 +00001136
Chandler Carruth10281422011-10-21 06:46:38 +00001137 BlockToChain.clear();
Chandler Carruthfd9b4d92011-11-14 10:57:23 +00001138 ChainAllocator.DestroyAll();
Chandler Carruth10281422011-10-21 06:46:38 +00001139
Nadav Rotemc0adc9f2013-04-12 01:24:16 +00001140 if (AlignAllBlock)
1141 // Align all of the blocks in the function to a specific alignment.
1142 for (MachineFunction::iterator FI = F.begin(), FE = F.end();
1143 FI != FE; ++FI)
1144 FI->setAlignment(AlignAllBlock);
1145
Chandler Carruth10281422011-10-21 06:46:38 +00001146 // We always return true as we have no way to track whether the final order
1147 // differs from the original order.
1148 return true;
1149}
Chandler Carruthae4e8002011-11-02 07:17:12 +00001150
1151namespace {
1152/// \brief A pass to compute block placement statistics.
1153///
1154/// A separate pass to compute interesting statistics for evaluating block
1155/// placement. This is separate from the actual placement pass so that they can
Benjamin Kramerbde91762012-06-02 10:20:22 +00001156/// be computed in the absence of any placement transformations or when using
Chandler Carruthae4e8002011-11-02 07:17:12 +00001157/// alternative placement strategies.
1158class MachineBlockPlacementStats : public MachineFunctionPass {
1159 /// \brief A handle to the branch probability pass.
1160 const MachineBranchProbabilityInfo *MBPI;
1161
1162 /// \brief A handle to the function-wide block frequency pass.
1163 const MachineBlockFrequencyInfo *MBFI;
1164
1165public:
1166 static char ID; // Pass identification, replacement for typeid
1167 MachineBlockPlacementStats() : MachineFunctionPass(ID) {
1168 initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
1169 }
1170
Craig Topper4584cd52014-03-07 09:26:03 +00001171 bool runOnMachineFunction(MachineFunction &F) override;
Chandler Carruthae4e8002011-11-02 07:17:12 +00001172
Craig Topper4584cd52014-03-07 09:26:03 +00001173 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruthae4e8002011-11-02 07:17:12 +00001174 AU.addRequired<MachineBranchProbabilityInfo>();
1175 AU.addRequired<MachineBlockFrequencyInfo>();
1176 AU.setPreservesAll();
1177 MachineFunctionPass::getAnalysisUsage(AU);
1178 }
Chandler Carruthae4e8002011-11-02 07:17:12 +00001179};
1180}
1181
1182char MachineBlockPlacementStats::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +00001183char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
Chandler Carruthae4e8002011-11-02 07:17:12 +00001184INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
1185 "Basic Block Placement Stats", false, false)
1186INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
1187INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
1188INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
1189 "Basic Block Placement Stats", false, false)
1190
Chandler Carruthae4e8002011-11-02 07:17:12 +00001191bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
1192 // Check for single-block functions and skip them.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001193 if (std::next(F.begin()) == F.end())
Chandler Carruthae4e8002011-11-02 07:17:12 +00001194 return false;
1195
1196 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1197 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1198
1199 for (MachineFunction::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1200 BlockFrequency BlockFreq = MBFI->getBlockFreq(I);
1201 Statistic &NumBranches = (I->succ_size() > 1) ? NumCondBranches
1202 : NumUncondBranches;
1203 Statistic &BranchTakenFreq = (I->succ_size() > 1) ? CondBranchTakenFreq
1204 : UncondBranchTakenFreq;
1205 for (MachineBasicBlock::succ_iterator SI = I->succ_begin(),
1206 SE = I->succ_end();
1207 SI != SE; ++SI) {
1208 // Skip if this successor is a fallthrough.
1209 if (I->isLayoutSuccessor(*SI))
1210 continue;
1211
1212 BlockFrequency EdgeFreq = BlockFreq * MBPI->getEdgeProbability(I, *SI);
1213 ++NumBranches;
1214 BranchTakenFreq += EdgeFreq.getFrequency();
1215 }
1216 }
1217
1218 return false;
1219}
1220