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 
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
667ae0e2c9SDimitry Andric /// probabilities and code locality. We also can use a block chain to represent
677ae0e2c9SDimitry Andric /// a sequence of basic blocks which have some external (correctness)
687ae0e2c9SDimitry Andric /// requirement for sequential layout.
69dff0c46cSDimitry Andric ///
707ae0e2c9SDimitry Andric /// Chains can be built around a single basic block and can be merged to grow
717ae0e2c9SDimitry Andric /// them. They participate in a block-to-chain mapping, which is updated
727ae0e2c9SDimitry Andric /// automatically as chains are merged together.
73dff0c46cSDimitry Andric class BlockChain {
74dff0c46cSDimitry Andric   /// \brief The sequence of blocks belonging to this chain.
75dff0c46cSDimitry Andric   ///
76dff0c46cSDimitry Andric   /// This is the sequence of blocks for a particular chain. These will be laid
77dff0c46cSDimitry Andric   /// out in-order within the function.
78dff0c46cSDimitry Andric   SmallVector<MachineBasicBlock *, 4> Blocks;
79dff0c46cSDimitry Andric 
80dff0c46cSDimitry Andric   /// \brief A handle to the function-wide basic block to block chain mapping.
81dff0c46cSDimitry Andric   ///
82dff0c46cSDimitry Andric   /// This is retained in each block chain to simplify the computation of child
83dff0c46cSDimitry Andric   /// block chains for SCC-formation and iteration. We store the edges to child
84dff0c46cSDimitry Andric   /// basic blocks, and map them back to their associated chains using this
85dff0c46cSDimitry Andric   /// structure.
86dff0c46cSDimitry Andric   BlockToChainMapType &BlockToChain;
87dff0c46cSDimitry Andric 
88dff0c46cSDimitry Andric public:
89dff0c46cSDimitry Andric   /// \brief Construct a new BlockChain.
90dff0c46cSDimitry Andric   ///
91dff0c46cSDimitry Andric   /// This builds a new block chain representing a single basic block in the
92dff0c46cSDimitry Andric   /// function. It also registers itself as the chain that block participates
93dff0c46cSDimitry Andric   /// in with the BlockToChain mapping.
94dff0c46cSDimitry Andric   BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
95dff0c46cSDimitry Andric     : Blocks(1, BB), BlockToChain(BlockToChain), LoopPredecessors(0) {
96dff0c46cSDimitry Andric     assert(BB && "Cannot create a chain with a null basic block");
97dff0c46cSDimitry Andric     BlockToChain[BB] = this;
98dff0c46cSDimitry Andric   }
99dff0c46cSDimitry Andric 
100dff0c46cSDimitry Andric   /// \brief Iterator over blocks within the chain.
101cb4dff85SDimitry Andric   typedef SmallVectorImpl<MachineBasicBlock *>::iterator iterator;
102dff0c46cSDimitry Andric 
103dff0c46cSDimitry Andric   /// \brief Beginning of blocks within the chain.
104cb4dff85SDimitry Andric   iterator begin() { return Blocks.begin(); }
105dff0c46cSDimitry Andric 
106dff0c46cSDimitry Andric   /// \brief End of blocks within the chain.
107cb4dff85SDimitry Andric   iterator end() { return Blocks.end(); }
108dff0c46cSDimitry Andric 
109dff0c46cSDimitry Andric   /// \brief Merge a block chain into this one.
110dff0c46cSDimitry Andric   ///
111dff0c46cSDimitry Andric   /// This routine merges a block chain into this one. It takes care of forming
112dff0c46cSDimitry Andric   /// a contiguous sequence of basic blocks, updating the edge list, and
113dff0c46cSDimitry Andric   /// updating the block -> chain mapping. It does not free or tear down the
114dff0c46cSDimitry Andric   /// old chain, but the old chain's block list is no longer valid.
115dff0c46cSDimitry Andric   void merge(MachineBasicBlock *BB, BlockChain *Chain) {
116dff0c46cSDimitry Andric     assert(BB);
117dff0c46cSDimitry Andric     assert(!Blocks.empty());
118dff0c46cSDimitry Andric 
119dff0c46cSDimitry Andric     // Fast path in case we don't have a chain already.
120dff0c46cSDimitry Andric     if (!Chain) {
121dff0c46cSDimitry Andric       assert(!BlockToChain[BB]);
122dff0c46cSDimitry Andric       Blocks.push_back(BB);
123dff0c46cSDimitry Andric       BlockToChain[BB] = this;
124dff0c46cSDimitry Andric       return;
125dff0c46cSDimitry Andric     }
126dff0c46cSDimitry Andric 
127dff0c46cSDimitry Andric     assert(BB == *Chain->begin());
128dff0c46cSDimitry Andric     assert(Chain->begin() != Chain->end());
129dff0c46cSDimitry Andric 
130dff0c46cSDimitry Andric     // Update the incoming blocks to point to this chain, and add them to the
131dff0c46cSDimitry Andric     // chain structure.
132dff0c46cSDimitry Andric     for (BlockChain::iterator BI = Chain->begin(), BE = Chain->end();
133dff0c46cSDimitry Andric          BI != BE; ++BI) {
134dff0c46cSDimitry Andric       Blocks.push_back(*BI);
135dff0c46cSDimitry Andric       assert(BlockToChain[*BI] == Chain && "Incoming blocks not in chain");
136dff0c46cSDimitry Andric       BlockToChain[*BI] = this;
137dff0c46cSDimitry Andric     }
138dff0c46cSDimitry Andric   }
139dff0c46cSDimitry Andric 
140dff0c46cSDimitry Andric #ifndef NDEBUG
141dff0c46cSDimitry Andric   /// \brief Dump the blocks in this chain.
142dff0c46cSDimitry Andric   void dump() LLVM_ATTRIBUTE_USED {
143dff0c46cSDimitry Andric     for (iterator I = begin(), E = end(); I != E; ++I)
144dff0c46cSDimitry Andric       (*I)->dump();
145dff0c46cSDimitry Andric   }
146dff0c46cSDimitry Andric #endif // NDEBUG
147dff0c46cSDimitry Andric 
148dff0c46cSDimitry Andric   /// \brief Count of predecessors within the loop currently being processed.
149dff0c46cSDimitry Andric   ///
150dff0c46cSDimitry Andric   /// This count is updated at each loop we process to represent the number of
151dff0c46cSDimitry Andric   /// in-loop predecessors of this chain.
152dff0c46cSDimitry Andric   unsigned LoopPredecessors;
153dff0c46cSDimitry Andric };
154dff0c46cSDimitry Andric }
155dff0c46cSDimitry Andric 
156dff0c46cSDimitry Andric namespace {
157dff0c46cSDimitry Andric class MachineBlockPlacement : public MachineFunctionPass {
158dff0c46cSDimitry Andric   /// \brief A typedef for a block filter set.
159dff0c46cSDimitry Andric   typedef SmallPtrSet<MachineBasicBlock *, 16> BlockFilterSet;
160dff0c46cSDimitry Andric 
161dff0c46cSDimitry Andric   /// \brief A handle to the branch probability pass.
162dff0c46cSDimitry Andric   const MachineBranchProbabilityInfo *MBPI;
163dff0c46cSDimitry Andric 
164dff0c46cSDimitry Andric   /// \brief A handle to the function-wide block frequency pass.
165dff0c46cSDimitry Andric   const MachineBlockFrequencyInfo *MBFI;
166dff0c46cSDimitry Andric 
167dff0c46cSDimitry Andric   /// \brief A handle to the loop info.
168dff0c46cSDimitry Andric   const MachineLoopInfo *MLI;
169dff0c46cSDimitry Andric 
170dff0c46cSDimitry Andric   /// \brief A handle to the target's instruction info.
171dff0c46cSDimitry Andric   const TargetInstrInfo *TII;
172dff0c46cSDimitry Andric 
173dff0c46cSDimitry Andric   /// \brief A handle to the target's lowering info.
174dff0c46cSDimitry Andric   const TargetLowering *TLI;
175dff0c46cSDimitry Andric 
176dff0c46cSDimitry Andric   /// \brief Allocator and owner of BlockChain structures.
177dff0c46cSDimitry Andric   ///
1787ae0e2c9SDimitry Andric   /// We build BlockChains lazily while processing the loop structure of
1797ae0e2c9SDimitry Andric   /// a function. To reduce malloc traffic, we allocate them using this
1807ae0e2c9SDimitry Andric   /// slab-like allocator, and destroy them after the pass completes. An
1817ae0e2c9SDimitry Andric   /// important guarantee is that this allocator produces stable pointers to
1827ae0e2c9SDimitry Andric   /// the chains.
183dff0c46cSDimitry Andric   SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
184dff0c46cSDimitry Andric 
185dff0c46cSDimitry Andric   /// \brief Function wide BasicBlock to BlockChain mapping.
186dff0c46cSDimitry Andric   ///
187dff0c46cSDimitry Andric   /// This mapping allows efficiently moving from any given basic block to the
188dff0c46cSDimitry Andric   /// BlockChain it participates in, if any. We use it to, among other things,
189dff0c46cSDimitry Andric   /// allow implicitly defining edges between chains as the existing edges
190dff0c46cSDimitry Andric   /// between basic blocks.
191dff0c46cSDimitry Andric   DenseMap<MachineBasicBlock *, BlockChain *> BlockToChain;
192dff0c46cSDimitry Andric 
193dff0c46cSDimitry Andric   void markChainSuccessors(BlockChain &Chain,
194dff0c46cSDimitry Andric                            MachineBasicBlock *LoopHeaderBB,
195dff0c46cSDimitry Andric                            SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
196dff0c46cSDimitry Andric                            const BlockFilterSet *BlockFilter = 0);
197dff0c46cSDimitry Andric   MachineBasicBlock *selectBestSuccessor(MachineBasicBlock *BB,
198dff0c46cSDimitry Andric                                          BlockChain &Chain,
199dff0c46cSDimitry Andric                                          const BlockFilterSet *BlockFilter);
200dff0c46cSDimitry Andric   MachineBasicBlock *selectBestCandidateBlock(
201dff0c46cSDimitry Andric       BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList,
202dff0c46cSDimitry Andric       const BlockFilterSet *BlockFilter);
203dff0c46cSDimitry Andric   MachineBasicBlock *getFirstUnplacedBlock(
204dff0c46cSDimitry Andric       MachineFunction &F,
205dff0c46cSDimitry Andric       const BlockChain &PlacedChain,
206dff0c46cSDimitry Andric       MachineFunction::iterator &PrevUnplacedBlockIt,
207dff0c46cSDimitry Andric       const BlockFilterSet *BlockFilter);
208dff0c46cSDimitry Andric   void buildChain(MachineBasicBlock *BB, BlockChain &Chain,
209dff0c46cSDimitry Andric                   SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
210dff0c46cSDimitry Andric                   const BlockFilterSet *BlockFilter = 0);
211cb4dff85SDimitry Andric   MachineBasicBlock *findBestLoopTop(MachineLoop &L,
212cb4dff85SDimitry Andric                                      const BlockFilterSet &LoopBlockSet);
213cb4dff85SDimitry Andric   MachineBasicBlock *findBestLoopExit(MachineFunction &F,
214dff0c46cSDimitry Andric                                       MachineLoop &L,
215dff0c46cSDimitry Andric                                       const BlockFilterSet &LoopBlockSet);
216dff0c46cSDimitry Andric   void buildLoopChains(MachineFunction &F, MachineLoop &L);
217cb4dff85SDimitry Andric   void rotateLoop(BlockChain &LoopChain, MachineBasicBlock *ExitingBB,
218cb4dff85SDimitry Andric                   const BlockFilterSet &LoopBlockSet);
219dff0c46cSDimitry Andric   void buildCFGChains(MachineFunction &F);
220dff0c46cSDimitry Andric 
221dff0c46cSDimitry Andric public:
222dff0c46cSDimitry Andric   static char ID; // Pass identification, replacement for typeid
223dff0c46cSDimitry Andric   MachineBlockPlacement() : MachineFunctionPass(ID) {
224dff0c46cSDimitry Andric     initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
225dff0c46cSDimitry Andric   }
226dff0c46cSDimitry Andric 
227dff0c46cSDimitry Andric   bool runOnMachineFunction(MachineFunction &F);
228dff0c46cSDimitry Andric 
229dff0c46cSDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const {
230dff0c46cSDimitry Andric     AU.addRequired<MachineBranchProbabilityInfo>();
231dff0c46cSDimitry Andric     AU.addRequired<MachineBlockFrequencyInfo>();
232dff0c46cSDimitry Andric     AU.addRequired<MachineLoopInfo>();
233dff0c46cSDimitry Andric     MachineFunctionPass::getAnalysisUsage(AU);
234dff0c46cSDimitry Andric   }
235dff0c46cSDimitry Andric };
236dff0c46cSDimitry Andric }
237dff0c46cSDimitry Andric 
238dff0c46cSDimitry Andric char MachineBlockPlacement::ID = 0;
239dff0c46cSDimitry Andric char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
240dff0c46cSDimitry Andric INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement2",
241dff0c46cSDimitry Andric                       "Branch Probability Basic Block Placement", false, false)
242dff0c46cSDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
243dff0c46cSDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
244dff0c46cSDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
245dff0c46cSDimitry Andric INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement2",
246dff0c46cSDimitry Andric                     "Branch Probability Basic Block Placement", false, false)
247dff0c46cSDimitry Andric 
248dff0c46cSDimitry Andric #ifndef NDEBUG
249dff0c46cSDimitry Andric /// \brief Helper to print the name of a MBB.
250dff0c46cSDimitry Andric ///
251dff0c46cSDimitry Andric /// Only used by debug logging.
252dff0c46cSDimitry Andric static std::string getBlockName(MachineBasicBlock *BB) {
253dff0c46cSDimitry Andric   std::string Result;
254dff0c46cSDimitry Andric   raw_string_ostream OS(Result);
255dff0c46cSDimitry Andric   OS << "BB#" << BB->getNumber()
256dff0c46cSDimitry Andric      << " (derived from LLVM BB '" << BB->getName() << "')";
257dff0c46cSDimitry Andric   OS.flush();
258dff0c46cSDimitry Andric   return Result;
259dff0c46cSDimitry Andric }
260dff0c46cSDimitry Andric 
261dff0c46cSDimitry Andric /// \brief Helper to print the number of a MBB.
262dff0c46cSDimitry Andric ///
263dff0c46cSDimitry Andric /// Only used by debug logging.
264dff0c46cSDimitry Andric static std::string getBlockNum(MachineBasicBlock *BB) {
265dff0c46cSDimitry Andric   std::string Result;
266dff0c46cSDimitry Andric   raw_string_ostream OS(Result);
267dff0c46cSDimitry Andric   OS << "BB#" << BB->getNumber();
268dff0c46cSDimitry Andric   OS.flush();
269dff0c46cSDimitry Andric   return Result;
270dff0c46cSDimitry Andric }
271dff0c46cSDimitry Andric #endif
272dff0c46cSDimitry Andric 
273dff0c46cSDimitry Andric /// \brief Mark a chain's successors as having one fewer preds.
274dff0c46cSDimitry Andric ///
275dff0c46cSDimitry Andric /// When a chain is being merged into the "placed" chain, this routine will
276dff0c46cSDimitry Andric /// quickly walk the successors of each block in the chain and mark them as
277dff0c46cSDimitry Andric /// having one fewer active predecessor. It also adds any successors of this
278dff0c46cSDimitry Andric /// chain which reach the zero-predecessor state to the worklist passed in.
279dff0c46cSDimitry Andric void MachineBlockPlacement::markChainSuccessors(
280dff0c46cSDimitry Andric     BlockChain &Chain,
281dff0c46cSDimitry Andric     MachineBasicBlock *LoopHeaderBB,
282dff0c46cSDimitry Andric     SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
283dff0c46cSDimitry Andric     const BlockFilterSet *BlockFilter) {
284dff0c46cSDimitry Andric   // Walk all the blocks in this chain, marking their successors as having
285dff0c46cSDimitry Andric   // a predecessor placed.
286dff0c46cSDimitry Andric   for (BlockChain::iterator CBI = Chain.begin(), CBE = Chain.end();
287dff0c46cSDimitry Andric        CBI != CBE; ++CBI) {
288dff0c46cSDimitry Andric     // Add any successors for which this is the only un-placed in-loop
289dff0c46cSDimitry Andric     // predecessor to the worklist as a viable candidate for CFG-neutral
290dff0c46cSDimitry Andric     // placement. No subsequent placement of this block will violate the CFG
291dff0c46cSDimitry Andric     // shape, so we get to use heuristics to choose a favorable placement.
292dff0c46cSDimitry Andric     for (MachineBasicBlock::succ_iterator SI = (*CBI)->succ_begin(),
293dff0c46cSDimitry Andric                                           SE = (*CBI)->succ_end();
294dff0c46cSDimitry Andric          SI != SE; ++SI) {
295dff0c46cSDimitry Andric       if (BlockFilter && !BlockFilter->count(*SI))
296dff0c46cSDimitry Andric         continue;
297dff0c46cSDimitry Andric       BlockChain &SuccChain = *BlockToChain[*SI];
298dff0c46cSDimitry Andric       // Disregard edges within a fixed chain, or edges to the loop header.
299dff0c46cSDimitry Andric       if (&Chain == &SuccChain || *SI == LoopHeaderBB)
300dff0c46cSDimitry Andric         continue;
301dff0c46cSDimitry Andric 
302dff0c46cSDimitry Andric       // This is a cross-chain edge that is within the loop, so decrement the
303dff0c46cSDimitry Andric       // loop predecessor count of the destination chain.
304dff0c46cSDimitry Andric       if (SuccChain.LoopPredecessors > 0 && --SuccChain.LoopPredecessors == 0)
305dff0c46cSDimitry Andric         BlockWorkList.push_back(*SuccChain.begin());
306dff0c46cSDimitry Andric     }
307dff0c46cSDimitry Andric   }
308dff0c46cSDimitry Andric }
309dff0c46cSDimitry Andric 
310dff0c46cSDimitry Andric /// \brief Select the best successor for a block.
311dff0c46cSDimitry Andric ///
312dff0c46cSDimitry Andric /// This looks across all successors of a particular block and attempts to
313dff0c46cSDimitry Andric /// select the "best" one to be the layout successor. It only considers direct
314dff0c46cSDimitry Andric /// successors which also pass the block filter. It will attempt to avoid
315dff0c46cSDimitry Andric /// breaking CFG structure, but cave and break such structures in the case of
316dff0c46cSDimitry Andric /// very hot successor edges.
317dff0c46cSDimitry Andric ///
318dff0c46cSDimitry Andric /// \returns The best successor block found, or null if none are viable.
319dff0c46cSDimitry Andric MachineBasicBlock *MachineBlockPlacement::selectBestSuccessor(
320dff0c46cSDimitry Andric     MachineBasicBlock *BB, BlockChain &Chain,
321dff0c46cSDimitry Andric     const BlockFilterSet *BlockFilter) {
322dff0c46cSDimitry Andric   const BranchProbability HotProb(4, 5); // 80%
323dff0c46cSDimitry Andric 
324dff0c46cSDimitry Andric   MachineBasicBlock *BestSucc = 0;
325dff0c46cSDimitry Andric   // FIXME: Due to the performance of the probability and weight routines in
326dff0c46cSDimitry Andric   // the MBPI analysis, we manually compute probabilities using the edge
327dff0c46cSDimitry Andric   // weights. This is suboptimal as it means that the somewhat subtle
328dff0c46cSDimitry Andric   // definition of edge weight semantics is encoded here as well. We should
3297ae0e2c9SDimitry Andric   // improve the MBPI interface to efficiently support query patterns such as
330dff0c46cSDimitry Andric   // this.
331dff0c46cSDimitry Andric   uint32_t BestWeight = 0;
332dff0c46cSDimitry Andric   uint32_t WeightScale = 0;
333dff0c46cSDimitry Andric   uint32_t SumWeight = MBPI->getSumForBlock(BB, WeightScale);
334dff0c46cSDimitry Andric   DEBUG(dbgs() << "Attempting merge from: " << getBlockName(BB) << "\n");
335dff0c46cSDimitry Andric   for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
336dff0c46cSDimitry Andric                                         SE = BB->succ_end();
337dff0c46cSDimitry Andric        SI != SE; ++SI) {
338dff0c46cSDimitry Andric     if (BlockFilter && !BlockFilter->count(*SI))
339dff0c46cSDimitry Andric       continue;
340dff0c46cSDimitry Andric     BlockChain &SuccChain = *BlockToChain[*SI];
341dff0c46cSDimitry Andric     if (&SuccChain == &Chain) {
342dff0c46cSDimitry Andric       DEBUG(dbgs() << "    " << getBlockName(*SI) << " -> Already merged!\n");
343dff0c46cSDimitry Andric       continue;
344dff0c46cSDimitry Andric     }
345dff0c46cSDimitry Andric     if (*SI != *SuccChain.begin()) {
346dff0c46cSDimitry Andric       DEBUG(dbgs() << "    " << getBlockName(*SI) << " -> Mid chain!\n");
347dff0c46cSDimitry Andric       continue;
348dff0c46cSDimitry Andric     }
349dff0c46cSDimitry Andric 
350dff0c46cSDimitry Andric     uint32_t SuccWeight = MBPI->getEdgeWeight(BB, *SI);
351dff0c46cSDimitry Andric     BranchProbability SuccProb(SuccWeight / WeightScale, SumWeight);
352dff0c46cSDimitry Andric 
353dff0c46cSDimitry Andric     // Only consider successors which are either "hot", or wouldn't violate
354dff0c46cSDimitry Andric     // any CFG constraints.
355dff0c46cSDimitry Andric     if (SuccChain.LoopPredecessors != 0) {
356dff0c46cSDimitry Andric       if (SuccProb < HotProb) {
357dff0c46cSDimitry Andric         DEBUG(dbgs() << "    " << getBlockName(*SI) << " -> CFG conflict\n");
358dff0c46cSDimitry Andric         continue;
359dff0c46cSDimitry Andric       }
360dff0c46cSDimitry Andric 
361dff0c46cSDimitry Andric       // Make sure that a hot successor doesn't have a globally more important
362dff0c46cSDimitry Andric       // predecessor.
363dff0c46cSDimitry Andric       BlockFrequency CandidateEdgeFreq
364dff0c46cSDimitry Andric         = MBFI->getBlockFreq(BB) * SuccProb * HotProb.getCompl();
365dff0c46cSDimitry Andric       bool BadCFGConflict = false;
366dff0c46cSDimitry Andric       for (MachineBasicBlock::pred_iterator PI = (*SI)->pred_begin(),
367dff0c46cSDimitry Andric                                             PE = (*SI)->pred_end();
368dff0c46cSDimitry Andric            PI != PE; ++PI) {
369dff0c46cSDimitry Andric         if (*PI == *SI || (BlockFilter && !BlockFilter->count(*PI)) ||
370dff0c46cSDimitry Andric             BlockToChain[*PI] == &Chain)
371dff0c46cSDimitry Andric           continue;
372dff0c46cSDimitry Andric         BlockFrequency PredEdgeFreq
373dff0c46cSDimitry Andric           = MBFI->getBlockFreq(*PI) * MBPI->getEdgeProbability(*PI, *SI);
374dff0c46cSDimitry Andric         if (PredEdgeFreq >= CandidateEdgeFreq) {
375dff0c46cSDimitry Andric           BadCFGConflict = true;
376dff0c46cSDimitry Andric           break;
377dff0c46cSDimitry Andric         }
378dff0c46cSDimitry Andric       }
379dff0c46cSDimitry Andric       if (BadCFGConflict) {
380dff0c46cSDimitry Andric         DEBUG(dbgs() << "    " << getBlockName(*SI)
381dff0c46cSDimitry Andric                                << " -> non-cold CFG conflict\n");
382dff0c46cSDimitry Andric         continue;
383dff0c46cSDimitry Andric       }
384dff0c46cSDimitry Andric     }
385dff0c46cSDimitry Andric 
386dff0c46cSDimitry Andric     DEBUG(dbgs() << "    " << getBlockName(*SI) << " -> " << SuccProb
387dff0c46cSDimitry Andric                  << " (prob)"
388dff0c46cSDimitry Andric                  << (SuccChain.LoopPredecessors != 0 ? " (CFG break)" : "")
389dff0c46cSDimitry Andric                  << "\n");
390dff0c46cSDimitry Andric     if (BestSucc && BestWeight >= SuccWeight)
391dff0c46cSDimitry Andric       continue;
392dff0c46cSDimitry Andric     BestSucc = *SI;
393dff0c46cSDimitry Andric     BestWeight = SuccWeight;
394dff0c46cSDimitry Andric   }
395dff0c46cSDimitry Andric   return BestSucc;
396dff0c46cSDimitry Andric }
397dff0c46cSDimitry Andric 
398dff0c46cSDimitry Andric namespace {
399dff0c46cSDimitry Andric /// \brief Predicate struct to detect blocks already placed.
400dff0c46cSDimitry Andric class IsBlockPlaced {
401dff0c46cSDimitry Andric   const BlockChain &PlacedChain;
402dff0c46cSDimitry Andric   const BlockToChainMapType &BlockToChain;
403dff0c46cSDimitry Andric 
404dff0c46cSDimitry Andric public:
405dff0c46cSDimitry Andric   IsBlockPlaced(const BlockChain &PlacedChain,
406dff0c46cSDimitry Andric                 const BlockToChainMapType &BlockToChain)
407dff0c46cSDimitry Andric       : PlacedChain(PlacedChain), BlockToChain(BlockToChain) {}
408dff0c46cSDimitry Andric 
409dff0c46cSDimitry Andric   bool operator()(MachineBasicBlock *BB) const {
410dff0c46cSDimitry Andric     return BlockToChain.lookup(BB) == &PlacedChain;
411dff0c46cSDimitry Andric   }
412dff0c46cSDimitry Andric };
413dff0c46cSDimitry Andric }
414dff0c46cSDimitry Andric 
415dff0c46cSDimitry Andric /// \brief Select the best block from a worklist.
416dff0c46cSDimitry Andric ///
417dff0c46cSDimitry Andric /// This looks through the provided worklist as a list of candidate basic
418dff0c46cSDimitry Andric /// blocks and select the most profitable one to place. The definition of
419dff0c46cSDimitry Andric /// profitable only really makes sense in the context of a loop. This returns
420dff0c46cSDimitry Andric /// the most frequently visited block in the worklist, which in the case of
421dff0c46cSDimitry Andric /// a loop, is the one most desirable to be physically close to the rest of the
422dff0c46cSDimitry Andric /// loop body in order to improve icache behavior.
423dff0c46cSDimitry Andric ///
424dff0c46cSDimitry Andric /// \returns The best block found, or null if none are viable.
425dff0c46cSDimitry Andric MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
426dff0c46cSDimitry Andric     BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList,
427dff0c46cSDimitry Andric     const BlockFilterSet *BlockFilter) {
428dff0c46cSDimitry Andric   // Once we need to walk the worklist looking for a candidate, cleanup the
429dff0c46cSDimitry Andric   // worklist of already placed entries.
430dff0c46cSDimitry Andric   // FIXME: If this shows up on profiles, it could be folded (at the cost of
431dff0c46cSDimitry Andric   // some code complexity) into the loop below.
432dff0c46cSDimitry Andric   WorkList.erase(std::remove_if(WorkList.begin(), WorkList.end(),
433dff0c46cSDimitry Andric                                 IsBlockPlaced(Chain, BlockToChain)),
434dff0c46cSDimitry Andric                  WorkList.end());
435dff0c46cSDimitry Andric 
436dff0c46cSDimitry Andric   MachineBasicBlock *BestBlock = 0;
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);
450dff0c46cSDimitry Andric     DEBUG(dbgs() << "    " << getBlockName(*WBI) << " -> " << CandidateFreq
451dff0c46cSDimitry Andric                  << " (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   }
483dff0c46cSDimitry Andric   return 0;
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);
498dff0c46cSDimitry Andric   BB = *llvm::prior(Chain.end());
499dff0c46cSDimitry Andric   for (;;) {
500dff0c46cSDimitry Andric     assert(BB);
501dff0c46cSDimitry Andric     assert(BlockToChain[BB] == &Chain);
502dff0c46cSDimitry Andric     assert(*llvm::prior(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);
533dff0c46cSDimitry Andric     BB = *llvm::prior(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;
564cb4dff85SDimitry Andric   MachineBasicBlock *BestPred = 0;
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) << ", "
572cb4dff85SDimitry Andric                  << Pred->succ_size() << " successors, "
573cb4dff85SDimitry Andric                  << MBFI->getBlockFreq(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()))
620cb4dff85SDimitry Andric     return 0;
621dff0c46cSDimitry Andric 
622dff0c46cSDimitry Andric   BlockFrequency BestExitEdgeFreq;
623cb4dff85SDimitry Andric   unsigned BestExitLoopDepth = 0;
624dff0c46cSDimitry Andric   MachineBasicBlock *ExitingBB = 0;
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.
638dff0c46cSDimitry Andric     if (*I != *llvm::prior(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
687cb4dff85SDimitry Andric                    << "] (" << ExitEdgeFreq << ")\n");
688dff0c46cSDimitry Andric       // Note that we slightly bias this toward an existing layout successor to
689dff0c46cSDimitry Andric       // retain incoming order in the absence of better information.
690dff0c46cSDimitry Andric       // FIXME: Should we bias this more strongly? It's pretty weak.
691cb4dff85SDimitry Andric       if (!ExitingBB || BestExitLoopDepth < SuccLoopDepth ||
692cb4dff85SDimitry Andric           ExitEdgeFreq > BestExitEdgeFreq ||
693dff0c46cSDimitry Andric           ((*I)->isLayoutSuccessor(*SI) &&
694dff0c46cSDimitry Andric            !(ExitEdgeFreq < BestExitEdgeFreq))) {
695dff0c46cSDimitry Andric         BestExitEdgeFreq = ExitEdgeFreq;
696dff0c46cSDimitry Andric         ExitingBB = *I;
697dff0c46cSDimitry Andric       }
698dff0c46cSDimitry Andric     }
699dff0c46cSDimitry Andric 
700dff0c46cSDimitry Andric     // Restore the old exiting state, no viable looping successor was found.
701cb4dff85SDimitry Andric     if (!HasLoopingSucc) {
702dff0c46cSDimitry Andric       ExitingBB = OldExitingBB;
703dff0c46cSDimitry Andric       BestExitEdgeFreq = OldBestExitEdgeFreq;
704dff0c46cSDimitry Andric       continue;
705dff0c46cSDimitry Andric     }
706dff0c46cSDimitry Andric   }
707cb4dff85SDimitry Andric   // Without a candidate exiting block or with only a single block in the
708dff0c46cSDimitry Andric   // loop, just use the loop header to layout the loop.
709dff0c46cSDimitry Andric   if (!ExitingBB || L.getNumBlocks() == 1)
710cb4dff85SDimitry Andric     return 0;
711dff0c46cSDimitry Andric 
712dff0c46cSDimitry Andric   // Also, if we have exit blocks which lead to outer loops but didn't select
713dff0c46cSDimitry Andric   // one of them as the exiting block we are rotating toward, disable loop
714dff0c46cSDimitry Andric   // rotation altogether.
715dff0c46cSDimitry Andric   if (!BlocksExitingToOuterLoop.empty() &&
716dff0c46cSDimitry Andric       !BlocksExitingToOuterLoop.count(ExitingBB))
717cb4dff85SDimitry Andric     return 0;
718dff0c46cSDimitry Andric 
719dff0c46cSDimitry Andric   DEBUG(dbgs() << "  Best exiting block: " << getBlockName(ExitingBB) << "\n");
720cb4dff85SDimitry Andric   return ExitingBB;
721cb4dff85SDimitry Andric }
722cb4dff85SDimitry Andric 
723cb4dff85SDimitry Andric /// \brief Attempt to rotate an exiting block to the bottom of the loop.
724cb4dff85SDimitry Andric ///
725cb4dff85SDimitry Andric /// Once we have built a chain, try to rotate it to line up the hot exit block
726cb4dff85SDimitry Andric /// with fallthrough out of the loop if doing so doesn't introduce unnecessary
727cb4dff85SDimitry Andric /// branches. For example, if the loop has fallthrough into its header and out
728cb4dff85SDimitry Andric /// of its bottom already, don't rotate it.
729cb4dff85SDimitry Andric void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
730cb4dff85SDimitry Andric                                        MachineBasicBlock *ExitingBB,
731cb4dff85SDimitry Andric                                        const BlockFilterSet &LoopBlockSet) {
732cb4dff85SDimitry Andric   if (!ExitingBB)
733cb4dff85SDimitry Andric     return;
734cb4dff85SDimitry Andric 
735cb4dff85SDimitry Andric   MachineBasicBlock *Top = *LoopChain.begin();
736cb4dff85SDimitry Andric   bool ViableTopFallthrough = false;
737cb4dff85SDimitry Andric   for (MachineBasicBlock::pred_iterator PI = Top->pred_begin(),
738cb4dff85SDimitry Andric                                         PE = Top->pred_end();
739cb4dff85SDimitry Andric        PI != PE; ++PI) {
740cb4dff85SDimitry Andric     BlockChain *PredChain = BlockToChain[*PI];
741cb4dff85SDimitry Andric     if (!LoopBlockSet.count(*PI) &&
742cb4dff85SDimitry Andric         (!PredChain || *PI == *llvm::prior(PredChain->end()))) {
743cb4dff85SDimitry Andric       ViableTopFallthrough = true;
744cb4dff85SDimitry Andric       break;
745cb4dff85SDimitry Andric     }
746cb4dff85SDimitry Andric   }
747cb4dff85SDimitry Andric 
748cb4dff85SDimitry Andric   // If the header has viable fallthrough, check whether the current loop
749cb4dff85SDimitry Andric   // bottom is a viable exiting block. If so, bail out as rotating will
750cb4dff85SDimitry Andric   // introduce an unnecessary branch.
751cb4dff85SDimitry Andric   if (ViableTopFallthrough) {
752cb4dff85SDimitry Andric     MachineBasicBlock *Bottom = *llvm::prior(LoopChain.end());
753cb4dff85SDimitry Andric     for (MachineBasicBlock::succ_iterator SI = Bottom->succ_begin(),
754cb4dff85SDimitry Andric                                           SE = Bottom->succ_end();
755cb4dff85SDimitry Andric          SI != SE; ++SI) {
756cb4dff85SDimitry Andric       BlockChain *SuccChain = BlockToChain[*SI];
757cb4dff85SDimitry Andric       if (!LoopBlockSet.count(*SI) &&
758cb4dff85SDimitry Andric           (!SuccChain || *SI == *SuccChain->begin()))
759cb4dff85SDimitry Andric         return;
760cb4dff85SDimitry Andric     }
761cb4dff85SDimitry Andric   }
762cb4dff85SDimitry Andric 
763cb4dff85SDimitry Andric   BlockChain::iterator ExitIt = std::find(LoopChain.begin(), LoopChain.end(),
764cb4dff85SDimitry Andric                                           ExitingBB);
765cb4dff85SDimitry Andric   if (ExitIt == LoopChain.end())
766cb4dff85SDimitry Andric     return;
767cb4dff85SDimitry Andric 
768cb4dff85SDimitry Andric   std::rotate(LoopChain.begin(), llvm::next(ExitIt), LoopChain.end());
769dff0c46cSDimitry Andric }
770dff0c46cSDimitry Andric 
771dff0c46cSDimitry Andric /// \brief Forms basic block chains from the natural loop structures.
772dff0c46cSDimitry Andric ///
773dff0c46cSDimitry Andric /// These chains are designed to preserve the existing *structure* of the code
774dff0c46cSDimitry Andric /// as much as possible. We can then stitch the chains together in a way which
775dff0c46cSDimitry Andric /// both preserves the topological structure and minimizes taken conditional
776dff0c46cSDimitry Andric /// branches.
777dff0c46cSDimitry Andric void MachineBlockPlacement::buildLoopChains(MachineFunction &F,
778dff0c46cSDimitry Andric                                             MachineLoop &L) {
779dff0c46cSDimitry Andric   // First recurse through any nested loops, building chains for those inner
780dff0c46cSDimitry Andric   // loops.
781dff0c46cSDimitry Andric   for (MachineLoop::iterator LI = L.begin(), LE = L.end(); LI != LE; ++LI)
782dff0c46cSDimitry Andric     buildLoopChains(F, **LI);
783dff0c46cSDimitry Andric 
784dff0c46cSDimitry Andric   SmallVector<MachineBasicBlock *, 16> BlockWorkList;
785dff0c46cSDimitry Andric   BlockFilterSet LoopBlockSet(L.block_begin(), L.block_end());
786dff0c46cSDimitry Andric 
787cb4dff85SDimitry Andric   // First check to see if there is an obviously preferable top block for the
788cb4dff85SDimitry Andric   // loop. This will default to the header, but may end up as one of the
789cb4dff85SDimitry Andric   // predecessors to the header if there is one which will result in strictly
790cb4dff85SDimitry Andric   // fewer branches in the loop body.
791cb4dff85SDimitry Andric   MachineBasicBlock *LoopTop = findBestLoopTop(L, LoopBlockSet);
792cb4dff85SDimitry Andric 
793cb4dff85SDimitry Andric   // If we selected just the header for the loop top, look for a potentially
794cb4dff85SDimitry Andric   // profitable exit block in the event that rotating the loop can eliminate
795cb4dff85SDimitry Andric   // branches by placing an exit edge at the bottom.
796cb4dff85SDimitry Andric   MachineBasicBlock *ExitingBB = 0;
797cb4dff85SDimitry Andric   if (LoopTop == L.getHeader())
798cb4dff85SDimitry Andric     ExitingBB = findBestLoopExit(F, L, LoopBlockSet);
799cb4dff85SDimitry Andric 
800cb4dff85SDimitry Andric   BlockChain &LoopChain = *BlockToChain[LoopTop];
801dff0c46cSDimitry Andric 
802dff0c46cSDimitry Andric   // FIXME: This is a really lame way of walking the chains in the loop: we
803dff0c46cSDimitry Andric   // walk the blocks, and use a set to prevent visiting a particular chain
804dff0c46cSDimitry Andric   // twice.
805dff0c46cSDimitry Andric   SmallPtrSet<BlockChain *, 4> UpdatedPreds;
806dff0c46cSDimitry Andric   assert(LoopChain.LoopPredecessors == 0);
807dff0c46cSDimitry Andric   UpdatedPreds.insert(&LoopChain);
808dff0c46cSDimitry Andric   for (MachineLoop::block_iterator BI = L.block_begin(),
809dff0c46cSDimitry Andric                                    BE = L.block_end();
810dff0c46cSDimitry Andric        BI != BE; ++BI) {
811dff0c46cSDimitry Andric     BlockChain &Chain = *BlockToChain[*BI];
812dff0c46cSDimitry Andric     if (!UpdatedPreds.insert(&Chain))
813dff0c46cSDimitry Andric       continue;
814dff0c46cSDimitry Andric 
815dff0c46cSDimitry Andric     assert(Chain.LoopPredecessors == 0);
816dff0c46cSDimitry Andric     for (BlockChain::iterator BCI = Chain.begin(), BCE = Chain.end();
817dff0c46cSDimitry Andric          BCI != BCE; ++BCI) {
818dff0c46cSDimitry Andric       assert(BlockToChain[*BCI] == &Chain);
819dff0c46cSDimitry Andric       for (MachineBasicBlock::pred_iterator PI = (*BCI)->pred_begin(),
820dff0c46cSDimitry Andric                                             PE = (*BCI)->pred_end();
821dff0c46cSDimitry Andric            PI != PE; ++PI) {
822dff0c46cSDimitry Andric         if (BlockToChain[*PI] == &Chain || !LoopBlockSet.count(*PI))
823dff0c46cSDimitry Andric           continue;
824dff0c46cSDimitry Andric         ++Chain.LoopPredecessors;
825dff0c46cSDimitry Andric       }
826dff0c46cSDimitry Andric     }
827dff0c46cSDimitry Andric 
828dff0c46cSDimitry Andric     if (Chain.LoopPredecessors == 0)
829dff0c46cSDimitry Andric       BlockWorkList.push_back(*Chain.begin());
830dff0c46cSDimitry Andric   }
831dff0c46cSDimitry Andric 
832cb4dff85SDimitry Andric   buildChain(LoopTop, LoopChain, BlockWorkList, &LoopBlockSet);
833cb4dff85SDimitry Andric   rotateLoop(LoopChain, ExitingBB, LoopBlockSet);
834dff0c46cSDimitry Andric 
835dff0c46cSDimitry Andric   DEBUG({
836dff0c46cSDimitry Andric     // Crash at the end so we get all of the debugging output first.
837dff0c46cSDimitry Andric     bool BadLoop = false;
838dff0c46cSDimitry Andric     if (LoopChain.LoopPredecessors) {
839dff0c46cSDimitry Andric       BadLoop = true;
840dff0c46cSDimitry Andric       dbgs() << "Loop chain contains a block without its preds placed!\n"
841dff0c46cSDimitry Andric              << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
842dff0c46cSDimitry Andric              << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
843dff0c46cSDimitry Andric     }
844dff0c46cSDimitry Andric     for (BlockChain::iterator BCI = LoopChain.begin(), BCE = LoopChain.end();
845cb4dff85SDimitry Andric          BCI != BCE; ++BCI) {
846cb4dff85SDimitry Andric       dbgs() << "          ... " << getBlockName(*BCI) << "\n";
847dff0c46cSDimitry Andric       if (!LoopBlockSet.erase(*BCI)) {
848dff0c46cSDimitry Andric         // We don't mark the loop as bad here because there are real situations
849dff0c46cSDimitry Andric         // where this can occur. For example, with an unanalyzable fallthrough
850dff0c46cSDimitry Andric         // from a loop block to a non-loop block or vice versa.
851dff0c46cSDimitry Andric         dbgs() << "Loop chain contains a block not contained by the loop!\n"
852dff0c46cSDimitry Andric                << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
853dff0c46cSDimitry Andric                << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
854dff0c46cSDimitry Andric                << "  Bad block:    " << getBlockName(*BCI) << "\n";
855dff0c46cSDimitry Andric       }
856cb4dff85SDimitry Andric     }
857dff0c46cSDimitry Andric 
858dff0c46cSDimitry Andric     if (!LoopBlockSet.empty()) {
859dff0c46cSDimitry Andric       BadLoop = true;
860dff0c46cSDimitry Andric       for (BlockFilterSet::iterator LBI = LoopBlockSet.begin(),
861dff0c46cSDimitry Andric                                     LBE = LoopBlockSet.end();
862dff0c46cSDimitry Andric            LBI != LBE; ++LBI)
863dff0c46cSDimitry Andric         dbgs() << "Loop contains blocks never placed into a chain!\n"
864dff0c46cSDimitry Andric                << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
865dff0c46cSDimitry Andric                << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
866dff0c46cSDimitry Andric                << "  Bad block:    " << getBlockName(*LBI) << "\n";
867dff0c46cSDimitry Andric     }
868dff0c46cSDimitry Andric     assert(!BadLoop && "Detected problems with the placement of this loop.");
869dff0c46cSDimitry Andric   });
870dff0c46cSDimitry Andric }
871dff0c46cSDimitry Andric 
872dff0c46cSDimitry Andric void MachineBlockPlacement::buildCFGChains(MachineFunction &F) {
873dff0c46cSDimitry Andric   // Ensure that every BB in the function has an associated chain to simplify
874dff0c46cSDimitry Andric   // the assumptions of the remaining algorithm.
875dff0c46cSDimitry Andric   SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
876dff0c46cSDimitry Andric   for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
877dff0c46cSDimitry Andric     MachineBasicBlock *BB = FI;
878dff0c46cSDimitry Andric     BlockChain *Chain
879dff0c46cSDimitry Andric       = new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
880dff0c46cSDimitry Andric     // Also, merge any blocks which we cannot reason about and must preserve
881dff0c46cSDimitry Andric     // the exact fallthrough behavior for.
882dff0c46cSDimitry Andric     for (;;) {
883dff0c46cSDimitry Andric       Cond.clear();
884dff0c46cSDimitry Andric       MachineBasicBlock *TBB = 0, *FBB = 0; // For AnalyzeBranch.
885dff0c46cSDimitry Andric       if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
886dff0c46cSDimitry Andric         break;
887dff0c46cSDimitry Andric 
888dff0c46cSDimitry Andric       MachineFunction::iterator NextFI(llvm::next(FI));
889dff0c46cSDimitry Andric       MachineBasicBlock *NextBB = NextFI;
890dff0c46cSDimitry Andric       // Ensure that the layout successor is a viable block, as we know that
891dff0c46cSDimitry Andric       // fallthrough is a possibility.
892dff0c46cSDimitry Andric       assert(NextFI != FE && "Can't fallthrough past the last block.");
893dff0c46cSDimitry Andric       DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
894dff0c46cSDimitry Andric                    << getBlockName(BB) << " -> " << getBlockName(NextBB)
895dff0c46cSDimitry Andric                    << "\n");
896dff0c46cSDimitry Andric       Chain->merge(NextBB, 0);
897dff0c46cSDimitry Andric       FI = NextFI;
898dff0c46cSDimitry Andric       BB = NextBB;
899dff0c46cSDimitry Andric     }
900dff0c46cSDimitry Andric   }
901dff0c46cSDimitry Andric 
902dff0c46cSDimitry Andric   // Build any loop-based chains.
903dff0c46cSDimitry Andric   for (MachineLoopInfo::iterator LI = MLI->begin(), LE = MLI->end(); LI != LE;
904dff0c46cSDimitry Andric        ++LI)
905dff0c46cSDimitry Andric     buildLoopChains(F, **LI);
906dff0c46cSDimitry Andric 
907dff0c46cSDimitry Andric   SmallVector<MachineBasicBlock *, 16> BlockWorkList;
908dff0c46cSDimitry Andric 
909dff0c46cSDimitry Andric   SmallPtrSet<BlockChain *, 4> UpdatedPreds;
910dff0c46cSDimitry Andric   for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
911dff0c46cSDimitry Andric     MachineBasicBlock *BB = &*FI;
912dff0c46cSDimitry Andric     BlockChain &Chain = *BlockToChain[BB];
913dff0c46cSDimitry Andric     if (!UpdatedPreds.insert(&Chain))
914dff0c46cSDimitry Andric       continue;
915dff0c46cSDimitry Andric 
916dff0c46cSDimitry Andric     assert(Chain.LoopPredecessors == 0);
917dff0c46cSDimitry Andric     for (BlockChain::iterator BCI = Chain.begin(), BCE = Chain.end();
918dff0c46cSDimitry Andric          BCI != BCE; ++BCI) {
919dff0c46cSDimitry Andric       assert(BlockToChain[*BCI] == &Chain);
920dff0c46cSDimitry Andric       for (MachineBasicBlock::pred_iterator PI = (*BCI)->pred_begin(),
921dff0c46cSDimitry Andric                                             PE = (*BCI)->pred_end();
922dff0c46cSDimitry Andric            PI != PE; ++PI) {
923dff0c46cSDimitry Andric         if (BlockToChain[*PI] == &Chain)
924dff0c46cSDimitry Andric           continue;
925dff0c46cSDimitry Andric         ++Chain.LoopPredecessors;
926dff0c46cSDimitry Andric       }
927dff0c46cSDimitry Andric     }
928dff0c46cSDimitry Andric 
929dff0c46cSDimitry Andric     if (Chain.LoopPredecessors == 0)
930dff0c46cSDimitry Andric       BlockWorkList.push_back(*Chain.begin());
931dff0c46cSDimitry Andric   }
932dff0c46cSDimitry Andric 
933dff0c46cSDimitry Andric   BlockChain &FunctionChain = *BlockToChain[&F.front()];
934dff0c46cSDimitry Andric   buildChain(&F.front(), FunctionChain, BlockWorkList);
935dff0c46cSDimitry Andric 
936dff0c46cSDimitry Andric   typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType;
937dff0c46cSDimitry Andric   DEBUG({
938dff0c46cSDimitry Andric     // Crash at the end so we get all of the debugging output first.
939dff0c46cSDimitry Andric     bool BadFunc = false;
940dff0c46cSDimitry Andric     FunctionBlockSetType FunctionBlockSet;
941dff0c46cSDimitry Andric     for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
942dff0c46cSDimitry Andric       FunctionBlockSet.insert(FI);
943dff0c46cSDimitry Andric 
944dff0c46cSDimitry Andric     for (BlockChain::iterator BCI = FunctionChain.begin(),
945dff0c46cSDimitry Andric                               BCE = FunctionChain.end();
946dff0c46cSDimitry Andric          BCI != BCE; ++BCI)
947dff0c46cSDimitry Andric       if (!FunctionBlockSet.erase(*BCI)) {
948dff0c46cSDimitry Andric         BadFunc = true;
949dff0c46cSDimitry Andric         dbgs() << "Function chain contains a block not in the function!\n"
950dff0c46cSDimitry Andric                << "  Bad block:    " << getBlockName(*BCI) << "\n";
951dff0c46cSDimitry Andric       }
952dff0c46cSDimitry Andric 
953dff0c46cSDimitry Andric     if (!FunctionBlockSet.empty()) {
954dff0c46cSDimitry Andric       BadFunc = true;
955dff0c46cSDimitry Andric       for (FunctionBlockSetType::iterator FBI = FunctionBlockSet.begin(),
956dff0c46cSDimitry Andric                                           FBE = FunctionBlockSet.end();
957dff0c46cSDimitry Andric            FBI != FBE; ++FBI)
958dff0c46cSDimitry Andric         dbgs() << "Function contains blocks never placed into a chain!\n"
959dff0c46cSDimitry Andric                << "  Bad block:    " << getBlockName(*FBI) << "\n";
960dff0c46cSDimitry Andric     }
961dff0c46cSDimitry Andric     assert(!BadFunc && "Detected problems with the block placement.");
962dff0c46cSDimitry Andric   });
963dff0c46cSDimitry Andric 
964dff0c46cSDimitry Andric   // Splice the blocks into place.
965dff0c46cSDimitry Andric   MachineFunction::iterator InsertPos = F.begin();
966dff0c46cSDimitry Andric   for (BlockChain::iterator BI = FunctionChain.begin(),
967dff0c46cSDimitry Andric                             BE = FunctionChain.end();
968dff0c46cSDimitry Andric        BI != BE; ++BI) {
969dff0c46cSDimitry Andric     DEBUG(dbgs() << (BI == FunctionChain.begin() ? "Placing chain "
970dff0c46cSDimitry Andric                                                   : "          ... ")
971dff0c46cSDimitry Andric           << getBlockName(*BI) << "\n");
972dff0c46cSDimitry Andric     if (InsertPos != MachineFunction::iterator(*BI))
973dff0c46cSDimitry Andric       F.splice(InsertPos, *BI);
974dff0c46cSDimitry Andric     else
975dff0c46cSDimitry Andric       ++InsertPos;
976dff0c46cSDimitry Andric 
977dff0c46cSDimitry Andric     // Update the terminator of the previous block.
978dff0c46cSDimitry Andric     if (BI == FunctionChain.begin())
979dff0c46cSDimitry Andric       continue;
980dff0c46cSDimitry Andric     MachineBasicBlock *PrevBB = llvm::prior(MachineFunction::iterator(*BI));
981dff0c46cSDimitry Andric 
982dff0c46cSDimitry Andric     // FIXME: It would be awesome of updateTerminator would just return rather
983dff0c46cSDimitry Andric     // than assert when the branch cannot be analyzed in order to remove this
984dff0c46cSDimitry Andric     // boiler plate.
985dff0c46cSDimitry Andric     Cond.clear();
986dff0c46cSDimitry Andric     MachineBasicBlock *TBB = 0, *FBB = 0; // For AnalyzeBranch.
9877ae0e2c9SDimitry Andric     if (!TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
9887ae0e2c9SDimitry Andric       // If PrevBB has a two-way branch, try to re-order the branches
9897ae0e2c9SDimitry Andric       // such that we branch to the successor with higher weight first.
9907ae0e2c9SDimitry Andric       if (TBB && !Cond.empty() && FBB &&
9917ae0e2c9SDimitry Andric           MBPI->getEdgeWeight(PrevBB, FBB) > MBPI->getEdgeWeight(PrevBB, TBB) &&
9927ae0e2c9SDimitry Andric           !TII->ReverseBranchCondition(Cond)) {
9937ae0e2c9SDimitry Andric         DEBUG(dbgs() << "Reverse order of the two branches: "
9947ae0e2c9SDimitry Andric                      << getBlockName(PrevBB) << "\n");
9957ae0e2c9SDimitry Andric         DEBUG(dbgs() << "    Edge weight: " << MBPI->getEdgeWeight(PrevBB, FBB)
9967ae0e2c9SDimitry Andric                      << " vs " << MBPI->getEdgeWeight(PrevBB, TBB) << "\n");
9977ae0e2c9SDimitry Andric         DebugLoc dl;  // FIXME: this is nowhere
9987ae0e2c9SDimitry Andric         TII->RemoveBranch(*PrevBB);
9997ae0e2c9SDimitry Andric         TII->InsertBranch(*PrevBB, FBB, TBB, Cond, dl);
10007ae0e2c9SDimitry Andric       }
1001dff0c46cSDimitry Andric       PrevBB->updateTerminator();
1002dff0c46cSDimitry Andric     }
10037ae0e2c9SDimitry Andric   }
1004dff0c46cSDimitry Andric 
1005dff0c46cSDimitry Andric   // Fixup the last block.
1006dff0c46cSDimitry Andric   Cond.clear();
1007dff0c46cSDimitry Andric   MachineBasicBlock *TBB = 0, *FBB = 0; // For AnalyzeBranch.
1008dff0c46cSDimitry Andric   if (!TII->AnalyzeBranch(F.back(), TBB, FBB, Cond))
1009dff0c46cSDimitry Andric     F.back().updateTerminator();
1010dff0c46cSDimitry Andric 
1011cb4dff85SDimitry Andric   // Walk through the backedges of the function now that we have fully laid out
1012cb4dff85SDimitry Andric   // the basic blocks and align the destination of each backedge. We don't rely
10137ae0e2c9SDimitry Andric   // exclusively on the loop info here so that we can align backedges in
10147ae0e2c9SDimitry Andric   // unnatural CFGs and backedges that were introduced purely because of the
10157ae0e2c9SDimitry Andric   // loop rotations done during this layout pass.
10163861d79fSDimitry Andric   if (F.getFunction()->getFnAttributes().
10173861d79fSDimitry Andric         hasAttribute(Attributes::OptimizeForSize))
1018dff0c46cSDimitry Andric     return;
1019dff0c46cSDimitry Andric   unsigned Align = TLI->getPrefLoopAlignment();
1020dff0c46cSDimitry Andric   if (!Align)
1021dff0c46cSDimitry Andric     return;  // Don't care about loop alignment.
10227ae0e2c9SDimitry Andric   if (FunctionChain.begin() == FunctionChain.end())
10237ae0e2c9SDimitry Andric     return;  // Empty chain.
1024dff0c46cSDimitry Andric 
10257ae0e2c9SDimitry Andric   const BranchProbability ColdProb(1, 5); // 20%
10267ae0e2c9SDimitry Andric   BlockFrequency EntryFreq = MBFI->getBlockFreq(F.begin());
10277ae0e2c9SDimitry Andric   BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
10287ae0e2c9SDimitry Andric   for (BlockChain::iterator BI = llvm::next(FunctionChain.begin()),
1029cb4dff85SDimitry Andric                             BE = FunctionChain.end();
1030cb4dff85SDimitry Andric        BI != BE; ++BI) {
10317ae0e2c9SDimitry Andric     // Don't align non-looping basic blocks. These are unlikely to execute
10327ae0e2c9SDimitry Andric     // enough times to matter in practice. Note that we'll still handle
10337ae0e2c9SDimitry Andric     // unnatural CFGs inside of a natural outer loop (the common case) and
10347ae0e2c9SDimitry Andric     // rotated loops.
10357ae0e2c9SDimitry Andric     MachineLoop *L = MLI->getLoopFor(*BI);
10367ae0e2c9SDimitry Andric     if (!L)
10377ae0e2c9SDimitry Andric       continue;
10387ae0e2c9SDimitry Andric 
10397ae0e2c9SDimitry Andric     // If the block is cold relative to the function entry don't waste space
10407ae0e2c9SDimitry Andric     // aligning it.
10417ae0e2c9SDimitry Andric     BlockFrequency Freq = MBFI->getBlockFreq(*BI);
10427ae0e2c9SDimitry Andric     if (Freq < WeightedEntryFreq)
10437ae0e2c9SDimitry Andric       continue;
10447ae0e2c9SDimitry Andric 
10457ae0e2c9SDimitry Andric     // If the block is cold relative to its loop header, don't align it
10467ae0e2c9SDimitry Andric     // regardless of what edges into the block exist.
10477ae0e2c9SDimitry Andric     MachineBasicBlock *LoopHeader = L->getHeader();
10487ae0e2c9SDimitry Andric     BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
10497ae0e2c9SDimitry Andric     if (Freq < (LoopHeaderFreq * ColdProb))
10507ae0e2c9SDimitry Andric       continue;
10517ae0e2c9SDimitry Andric 
10527ae0e2c9SDimitry Andric     // Check for the existence of a non-layout predecessor which would benefit
10537ae0e2c9SDimitry Andric     // from aligning this block.
10547ae0e2c9SDimitry Andric     MachineBasicBlock *LayoutPred = *llvm::prior(BI);
10557ae0e2c9SDimitry Andric 
10567ae0e2c9SDimitry Andric     // Force alignment if all the predecessors are jumps. We already checked
10577ae0e2c9SDimitry Andric     // that the block isn't cold above.
10587ae0e2c9SDimitry Andric     if (!LayoutPred->isSuccessor(*BI)) {
10597ae0e2c9SDimitry Andric       (*BI)->setAlignment(Align);
10607ae0e2c9SDimitry Andric       continue;
10617ae0e2c9SDimitry Andric     }
10627ae0e2c9SDimitry Andric 
10637ae0e2c9SDimitry Andric     // Align this block if the layout predecessor's edge into this block is
10647ae0e2c9SDimitry Andric     // cold relative to the block. When this is true, othe predecessors make up
10657ae0e2c9SDimitry Andric     // all of the hot entries into the block and thus alignment is likely to be
10667ae0e2c9SDimitry Andric     // important.
10677ae0e2c9SDimitry Andric     BranchProbability LayoutProb = MBPI->getEdgeProbability(LayoutPred, *BI);
10687ae0e2c9SDimitry Andric     BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
10697ae0e2c9SDimitry Andric     if (LayoutEdgeFreq <= (Freq * ColdProb))
10707ae0e2c9SDimitry Andric       (*BI)->setAlignment(Align);
1071cb4dff85SDimitry Andric   }
1072dff0c46cSDimitry Andric }
1073dff0c46cSDimitry Andric 
1074dff0c46cSDimitry Andric bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &F) {
1075dff0c46cSDimitry Andric   // Check for single-block functions and skip them.
1076dff0c46cSDimitry Andric   if (llvm::next(F.begin()) == F.end())
1077dff0c46cSDimitry Andric     return false;
1078dff0c46cSDimitry Andric 
1079dff0c46cSDimitry Andric   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1080dff0c46cSDimitry Andric   MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1081dff0c46cSDimitry Andric   MLI = &getAnalysis<MachineLoopInfo>();
1082dff0c46cSDimitry Andric   TII = F.getTarget().getInstrInfo();
1083dff0c46cSDimitry Andric   TLI = F.getTarget().getTargetLowering();
1084dff0c46cSDimitry Andric   assert(BlockToChain.empty());
1085dff0c46cSDimitry Andric 
1086dff0c46cSDimitry Andric   buildCFGChains(F);
1087dff0c46cSDimitry Andric 
1088dff0c46cSDimitry Andric   BlockToChain.clear();
1089dff0c46cSDimitry Andric   ChainAllocator.DestroyAll();
1090dff0c46cSDimitry Andric 
1091dff0c46cSDimitry Andric   // We always return true as we have no way to track whether the final order
1092dff0c46cSDimitry Andric   // differs from the original order.
1093dff0c46cSDimitry Andric   return true;
1094dff0c46cSDimitry Andric }
1095dff0c46cSDimitry Andric 
1096dff0c46cSDimitry Andric namespace {
1097dff0c46cSDimitry Andric /// \brief A pass to compute block placement statistics.
1098dff0c46cSDimitry Andric ///
1099dff0c46cSDimitry Andric /// A separate pass to compute interesting statistics for evaluating block
1100dff0c46cSDimitry Andric /// placement. This is separate from the actual placement pass so that they can
11017ae0e2c9SDimitry Andric /// be computed in the absence of any placement transformations or when using
1102dff0c46cSDimitry Andric /// alternative placement strategies.
1103dff0c46cSDimitry Andric class MachineBlockPlacementStats : public MachineFunctionPass {
1104dff0c46cSDimitry Andric   /// \brief A handle to the branch probability pass.
1105dff0c46cSDimitry Andric   const MachineBranchProbabilityInfo *MBPI;
1106dff0c46cSDimitry Andric 
1107dff0c46cSDimitry Andric   /// \brief A handle to the function-wide block frequency pass.
1108dff0c46cSDimitry Andric   const MachineBlockFrequencyInfo *MBFI;
1109dff0c46cSDimitry Andric 
1110dff0c46cSDimitry Andric public:
1111dff0c46cSDimitry Andric   static char ID; // Pass identification, replacement for typeid
1112dff0c46cSDimitry Andric   MachineBlockPlacementStats() : MachineFunctionPass(ID) {
1113dff0c46cSDimitry Andric     initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
1114dff0c46cSDimitry Andric   }
1115dff0c46cSDimitry Andric 
1116dff0c46cSDimitry Andric   bool runOnMachineFunction(MachineFunction &F);
1117dff0c46cSDimitry Andric 
1118dff0c46cSDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const {
1119dff0c46cSDimitry Andric     AU.addRequired<MachineBranchProbabilityInfo>();
1120dff0c46cSDimitry Andric     AU.addRequired<MachineBlockFrequencyInfo>();
1121dff0c46cSDimitry Andric     AU.setPreservesAll();
1122dff0c46cSDimitry Andric     MachineFunctionPass::getAnalysisUsage(AU);
1123dff0c46cSDimitry Andric   }
1124dff0c46cSDimitry Andric };
1125dff0c46cSDimitry Andric }
1126dff0c46cSDimitry Andric 
1127dff0c46cSDimitry Andric char MachineBlockPlacementStats::ID = 0;
1128dff0c46cSDimitry Andric char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
1129dff0c46cSDimitry Andric INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
1130dff0c46cSDimitry Andric                       "Basic Block Placement Stats", false, false)
1131dff0c46cSDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
1132dff0c46cSDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
1133dff0c46cSDimitry Andric INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
1134dff0c46cSDimitry Andric                     "Basic Block Placement Stats", false, false)
1135dff0c46cSDimitry Andric 
1136dff0c46cSDimitry Andric bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
1137dff0c46cSDimitry Andric   // Check for single-block functions and skip them.
1138dff0c46cSDimitry Andric   if (llvm::next(F.begin()) == F.end())
1139dff0c46cSDimitry Andric     return false;
1140dff0c46cSDimitry Andric 
1141dff0c46cSDimitry Andric   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1142dff0c46cSDimitry Andric   MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1143dff0c46cSDimitry Andric 
1144dff0c46cSDimitry Andric   for (MachineFunction::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1145dff0c46cSDimitry Andric     BlockFrequency BlockFreq = MBFI->getBlockFreq(I);
1146dff0c46cSDimitry Andric     Statistic &NumBranches = (I->succ_size() > 1) ? NumCondBranches
1147dff0c46cSDimitry Andric                                                   : NumUncondBranches;
1148dff0c46cSDimitry Andric     Statistic &BranchTakenFreq = (I->succ_size() > 1) ? CondBranchTakenFreq
1149dff0c46cSDimitry Andric                                                       : UncondBranchTakenFreq;
1150dff0c46cSDimitry Andric     for (MachineBasicBlock::succ_iterator SI = I->succ_begin(),
1151dff0c46cSDimitry Andric                                           SE = I->succ_end();
1152dff0c46cSDimitry Andric          SI != SE; ++SI) {
1153dff0c46cSDimitry Andric       // Skip if this successor is a fallthrough.
1154dff0c46cSDimitry Andric       if (I->isLayoutSuccessor(*SI))
1155dff0c46cSDimitry Andric         continue;
1156dff0c46cSDimitry Andric 
1157dff0c46cSDimitry Andric       BlockFrequency EdgeFreq = BlockFreq * MBPI->getEdgeProbability(I, *SI);
1158dff0c46cSDimitry Andric       ++NumBranches;
1159dff0c46cSDimitry Andric       BranchTakenFreq += EdgeFreq.getFrequency();
1160dff0c46cSDimitry Andric     }
1161dff0c46cSDimitry Andric   }
1162dff0c46cSDimitry Andric 
1163dff0c46cSDimitry Andric   return false;
1164dff0c46cSDimitry Andric }
1165dff0c46cSDimitry Andric 
1166