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