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