blob: 141990bbe87df09271f99e3922d8619566943861 [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");
54STATISTIC(NumUncondBranches, "Number of uncondittional branches");
55STATISTIC(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
Benjamin Kramerc8160d62013-11-20 19:08:44 +000065// FIXME: Find a good default for this flag and remove the flag.
Chandler Carruth2fc3fe12015-03-05 02:35:31 +000066static cl::opt<unsigned> ExitBlockBias(
67 "block-placement-exit-block-bias",
68 cl::desc("Block frequency percentage a loop exit block needs "
69 "over the original exit to be considered the new exit."),
70 cl::init(0), cl::Hidden);
Benjamin Kramerc8160d62013-11-20 19:08:44 +000071
Daniel Jasper471e8562015-03-04 11:05:34 +000072static cl::opt<bool> OutlineOptionalBranches(
73 "outline-optional-branches",
74 cl::desc("Put completely optional branches, i.e. branches with a common "
75 "post dominator, out of line."),
76 cl::init(false), cl::Hidden);
77
Daniel Jasper214997c2015-03-20 10:00:37 +000078static cl::opt<unsigned> OutlineOptionalThreshold(
79 "outline-optional-threshold",
80 cl::desc("Don't outline optional branches that are a single block with an "
81 "instruction count below this threshold"),
82 cl::init(4), cl::Hidden);
83
Chandler Carruth10281422011-10-21 06:46:38 +000084namespace {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +000085class BlockChain;
Chandler Carruth10281422011-10-21 06:46:38 +000086/// \brief Type for our function-wide basic block -> block chain mapping.
87typedef DenseMap<MachineBasicBlock *, BlockChain *> BlockToChainMapType;
88}
89
90namespace {
91/// \brief A chain of blocks which will be laid out contiguously.
92///
93/// This is the datastructure representing a chain of consecutive blocks that
94/// are profitable to layout together in order to maximize fallthrough
Chandler Carruth9139f442012-06-26 05:16:37 +000095/// probabilities and code locality. We also can use a block chain to represent
96/// a sequence of basic blocks which have some external (correctness)
97/// requirement for sequential layout.
Chandler Carruth10281422011-10-21 06:46:38 +000098///
Chandler Carruth9139f442012-06-26 05:16:37 +000099/// Chains can be built around a single basic block and can be merged to grow
100/// them. They participate in a block-to-chain mapping, which is updated
101/// automatically as chains are merged together.
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000102class BlockChain {
103 /// \brief The sequence of blocks belonging to this chain.
Chandler Carruth10281422011-10-21 06:46:38 +0000104 ///
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000105 /// This is the sequence of blocks for a particular chain. These will be laid
106 /// out in-order within the function.
107 SmallVector<MachineBasicBlock *, 4> Blocks;
Chandler Carruth10281422011-10-21 06:46:38 +0000108
109 /// \brief A handle to the function-wide basic block to block chain mapping.
110 ///
111 /// This is retained in each block chain to simplify the computation of child
112 /// block chains for SCC-formation and iteration. We store the edges to child
113 /// basic blocks, and map them back to their associated chains using this
114 /// structure.
115 BlockToChainMapType &BlockToChain;
116
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000117public:
Chandler Carruth10281422011-10-21 06:46:38 +0000118 /// \brief Construct a new BlockChain.
119 ///
120 /// This builds a new block chain representing a single basic block in the
121 /// function. It also registers itself as the chain that block participates
122 /// in with the BlockToChain mapping.
123 BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000124 : Blocks(1, BB), BlockToChain(BlockToChain), LoopPredecessors(0) {
Chandler Carruth10281422011-10-21 06:46:38 +0000125 assert(BB && "Cannot create a chain with a null basic block");
126 BlockToChain[BB] = this;
127 }
128
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000129 /// \brief Iterator over blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000130 typedef SmallVectorImpl<MachineBasicBlock *>::iterator iterator;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000131
132 /// \brief Beginning of blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000133 iterator begin() { return Blocks.begin(); }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000134
135 /// \brief End of blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000136 iterator end() { return Blocks.end(); }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000137
138 /// \brief Merge a block chain into this one.
Chandler Carruth10281422011-10-21 06:46:38 +0000139 ///
140 /// This routine merges a block chain into this one. It takes care of forming
141 /// a contiguous sequence of basic blocks, updating the edge list, and
142 /// updating the block -> chain mapping. It does not free or tear down the
143 /// old chain, but the old chain's block list is no longer valid.
Jakub Staszak90616162011-12-21 23:02:08 +0000144 void merge(MachineBasicBlock *BB, BlockChain *Chain) {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000145 assert(BB);
146 assert(!Blocks.empty());
Chandler Carruth10281422011-10-21 06:46:38 +0000147
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000148 // Fast path in case we don't have a chain already.
149 if (!Chain) {
150 assert(!BlockToChain[BB]);
151 Blocks.push_back(BB);
152 BlockToChain[BB] = this;
153 return;
Chandler Carruth10281422011-10-21 06:46:38 +0000154 }
155
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000156 assert(BB == *Chain->begin());
157 assert(Chain->begin() != Chain->end());
Chandler Carruth10281422011-10-21 06:46:38 +0000158
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000159 // Update the incoming blocks to point to this chain, and add them to the
160 // chain structure.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000161 for (MachineBasicBlock *ChainBB : *Chain) {
162 Blocks.push_back(ChainBB);
163 assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain");
164 BlockToChain[ChainBB] = this;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000165 }
Chandler Carruth10281422011-10-21 06:46:38 +0000166 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000167
Chandler Carruth49158902012-04-08 14:37:01 +0000168#ifndef NDEBUG
169 /// \brief Dump the blocks in this chain.
Nico Weber7408c702014-01-03 22:53:37 +0000170 LLVM_DUMP_METHOD void dump() {
Chandler Carruth7a715da2015-03-05 03:19:05 +0000171 for (MachineBasicBlock *MBB : *this)
172 MBB->dump();
Chandler Carruth49158902012-04-08 14:37:01 +0000173 }
174#endif // NDEBUG
175
Chandler Carruth8d150782011-11-13 11:20:44 +0000176 /// \brief Count of predecessors within the loop currently being processed.
177 ///
178 /// This count is updated at each loop we process to represent the number of
179 /// in-loop predecessors of this chain.
180 unsigned LoopPredecessors;
Chandler Carruth10281422011-10-21 06:46:38 +0000181};
Alexander Kornienko70bc5f12015-06-19 15:57:42 +0000182} // namespace
Chandler Carruth10281422011-10-21 06:46:38 +0000183
184namespace {
185class MachineBlockPlacement : public MachineFunctionPass {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000186 /// \brief A typedef for a block filter set.
187 typedef SmallPtrSet<MachineBasicBlock *, 16> BlockFilterSet;
188
Chandler Carruth10281422011-10-21 06:46:38 +0000189 /// \brief A handle to the branch probability pass.
190 const MachineBranchProbabilityInfo *MBPI;
191
192 /// \brief A handle to the function-wide block frequency pass.
193 const MachineBlockFrequencyInfo *MBFI;
194
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000195 /// \brief A handle to the loop info.
196 const MachineLoopInfo *MLI;
197
Chandler Carruth10281422011-10-21 06:46:38 +0000198 /// \brief A handle to the target's instruction info.
199 const TargetInstrInfo *TII;
200
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000201 /// \brief A handle to the target's lowering info.
Benjamin Kramer56b31bd2013-01-11 20:05:37 +0000202 const TargetLoweringBase *TLI;
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000203
Daniel Jasper471e8562015-03-04 11:05:34 +0000204 /// \brief A handle to the post dominator tree.
205 MachineDominatorTree *MDT;
206
207 /// \brief A set of blocks that are unavoidably execute, i.e. they dominate
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000208 /// all terminators of the MachineFunction.
Daniel Jasper471e8562015-03-04 11:05:34 +0000209 SmallPtrSet<MachineBasicBlock *, 4> UnavoidableBlocks;
210
Chandler Carruth10281422011-10-21 06:46:38 +0000211 /// \brief Allocator and owner of BlockChain structures.
212 ///
Chandler Carruth9139f442012-06-26 05:16:37 +0000213 /// We build BlockChains lazily while processing the loop structure of
214 /// a function. To reduce malloc traffic, we allocate them using this
215 /// slab-like allocator, and destroy them after the pass completes. An
216 /// important guarantee is that this allocator produces stable pointers to
217 /// the chains.
Chandler Carruth10281422011-10-21 06:46:38 +0000218 SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
219
220 /// \brief Function wide BasicBlock to BlockChain mapping.
221 ///
222 /// This mapping allows efficiently moving from any given basic block to the
223 /// BlockChain it participates in, if any. We use it to, among other things,
224 /// allow implicitly defining edges between chains as the existing edges
225 /// between basic blocks.
226 DenseMap<MachineBasicBlock *, BlockChain *> BlockToChain;
227
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000228 void markChainSuccessors(BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000229 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
Craig Topperc0196b12014-04-14 00:51:57 +0000230 const BlockFilterSet *BlockFilter = nullptr);
Jakub Staszak90616162011-12-21 23:02:08 +0000231 MachineBasicBlock *selectBestSuccessor(MachineBasicBlock *BB,
232 BlockChain &Chain,
233 const BlockFilterSet *BlockFilter);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000234 MachineBasicBlock *
235 selectBestCandidateBlock(BlockChain &Chain,
236 SmallVectorImpl<MachineBasicBlock *> &WorkList,
237 const BlockFilterSet *BlockFilter);
238 MachineBasicBlock *
239 getFirstUnplacedBlock(MachineFunction &F, const BlockChain &PlacedChain,
240 MachineFunction::iterator &PrevUnplacedBlockIt,
241 const BlockFilterSet *BlockFilter);
Chandler Carruth8d150782011-11-13 11:20:44 +0000242 void buildChain(MachineBasicBlock *BB, BlockChain &Chain,
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000243 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
Craig Topperc0196b12014-04-14 00:51:57 +0000244 const BlockFilterSet *BlockFilter = nullptr);
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000245 MachineBasicBlock *findBestLoopTop(MachineLoop &L,
246 const BlockFilterSet &LoopBlockSet);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000247 MachineBasicBlock *findBestLoopExit(MachineFunction &F, MachineLoop &L,
Chandler Carruthccc7e422012-04-16 01:12:56 +0000248 const BlockFilterSet &LoopBlockSet);
Jakub Staszak90616162011-12-21 23:02:08 +0000249 void buildLoopChains(MachineFunction &F, MachineLoop &L);
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000250 void rotateLoop(BlockChain &LoopChain, MachineBasicBlock *ExitingBB,
251 const BlockFilterSet &LoopBlockSet);
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000252 void buildCFGChains(MachineFunction &F);
Chandler Carruth10281422011-10-21 06:46:38 +0000253
254public:
255 static char ID; // Pass identification, replacement for typeid
256 MachineBlockPlacement() : MachineFunctionPass(ID) {
257 initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
258 }
259
Craig Topper4584cd52014-03-07 09:26:03 +0000260 bool runOnMachineFunction(MachineFunction &F) override;
Chandler Carruth10281422011-10-21 06:46:38 +0000261
Craig Topper4584cd52014-03-07 09:26:03 +0000262 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth10281422011-10-21 06:46:38 +0000263 AU.addRequired<MachineBranchProbabilityInfo>();
264 AU.addRequired<MachineBlockFrequencyInfo>();
Daniel Jasper471e8562015-03-04 11:05:34 +0000265 AU.addRequired<MachineDominatorTree>();
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000266 AU.addRequired<MachineLoopInfo>();
Chandler Carruth10281422011-10-21 06:46:38 +0000267 MachineFunctionPass::getAnalysisUsage(AU);
268 }
Chandler Carruth10281422011-10-21 06:46:38 +0000269};
Alexander Kornienko70bc5f12015-06-19 15:57:42 +0000270} // namespace
Chandler Carruth10281422011-10-21 06:46:38 +0000271
272char MachineBlockPlacement::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000273char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
Chandler Carruthd0dced52015-03-05 02:28:25 +0000274INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement",
Chandler Carruth10281422011-10-21 06:46:38 +0000275 "Branch Probability Basic Block Placement", false, false)
276INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
277INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
Daniel Jasper471e8562015-03-04 11:05:34 +0000278INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000279INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
Chandler Carruthd0dced52015-03-05 02:28:25 +0000280INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement",
Chandler Carruth10281422011-10-21 06:46:38 +0000281 "Branch Probability Basic Block Placement", false, false)
282
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000283#ifndef NDEBUG
284/// \brief Helper to print the name of a MBB.
285///
286/// Only used by debug logging.
Jakub Staszak90616162011-12-21 23:02:08 +0000287static std::string getBlockName(MachineBasicBlock *BB) {
Alp Tokere69170a2014-06-26 22:52:05 +0000288 std::string Result;
289 raw_string_ostream OS(Result);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000290 OS << "BB#" << BB->getNumber();
291 OS << " (derived from LLVM BB '" << BB->getName() << "')";
Alp Tokere69170a2014-06-26 22:52:05 +0000292 OS.flush();
293 return Result;
Chandler Carruth10281422011-10-21 06:46:38 +0000294}
295
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000296/// \brief Helper to print the number of a MBB.
297///
298/// Only used by debug logging.
Jakub Staszak90616162011-12-21 23:02:08 +0000299static std::string getBlockNum(MachineBasicBlock *BB) {
Alp Tokere69170a2014-06-26 22:52:05 +0000300 std::string Result;
301 raw_string_ostream OS(Result);
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000302 OS << "BB#" << BB->getNumber();
Alp Tokere69170a2014-06-26 22:52:05 +0000303 OS.flush();
304 return Result;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000305}
306#endif
307
Chandler Carrutheb4ec3a2011-11-13 11:34:55 +0000308/// \brief Mark a chain's successors as having one fewer preds.
309///
310/// When a chain is being merged into the "placed" chain, this routine will
311/// quickly walk the successors of each block in the chain and mark them as
312/// having one fewer active predecessor. It also adds any successors of this
313/// chain which reach the zero-predecessor state to the worklist passed in.
Chandler Carruth8d150782011-11-13 11:20:44 +0000314void MachineBlockPlacement::markChainSuccessors(
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000315 BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
Chandler Carruth8d150782011-11-13 11:20:44 +0000316 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
Jakub Staszak90616162011-12-21 23:02:08 +0000317 const BlockFilterSet *BlockFilter) {
Chandler Carruth8d150782011-11-13 11:20:44 +0000318 // Walk all the blocks in this chain, marking their successors as having
319 // a predecessor placed.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000320 for (MachineBasicBlock *MBB : Chain) {
Chandler Carruth8d150782011-11-13 11:20:44 +0000321 // Add any successors for which this is the only un-placed in-loop
322 // predecessor to the worklist as a viable candidate for CFG-neutral
323 // placement. No subsequent placement of this block will violate the CFG
324 // shape, so we get to use heuristics to choose a favorable placement.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000325 for (MachineBasicBlock *Succ : MBB->successors()) {
326 if (BlockFilter && !BlockFilter->count(Succ))
Chandler Carruth8d150782011-11-13 11:20:44 +0000327 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000328 BlockChain &SuccChain = *BlockToChain[Succ];
Chandler Carruth8d150782011-11-13 11:20:44 +0000329 // Disregard edges within a fixed chain, or edges to the loop header.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000330 if (&Chain == &SuccChain || Succ == LoopHeaderBB)
Chandler Carruth8d150782011-11-13 11:20:44 +0000331 continue;
Chandler Carruth10281422011-10-21 06:46:38 +0000332
Chandler Carruth8d150782011-11-13 11:20:44 +0000333 // This is a cross-chain edge that is within the loop, so decrement the
334 // loop predecessor count of the destination chain.
335 if (SuccChain.LoopPredecessors > 0 && --SuccChain.LoopPredecessors == 0)
Chandler Carruthd394baf2011-11-24 08:46:04 +0000336 BlockWorkList.push_back(*SuccChain.begin());
Chandler Carruth10281422011-10-21 06:46:38 +0000337 }
338 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000339}
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000340
Chandler Carruthb3361722011-11-13 11:34:53 +0000341/// \brief Select the best successor for a block.
342///
343/// This looks across all successors of a particular block and attempts to
344/// select the "best" one to be the layout successor. It only considers direct
345/// successors which also pass the block filter. It will attempt to avoid
346/// breaking CFG structure, but cave and break such structures in the case of
347/// very hot successor edges.
348///
349/// \returns The best successor block found, or null if none are viable.
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000350MachineBasicBlock *
351MachineBlockPlacement::selectBestSuccessor(MachineBasicBlock *BB,
352 BlockChain &Chain,
353 const BlockFilterSet *BlockFilter) {
Chandler Carruthb3361722011-11-13 11:34:53 +0000354 const BranchProbability HotProb(4, 5); // 80%
355
Craig Topperc0196b12014-04-14 00:51:57 +0000356 MachineBasicBlock *BestSucc = nullptr;
Chandler Carruth84cd44c2011-11-14 09:12:57 +0000357 // FIXME: Due to the performance of the probability and weight routines in
358 // the MBPI analysis, we manually compute probabilities using the edge
359 // weights. This is suboptimal as it means that the somewhat subtle
360 // definition of edge weight semantics is encoded here as well. We should
Benjamin Kramerbde91762012-06-02 10:20:22 +0000361 // improve the MBPI interface to efficiently support query patterns such as
Chandler Carruth84cd44c2011-11-14 09:12:57 +0000362 // this.
363 uint32_t BestWeight = 0;
364 uint32_t WeightScale = 0;
365 uint32_t SumWeight = MBPI->getSumForBlock(BB, WeightScale);
Chandler Carruthb3361722011-11-13 11:34:53 +0000366 DEBUG(dbgs() << "Attempting merge from: " << getBlockName(BB) << "\n");
Daniel Jaspered9eb722015-02-18 08:19:16 +0000367 for (MachineBasicBlock *Succ : BB->successors()) {
368 if (BlockFilter && !BlockFilter->count(Succ))
Chandler Carruthb3361722011-11-13 11:34:53 +0000369 continue;
Daniel Jaspered9eb722015-02-18 08:19:16 +0000370 BlockChain &SuccChain = *BlockToChain[Succ];
Chandler Carruthb3361722011-11-13 11:34:53 +0000371 if (&SuccChain == &Chain) {
Daniel Jaspered9eb722015-02-18 08:19:16 +0000372 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> Already merged!\n");
Chandler Carruthb3361722011-11-13 11:34:53 +0000373 continue;
374 }
Daniel Jaspered9eb722015-02-18 08:19:16 +0000375 if (Succ != *SuccChain.begin()) {
376 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> Mid chain!\n");
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +0000377 continue;
378 }
Chandler Carruthb3361722011-11-13 11:34:53 +0000379
Daniel Jaspered9eb722015-02-18 08:19:16 +0000380 uint32_t SuccWeight = MBPI->getEdgeWeight(BB, Succ);
Chandler Carruth84cd44c2011-11-14 09:12:57 +0000381 BranchProbability SuccProb(SuccWeight / WeightScale, SumWeight);
Chandler Carruthb3361722011-11-13 11:34:53 +0000382
Daniel Jasper471e8562015-03-04 11:05:34 +0000383 // If we outline optional branches, look whether Succ is unavoidable, i.e.
384 // dominates all terminators of the MachineFunction. If it does, other
385 // successors must be optional. Don't do this for cold branches.
386 if (OutlineOptionalBranches && SuccProb > HotProb.getCompl() &&
Daniel Jasper214997c2015-03-20 10:00:37 +0000387 UnavoidableBlocks.count(Succ) > 0) {
388 auto HasShortOptionalBranch = [&]() {
389 for (MachineBasicBlock *Pred : Succ->predecessors()) {
390 // Check whether there is an unplaced optional branch.
391 if (Pred == Succ || (BlockFilter && !BlockFilter->count(Pred)) ||
392 BlockToChain[Pred] == &Chain)
393 continue;
394 // Check whether the optional branch has exactly one BB.
395 if (Pred->pred_size() > 1 || *Pred->pred_begin() != BB)
396 continue;
397 // Check whether the optional branch is small.
398 if (Pred->size() < OutlineOptionalThreshold)
399 return true;
400 }
401 return false;
402 };
403 if (!HasShortOptionalBranch())
404 return Succ;
405 }
Daniel Jasper471e8562015-03-04 11:05:34 +0000406
Chandler Carruthb3361722011-11-13 11:34:53 +0000407 // Only consider successors which are either "hot", or wouldn't violate
408 // any CFG constraints.
Chandler Carruth18dfac32011-11-20 11:22:06 +0000409 if (SuccChain.LoopPredecessors != 0) {
410 if (SuccProb < HotProb) {
Daniel Jaspered9eb722015-02-18 08:19:16 +0000411 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
Chandler Carruth260258b2013-11-25 00:43:41 +0000412 << " (prob) (CFG conflict)\n");
Chandler Carruth18dfac32011-11-20 11:22:06 +0000413 continue;
414 }
415
Daniel Jasper4d7b0432015-02-18 08:18:07 +0000416 // Make sure that a hot successor doesn't have a globally more
417 // important predecessor.
418 BlockFrequency CandidateEdgeFreq =
419 MBFI->getBlockFreq(BB) * SuccProb * HotProb.getCompl();
420 bool BadCFGConflict = false;
Daniel Jaspered9eb722015-02-18 08:19:16 +0000421 for (MachineBasicBlock *Pred : Succ->predecessors()) {
422 if (Pred == Succ || (BlockFilter && !BlockFilter->count(Pred)) ||
423 BlockToChain[Pred] == &Chain)
Chandler Carruthe3288142015-01-14 20:19:29 +0000424 continue;
Daniel Jasper4d7b0432015-02-18 08:18:07 +0000425 BlockFrequency PredEdgeFreq =
Daniel Jaspered9eb722015-02-18 08:19:16 +0000426 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
Daniel Jasper4d7b0432015-02-18 08:18:07 +0000427 if (PredEdgeFreq >= CandidateEdgeFreq) {
428 BadCFGConflict = true;
429 break;
Chandler Carruthe3288142015-01-14 20:19:29 +0000430 }
Chandler Carruth18dfac32011-11-20 11:22:06 +0000431 }
Daniel Jasper4d7b0432015-02-18 08:18:07 +0000432 if (BadCFGConflict) {
Daniel Jaspered9eb722015-02-18 08:19:16 +0000433 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
Daniel Jasper4d7b0432015-02-18 08:18:07 +0000434 << " (prob) (non-cold CFG conflict)\n");
435 continue;
436 }
Chandler Carruthb3361722011-11-13 11:34:53 +0000437 }
438
Daniel Jaspered9eb722015-02-18 08:19:16 +0000439 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
Chandler Carruthb3361722011-11-13 11:34:53 +0000440 << " (prob)"
441 << (SuccChain.LoopPredecessors != 0 ? " (CFG break)" : "")
442 << "\n");
Chandler Carruth84cd44c2011-11-14 09:12:57 +0000443 if (BestSucc && BestWeight >= SuccWeight)
Chandler Carruthb3361722011-11-13 11:34:53 +0000444 continue;
Daniel Jaspered9eb722015-02-18 08:19:16 +0000445 BestSucc = Succ;
Chandler Carruth84cd44c2011-11-14 09:12:57 +0000446 BestWeight = SuccWeight;
Chandler Carruthb3361722011-11-13 11:34:53 +0000447 }
448 return BestSucc;
449}
450
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000451/// \brief Select the best block from a worklist.
452///
453/// This looks through the provided worklist as a list of candidate basic
454/// blocks and select the most profitable one to place. The definition of
455/// profitable only really makes sense in the context of a loop. This returns
456/// the most frequently visited block in the worklist, which in the case of
457/// a loop, is the one most desirable to be physically close to the rest of the
458/// loop body in order to improve icache behavior.
459///
460/// \returns The best block found, or null if none are viable.
461MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
Jakub Staszak90616162011-12-21 23:02:08 +0000462 BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList,
463 const BlockFilterSet *BlockFilter) {
Chandler Carruth0af6a0b2011-11-14 09:46:33 +0000464 // Once we need to walk the worklist looking for a candidate, cleanup the
465 // worklist of already placed entries.
466 // FIXME: If this shows up on profiles, it could be folded (at the cost of
467 // some code complexity) into the loop below.
468 WorkList.erase(std::remove_if(WorkList.begin(), WorkList.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000469 [&](MachineBasicBlock *BB) {
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000470 return BlockToChain.lookup(BB) == &Chain;
471 }),
Chandler Carruth0af6a0b2011-11-14 09:46:33 +0000472 WorkList.end());
473
Craig Topperc0196b12014-04-14 00:51:57 +0000474 MachineBasicBlock *BestBlock = nullptr;
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000475 BlockFrequency BestFreq;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000476 for (MachineBasicBlock *MBB : WorkList) {
477 BlockChain &SuccChain = *BlockToChain[MBB];
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000478 if (&SuccChain == &Chain) {
Chandler Carruth7a715da2015-03-05 03:19:05 +0000479 DEBUG(dbgs() << " " << getBlockName(MBB) << " -> Already merged!\n");
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000480 continue;
481 }
482 assert(SuccChain.LoopPredecessors == 0 && "Found CFG-violating block");
483
Chandler Carruth7a715da2015-03-05 03:19:05 +0000484 BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
485 DEBUG(dbgs() << " " << getBlockName(MBB) << " -> ";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000486 MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000487 if (BestBlock && BestFreq >= CandidateFreq)
488 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000489 BestBlock = MBB;
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000490 BestFreq = CandidateFreq;
491 }
492 return BestBlock;
493}
494
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000495/// \brief Retrieve the first unplaced basic block.
496///
497/// This routine is called when we are unable to use the CFG to walk through
498/// all of the basic blocks and form a chain due to unnatural loops in the CFG.
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000499/// We walk through the function's blocks in order, starting from the
500/// LastUnplacedBlockIt. We update this iterator on each call to avoid
501/// re-scanning the entire sequence on repeated calls to this routine.
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000502MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000503 MachineFunction &F, const BlockChain &PlacedChain,
504 MachineFunction::iterator &PrevUnplacedBlockIt,
Jakub Staszak90616162011-12-21 23:02:08 +0000505 const BlockFilterSet *BlockFilter) {
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000506 for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F.end(); I != E;
507 ++I) {
508 if (BlockFilter && !BlockFilter->count(I))
509 continue;
Jakub Staszak90616162011-12-21 23:02:08 +0000510 if (BlockToChain[I] != &PlacedChain) {
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000511 PrevUnplacedBlockIt = I;
Chandler Carruth4a87aa02011-11-23 03:03:21 +0000512 // Now select the head of the chain to which the unplaced block belongs
513 // as the block to place. This will force the entire chain to be placed,
514 // and satisfies the requirements of merging chains.
Jakub Staszak90616162011-12-21 23:02:08 +0000515 return *BlockToChain[I]->begin();
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000516 }
517 }
Craig Topperc0196b12014-04-14 00:51:57 +0000518 return nullptr;
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000519}
520
Chandler Carruth8d150782011-11-13 11:20:44 +0000521void MachineBlockPlacement::buildChain(
Daniel Jasper471e8562015-03-04 11:05:34 +0000522 MachineBasicBlock *BB, BlockChain &Chain,
Chandler Carruth8d150782011-11-13 11:20:44 +0000523 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
Jakub Staszak90616162011-12-21 23:02:08 +0000524 const BlockFilterSet *BlockFilter) {
Chandler Carruth8d150782011-11-13 11:20:44 +0000525 assert(BB);
Jakub Staszak90616162011-12-21 23:02:08 +0000526 assert(BlockToChain[BB] == &Chain);
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000527 MachineFunction &F = *BB->getParent();
528 MachineFunction::iterator PrevUnplacedBlockIt = F.begin();
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000529
Chandler Carruth8d150782011-11-13 11:20:44 +0000530 MachineBasicBlock *LoopHeaderBB = BB;
531 markChainSuccessors(Chain, LoopHeaderBB, BlockWorkList, BlockFilter);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000532 BB = *std::prev(Chain.end());
Chandler Carruth8d150782011-11-13 11:20:44 +0000533 for (;;) {
534 assert(BB);
Jakub Staszak90616162011-12-21 23:02:08 +0000535 assert(BlockToChain[BB] == &Chain);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000536 assert(*std::prev(Chain.end()) == BB);
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000537
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +0000538 // Look for the best viable successor if there is one to place immediately
539 // after this block.
Duncan Sands291d47e2012-09-14 09:00:11 +0000540 MachineBasicBlock *BestSucc = selectBestSuccessor(BB, Chain, BlockFilter);
Chandler Carruth8d150782011-11-13 11:20:44 +0000541
542 // If an immediate successor isn't available, look for the best viable
543 // block among those we've identified as not violating the loop's CFG at
544 // this point. This won't be a fallthrough, but it will increase locality.
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000545 if (!BestSucc)
546 BestSucc = selectBestCandidateBlock(Chain, BlockWorkList, BlockFilter);
Chandler Carruth8d150782011-11-13 11:20:44 +0000547
Chandler Carruth8d150782011-11-13 11:20:44 +0000548 if (!BestSucc) {
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000549 BestSucc =
550 getFirstUnplacedBlock(F, Chain, PrevUnplacedBlockIt, BlockFilter);
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000551 if (!BestSucc)
552 break;
553
554 DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
555 "layout successor until the CFG reduces\n");
Chandler Carruth8d150782011-11-13 11:20:44 +0000556 }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000557
Chandler Carruth8d150782011-11-13 11:20:44 +0000558 // Place this block, updating the datastructures to reflect its placement.
Jakub Staszak90616162011-12-21 23:02:08 +0000559 BlockChain &SuccChain = *BlockToChain[BestSucc];
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000560 // Zero out LoopPredecessors for the successor we're about to merge in case
561 // we selected a successor that didn't fit naturally into the CFG.
562 SuccChain.LoopPredecessors = 0;
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000563 DEBUG(dbgs() << "Merging from " << getBlockNum(BB) << " to "
564 << getBlockNum(BestSucc) << "\n");
Chandler Carruth8d150782011-11-13 11:20:44 +0000565 markChainSuccessors(SuccChain, LoopHeaderBB, BlockWorkList, BlockFilter);
566 Chain.merge(BestSucc, &SuccChain);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000567 BB = *std::prev(Chain.end());
Jakub Staszak190c7122011-12-07 19:46:10 +0000568 }
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000569
570 DEBUG(dbgs() << "Finished forming chain for header block "
571 << getBlockNum(*Chain.begin()) << "\n");
Chandler Carruth10281422011-10-21 06:46:38 +0000572}
573
Chandler Carruth03adbd42011-11-27 13:34:33 +0000574/// \brief Find the best loop top block for layout.
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000575///
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000576/// Look for a block which is strictly better than the loop header for laying
577/// out at the top of the loop. This looks for one and only one pattern:
578/// a latch block with no conditional exit. This block will cause a conditional
579/// jump around it or will be the bottom of the loop if we lay it out in place,
580/// but if it it doesn't end up at the bottom of the loop for any reason,
581/// rotation alone won't fix it. Because such a block will always result in an
582/// unconditional jump (for the backedge) rotating it in front of the loop
583/// header is always profitable.
584MachineBasicBlock *
585MachineBlockPlacement::findBestLoopTop(MachineLoop &L,
586 const BlockFilterSet &LoopBlockSet) {
587 // Check that the header hasn't been fused with a preheader block due to
588 // crazy branches. If it has, we need to start with the header at the top to
589 // prevent pulling the preheader into the loop body.
590 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
591 if (!LoopBlockSet.count(*HeaderChain.begin()))
592 return L.getHeader();
593
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000594 DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(L.getHeader())
595 << "\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000596
597 BlockFrequency BestPredFreq;
Craig Topperc0196b12014-04-14 00:51:57 +0000598 MachineBasicBlock *BestPred = nullptr;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000599 for (MachineBasicBlock *Pred : L.getHeader()->predecessors()) {
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000600 if (!LoopBlockSet.count(Pred))
601 continue;
602 DEBUG(dbgs() << " header pred: " << getBlockName(Pred) << ", "
Michael Gottesmanb78dec82013-12-14 00:25:45 +0000603 << Pred->succ_size() << " successors, ";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000604 MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000605 if (Pred->succ_size() > 1)
606 continue;
607
608 BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
609 if (!BestPred || PredFreq > BestPredFreq ||
610 (!(PredFreq < BestPredFreq) &&
611 Pred->isLayoutSuccessor(L.getHeader()))) {
612 BestPred = Pred;
613 BestPredFreq = PredFreq;
614 }
615 }
616
617 // If no direct predecessor is fine, just use the loop header.
618 if (!BestPred)
619 return L.getHeader();
620
621 // Walk backwards through any straight line of predecessors.
622 while (BestPred->pred_size() == 1 &&
623 (*BestPred->pred_begin())->succ_size() == 1 &&
624 *BestPred->pred_begin() != L.getHeader())
625 BestPred = *BestPred->pred_begin();
626
627 DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n");
628 return BestPred;
629}
630
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000631/// \brief Find the best loop exiting block for layout.
632///
Chandler Carruth03adbd42011-11-27 13:34:33 +0000633/// This routine implements the logic to analyze the loop looking for the best
634/// block to layout at the top of the loop. Typically this is done to maximize
635/// fallthrough opportunities.
636MachineBasicBlock *
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000637MachineBlockPlacement::findBestLoopExit(MachineFunction &F, MachineLoop &L,
Chandler Carruthccc7e422012-04-16 01:12:56 +0000638 const BlockFilterSet &LoopBlockSet) {
Chandler Carruth68062612012-04-10 13:35:57 +0000639 // We don't want to layout the loop linearly in all cases. If the loop header
640 // is just a normal basic block in the loop, we want to look for what block
641 // within the loop is the best one to layout at the top. However, if the loop
642 // header has be pre-merged into a chain due to predecessors not having
643 // analyzable branches, *and* the predecessor it is merged with is *not* part
644 // of the loop, rotating the header into the middle of the loop will create
645 // a non-contiguous range of blocks which is Very Bad. So start with the
646 // header and only rotate if safe.
647 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
648 if (!LoopBlockSet.count(*HeaderChain.begin()))
Craig Topperc0196b12014-04-14 00:51:57 +0000649 return nullptr;
Chandler Carruth68062612012-04-10 13:35:57 +0000650
Chandler Carruth03adbd42011-11-27 13:34:33 +0000651 BlockFrequency BestExitEdgeFreq;
Chandler Carruthccc7e422012-04-16 01:12:56 +0000652 unsigned BestExitLoopDepth = 0;
Craig Topperc0196b12014-04-14 00:51:57 +0000653 MachineBasicBlock *ExitingBB = nullptr;
Chandler Carruth4f567202011-11-27 20:18:00 +0000654 // If there are exits to outer loops, loop rotation can severely limit
655 // fallthrough opportunites unless it selects such an exit. Keep a set of
656 // blocks where rotating to exit with that block will reach an outer loop.
657 SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
658
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000659 DEBUG(dbgs() << "Finding best loop exit for: " << getBlockName(L.getHeader())
660 << "\n");
Chandler Carruth7a715da2015-03-05 03:19:05 +0000661 for (MachineBasicBlock *MBB : L.getBlocks()) {
662 BlockChain &Chain = *BlockToChain[MBB];
Chandler Carruth03adbd42011-11-27 13:34:33 +0000663 // Ensure that this block is at the end of a chain; otherwise it could be
Chandler Carruth9a512a42015-04-15 13:19:54 +0000664 // mid-way through an inner loop or a successor of an unanalyzable branch.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000665 if (MBB != *std::prev(Chain.end()))
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000666 continue;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000667
Chandler Carruth03adbd42011-11-27 13:34:33 +0000668 // Now walk the successors. We need to establish whether this has a viable
669 // exiting successor and whether it has a viable non-exiting successor.
670 // We store the old exiting state and restore it if a viable looping
671 // successor isn't found.
672 MachineBasicBlock *OldExitingBB = ExitingBB;
673 BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
Chandler Carruthccc7e422012-04-16 01:12:56 +0000674 bool HasLoopingSucc = false;
Chandler Carruth03adbd42011-11-27 13:34:33 +0000675 // FIXME: Due to the performance of the probability and weight routines in
Chandler Carruthccc7e422012-04-16 01:12:56 +0000676 // the MBPI analysis, we use the internal weights and manually compute the
677 // probabilities to avoid quadratic behavior.
Chandler Carruth03adbd42011-11-27 13:34:33 +0000678 uint32_t WeightScale = 0;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000679 uint32_t SumWeight = MBPI->getSumForBlock(MBB, WeightScale);
680 for (MachineBasicBlock *Succ : MBB->successors()) {
681 if (Succ->isLandingPad())
Chandler Carruth03adbd42011-11-27 13:34:33 +0000682 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000683 if (Succ == MBB)
Chandler Carruth03adbd42011-11-27 13:34:33 +0000684 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000685 BlockChain &SuccChain = *BlockToChain[Succ];
Chandler Carruth03adbd42011-11-27 13:34:33 +0000686 // Don't split chains, either this chain or the successor's chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000687 if (&Chain == &SuccChain) {
Chandler Carruth7a715da2015-03-05 03:19:05 +0000688 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
689 << getBlockName(Succ) << " (chain conflict)\n");
Chandler Carruth03adbd42011-11-27 13:34:33 +0000690 continue;
691 }
692
Chandler Carruth7a715da2015-03-05 03:19:05 +0000693 uint32_t SuccWeight = MBPI->getEdgeWeight(MBB, Succ);
694 if (LoopBlockSet.count(Succ)) {
695 DEBUG(dbgs() << " looping: " << getBlockName(MBB) << " -> "
696 << getBlockName(Succ) << " (" << SuccWeight << ")\n");
Chandler Carruthccc7e422012-04-16 01:12:56 +0000697 HasLoopingSucc = true;
Chandler Carruth03adbd42011-11-27 13:34:33 +0000698 continue;
699 }
700
Chandler Carruthccc7e422012-04-16 01:12:56 +0000701 unsigned SuccLoopDepth = 0;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000702 if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
Chandler Carruthccc7e422012-04-16 01:12:56 +0000703 SuccLoopDepth = ExitLoop->getLoopDepth();
704 if (ExitLoop->contains(&L))
Chandler Carruth7a715da2015-03-05 03:19:05 +0000705 BlocksExitingToOuterLoop.insert(MBB);
Chandler Carruthccc7e422012-04-16 01:12:56 +0000706 }
707
Chandler Carruth03adbd42011-11-27 13:34:33 +0000708 BranchProbability SuccProb(SuccWeight / WeightScale, SumWeight);
Chandler Carruth7a715da2015-03-05 03:19:05 +0000709 BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
710 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
711 << getBlockName(Succ) << " [L:" << SuccLoopDepth << "] (";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000712 MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
Benjamin Kramerc8160d62013-11-20 19:08:44 +0000713 // Note that we bias this toward an existing layout successor to retain
714 // incoming order in the absence of better information. The exit must have
715 // a frequency higher than the current exit before we consider breaking
716 // the layout.
717 BranchProbability Bias(100 - ExitBlockBias, 100);
Chandler Carruth26d30172015-04-15 13:39:42 +0000718 if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
Chandler Carruthccc7e422012-04-16 01:12:56 +0000719 ExitEdgeFreq > BestExitEdgeFreq ||
Chandler Carruth7a715da2015-03-05 03:19:05 +0000720 (MBB->isLayoutSuccessor(Succ) &&
Benjamin Kramerc8160d62013-11-20 19:08:44 +0000721 !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
Chandler Carruth03adbd42011-11-27 13:34:33 +0000722 BestExitEdgeFreq = ExitEdgeFreq;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000723 ExitingBB = MBB;
Chandler Carrutha0545802011-11-27 09:22:53 +0000724 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000725 }
Chandler Carruth03adbd42011-11-27 13:34:33 +0000726
Chandler Carruthccc7e422012-04-16 01:12:56 +0000727 if (!HasLoopingSucc) {
Chandler Carruthcfb2b9d2015-04-15 13:26:41 +0000728 // Restore the old exiting state, no viable looping successor was found.
Chandler Carruth03adbd42011-11-27 13:34:33 +0000729 ExitingBB = OldExitingBB;
730 BestExitEdgeFreq = OldBestExitEdgeFreq;
Chandler Carrutha0545802011-11-27 09:22:53 +0000731 continue;
Chandler Carruth03adbd42011-11-27 13:34:33 +0000732 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000733 }
Chandler Carruthccc7e422012-04-16 01:12:56 +0000734 // Without a candidate exiting block or with only a single block in the
Chandler Carruth03adbd42011-11-27 13:34:33 +0000735 // loop, just use the loop header to layout the loop.
736 if (!ExitingBB || L.getNumBlocks() == 1)
Craig Topperc0196b12014-04-14 00:51:57 +0000737 return nullptr;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000738
Chandler Carruth4f567202011-11-27 20:18:00 +0000739 // Also, if we have exit blocks which lead to outer loops but didn't select
740 // one of them as the exiting block we are rotating toward, disable loop
741 // rotation altogether.
742 if (!BlocksExitingToOuterLoop.empty() &&
743 !BlocksExitingToOuterLoop.count(ExitingBB))
Craig Topperc0196b12014-04-14 00:51:57 +0000744 return nullptr;
Chandler Carruth4f567202011-11-27 20:18:00 +0000745
Chandler Carruth03adbd42011-11-27 13:34:33 +0000746 DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB) << "\n");
Chandler Carruthccc7e422012-04-16 01:12:56 +0000747 return ExitingBB;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000748}
749
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000750/// \brief Attempt to rotate an exiting block to the bottom of the loop.
751///
752/// Once we have built a chain, try to rotate it to line up the hot exit block
753/// with fallthrough out of the loop if doing so doesn't introduce unnecessary
754/// branches. For example, if the loop has fallthrough into its header and out
755/// of its bottom already, don't rotate it.
756void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
757 MachineBasicBlock *ExitingBB,
758 const BlockFilterSet &LoopBlockSet) {
759 if (!ExitingBB)
760 return;
761
762 MachineBasicBlock *Top = *LoopChain.begin();
763 bool ViableTopFallthrough = false;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000764 for (MachineBasicBlock *Pred : Top->predecessors()) {
765 BlockChain *PredChain = BlockToChain[Pred];
766 if (!LoopBlockSet.count(Pred) &&
767 (!PredChain || Pred == *std::prev(PredChain->end()))) {
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000768 ViableTopFallthrough = true;
769 break;
770 }
771 }
772
773 // If the header has viable fallthrough, check whether the current loop
774 // bottom is a viable exiting block. If so, bail out as rotating will
775 // introduce an unnecessary branch.
776 if (ViableTopFallthrough) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000777 MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
Chandler Carruth7a715da2015-03-05 03:19:05 +0000778 for (MachineBasicBlock *Succ : Bottom->successors()) {
779 BlockChain *SuccChain = BlockToChain[Succ];
780 if (!LoopBlockSet.count(Succ) &&
781 (!SuccChain || Succ == *SuccChain->begin()))
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000782 return;
783 }
784 }
785
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000786 BlockChain::iterator ExitIt =
787 std::find(LoopChain.begin(), LoopChain.end(), ExitingBB);
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000788 if (ExitIt == LoopChain.end())
789 return;
790
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000791 std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000792}
793
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000794/// \brief Forms basic block chains from the natural loop structures.
Chandler Carruth10281422011-10-21 06:46:38 +0000795///
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000796/// These chains are designed to preserve the existing *structure* of the code
797/// as much as possible. We can then stitch the chains together in a way which
798/// both preserves the topological structure and minimizes taken conditional
799/// branches.
Chandler Carruth8d150782011-11-13 11:20:44 +0000800void MachineBlockPlacement::buildLoopChains(MachineFunction &F,
Jakub Staszak90616162011-12-21 23:02:08 +0000801 MachineLoop &L) {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000802 // First recurse through any nested loops, building chains for those inner
803 // loops.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000804 for (MachineLoop *InnerLoop : L)
805 buildLoopChains(F, *InnerLoop);
Chandler Carruth10281422011-10-21 06:46:38 +0000806
Chandler Carruth8d150782011-11-13 11:20:44 +0000807 SmallVector<MachineBasicBlock *, 16> BlockWorkList;
808 BlockFilterSet LoopBlockSet(L.block_begin(), L.block_end());
Chandler Carruth03adbd42011-11-27 13:34:33 +0000809
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000810 // First check to see if there is an obviously preferable top block for the
811 // loop. This will default to the header, but may end up as one of the
812 // predecessors to the header if there is one which will result in strictly
813 // fewer branches in the loop body.
814 MachineBasicBlock *LoopTop = findBestLoopTop(L, LoopBlockSet);
815
816 // If we selected just the header for the loop top, look for a potentially
817 // profitable exit block in the event that rotating the loop can eliminate
818 // branches by placing an exit edge at the bottom.
Craig Topperc0196b12014-04-14 00:51:57 +0000819 MachineBasicBlock *ExitingBB = nullptr;
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000820 if (LoopTop == L.getHeader())
821 ExitingBB = findBestLoopExit(F, L, LoopBlockSet);
822
823 BlockChain &LoopChain = *BlockToChain[LoopTop];
Chandler Carruth10281422011-10-21 06:46:38 +0000824
Chandler Carruth8d150782011-11-13 11:20:44 +0000825 // FIXME: This is a really lame way of walking the chains in the loop: we
826 // walk the blocks, and use a set to prevent visiting a particular chain
827 // twice.
Jakub Staszak90616162011-12-21 23:02:08 +0000828 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
Jakub Staszak190c7122011-12-07 19:46:10 +0000829 assert(LoopChain.LoopPredecessors == 0);
830 UpdatedPreds.insert(&LoopChain);
Chandler Carruth7a715da2015-03-05 03:19:05 +0000831 for (MachineBasicBlock *LoopBB : L.getBlocks()) {
832 BlockChain &Chain = *BlockToChain[LoopBB];
David Blaikie70573dc2014-11-19 07:49:26 +0000833 if (!UpdatedPreds.insert(&Chain).second)
Chandler Carruth8d150782011-11-13 11:20:44 +0000834 continue;
835
836 assert(Chain.LoopPredecessors == 0);
Chandler Carruth7a715da2015-03-05 03:19:05 +0000837 for (MachineBasicBlock *ChainBB : Chain) {
838 assert(BlockToChain[ChainBB] == &Chain);
839 for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
840 if (BlockToChain[Pred] == &Chain || !LoopBlockSet.count(Pred))
Chandler Carruth8d150782011-11-13 11:20:44 +0000841 continue;
842 ++Chain.LoopPredecessors;
843 }
844 }
845
846 if (Chain.LoopPredecessors == 0)
Chandler Carruthd394baf2011-11-24 08:46:04 +0000847 BlockWorkList.push_back(*Chain.begin());
Chandler Carruth10281422011-10-21 06:46:38 +0000848 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000849
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000850 buildChain(LoopTop, LoopChain, BlockWorkList, &LoopBlockSet);
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000851 rotateLoop(LoopChain, ExitingBB, LoopBlockSet);
Chandler Carruth8d150782011-11-13 11:20:44 +0000852
853 DEBUG({
Chandler Carruth8e1d9062011-11-13 21:39:51 +0000854 // Crash at the end so we get all of the debugging output first.
855 bool BadLoop = false;
856 if (LoopChain.LoopPredecessors) {
857 BadLoop = true;
Chandler Carruth8d150782011-11-13 11:20:44 +0000858 dbgs() << "Loop chain contains a block without its preds placed!\n"
859 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
860 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +0000861 }
Chandler Carruth7a715da2015-03-05 03:19:05 +0000862 for (MachineBasicBlock *ChainBB : LoopChain) {
863 dbgs() << " ... " << getBlockName(ChainBB) << "\n";
864 if (!LoopBlockSet.erase(ChainBB)) {
Chandler Carruth0a31d142011-11-14 10:55:53 +0000865 // We don't mark the loop as bad here because there are real situations
866 // where this can occur. For example, with an unanalyzable fallthrough
Chandler Carruth99fe42f2011-11-23 10:35:36 +0000867 // from a loop block to a non-loop block or vice versa.
Chandler Carruth8d150782011-11-13 11:20:44 +0000868 dbgs() << "Loop chain contains a block not contained by the loop!\n"
869 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
870 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +0000871 << " Bad block: " << getBlockName(ChainBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +0000872 }
Chandler Carruthccc7e422012-04-16 01:12:56 +0000873 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000874
Chandler Carruth8e1d9062011-11-13 21:39:51 +0000875 if (!LoopBlockSet.empty()) {
876 BadLoop = true;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000877 for (MachineBasicBlock *LoopBB : LoopBlockSet)
Chandler Carruth8d150782011-11-13 11:20:44 +0000878 dbgs() << "Loop contains blocks never placed into a chain!\n"
879 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
880 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +0000881 << " Bad block: " << getBlockName(LoopBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +0000882 }
883 assert(!BadLoop && "Detected problems with the placement of this loop.");
Chandler Carruth8d150782011-11-13 11:20:44 +0000884 });
Chandler Carruth10281422011-10-21 06:46:38 +0000885}
886
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000887void MachineBlockPlacement::buildCFGChains(MachineFunction &F) {
Chandler Carruth8d150782011-11-13 11:20:44 +0000888 // Ensure that every BB in the function has an associated chain to simplify
889 // the assumptions of the remaining algorithm.
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +0000890 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
891 for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
892 MachineBasicBlock *BB = FI;
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000893 BlockChain *Chain =
894 new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +0000895 // Also, merge any blocks which we cannot reason about and must preserve
896 // the exact fallthrough behavior for.
897 for (;;) {
898 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +0000899 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +0000900 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
901 break;
902
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000903 MachineFunction::iterator NextFI(std::next(FI));
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +0000904 MachineBasicBlock *NextBB = NextFI;
905 // Ensure that the layout successor is a viable block, as we know that
906 // fallthrough is a possibility.
907 assert(NextFI != FE && "Can't fallthrough past the last block.");
908 DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
909 << getBlockName(BB) << " -> " << getBlockName(NextBB)
910 << "\n");
Craig Topperc0196b12014-04-14 00:51:57 +0000911 Chain->merge(NextBB, nullptr);
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +0000912 FI = NextFI;
913 BB = NextBB;
914 }
915 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000916
Daniel Jasper471e8562015-03-04 11:05:34 +0000917 if (OutlineOptionalBranches) {
918 // Find the nearest common dominator of all of F's terminators.
919 MachineBasicBlock *Terminator = nullptr;
920 for (MachineBasicBlock &MBB : F) {
921 if (MBB.succ_size() == 0) {
922 if (Terminator == nullptr)
923 Terminator = &MBB;
924 else
925 Terminator = MDT->findNearestCommonDominator(Terminator, &MBB);
926 }
927 }
928
929 // MBBs dominating this common dominator are unavoidable.
930 UnavoidableBlocks.clear();
931 for (MachineBasicBlock &MBB : F) {
932 if (MDT->dominates(&MBB, Terminator)) {
933 UnavoidableBlocks.insert(&MBB);
934 }
935 }
936 }
937
Chandler Carruth8d150782011-11-13 11:20:44 +0000938 // Build any loop-based chains.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000939 for (MachineLoop *L : *MLI)
940 buildLoopChains(F, *L);
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000941
Chandler Carruth8d150782011-11-13 11:20:44 +0000942 SmallVector<MachineBasicBlock *, 16> BlockWorkList;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000943
Chandler Carruth8d150782011-11-13 11:20:44 +0000944 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000945 for (MachineBasicBlock &MBB : F) {
946 BlockChain &Chain = *BlockToChain[&MBB];
David Blaikie70573dc2014-11-19 07:49:26 +0000947 if (!UpdatedPreds.insert(&Chain).second)
Chandler Carruth8d150782011-11-13 11:20:44 +0000948 continue;
949
950 assert(Chain.LoopPredecessors == 0);
Chandler Carruth7a715da2015-03-05 03:19:05 +0000951 for (MachineBasicBlock *ChainBB : Chain) {
952 assert(BlockToChain[ChainBB] == &Chain);
953 for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
954 if (BlockToChain[Pred] == &Chain)
Chandler Carruth8d150782011-11-13 11:20:44 +0000955 continue;
956 ++Chain.LoopPredecessors;
957 }
958 }
959
960 if (Chain.LoopPredecessors == 0)
Chandler Carruthd394baf2011-11-24 08:46:04 +0000961 BlockWorkList.push_back(*Chain.begin());
Chandler Carruth8d150782011-11-13 11:20:44 +0000962 }
963
964 BlockChain &FunctionChain = *BlockToChain[&F.front()];
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000965 buildChain(&F.front(), FunctionChain, BlockWorkList);
Chandler Carruth8d150782011-11-13 11:20:44 +0000966
Matt Arsenault0f5f0152013-12-10 18:55:37 +0000967#ifndef NDEBUG
Matt Arsenault79d55f52013-12-05 20:02:18 +0000968 typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType;
Matt Arsenault0f5f0152013-12-10 18:55:37 +0000969#endif
Chandler Carruth8d150782011-11-13 11:20:44 +0000970 DEBUG({
Chandler Carruth8e1d9062011-11-13 21:39:51 +0000971 // Crash at the end so we get all of the debugging output first.
972 bool BadFunc = false;
Chandler Carruth8d150782011-11-13 11:20:44 +0000973 FunctionBlockSetType FunctionBlockSet;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000974 for (MachineBasicBlock &MBB : F)
975 FunctionBlockSet.insert(&MBB);
Chandler Carruth8d150782011-11-13 11:20:44 +0000976
Chandler Carruth7a715da2015-03-05 03:19:05 +0000977 for (MachineBasicBlock *ChainBB : FunctionChain)
978 if (!FunctionBlockSet.erase(ChainBB)) {
Chandler Carruth8e1d9062011-11-13 21:39:51 +0000979 BadFunc = true;
Chandler Carruth8d150782011-11-13 11:20:44 +0000980 dbgs() << "Function chain contains a block not in the function!\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +0000981 << " Bad block: " << getBlockName(ChainBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +0000982 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000983
Chandler Carruth8e1d9062011-11-13 21:39:51 +0000984 if (!FunctionBlockSet.empty()) {
985 BadFunc = true;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000986 for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
Chandler Carruth8d150782011-11-13 11:20:44 +0000987 dbgs() << "Function contains blocks never placed into a chain!\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +0000988 << " Bad block: " << getBlockName(RemainingBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +0000989 }
990 assert(!BadFunc && "Detected problems with the block placement.");
Chandler Carruth8d150782011-11-13 11:20:44 +0000991 });
992
993 // Splice the blocks into place.
994 MachineFunction::iterator InsertPos = F.begin();
Chandler Carruth7a715da2015-03-05 03:19:05 +0000995 for (MachineBasicBlock *ChainBB : FunctionChain) {
996 DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
997 : " ... ")
998 << getBlockName(ChainBB) << "\n");
999 if (InsertPos != MachineFunction::iterator(ChainBB))
1000 F.splice(InsertPos, ChainBB);
Chandler Carruth8d150782011-11-13 11:20:44 +00001001 else
1002 ++InsertPos;
1003
1004 // Update the terminator of the previous block.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001005 if (ChainBB == *FunctionChain.begin())
Chandler Carruth8d150782011-11-13 11:20:44 +00001006 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001007 MachineBasicBlock *PrevBB = std::prev(MachineFunction::iterator(ChainBB));
Chandler Carruth8d150782011-11-13 11:20:44 +00001008
Chandler Carruth10281422011-10-21 06:46:38 +00001009 // FIXME: It would be awesome of updateTerminator would just return rather
1010 // than assert when the branch cannot be analyzed in order to remove this
1011 // boiler plate.
1012 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001013 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Manman Ren2b6a0df2012-07-31 01:11:07 +00001014 if (!TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001015 // The "PrevBB" is not yet updated to reflect current code layout, so,
1016 // o. it may fall-through to a block without explict "goto" instruction
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001017 // before layout, and no longer fall-through it after layout; or
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001018 // o. just opposite.
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001019 //
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001020 // AnalyzeBranch() may return erroneous value for FBB when these two
1021 // situations take place. For the first scenario FBB is mistakenly set
1022 // NULL; for the 2nd scenario, the FBB, which is expected to be NULL,
1023 // is mistakenly pointing to "*BI".
1024 //
1025 bool needUpdateBr = true;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001026 if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001027 PrevBB->updateTerminator();
1028 needUpdateBr = false;
1029 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001030 TBB = FBB = nullptr;
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001031 if (TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
1032 // FIXME: This should never take place.
Craig Topperc0196b12014-04-14 00:51:57 +00001033 TBB = FBB = nullptr;
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001034 }
1035 }
1036
Manman Ren2b6a0df2012-07-31 01:11:07 +00001037 // If PrevBB has a two-way branch, try to re-order the branches
1038 // such that we branch to the successor with higher weight first.
1039 if (TBB && !Cond.empty() && FBB &&
1040 MBPI->getEdgeWeight(PrevBB, FBB) > MBPI->getEdgeWeight(PrevBB, TBB) &&
1041 !TII->ReverseBranchCondition(Cond)) {
1042 DEBUG(dbgs() << "Reverse order of the two branches: "
1043 << getBlockName(PrevBB) << "\n");
1044 DEBUG(dbgs() << " Edge weight: " << MBPI->getEdgeWeight(PrevBB, FBB)
1045 << " vs " << MBPI->getEdgeWeight(PrevBB, TBB) << "\n");
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001046 DebugLoc dl; // FIXME: this is nowhere
Manman Ren2b6a0df2012-07-31 01:11:07 +00001047 TII->RemoveBranch(*PrevBB);
1048 TII->InsertBranch(*PrevBB, FBB, TBB, Cond, dl);
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001049 needUpdateBr = true;
Manman Ren2b6a0df2012-07-31 01:11:07 +00001050 }
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001051 if (needUpdateBr)
1052 PrevBB->updateTerminator();
Manman Ren2b6a0df2012-07-31 01:11:07 +00001053 }
Chandler Carruth10281422011-10-21 06:46:38 +00001054 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001055
1056 // Fixup the last block.
1057 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001058 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Chandler Carruth8d150782011-11-13 11:20:44 +00001059 if (!TII->AnalyzeBranch(F.back(), TBB, FBB, Cond))
1060 F.back().updateTerminator();
Chandler Carruth10281422011-10-21 06:46:38 +00001061
Chandler Carruthccc7e422012-04-16 01:12:56 +00001062 // Walk through the backedges of the function now that we have fully laid out
1063 // the basic blocks and align the destination of each backedge. We don't rely
Chandler Carruth881d0a72012-08-07 09:45:24 +00001064 // exclusively on the loop info here so that we can align backedges in
1065 // unnatural CFGs and backedges that were introduced purely because of the
1066 // loop rotations done during this layout pass.
Duncan P. N. Exon Smith70eb9c52015-02-14 01:44:41 +00001067 if (F.getFunction()->hasFnAttribute(Attribute::OptimizeForSize))
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001068 return;
Chandler Carruth881d0a72012-08-07 09:45:24 +00001069 if (FunctionChain.begin() == FunctionChain.end())
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001070 return; // Empty chain.
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001071
Chandler Carruth881d0a72012-08-07 09:45:24 +00001072 const BranchProbability ColdProb(1, 5); // 20%
1073 BlockFrequency EntryFreq = MBFI->getBlockFreq(F.begin());
1074 BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001075 for (MachineBasicBlock *ChainBB : FunctionChain) {
1076 if (ChainBB == *FunctionChain.begin())
1077 continue;
1078
Chandler Carruth881d0a72012-08-07 09:45:24 +00001079 // Don't align non-looping basic blocks. These are unlikely to execute
1080 // enough times to matter in practice. Note that we'll still handle
1081 // unnatural CFGs inside of a natural outer loop (the common case) and
1082 // rotated loops.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001083 MachineLoop *L = MLI->getLoopFor(ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001084 if (!L)
1085 continue;
1086
Hal Finkel57725662015-01-03 17:58:24 +00001087 unsigned Align = TLI->getPrefLoopAlignment(L);
1088 if (!Align)
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001089 continue; // Don't care about loop alignment.
Hal Finkel57725662015-01-03 17:58:24 +00001090
Chandler Carruth881d0a72012-08-07 09:45:24 +00001091 // If the block is cold relative to the function entry don't waste space
1092 // aligning it.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001093 BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001094 if (Freq < WeightedEntryFreq)
1095 continue;
1096
1097 // If the block is cold relative to its loop header, don't align it
1098 // regardless of what edges into the block exist.
1099 MachineBasicBlock *LoopHeader = L->getHeader();
1100 BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
1101 if (Freq < (LoopHeaderFreq * ColdProb))
1102 continue;
1103
1104 // Check for the existence of a non-layout predecessor which would benefit
1105 // from aligning this block.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001106 MachineBasicBlock *LayoutPred =
1107 &*std::prev(MachineFunction::iterator(ChainBB));
Chandler Carruth881d0a72012-08-07 09:45:24 +00001108
1109 // Force alignment if all the predecessors are jumps. We already checked
1110 // that the block isn't cold above.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001111 if (!LayoutPred->isSuccessor(ChainBB)) {
1112 ChainBB->setAlignment(Align);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001113 continue;
1114 }
1115
1116 // Align this block if the layout predecessor's edge into this block is
Nadav Rotem6036f582013-03-29 16:34:23 +00001117 // cold relative to the block. When this is true, other predecessors make up
Chandler Carruth881d0a72012-08-07 09:45:24 +00001118 // all of the hot entries into the block and thus alignment is likely to be
1119 // important.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001120 BranchProbability LayoutProb =
1121 MBPI->getEdgeProbability(LayoutPred, ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001122 BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
1123 if (LayoutEdgeFreq <= (Freq * ColdProb))
Chandler Carruth7a715da2015-03-05 03:19:05 +00001124 ChainBB->setAlignment(Align);
Chandler Carruthccc7e422012-04-16 01:12:56 +00001125 }
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001126}
1127
Chandler Carruth10281422011-10-21 06:46:38 +00001128bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &F) {
1129 // Check for single-block functions and skip them.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001130 if (std::next(F.begin()) == F.end())
Chandler Carruth10281422011-10-21 06:46:38 +00001131 return false;
1132
Paul Robinson7c99ec52014-03-31 17:43:35 +00001133 if (skipOptnoneFunction(*F.getFunction()))
1134 return false;
1135
Chandler Carruth10281422011-10-21 06:46:38 +00001136 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1137 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001138 MLI = &getAnalysis<MachineLoopInfo>();
Eric Christopherfc6de422014-08-05 02:39:49 +00001139 TII = F.getSubtarget().getInstrInfo();
1140 TLI = F.getSubtarget().getTargetLowering();
Daniel Jasper471e8562015-03-04 11:05:34 +00001141 MDT = &getAnalysis<MachineDominatorTree>();
Chandler Carruth10281422011-10-21 06:46:38 +00001142 assert(BlockToChain.empty());
Chandler Carruth10281422011-10-21 06:46:38 +00001143
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001144 buildCFGChains(F);
Chandler Carruth10281422011-10-21 06:46:38 +00001145
Chandler Carruth10281422011-10-21 06:46:38 +00001146 BlockToChain.clear();
Chandler Carruthfd9b4d92011-11-14 10:57:23 +00001147 ChainAllocator.DestroyAll();
Chandler Carruth10281422011-10-21 06:46:38 +00001148
Nadav Rotemc0adc9f2013-04-12 01:24:16 +00001149 if (AlignAllBlock)
1150 // Align all of the blocks in the function to a specific alignment.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001151 for (MachineBasicBlock &MBB : F)
1152 MBB.setAlignment(AlignAllBlock);
Nadav Rotemc0adc9f2013-04-12 01:24:16 +00001153
Chandler Carruth10281422011-10-21 06:46:38 +00001154 // We always return true as we have no way to track whether the final order
1155 // differs from the original order.
1156 return true;
1157}
Chandler Carruthae4e8002011-11-02 07:17:12 +00001158
1159namespace {
1160/// \brief A pass to compute block placement statistics.
1161///
1162/// A separate pass to compute interesting statistics for evaluating block
1163/// placement. This is separate from the actual placement pass so that they can
Benjamin Kramerbde91762012-06-02 10:20:22 +00001164/// be computed in the absence of any placement transformations or when using
Chandler Carruthae4e8002011-11-02 07:17:12 +00001165/// alternative placement strategies.
1166class MachineBlockPlacementStats : public MachineFunctionPass {
1167 /// \brief A handle to the branch probability pass.
1168 const MachineBranchProbabilityInfo *MBPI;
1169
1170 /// \brief A handle to the function-wide block frequency pass.
1171 const MachineBlockFrequencyInfo *MBFI;
1172
1173public:
1174 static char ID; // Pass identification, replacement for typeid
1175 MachineBlockPlacementStats() : MachineFunctionPass(ID) {
1176 initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
1177 }
1178
Craig Topper4584cd52014-03-07 09:26:03 +00001179 bool runOnMachineFunction(MachineFunction &F) override;
Chandler Carruthae4e8002011-11-02 07:17:12 +00001180
Craig Topper4584cd52014-03-07 09:26:03 +00001181 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruthae4e8002011-11-02 07:17:12 +00001182 AU.addRequired<MachineBranchProbabilityInfo>();
1183 AU.addRequired<MachineBlockFrequencyInfo>();
1184 AU.setPreservesAll();
1185 MachineFunctionPass::getAnalysisUsage(AU);
1186 }
Chandler Carruthae4e8002011-11-02 07:17:12 +00001187};
Alexander Kornienko70bc5f12015-06-19 15:57:42 +00001188} // namespace
Chandler Carruthae4e8002011-11-02 07:17:12 +00001189
1190char MachineBlockPlacementStats::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +00001191char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
Chandler Carruthae4e8002011-11-02 07:17:12 +00001192INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
1193 "Basic Block Placement Stats", false, false)
1194INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
1195INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
1196INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
1197 "Basic Block Placement Stats", false, false)
1198
Chandler Carruthae4e8002011-11-02 07:17:12 +00001199bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
1200 // Check for single-block functions and skip them.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001201 if (std::next(F.begin()) == F.end())
Chandler Carruthae4e8002011-11-02 07:17:12 +00001202 return false;
1203
1204 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1205 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1206
Chandler Carruth7a715da2015-03-05 03:19:05 +00001207 for (MachineBasicBlock &MBB : F) {
1208 BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001209 Statistic &NumBranches =
Chandler Carruth7a715da2015-03-05 03:19:05 +00001210 (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001211 Statistic &BranchTakenFreq =
Chandler Carruth7a715da2015-03-05 03:19:05 +00001212 (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
1213 for (MachineBasicBlock *Succ : MBB.successors()) {
Chandler Carruthae4e8002011-11-02 07:17:12 +00001214 // Skip if this successor is a fallthrough.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001215 if (MBB.isLayoutSuccessor(Succ))
Chandler Carruthae4e8002011-11-02 07:17:12 +00001216 continue;
1217
Chandler Carruth7a715da2015-03-05 03:19:05 +00001218 BlockFrequency EdgeFreq =
1219 BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
Chandler Carruthae4e8002011-11-02 07:17:12 +00001220 ++NumBranches;
1221 BranchTakenFreq += EdgeFreq.getFrequency();
1222 }
1223 }
1224
1225 return false;
1226}
1227