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