blob: 53a8779c10e78656faf1e4b413b91b36ce3177ce [file] [log] [blame]
Chandler Carruthdb350872011-10-21 06:46:38 +00001//===-- 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//
Chandler Carruth30713632011-10-23 09:18:45 +000010// This file implements basic block placement transformations using the CFG
11// structure and branch probability estimates.
Chandler Carruthdb350872011-10-21 06:46:38 +000012//
Chandler Carruth30713632011-10-23 09:18:45 +000013// 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.
Chandler Carruthdb350872011-10-21 06:46:38 +000025//
26//===----------------------------------------------------------------------===//
27
28#define DEBUG_TYPE "block-placement2"
Chandler Carruth4a85cc92011-10-21 08:57:37 +000029#include "llvm/CodeGen/MachineBasicBlock.h"
Chandler Carruthdb350872011-10-21 06:46:38 +000030#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
31#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
32#include "llvm/CodeGen/MachineFunction.h"
Chandler Carruthdb350872011-10-21 06:46:38 +000033#include "llvm/CodeGen/MachineFunctionPass.h"
Chandler Carruth4a85cc92011-10-21 08:57:37 +000034#include "llvm/CodeGen/MachineLoopInfo.h"
35#include "llvm/CodeGen/MachineModuleInfo.h"
36#include "llvm/CodeGen/Passes.h"
Chandler Carruthdb350872011-10-21 06:46:38 +000037#include "llvm/Support/Allocator.h"
Chandler Carruth30713632011-10-23 09:18:45 +000038#include "llvm/Support/Debug.h"
Chandler Carruthdb350872011-10-21 06:46:38 +000039#include "llvm/Support/ErrorHandling.h"
40#include "llvm/ADT/DenseMap.h"
Chandler Carruth30713632011-10-23 09:18:45 +000041#include "llvm/ADT/PostOrderIterator.h"
Chandler Carruthdb350872011-10-21 06:46:38 +000042#include "llvm/ADT/SCCIterator.h"
43#include "llvm/ADT/SmallPtrSet.h"
44#include "llvm/ADT/SmallVector.h"
45#include "llvm/ADT/Statistic.h"
46#include "llvm/Target/TargetInstrInfo.h"
Chandler Carruth4a85cc92011-10-21 08:57:37 +000047#include "llvm/Target/TargetLowering.h"
Chandler Carruthdb350872011-10-21 06:46:38 +000048#include <algorithm>
49using namespace llvm;
50
Chandler Carruth37efc9f2011-11-02 07:17:12 +000051STATISTIC(NumCondBranches, "Number of conditional branches");
52STATISTIC(NumUncondBranches, "Number of uncondittional branches");
53STATISTIC(CondBranchTakenFreq,
54 "Potential frequency of taking conditional branches");
55STATISTIC(UncondBranchTakenFreq,
56 "Potential frequency of taking unconditional branches");
57
Chandler Carruthdb350872011-10-21 06:46:38 +000058namespace {
59/// \brief A structure for storing a weighted edge.
60///
61/// This stores an edge and its weight, computed as the product of the
62/// frequency that the starting block is entered with the probability of
63/// a particular exit block.
64struct WeightedEdge {
65 BlockFrequency EdgeFrequency;
66 MachineBasicBlock *From, *To;
67
68 bool operator<(const WeightedEdge &RHS) const {
69 return EdgeFrequency < RHS.EdgeFrequency;
70 }
71};
72}
73
74namespace {
Chandler Carruth30713632011-10-23 09:18:45 +000075class BlockChain;
Chandler Carruthdb350872011-10-21 06:46:38 +000076/// \brief Type for our function-wide basic block -> block chain mapping.
77typedef DenseMap<MachineBasicBlock *, BlockChain *> BlockToChainMapType;
78}
79
80namespace {
81/// \brief A chain of blocks which will be laid out contiguously.
82///
83/// This is the datastructure representing a chain of consecutive blocks that
84/// are profitable to layout together in order to maximize fallthrough
85/// probabilities. We also can use a block chain to represent a sequence of
86/// basic blocks which have some external (correctness) requirement for
87/// sequential layout.
88///
89/// Eventually, the block chains will form a directed graph over the function.
90/// We provide an SCC-supporting-iterator in order to quicky build and walk the
91/// SCCs of block chains within a function.
92///
93/// The block chains also have support for calculating and caching probability
94/// information related to the chain itself versus other chains. This is used
95/// for ranking during the final layout of block chains.
Chandler Carruth30713632011-10-23 09:18:45 +000096class BlockChain {
97 /// \brief The sequence of blocks belonging to this chain.
Chandler Carruthdb350872011-10-21 06:46:38 +000098 ///
Chandler Carruth30713632011-10-23 09:18:45 +000099 /// This is the sequence of blocks for a particular chain. These will be laid
100 /// out in-order within the function.
101 SmallVector<MachineBasicBlock *, 4> Blocks;
Chandler Carruthdb350872011-10-21 06:46:38 +0000102
103 /// \brief A handle to the function-wide basic block to block chain mapping.
104 ///
105 /// This is retained in each block chain to simplify the computation of child
106 /// block chains for SCC-formation and iteration. We store the edges to child
107 /// basic blocks, and map them back to their associated chains using this
108 /// structure.
109 BlockToChainMapType &BlockToChain;
110
Chandler Carruth30713632011-10-23 09:18:45 +0000111public:
Chandler Carruthdb350872011-10-21 06:46:38 +0000112 /// \brief Construct a new BlockChain.
113 ///
114 /// This builds a new block chain representing a single basic block in the
115 /// function. It also registers itself as the chain that block participates
116 /// in with the BlockToChain mapping.
117 BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
Chandler Carruth30713632011-10-23 09:18:45 +0000118 : Blocks(1, BB), BlockToChain(BlockToChain) {
Chandler Carruthdb350872011-10-21 06:46:38 +0000119 assert(BB && "Cannot create a chain with a null basic block");
120 BlockToChain[BB] = this;
121 }
122
Chandler Carruth30713632011-10-23 09:18:45 +0000123 /// \brief Iterator over blocks within the chain.
124 typedef SmallVectorImpl<MachineBasicBlock *>::const_iterator iterator;
125
126 /// \brief Beginning of blocks within the chain.
127 iterator begin() const { return Blocks.begin(); }
128
129 /// \brief End of blocks within the chain.
130 iterator end() const { return Blocks.end(); }
131
132 /// \brief Merge a block chain into this one.
Chandler Carruthdb350872011-10-21 06:46:38 +0000133 ///
134 /// This routine merges a block chain into this one. It takes care of forming
135 /// a contiguous sequence of basic blocks, updating the edge list, and
136 /// updating the block -> chain mapping. It does not free or tear down the
137 /// old chain, but the old chain's block list is no longer valid.
Chandler Carruth30713632011-10-23 09:18:45 +0000138 void merge(MachineBasicBlock *BB, BlockChain *Chain) {
139 assert(BB);
140 assert(!Blocks.empty());
141 assert(Blocks.back()->isSuccessor(BB));
Chandler Carruthdb350872011-10-21 06:46:38 +0000142
Chandler Carruth30713632011-10-23 09:18:45 +0000143 // Fast path in case we don't have a chain already.
144 if (!Chain) {
145 assert(!BlockToChain[BB]);
146 Blocks.push_back(BB);
147 BlockToChain[BB] = this;
148 return;
Chandler Carruthdb350872011-10-21 06:46:38 +0000149 }
150
Chandler Carruth30713632011-10-23 09:18:45 +0000151 assert(BB == *Chain->begin());
152 assert(Chain->begin() != Chain->end());
Chandler Carruthdb350872011-10-21 06:46:38 +0000153
Chandler Carruth30713632011-10-23 09:18:45 +0000154 // Update the incoming blocks to point to this chain, and add them to the
155 // chain structure.
156 for (BlockChain::iterator BI = Chain->begin(), BE = Chain->end();
157 BI != BE; ++BI) {
158 Blocks.push_back(*BI);
159 assert(BlockToChain[*BI] == Chain && "Incoming blocks not in chain");
160 BlockToChain[*BI] = this;
161 }
Chandler Carruthdb350872011-10-21 06:46:38 +0000162 }
163};
164}
165
166namespace {
167class MachineBlockPlacement : public MachineFunctionPass {
Chandler Carruth30713632011-10-23 09:18:45 +0000168 /// \brief A typedef for a block filter set.
169 typedef SmallPtrSet<MachineBasicBlock *, 16> BlockFilterSet;
170
Chandler Carruthdb350872011-10-21 06:46:38 +0000171 /// \brief A handle to the branch probability pass.
172 const MachineBranchProbabilityInfo *MBPI;
173
174 /// \brief A handle to the function-wide block frequency pass.
175 const MachineBlockFrequencyInfo *MBFI;
176
Chandler Carruth4a85cc92011-10-21 08:57:37 +0000177 /// \brief A handle to the loop info.
178 const MachineLoopInfo *MLI;
179
Chandler Carruthdb350872011-10-21 06:46:38 +0000180 /// \brief A handle to the target's instruction info.
181 const TargetInstrInfo *TII;
182
Chandler Carruth4a85cc92011-10-21 08:57:37 +0000183 /// \brief A handle to the target's lowering info.
184 const TargetLowering *TLI;
185
Chandler Carruthdb350872011-10-21 06:46:38 +0000186 /// \brief Allocator and owner of BlockChain structures.
187 ///
188 /// We build BlockChains lazily by merging together high probability BB
189 /// sequences acording to the "Algo2" in the paper mentioned at the top of
190 /// the file. To reduce malloc traffic, we allocate them using this slab-like
191 /// allocator, and destroy them after the pass completes.
192 SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
193
194 /// \brief Function wide BasicBlock to BlockChain mapping.
195 ///
196 /// This mapping allows efficiently moving from any given basic block to the
197 /// BlockChain it participates in, if any. We use it to, among other things,
198 /// allow implicitly defining edges between chains as the existing edges
199 /// between basic blocks.
200 DenseMap<MachineBasicBlock *, BlockChain *> BlockToChain;
201
Chandler Carruthdb350872011-10-21 06:46:38 +0000202 BlockChain *CreateChain(MachineBasicBlock *BB);
Chandler Carruth30713632011-10-23 09:18:45 +0000203 void mergeSuccessor(MachineBasicBlock *BB, BlockChain *Chain,
204 BlockFilterSet *Filter = 0);
205 void buildLoopChains(MachineFunction &F, MachineLoop &L);
206 void buildCFGChains(MachineFunction &F);
207 void placeChainsTopologically(MachineFunction &F);
Chandler Carruth4a85cc92011-10-21 08:57:37 +0000208 void AlignLoops(MachineFunction &F);
Chandler Carruthdb350872011-10-21 06:46:38 +0000209
210public:
211 static char ID; // Pass identification, replacement for typeid
212 MachineBlockPlacement() : MachineFunctionPass(ID) {
213 initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
214 }
215
216 bool runOnMachineFunction(MachineFunction &F);
217
218 void getAnalysisUsage(AnalysisUsage &AU) const {
219 AU.addRequired<MachineBranchProbabilityInfo>();
220 AU.addRequired<MachineBlockFrequencyInfo>();
Chandler Carruth4a85cc92011-10-21 08:57:37 +0000221 AU.addRequired<MachineLoopInfo>();
Chandler Carruthdb350872011-10-21 06:46:38 +0000222 MachineFunctionPass::getAnalysisUsage(AU);
223 }
224
225 const char *getPassName() const { return "Block Placement"; }
226};
227}
228
229char MachineBlockPlacement::ID = 0;
230INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement2",
231 "Branch Probability Basic Block Placement", false, false)
232INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
233INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
Chandler Carruth4a85cc92011-10-21 08:57:37 +0000234INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
Chandler Carruthdb350872011-10-21 06:46:38 +0000235INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement2",
236 "Branch Probability Basic Block Placement", false, false)
237
238FunctionPass *llvm::createMachineBlockPlacementPass() {
239 return new MachineBlockPlacement();
240}
241
Chandler Carruth30713632011-10-23 09:18:45 +0000242#ifndef NDEBUG
243/// \brief Helper to print the name of a MBB.
244///
245/// Only used by debug logging.
246static std::string getBlockName(MachineBasicBlock *BB) {
247 std::string Result;
248 raw_string_ostream OS(Result);
249 OS << "BB#" << BB->getNumber()
250 << " (derived from LLVM BB '" << BB->getName() << "')";
251 OS.flush();
252 return Result;
Chandler Carruthdb350872011-10-21 06:46:38 +0000253}
254
Chandler Carruth30713632011-10-23 09:18:45 +0000255/// \brief Helper to print the number of a MBB.
256///
257/// Only used by debug logging.
258static std::string getBlockNum(MachineBasicBlock *BB) {
259 std::string Result;
260 raw_string_ostream OS(Result);
261 OS << "BB#" << BB->getNumber();
262 OS.flush();
263 return Result;
264}
265#endif
266
Chandler Carruthdb350872011-10-21 06:46:38 +0000267/// \brief Helper to create a new chain for a single BB.
268///
269/// Takes care of growing the Chains, setting up the BlockChain object, and any
270/// debug checking logic.
271/// \returns A pointer to the new BlockChain.
272BlockChain *MachineBlockPlacement::CreateChain(MachineBasicBlock *BB) {
273 BlockChain *Chain =
274 new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
Chandler Carruthdb350872011-10-21 06:46:38 +0000275 return Chain;
276}
277
Chandler Carruth30713632011-10-23 09:18:45 +0000278/// \brief Merge a chain with any viable successor.
Chandler Carruthdb350872011-10-21 06:46:38 +0000279///
Chandler Carruth30713632011-10-23 09:18:45 +0000280/// This routine walks the predecessors of the current block, looking for
281/// viable merge candidates. It has strict rules it uses to determine when
282/// a predecessor can be merged with the current block, which center around
283/// preserving the CFG structure. It performs the merge if any viable candidate
284/// is found.
285void MachineBlockPlacement::mergeSuccessor(MachineBasicBlock *BB,
286 BlockChain *Chain,
287 BlockFilterSet *Filter) {
288 assert(BB);
289 assert(Chain);
Chandler Carruthdb350872011-10-21 06:46:38 +0000290
Chandler Carruth30713632011-10-23 09:18:45 +0000291 // If this block is not at the end of its chain, it cannot merge with any
292 // other chain.
293 if (Chain && *llvm::prior(Chain->end()) != BB)
294 return;
295
296 // Walk through the successors looking for the highest probability edge.
Chandler Carruth30713632011-10-23 09:18:45 +0000297 MachineBasicBlock *Successor = 0;
Chandler Carruth66d847c2011-10-23 20:10:34 +0000298 BranchProbability BestProb = BranchProbability::getZero();
Chandler Carruth30713632011-10-23 09:18:45 +0000299 DEBUG(dbgs() << "Attempting merge from: " << getBlockName(BB) << "\n");
300 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
301 SE = BB->succ_end();
302 SI != SE; ++SI) {
303 if (BB == *SI || (Filter && !Filter->count(*SI)))
304 continue;
305
Chandler Carruth66d847c2011-10-23 20:10:34 +0000306 BranchProbability SuccProb = MBPI->getEdgeProbability(BB, *SI);
307 DEBUG(dbgs() << " " << getBlockName(*SI) << " -> " << SuccProb << "\n");
308 if (!Successor || SuccProb > BestProb || (!(SuccProb < BestProb) &&
Chandler Carruth30713632011-10-23 09:18:45 +0000309 BB->isLayoutSuccessor(*SI))) {
310 Successor = *SI;
Chandler Carruth66d847c2011-10-23 20:10:34 +0000311 BestProb = SuccProb;
Chandler Carruthdb350872011-10-21 06:46:38 +0000312 }
313 }
Chandler Carruth30713632011-10-23 09:18:45 +0000314 if (!Successor)
315 return;
316
317 // Grab a chain if it exists already for this successor and make sure the
318 // successor is at the start of the chain as we can't merge mid-chain. Also,
319 // if the successor chain is the same as our chain, we're already merged.
320 BlockChain *SuccChain = BlockToChain[Successor];
321 if (SuccChain && (SuccChain == Chain || Successor != *SuccChain->begin()))
322 return;
323
324 // We only merge chains across a CFG merge when the desired merge path is
325 // significantly hotter than the incoming edge. We define a hot edge more
326 // strictly than the BranchProbabilityInfo does, as the two predecessor
327 // blocks may have dramatically different incoming probabilities we need to
328 // account for. Therefor we use the "global" edge weight which is the
329 // branch's probability times the block frequency of the predecessor.
330 BlockFrequency MergeWeight = MBFI->getBlockFreq(BB);
331 MergeWeight *= MBPI->getEdgeProbability(BB, Successor);
332 // We only want to consider breaking the CFG when the merge weight is much
333 // higher (80% vs. 20%), so multiply it by 1/4. This will require the merged
334 // edge to be 4x more likely before we disrupt the CFG. This number matches
335 // the definition of "hot" in BranchProbabilityAnalysis (80% vs. 20%).
336 MergeWeight *= BranchProbability(1, 4);
337 for (MachineBasicBlock::pred_iterator PI = Successor->pred_begin(),
338 PE = Successor->pred_end();
339 PI != PE; ++PI) {
340 if (BB == *PI || Successor == *PI) continue;
341 BlockFrequency PredWeight = MBFI->getBlockFreq(*PI);
342 PredWeight *= MBPI->getEdgeProbability(*PI, Successor);
343
344 // Return on the first predecessor we find which outstrips our merge weight.
345 if (MergeWeight < PredWeight)
346 return;
347 DEBUG(dbgs() << "Breaking CFG edge!\n"
348 << " Edge from " << getBlockNum(BB) << " to "
349 << getBlockNum(Successor) << ": " << MergeWeight << "\n"
350 << " vs. " << getBlockNum(BB) << " to "
351 << getBlockNum(*PI) << ": " << PredWeight << "\n");
352 }
353
354 DEBUG(dbgs() << "Merging from " << getBlockNum(BB) << " to "
355 << getBlockNum(Successor) << "\n");
356 Chain->merge(Successor, SuccChain);
Chandler Carruthdb350872011-10-21 06:46:38 +0000357}
358
Chandler Carruth30713632011-10-23 09:18:45 +0000359/// \brief Forms basic block chains from the natural loop structures.
Chandler Carruthdb350872011-10-21 06:46:38 +0000360///
Chandler Carruth30713632011-10-23 09:18:45 +0000361/// These chains are designed to preserve the existing *structure* of the code
362/// as much as possible. We can then stitch the chains together in a way which
363/// both preserves the topological structure and minimizes taken conditional
364/// branches.
365void MachineBlockPlacement::buildLoopChains(MachineFunction &F, MachineLoop &L) {
366 // First recurse through any nested loops, building chains for those inner
367 // loops.
368 for (MachineLoop::iterator LI = L.begin(), LE = L.end(); LI != LE; ++LI)
369 buildLoopChains(F, **LI);
Chandler Carruthdb350872011-10-21 06:46:38 +0000370
Chandler Carruth30713632011-10-23 09:18:45 +0000371 SmallPtrSet<MachineBasicBlock *, 16> LoopBlockSet(L.block_begin(),
372 L.block_end());
Chandler Carruthdb350872011-10-21 06:46:38 +0000373
Chandler Carruth30713632011-10-23 09:18:45 +0000374 // Begin building up a set of chains of blocks within this loop which should
375 // remain contiguous. Some of the blocks already belong to a chain which
376 // represents an inner loop.
377 for (MachineLoop::block_iterator BI = L.block_begin(), BE = L.block_end();
378 BI != BE; ++BI) {
379 MachineBasicBlock *BB = *BI;
380 BlockChain *Chain = BlockToChain[BB];
381 if (!Chain) Chain = CreateChain(BB);
382 mergeSuccessor(BB, Chain, &LoopBlockSet);
Chandler Carruthdb350872011-10-21 06:46:38 +0000383 }
384}
385
Chandler Carruth30713632011-10-23 09:18:45 +0000386void MachineBlockPlacement::buildCFGChains(MachineFunction &F) {
387 // First build any loop-based chains.
388 for (MachineLoopInfo::iterator LI = MLI->begin(), LE = MLI->end(); LI != LE;
389 ++LI)
390 buildLoopChains(F, **LI);
391
392 // Now walk the blocks of the function forming chains where they don't
393 // violate any CFG structure.
394 for (MachineFunction::iterator BI = F.begin(), BE = F.end();
395 BI != BE; ++BI) {
396 MachineBasicBlock *BB = BI;
397 BlockChain *Chain = BlockToChain[BB];
398 if (!Chain) Chain = CreateChain(BB);
399 mergeSuccessor(BB, Chain);
400 }
401}
402
403void MachineBlockPlacement::placeChainsTopologically(MachineFunction &F) {
Chandler Carruthdb350872011-10-21 06:46:38 +0000404 MachineBasicBlock *EntryB = &F.front();
Chandler Carruthe4617c02011-10-24 16:51:55 +0000405 assert(BlockToChain[EntryB] && "Missing chain for entry block");
406 assert(*BlockToChain[EntryB]->begin() == EntryB &&
Chandler Carruthdb350872011-10-21 06:46:38 +0000407 "Entry block is not the head of the entry block chain");
408
Chandler Carruth30713632011-10-23 09:18:45 +0000409 // Walk the blocks in RPO, and insert each block for a chain in order the
410 // first time we see that chain.
Chandler Carruthdb350872011-10-21 06:46:38 +0000411 MachineFunction::iterator InsertPos = F.begin();
Chandler Carruth30713632011-10-23 09:18:45 +0000412 SmallPtrSet<BlockChain *, 16> VisitedChains;
413 ReversePostOrderTraversal<MachineBasicBlock *> RPOT(EntryB);
414 typedef ReversePostOrderTraversal<MachineBasicBlock *>::rpo_iterator
415 rpo_iterator;
416 for (rpo_iterator I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
417 BlockChain *Chain = BlockToChain[*I];
418 assert(Chain);
419 if(!VisitedChains.insert(Chain))
420 continue;
421 for (BlockChain::iterator BI = Chain->begin(), BE = Chain->end(); BI != BE;
422 ++BI) {
423 DEBUG(dbgs() << (BI == Chain->begin() ? "Placing chain "
424 : " ... ")
425 << getBlockName(*BI) << "\n");
426 if (InsertPos != MachineFunction::iterator(*BI))
427 F.splice(InsertPos, *BI);
428 else
429 ++InsertPos;
430 }
Chandler Carruthdb350872011-10-21 06:46:38 +0000431 }
432
Chandler Carruthdb350872011-10-21 06:46:38 +0000433 // Now that every block is in its final position, update all of the
434 // terminators.
435 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
436 for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
437 // FIXME: It would be awesome of updateTerminator would just return rather
438 // than assert when the branch cannot be analyzed in order to remove this
439 // boiler plate.
440 Cond.clear();
441 MachineBasicBlock *TBB = 0, *FBB = 0; // For AnalyzeBranch.
442 if (!TII->AnalyzeBranch(*FI, TBB, FBB, Cond))
443 FI->updateTerminator();
444 }
445}
446
Chandler Carruth4a85cc92011-10-21 08:57:37 +0000447/// \brief Recursive helper to align a loop and any nested loops.
448static void AlignLoop(MachineFunction &F, MachineLoop *L, unsigned Align) {
449 // Recurse through nested loops.
450 for (MachineLoop::iterator I = L->begin(), E = L->end(); I != E; ++I)
451 AlignLoop(F, *I, Align);
452
453 L->getTopBlock()->setAlignment(Align);
454}
455
456/// \brief Align loop headers to target preferred alignments.
457void MachineBlockPlacement::AlignLoops(MachineFunction &F) {
458 if (F.getFunction()->hasFnAttr(Attribute::OptimizeForSize))
459 return;
460
461 unsigned Align = TLI->getPrefLoopAlignment();
462 if (!Align)
463 return; // Don't care about loop alignment.
464
465 for (MachineLoopInfo::iterator I = MLI->begin(), E = MLI->end(); I != E; ++I)
466 AlignLoop(F, *I, Align);
467}
468
Chandler Carruthdb350872011-10-21 06:46:38 +0000469bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &F) {
470 // Check for single-block functions and skip them.
471 if (llvm::next(F.begin()) == F.end())
472 return false;
473
474 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
475 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
Chandler Carruth4a85cc92011-10-21 08:57:37 +0000476 MLI = &getAnalysis<MachineLoopInfo>();
Chandler Carruthdb350872011-10-21 06:46:38 +0000477 TII = F.getTarget().getInstrInfo();
Chandler Carruth4a85cc92011-10-21 08:57:37 +0000478 TLI = F.getTarget().getTargetLowering();
Chandler Carruthdb350872011-10-21 06:46:38 +0000479 assert(BlockToChain.empty());
Chandler Carruthdb350872011-10-21 06:46:38 +0000480
Chandler Carruth30713632011-10-23 09:18:45 +0000481 buildCFGChains(F);
482 placeChainsTopologically(F);
Chandler Carruth4a85cc92011-10-21 08:57:37 +0000483 AlignLoops(F);
Chandler Carruthdb350872011-10-21 06:46:38 +0000484
Chandler Carruthdb350872011-10-21 06:46:38 +0000485 BlockToChain.clear();
Chandler Carruthdb350872011-10-21 06:46:38 +0000486
487 // We always return true as we have no way to track whether the final order
488 // differs from the original order.
489 return true;
490}
Chandler Carruth37efc9f2011-11-02 07:17:12 +0000491
492namespace {
493/// \brief A pass to compute block placement statistics.
494///
495/// A separate pass to compute interesting statistics for evaluating block
496/// placement. This is separate from the actual placement pass so that they can
497/// be computed in the absense of any placement transformations or when using
498/// alternative placement strategies.
499class MachineBlockPlacementStats : public MachineFunctionPass {
500 /// \brief A handle to the branch probability pass.
501 const MachineBranchProbabilityInfo *MBPI;
502
503 /// \brief A handle to the function-wide block frequency pass.
504 const MachineBlockFrequencyInfo *MBFI;
505
506public:
507 static char ID; // Pass identification, replacement for typeid
508 MachineBlockPlacementStats() : MachineFunctionPass(ID) {
509 initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
510 }
511
512 bool runOnMachineFunction(MachineFunction &F);
513
514 void getAnalysisUsage(AnalysisUsage &AU) const {
515 AU.addRequired<MachineBranchProbabilityInfo>();
516 AU.addRequired<MachineBlockFrequencyInfo>();
517 AU.setPreservesAll();
518 MachineFunctionPass::getAnalysisUsage(AU);
519 }
520
521 const char *getPassName() const { return "Block Placement Stats"; }
522};
523}
524
525char MachineBlockPlacementStats::ID = 0;
526INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
527 "Basic Block Placement Stats", false, false)
528INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
529INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
530INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
531 "Basic Block Placement Stats", false, false)
532
533FunctionPass *llvm::createMachineBlockPlacementStatsPass() {
534 return new MachineBlockPlacementStats();
535}
536
537bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
538 // Check for single-block functions and skip them.
539 if (llvm::next(F.begin()) == F.end())
540 return false;
541
542 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
543 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
544
545 for (MachineFunction::iterator I = F.begin(), E = F.end(); I != E; ++I) {
546 BlockFrequency BlockFreq = MBFI->getBlockFreq(I);
547 Statistic &NumBranches = (I->succ_size() > 1) ? NumCondBranches
548 : NumUncondBranches;
549 Statistic &BranchTakenFreq = (I->succ_size() > 1) ? CondBranchTakenFreq
550 : UncondBranchTakenFreq;
551 for (MachineBasicBlock::succ_iterator SI = I->succ_begin(),
552 SE = I->succ_end();
553 SI != SE; ++SI) {
554 // Skip if this successor is a fallthrough.
555 if (I->isLayoutSuccessor(*SI))
556 continue;
557
558 BlockFrequency EdgeFreq = BlockFreq * MBPI->getEdgeProbability(I, *SI);
559 ++NumBranches;
560 BranchTakenFreq += EdgeFreq.getFrequency();
561 }
562 }
563
564 return false;
565}
566