1f4a2713aSLionel Sambuc //===-- MachineBlockPlacement.cpp - Basic Block Code Layout optimization --===//
2f4a2713aSLionel Sambuc //
3f4a2713aSLionel Sambuc // The LLVM Compiler Infrastructure
4f4a2713aSLionel Sambuc //
5f4a2713aSLionel Sambuc // This file is distributed under the University of Illinois Open Source
6f4a2713aSLionel Sambuc // License. See LICENSE.TXT for details.
7f4a2713aSLionel Sambuc //
8f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
9f4a2713aSLionel Sambuc //
10f4a2713aSLionel Sambuc // This file implements basic block placement transformations using the CFG
11f4a2713aSLionel Sambuc // structure and branch probability estimates.
12f4a2713aSLionel Sambuc //
13f4a2713aSLionel Sambuc // The pass strives to preserve the structure of the CFG (that is, retain
14f4a2713aSLionel Sambuc // a topological ordering of basic blocks) in the absence of a *strong* signal
15f4a2713aSLionel Sambuc // to the contrary from probabilities. However, within the CFG structure, it
16f4a2713aSLionel Sambuc // attempts to choose an ordering which favors placing more likely sequences of
17f4a2713aSLionel Sambuc // blocks adjacent to each other.
18f4a2713aSLionel Sambuc //
19f4a2713aSLionel Sambuc // The algorithm works from the inner-most loop within a function outward, and
20f4a2713aSLionel Sambuc // at each stage walks through the basic blocks, trying to coalesce them into
21f4a2713aSLionel Sambuc // sequential chains where allowed by the CFG (or demanded by heavy
22f4a2713aSLionel Sambuc // probabilities). Finally, it walks the blocks in topological order, and the
23f4a2713aSLionel Sambuc // first time it reaches a chain of basic blocks, it schedules them in the
24f4a2713aSLionel Sambuc // function in-order.
25f4a2713aSLionel Sambuc //
26f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
27f4a2713aSLionel Sambuc
28f4a2713aSLionel Sambuc #include "llvm/CodeGen/Passes.h"
29f4a2713aSLionel Sambuc #include "llvm/ADT/DenseMap.h"
30f4a2713aSLionel Sambuc #include "llvm/ADT/SmallPtrSet.h"
31f4a2713aSLionel Sambuc #include "llvm/ADT/SmallVector.h"
32f4a2713aSLionel Sambuc #include "llvm/ADT/Statistic.h"
33f4a2713aSLionel Sambuc #include "llvm/CodeGen/MachineBasicBlock.h"
34f4a2713aSLionel Sambuc #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
35f4a2713aSLionel Sambuc #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
36f4a2713aSLionel Sambuc #include "llvm/CodeGen/MachineFunction.h"
37f4a2713aSLionel Sambuc #include "llvm/CodeGen/MachineFunctionPass.h"
38f4a2713aSLionel Sambuc #include "llvm/CodeGen/MachineLoopInfo.h"
39f4a2713aSLionel Sambuc #include "llvm/CodeGen/MachineModuleInfo.h"
40f4a2713aSLionel Sambuc #include "llvm/Support/Allocator.h"
41f4a2713aSLionel Sambuc #include "llvm/Support/CommandLine.h"
42f4a2713aSLionel Sambuc #include "llvm/Support/Debug.h"
43f4a2713aSLionel Sambuc #include "llvm/Target/TargetInstrInfo.h"
44f4a2713aSLionel Sambuc #include "llvm/Target/TargetLowering.h"
45*0a6a1f1dSLionel Sambuc #include "llvm/Target/TargetSubtargetInfo.h"
46f4a2713aSLionel Sambuc #include <algorithm>
47f4a2713aSLionel Sambuc using namespace llvm;
48f4a2713aSLionel Sambuc
49*0a6a1f1dSLionel Sambuc #define DEBUG_TYPE "block-placement2"
50*0a6a1f1dSLionel Sambuc
51f4a2713aSLionel Sambuc STATISTIC(NumCondBranches, "Number of conditional branches");
52f4a2713aSLionel Sambuc STATISTIC(NumUncondBranches, "Number of uncondittional branches");
53f4a2713aSLionel Sambuc STATISTIC(CondBranchTakenFreq,
54f4a2713aSLionel Sambuc "Potential frequency of taking conditional branches");
55f4a2713aSLionel Sambuc STATISTIC(UncondBranchTakenFreq,
56f4a2713aSLionel Sambuc "Potential frequency of taking unconditional branches");
57f4a2713aSLionel Sambuc
58f4a2713aSLionel Sambuc static cl::opt<unsigned> AlignAllBlock("align-all-blocks",
59f4a2713aSLionel Sambuc cl::desc("Force the alignment of all "
60f4a2713aSLionel Sambuc "blocks in the function."),
61f4a2713aSLionel Sambuc cl::init(0), cl::Hidden);
62f4a2713aSLionel Sambuc
63*0a6a1f1dSLionel Sambuc // FIXME: Find a good default for this flag and remove the flag.
64*0a6a1f1dSLionel Sambuc static cl::opt<unsigned>
65*0a6a1f1dSLionel Sambuc ExitBlockBias("block-placement-exit-block-bias",
66*0a6a1f1dSLionel Sambuc cl::desc("Block frequency percentage a loop exit block needs "
67*0a6a1f1dSLionel Sambuc "over the original exit to be considered the new exit."),
68*0a6a1f1dSLionel Sambuc cl::init(0), cl::Hidden);
69*0a6a1f1dSLionel Sambuc
70f4a2713aSLionel Sambuc namespace {
71f4a2713aSLionel Sambuc class BlockChain;
72f4a2713aSLionel Sambuc /// \brief Type for our function-wide basic block -> block chain mapping.
73f4a2713aSLionel Sambuc typedef DenseMap<MachineBasicBlock *, BlockChain *> BlockToChainMapType;
74f4a2713aSLionel Sambuc }
75f4a2713aSLionel Sambuc
76f4a2713aSLionel Sambuc namespace {
77f4a2713aSLionel Sambuc /// \brief A chain of blocks which will be laid out contiguously.
78f4a2713aSLionel Sambuc ///
79f4a2713aSLionel Sambuc /// This is the datastructure representing a chain of consecutive blocks that
80f4a2713aSLionel Sambuc /// are profitable to layout together in order to maximize fallthrough
81f4a2713aSLionel Sambuc /// probabilities and code locality. We also can use a block chain to represent
82f4a2713aSLionel Sambuc /// a sequence of basic blocks which have some external (correctness)
83f4a2713aSLionel Sambuc /// requirement for sequential layout.
84f4a2713aSLionel Sambuc ///
85f4a2713aSLionel Sambuc /// Chains can be built around a single basic block and can be merged to grow
86f4a2713aSLionel Sambuc /// them. They participate in a block-to-chain mapping, which is updated
87f4a2713aSLionel Sambuc /// automatically as chains are merged together.
88f4a2713aSLionel Sambuc class BlockChain {
89f4a2713aSLionel Sambuc /// \brief The sequence of blocks belonging to this chain.
90f4a2713aSLionel Sambuc ///
91f4a2713aSLionel Sambuc /// This is the sequence of blocks for a particular chain. These will be laid
92f4a2713aSLionel Sambuc /// out in-order within the function.
93f4a2713aSLionel Sambuc SmallVector<MachineBasicBlock *, 4> Blocks;
94f4a2713aSLionel Sambuc
95f4a2713aSLionel Sambuc /// \brief A handle to the function-wide basic block to block chain mapping.
96f4a2713aSLionel Sambuc ///
97f4a2713aSLionel Sambuc /// This is retained in each block chain to simplify the computation of child
98f4a2713aSLionel Sambuc /// block chains for SCC-formation and iteration. We store the edges to child
99f4a2713aSLionel Sambuc /// basic blocks, and map them back to their associated chains using this
100f4a2713aSLionel Sambuc /// structure.
101f4a2713aSLionel Sambuc BlockToChainMapType &BlockToChain;
102f4a2713aSLionel Sambuc
103f4a2713aSLionel Sambuc public:
104f4a2713aSLionel Sambuc /// \brief Construct a new BlockChain.
105f4a2713aSLionel Sambuc ///
106f4a2713aSLionel Sambuc /// This builds a new block chain representing a single basic block in the
107f4a2713aSLionel Sambuc /// function. It also registers itself as the chain that block participates
108f4a2713aSLionel Sambuc /// in with the BlockToChain mapping.
BlockChain(BlockToChainMapType & BlockToChain,MachineBasicBlock * BB)109f4a2713aSLionel Sambuc BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
110f4a2713aSLionel Sambuc : Blocks(1, BB), BlockToChain(BlockToChain), LoopPredecessors(0) {
111f4a2713aSLionel Sambuc assert(BB && "Cannot create a chain with a null basic block");
112f4a2713aSLionel Sambuc BlockToChain[BB] = this;
113f4a2713aSLionel Sambuc }
114f4a2713aSLionel Sambuc
115f4a2713aSLionel Sambuc /// \brief Iterator over blocks within the chain.
116f4a2713aSLionel Sambuc typedef SmallVectorImpl<MachineBasicBlock *>::iterator iterator;
117f4a2713aSLionel Sambuc
118f4a2713aSLionel Sambuc /// \brief Beginning of blocks within the chain.
begin()119f4a2713aSLionel Sambuc iterator begin() { return Blocks.begin(); }
120f4a2713aSLionel Sambuc
121f4a2713aSLionel Sambuc /// \brief End of blocks within the chain.
end()122f4a2713aSLionel Sambuc iterator end() { return Blocks.end(); }
123f4a2713aSLionel Sambuc
124f4a2713aSLionel Sambuc /// \brief Merge a block chain into this one.
125f4a2713aSLionel Sambuc ///
126f4a2713aSLionel Sambuc /// This routine merges a block chain into this one. It takes care of forming
127f4a2713aSLionel Sambuc /// a contiguous sequence of basic blocks, updating the edge list, and
128f4a2713aSLionel Sambuc /// updating the block -> chain mapping. It does not free or tear down the
129f4a2713aSLionel Sambuc /// old chain, but the old chain's block list is no longer valid.
merge(MachineBasicBlock * BB,BlockChain * Chain)130f4a2713aSLionel Sambuc void merge(MachineBasicBlock *BB, BlockChain *Chain) {
131f4a2713aSLionel Sambuc assert(BB);
132f4a2713aSLionel Sambuc assert(!Blocks.empty());
133f4a2713aSLionel Sambuc
134f4a2713aSLionel Sambuc // Fast path in case we don't have a chain already.
135f4a2713aSLionel Sambuc if (!Chain) {
136f4a2713aSLionel Sambuc assert(!BlockToChain[BB]);
137f4a2713aSLionel Sambuc Blocks.push_back(BB);
138f4a2713aSLionel Sambuc BlockToChain[BB] = this;
139f4a2713aSLionel Sambuc return;
140f4a2713aSLionel Sambuc }
141f4a2713aSLionel Sambuc
142f4a2713aSLionel Sambuc assert(BB == *Chain->begin());
143f4a2713aSLionel Sambuc assert(Chain->begin() != Chain->end());
144f4a2713aSLionel Sambuc
145f4a2713aSLionel Sambuc // Update the incoming blocks to point to this chain, and add them to the
146f4a2713aSLionel Sambuc // chain structure.
147f4a2713aSLionel Sambuc for (BlockChain::iterator BI = Chain->begin(), BE = Chain->end();
148f4a2713aSLionel Sambuc BI != BE; ++BI) {
149f4a2713aSLionel Sambuc Blocks.push_back(*BI);
150f4a2713aSLionel Sambuc assert(BlockToChain[*BI] == Chain && "Incoming blocks not in chain");
151f4a2713aSLionel Sambuc BlockToChain[*BI] = this;
152f4a2713aSLionel Sambuc }
153f4a2713aSLionel Sambuc }
154f4a2713aSLionel Sambuc
155f4a2713aSLionel Sambuc #ifndef NDEBUG
156f4a2713aSLionel Sambuc /// \brief Dump the blocks in this chain.
dump()157*0a6a1f1dSLionel Sambuc LLVM_DUMP_METHOD void dump() {
158f4a2713aSLionel Sambuc for (iterator I = begin(), E = end(); I != E; ++I)
159f4a2713aSLionel Sambuc (*I)->dump();
160f4a2713aSLionel Sambuc }
161f4a2713aSLionel Sambuc #endif // NDEBUG
162f4a2713aSLionel Sambuc
163f4a2713aSLionel Sambuc /// \brief Count of predecessors within the loop currently being processed.
164f4a2713aSLionel Sambuc ///
165f4a2713aSLionel Sambuc /// This count is updated at each loop we process to represent the number of
166f4a2713aSLionel Sambuc /// in-loop predecessors of this chain.
167f4a2713aSLionel Sambuc unsigned LoopPredecessors;
168f4a2713aSLionel Sambuc };
169f4a2713aSLionel Sambuc }
170f4a2713aSLionel Sambuc
171f4a2713aSLionel Sambuc namespace {
172f4a2713aSLionel Sambuc class MachineBlockPlacement : public MachineFunctionPass {
173f4a2713aSLionel Sambuc /// \brief A typedef for a block filter set.
174f4a2713aSLionel Sambuc typedef SmallPtrSet<MachineBasicBlock *, 16> BlockFilterSet;
175f4a2713aSLionel Sambuc
176f4a2713aSLionel Sambuc /// \brief A handle to the branch probability pass.
177f4a2713aSLionel Sambuc const MachineBranchProbabilityInfo *MBPI;
178f4a2713aSLionel Sambuc
179f4a2713aSLionel Sambuc /// \brief A handle to the function-wide block frequency pass.
180f4a2713aSLionel Sambuc const MachineBlockFrequencyInfo *MBFI;
181f4a2713aSLionel Sambuc
182f4a2713aSLionel Sambuc /// \brief A handle to the loop info.
183f4a2713aSLionel Sambuc const MachineLoopInfo *MLI;
184f4a2713aSLionel Sambuc
185f4a2713aSLionel Sambuc /// \brief A handle to the target's instruction info.
186f4a2713aSLionel Sambuc const TargetInstrInfo *TII;
187f4a2713aSLionel Sambuc
188f4a2713aSLionel Sambuc /// \brief A handle to the target's lowering info.
189f4a2713aSLionel Sambuc const TargetLoweringBase *TLI;
190f4a2713aSLionel Sambuc
191f4a2713aSLionel Sambuc /// \brief Allocator and owner of BlockChain structures.
192f4a2713aSLionel Sambuc ///
193f4a2713aSLionel Sambuc /// We build BlockChains lazily while processing the loop structure of
194f4a2713aSLionel Sambuc /// a function. To reduce malloc traffic, we allocate them using this
195f4a2713aSLionel Sambuc /// slab-like allocator, and destroy them after the pass completes. An
196f4a2713aSLionel Sambuc /// important guarantee is that this allocator produces stable pointers to
197f4a2713aSLionel Sambuc /// the chains.
198f4a2713aSLionel Sambuc SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
199f4a2713aSLionel Sambuc
200f4a2713aSLionel Sambuc /// \brief Function wide BasicBlock to BlockChain mapping.
201f4a2713aSLionel Sambuc ///
202f4a2713aSLionel Sambuc /// This mapping allows efficiently moving from any given basic block to the
203f4a2713aSLionel Sambuc /// BlockChain it participates in, if any. We use it to, among other things,
204f4a2713aSLionel Sambuc /// allow implicitly defining edges between chains as the existing edges
205f4a2713aSLionel Sambuc /// between basic blocks.
206f4a2713aSLionel Sambuc DenseMap<MachineBasicBlock *, BlockChain *> BlockToChain;
207f4a2713aSLionel Sambuc
208f4a2713aSLionel Sambuc void markChainSuccessors(BlockChain &Chain,
209f4a2713aSLionel Sambuc MachineBasicBlock *LoopHeaderBB,
210f4a2713aSLionel Sambuc SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
211*0a6a1f1dSLionel Sambuc const BlockFilterSet *BlockFilter = nullptr);
212f4a2713aSLionel Sambuc MachineBasicBlock *selectBestSuccessor(MachineBasicBlock *BB,
213f4a2713aSLionel Sambuc BlockChain &Chain,
214f4a2713aSLionel Sambuc const BlockFilterSet *BlockFilter);
215f4a2713aSLionel Sambuc MachineBasicBlock *selectBestCandidateBlock(
216f4a2713aSLionel Sambuc BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList,
217f4a2713aSLionel Sambuc const BlockFilterSet *BlockFilter);
218f4a2713aSLionel Sambuc MachineBasicBlock *getFirstUnplacedBlock(
219f4a2713aSLionel Sambuc MachineFunction &F,
220f4a2713aSLionel Sambuc const BlockChain &PlacedChain,
221f4a2713aSLionel Sambuc MachineFunction::iterator &PrevUnplacedBlockIt,
222f4a2713aSLionel Sambuc const BlockFilterSet *BlockFilter);
223f4a2713aSLionel Sambuc void buildChain(MachineBasicBlock *BB, BlockChain &Chain,
224f4a2713aSLionel Sambuc SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
225*0a6a1f1dSLionel Sambuc const BlockFilterSet *BlockFilter = nullptr);
226f4a2713aSLionel Sambuc MachineBasicBlock *findBestLoopTop(MachineLoop &L,
227f4a2713aSLionel Sambuc const BlockFilterSet &LoopBlockSet);
228f4a2713aSLionel Sambuc MachineBasicBlock *findBestLoopExit(MachineFunction &F,
229f4a2713aSLionel Sambuc MachineLoop &L,
230f4a2713aSLionel Sambuc const BlockFilterSet &LoopBlockSet);
231f4a2713aSLionel Sambuc void buildLoopChains(MachineFunction &F, MachineLoop &L);
232f4a2713aSLionel Sambuc void rotateLoop(BlockChain &LoopChain, MachineBasicBlock *ExitingBB,
233f4a2713aSLionel Sambuc const BlockFilterSet &LoopBlockSet);
234f4a2713aSLionel Sambuc void buildCFGChains(MachineFunction &F);
235f4a2713aSLionel Sambuc
236f4a2713aSLionel Sambuc public:
237f4a2713aSLionel Sambuc static char ID; // Pass identification, replacement for typeid
MachineBlockPlacement()238f4a2713aSLionel Sambuc MachineBlockPlacement() : MachineFunctionPass(ID) {
239f4a2713aSLionel Sambuc initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
240f4a2713aSLionel Sambuc }
241f4a2713aSLionel Sambuc
242*0a6a1f1dSLionel Sambuc bool runOnMachineFunction(MachineFunction &F) override;
243f4a2713aSLionel Sambuc
getAnalysisUsage(AnalysisUsage & AU) const244*0a6a1f1dSLionel Sambuc void getAnalysisUsage(AnalysisUsage &AU) const override {
245f4a2713aSLionel Sambuc AU.addRequired<MachineBranchProbabilityInfo>();
246f4a2713aSLionel Sambuc AU.addRequired<MachineBlockFrequencyInfo>();
247f4a2713aSLionel Sambuc AU.addRequired<MachineLoopInfo>();
248f4a2713aSLionel Sambuc MachineFunctionPass::getAnalysisUsage(AU);
249f4a2713aSLionel Sambuc }
250f4a2713aSLionel Sambuc };
251f4a2713aSLionel Sambuc }
252f4a2713aSLionel Sambuc
253f4a2713aSLionel Sambuc char MachineBlockPlacement::ID = 0;
254f4a2713aSLionel Sambuc char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
255f4a2713aSLionel Sambuc INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement2",
256f4a2713aSLionel Sambuc "Branch Probability Basic Block Placement", false, false)
INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)257f4a2713aSLionel Sambuc INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
258f4a2713aSLionel Sambuc INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
259f4a2713aSLionel Sambuc INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
260f4a2713aSLionel Sambuc INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement2",
261f4a2713aSLionel Sambuc "Branch Probability Basic Block Placement", false, false)
262f4a2713aSLionel Sambuc
263f4a2713aSLionel Sambuc #ifndef NDEBUG
264f4a2713aSLionel Sambuc /// \brief Helper to print the name of a MBB.
265f4a2713aSLionel Sambuc ///
266f4a2713aSLionel Sambuc /// Only used by debug logging.
267f4a2713aSLionel Sambuc static std::string getBlockName(MachineBasicBlock *BB) {
268f4a2713aSLionel Sambuc std::string Result;
269f4a2713aSLionel Sambuc raw_string_ostream OS(Result);
270f4a2713aSLionel Sambuc OS << "BB#" << BB->getNumber()
271f4a2713aSLionel Sambuc << " (derived from LLVM BB '" << BB->getName() << "')";
272f4a2713aSLionel Sambuc OS.flush();
273f4a2713aSLionel Sambuc return Result;
274f4a2713aSLionel Sambuc }
275f4a2713aSLionel Sambuc
276f4a2713aSLionel Sambuc /// \brief Helper to print the number of a MBB.
277f4a2713aSLionel Sambuc ///
278f4a2713aSLionel Sambuc /// Only used by debug logging.
getBlockNum(MachineBasicBlock * BB)279f4a2713aSLionel Sambuc static std::string getBlockNum(MachineBasicBlock *BB) {
280f4a2713aSLionel Sambuc std::string Result;
281f4a2713aSLionel Sambuc raw_string_ostream OS(Result);
282f4a2713aSLionel Sambuc OS << "BB#" << BB->getNumber();
283f4a2713aSLionel Sambuc OS.flush();
284f4a2713aSLionel Sambuc return Result;
285f4a2713aSLionel Sambuc }
286f4a2713aSLionel Sambuc #endif
287f4a2713aSLionel Sambuc
288f4a2713aSLionel Sambuc /// \brief Mark a chain's successors as having one fewer preds.
289f4a2713aSLionel Sambuc ///
290f4a2713aSLionel Sambuc /// When a chain is being merged into the "placed" chain, this routine will
291f4a2713aSLionel Sambuc /// quickly walk the successors of each block in the chain and mark them as
292f4a2713aSLionel Sambuc /// having one fewer active predecessor. It also adds any successors of this
293f4a2713aSLionel Sambuc /// chain which reach the zero-predecessor state to the worklist passed in.
markChainSuccessors(BlockChain & Chain,MachineBasicBlock * LoopHeaderBB,SmallVectorImpl<MachineBasicBlock * > & BlockWorkList,const BlockFilterSet * BlockFilter)294f4a2713aSLionel Sambuc void MachineBlockPlacement::markChainSuccessors(
295f4a2713aSLionel Sambuc BlockChain &Chain,
296f4a2713aSLionel Sambuc MachineBasicBlock *LoopHeaderBB,
297f4a2713aSLionel Sambuc SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
298f4a2713aSLionel Sambuc const BlockFilterSet *BlockFilter) {
299f4a2713aSLionel Sambuc // Walk all the blocks in this chain, marking their successors as having
300f4a2713aSLionel Sambuc // a predecessor placed.
301f4a2713aSLionel Sambuc for (BlockChain::iterator CBI = Chain.begin(), CBE = Chain.end();
302f4a2713aSLionel Sambuc CBI != CBE; ++CBI) {
303f4a2713aSLionel Sambuc // Add any successors for which this is the only un-placed in-loop
304f4a2713aSLionel Sambuc // predecessor to the worklist as a viable candidate for CFG-neutral
305f4a2713aSLionel Sambuc // placement. No subsequent placement of this block will violate the CFG
306f4a2713aSLionel Sambuc // shape, so we get to use heuristics to choose a favorable placement.
307f4a2713aSLionel Sambuc for (MachineBasicBlock::succ_iterator SI = (*CBI)->succ_begin(),
308f4a2713aSLionel Sambuc SE = (*CBI)->succ_end();
309f4a2713aSLionel Sambuc SI != SE; ++SI) {
310f4a2713aSLionel Sambuc if (BlockFilter && !BlockFilter->count(*SI))
311f4a2713aSLionel Sambuc continue;
312f4a2713aSLionel Sambuc BlockChain &SuccChain = *BlockToChain[*SI];
313f4a2713aSLionel Sambuc // Disregard edges within a fixed chain, or edges to the loop header.
314f4a2713aSLionel Sambuc if (&Chain == &SuccChain || *SI == LoopHeaderBB)
315f4a2713aSLionel Sambuc continue;
316f4a2713aSLionel Sambuc
317f4a2713aSLionel Sambuc // This is a cross-chain edge that is within the loop, so decrement the
318f4a2713aSLionel Sambuc // loop predecessor count of the destination chain.
319f4a2713aSLionel Sambuc if (SuccChain.LoopPredecessors > 0 && --SuccChain.LoopPredecessors == 0)
320f4a2713aSLionel Sambuc BlockWorkList.push_back(*SuccChain.begin());
321f4a2713aSLionel Sambuc }
322f4a2713aSLionel Sambuc }
323f4a2713aSLionel Sambuc }
324f4a2713aSLionel Sambuc
325f4a2713aSLionel Sambuc /// \brief Select the best successor for a block.
326f4a2713aSLionel Sambuc ///
327f4a2713aSLionel Sambuc /// This looks across all successors of a particular block and attempts to
328f4a2713aSLionel Sambuc /// select the "best" one to be the layout successor. It only considers direct
329f4a2713aSLionel Sambuc /// successors which also pass the block filter. It will attempt to avoid
330f4a2713aSLionel Sambuc /// breaking CFG structure, but cave and break such structures in the case of
331f4a2713aSLionel Sambuc /// very hot successor edges.
332f4a2713aSLionel Sambuc ///
333f4a2713aSLionel Sambuc /// \returns The best successor block found, or null if none are viable.
selectBestSuccessor(MachineBasicBlock * BB,BlockChain & Chain,const BlockFilterSet * BlockFilter)334f4a2713aSLionel Sambuc MachineBasicBlock *MachineBlockPlacement::selectBestSuccessor(
335f4a2713aSLionel Sambuc MachineBasicBlock *BB, BlockChain &Chain,
336f4a2713aSLionel Sambuc const BlockFilterSet *BlockFilter) {
337f4a2713aSLionel Sambuc const BranchProbability HotProb(4, 5); // 80%
338f4a2713aSLionel Sambuc
339*0a6a1f1dSLionel Sambuc MachineBasicBlock *BestSucc = nullptr;
340f4a2713aSLionel Sambuc // FIXME: Due to the performance of the probability and weight routines in
341f4a2713aSLionel Sambuc // the MBPI analysis, we manually compute probabilities using the edge
342f4a2713aSLionel Sambuc // weights. This is suboptimal as it means that the somewhat subtle
343f4a2713aSLionel Sambuc // definition of edge weight semantics is encoded here as well. We should
344f4a2713aSLionel Sambuc // improve the MBPI interface to efficiently support query patterns such as
345f4a2713aSLionel Sambuc // this.
346f4a2713aSLionel Sambuc uint32_t BestWeight = 0;
347f4a2713aSLionel Sambuc uint32_t WeightScale = 0;
348f4a2713aSLionel Sambuc uint32_t SumWeight = MBPI->getSumForBlock(BB, WeightScale);
349f4a2713aSLionel Sambuc DEBUG(dbgs() << "Attempting merge from: " << getBlockName(BB) << "\n");
350f4a2713aSLionel Sambuc for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
351f4a2713aSLionel Sambuc SE = BB->succ_end();
352f4a2713aSLionel Sambuc SI != SE; ++SI) {
353f4a2713aSLionel Sambuc if (BlockFilter && !BlockFilter->count(*SI))
354f4a2713aSLionel Sambuc continue;
355f4a2713aSLionel Sambuc BlockChain &SuccChain = *BlockToChain[*SI];
356f4a2713aSLionel Sambuc if (&SuccChain == &Chain) {
357f4a2713aSLionel Sambuc DEBUG(dbgs() << " " << getBlockName(*SI) << " -> Already merged!\n");
358f4a2713aSLionel Sambuc continue;
359f4a2713aSLionel Sambuc }
360f4a2713aSLionel Sambuc if (*SI != *SuccChain.begin()) {
361f4a2713aSLionel Sambuc DEBUG(dbgs() << " " << getBlockName(*SI) << " -> Mid chain!\n");
362f4a2713aSLionel Sambuc continue;
363f4a2713aSLionel Sambuc }
364f4a2713aSLionel Sambuc
365f4a2713aSLionel Sambuc uint32_t SuccWeight = MBPI->getEdgeWeight(BB, *SI);
366f4a2713aSLionel Sambuc BranchProbability SuccProb(SuccWeight / WeightScale, SumWeight);
367f4a2713aSLionel Sambuc
368f4a2713aSLionel Sambuc // Only consider successors which are either "hot", or wouldn't violate
369f4a2713aSLionel Sambuc // any CFG constraints.
370f4a2713aSLionel Sambuc if (SuccChain.LoopPredecessors != 0) {
371f4a2713aSLionel Sambuc if (SuccProb < HotProb) {
372*0a6a1f1dSLionel Sambuc DEBUG(dbgs() << " " << getBlockName(*SI) << " -> " << SuccProb
373*0a6a1f1dSLionel Sambuc << " (prob) (CFG conflict)\n");
374f4a2713aSLionel Sambuc continue;
375f4a2713aSLionel Sambuc }
376f4a2713aSLionel Sambuc
377f4a2713aSLionel Sambuc // Make sure that a hot successor doesn't have a globally more important
378f4a2713aSLionel Sambuc // predecessor.
379f4a2713aSLionel Sambuc BlockFrequency CandidateEdgeFreq
380f4a2713aSLionel Sambuc = MBFI->getBlockFreq(BB) * SuccProb * HotProb.getCompl();
381f4a2713aSLionel Sambuc bool BadCFGConflict = false;
382f4a2713aSLionel Sambuc for (MachineBasicBlock::pred_iterator PI = (*SI)->pred_begin(),
383f4a2713aSLionel Sambuc PE = (*SI)->pred_end();
384f4a2713aSLionel Sambuc PI != PE; ++PI) {
385f4a2713aSLionel Sambuc if (*PI == *SI || (BlockFilter && !BlockFilter->count(*PI)) ||
386f4a2713aSLionel Sambuc BlockToChain[*PI] == &Chain)
387f4a2713aSLionel Sambuc continue;
388f4a2713aSLionel Sambuc BlockFrequency PredEdgeFreq
389f4a2713aSLionel Sambuc = MBFI->getBlockFreq(*PI) * MBPI->getEdgeProbability(*PI, *SI);
390f4a2713aSLionel Sambuc if (PredEdgeFreq >= CandidateEdgeFreq) {
391f4a2713aSLionel Sambuc BadCFGConflict = true;
392f4a2713aSLionel Sambuc break;
393f4a2713aSLionel Sambuc }
394f4a2713aSLionel Sambuc }
395f4a2713aSLionel Sambuc if (BadCFGConflict) {
396*0a6a1f1dSLionel Sambuc DEBUG(dbgs() << " " << getBlockName(*SI) << " -> " << SuccProb
397*0a6a1f1dSLionel Sambuc << " (prob) (non-cold CFG conflict)\n");
398f4a2713aSLionel Sambuc continue;
399f4a2713aSLionel Sambuc }
400f4a2713aSLionel Sambuc }
401f4a2713aSLionel Sambuc
402f4a2713aSLionel Sambuc DEBUG(dbgs() << " " << getBlockName(*SI) << " -> " << SuccProb
403f4a2713aSLionel Sambuc << " (prob)"
404f4a2713aSLionel Sambuc << (SuccChain.LoopPredecessors != 0 ? " (CFG break)" : "")
405f4a2713aSLionel Sambuc << "\n");
406f4a2713aSLionel Sambuc if (BestSucc && BestWeight >= SuccWeight)
407f4a2713aSLionel Sambuc continue;
408f4a2713aSLionel Sambuc BestSucc = *SI;
409f4a2713aSLionel Sambuc BestWeight = SuccWeight;
410f4a2713aSLionel Sambuc }
411f4a2713aSLionel Sambuc return BestSucc;
412f4a2713aSLionel Sambuc }
413f4a2713aSLionel Sambuc
414f4a2713aSLionel Sambuc /// \brief Select the best block from a worklist.
415f4a2713aSLionel Sambuc ///
416f4a2713aSLionel Sambuc /// This looks through the provided worklist as a list of candidate basic
417f4a2713aSLionel Sambuc /// blocks and select the most profitable one to place. The definition of
418f4a2713aSLionel Sambuc /// profitable only really makes sense in the context of a loop. This returns
419f4a2713aSLionel Sambuc /// the most frequently visited block in the worklist, which in the case of
420f4a2713aSLionel Sambuc /// a loop, is the one most desirable to be physically close to the rest of the
421f4a2713aSLionel Sambuc /// loop body in order to improve icache behavior.
422f4a2713aSLionel Sambuc ///
423f4a2713aSLionel Sambuc /// \returns The best block found, or null if none are viable.
selectBestCandidateBlock(BlockChain & Chain,SmallVectorImpl<MachineBasicBlock * > & WorkList,const BlockFilterSet * BlockFilter)424f4a2713aSLionel Sambuc MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
425f4a2713aSLionel Sambuc BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList,
426f4a2713aSLionel Sambuc const BlockFilterSet *BlockFilter) {
427f4a2713aSLionel Sambuc // Once we need to walk the worklist looking for a candidate, cleanup the
428f4a2713aSLionel Sambuc // worklist of already placed entries.
429f4a2713aSLionel Sambuc // FIXME: If this shows up on profiles, it could be folded (at the cost of
430f4a2713aSLionel Sambuc // some code complexity) into the loop below.
431f4a2713aSLionel Sambuc WorkList.erase(std::remove_if(WorkList.begin(), WorkList.end(),
432*0a6a1f1dSLionel Sambuc [&](MachineBasicBlock *BB) {
433*0a6a1f1dSLionel Sambuc return BlockToChain.lookup(BB) == &Chain;
434*0a6a1f1dSLionel Sambuc }),
435f4a2713aSLionel Sambuc WorkList.end());
436f4a2713aSLionel Sambuc
437*0a6a1f1dSLionel Sambuc MachineBasicBlock *BestBlock = nullptr;
438f4a2713aSLionel Sambuc BlockFrequency BestFreq;
439f4a2713aSLionel Sambuc for (SmallVectorImpl<MachineBasicBlock *>::iterator WBI = WorkList.begin(),
440f4a2713aSLionel Sambuc WBE = WorkList.end();
441f4a2713aSLionel Sambuc WBI != WBE; ++WBI) {
442f4a2713aSLionel Sambuc BlockChain &SuccChain = *BlockToChain[*WBI];
443f4a2713aSLionel Sambuc if (&SuccChain == &Chain) {
444f4a2713aSLionel Sambuc DEBUG(dbgs() << " " << getBlockName(*WBI)
445f4a2713aSLionel Sambuc << " -> Already merged!\n");
446f4a2713aSLionel Sambuc continue;
447f4a2713aSLionel Sambuc }
448f4a2713aSLionel Sambuc assert(SuccChain.LoopPredecessors == 0 && "Found CFG-violating block");
449f4a2713aSLionel Sambuc
450f4a2713aSLionel Sambuc BlockFrequency CandidateFreq = MBFI->getBlockFreq(*WBI);
451*0a6a1f1dSLionel Sambuc DEBUG(dbgs() << " " << getBlockName(*WBI) << " -> ";
452*0a6a1f1dSLionel Sambuc MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
453f4a2713aSLionel Sambuc if (BestBlock && BestFreq >= CandidateFreq)
454f4a2713aSLionel Sambuc continue;
455f4a2713aSLionel Sambuc BestBlock = *WBI;
456f4a2713aSLionel Sambuc BestFreq = CandidateFreq;
457f4a2713aSLionel Sambuc }
458f4a2713aSLionel Sambuc return BestBlock;
459f4a2713aSLionel Sambuc }
460f4a2713aSLionel Sambuc
461f4a2713aSLionel Sambuc /// \brief Retrieve the first unplaced basic block.
462f4a2713aSLionel Sambuc ///
463f4a2713aSLionel Sambuc /// This routine is called when we are unable to use the CFG to walk through
464f4a2713aSLionel Sambuc /// all of the basic blocks and form a chain due to unnatural loops in the CFG.
465f4a2713aSLionel Sambuc /// We walk through the function's blocks in order, starting from the
466f4a2713aSLionel Sambuc /// LastUnplacedBlockIt. We update this iterator on each call to avoid
467f4a2713aSLionel Sambuc /// re-scanning the entire sequence on repeated calls to this routine.
getFirstUnplacedBlock(MachineFunction & F,const BlockChain & PlacedChain,MachineFunction::iterator & PrevUnplacedBlockIt,const BlockFilterSet * BlockFilter)468f4a2713aSLionel Sambuc MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
469f4a2713aSLionel Sambuc MachineFunction &F, const BlockChain &PlacedChain,
470f4a2713aSLionel Sambuc MachineFunction::iterator &PrevUnplacedBlockIt,
471f4a2713aSLionel Sambuc const BlockFilterSet *BlockFilter) {
472f4a2713aSLionel Sambuc for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F.end(); I != E;
473f4a2713aSLionel Sambuc ++I) {
474f4a2713aSLionel Sambuc if (BlockFilter && !BlockFilter->count(I))
475f4a2713aSLionel Sambuc continue;
476f4a2713aSLionel Sambuc if (BlockToChain[I] != &PlacedChain) {
477f4a2713aSLionel Sambuc PrevUnplacedBlockIt = I;
478f4a2713aSLionel Sambuc // Now select the head of the chain to which the unplaced block belongs
479f4a2713aSLionel Sambuc // as the block to place. This will force the entire chain to be placed,
480f4a2713aSLionel Sambuc // and satisfies the requirements of merging chains.
481f4a2713aSLionel Sambuc return *BlockToChain[I]->begin();
482f4a2713aSLionel Sambuc }
483f4a2713aSLionel Sambuc }
484*0a6a1f1dSLionel Sambuc return nullptr;
485f4a2713aSLionel Sambuc }
486f4a2713aSLionel Sambuc
buildChain(MachineBasicBlock * BB,BlockChain & Chain,SmallVectorImpl<MachineBasicBlock * > & BlockWorkList,const BlockFilterSet * BlockFilter)487f4a2713aSLionel Sambuc void MachineBlockPlacement::buildChain(
488f4a2713aSLionel Sambuc MachineBasicBlock *BB,
489f4a2713aSLionel Sambuc BlockChain &Chain,
490f4a2713aSLionel Sambuc SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
491f4a2713aSLionel Sambuc const BlockFilterSet *BlockFilter) {
492f4a2713aSLionel Sambuc assert(BB);
493f4a2713aSLionel Sambuc assert(BlockToChain[BB] == &Chain);
494f4a2713aSLionel Sambuc MachineFunction &F = *BB->getParent();
495f4a2713aSLionel Sambuc MachineFunction::iterator PrevUnplacedBlockIt = F.begin();
496f4a2713aSLionel Sambuc
497f4a2713aSLionel Sambuc MachineBasicBlock *LoopHeaderBB = BB;
498f4a2713aSLionel Sambuc markChainSuccessors(Chain, LoopHeaderBB, BlockWorkList, BlockFilter);
499*0a6a1f1dSLionel Sambuc BB = *std::prev(Chain.end());
500f4a2713aSLionel Sambuc for (;;) {
501f4a2713aSLionel Sambuc assert(BB);
502f4a2713aSLionel Sambuc assert(BlockToChain[BB] == &Chain);
503*0a6a1f1dSLionel Sambuc assert(*std::prev(Chain.end()) == BB);
504f4a2713aSLionel Sambuc
505f4a2713aSLionel Sambuc // Look for the best viable successor if there is one to place immediately
506f4a2713aSLionel Sambuc // after this block.
507f4a2713aSLionel Sambuc MachineBasicBlock *BestSucc = selectBestSuccessor(BB, Chain, BlockFilter);
508f4a2713aSLionel Sambuc
509f4a2713aSLionel Sambuc // If an immediate successor isn't available, look for the best viable
510f4a2713aSLionel Sambuc // block among those we've identified as not violating the loop's CFG at
511f4a2713aSLionel Sambuc // this point. This won't be a fallthrough, but it will increase locality.
512f4a2713aSLionel Sambuc if (!BestSucc)
513f4a2713aSLionel Sambuc BestSucc = selectBestCandidateBlock(Chain, BlockWorkList, BlockFilter);
514f4a2713aSLionel Sambuc
515f4a2713aSLionel Sambuc if (!BestSucc) {
516f4a2713aSLionel Sambuc BestSucc = getFirstUnplacedBlock(F, Chain, PrevUnplacedBlockIt,
517f4a2713aSLionel Sambuc BlockFilter);
518f4a2713aSLionel Sambuc if (!BestSucc)
519f4a2713aSLionel Sambuc break;
520f4a2713aSLionel Sambuc
521f4a2713aSLionel Sambuc DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
522f4a2713aSLionel Sambuc "layout successor until the CFG reduces\n");
523f4a2713aSLionel Sambuc }
524f4a2713aSLionel Sambuc
525f4a2713aSLionel Sambuc // Place this block, updating the datastructures to reflect its placement.
526f4a2713aSLionel Sambuc BlockChain &SuccChain = *BlockToChain[BestSucc];
527f4a2713aSLionel Sambuc // Zero out LoopPredecessors for the successor we're about to merge in case
528f4a2713aSLionel Sambuc // we selected a successor that didn't fit naturally into the CFG.
529f4a2713aSLionel Sambuc SuccChain.LoopPredecessors = 0;
530f4a2713aSLionel Sambuc DEBUG(dbgs() << "Merging from " << getBlockNum(BB)
531f4a2713aSLionel Sambuc << " to " << getBlockNum(BestSucc) << "\n");
532f4a2713aSLionel Sambuc markChainSuccessors(SuccChain, LoopHeaderBB, BlockWorkList, BlockFilter);
533f4a2713aSLionel Sambuc Chain.merge(BestSucc, &SuccChain);
534*0a6a1f1dSLionel Sambuc BB = *std::prev(Chain.end());
535f4a2713aSLionel Sambuc }
536f4a2713aSLionel Sambuc
537f4a2713aSLionel Sambuc DEBUG(dbgs() << "Finished forming chain for header block "
538f4a2713aSLionel Sambuc << getBlockNum(*Chain.begin()) << "\n");
539f4a2713aSLionel Sambuc }
540f4a2713aSLionel Sambuc
541f4a2713aSLionel Sambuc /// \brief Find the best loop top block for layout.
542f4a2713aSLionel Sambuc ///
543f4a2713aSLionel Sambuc /// Look for a block which is strictly better than the loop header for laying
544f4a2713aSLionel Sambuc /// out at the top of the loop. This looks for one and only one pattern:
545f4a2713aSLionel Sambuc /// a latch block with no conditional exit. This block will cause a conditional
546f4a2713aSLionel Sambuc /// jump around it or will be the bottom of the loop if we lay it out in place,
547f4a2713aSLionel Sambuc /// but if it it doesn't end up at the bottom of the loop for any reason,
548f4a2713aSLionel Sambuc /// rotation alone won't fix it. Because such a block will always result in an
549f4a2713aSLionel Sambuc /// unconditional jump (for the backedge) rotating it in front of the loop
550f4a2713aSLionel Sambuc /// header is always profitable.
551f4a2713aSLionel Sambuc MachineBasicBlock *
findBestLoopTop(MachineLoop & L,const BlockFilterSet & LoopBlockSet)552f4a2713aSLionel Sambuc MachineBlockPlacement::findBestLoopTop(MachineLoop &L,
553f4a2713aSLionel Sambuc const BlockFilterSet &LoopBlockSet) {
554f4a2713aSLionel Sambuc // Check that the header hasn't been fused with a preheader block due to
555f4a2713aSLionel Sambuc // crazy branches. If it has, we need to start with the header at the top to
556f4a2713aSLionel Sambuc // prevent pulling the preheader into the loop body.
557f4a2713aSLionel Sambuc BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
558f4a2713aSLionel Sambuc if (!LoopBlockSet.count(*HeaderChain.begin()))
559f4a2713aSLionel Sambuc return L.getHeader();
560f4a2713aSLionel Sambuc
561f4a2713aSLionel Sambuc DEBUG(dbgs() << "Finding best loop top for: "
562f4a2713aSLionel Sambuc << getBlockName(L.getHeader()) << "\n");
563f4a2713aSLionel Sambuc
564f4a2713aSLionel Sambuc BlockFrequency BestPredFreq;
565*0a6a1f1dSLionel Sambuc MachineBasicBlock *BestPred = nullptr;
566f4a2713aSLionel Sambuc for (MachineBasicBlock::pred_iterator PI = L.getHeader()->pred_begin(),
567f4a2713aSLionel Sambuc PE = L.getHeader()->pred_end();
568f4a2713aSLionel Sambuc PI != PE; ++PI) {
569f4a2713aSLionel Sambuc MachineBasicBlock *Pred = *PI;
570f4a2713aSLionel Sambuc if (!LoopBlockSet.count(Pred))
571f4a2713aSLionel Sambuc continue;
572f4a2713aSLionel Sambuc DEBUG(dbgs() << " header pred: " << getBlockName(Pred) << ", "
573*0a6a1f1dSLionel Sambuc << Pred->succ_size() << " successors, ";
574*0a6a1f1dSLionel Sambuc MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
575f4a2713aSLionel Sambuc if (Pred->succ_size() > 1)
576f4a2713aSLionel Sambuc continue;
577f4a2713aSLionel Sambuc
578f4a2713aSLionel Sambuc BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
579f4a2713aSLionel Sambuc if (!BestPred || PredFreq > BestPredFreq ||
580f4a2713aSLionel Sambuc (!(PredFreq < BestPredFreq) &&
581f4a2713aSLionel Sambuc Pred->isLayoutSuccessor(L.getHeader()))) {
582f4a2713aSLionel Sambuc BestPred = Pred;
583f4a2713aSLionel Sambuc BestPredFreq = PredFreq;
584f4a2713aSLionel Sambuc }
585f4a2713aSLionel Sambuc }
586f4a2713aSLionel Sambuc
587f4a2713aSLionel Sambuc // If no direct predecessor is fine, just use the loop header.
588f4a2713aSLionel Sambuc if (!BestPred)
589f4a2713aSLionel Sambuc return L.getHeader();
590f4a2713aSLionel Sambuc
591f4a2713aSLionel Sambuc // Walk backwards through any straight line of predecessors.
592f4a2713aSLionel Sambuc while (BestPred->pred_size() == 1 &&
593f4a2713aSLionel Sambuc (*BestPred->pred_begin())->succ_size() == 1 &&
594f4a2713aSLionel Sambuc *BestPred->pred_begin() != L.getHeader())
595f4a2713aSLionel Sambuc BestPred = *BestPred->pred_begin();
596f4a2713aSLionel Sambuc
597f4a2713aSLionel Sambuc DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n");
598f4a2713aSLionel Sambuc return BestPred;
599f4a2713aSLionel Sambuc }
600f4a2713aSLionel Sambuc
601f4a2713aSLionel Sambuc
602f4a2713aSLionel Sambuc /// \brief Find the best loop exiting block for layout.
603f4a2713aSLionel Sambuc ///
604f4a2713aSLionel Sambuc /// This routine implements the logic to analyze the loop looking for the best
605f4a2713aSLionel Sambuc /// block to layout at the top of the loop. Typically this is done to maximize
606f4a2713aSLionel Sambuc /// fallthrough opportunities.
607f4a2713aSLionel Sambuc MachineBasicBlock *
findBestLoopExit(MachineFunction & F,MachineLoop & L,const BlockFilterSet & LoopBlockSet)608f4a2713aSLionel Sambuc MachineBlockPlacement::findBestLoopExit(MachineFunction &F,
609f4a2713aSLionel Sambuc MachineLoop &L,
610f4a2713aSLionel Sambuc const BlockFilterSet &LoopBlockSet) {
611f4a2713aSLionel Sambuc // We don't want to layout the loop linearly in all cases. If the loop header
612f4a2713aSLionel Sambuc // is just a normal basic block in the loop, we want to look for what block
613f4a2713aSLionel Sambuc // within the loop is the best one to layout at the top. However, if the loop
614f4a2713aSLionel Sambuc // header has be pre-merged into a chain due to predecessors not having
615f4a2713aSLionel Sambuc // analyzable branches, *and* the predecessor it is merged with is *not* part
616f4a2713aSLionel Sambuc // of the loop, rotating the header into the middle of the loop will create
617f4a2713aSLionel Sambuc // a non-contiguous range of blocks which is Very Bad. So start with the
618f4a2713aSLionel Sambuc // header and only rotate if safe.
619f4a2713aSLionel Sambuc BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
620f4a2713aSLionel Sambuc if (!LoopBlockSet.count(*HeaderChain.begin()))
621*0a6a1f1dSLionel Sambuc return nullptr;
622f4a2713aSLionel Sambuc
623f4a2713aSLionel Sambuc BlockFrequency BestExitEdgeFreq;
624f4a2713aSLionel Sambuc unsigned BestExitLoopDepth = 0;
625*0a6a1f1dSLionel Sambuc MachineBasicBlock *ExitingBB = nullptr;
626f4a2713aSLionel Sambuc // If there are exits to outer loops, loop rotation can severely limit
627f4a2713aSLionel Sambuc // fallthrough opportunites unless it selects such an exit. Keep a set of
628f4a2713aSLionel Sambuc // blocks where rotating to exit with that block will reach an outer loop.
629f4a2713aSLionel Sambuc SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
630f4a2713aSLionel Sambuc
631f4a2713aSLionel Sambuc DEBUG(dbgs() << "Finding best loop exit for: "
632f4a2713aSLionel Sambuc << getBlockName(L.getHeader()) << "\n");
633f4a2713aSLionel Sambuc for (MachineLoop::block_iterator I = L.block_begin(),
634f4a2713aSLionel Sambuc E = L.block_end();
635f4a2713aSLionel Sambuc I != E; ++I) {
636f4a2713aSLionel Sambuc BlockChain &Chain = *BlockToChain[*I];
637f4a2713aSLionel Sambuc // Ensure that this block is at the end of a chain; otherwise it could be
638f4a2713aSLionel Sambuc // mid-way through an inner loop or a successor of an analyzable branch.
639*0a6a1f1dSLionel Sambuc if (*I != *std::prev(Chain.end()))
640f4a2713aSLionel Sambuc continue;
641f4a2713aSLionel Sambuc
642f4a2713aSLionel Sambuc // Now walk the successors. We need to establish whether this has a viable
643f4a2713aSLionel Sambuc // exiting successor and whether it has a viable non-exiting successor.
644f4a2713aSLionel Sambuc // We store the old exiting state and restore it if a viable looping
645f4a2713aSLionel Sambuc // successor isn't found.
646f4a2713aSLionel Sambuc MachineBasicBlock *OldExitingBB = ExitingBB;
647f4a2713aSLionel Sambuc BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
648f4a2713aSLionel Sambuc bool HasLoopingSucc = false;
649f4a2713aSLionel Sambuc // FIXME: Due to the performance of the probability and weight routines in
650f4a2713aSLionel Sambuc // the MBPI analysis, we use the internal weights and manually compute the
651f4a2713aSLionel Sambuc // probabilities to avoid quadratic behavior.
652f4a2713aSLionel Sambuc uint32_t WeightScale = 0;
653f4a2713aSLionel Sambuc uint32_t SumWeight = MBPI->getSumForBlock(*I, WeightScale);
654f4a2713aSLionel Sambuc for (MachineBasicBlock::succ_iterator SI = (*I)->succ_begin(),
655f4a2713aSLionel Sambuc SE = (*I)->succ_end();
656f4a2713aSLionel Sambuc SI != SE; ++SI) {
657f4a2713aSLionel Sambuc if ((*SI)->isLandingPad())
658f4a2713aSLionel Sambuc continue;
659f4a2713aSLionel Sambuc if (*SI == *I)
660f4a2713aSLionel Sambuc continue;
661f4a2713aSLionel Sambuc BlockChain &SuccChain = *BlockToChain[*SI];
662f4a2713aSLionel Sambuc // Don't split chains, either this chain or the successor's chain.
663f4a2713aSLionel Sambuc if (&Chain == &SuccChain) {
664f4a2713aSLionel Sambuc DEBUG(dbgs() << " exiting: " << getBlockName(*I) << " -> "
665f4a2713aSLionel Sambuc << getBlockName(*SI) << " (chain conflict)\n");
666f4a2713aSLionel Sambuc continue;
667f4a2713aSLionel Sambuc }
668f4a2713aSLionel Sambuc
669f4a2713aSLionel Sambuc uint32_t SuccWeight = MBPI->getEdgeWeight(*I, *SI);
670f4a2713aSLionel Sambuc if (LoopBlockSet.count(*SI)) {
671f4a2713aSLionel Sambuc DEBUG(dbgs() << " looping: " << getBlockName(*I) << " -> "
672f4a2713aSLionel Sambuc << getBlockName(*SI) << " (" << SuccWeight << ")\n");
673f4a2713aSLionel Sambuc HasLoopingSucc = true;
674f4a2713aSLionel Sambuc continue;
675f4a2713aSLionel Sambuc }
676f4a2713aSLionel Sambuc
677f4a2713aSLionel Sambuc unsigned SuccLoopDepth = 0;
678f4a2713aSLionel Sambuc if (MachineLoop *ExitLoop = MLI->getLoopFor(*SI)) {
679f4a2713aSLionel Sambuc SuccLoopDepth = ExitLoop->getLoopDepth();
680f4a2713aSLionel Sambuc if (ExitLoop->contains(&L))
681f4a2713aSLionel Sambuc BlocksExitingToOuterLoop.insert(*I);
682f4a2713aSLionel Sambuc }
683f4a2713aSLionel Sambuc
684f4a2713aSLionel Sambuc BranchProbability SuccProb(SuccWeight / WeightScale, SumWeight);
685f4a2713aSLionel Sambuc BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(*I) * SuccProb;
686f4a2713aSLionel Sambuc DEBUG(dbgs() << " exiting: " << getBlockName(*I) << " -> "
687f4a2713aSLionel Sambuc << getBlockName(*SI) << " [L:" << SuccLoopDepth
688*0a6a1f1dSLionel Sambuc << "] (";
689*0a6a1f1dSLionel Sambuc MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
690*0a6a1f1dSLionel Sambuc // Note that we bias this toward an existing layout successor to retain
691*0a6a1f1dSLionel Sambuc // incoming order in the absence of better information. The exit must have
692*0a6a1f1dSLionel Sambuc // a frequency higher than the current exit before we consider breaking
693*0a6a1f1dSLionel Sambuc // the layout.
694*0a6a1f1dSLionel Sambuc BranchProbability Bias(100 - ExitBlockBias, 100);
695f4a2713aSLionel Sambuc if (!ExitingBB || BestExitLoopDepth < SuccLoopDepth ||
696f4a2713aSLionel Sambuc ExitEdgeFreq > BestExitEdgeFreq ||
697f4a2713aSLionel Sambuc ((*I)->isLayoutSuccessor(*SI) &&
698*0a6a1f1dSLionel Sambuc !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
699f4a2713aSLionel Sambuc BestExitEdgeFreq = ExitEdgeFreq;
700f4a2713aSLionel Sambuc ExitingBB = *I;
701f4a2713aSLionel Sambuc }
702f4a2713aSLionel Sambuc }
703f4a2713aSLionel Sambuc
704f4a2713aSLionel Sambuc // Restore the old exiting state, no viable looping successor was found.
705f4a2713aSLionel Sambuc if (!HasLoopingSucc) {
706f4a2713aSLionel Sambuc ExitingBB = OldExitingBB;
707f4a2713aSLionel Sambuc BestExitEdgeFreq = OldBestExitEdgeFreq;
708f4a2713aSLionel Sambuc continue;
709f4a2713aSLionel Sambuc }
710f4a2713aSLionel Sambuc }
711f4a2713aSLionel Sambuc // Without a candidate exiting block or with only a single block in the
712f4a2713aSLionel Sambuc // loop, just use the loop header to layout the loop.
713f4a2713aSLionel Sambuc if (!ExitingBB || L.getNumBlocks() == 1)
714*0a6a1f1dSLionel Sambuc return nullptr;
715f4a2713aSLionel Sambuc
716f4a2713aSLionel Sambuc // Also, if we have exit blocks which lead to outer loops but didn't select
717f4a2713aSLionel Sambuc // one of them as the exiting block we are rotating toward, disable loop
718f4a2713aSLionel Sambuc // rotation altogether.
719f4a2713aSLionel Sambuc if (!BlocksExitingToOuterLoop.empty() &&
720f4a2713aSLionel Sambuc !BlocksExitingToOuterLoop.count(ExitingBB))
721*0a6a1f1dSLionel Sambuc return nullptr;
722f4a2713aSLionel Sambuc
723f4a2713aSLionel Sambuc DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB) << "\n");
724f4a2713aSLionel Sambuc return ExitingBB;
725f4a2713aSLionel Sambuc }
726f4a2713aSLionel Sambuc
727f4a2713aSLionel Sambuc /// \brief Attempt to rotate an exiting block to the bottom of the loop.
728f4a2713aSLionel Sambuc ///
729f4a2713aSLionel Sambuc /// Once we have built a chain, try to rotate it to line up the hot exit block
730f4a2713aSLionel Sambuc /// with fallthrough out of the loop if doing so doesn't introduce unnecessary
731f4a2713aSLionel Sambuc /// branches. For example, if the loop has fallthrough into its header and out
732f4a2713aSLionel Sambuc /// of its bottom already, don't rotate it.
rotateLoop(BlockChain & LoopChain,MachineBasicBlock * ExitingBB,const BlockFilterSet & LoopBlockSet)733f4a2713aSLionel Sambuc void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
734f4a2713aSLionel Sambuc MachineBasicBlock *ExitingBB,
735f4a2713aSLionel Sambuc const BlockFilterSet &LoopBlockSet) {
736f4a2713aSLionel Sambuc if (!ExitingBB)
737f4a2713aSLionel Sambuc return;
738f4a2713aSLionel Sambuc
739f4a2713aSLionel Sambuc MachineBasicBlock *Top = *LoopChain.begin();
740f4a2713aSLionel Sambuc bool ViableTopFallthrough = false;
741f4a2713aSLionel Sambuc for (MachineBasicBlock::pred_iterator PI = Top->pred_begin(),
742f4a2713aSLionel Sambuc PE = Top->pred_end();
743f4a2713aSLionel Sambuc PI != PE; ++PI) {
744f4a2713aSLionel Sambuc BlockChain *PredChain = BlockToChain[*PI];
745f4a2713aSLionel Sambuc if (!LoopBlockSet.count(*PI) &&
746*0a6a1f1dSLionel Sambuc (!PredChain || *PI == *std::prev(PredChain->end()))) {
747f4a2713aSLionel Sambuc ViableTopFallthrough = true;
748f4a2713aSLionel Sambuc break;
749f4a2713aSLionel Sambuc }
750f4a2713aSLionel Sambuc }
751f4a2713aSLionel Sambuc
752f4a2713aSLionel Sambuc // If the header has viable fallthrough, check whether the current loop
753f4a2713aSLionel Sambuc // bottom is a viable exiting block. If so, bail out as rotating will
754f4a2713aSLionel Sambuc // introduce an unnecessary branch.
755f4a2713aSLionel Sambuc if (ViableTopFallthrough) {
756*0a6a1f1dSLionel Sambuc MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
757f4a2713aSLionel Sambuc for (MachineBasicBlock::succ_iterator SI = Bottom->succ_begin(),
758f4a2713aSLionel Sambuc SE = Bottom->succ_end();
759f4a2713aSLionel Sambuc SI != SE; ++SI) {
760f4a2713aSLionel Sambuc BlockChain *SuccChain = BlockToChain[*SI];
761f4a2713aSLionel Sambuc if (!LoopBlockSet.count(*SI) &&
762f4a2713aSLionel Sambuc (!SuccChain || *SI == *SuccChain->begin()))
763f4a2713aSLionel Sambuc return;
764f4a2713aSLionel Sambuc }
765f4a2713aSLionel Sambuc }
766f4a2713aSLionel Sambuc
767f4a2713aSLionel Sambuc BlockChain::iterator ExitIt = std::find(LoopChain.begin(), LoopChain.end(),
768f4a2713aSLionel Sambuc ExitingBB);
769f4a2713aSLionel Sambuc if (ExitIt == LoopChain.end())
770f4a2713aSLionel Sambuc return;
771f4a2713aSLionel Sambuc
772*0a6a1f1dSLionel Sambuc std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
773f4a2713aSLionel Sambuc }
774f4a2713aSLionel Sambuc
775f4a2713aSLionel Sambuc /// \brief Forms basic block chains from the natural loop structures.
776f4a2713aSLionel Sambuc ///
777f4a2713aSLionel Sambuc /// These chains are designed to preserve the existing *structure* of the code
778f4a2713aSLionel Sambuc /// as much as possible. We can then stitch the chains together in a way which
779f4a2713aSLionel Sambuc /// both preserves the topological structure and minimizes taken conditional
780f4a2713aSLionel Sambuc /// branches.
buildLoopChains(MachineFunction & F,MachineLoop & L)781f4a2713aSLionel Sambuc void MachineBlockPlacement::buildLoopChains(MachineFunction &F,
782f4a2713aSLionel Sambuc MachineLoop &L) {
783f4a2713aSLionel Sambuc // First recurse through any nested loops, building chains for those inner
784f4a2713aSLionel Sambuc // loops.
785f4a2713aSLionel Sambuc for (MachineLoop::iterator LI = L.begin(), LE = L.end(); LI != LE; ++LI)
786f4a2713aSLionel Sambuc buildLoopChains(F, **LI);
787f4a2713aSLionel Sambuc
788f4a2713aSLionel Sambuc SmallVector<MachineBasicBlock *, 16> BlockWorkList;
789f4a2713aSLionel Sambuc BlockFilterSet LoopBlockSet(L.block_begin(), L.block_end());
790f4a2713aSLionel Sambuc
791f4a2713aSLionel Sambuc // First check to see if there is an obviously preferable top block for the
792f4a2713aSLionel Sambuc // loop. This will default to the header, but may end up as one of the
793f4a2713aSLionel Sambuc // predecessors to the header if there is one which will result in strictly
794f4a2713aSLionel Sambuc // fewer branches in the loop body.
795f4a2713aSLionel Sambuc MachineBasicBlock *LoopTop = findBestLoopTop(L, LoopBlockSet);
796f4a2713aSLionel Sambuc
797f4a2713aSLionel Sambuc // If we selected just the header for the loop top, look for a potentially
798f4a2713aSLionel Sambuc // profitable exit block in the event that rotating the loop can eliminate
799f4a2713aSLionel Sambuc // branches by placing an exit edge at the bottom.
800*0a6a1f1dSLionel Sambuc MachineBasicBlock *ExitingBB = nullptr;
801f4a2713aSLionel Sambuc if (LoopTop == L.getHeader())
802f4a2713aSLionel Sambuc ExitingBB = findBestLoopExit(F, L, LoopBlockSet);
803f4a2713aSLionel Sambuc
804f4a2713aSLionel Sambuc BlockChain &LoopChain = *BlockToChain[LoopTop];
805f4a2713aSLionel Sambuc
806f4a2713aSLionel Sambuc // FIXME: This is a really lame way of walking the chains in the loop: we
807f4a2713aSLionel Sambuc // walk the blocks, and use a set to prevent visiting a particular chain
808f4a2713aSLionel Sambuc // twice.
809f4a2713aSLionel Sambuc SmallPtrSet<BlockChain *, 4> UpdatedPreds;
810f4a2713aSLionel Sambuc assert(LoopChain.LoopPredecessors == 0);
811f4a2713aSLionel Sambuc UpdatedPreds.insert(&LoopChain);
812f4a2713aSLionel Sambuc for (MachineLoop::block_iterator BI = L.block_begin(),
813f4a2713aSLionel Sambuc BE = L.block_end();
814f4a2713aSLionel Sambuc BI != BE; ++BI) {
815f4a2713aSLionel Sambuc BlockChain &Chain = *BlockToChain[*BI];
816*0a6a1f1dSLionel Sambuc if (!UpdatedPreds.insert(&Chain).second)
817f4a2713aSLionel Sambuc continue;
818f4a2713aSLionel Sambuc
819f4a2713aSLionel Sambuc assert(Chain.LoopPredecessors == 0);
820f4a2713aSLionel Sambuc for (BlockChain::iterator BCI = Chain.begin(), BCE = Chain.end();
821f4a2713aSLionel Sambuc BCI != BCE; ++BCI) {
822f4a2713aSLionel Sambuc assert(BlockToChain[*BCI] == &Chain);
823f4a2713aSLionel Sambuc for (MachineBasicBlock::pred_iterator PI = (*BCI)->pred_begin(),
824f4a2713aSLionel Sambuc PE = (*BCI)->pred_end();
825f4a2713aSLionel Sambuc PI != PE; ++PI) {
826f4a2713aSLionel Sambuc if (BlockToChain[*PI] == &Chain || !LoopBlockSet.count(*PI))
827f4a2713aSLionel Sambuc continue;
828f4a2713aSLionel Sambuc ++Chain.LoopPredecessors;
829f4a2713aSLionel Sambuc }
830f4a2713aSLionel Sambuc }
831f4a2713aSLionel Sambuc
832f4a2713aSLionel Sambuc if (Chain.LoopPredecessors == 0)
833f4a2713aSLionel Sambuc BlockWorkList.push_back(*Chain.begin());
834f4a2713aSLionel Sambuc }
835f4a2713aSLionel Sambuc
836f4a2713aSLionel Sambuc buildChain(LoopTop, LoopChain, BlockWorkList, &LoopBlockSet);
837f4a2713aSLionel Sambuc rotateLoop(LoopChain, ExitingBB, LoopBlockSet);
838f4a2713aSLionel Sambuc
839f4a2713aSLionel Sambuc DEBUG({
840f4a2713aSLionel Sambuc // Crash at the end so we get all of the debugging output first.
841f4a2713aSLionel Sambuc bool BadLoop = false;
842f4a2713aSLionel Sambuc if (LoopChain.LoopPredecessors) {
843f4a2713aSLionel Sambuc BadLoop = true;
844f4a2713aSLionel Sambuc dbgs() << "Loop chain contains a block without its preds placed!\n"
845f4a2713aSLionel Sambuc << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
846f4a2713aSLionel Sambuc << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
847f4a2713aSLionel Sambuc }
848f4a2713aSLionel Sambuc for (BlockChain::iterator BCI = LoopChain.begin(), BCE = LoopChain.end();
849f4a2713aSLionel Sambuc BCI != BCE; ++BCI) {
850f4a2713aSLionel Sambuc dbgs() << " ... " << getBlockName(*BCI) << "\n";
851f4a2713aSLionel Sambuc if (!LoopBlockSet.erase(*BCI)) {
852f4a2713aSLionel Sambuc // We don't mark the loop as bad here because there are real situations
853f4a2713aSLionel Sambuc // where this can occur. For example, with an unanalyzable fallthrough
854f4a2713aSLionel Sambuc // from a loop block to a non-loop block or vice versa.
855f4a2713aSLionel Sambuc dbgs() << "Loop chain contains a block not contained by the loop!\n"
856f4a2713aSLionel Sambuc << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
857f4a2713aSLionel Sambuc << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
858f4a2713aSLionel Sambuc << " Bad block: " << getBlockName(*BCI) << "\n";
859f4a2713aSLionel Sambuc }
860f4a2713aSLionel Sambuc }
861f4a2713aSLionel Sambuc
862f4a2713aSLionel Sambuc if (!LoopBlockSet.empty()) {
863f4a2713aSLionel Sambuc BadLoop = true;
864f4a2713aSLionel Sambuc for (BlockFilterSet::iterator LBI = LoopBlockSet.begin(),
865f4a2713aSLionel Sambuc LBE = LoopBlockSet.end();
866f4a2713aSLionel Sambuc LBI != LBE; ++LBI)
867f4a2713aSLionel Sambuc dbgs() << "Loop contains blocks never placed into a chain!\n"
868f4a2713aSLionel Sambuc << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
869f4a2713aSLionel Sambuc << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
870f4a2713aSLionel Sambuc << " Bad block: " << getBlockName(*LBI) << "\n";
871f4a2713aSLionel Sambuc }
872f4a2713aSLionel Sambuc assert(!BadLoop && "Detected problems with the placement of this loop.");
873f4a2713aSLionel Sambuc });
874f4a2713aSLionel Sambuc }
875f4a2713aSLionel Sambuc
buildCFGChains(MachineFunction & F)876f4a2713aSLionel Sambuc void MachineBlockPlacement::buildCFGChains(MachineFunction &F) {
877f4a2713aSLionel Sambuc // Ensure that every BB in the function has an associated chain to simplify
878f4a2713aSLionel Sambuc // the assumptions of the remaining algorithm.
879f4a2713aSLionel Sambuc SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
880f4a2713aSLionel Sambuc for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
881f4a2713aSLionel Sambuc MachineBasicBlock *BB = FI;
882f4a2713aSLionel Sambuc BlockChain *Chain
883f4a2713aSLionel Sambuc = new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
884f4a2713aSLionel Sambuc // Also, merge any blocks which we cannot reason about and must preserve
885f4a2713aSLionel Sambuc // the exact fallthrough behavior for.
886f4a2713aSLionel Sambuc for (;;) {
887f4a2713aSLionel Sambuc Cond.clear();
888*0a6a1f1dSLionel Sambuc MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
889f4a2713aSLionel Sambuc if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
890f4a2713aSLionel Sambuc break;
891f4a2713aSLionel Sambuc
892*0a6a1f1dSLionel Sambuc MachineFunction::iterator NextFI(std::next(FI));
893f4a2713aSLionel Sambuc MachineBasicBlock *NextBB = NextFI;
894f4a2713aSLionel Sambuc // Ensure that the layout successor is a viable block, as we know that
895f4a2713aSLionel Sambuc // fallthrough is a possibility.
896f4a2713aSLionel Sambuc assert(NextFI != FE && "Can't fallthrough past the last block.");
897f4a2713aSLionel Sambuc DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
898f4a2713aSLionel Sambuc << getBlockName(BB) << " -> " << getBlockName(NextBB)
899f4a2713aSLionel Sambuc << "\n");
900*0a6a1f1dSLionel Sambuc Chain->merge(NextBB, nullptr);
901f4a2713aSLionel Sambuc FI = NextFI;
902f4a2713aSLionel Sambuc BB = NextBB;
903f4a2713aSLionel Sambuc }
904f4a2713aSLionel Sambuc }
905f4a2713aSLionel Sambuc
906f4a2713aSLionel Sambuc // Build any loop-based chains.
907f4a2713aSLionel Sambuc for (MachineLoopInfo::iterator LI = MLI->begin(), LE = MLI->end(); LI != LE;
908f4a2713aSLionel Sambuc ++LI)
909f4a2713aSLionel Sambuc buildLoopChains(F, **LI);
910f4a2713aSLionel Sambuc
911f4a2713aSLionel Sambuc SmallVector<MachineBasicBlock *, 16> BlockWorkList;
912f4a2713aSLionel Sambuc
913f4a2713aSLionel Sambuc SmallPtrSet<BlockChain *, 4> UpdatedPreds;
914f4a2713aSLionel Sambuc for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
915f4a2713aSLionel Sambuc MachineBasicBlock *BB = &*FI;
916f4a2713aSLionel Sambuc BlockChain &Chain = *BlockToChain[BB];
917*0a6a1f1dSLionel Sambuc if (!UpdatedPreds.insert(&Chain).second)
918f4a2713aSLionel Sambuc continue;
919f4a2713aSLionel Sambuc
920f4a2713aSLionel Sambuc assert(Chain.LoopPredecessors == 0);
921f4a2713aSLionel Sambuc for (BlockChain::iterator BCI = Chain.begin(), BCE = Chain.end();
922f4a2713aSLionel Sambuc BCI != BCE; ++BCI) {
923f4a2713aSLionel Sambuc assert(BlockToChain[*BCI] == &Chain);
924f4a2713aSLionel Sambuc for (MachineBasicBlock::pred_iterator PI = (*BCI)->pred_begin(),
925f4a2713aSLionel Sambuc PE = (*BCI)->pred_end();
926f4a2713aSLionel Sambuc PI != PE; ++PI) {
927f4a2713aSLionel Sambuc if (BlockToChain[*PI] == &Chain)
928f4a2713aSLionel Sambuc continue;
929f4a2713aSLionel Sambuc ++Chain.LoopPredecessors;
930f4a2713aSLionel Sambuc }
931f4a2713aSLionel Sambuc }
932f4a2713aSLionel Sambuc
933f4a2713aSLionel Sambuc if (Chain.LoopPredecessors == 0)
934f4a2713aSLionel Sambuc BlockWorkList.push_back(*Chain.begin());
935f4a2713aSLionel Sambuc }
936f4a2713aSLionel Sambuc
937f4a2713aSLionel Sambuc BlockChain &FunctionChain = *BlockToChain[&F.front()];
938f4a2713aSLionel Sambuc buildChain(&F.front(), FunctionChain, BlockWorkList);
939f4a2713aSLionel Sambuc
940*0a6a1f1dSLionel Sambuc #ifndef NDEBUG
941f4a2713aSLionel Sambuc typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType;
942*0a6a1f1dSLionel Sambuc #endif
943f4a2713aSLionel Sambuc DEBUG({
944f4a2713aSLionel Sambuc // Crash at the end so we get all of the debugging output first.
945f4a2713aSLionel Sambuc bool BadFunc = false;
946f4a2713aSLionel Sambuc FunctionBlockSetType FunctionBlockSet;
947f4a2713aSLionel Sambuc for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
948f4a2713aSLionel Sambuc FunctionBlockSet.insert(FI);
949f4a2713aSLionel Sambuc
950f4a2713aSLionel Sambuc for (BlockChain::iterator BCI = FunctionChain.begin(),
951f4a2713aSLionel Sambuc BCE = FunctionChain.end();
952f4a2713aSLionel Sambuc BCI != BCE; ++BCI)
953f4a2713aSLionel Sambuc if (!FunctionBlockSet.erase(*BCI)) {
954f4a2713aSLionel Sambuc BadFunc = true;
955f4a2713aSLionel Sambuc dbgs() << "Function chain contains a block not in the function!\n"
956f4a2713aSLionel Sambuc << " Bad block: " << getBlockName(*BCI) << "\n";
957f4a2713aSLionel Sambuc }
958f4a2713aSLionel Sambuc
959f4a2713aSLionel Sambuc if (!FunctionBlockSet.empty()) {
960f4a2713aSLionel Sambuc BadFunc = true;
961f4a2713aSLionel Sambuc for (FunctionBlockSetType::iterator FBI = FunctionBlockSet.begin(),
962f4a2713aSLionel Sambuc FBE = FunctionBlockSet.end();
963f4a2713aSLionel Sambuc FBI != FBE; ++FBI)
964f4a2713aSLionel Sambuc dbgs() << "Function contains blocks never placed into a chain!\n"
965f4a2713aSLionel Sambuc << " Bad block: " << getBlockName(*FBI) << "\n";
966f4a2713aSLionel Sambuc }
967f4a2713aSLionel Sambuc assert(!BadFunc && "Detected problems with the block placement.");
968f4a2713aSLionel Sambuc });
969f4a2713aSLionel Sambuc
970f4a2713aSLionel Sambuc // Splice the blocks into place.
971f4a2713aSLionel Sambuc MachineFunction::iterator InsertPos = F.begin();
972f4a2713aSLionel Sambuc for (BlockChain::iterator BI = FunctionChain.begin(),
973f4a2713aSLionel Sambuc BE = FunctionChain.end();
974f4a2713aSLionel Sambuc BI != BE; ++BI) {
975f4a2713aSLionel Sambuc DEBUG(dbgs() << (BI == FunctionChain.begin() ? "Placing chain "
976f4a2713aSLionel Sambuc : " ... ")
977f4a2713aSLionel Sambuc << getBlockName(*BI) << "\n");
978f4a2713aSLionel Sambuc if (InsertPos != MachineFunction::iterator(*BI))
979f4a2713aSLionel Sambuc F.splice(InsertPos, *BI);
980f4a2713aSLionel Sambuc else
981f4a2713aSLionel Sambuc ++InsertPos;
982f4a2713aSLionel Sambuc
983f4a2713aSLionel Sambuc // Update the terminator of the previous block.
984f4a2713aSLionel Sambuc if (BI == FunctionChain.begin())
985f4a2713aSLionel Sambuc continue;
986*0a6a1f1dSLionel Sambuc MachineBasicBlock *PrevBB = std::prev(MachineFunction::iterator(*BI));
987f4a2713aSLionel Sambuc
988f4a2713aSLionel Sambuc // FIXME: It would be awesome of updateTerminator would just return rather
989f4a2713aSLionel Sambuc // than assert when the branch cannot be analyzed in order to remove this
990f4a2713aSLionel Sambuc // boiler plate.
991f4a2713aSLionel Sambuc Cond.clear();
992*0a6a1f1dSLionel Sambuc MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
993f4a2713aSLionel Sambuc if (!TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
994f4a2713aSLionel Sambuc // The "PrevBB" is not yet updated to reflect current code layout, so,
995f4a2713aSLionel Sambuc // o. it may fall-through to a block without explict "goto" instruction
996f4a2713aSLionel Sambuc // before layout, and no longer fall-through it after layout; or
997f4a2713aSLionel Sambuc // o. just opposite.
998f4a2713aSLionel Sambuc //
999f4a2713aSLionel Sambuc // AnalyzeBranch() may return erroneous value for FBB when these two
1000f4a2713aSLionel Sambuc // situations take place. For the first scenario FBB is mistakenly set
1001f4a2713aSLionel Sambuc // NULL; for the 2nd scenario, the FBB, which is expected to be NULL,
1002f4a2713aSLionel Sambuc // is mistakenly pointing to "*BI".
1003f4a2713aSLionel Sambuc //
1004f4a2713aSLionel Sambuc bool needUpdateBr = true;
1005f4a2713aSLionel Sambuc if (!Cond.empty() && (!FBB || FBB == *BI)) {
1006f4a2713aSLionel Sambuc PrevBB->updateTerminator();
1007f4a2713aSLionel Sambuc needUpdateBr = false;
1008f4a2713aSLionel Sambuc Cond.clear();
1009*0a6a1f1dSLionel Sambuc TBB = FBB = nullptr;
1010f4a2713aSLionel Sambuc if (TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
1011f4a2713aSLionel Sambuc // FIXME: This should never take place.
1012*0a6a1f1dSLionel Sambuc TBB = FBB = nullptr;
1013f4a2713aSLionel Sambuc }
1014f4a2713aSLionel Sambuc }
1015f4a2713aSLionel Sambuc
1016f4a2713aSLionel Sambuc // If PrevBB has a two-way branch, try to re-order the branches
1017f4a2713aSLionel Sambuc // such that we branch to the successor with higher weight first.
1018f4a2713aSLionel Sambuc if (TBB && !Cond.empty() && FBB &&
1019f4a2713aSLionel Sambuc MBPI->getEdgeWeight(PrevBB, FBB) > MBPI->getEdgeWeight(PrevBB, TBB) &&
1020f4a2713aSLionel Sambuc !TII->ReverseBranchCondition(Cond)) {
1021f4a2713aSLionel Sambuc DEBUG(dbgs() << "Reverse order of the two branches: "
1022f4a2713aSLionel Sambuc << getBlockName(PrevBB) << "\n");
1023f4a2713aSLionel Sambuc DEBUG(dbgs() << " Edge weight: " << MBPI->getEdgeWeight(PrevBB, FBB)
1024f4a2713aSLionel Sambuc << " vs " << MBPI->getEdgeWeight(PrevBB, TBB) << "\n");
1025f4a2713aSLionel Sambuc DebugLoc dl; // FIXME: this is nowhere
1026f4a2713aSLionel Sambuc TII->RemoveBranch(*PrevBB);
1027f4a2713aSLionel Sambuc TII->InsertBranch(*PrevBB, FBB, TBB, Cond, dl);
1028f4a2713aSLionel Sambuc needUpdateBr = true;
1029f4a2713aSLionel Sambuc }
1030f4a2713aSLionel Sambuc if (needUpdateBr)
1031f4a2713aSLionel Sambuc PrevBB->updateTerminator();
1032f4a2713aSLionel Sambuc }
1033f4a2713aSLionel Sambuc }
1034f4a2713aSLionel Sambuc
1035f4a2713aSLionel Sambuc // Fixup the last block.
1036f4a2713aSLionel Sambuc Cond.clear();
1037*0a6a1f1dSLionel Sambuc MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1038f4a2713aSLionel Sambuc if (!TII->AnalyzeBranch(F.back(), TBB, FBB, Cond))
1039f4a2713aSLionel Sambuc F.back().updateTerminator();
1040f4a2713aSLionel Sambuc
1041f4a2713aSLionel Sambuc // Walk through the backedges of the function now that we have fully laid out
1042f4a2713aSLionel Sambuc // the basic blocks and align the destination of each backedge. We don't rely
1043f4a2713aSLionel Sambuc // exclusively on the loop info here so that we can align backedges in
1044f4a2713aSLionel Sambuc // unnatural CFGs and backedges that were introduced purely because of the
1045f4a2713aSLionel Sambuc // loop rotations done during this layout pass.
1046f4a2713aSLionel Sambuc if (F.getFunction()->getAttributes().
1047f4a2713aSLionel Sambuc hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize))
1048f4a2713aSLionel Sambuc return;
1049f4a2713aSLionel Sambuc if (FunctionChain.begin() == FunctionChain.end())
1050f4a2713aSLionel Sambuc return; // Empty chain.
1051f4a2713aSLionel Sambuc
1052f4a2713aSLionel Sambuc const BranchProbability ColdProb(1, 5); // 20%
1053f4a2713aSLionel Sambuc BlockFrequency EntryFreq = MBFI->getBlockFreq(F.begin());
1054f4a2713aSLionel Sambuc BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
1055*0a6a1f1dSLionel Sambuc for (BlockChain::iterator BI = std::next(FunctionChain.begin()),
1056f4a2713aSLionel Sambuc BE = FunctionChain.end();
1057f4a2713aSLionel Sambuc BI != BE; ++BI) {
1058f4a2713aSLionel Sambuc // Don't align non-looping basic blocks. These are unlikely to execute
1059f4a2713aSLionel Sambuc // enough times to matter in practice. Note that we'll still handle
1060f4a2713aSLionel Sambuc // unnatural CFGs inside of a natural outer loop (the common case) and
1061f4a2713aSLionel Sambuc // rotated loops.
1062f4a2713aSLionel Sambuc MachineLoop *L = MLI->getLoopFor(*BI);
1063f4a2713aSLionel Sambuc if (!L)
1064f4a2713aSLionel Sambuc continue;
1065f4a2713aSLionel Sambuc
1066*0a6a1f1dSLionel Sambuc unsigned Align = TLI->getPrefLoopAlignment(L);
1067*0a6a1f1dSLionel Sambuc if (!Align)
1068*0a6a1f1dSLionel Sambuc continue; // Don't care about loop alignment.
1069*0a6a1f1dSLionel Sambuc
1070f4a2713aSLionel Sambuc // If the block is cold relative to the function entry don't waste space
1071f4a2713aSLionel Sambuc // aligning it.
1072f4a2713aSLionel Sambuc BlockFrequency Freq = MBFI->getBlockFreq(*BI);
1073f4a2713aSLionel Sambuc if (Freq < WeightedEntryFreq)
1074f4a2713aSLionel Sambuc continue;
1075f4a2713aSLionel Sambuc
1076f4a2713aSLionel Sambuc // If the block is cold relative to its loop header, don't align it
1077f4a2713aSLionel Sambuc // regardless of what edges into the block exist.
1078f4a2713aSLionel Sambuc MachineBasicBlock *LoopHeader = L->getHeader();
1079f4a2713aSLionel Sambuc BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
1080f4a2713aSLionel Sambuc if (Freq < (LoopHeaderFreq * ColdProb))
1081f4a2713aSLionel Sambuc continue;
1082f4a2713aSLionel Sambuc
1083f4a2713aSLionel Sambuc // Check for the existence of a non-layout predecessor which would benefit
1084f4a2713aSLionel Sambuc // from aligning this block.
1085*0a6a1f1dSLionel Sambuc MachineBasicBlock *LayoutPred = *std::prev(BI);
1086f4a2713aSLionel Sambuc
1087f4a2713aSLionel Sambuc // Force alignment if all the predecessors are jumps. We already checked
1088f4a2713aSLionel Sambuc // that the block isn't cold above.
1089f4a2713aSLionel Sambuc if (!LayoutPred->isSuccessor(*BI)) {
1090f4a2713aSLionel Sambuc (*BI)->setAlignment(Align);
1091f4a2713aSLionel Sambuc continue;
1092f4a2713aSLionel Sambuc }
1093f4a2713aSLionel Sambuc
1094f4a2713aSLionel Sambuc // Align this block if the layout predecessor's edge into this block is
1095f4a2713aSLionel Sambuc // cold relative to the block. When this is true, other predecessors make up
1096f4a2713aSLionel Sambuc // all of the hot entries into the block and thus alignment is likely to be
1097f4a2713aSLionel Sambuc // important.
1098f4a2713aSLionel Sambuc BranchProbability LayoutProb = MBPI->getEdgeProbability(LayoutPred, *BI);
1099f4a2713aSLionel Sambuc BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
1100f4a2713aSLionel Sambuc if (LayoutEdgeFreq <= (Freq * ColdProb))
1101f4a2713aSLionel Sambuc (*BI)->setAlignment(Align);
1102f4a2713aSLionel Sambuc }
1103f4a2713aSLionel Sambuc }
1104f4a2713aSLionel Sambuc
runOnMachineFunction(MachineFunction & F)1105f4a2713aSLionel Sambuc bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &F) {
1106f4a2713aSLionel Sambuc // Check for single-block functions and skip them.
1107*0a6a1f1dSLionel Sambuc if (std::next(F.begin()) == F.end())
1108*0a6a1f1dSLionel Sambuc return false;
1109*0a6a1f1dSLionel Sambuc
1110*0a6a1f1dSLionel Sambuc if (skipOptnoneFunction(*F.getFunction()))
1111f4a2713aSLionel Sambuc return false;
1112f4a2713aSLionel Sambuc
1113f4a2713aSLionel Sambuc MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1114f4a2713aSLionel Sambuc MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1115f4a2713aSLionel Sambuc MLI = &getAnalysis<MachineLoopInfo>();
1116*0a6a1f1dSLionel Sambuc TII = F.getSubtarget().getInstrInfo();
1117*0a6a1f1dSLionel Sambuc TLI = F.getSubtarget().getTargetLowering();
1118f4a2713aSLionel Sambuc assert(BlockToChain.empty());
1119f4a2713aSLionel Sambuc
1120f4a2713aSLionel Sambuc buildCFGChains(F);
1121f4a2713aSLionel Sambuc
1122f4a2713aSLionel Sambuc BlockToChain.clear();
1123f4a2713aSLionel Sambuc ChainAllocator.DestroyAll();
1124f4a2713aSLionel Sambuc
1125f4a2713aSLionel Sambuc if (AlignAllBlock)
1126f4a2713aSLionel Sambuc // Align all of the blocks in the function to a specific alignment.
1127f4a2713aSLionel Sambuc for (MachineFunction::iterator FI = F.begin(), FE = F.end();
1128f4a2713aSLionel Sambuc FI != FE; ++FI)
1129f4a2713aSLionel Sambuc FI->setAlignment(AlignAllBlock);
1130f4a2713aSLionel Sambuc
1131f4a2713aSLionel Sambuc // We always return true as we have no way to track whether the final order
1132f4a2713aSLionel Sambuc // differs from the original order.
1133f4a2713aSLionel Sambuc return true;
1134f4a2713aSLionel Sambuc }
1135f4a2713aSLionel Sambuc
1136f4a2713aSLionel Sambuc namespace {
1137f4a2713aSLionel Sambuc /// \brief A pass to compute block placement statistics.
1138f4a2713aSLionel Sambuc ///
1139f4a2713aSLionel Sambuc /// A separate pass to compute interesting statistics for evaluating block
1140f4a2713aSLionel Sambuc /// placement. This is separate from the actual placement pass so that they can
1141f4a2713aSLionel Sambuc /// be computed in the absence of any placement transformations or when using
1142f4a2713aSLionel Sambuc /// alternative placement strategies.
1143f4a2713aSLionel Sambuc class MachineBlockPlacementStats : public MachineFunctionPass {
1144f4a2713aSLionel Sambuc /// \brief A handle to the branch probability pass.
1145f4a2713aSLionel Sambuc const MachineBranchProbabilityInfo *MBPI;
1146f4a2713aSLionel Sambuc
1147f4a2713aSLionel Sambuc /// \brief A handle to the function-wide block frequency pass.
1148f4a2713aSLionel Sambuc const MachineBlockFrequencyInfo *MBFI;
1149f4a2713aSLionel Sambuc
1150f4a2713aSLionel Sambuc public:
1151f4a2713aSLionel Sambuc static char ID; // Pass identification, replacement for typeid
MachineBlockPlacementStats()1152f4a2713aSLionel Sambuc MachineBlockPlacementStats() : MachineFunctionPass(ID) {
1153f4a2713aSLionel Sambuc initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
1154f4a2713aSLionel Sambuc }
1155f4a2713aSLionel Sambuc
1156*0a6a1f1dSLionel Sambuc bool runOnMachineFunction(MachineFunction &F) override;
1157f4a2713aSLionel Sambuc
getAnalysisUsage(AnalysisUsage & AU) const1158*0a6a1f1dSLionel Sambuc void getAnalysisUsage(AnalysisUsage &AU) const override {
1159f4a2713aSLionel Sambuc AU.addRequired<MachineBranchProbabilityInfo>();
1160f4a2713aSLionel Sambuc AU.addRequired<MachineBlockFrequencyInfo>();
1161f4a2713aSLionel Sambuc AU.setPreservesAll();
1162f4a2713aSLionel Sambuc MachineFunctionPass::getAnalysisUsage(AU);
1163f4a2713aSLionel Sambuc }
1164f4a2713aSLionel Sambuc };
1165f4a2713aSLionel Sambuc }
1166f4a2713aSLionel Sambuc
1167f4a2713aSLionel Sambuc char MachineBlockPlacementStats::ID = 0;
1168f4a2713aSLionel Sambuc char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
1169f4a2713aSLionel Sambuc INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
1170f4a2713aSLionel Sambuc "Basic Block Placement Stats", false, false)
INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)1171f4a2713aSLionel Sambuc INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
1172f4a2713aSLionel Sambuc INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
1173f4a2713aSLionel Sambuc INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
1174f4a2713aSLionel Sambuc "Basic Block Placement Stats", false, false)
1175f4a2713aSLionel Sambuc
1176f4a2713aSLionel Sambuc bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
1177f4a2713aSLionel Sambuc // Check for single-block functions and skip them.
1178*0a6a1f1dSLionel Sambuc if (std::next(F.begin()) == F.end())
1179f4a2713aSLionel Sambuc return false;
1180f4a2713aSLionel Sambuc
1181f4a2713aSLionel Sambuc MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1182f4a2713aSLionel Sambuc MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1183f4a2713aSLionel Sambuc
1184f4a2713aSLionel Sambuc for (MachineFunction::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1185f4a2713aSLionel Sambuc BlockFrequency BlockFreq = MBFI->getBlockFreq(I);
1186f4a2713aSLionel Sambuc Statistic &NumBranches = (I->succ_size() > 1) ? NumCondBranches
1187f4a2713aSLionel Sambuc : NumUncondBranches;
1188f4a2713aSLionel Sambuc Statistic &BranchTakenFreq = (I->succ_size() > 1) ? CondBranchTakenFreq
1189f4a2713aSLionel Sambuc : UncondBranchTakenFreq;
1190f4a2713aSLionel Sambuc for (MachineBasicBlock::succ_iterator SI = I->succ_begin(),
1191f4a2713aSLionel Sambuc SE = I->succ_end();
1192f4a2713aSLionel Sambuc SI != SE; ++SI) {
1193f4a2713aSLionel Sambuc // Skip if this successor is a fallthrough.
1194f4a2713aSLionel Sambuc if (I->isLayoutSuccessor(*SI))
1195f4a2713aSLionel Sambuc continue;
1196f4a2713aSLionel Sambuc
1197f4a2713aSLionel Sambuc BlockFrequency EdgeFreq = BlockFreq * MBPI->getEdgeProbability(I, *SI);
1198f4a2713aSLionel Sambuc ++NumBranches;
1199f4a2713aSLionel Sambuc BranchTakenFreq += EdgeFreq.getFrequency();
1200f4a2713aSLionel Sambuc }
1201f4a2713aSLionel Sambuc }
1202f4a2713aSLionel Sambuc
1203f4a2713aSLionel Sambuc return false;
1204f4a2713aSLionel Sambuc }
1205f4a2713aSLionel Sambuc
1206