blob: 4838e6b6cc2a18b8508b4be9b3398f974178ff75 [file] [log] [blame]
Chandler Carruth10281422011-10-21 06:46:38 +00001//===-- MachineBlockPlacement.cpp - Basic Block Code Layout optimization --===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chandler Carruthbd1be4d2011-10-23 09:18:45 +000010// This file implements basic block placement transformations using the CFG
11// structure and branch probability estimates.
Chandler Carruth10281422011-10-21 06:46:38 +000012//
Chandler Carruthbd1be4d2011-10-23 09:18:45 +000013// The pass strives to preserve the structure of the CFG (that is, retain
Benjamin Kramerbde91762012-06-02 10:20:22 +000014// a topological ordering of basic blocks) in the absence of a *strong* signal
Chandler Carruthbd1be4d2011-10-23 09:18:45 +000015// to the contrary from probabilities. However, within the CFG structure, it
16// attempts to choose an ordering which favors placing more likely sequences of
17// blocks adjacent to each other.
18//
19// The algorithm works from the inner-most loop within a function outward, and
20// at each stage walks through the basic blocks, trying to coalesce them into
21// sequential chains where allowed by the CFG (or demanded by heavy
22// probabilities). Finally, it walks the blocks in topological order, and the
23// first time it reaches a chain of basic blocks, it schedules them in the
24// function in-order.
Chandler Carruth10281422011-10-21 06:46:38 +000025//
26//===----------------------------------------------------------------------===//
27
Chandler Carruthed0881b2012-12-03 16:50:05 +000028#include "llvm/CodeGen/Passes.h"
29#include "llvm/ADT/DenseMap.h"
30#include "llvm/ADT/SmallPtrSet.h"
31#include "llvm/ADT/SmallVector.h"
32#include "llvm/ADT/Statistic.h"
Chandler Carruth8b9737c2011-10-21 08:57:37 +000033#include "llvm/CodeGen/MachineBasicBlock.h"
Chandler Carruth10281422011-10-21 06:46:38 +000034#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
35#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Daniel Jasper471e8562015-03-04 11:05:34 +000036#include "llvm/CodeGen/MachineDominators.h"
Chandler Carruth10281422011-10-21 06:46:38 +000037#include "llvm/CodeGen/MachineFunction.h"
Chandler Carruth10281422011-10-21 06:46:38 +000038#include "llvm/CodeGen/MachineFunctionPass.h"
Chandler Carruth8b9737c2011-10-21 08:57:37 +000039#include "llvm/CodeGen/MachineLoopInfo.h"
40#include "llvm/CodeGen/MachineModuleInfo.h"
Chandler Carruth10281422011-10-21 06:46:38 +000041#include "llvm/Support/Allocator.h"
Nadav Rotemc3b0f502013-04-12 00:48:32 +000042#include "llvm/Support/CommandLine.h"
Chandler Carruthbd1be4d2011-10-23 09:18:45 +000043#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000044#include "llvm/Support/raw_ostream.h"
Chandler Carruth10281422011-10-21 06:46:38 +000045#include "llvm/Target/TargetInstrInfo.h"
Chandler Carruth8b9737c2011-10-21 08:57:37 +000046#include "llvm/Target/TargetLowering.h"
Eric Christopherd9134482014-08-04 21:25:23 +000047#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruth10281422011-10-21 06:46:38 +000048#include <algorithm>
49using namespace llvm;
50
Chandler Carruthd0dced52015-03-05 02:28:25 +000051#define DEBUG_TYPE "block-placement"
Chandler Carruth1b9dde02014-04-22 02:02:50 +000052
Chandler Carruthae4e8002011-11-02 07:17:12 +000053STATISTIC(NumCondBranches, "Number of conditional branches");
Craig Topper77ec0772015-09-16 03:52:32 +000054STATISTIC(NumUncondBranches, "Number of unconditional branches");
Chandler Carruthae4e8002011-11-02 07:17:12 +000055STATISTIC(CondBranchTakenFreq,
56 "Potential frequency of taking conditional branches");
57STATISTIC(UncondBranchTakenFreq,
58 "Potential frequency of taking unconditional branches");
59
Nadav Rotemc3b0f502013-04-12 00:48:32 +000060static cl::opt<unsigned> AlignAllBlock("align-all-blocks",
61 cl::desc("Force the alignment of all "
62 "blocks in the function."),
63 cl::init(0), cl::Hidden);
64
Geoff Berry10494ac2016-01-21 17:25:52 +000065static cl::opt<unsigned> AlignAllNonFallThruBlocks(
66 "align-all-nofallthru-blocks",
67 cl::desc("Force the alignment of all "
68 "blocks that have no fall-through predecessors (i.e. don't add "
69 "nops that are executed)."),
70 cl::init(0), cl::Hidden);
71
Benjamin Kramerc8160d62013-11-20 19:08:44 +000072// FIXME: Find a good default for this flag and remove the flag.
Chandler Carruth2fc3fe12015-03-05 02:35:31 +000073static cl::opt<unsigned> ExitBlockBias(
74 "block-placement-exit-block-bias",
75 cl::desc("Block frequency percentage a loop exit block needs "
76 "over the original exit to be considered the new exit."),
77 cl::init(0), cl::Hidden);
Benjamin Kramerc8160d62013-11-20 19:08:44 +000078
Daniel Jasper471e8562015-03-04 11:05:34 +000079static cl::opt<bool> OutlineOptionalBranches(
80 "outline-optional-branches",
81 cl::desc("Put completely optional branches, i.e. branches with a common "
82 "post dominator, out of line."),
83 cl::init(false), cl::Hidden);
84
Daniel Jasper214997c2015-03-20 10:00:37 +000085static cl::opt<unsigned> OutlineOptionalThreshold(
86 "outline-optional-threshold",
87 cl::desc("Don't outline optional branches that are a single block with an "
88 "instruction count below this threshold"),
89 cl::init(4), cl::Hidden);
90
Cong Houb90b9e02015-11-02 21:24:00 +000091static cl::opt<unsigned> LoopToColdBlockRatio(
92 "loop-to-cold-block-ratio",
93 cl::desc("Outline loop blocks from loop chain if (frequency of loop) / "
94 "(frequency of block) is greater than this ratio"),
95 cl::init(5), cl::Hidden);
96
Cong Hou7745dbc2015-10-19 23:16:40 +000097static cl::opt<bool>
98 PreciseRotationCost("precise-rotation-cost",
99 cl::desc("Model the cost of loop rotation more "
100 "precisely by using profile data."),
101 cl::init(false), cl::Hidden);
102
103static cl::opt<unsigned> MisfetchCost(
104 "misfetch-cost",
105 cl::desc("Cost that models the probablistic risk of an instruction "
106 "misfetch due to a jump comparing to falling through, whose cost "
107 "is zero."),
108 cl::init(1), cl::Hidden);
109
110static cl::opt<unsigned> JumpInstCost("jump-inst-cost",
111 cl::desc("Cost of jump instructions."),
112 cl::init(1), cl::Hidden);
113
Chandler Carruth10281422011-10-21 06:46:38 +0000114namespace {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000115class BlockChain;
Chandler Carruth10281422011-10-21 06:46:38 +0000116/// \brief Type for our function-wide basic block -> block chain mapping.
117typedef DenseMap<MachineBasicBlock *, BlockChain *> BlockToChainMapType;
118}
119
120namespace {
121/// \brief A chain of blocks which will be laid out contiguously.
122///
123/// This is the datastructure representing a chain of consecutive blocks that
124/// are profitable to layout together in order to maximize fallthrough
Chandler Carruth9139f442012-06-26 05:16:37 +0000125/// probabilities and code locality. We also can use a block chain to represent
126/// a sequence of basic blocks which have some external (correctness)
127/// requirement for sequential layout.
Chandler Carruth10281422011-10-21 06:46:38 +0000128///
Chandler Carruth9139f442012-06-26 05:16:37 +0000129/// Chains can be built around a single basic block and can be merged to grow
130/// them. They participate in a block-to-chain mapping, which is updated
131/// automatically as chains are merged together.
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000132class BlockChain {
133 /// \brief The sequence of blocks belonging to this chain.
Chandler Carruth10281422011-10-21 06:46:38 +0000134 ///
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000135 /// This is the sequence of blocks for a particular chain. These will be laid
136 /// out in-order within the function.
137 SmallVector<MachineBasicBlock *, 4> Blocks;
Chandler Carruth10281422011-10-21 06:46:38 +0000138
139 /// \brief A handle to the function-wide basic block to block chain mapping.
140 ///
141 /// This is retained in each block chain to simplify the computation of child
142 /// block chains for SCC-formation and iteration. We store the edges to child
143 /// basic blocks, and map them back to their associated chains using this
144 /// structure.
145 BlockToChainMapType &BlockToChain;
146
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000147public:
Chandler Carruth10281422011-10-21 06:46:38 +0000148 /// \brief Construct a new BlockChain.
149 ///
150 /// This builds a new block chain representing a single basic block in the
151 /// function. It also registers itself as the chain that block participates
152 /// in with the BlockToChain mapping.
153 BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000154 : Blocks(1, BB), BlockToChain(BlockToChain), LoopPredecessors(0) {
Chandler Carruth10281422011-10-21 06:46:38 +0000155 assert(BB && "Cannot create a chain with a null basic block");
156 BlockToChain[BB] = this;
157 }
158
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000159 /// \brief Iterator over blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000160 typedef SmallVectorImpl<MachineBasicBlock *>::iterator iterator;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000161
162 /// \brief Beginning of blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000163 iterator begin() { return Blocks.begin(); }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000164
165 /// \brief End of blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000166 iterator end() { return Blocks.end(); }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000167
168 /// \brief Merge a block chain into this one.
Chandler Carruth10281422011-10-21 06:46:38 +0000169 ///
170 /// This routine merges a block chain into this one. It takes care of forming
171 /// a contiguous sequence of basic blocks, updating the edge list, and
172 /// updating the block -> chain mapping. It does not free or tear down the
173 /// old chain, but the old chain's block list is no longer valid.
Jakub Staszak90616162011-12-21 23:02:08 +0000174 void merge(MachineBasicBlock *BB, BlockChain *Chain) {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000175 assert(BB);
176 assert(!Blocks.empty());
Chandler Carruth10281422011-10-21 06:46:38 +0000177
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000178 // Fast path in case we don't have a chain already.
179 if (!Chain) {
180 assert(!BlockToChain[BB]);
181 Blocks.push_back(BB);
182 BlockToChain[BB] = this;
183 return;
Chandler Carruth10281422011-10-21 06:46:38 +0000184 }
185
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000186 assert(BB == *Chain->begin());
187 assert(Chain->begin() != Chain->end());
Chandler Carruth10281422011-10-21 06:46:38 +0000188
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000189 // Update the incoming blocks to point to this chain, and add them to the
190 // chain structure.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000191 for (MachineBasicBlock *ChainBB : *Chain) {
192 Blocks.push_back(ChainBB);
193 assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain");
194 BlockToChain[ChainBB] = this;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000195 }
Chandler Carruth10281422011-10-21 06:46:38 +0000196 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000197
Chandler Carruth49158902012-04-08 14:37:01 +0000198#ifndef NDEBUG
199 /// \brief Dump the blocks in this chain.
Nico Weber7408c702014-01-03 22:53:37 +0000200 LLVM_DUMP_METHOD void dump() {
Chandler Carruth7a715da2015-03-05 03:19:05 +0000201 for (MachineBasicBlock *MBB : *this)
202 MBB->dump();
Chandler Carruth49158902012-04-08 14:37:01 +0000203 }
204#endif // NDEBUG
205
Chandler Carruth8d150782011-11-13 11:20:44 +0000206 /// \brief Count of predecessors within the loop currently being processed.
207 ///
208 /// This count is updated at each loop we process to represent the number of
209 /// in-loop predecessors of this chain.
210 unsigned LoopPredecessors;
Chandler Carruth10281422011-10-21 06:46:38 +0000211};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000212}
Chandler Carruth10281422011-10-21 06:46:38 +0000213
214namespace {
215class MachineBlockPlacement : public MachineFunctionPass {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000216 /// \brief A typedef for a block filter set.
217 typedef SmallPtrSet<MachineBasicBlock *, 16> BlockFilterSet;
218
Chandler Carruth10281422011-10-21 06:46:38 +0000219 /// \brief A handle to the branch probability pass.
220 const MachineBranchProbabilityInfo *MBPI;
221
222 /// \brief A handle to the function-wide block frequency pass.
223 const MachineBlockFrequencyInfo *MBFI;
224
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000225 /// \brief A handle to the loop info.
226 const MachineLoopInfo *MLI;
227
Chandler Carruth10281422011-10-21 06:46:38 +0000228 /// \brief A handle to the target's instruction info.
229 const TargetInstrInfo *TII;
230
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000231 /// \brief A handle to the target's lowering info.
Benjamin Kramer56b31bd2013-01-11 20:05:37 +0000232 const TargetLoweringBase *TLI;
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000233
Daniel Jasper471e8562015-03-04 11:05:34 +0000234 /// \brief A handle to the post dominator tree.
235 MachineDominatorTree *MDT;
236
237 /// \brief A set of blocks that are unavoidably execute, i.e. they dominate
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000238 /// all terminators of the MachineFunction.
Daniel Jasper471e8562015-03-04 11:05:34 +0000239 SmallPtrSet<MachineBasicBlock *, 4> UnavoidableBlocks;
240
Chandler Carruth10281422011-10-21 06:46:38 +0000241 /// \brief Allocator and owner of BlockChain structures.
242 ///
Chandler Carruth9139f442012-06-26 05:16:37 +0000243 /// We build BlockChains lazily while processing the loop structure of
244 /// a function. To reduce malloc traffic, we allocate them using this
245 /// slab-like allocator, and destroy them after the pass completes. An
246 /// important guarantee is that this allocator produces stable pointers to
247 /// the chains.
Chandler Carruth10281422011-10-21 06:46:38 +0000248 SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
249
250 /// \brief Function wide BasicBlock to BlockChain mapping.
251 ///
252 /// This mapping allows efficiently moving from any given basic block to the
253 /// BlockChain it participates in, if any. We use it to, among other things,
254 /// allow implicitly defining edges between chains as the existing edges
255 /// between basic blocks.
256 DenseMap<MachineBasicBlock *, BlockChain *> BlockToChain;
257
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000258 void markChainSuccessors(BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000259 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
Craig Topperc0196b12014-04-14 00:51:57 +0000260 const BlockFilterSet *BlockFilter = nullptr);
Jakub Staszak90616162011-12-21 23:02:08 +0000261 MachineBasicBlock *selectBestSuccessor(MachineBasicBlock *BB,
262 BlockChain &Chain,
263 const BlockFilterSet *BlockFilter);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000264 MachineBasicBlock *
265 selectBestCandidateBlock(BlockChain &Chain,
266 SmallVectorImpl<MachineBasicBlock *> &WorkList,
267 const BlockFilterSet *BlockFilter);
268 MachineBasicBlock *
269 getFirstUnplacedBlock(MachineFunction &F, const BlockChain &PlacedChain,
270 MachineFunction::iterator &PrevUnplacedBlockIt,
271 const BlockFilterSet *BlockFilter);
Chandler Carruth8d150782011-11-13 11:20:44 +0000272 void buildChain(MachineBasicBlock *BB, BlockChain &Chain,
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000273 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
Craig Topperc0196b12014-04-14 00:51:57 +0000274 const BlockFilterSet *BlockFilter = nullptr);
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000275 MachineBasicBlock *findBestLoopTop(MachineLoop &L,
276 const BlockFilterSet &LoopBlockSet);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000277 MachineBasicBlock *findBestLoopExit(MachineFunction &F, MachineLoop &L,
Chandler Carruthccc7e422012-04-16 01:12:56 +0000278 const BlockFilterSet &LoopBlockSet);
Cong Houb90b9e02015-11-02 21:24:00 +0000279 BlockFilterSet collectLoopBlockSet(MachineFunction &F, MachineLoop &L);
Jakub Staszak90616162011-12-21 23:02:08 +0000280 void buildLoopChains(MachineFunction &F, MachineLoop &L);
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000281 void rotateLoop(BlockChain &LoopChain, MachineBasicBlock *ExitingBB,
282 const BlockFilterSet &LoopBlockSet);
Cong Hou7745dbc2015-10-19 23:16:40 +0000283 void rotateLoopWithProfile(BlockChain &LoopChain, MachineLoop &L,
284 const BlockFilterSet &LoopBlockSet);
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000285 void buildCFGChains(MachineFunction &F);
Chandler Carruth10281422011-10-21 06:46:38 +0000286
287public:
288 static char ID; // Pass identification, replacement for typeid
289 MachineBlockPlacement() : MachineFunctionPass(ID) {
290 initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
291 }
292
Craig Topper4584cd52014-03-07 09:26:03 +0000293 bool runOnMachineFunction(MachineFunction &F) override;
Chandler Carruth10281422011-10-21 06:46:38 +0000294
Craig Topper4584cd52014-03-07 09:26:03 +0000295 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth10281422011-10-21 06:46:38 +0000296 AU.addRequired<MachineBranchProbabilityInfo>();
297 AU.addRequired<MachineBlockFrequencyInfo>();
Daniel Jasper471e8562015-03-04 11:05:34 +0000298 AU.addRequired<MachineDominatorTree>();
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000299 AU.addRequired<MachineLoopInfo>();
Chandler Carruth10281422011-10-21 06:46:38 +0000300 MachineFunctionPass::getAnalysisUsage(AU);
301 }
Chandler Carruth10281422011-10-21 06:46:38 +0000302};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000303}
Chandler Carruth10281422011-10-21 06:46:38 +0000304
305char MachineBlockPlacement::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000306char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
Chandler Carruthd0dced52015-03-05 02:28:25 +0000307INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement",
Chandler Carruth10281422011-10-21 06:46:38 +0000308 "Branch Probability Basic Block Placement", false, false)
309INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
310INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
Daniel Jasper471e8562015-03-04 11:05:34 +0000311INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000312INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
Chandler Carruthd0dced52015-03-05 02:28:25 +0000313INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement",
Chandler Carruth10281422011-10-21 06:46:38 +0000314 "Branch Probability Basic Block Placement", false, false)
315
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000316#ifndef NDEBUG
317/// \brief Helper to print the name of a MBB.
318///
319/// Only used by debug logging.
Jakub Staszak90616162011-12-21 23:02:08 +0000320static std::string getBlockName(MachineBasicBlock *BB) {
Alp Tokere69170a2014-06-26 22:52:05 +0000321 std::string Result;
322 raw_string_ostream OS(Result);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000323 OS << "BB#" << BB->getNumber();
Philip Reamesb9688f42016-03-02 21:45:13 +0000324 OS << " ('" << BB->getName() << "')";
Alp Tokere69170a2014-06-26 22:52:05 +0000325 OS.flush();
326 return Result;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000327}
328#endif
329
Chandler Carrutheb4ec3a2011-11-13 11:34:55 +0000330/// \brief Mark a chain's successors as having one fewer preds.
331///
332/// When a chain is being merged into the "placed" chain, this routine will
333/// quickly walk the successors of each block in the chain and mark them as
334/// having one fewer active predecessor. It also adds any successors of this
335/// chain which reach the zero-predecessor state to the worklist passed in.
Chandler Carruth8d150782011-11-13 11:20:44 +0000336void MachineBlockPlacement::markChainSuccessors(
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000337 BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
Chandler Carruth8d150782011-11-13 11:20:44 +0000338 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
Jakub Staszak90616162011-12-21 23:02:08 +0000339 const BlockFilterSet *BlockFilter) {
Chandler Carruth8d150782011-11-13 11:20:44 +0000340 // Walk all the blocks in this chain, marking their successors as having
341 // a predecessor placed.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000342 for (MachineBasicBlock *MBB : Chain) {
Chandler Carruth8d150782011-11-13 11:20:44 +0000343 // Add any successors for which this is the only un-placed in-loop
344 // predecessor to the worklist as a viable candidate for CFG-neutral
345 // placement. No subsequent placement of this block will violate the CFG
346 // shape, so we get to use heuristics to choose a favorable placement.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000347 for (MachineBasicBlock *Succ : MBB->successors()) {
348 if (BlockFilter && !BlockFilter->count(Succ))
Chandler Carruth8d150782011-11-13 11:20:44 +0000349 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000350 BlockChain &SuccChain = *BlockToChain[Succ];
Chandler Carruth8d150782011-11-13 11:20:44 +0000351 // Disregard edges within a fixed chain, or edges to the loop header.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000352 if (&Chain == &SuccChain || Succ == LoopHeaderBB)
Chandler Carruth8d150782011-11-13 11:20:44 +0000353 continue;
Chandler Carruth10281422011-10-21 06:46:38 +0000354
Chandler Carruth8d150782011-11-13 11:20:44 +0000355 // This is a cross-chain edge that is within the loop, so decrement the
356 // loop predecessor count of the destination chain.
357 if (SuccChain.LoopPredecessors > 0 && --SuccChain.LoopPredecessors == 0)
Chandler Carruthd394baf2011-11-24 08:46:04 +0000358 BlockWorkList.push_back(*SuccChain.begin());
Chandler Carruth10281422011-10-21 06:46:38 +0000359 }
360 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000361}
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000362
Chandler Carruthb3361722011-11-13 11:34:53 +0000363/// \brief Select the best successor for a block.
364///
365/// This looks across all successors of a particular block and attempts to
366/// select the "best" one to be the layout successor. It only considers direct
367/// successors which also pass the block filter. It will attempt to avoid
368/// breaking CFG structure, but cave and break such structures in the case of
369/// very hot successor edges.
370///
371/// \returns The best successor block found, or null if none are viable.
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000372MachineBasicBlock *
373MachineBlockPlacement::selectBestSuccessor(MachineBasicBlock *BB,
374 BlockChain &Chain,
375 const BlockFilterSet *BlockFilter) {
Chandler Carruthb3361722011-11-13 11:34:53 +0000376 const BranchProbability HotProb(4, 5); // 80%
377
Craig Topperc0196b12014-04-14 00:51:57 +0000378 MachineBasicBlock *BestSucc = nullptr;
Cong Houd97c1002015-12-01 05:29:22 +0000379 auto BestProb = BranchProbability::getZero();
Chandler Carruthb3361722011-11-13 11:34:53 +0000380
Cong Houd97c1002015-12-01 05:29:22 +0000381 // Adjust edge probabilities by excluding edges pointing to blocks that is
382 // either not in BlockFilter or is already in the current chain. Consider the
383 // following CFG:
Cong Hou41cf1a52015-11-18 00:52:52 +0000384 //
385 // --->A
386 // | / \
387 // | B C
388 // | \ / \
389 // ----D E
390 //
391 // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after
392 // A->C is chosen as a fall-through, D won't be selected as a successor of C
393 // due to CFG constraint (the probability of C->D is not greater than
394 // HotProb). If we exclude E that is not in BlockFilter when calculating the
395 // probability of C->D, D will be selected and we will get A C D B as the
396 // layout of this loop.
Cong Houd97c1002015-12-01 05:29:22 +0000397 auto AdjustedSumProb = BranchProbability::getOne();
Cong Hou41cf1a52015-11-18 00:52:52 +0000398 SmallVector<MachineBasicBlock *, 4> Successors;
399 for (MachineBasicBlock *Succ : BB->successors()) {
400 bool SkipSucc = false;
401 if (BlockFilter && !BlockFilter->count(Succ)) {
402 SkipSucc = true;
403 } else {
404 BlockChain *SuccChain = BlockToChain[Succ];
405 if (SuccChain == &Chain) {
406 DEBUG(dbgs() << " " << getBlockName(Succ)
407 << " -> Already merged!\n");
408 SkipSucc = true;
409 } else if (Succ != *SuccChain->begin()) {
410 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> Mid chain!\n");
411 continue;
412 }
413 }
414 if (SkipSucc)
Cong Houd97c1002015-12-01 05:29:22 +0000415 AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ);
Cong Hou41cf1a52015-11-18 00:52:52 +0000416 else
417 Successors.push_back(Succ);
418 }
419
420 DEBUG(dbgs() << "Attempting merge from: " << getBlockName(BB) << "\n");
421 for (MachineBasicBlock *Succ : Successors) {
Cong Houd97c1002015-12-01 05:29:22 +0000422 BranchProbability SuccProb;
423 uint32_t SuccProbN = MBPI->getEdgeProbability(BB, Succ).getNumerator();
424 uint32_t SuccProbD = AdjustedSumProb.getNumerator();
425 if (SuccProbN >= SuccProbD)
426 SuccProb = BranchProbability::getOne();
427 else
428 SuccProb = BranchProbability(SuccProbN, SuccProbD);
Chandler Carruthb3361722011-11-13 11:34:53 +0000429
Daniel Jasper471e8562015-03-04 11:05:34 +0000430 // If we outline optional branches, look whether Succ is unavoidable, i.e.
431 // dominates all terminators of the MachineFunction. If it does, other
432 // successors must be optional. Don't do this for cold branches.
433 if (OutlineOptionalBranches && SuccProb > HotProb.getCompl() &&
Daniel Jasper214997c2015-03-20 10:00:37 +0000434 UnavoidableBlocks.count(Succ) > 0) {
435 auto HasShortOptionalBranch = [&]() {
436 for (MachineBasicBlock *Pred : Succ->predecessors()) {
437 // Check whether there is an unplaced optional branch.
438 if (Pred == Succ || (BlockFilter && !BlockFilter->count(Pred)) ||
439 BlockToChain[Pred] == &Chain)
440 continue;
441 // Check whether the optional branch has exactly one BB.
442 if (Pred->pred_size() > 1 || *Pred->pred_begin() != BB)
443 continue;
444 // Check whether the optional branch is small.
445 if (Pred->size() < OutlineOptionalThreshold)
446 return true;
447 }
448 return false;
449 };
450 if (!HasShortOptionalBranch())
451 return Succ;
452 }
Daniel Jasper471e8562015-03-04 11:05:34 +0000453
Chandler Carruthb3361722011-11-13 11:34:53 +0000454 // Only consider successors which are either "hot", or wouldn't violate
455 // any CFG constraints.
Cong Hou41cf1a52015-11-18 00:52:52 +0000456 BlockChain &SuccChain = *BlockToChain[Succ];
Chandler Carruth18dfac32011-11-20 11:22:06 +0000457 if (SuccChain.LoopPredecessors != 0) {
458 if (SuccProb < HotProb) {
Daniel Jaspered9eb722015-02-18 08:19:16 +0000459 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
Chandler Carruth260258b2013-11-25 00:43:41 +0000460 << " (prob) (CFG conflict)\n");
Chandler Carruth18dfac32011-11-20 11:22:06 +0000461 continue;
462 }
463
Daniel Jasper4d7b0432015-02-18 08:18:07 +0000464 // Make sure that a hot successor doesn't have a globally more
465 // important predecessor.
Cong Houd97c1002015-12-01 05:29:22 +0000466 auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ);
Daniel Jasper4d7b0432015-02-18 08:18:07 +0000467 BlockFrequency CandidateEdgeFreq =
Cong Hou41cf1a52015-11-18 00:52:52 +0000468 MBFI->getBlockFreq(BB) * RealSuccProb * HotProb.getCompl();
Daniel Jasper4d7b0432015-02-18 08:18:07 +0000469 bool BadCFGConflict = false;
Daniel Jaspered9eb722015-02-18 08:19:16 +0000470 for (MachineBasicBlock *Pred : Succ->predecessors()) {
471 if (Pred == Succ || (BlockFilter && !BlockFilter->count(Pred)) ||
472 BlockToChain[Pred] == &Chain)
Chandler Carruthe3288142015-01-14 20:19:29 +0000473 continue;
Daniel Jasper4d7b0432015-02-18 08:18:07 +0000474 BlockFrequency PredEdgeFreq =
Daniel Jaspered9eb722015-02-18 08:19:16 +0000475 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
Daniel Jasper4d7b0432015-02-18 08:18:07 +0000476 if (PredEdgeFreq >= CandidateEdgeFreq) {
477 BadCFGConflict = true;
478 break;
Chandler Carruthe3288142015-01-14 20:19:29 +0000479 }
Chandler Carruth18dfac32011-11-20 11:22:06 +0000480 }
Daniel Jasper4d7b0432015-02-18 08:18:07 +0000481 if (BadCFGConflict) {
Daniel Jaspered9eb722015-02-18 08:19:16 +0000482 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
Daniel Jasper4d7b0432015-02-18 08:18:07 +0000483 << " (prob) (non-cold CFG conflict)\n");
484 continue;
485 }
Chandler Carruthb3361722011-11-13 11:34:53 +0000486 }
487
Daniel Jaspered9eb722015-02-18 08:19:16 +0000488 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
Chandler Carruthb3361722011-11-13 11:34:53 +0000489 << " (prob)"
490 << (SuccChain.LoopPredecessors != 0 ? " (CFG break)" : "")
491 << "\n");
Cong Houd97c1002015-12-01 05:29:22 +0000492 if (BestSucc && BestProb >= SuccProb)
Chandler Carruthb3361722011-11-13 11:34:53 +0000493 continue;
Daniel Jaspered9eb722015-02-18 08:19:16 +0000494 BestSucc = Succ;
Cong Houd97c1002015-12-01 05:29:22 +0000495 BestProb = SuccProb;
Chandler Carruthb3361722011-11-13 11:34:53 +0000496 }
497 return BestSucc;
498}
499
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000500/// \brief Select the best block from a worklist.
501///
502/// This looks through the provided worklist as a list of candidate basic
503/// blocks and select the most profitable one to place. The definition of
504/// profitable only really makes sense in the context of a loop. This returns
505/// the most frequently visited block in the worklist, which in the case of
506/// a loop, is the one most desirable to be physically close to the rest of the
507/// loop body in order to improve icache behavior.
508///
509/// \returns The best block found, or null if none are viable.
510MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
Jakub Staszak90616162011-12-21 23:02:08 +0000511 BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList,
512 const BlockFilterSet *BlockFilter) {
Chandler Carruth0af6a0b2011-11-14 09:46:33 +0000513 // Once we need to walk the worklist looking for a candidate, cleanup the
514 // worklist of already placed entries.
515 // FIXME: If this shows up on profiles, it could be folded (at the cost of
516 // some code complexity) into the loop below.
517 WorkList.erase(std::remove_if(WorkList.begin(), WorkList.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000518 [&](MachineBasicBlock *BB) {
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000519 return BlockToChain.lookup(BB) == &Chain;
520 }),
Chandler Carruth0af6a0b2011-11-14 09:46:33 +0000521 WorkList.end());
522
Craig Topperc0196b12014-04-14 00:51:57 +0000523 MachineBasicBlock *BestBlock = nullptr;
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000524 BlockFrequency BestFreq;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000525 for (MachineBasicBlock *MBB : WorkList) {
526 BlockChain &SuccChain = *BlockToChain[MBB];
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000527 if (&SuccChain == &Chain) {
Chandler Carruth7a715da2015-03-05 03:19:05 +0000528 DEBUG(dbgs() << " " << getBlockName(MBB) << " -> Already merged!\n");
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000529 continue;
530 }
531 assert(SuccChain.LoopPredecessors == 0 && "Found CFG-violating block");
532
Chandler Carruth7a715da2015-03-05 03:19:05 +0000533 BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
534 DEBUG(dbgs() << " " << getBlockName(MBB) << " -> ";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000535 MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000536 if (BestBlock && BestFreq >= CandidateFreq)
537 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000538 BestBlock = MBB;
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000539 BestFreq = CandidateFreq;
540 }
541 return BestBlock;
542}
543
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000544/// \brief Retrieve the first unplaced basic block.
545///
546/// This routine is called when we are unable to use the CFG to walk through
547/// all of the basic blocks and form a chain due to unnatural loops in the CFG.
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000548/// We walk through the function's blocks in order, starting from the
549/// LastUnplacedBlockIt. We update this iterator on each call to avoid
550/// re-scanning the entire sequence on repeated calls to this routine.
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000551MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000552 MachineFunction &F, const BlockChain &PlacedChain,
553 MachineFunction::iterator &PrevUnplacedBlockIt,
Jakub Staszak90616162011-12-21 23:02:08 +0000554 const BlockFilterSet *BlockFilter) {
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000555 for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F.end(); I != E;
556 ++I) {
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +0000557 if (BlockFilter && !BlockFilter->count(&*I))
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000558 continue;
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +0000559 if (BlockToChain[&*I] != &PlacedChain) {
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000560 PrevUnplacedBlockIt = I;
Chandler Carruth4a87aa02011-11-23 03:03:21 +0000561 // Now select the head of the chain to which the unplaced block belongs
562 // as the block to place. This will force the entire chain to be placed,
563 // and satisfies the requirements of merging chains.
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +0000564 return *BlockToChain[&*I]->begin();
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000565 }
566 }
Craig Topperc0196b12014-04-14 00:51:57 +0000567 return nullptr;
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000568}
569
Chandler Carruth8d150782011-11-13 11:20:44 +0000570void MachineBlockPlacement::buildChain(
Daniel Jasper471e8562015-03-04 11:05:34 +0000571 MachineBasicBlock *BB, BlockChain &Chain,
Chandler Carruth8d150782011-11-13 11:20:44 +0000572 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
Jakub Staszak90616162011-12-21 23:02:08 +0000573 const BlockFilterSet *BlockFilter) {
Chandler Carruth8d150782011-11-13 11:20:44 +0000574 assert(BB);
Jakub Staszak90616162011-12-21 23:02:08 +0000575 assert(BlockToChain[BB] == &Chain);
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000576 MachineFunction &F = *BB->getParent();
577 MachineFunction::iterator PrevUnplacedBlockIt = F.begin();
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000578
Chandler Carruth8d150782011-11-13 11:20:44 +0000579 MachineBasicBlock *LoopHeaderBB = BB;
580 markChainSuccessors(Chain, LoopHeaderBB, BlockWorkList, BlockFilter);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000581 BB = *std::prev(Chain.end());
Chandler Carruth8d150782011-11-13 11:20:44 +0000582 for (;;) {
583 assert(BB);
Jakub Staszak90616162011-12-21 23:02:08 +0000584 assert(BlockToChain[BB] == &Chain);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000585 assert(*std::prev(Chain.end()) == BB);
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000586
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +0000587 // Look for the best viable successor if there is one to place immediately
588 // after this block.
Duncan Sands291d47e2012-09-14 09:00:11 +0000589 MachineBasicBlock *BestSucc = selectBestSuccessor(BB, Chain, BlockFilter);
Chandler Carruth8d150782011-11-13 11:20:44 +0000590
591 // If an immediate successor isn't available, look for the best viable
592 // block among those we've identified as not violating the loop's CFG at
593 // this point. This won't be a fallthrough, but it will increase locality.
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000594 if (!BestSucc)
595 BestSucc = selectBestCandidateBlock(Chain, BlockWorkList, BlockFilter);
Chandler Carruth8d150782011-11-13 11:20:44 +0000596
Chandler Carruth8d150782011-11-13 11:20:44 +0000597 if (!BestSucc) {
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000598 BestSucc =
599 getFirstUnplacedBlock(F, Chain, PrevUnplacedBlockIt, BlockFilter);
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000600 if (!BestSucc)
601 break;
602
603 DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
604 "layout successor until the CFG reduces\n");
Chandler Carruth8d150782011-11-13 11:20:44 +0000605 }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000606
Chandler Carruth8d150782011-11-13 11:20:44 +0000607 // Place this block, updating the datastructures to reflect its placement.
Jakub Staszak90616162011-12-21 23:02:08 +0000608 BlockChain &SuccChain = *BlockToChain[BestSucc];
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000609 // Zero out LoopPredecessors for the successor we're about to merge in case
610 // we selected a successor that didn't fit naturally into the CFG.
611 SuccChain.LoopPredecessors = 0;
Philip Reamesb9688f42016-03-02 21:45:13 +0000612 DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to "
613 << getBlockName(BestSucc) << "\n");
Chandler Carruth8d150782011-11-13 11:20:44 +0000614 markChainSuccessors(SuccChain, LoopHeaderBB, BlockWorkList, BlockFilter);
615 Chain.merge(BestSucc, &SuccChain);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000616 BB = *std::prev(Chain.end());
Jakub Staszak190c7122011-12-07 19:46:10 +0000617 }
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000618
619 DEBUG(dbgs() << "Finished forming chain for header block "
Philip Reamesb9688f42016-03-02 21:45:13 +0000620 << getBlockName(*Chain.begin()) << "\n");
Chandler Carruth10281422011-10-21 06:46:38 +0000621}
622
Chandler Carruth03adbd42011-11-27 13:34:33 +0000623/// \brief Find the best loop top block for layout.
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000624///
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000625/// Look for a block which is strictly better than the loop header for laying
626/// out at the top of the loop. This looks for one and only one pattern:
627/// a latch block with no conditional exit. This block will cause a conditional
628/// jump around it or will be the bottom of the loop if we lay it out in place,
629/// but if it it doesn't end up at the bottom of the loop for any reason,
630/// rotation alone won't fix it. Because such a block will always result in an
631/// unconditional jump (for the backedge) rotating it in front of the loop
632/// header is always profitable.
633MachineBasicBlock *
634MachineBlockPlacement::findBestLoopTop(MachineLoop &L,
635 const BlockFilterSet &LoopBlockSet) {
636 // Check that the header hasn't been fused with a preheader block due to
637 // crazy branches. If it has, we need to start with the header at the top to
638 // prevent pulling the preheader into the loop body.
639 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
640 if (!LoopBlockSet.count(*HeaderChain.begin()))
641 return L.getHeader();
642
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000643 DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(L.getHeader())
644 << "\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000645
646 BlockFrequency BestPredFreq;
Craig Topperc0196b12014-04-14 00:51:57 +0000647 MachineBasicBlock *BestPred = nullptr;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000648 for (MachineBasicBlock *Pred : L.getHeader()->predecessors()) {
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000649 if (!LoopBlockSet.count(Pred))
650 continue;
651 DEBUG(dbgs() << " header pred: " << getBlockName(Pred) << ", "
Michael Gottesmanb78dec82013-12-14 00:25:45 +0000652 << Pred->succ_size() << " successors, ";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000653 MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000654 if (Pred->succ_size() > 1)
655 continue;
656
657 BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
658 if (!BestPred || PredFreq > BestPredFreq ||
659 (!(PredFreq < BestPredFreq) &&
660 Pred->isLayoutSuccessor(L.getHeader()))) {
661 BestPred = Pred;
662 BestPredFreq = PredFreq;
663 }
664 }
665
666 // If no direct predecessor is fine, just use the loop header.
Philip Reamesb9688f42016-03-02 21:45:13 +0000667 if (!BestPred) {
668 DEBUG(dbgs() << " final top unchanged\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000669 return L.getHeader();
Philip Reamesb9688f42016-03-02 21:45:13 +0000670 }
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000671
672 // Walk backwards through any straight line of predecessors.
673 while (BestPred->pred_size() == 1 &&
674 (*BestPred->pred_begin())->succ_size() == 1 &&
675 *BestPred->pred_begin() != L.getHeader())
676 BestPred = *BestPred->pred_begin();
677
678 DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n");
679 return BestPred;
680}
681
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000682/// \brief Find the best loop exiting block for layout.
683///
Chandler Carruth03adbd42011-11-27 13:34:33 +0000684/// This routine implements the logic to analyze the loop looking for the best
685/// block to layout at the top of the loop. Typically this is done to maximize
686/// fallthrough opportunities.
687MachineBasicBlock *
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000688MachineBlockPlacement::findBestLoopExit(MachineFunction &F, MachineLoop &L,
Chandler Carruthccc7e422012-04-16 01:12:56 +0000689 const BlockFilterSet &LoopBlockSet) {
Chandler Carruth68062612012-04-10 13:35:57 +0000690 // We don't want to layout the loop linearly in all cases. If the loop header
691 // is just a normal basic block in the loop, we want to look for what block
692 // within the loop is the best one to layout at the top. However, if the loop
693 // header has be pre-merged into a chain due to predecessors not having
694 // analyzable branches, *and* the predecessor it is merged with is *not* part
695 // of the loop, rotating the header into the middle of the loop will create
696 // a non-contiguous range of blocks which is Very Bad. So start with the
697 // header and only rotate if safe.
698 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
699 if (!LoopBlockSet.count(*HeaderChain.begin()))
Craig Topperc0196b12014-04-14 00:51:57 +0000700 return nullptr;
Chandler Carruth68062612012-04-10 13:35:57 +0000701
Chandler Carruth03adbd42011-11-27 13:34:33 +0000702 BlockFrequency BestExitEdgeFreq;
Chandler Carruthccc7e422012-04-16 01:12:56 +0000703 unsigned BestExitLoopDepth = 0;
Craig Topperc0196b12014-04-14 00:51:57 +0000704 MachineBasicBlock *ExitingBB = nullptr;
Chandler Carruth4f567202011-11-27 20:18:00 +0000705 // If there are exits to outer loops, loop rotation can severely limit
706 // fallthrough opportunites unless it selects such an exit. Keep a set of
707 // blocks where rotating to exit with that block will reach an outer loop.
708 SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
709
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000710 DEBUG(dbgs() << "Finding best loop exit for: " << getBlockName(L.getHeader())
711 << "\n");
Chandler Carruth7a715da2015-03-05 03:19:05 +0000712 for (MachineBasicBlock *MBB : L.getBlocks()) {
713 BlockChain &Chain = *BlockToChain[MBB];
Chandler Carruth03adbd42011-11-27 13:34:33 +0000714 // Ensure that this block is at the end of a chain; otherwise it could be
Chandler Carruth9a512a42015-04-15 13:19:54 +0000715 // mid-way through an inner loop or a successor of an unanalyzable branch.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000716 if (MBB != *std::prev(Chain.end()))
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000717 continue;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000718
Chandler Carruth03adbd42011-11-27 13:34:33 +0000719 // Now walk the successors. We need to establish whether this has a viable
720 // exiting successor and whether it has a viable non-exiting successor.
721 // We store the old exiting state and restore it if a viable looping
722 // successor isn't found.
723 MachineBasicBlock *OldExitingBB = ExitingBB;
724 BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
Chandler Carruthccc7e422012-04-16 01:12:56 +0000725 bool HasLoopingSucc = false;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000726 for (MachineBasicBlock *Succ : MBB->successors()) {
Reid Kleckner0e288232015-08-27 23:27:47 +0000727 if (Succ->isEHPad())
Chandler Carruth03adbd42011-11-27 13:34:33 +0000728 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000729 if (Succ == MBB)
Chandler Carruth03adbd42011-11-27 13:34:33 +0000730 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000731 BlockChain &SuccChain = *BlockToChain[Succ];
Chandler Carruth03adbd42011-11-27 13:34:33 +0000732 // Don't split chains, either this chain or the successor's chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000733 if (&Chain == &SuccChain) {
Chandler Carruth7a715da2015-03-05 03:19:05 +0000734 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
735 << getBlockName(Succ) << " (chain conflict)\n");
Chandler Carruth03adbd42011-11-27 13:34:33 +0000736 continue;
737 }
738
Cong Houd97c1002015-12-01 05:29:22 +0000739 auto SuccProb = MBPI->getEdgeProbability(MBB, Succ);
Chandler Carruth7a715da2015-03-05 03:19:05 +0000740 if (LoopBlockSet.count(Succ)) {
741 DEBUG(dbgs() << " looping: " << getBlockName(MBB) << " -> "
Cong Houd97c1002015-12-01 05:29:22 +0000742 << getBlockName(Succ) << " (" << SuccProb << ")\n");
Chandler Carruthccc7e422012-04-16 01:12:56 +0000743 HasLoopingSucc = true;
Chandler Carruth03adbd42011-11-27 13:34:33 +0000744 continue;
745 }
746
Chandler Carruthccc7e422012-04-16 01:12:56 +0000747 unsigned SuccLoopDepth = 0;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000748 if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
Chandler Carruthccc7e422012-04-16 01:12:56 +0000749 SuccLoopDepth = ExitLoop->getLoopDepth();
750 if (ExitLoop->contains(&L))
Chandler Carruth7a715da2015-03-05 03:19:05 +0000751 BlocksExitingToOuterLoop.insert(MBB);
Chandler Carruthccc7e422012-04-16 01:12:56 +0000752 }
753
Chandler Carruth7a715da2015-03-05 03:19:05 +0000754 BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
755 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
756 << getBlockName(Succ) << " [L:" << SuccLoopDepth << "] (";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000757 MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
Benjamin Kramerc8160d62013-11-20 19:08:44 +0000758 // Note that we bias this toward an existing layout successor to retain
759 // incoming order in the absence of better information. The exit must have
760 // a frequency higher than the current exit before we consider breaking
761 // the layout.
762 BranchProbability Bias(100 - ExitBlockBias, 100);
Chandler Carruth26d30172015-04-15 13:39:42 +0000763 if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
Chandler Carruthccc7e422012-04-16 01:12:56 +0000764 ExitEdgeFreq > BestExitEdgeFreq ||
Chandler Carruth7a715da2015-03-05 03:19:05 +0000765 (MBB->isLayoutSuccessor(Succ) &&
Benjamin Kramerc8160d62013-11-20 19:08:44 +0000766 !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
Chandler Carruth03adbd42011-11-27 13:34:33 +0000767 BestExitEdgeFreq = ExitEdgeFreq;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000768 ExitingBB = MBB;
Chandler Carrutha0545802011-11-27 09:22:53 +0000769 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000770 }
Chandler Carruth03adbd42011-11-27 13:34:33 +0000771
Chandler Carruthccc7e422012-04-16 01:12:56 +0000772 if (!HasLoopingSucc) {
Chandler Carruthcfb2b9d2015-04-15 13:26:41 +0000773 // Restore the old exiting state, no viable looping successor was found.
Chandler Carruth03adbd42011-11-27 13:34:33 +0000774 ExitingBB = OldExitingBB;
775 BestExitEdgeFreq = OldBestExitEdgeFreq;
Chandler Carrutha0545802011-11-27 09:22:53 +0000776 continue;
Chandler Carruth03adbd42011-11-27 13:34:33 +0000777 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000778 }
Chandler Carruthccc7e422012-04-16 01:12:56 +0000779 // Without a candidate exiting block or with only a single block in the
Chandler Carruth03adbd42011-11-27 13:34:33 +0000780 // loop, just use the loop header to layout the loop.
781 if (!ExitingBB || L.getNumBlocks() == 1)
Craig Topperc0196b12014-04-14 00:51:57 +0000782 return nullptr;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000783
Chandler Carruth4f567202011-11-27 20:18:00 +0000784 // Also, if we have exit blocks which lead to outer loops but didn't select
785 // one of them as the exiting block we are rotating toward, disable loop
786 // rotation altogether.
787 if (!BlocksExitingToOuterLoop.empty() &&
788 !BlocksExitingToOuterLoop.count(ExitingBB))
Craig Topperc0196b12014-04-14 00:51:57 +0000789 return nullptr;
Chandler Carruth4f567202011-11-27 20:18:00 +0000790
Chandler Carruth03adbd42011-11-27 13:34:33 +0000791 DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB) << "\n");
Chandler Carruthccc7e422012-04-16 01:12:56 +0000792 return ExitingBB;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000793}
794
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000795/// \brief Attempt to rotate an exiting block to the bottom of the loop.
796///
797/// Once we have built a chain, try to rotate it to line up the hot exit block
798/// with fallthrough out of the loop if doing so doesn't introduce unnecessary
799/// branches. For example, if the loop has fallthrough into its header and out
800/// of its bottom already, don't rotate it.
801void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
802 MachineBasicBlock *ExitingBB,
803 const BlockFilterSet &LoopBlockSet) {
804 if (!ExitingBB)
805 return;
806
807 MachineBasicBlock *Top = *LoopChain.begin();
808 bool ViableTopFallthrough = false;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000809 for (MachineBasicBlock *Pred : Top->predecessors()) {
810 BlockChain *PredChain = BlockToChain[Pred];
811 if (!LoopBlockSet.count(Pred) &&
812 (!PredChain || Pred == *std::prev(PredChain->end()))) {
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000813 ViableTopFallthrough = true;
814 break;
815 }
816 }
817
818 // If the header has viable fallthrough, check whether the current loop
819 // bottom is a viable exiting block. If so, bail out as rotating will
820 // introduce an unnecessary branch.
821 if (ViableTopFallthrough) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000822 MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
Chandler Carruth7a715da2015-03-05 03:19:05 +0000823 for (MachineBasicBlock *Succ : Bottom->successors()) {
824 BlockChain *SuccChain = BlockToChain[Succ];
825 if (!LoopBlockSet.count(Succ) &&
826 (!SuccChain || Succ == *SuccChain->begin()))
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000827 return;
828 }
829 }
830
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000831 BlockChain::iterator ExitIt =
832 std::find(LoopChain.begin(), LoopChain.end(), ExitingBB);
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000833 if (ExitIt == LoopChain.end())
834 return;
835
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000836 std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000837}
838
Cong Hou7745dbc2015-10-19 23:16:40 +0000839/// \brief Attempt to rotate a loop based on profile data to reduce branch cost.
840///
841/// With profile data, we can determine the cost in terms of missed fall through
842/// opportunities when rotating a loop chain and select the best rotation.
843/// Basically, there are three kinds of cost to consider for each rotation:
844/// 1. The possibly missed fall through edge (if it exists) from BB out of
845/// the loop to the loop header.
846/// 2. The possibly missed fall through edges (if they exist) from the loop
847/// exits to BB out of the loop.
848/// 3. The missed fall through edge (if it exists) from the last BB to the
849/// first BB in the loop chain.
850/// Therefore, the cost for a given rotation is the sum of costs listed above.
851/// We select the best rotation with the smallest cost.
852void MachineBlockPlacement::rotateLoopWithProfile(
853 BlockChain &LoopChain, MachineLoop &L, const BlockFilterSet &LoopBlockSet) {
854 auto HeaderBB = L.getHeader();
855 auto HeaderIter = std::find(LoopChain.begin(), LoopChain.end(), HeaderBB);
856 auto RotationPos = LoopChain.end();
857
858 BlockFrequency SmallestRotationCost = BlockFrequency::getMaxFrequency();
859
860 // A utility lambda that scales up a block frequency by dividing it by a
861 // branch probability which is the reciprocal of the scale.
862 auto ScaleBlockFrequency = [](BlockFrequency Freq,
863 unsigned Scale) -> BlockFrequency {
864 if (Scale == 0)
865 return 0;
866 // Use operator / between BlockFrequency and BranchProbability to implement
867 // saturating multiplication.
868 return Freq / BranchProbability(1, Scale);
869 };
870
871 // Compute the cost of the missed fall-through edge to the loop header if the
872 // chain head is not the loop header. As we only consider natural loops with
873 // single header, this computation can be done only once.
874 BlockFrequency HeaderFallThroughCost(0);
875 for (auto *Pred : HeaderBB->predecessors()) {
876 BlockChain *PredChain = BlockToChain[Pred];
877 if (!LoopBlockSet.count(Pred) &&
878 (!PredChain || Pred == *std::prev(PredChain->end()))) {
879 auto EdgeFreq =
880 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, HeaderBB);
881 auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost);
882 // If the predecessor has only an unconditional jump to the header, we
883 // need to consider the cost of this jump.
884 if (Pred->succ_size() == 1)
885 FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost);
886 HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost);
887 }
888 }
889
890 // Here we collect all exit blocks in the loop, and for each exit we find out
891 // its hottest exit edge. For each loop rotation, we define the loop exit cost
892 // as the sum of frequencies of exit edges we collect here, excluding the exit
893 // edge from the tail of the loop chain.
894 SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq;
895 for (auto BB : LoopChain) {
Cong Houd97c1002015-12-01 05:29:22 +0000896 auto LargestExitEdgeProb = BranchProbability::getZero();
Cong Hou7745dbc2015-10-19 23:16:40 +0000897 for (auto *Succ : BB->successors()) {
898 BlockChain *SuccChain = BlockToChain[Succ];
899 if (!LoopBlockSet.count(Succ) &&
900 (!SuccChain || Succ == *SuccChain->begin())) {
Cong Houd97c1002015-12-01 05:29:22 +0000901 auto SuccProb = MBPI->getEdgeProbability(BB, Succ);
902 LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb);
Cong Hou7745dbc2015-10-19 23:16:40 +0000903 }
904 }
Cong Houd97c1002015-12-01 05:29:22 +0000905 if (LargestExitEdgeProb > BranchProbability::getZero()) {
906 auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb;
Cong Hou7745dbc2015-10-19 23:16:40 +0000907 ExitsWithFreq.emplace_back(BB, ExitFreq);
908 }
909 }
910
911 // In this loop we iterate every block in the loop chain and calculate the
912 // cost assuming the block is the head of the loop chain. When the loop ends,
913 // we should have found the best candidate as the loop chain's head.
914 for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()),
915 EndIter = LoopChain.end();
916 Iter != EndIter; Iter++, TailIter++) {
917 // TailIter is used to track the tail of the loop chain if the block we are
918 // checking (pointed by Iter) is the head of the chain.
919 if (TailIter == LoopChain.end())
920 TailIter = LoopChain.begin();
921
922 auto TailBB = *TailIter;
923
924 // Calculate the cost by putting this BB to the top.
925 BlockFrequency Cost = 0;
926
927 // If the current BB is the loop header, we need to take into account the
928 // cost of the missed fall through edge from outside of the loop to the
929 // header.
930 if (Iter != HeaderIter)
931 Cost += HeaderFallThroughCost;
932
933 // Collect the loop exit cost by summing up frequencies of all exit edges
934 // except the one from the chain tail.
935 for (auto &ExitWithFreq : ExitsWithFreq)
936 if (TailBB != ExitWithFreq.first)
937 Cost += ExitWithFreq.second;
938
939 // The cost of breaking the once fall-through edge from the tail to the top
940 // of the loop chain. Here we need to consider three cases:
941 // 1. If the tail node has only one successor, then we will get an
942 // additional jmp instruction. So the cost here is (MisfetchCost +
943 // JumpInstCost) * tail node frequency.
944 // 2. If the tail node has two successors, then we may still get an
945 // additional jmp instruction if the layout successor after the loop
946 // chain is not its CFG successor. Note that the more frequently executed
947 // jmp instruction will be put ahead of the other one. Assume the
948 // frequency of those two branches are x and y, where x is the frequency
949 // of the edge to the chain head, then the cost will be
950 // (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency.
951 // 3. If the tail node has more than two successors (this rarely happens),
952 // we won't consider any additional cost.
953 if (TailBB->isSuccessor(*Iter)) {
954 auto TailBBFreq = MBFI->getBlockFreq(TailBB);
955 if (TailBB->succ_size() == 1)
956 Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(),
957 MisfetchCost + JumpInstCost);
958 else if (TailBB->succ_size() == 2) {
959 auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter);
960 auto TailToHeadFreq = TailBBFreq * TailToHeadProb;
961 auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2)
962 ? TailBBFreq * TailToHeadProb.getCompl()
963 : TailToHeadFreq;
964 Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) +
965 ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost);
966 }
967 }
968
Philip Reamesb9688f42016-03-02 21:45:13 +0000969 DEBUG(dbgs() << "The cost of loop rotation by making " << getBlockName(*Iter)
Cong Hou7745dbc2015-10-19 23:16:40 +0000970 << " to the top: " << Cost.getFrequency() << "\n");
971
972 if (Cost < SmallestRotationCost) {
973 SmallestRotationCost = Cost;
974 RotationPos = Iter;
975 }
976 }
977
978 if (RotationPos != LoopChain.end()) {
Philip Reamesb9688f42016-03-02 21:45:13 +0000979 DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos)
Cong Hou7745dbc2015-10-19 23:16:40 +0000980 << " to the top\n");
981 std::rotate(LoopChain.begin(), RotationPos, LoopChain.end());
982 }
983}
984
Cong Houb90b9e02015-11-02 21:24:00 +0000985/// \brief Collect blocks in the given loop that are to be placed.
986///
987/// When profile data is available, exclude cold blocks from the returned set;
988/// otherwise, collect all blocks in the loop.
989MachineBlockPlacement::BlockFilterSet
990MachineBlockPlacement::collectLoopBlockSet(MachineFunction &F, MachineLoop &L) {
991 BlockFilterSet LoopBlockSet;
992
993 // Filter cold blocks off from LoopBlockSet when profile data is available.
994 // Collect the sum of frequencies of incoming edges to the loop header from
995 // outside. If we treat the loop as a super block, this is the frequency of
996 // the loop. Then for each block in the loop, we calculate the ratio between
997 // its frequency and the frequency of the loop block. When it is too small,
998 // don't add it to the loop chain. If there are outer loops, then this block
999 // will be merged into the first outer loop chain for which this block is not
1000 // cold anymore. This needs precise profile data and we only do this when
1001 // profile data is available.
1002 if (F.getFunction()->getEntryCount()) {
1003 BlockFrequency LoopFreq(0);
1004 for (auto LoopPred : L.getHeader()->predecessors())
1005 if (!L.contains(LoopPred))
1006 LoopFreq += MBFI->getBlockFreq(LoopPred) *
1007 MBPI->getEdgeProbability(LoopPred, L.getHeader());
1008
1009 for (MachineBasicBlock *LoopBB : L.getBlocks()) {
1010 auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency();
1011 if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio)
1012 continue;
1013 LoopBlockSet.insert(LoopBB);
1014 }
1015 } else
1016 LoopBlockSet.insert(L.block_begin(), L.block_end());
1017
1018 return LoopBlockSet;
1019}
1020
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001021/// \brief Forms basic block chains from the natural loop structures.
Chandler Carruth10281422011-10-21 06:46:38 +00001022///
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001023/// These chains are designed to preserve the existing *structure* of the code
1024/// as much as possible. We can then stitch the chains together in a way which
1025/// both preserves the topological structure and minimizes taken conditional
1026/// branches.
Chandler Carruth8d150782011-11-13 11:20:44 +00001027void MachineBlockPlacement::buildLoopChains(MachineFunction &F,
Jakub Staszak90616162011-12-21 23:02:08 +00001028 MachineLoop &L) {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001029 // First recurse through any nested loops, building chains for those inner
1030 // loops.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001031 for (MachineLoop *InnerLoop : L)
1032 buildLoopChains(F, *InnerLoop);
Chandler Carruth10281422011-10-21 06:46:38 +00001033
Chandler Carruth8d150782011-11-13 11:20:44 +00001034 SmallVector<MachineBasicBlock *, 16> BlockWorkList;
Cong Houb90b9e02015-11-02 21:24:00 +00001035 BlockFilterSet LoopBlockSet = collectLoopBlockSet(F, L);
Chandler Carruth03adbd42011-11-27 13:34:33 +00001036
Cong Hou7745dbc2015-10-19 23:16:40 +00001037 // Check if we have profile data for this function. If yes, we will rotate
1038 // this loop by modeling costs more precisely which requires the profile data
1039 // for better layout.
1040 bool RotateLoopWithProfile =
1041 PreciseRotationCost && F.getFunction()->getEntryCount();
1042
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001043 // First check to see if there is an obviously preferable top block for the
1044 // loop. This will default to the header, but may end up as one of the
1045 // predecessors to the header if there is one which will result in strictly
1046 // fewer branches in the loop body.
Cong Hou7745dbc2015-10-19 23:16:40 +00001047 // When we use profile data to rotate the loop, this is unnecessary.
1048 MachineBasicBlock *LoopTop =
1049 RotateLoopWithProfile ? L.getHeader() : findBestLoopTop(L, LoopBlockSet);
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001050
1051 // If we selected just the header for the loop top, look for a potentially
1052 // profitable exit block in the event that rotating the loop can eliminate
1053 // branches by placing an exit edge at the bottom.
Craig Topperc0196b12014-04-14 00:51:57 +00001054 MachineBasicBlock *ExitingBB = nullptr;
Cong Hou7745dbc2015-10-19 23:16:40 +00001055 if (!RotateLoopWithProfile && LoopTop == L.getHeader())
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001056 ExitingBB = findBestLoopExit(F, L, LoopBlockSet);
1057
1058 BlockChain &LoopChain = *BlockToChain[LoopTop];
Chandler Carruth10281422011-10-21 06:46:38 +00001059
Chandler Carruth8d150782011-11-13 11:20:44 +00001060 // FIXME: This is a really lame way of walking the chains in the loop: we
1061 // walk the blocks, and use a set to prevent visiting a particular chain
1062 // twice.
Jakub Staszak90616162011-12-21 23:02:08 +00001063 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
Jakub Staszak190c7122011-12-07 19:46:10 +00001064 assert(LoopChain.LoopPredecessors == 0);
1065 UpdatedPreds.insert(&LoopChain);
Cong Houb90b9e02015-11-02 21:24:00 +00001066
1067 for (MachineBasicBlock *LoopBB : LoopBlockSet) {
Chandler Carruth7a715da2015-03-05 03:19:05 +00001068 BlockChain &Chain = *BlockToChain[LoopBB];
David Blaikie70573dc2014-11-19 07:49:26 +00001069 if (!UpdatedPreds.insert(&Chain).second)
Chandler Carruth8d150782011-11-13 11:20:44 +00001070 continue;
1071
1072 assert(Chain.LoopPredecessors == 0);
Chandler Carruth7a715da2015-03-05 03:19:05 +00001073 for (MachineBasicBlock *ChainBB : Chain) {
1074 assert(BlockToChain[ChainBB] == &Chain);
1075 for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
1076 if (BlockToChain[Pred] == &Chain || !LoopBlockSet.count(Pred))
Chandler Carruth8d150782011-11-13 11:20:44 +00001077 continue;
1078 ++Chain.LoopPredecessors;
1079 }
1080 }
1081
1082 if (Chain.LoopPredecessors == 0)
Chandler Carruthd394baf2011-11-24 08:46:04 +00001083 BlockWorkList.push_back(*Chain.begin());
Chandler Carruth10281422011-10-21 06:46:38 +00001084 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001085
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001086 buildChain(LoopTop, LoopChain, BlockWorkList, &LoopBlockSet);
Cong Hou7745dbc2015-10-19 23:16:40 +00001087
1088 if (RotateLoopWithProfile)
1089 rotateLoopWithProfile(LoopChain, L, LoopBlockSet);
1090 else
1091 rotateLoop(LoopChain, ExitingBB, LoopBlockSet);
Chandler Carruth8d150782011-11-13 11:20:44 +00001092
1093 DEBUG({
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001094 // Crash at the end so we get all of the debugging output first.
1095 bool BadLoop = false;
1096 if (LoopChain.LoopPredecessors) {
1097 BadLoop = true;
Chandler Carruth8d150782011-11-13 11:20:44 +00001098 dbgs() << "Loop chain contains a block without its preds placed!\n"
1099 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
1100 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001101 }
Chandler Carruth7a715da2015-03-05 03:19:05 +00001102 for (MachineBasicBlock *ChainBB : LoopChain) {
1103 dbgs() << " ... " << getBlockName(ChainBB) << "\n";
1104 if (!LoopBlockSet.erase(ChainBB)) {
Chandler Carruth0a31d142011-11-14 10:55:53 +00001105 // We don't mark the loop as bad here because there are real situations
1106 // where this can occur. For example, with an unanalyzable fallthrough
Chandler Carruth99fe42f2011-11-23 10:35:36 +00001107 // from a loop block to a non-loop block or vice versa.
Chandler Carruth8d150782011-11-13 11:20:44 +00001108 dbgs() << "Loop chain contains a block not contained by the loop!\n"
1109 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
1110 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00001111 << " Bad block: " << getBlockName(ChainBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001112 }
Chandler Carruthccc7e422012-04-16 01:12:56 +00001113 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001114
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001115 if (!LoopBlockSet.empty()) {
1116 BadLoop = true;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001117 for (MachineBasicBlock *LoopBB : LoopBlockSet)
Chandler Carruth8d150782011-11-13 11:20:44 +00001118 dbgs() << "Loop contains blocks never placed into a chain!\n"
1119 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
1120 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00001121 << " Bad block: " << getBlockName(LoopBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001122 }
1123 assert(!BadLoop && "Detected problems with the placement of this loop.");
Chandler Carruth8d150782011-11-13 11:20:44 +00001124 });
Chandler Carruth10281422011-10-21 06:46:38 +00001125}
1126
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001127void MachineBlockPlacement::buildCFGChains(MachineFunction &F) {
Chandler Carruth8d150782011-11-13 11:20:44 +00001128 // Ensure that every BB in the function has an associated chain to simplify
1129 // the assumptions of the remaining algorithm.
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001130 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
1131 for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001132 MachineBasicBlock *BB = &*FI;
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001133 BlockChain *Chain =
1134 new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001135 // Also, merge any blocks which we cannot reason about and must preserve
1136 // the exact fallthrough behavior for.
1137 for (;;) {
1138 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001139 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001140 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
1141 break;
1142
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001143 MachineFunction::iterator NextFI = std::next(FI);
1144 MachineBasicBlock *NextBB = &*NextFI;
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001145 // Ensure that the layout successor is a viable block, as we know that
1146 // fallthrough is a possibility.
1147 assert(NextFI != FE && "Can't fallthrough past the last block.");
1148 DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
1149 << getBlockName(BB) << " -> " << getBlockName(NextBB)
1150 << "\n");
Craig Topperc0196b12014-04-14 00:51:57 +00001151 Chain->merge(NextBB, nullptr);
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001152 FI = NextFI;
1153 BB = NextBB;
1154 }
1155 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001156
Daniel Jasper471e8562015-03-04 11:05:34 +00001157 if (OutlineOptionalBranches) {
1158 // Find the nearest common dominator of all of F's terminators.
1159 MachineBasicBlock *Terminator = nullptr;
1160 for (MachineBasicBlock &MBB : F) {
1161 if (MBB.succ_size() == 0) {
1162 if (Terminator == nullptr)
1163 Terminator = &MBB;
1164 else
1165 Terminator = MDT->findNearestCommonDominator(Terminator, &MBB);
1166 }
1167 }
1168
1169 // MBBs dominating this common dominator are unavoidable.
1170 UnavoidableBlocks.clear();
1171 for (MachineBasicBlock &MBB : F) {
1172 if (MDT->dominates(&MBB, Terminator)) {
1173 UnavoidableBlocks.insert(&MBB);
1174 }
1175 }
1176 }
1177
Chandler Carruth8d150782011-11-13 11:20:44 +00001178 // Build any loop-based chains.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001179 for (MachineLoop *L : *MLI)
1180 buildLoopChains(F, *L);
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001181
Chandler Carruth8d150782011-11-13 11:20:44 +00001182 SmallVector<MachineBasicBlock *, 16> BlockWorkList;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001183
Chandler Carruth8d150782011-11-13 11:20:44 +00001184 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001185 for (MachineBasicBlock &MBB : F) {
1186 BlockChain &Chain = *BlockToChain[&MBB];
David Blaikie70573dc2014-11-19 07:49:26 +00001187 if (!UpdatedPreds.insert(&Chain).second)
Chandler Carruth8d150782011-11-13 11:20:44 +00001188 continue;
1189
1190 assert(Chain.LoopPredecessors == 0);
Chandler Carruth7a715da2015-03-05 03:19:05 +00001191 for (MachineBasicBlock *ChainBB : Chain) {
1192 assert(BlockToChain[ChainBB] == &Chain);
1193 for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
1194 if (BlockToChain[Pred] == &Chain)
Chandler Carruth8d150782011-11-13 11:20:44 +00001195 continue;
1196 ++Chain.LoopPredecessors;
1197 }
1198 }
1199
1200 if (Chain.LoopPredecessors == 0)
Chandler Carruthd394baf2011-11-24 08:46:04 +00001201 BlockWorkList.push_back(*Chain.begin());
Chandler Carruth8d150782011-11-13 11:20:44 +00001202 }
1203
1204 BlockChain &FunctionChain = *BlockToChain[&F.front()];
Chandler Carruth9b548a7f2011-11-15 06:26:43 +00001205 buildChain(&F.front(), FunctionChain, BlockWorkList);
Chandler Carruth8d150782011-11-13 11:20:44 +00001206
Matt Arsenault0f5f0152013-12-10 18:55:37 +00001207#ifndef NDEBUG
Matt Arsenault79d55f52013-12-05 20:02:18 +00001208 typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType;
Matt Arsenault0f5f0152013-12-10 18:55:37 +00001209#endif
Chandler Carruth8d150782011-11-13 11:20:44 +00001210 DEBUG({
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001211 // Crash at the end so we get all of the debugging output first.
1212 bool BadFunc = false;
Chandler Carruth8d150782011-11-13 11:20:44 +00001213 FunctionBlockSetType FunctionBlockSet;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001214 for (MachineBasicBlock &MBB : F)
1215 FunctionBlockSet.insert(&MBB);
Chandler Carruth8d150782011-11-13 11:20:44 +00001216
Chandler Carruth7a715da2015-03-05 03:19:05 +00001217 for (MachineBasicBlock *ChainBB : FunctionChain)
1218 if (!FunctionBlockSet.erase(ChainBB)) {
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001219 BadFunc = true;
Chandler Carruth8d150782011-11-13 11:20:44 +00001220 dbgs() << "Function chain contains a block not in the function!\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00001221 << " Bad block: " << getBlockName(ChainBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001222 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001223
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001224 if (!FunctionBlockSet.empty()) {
1225 BadFunc = true;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001226 for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
Chandler Carruth8d150782011-11-13 11:20:44 +00001227 dbgs() << "Function contains blocks never placed into a chain!\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00001228 << " Bad block: " << getBlockName(RemainingBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001229 }
1230 assert(!BadFunc && "Detected problems with the block placement.");
Chandler Carruth8d150782011-11-13 11:20:44 +00001231 });
1232
1233 // Splice the blocks into place.
1234 MachineFunction::iterator InsertPos = F.begin();
Chandler Carruth7a715da2015-03-05 03:19:05 +00001235 for (MachineBasicBlock *ChainBB : FunctionChain) {
1236 DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
1237 : " ... ")
1238 << getBlockName(ChainBB) << "\n");
1239 if (InsertPos != MachineFunction::iterator(ChainBB))
1240 F.splice(InsertPos, ChainBB);
Chandler Carruth8d150782011-11-13 11:20:44 +00001241 else
1242 ++InsertPos;
1243
1244 // Update the terminator of the previous block.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001245 if (ChainBB == *FunctionChain.begin())
Chandler Carruth8d150782011-11-13 11:20:44 +00001246 continue;
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001247 MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB));
Chandler Carruth8d150782011-11-13 11:20:44 +00001248
Chandler Carruth10281422011-10-21 06:46:38 +00001249 // FIXME: It would be awesome of updateTerminator would just return rather
1250 // than assert when the branch cannot be analyzed in order to remove this
1251 // boiler plate.
1252 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001253 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Manman Ren2b6a0df2012-07-31 01:11:07 +00001254 if (!TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001255 // The "PrevBB" is not yet updated to reflect current code layout, so,
1256 // o. it may fall-through to a block without explict "goto" instruction
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001257 // before layout, and no longer fall-through it after layout; or
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001258 // o. just opposite.
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001259 //
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001260 // AnalyzeBranch() may return erroneous value for FBB when these two
1261 // situations take place. For the first scenario FBB is mistakenly set
1262 // NULL; for the 2nd scenario, the FBB, which is expected to be NULL,
1263 // is mistakenly pointing to "*BI".
1264 //
1265 bool needUpdateBr = true;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001266 if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001267 PrevBB->updateTerminator();
1268 needUpdateBr = false;
1269 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001270 TBB = FBB = nullptr;
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001271 if (TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
1272 // FIXME: This should never take place.
Craig Topperc0196b12014-04-14 00:51:57 +00001273 TBB = FBB = nullptr;
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001274 }
1275 }
1276
Manman Ren2b6a0df2012-07-31 01:11:07 +00001277 // If PrevBB has a two-way branch, try to re-order the branches
Cong Houd97c1002015-12-01 05:29:22 +00001278 // such that we branch to the successor with higher probability first.
Manman Ren2b6a0df2012-07-31 01:11:07 +00001279 if (TBB && !Cond.empty() && FBB &&
Cong Houd97c1002015-12-01 05:29:22 +00001280 MBPI->getEdgeProbability(PrevBB, FBB) >
1281 MBPI->getEdgeProbability(PrevBB, TBB) &&
Manman Ren2b6a0df2012-07-31 01:11:07 +00001282 !TII->ReverseBranchCondition(Cond)) {
1283 DEBUG(dbgs() << "Reverse order of the two branches: "
1284 << getBlockName(PrevBB) << "\n");
Cong Houd97c1002015-12-01 05:29:22 +00001285 DEBUG(dbgs() << " Edge probability: "
1286 << MBPI->getEdgeProbability(PrevBB, FBB) << " vs "
1287 << MBPI->getEdgeProbability(PrevBB, TBB) << "\n");
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001288 DebugLoc dl; // FIXME: this is nowhere
Manman Ren2b6a0df2012-07-31 01:11:07 +00001289 TII->RemoveBranch(*PrevBB);
1290 TII->InsertBranch(*PrevBB, FBB, TBB, Cond, dl);
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001291 needUpdateBr = true;
Manman Ren2b6a0df2012-07-31 01:11:07 +00001292 }
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001293 if (needUpdateBr)
1294 PrevBB->updateTerminator();
Manman Ren2b6a0df2012-07-31 01:11:07 +00001295 }
Chandler Carruth10281422011-10-21 06:46:38 +00001296 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001297
1298 // Fixup the last block.
1299 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001300 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Chandler Carruth8d150782011-11-13 11:20:44 +00001301 if (!TII->AnalyzeBranch(F.back(), TBB, FBB, Cond))
1302 F.back().updateTerminator();
Chandler Carruth10281422011-10-21 06:46:38 +00001303
Chandler Carruthccc7e422012-04-16 01:12:56 +00001304 // Walk through the backedges of the function now that we have fully laid out
1305 // the basic blocks and align the destination of each backedge. We don't rely
Chandler Carruth881d0a72012-08-07 09:45:24 +00001306 // exclusively on the loop info here so that we can align backedges in
1307 // unnatural CFGs and backedges that were introduced purely because of the
1308 // loop rotations done during this layout pass.
Sanjay Patel924879a2015-08-04 15:49:57 +00001309 // FIXME: Use Function::optForSize().
Duncan P. N. Exon Smith70eb9c52015-02-14 01:44:41 +00001310 if (F.getFunction()->hasFnAttribute(Attribute::OptimizeForSize))
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001311 return;
Chandler Carruth881d0a72012-08-07 09:45:24 +00001312 if (FunctionChain.begin() == FunctionChain.end())
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001313 return; // Empty chain.
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001314
Chandler Carruth881d0a72012-08-07 09:45:24 +00001315 const BranchProbability ColdProb(1, 5); // 20%
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001316 BlockFrequency EntryFreq = MBFI->getBlockFreq(&F.front());
Chandler Carruth881d0a72012-08-07 09:45:24 +00001317 BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001318 for (MachineBasicBlock *ChainBB : FunctionChain) {
1319 if (ChainBB == *FunctionChain.begin())
1320 continue;
1321
Chandler Carruth881d0a72012-08-07 09:45:24 +00001322 // Don't align non-looping basic blocks. These are unlikely to execute
1323 // enough times to matter in practice. Note that we'll still handle
1324 // unnatural CFGs inside of a natural outer loop (the common case) and
1325 // rotated loops.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001326 MachineLoop *L = MLI->getLoopFor(ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001327 if (!L)
1328 continue;
1329
Hal Finkel57725662015-01-03 17:58:24 +00001330 unsigned Align = TLI->getPrefLoopAlignment(L);
1331 if (!Align)
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001332 continue; // Don't care about loop alignment.
Hal Finkel57725662015-01-03 17:58:24 +00001333
Chandler Carruth881d0a72012-08-07 09:45:24 +00001334 // If the block is cold relative to the function entry don't waste space
1335 // aligning it.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001336 BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001337 if (Freq < WeightedEntryFreq)
1338 continue;
1339
1340 // If the block is cold relative to its loop header, don't align it
1341 // regardless of what edges into the block exist.
1342 MachineBasicBlock *LoopHeader = L->getHeader();
1343 BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
1344 if (Freq < (LoopHeaderFreq * ColdProb))
1345 continue;
1346
1347 // Check for the existence of a non-layout predecessor which would benefit
1348 // from aligning this block.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001349 MachineBasicBlock *LayoutPred =
1350 &*std::prev(MachineFunction::iterator(ChainBB));
Chandler Carruth881d0a72012-08-07 09:45:24 +00001351
1352 // Force alignment if all the predecessors are jumps. We already checked
1353 // that the block isn't cold above.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001354 if (!LayoutPred->isSuccessor(ChainBB)) {
1355 ChainBB->setAlignment(Align);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001356 continue;
1357 }
1358
1359 // Align this block if the layout predecessor's edge into this block is
Nadav Rotem6036f582013-03-29 16:34:23 +00001360 // cold relative to the block. When this is true, other predecessors make up
Chandler Carruth881d0a72012-08-07 09:45:24 +00001361 // all of the hot entries into the block and thus alignment is likely to be
1362 // important.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001363 BranchProbability LayoutProb =
1364 MBPI->getEdgeProbability(LayoutPred, ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001365 BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
1366 if (LayoutEdgeFreq <= (Freq * ColdProb))
Chandler Carruth7a715da2015-03-05 03:19:05 +00001367 ChainBB->setAlignment(Align);
Chandler Carruthccc7e422012-04-16 01:12:56 +00001368 }
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001369}
1370
Chandler Carruth10281422011-10-21 06:46:38 +00001371bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &F) {
1372 // Check for single-block functions and skip them.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001373 if (std::next(F.begin()) == F.end())
Chandler Carruth10281422011-10-21 06:46:38 +00001374 return false;
1375
Paul Robinson7c99ec52014-03-31 17:43:35 +00001376 if (skipOptnoneFunction(*F.getFunction()))
1377 return false;
1378
Chandler Carruth10281422011-10-21 06:46:38 +00001379 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1380 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001381 MLI = &getAnalysis<MachineLoopInfo>();
Eric Christopherfc6de422014-08-05 02:39:49 +00001382 TII = F.getSubtarget().getInstrInfo();
1383 TLI = F.getSubtarget().getTargetLowering();
Daniel Jasper471e8562015-03-04 11:05:34 +00001384 MDT = &getAnalysis<MachineDominatorTree>();
Chandler Carruth10281422011-10-21 06:46:38 +00001385 assert(BlockToChain.empty());
Chandler Carruth10281422011-10-21 06:46:38 +00001386
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001387 buildCFGChains(F);
Chandler Carruth10281422011-10-21 06:46:38 +00001388
Chandler Carruth10281422011-10-21 06:46:38 +00001389 BlockToChain.clear();
Chandler Carruthfd9b4d92011-11-14 10:57:23 +00001390 ChainAllocator.DestroyAll();
Chandler Carruth10281422011-10-21 06:46:38 +00001391
Nadav Rotemc0adc9f2013-04-12 01:24:16 +00001392 if (AlignAllBlock)
1393 // Align all of the blocks in the function to a specific alignment.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001394 for (MachineBasicBlock &MBB : F)
1395 MBB.setAlignment(AlignAllBlock);
Geoff Berry10494ac2016-01-21 17:25:52 +00001396 else if (AlignAllNonFallThruBlocks) {
1397 // Align all of the blocks that have no fall-through predecessors to a
1398 // specific alignment.
1399 for (auto MBI = std::next(F.begin()), MBE = F.end(); MBI != MBE; ++MBI) {
1400 auto LayoutPred = std::prev(MBI);
1401 if (!LayoutPred->isSuccessor(&*MBI))
1402 MBI->setAlignment(AlignAllNonFallThruBlocks);
1403 }
1404 }
Nadav Rotemc0adc9f2013-04-12 01:24:16 +00001405
Chandler Carruth10281422011-10-21 06:46:38 +00001406 // We always return true as we have no way to track whether the final order
1407 // differs from the original order.
1408 return true;
1409}
Chandler Carruthae4e8002011-11-02 07:17:12 +00001410
1411namespace {
1412/// \brief A pass to compute block placement statistics.
1413///
1414/// A separate pass to compute interesting statistics for evaluating block
1415/// placement. This is separate from the actual placement pass so that they can
Benjamin Kramerbde91762012-06-02 10:20:22 +00001416/// be computed in the absence of any placement transformations or when using
Chandler Carruthae4e8002011-11-02 07:17:12 +00001417/// alternative placement strategies.
1418class MachineBlockPlacementStats : public MachineFunctionPass {
1419 /// \brief A handle to the branch probability pass.
1420 const MachineBranchProbabilityInfo *MBPI;
1421
1422 /// \brief A handle to the function-wide block frequency pass.
1423 const MachineBlockFrequencyInfo *MBFI;
1424
1425public:
1426 static char ID; // Pass identification, replacement for typeid
1427 MachineBlockPlacementStats() : MachineFunctionPass(ID) {
1428 initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
1429 }
1430
Craig Topper4584cd52014-03-07 09:26:03 +00001431 bool runOnMachineFunction(MachineFunction &F) override;
Chandler Carruthae4e8002011-11-02 07:17:12 +00001432
Craig Topper4584cd52014-03-07 09:26:03 +00001433 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruthae4e8002011-11-02 07:17:12 +00001434 AU.addRequired<MachineBranchProbabilityInfo>();
1435 AU.addRequired<MachineBlockFrequencyInfo>();
1436 AU.setPreservesAll();
1437 MachineFunctionPass::getAnalysisUsage(AU);
1438 }
Chandler Carruthae4e8002011-11-02 07:17:12 +00001439};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001440}
Chandler Carruthae4e8002011-11-02 07:17:12 +00001441
1442char MachineBlockPlacementStats::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +00001443char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
Chandler Carruthae4e8002011-11-02 07:17:12 +00001444INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
1445 "Basic Block Placement Stats", false, false)
1446INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
1447INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
1448INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
1449 "Basic Block Placement Stats", false, false)
1450
Chandler Carruthae4e8002011-11-02 07:17:12 +00001451bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
1452 // Check for single-block functions and skip them.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001453 if (std::next(F.begin()) == F.end())
Chandler Carruthae4e8002011-11-02 07:17:12 +00001454 return false;
1455
1456 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1457 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1458
Chandler Carruth7a715da2015-03-05 03:19:05 +00001459 for (MachineBasicBlock &MBB : F) {
1460 BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001461 Statistic &NumBranches =
Chandler Carruth7a715da2015-03-05 03:19:05 +00001462 (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001463 Statistic &BranchTakenFreq =
Chandler Carruth7a715da2015-03-05 03:19:05 +00001464 (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
1465 for (MachineBasicBlock *Succ : MBB.successors()) {
Chandler Carruthae4e8002011-11-02 07:17:12 +00001466 // Skip if this successor is a fallthrough.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001467 if (MBB.isLayoutSuccessor(Succ))
Chandler Carruthae4e8002011-11-02 07:17:12 +00001468 continue;
1469
Chandler Carruth7a715da2015-03-05 03:19:05 +00001470 BlockFrequency EdgeFreq =
1471 BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
Chandler Carruthae4e8002011-11-02 07:17:12 +00001472 ++NumBranches;
1473 BranchTakenFreq += EdgeFreq.getFrequency();
1474 }
1475 }
1476
1477 return false;
1478}