1 //===- PRE.cpp - Partial Redundancy Elimination ---------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the well-known Partial Redundancy Elimination
11 // optimization, using an SSA formulation based on e-paths. See this paper for
14 // E-path_PRE: partial redundancy elimination made easy
15 // By: Dhananjay M. Dhamdhere In: ACM SIGPLAN Notices. Vol 37, #8, 2002
16 // http://doi.acm.org/10.1145/596992.597004
18 // This file actually implements a sparse version of the algorithm, using SSA
19 // and CFG properties instead of bit-vectors.
21 //===----------------------------------------------------------------------===//
23 #include "llvm/Pass.h"
24 #include "llvm/Function.h"
25 #include "llvm/Type.h"
26 #include "llvm/iPHINode.h"
27 #include "llvm/iMemory.h"
28 #include "llvm/Support/CFG.h"
29 #include "llvm/Analysis/Dominators.h"
30 #include "llvm/Analysis/PostDominators.h"
31 #include "llvm/Analysis/ValueNumbering.h"
32 #include "llvm/Transforms/Scalar.h"
33 #include "Support/Debug.h"
34 #include "Support/DepthFirstIterator.h"
35 #include "Support/PostOrderIterator.h"
36 #include "Support/Statistic.h"
37 #include "Support/hash_set"
42 Statistic<> NumExprsEliminated("pre", "Number of expressions constantified");
43 Statistic<> NumRedundant ("pre", "Number of redundant exprs eliminated");
44 static Statistic<> NumInserted ("pre", "Number of expressions inserted");
46 struct PRE : public FunctionPass {
47 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
48 AU.addRequiredID(BreakCriticalEdgesID); // No critical edges for now!
49 AU.addRequired<PostDominatorTree>();
50 AU.addRequired<PostDominanceFrontier>();
51 AU.addRequired<DominatorSet>();
52 AU.addRequired<DominatorTree>();
53 AU.addRequired<DominanceFrontier>();
54 AU.addRequired<ValueNumbering>();
56 virtual bool runOnFunction(Function &F);
59 // Block information - Map basic blocks in a function back and forth to
61 std::vector<BasicBlock*> BlockMapping;
62 hash_map<BasicBlock*, unsigned> BlockNumbering;
64 // ProcessedExpressions - Keep track of which expressions have already been
66 hash_set<Instruction*> ProcessedExpressions;
68 // Provide access to the various analyses used...
70 DominatorTree *DT; PostDominatorTree *PDT;
71 DominanceFrontier *DF; PostDominanceFrontier *PDF;
74 // AvailableBlocks - Contain a mapping of blocks with available expression
75 // values to the expression value itself. This can be used as an efficient
76 // way to find out if the expression is available in the block, and if so,
77 // which version to use. This map is only used while processing a single
80 typedef hash_map<BasicBlock*, Instruction*> AvailableBlocksTy;
81 AvailableBlocksTy AvailableBlocks;
83 bool ProcessBlock(BasicBlock *BB);
85 // Anticipatibility calculation...
86 void MarkPostDominatingBlocksAnticipatible(PostDominatorTree::Node *N,
87 std::vector<char> &AntBlocks,
88 Instruction *Occurrence);
89 void CalculateAnticipatiblityForOccurrence(unsigned BlockNo,
90 std::vector<char> &AntBlocks,
91 Instruction *Occurrence);
92 void CalculateAnticipatibleBlocks(const std::map<unsigned, Instruction*> &D,
93 std::vector<char> &AnticipatibleBlocks);
95 // PRE for an expression
96 void MarkOccurrenceAvailableInAllDominatedBlocks(Instruction *Occurrence,
97 BasicBlock *StartBlock);
98 void ReplaceDominatedAvailableOccurrencesWith(Instruction *NewOcc,
99 DominatorTree::Node *N);
100 bool ProcessExpression(Instruction *I);
103 RegisterOpt<PRE> Z("pre", "Partial Redundancy Elimination");
107 bool PRE::runOnFunction(Function &F) {
108 VN = &getAnalysis<ValueNumbering>();
109 DS = &getAnalysis<DominatorSet>();
110 DT = &getAnalysis<DominatorTree>();
111 DF = &getAnalysis<DominanceFrontier>();
112 PDT = &getAnalysis<PostDominatorTree>();
113 PDF = &getAnalysis<PostDominanceFrontier>();
115 DEBUG(std::cerr << "\n*** Running PRE on func '" << F.getName() << "'...\n");
117 // Number the basic blocks based on a reverse post-order traversal of the CFG
118 // so that all predecessors of a block (ignoring back edges) are visited
119 // before a block is visited.
121 BlockMapping.reserve(F.size());
123 ReversePostOrderTraversal<Function*> RPOT(&F);
124 DEBUG(std::cerr << "Block order: ");
125 for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
126 E = RPOT.end(); I != E; ++I) {
127 // Keep track of mapping...
129 BlockNumbering.insert(std::make_pair(BB, BlockMapping.size()));
130 BlockMapping.push_back(BB);
131 DEBUG(std::cerr << BB->getName() << " ");
133 DEBUG(std::cerr << "\n");
136 // Traverse the current function depth-first in dominator-tree order. This
137 // ensures that we see all definitions before their uses (except for PHI
138 // nodes), allowing us to hoist dependent expressions correctly.
139 bool Changed = false;
140 for (unsigned i = 0, e = BlockMapping.size(); i != e; ++i)
141 Changed |= ProcessBlock(BlockMapping[i]);
144 BlockMapping.clear();
145 BlockNumbering.clear();
146 ProcessedExpressions.clear();
151 // ProcessBlock - Process any expressions first seen in this block...
153 bool PRE::ProcessBlock(BasicBlock *BB) {
154 bool Changed = false;
156 // PRE expressions first defined in this block...
157 Instruction *PrevInst = 0;
158 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); )
159 if (ProcessExpression(I)) {
160 // The current instruction may have been deleted, make sure to back up to
174 void PRE::MarkPostDominatingBlocksAnticipatible(PostDominatorTree::Node *N,
175 std::vector<char> &AntBlocks,
176 Instruction *Occurrence) {
177 unsigned BlockNo = BlockNumbering[N->getBlock()];
179 if (AntBlocks[BlockNo]) return; // Already known to be anticipatible??
181 // Check to see if any of the operands are defined in this block, if so, the
182 // entry of this block does not anticipate the expression. This computes
184 for (unsigned i = 0, e = Occurrence->getNumOperands(); i != e; ++i)
185 if (Instruction *I = dyn_cast<Instruction>(Occurrence->getOperand(i)))
186 if (I->getParent() == N->getBlock()) // Operand is defined in this block!
189 if (isa<LoadInst>(Occurrence))
190 return; // FIXME: compute transparency for load instructions using AA
192 // Insert block into AntBlocks list...
193 AntBlocks[BlockNo] = true;
195 for (PostDominatorTree::Node::iterator I = N->begin(), E = N->end(); I != E;
197 MarkPostDominatingBlocksAnticipatible(*I, AntBlocks, Occurrence);
200 void PRE::CalculateAnticipatiblityForOccurrence(unsigned BlockNo,
201 std::vector<char> &AntBlocks,
202 Instruction *Occurrence) {
203 if (AntBlocks[BlockNo]) return; // Block already anticipatible!
205 BasicBlock *BB = BlockMapping[BlockNo];
207 // For each occurrence, mark all post-dominated blocks as anticipatible...
208 MarkPostDominatingBlocksAnticipatible(PDT->getNode(BB), AntBlocks,
211 // Next, mark any blocks in the post-dominance frontier as anticipatible iff
212 // all successors are anticipatible.
214 PostDominanceFrontier::iterator PDFI = PDF->find(BB);
215 if (PDFI != DF->end())
216 for (std::set<BasicBlock*>::iterator DI = PDFI->second.begin();
217 DI != PDFI->second.end(); ++DI) {
218 BasicBlock *PDFBlock = *DI;
219 bool AllSuccessorsAnticipatible = true;
220 for (succ_iterator SI = succ_begin(PDFBlock), SE = succ_end(PDFBlock);
222 if (!AntBlocks[BlockNumbering[*SI]]) {
223 AllSuccessorsAnticipatible = false;
227 if (AllSuccessorsAnticipatible)
228 CalculateAnticipatiblityForOccurrence(BlockNumbering[PDFBlock],
229 AntBlocks, Occurrence);
234 void PRE::CalculateAnticipatibleBlocks(const std::map<unsigned,
236 std::vector<char> &AntBlocks) {
237 // Initialize to zeros...
238 AntBlocks.resize(BlockMapping.size());
240 // Loop over all of the expressions...
241 for (std::map<unsigned, Instruction*>::const_iterator I = Defs.begin(),
242 E = Defs.end(); I != E; ++I)
243 CalculateAnticipatiblityForOccurrence(I->first, AntBlocks, I->second);
246 /// MarkOccurrenceAvailableInAllDominatedBlocks - Add entries to AvailableBlocks
247 /// for all nodes dominated by the occurrence to indicate that it is now the
248 /// available occurrence to use in any of these blocks.
250 void PRE::MarkOccurrenceAvailableInAllDominatedBlocks(Instruction *Occurrence,
252 // FIXME: There are much more efficient ways to get the blocks dominated
253 // by a block. Use them.
255 DominatorTree::Node *N = DT->getNode(Occurrence->getParent());
256 for (df_iterator<DominatorTree::Node*> DI = df_begin(N), E = df_end(N);
258 AvailableBlocks[(*DI)->getBlock()] = Occurrence;
261 /// ReplaceDominatedAvailableOccurrencesWith - This loops over the region
262 /// dominated by N, replacing any available expressions with NewOcc.
263 void PRE::ReplaceDominatedAvailableOccurrencesWith(Instruction *NewOcc,
264 DominatorTree::Node *N) {
265 BasicBlock *BB = N->getBlock();
266 Instruction *&ExistingAvailableVal = AvailableBlocks[BB];
268 // If there isn't a definition already active in this node, make this the new
269 // active definition...
270 if (ExistingAvailableVal == 0) {
271 ExistingAvailableVal = NewOcc;
273 for (DominatorTree::Node::iterator I = N->begin(), E = N->end(); I != E;++I)
274 ReplaceDominatedAvailableOccurrencesWith(NewOcc, *I);
276 // If there is already an active definition in this block, replace it with
277 // NewOcc, and force it into all dominated blocks.
278 DEBUG(std::cerr << " Replacing dominated occ %"
279 << ExistingAvailableVal->getName() << " with %" << NewOcc->getName()
281 assert(ExistingAvailableVal != NewOcc && "NewOcc already inserted??");
282 ExistingAvailableVal->replaceAllUsesWith(NewOcc);
285 assert(ExistingAvailableVal->getParent() == BB &&
286 "OldOcc not defined in current block?");
287 BB->getInstList().erase(ExistingAvailableVal);
289 // Mark NewOCC as the Available expression in all blocks dominated by BB
290 for (df_iterator<DominatorTree::Node*> DI = df_begin(N), E = df_end(N);
292 AvailableBlocks[(*DI)->getBlock()] = NewOcc;
297 /// ProcessExpression - Given an expression (instruction) process the
298 /// instruction to remove any partial redundancies induced by equivalent
299 /// computations. Note that we only need to PRE each expression once, so we
300 /// keep track of whether an expression has been PRE'd already, and don't PRE an
301 /// expression again. Expressions may be seen multiple times because process
302 /// the entire equivalence class at once, which may leave expressions later in
303 /// the control path.
305 bool PRE::ProcessExpression(Instruction *Expr) {
306 if (Expr->mayWriteToMemory() || Expr->getType() == Type::VoidTy ||
308 return false; // Cannot move expression
309 if (ProcessedExpressions.count(Expr)) return false; // Already processed.
311 // Ok, this is the first time we have seen the expression. Build a set of
312 // equivalent expressions using SSA def/use information. We consider
313 // expressions to be equivalent if they are the same opcode and have
314 // equivalent operands. As a special case for SSA, values produced by PHI
315 // nodes are considered to be equivalent to all of their operands.
317 std::vector<Value*> Values;
318 VN->getEqualNumberNodes(Expr, Values);
321 // FIXME: This should handle PHI nodes correctly. To do this, we need to
322 // consider expressions of the following form equivalent to this set of
325 // If an operand is a PHI node, add any occurrences of the expression with the
326 // PHI operand replaced with the PHI node operands. This is only valid if the
327 // PHI operand occurrences exist in blocks post-dominated by the incoming edge
331 // We have to be careful to handle expression definitions which dominated by
332 // other expressions. These can be directly eliminated in favor of their
333 // dominating value. Keep track of which blocks contain definitions (the key)
334 // and if a block contains a definition, which instruction it is.
336 std::map<unsigned, Instruction*> Definitions;
337 Definitions.insert(std::make_pair(BlockNumbering[Expr->getParent()], Expr));
339 bool Changed = false;
341 // Look at all of the equal values. If any of the values is not an
342 // instruction, replace all other expressions immediately with it (it must be
343 // an argument or a constant or something). Otherwise, convert the list of
344 // values into a list of expression (instruction) definitions ordering
345 // according to their dominator tree ordering.
347 Value *NonInstValue = 0;
348 for (unsigned i = 0, e = Values.size(); i != e; ++i)
349 if (Instruction *I = dyn_cast<Instruction>(Values[i])) {
350 Instruction *&BlockInst = Definitions[BlockNumbering[I->getParent()]];
351 if (BlockInst && BlockInst != I) { // Eliminate direct redundancy
352 if (DS->dominates(I, BlockInst)) { // I dom BlockInst
353 BlockInst->replaceAllUsesWith(I);
354 BlockInst->getParent()->getInstList().erase(BlockInst);
355 } else { // BlockInst dom I
356 I->replaceAllUsesWith(BlockInst);
357 I->getParent()->getInstList().erase(I);
364 NonInstValue = Values[i];
367 std::vector<Value*>().swap(Values); // Done with the values list
370 // This is the good, though unlikely, case where we find out that this
371 // expression is equal to a constant or argument directly. We can replace
372 // this and all of the other equivalent instructions with the value
375 for (std::map<unsigned, Instruction*>::iterator I = Definitions.begin(),
376 E = Definitions.end(); I != E; ++I) {
377 Instruction *Inst = I->second;
378 // Replace the value with the specified non-instruction value.
379 Inst->replaceAllUsesWith(NonInstValue); // Fixup any uses
380 Inst->getParent()->getInstList().erase(Inst); // Erase the instruction
382 NumExprsEliminated += Definitions.size();
383 return true; // Program modified!
386 // There are no expressions equal to this one. Exit early.
387 assert(!Definitions.empty() && "no equal expressions??");
389 if (Definitions.size() == 1) {
390 ProcessedExpressions.insert(Definitions.begin()->second);
394 DEBUG(std::cerr << "\n====--- Expression: " << Expr);
395 const Type *ExprType = Expr->getType();
397 // AnticipatibleBlocks - Blocks where the current expression is anticipatible.
398 // This is logically std::vector<bool> but using 'char' for performance.
399 std::vector<char> AnticipatibleBlocks;
401 // Calculate all of the blocks which the current expression is anticipatible.
402 CalculateAnticipatibleBlocks(Definitions, AnticipatibleBlocks);
404 // Print out anticipatible blocks...
405 DEBUG(std::cerr << "AntBlocks: ";
406 for (unsigned i = 0, e = AnticipatibleBlocks.size(); i != e; ++i)
407 if (AnticipatibleBlocks[i])
408 std::cerr << BlockMapping[i]->getName() <<" ";
413 // AvailabilityFrontier - Calculates the availability frontier for the current
414 // expression. The availability frontier contains the blocks on the dominance
415 // frontier of the current available expressions, iff they anticipate a
416 // definition of the expression.
417 hash_set<unsigned> AvailabilityFrontier;
419 Instruction *NonPHIOccurrence = 0;
421 while (!Definitions.empty() || !AvailabilityFrontier.empty()) {
422 if (!Definitions.empty() &&
423 (AvailabilityFrontier.empty() ||
424 Definitions.begin()->first < *AvailabilityFrontier.begin())) {
425 Instruction *Occurrence = Definitions.begin()->second;
426 BasicBlock *BB = Occurrence->getParent();
427 Definitions.erase(Definitions.begin());
429 DEBUG(std::cerr << "PROCESSING Occurrence: " << Occurrence);
431 // Check to see if there is already an incoming value for this block...
432 AvailableBlocksTy::iterator LBI = AvailableBlocks.find(BB);
433 if (LBI != AvailableBlocks.end()) {
434 // Yes, there is a dominating definition for this block. Replace this
435 // occurrence with the incoming value.
436 if (LBI->second != Occurrence) {
437 DEBUG(std::cerr << " replacing with: " << LBI->second);
438 Occurrence->replaceAllUsesWith(LBI->second);
439 BB->getInstList().erase(Occurrence); // Delete instruction
443 ProcessedExpressions.insert(Occurrence);
444 if (!isa<PHINode>(Occurrence))
445 NonPHIOccurrence = Occurrence; // Keep an occurrence of this expr
447 // Okay, there is no incoming value for this block, so this expression
448 // is a new definition that is good for this block and all blocks
449 // dominated by it. Add this information to the AvailableBlocks map.
451 MarkOccurrenceAvailableInAllDominatedBlocks(Occurrence, BB);
453 // Update the dominance frontier for the definitions so far... if a node
454 // in the dominator frontier now has all of its predecessors available,
455 // and the block is in an anticipatible region, we can insert a PHI node
457 DominanceFrontier::iterator DFI = DF->find(BB);
458 if (DFI != DF->end()) {
459 for (std::set<BasicBlock*>::iterator DI = DFI->second.begin();
460 DI != DFI->second.end(); ++DI) {
461 BasicBlock *DFBlock = *DI;
462 unsigned DFBlockID = BlockNumbering[DFBlock];
463 if (AnticipatibleBlocks[DFBlockID]) {
464 // Check to see if any of the predecessors of this block on the
465 // frontier are not available...
466 bool AnyNotAvailable = false;
467 for (pred_iterator PI = pred_begin(DFBlock),
468 PE = pred_end(DFBlock); PI != PE; ++PI)
469 if (!AvailableBlocks.count(*PI)) {
470 AnyNotAvailable = true;
474 // If any predecessor blocks are not available, add the node to
475 // the current expression dominance frontier.
476 if (AnyNotAvailable) {
477 AvailabilityFrontier.insert(DFBlockID);
479 // This block is no longer in the availability frontier, it IS
481 AvailabilityFrontier.erase(DFBlockID);
483 // If all of the predecessor blocks are available (and the block
484 // anticipates a definition along the path to the exit), we need
485 // to insert a new PHI node in this block. This block serves as
486 // a new definition for the expression, extending the available
489 PHINode *PN = new PHINode(ExprType, Expr->getName()+".pre",
491 ProcessedExpressions.insert(PN);
493 DEBUG(std::cerr << " INSERTING PHI on frontier: " << PN);
495 // Add the incoming blocks for the PHI node
496 for (pred_iterator PI = pred_begin(DFBlock),
497 PE = pred_end(DFBlock); PI != PE; ++PI)
499 PN->addIncoming(AvailableBlocks[*PI], *PI);
500 else // edge from the current block
501 PN->addIncoming(PN, DFBlock);
503 Instruction *&BlockOcc = Definitions[DFBlockID];
505 DEBUG(std::cerr <<" PHI superceeds occurrence: "<<BlockOcc);
506 BlockOcc->replaceAllUsesWith(PN);
507 BlockOcc->getParent()->getInstList().erase(BlockOcc);
518 // Otherwise we must be looking at a node in the availability frontier!
519 unsigned AFBlockID = *AvailabilityFrontier.begin();
520 AvailabilityFrontier.erase(AvailabilityFrontier.begin());
521 BasicBlock *AFBlock = BlockMapping[AFBlockID];
523 // We eliminate the partial redundancy on this frontier by inserting a PHI
524 // node into this block, merging any incoming available versions into the
525 // PHI and inserting a new computation into predecessors without an
526 // incoming value. Note that we would have to insert the expression on
527 // the edge if the predecessor didn't anticipate the expression and we
528 // didn't break critical edges.
530 PHINode *PN = new PHINode(ExprType, Expr->getName()+".PRE",
532 DEBUG(std::cerr << "INSERTING PHI for PR: " << PN);
534 // If there is a pending occurrence in this block, make sure to replace it
535 // with the PHI node...
536 std::map<unsigned, Instruction*>::iterator EDFI =
537 Definitions.find(AFBlockID);
538 if (EDFI != Definitions.end()) {
539 // There is already an occurrence in this block. Replace it with PN and
541 Instruction *OldOcc = EDFI->second;
542 DEBUG(std::cerr << " Replaces occurrence: " << OldOcc);
543 OldOcc->replaceAllUsesWith(PN);
544 AFBlock->getInstList().erase(OldOcc);
545 Definitions.erase(EDFI);
549 for (pred_iterator PI = pred_begin(AFBlock), PE = pred_end(AFBlock);
551 BasicBlock *Pred = *PI;
552 AvailableBlocksTy::iterator LBI = AvailableBlocks.find(Pred);
553 if (LBI != AvailableBlocks.end()) { // If there is a available value
554 PN->addIncoming(LBI->second, Pred); // for this pred, use it.
555 } else { // No available value yet...
556 unsigned PredID = BlockNumbering[Pred];
558 // Is the predecessor the same block that we inserted the PHI into?
560 if (Pred == AFBlock) {
561 // Yes, reuse the incoming value here...
562 PN->addIncoming(PN, Pred);
564 // No, we must insert a new computation into this block and add it
565 // to the definitions list...
566 assert(NonPHIOccurrence && "No non-phi occurrences seen so far???");
567 Instruction *New = NonPHIOccurrence->clone();
568 New->setName(NonPHIOccurrence->getName() + ".PRE-inserted");
569 ProcessedExpressions.insert(New);
571 DEBUG(std::cerr << " INSERTING OCCURRRENCE: " << New);
573 // Insert it into the bottom of the predecessor, right before the
574 // terminator instruction...
575 Pred->getInstList().insert(Pred->getTerminator(), New);
577 // Make this block be the available definition for any blocks it
578 // dominates. The ONLY case that this can affect more than just the
579 // block itself is when we are moving a computation to a loop
580 // header. In all other cases, because we don't have critical
581 // edges, the node is guaranteed to only dominate itself.
583 ReplaceDominatedAvailableOccurrencesWith(New, DT->getNode(Pred));
585 // Add it as an incoming value on this edge to the PHI node
586 PN->addIncoming(New, Pred);
587 NonPHIOccurrence = New;
593 // Find out if there is already an available value in this block. If so,
594 // we need to replace the available value with the PHI node. This can
595 // only happen when we just inserted a PHI node on a backedge.
597 AvailableBlocksTy::iterator LBBlockAvailableValIt =
598 AvailableBlocks.find(AFBlock);
599 if (LBBlockAvailableValIt != AvailableBlocks.end()) {
600 if (LBBlockAvailableValIt->second->getParent() == AFBlock) {
601 Instruction *OldVal = LBBlockAvailableValIt->second;
602 OldVal->replaceAllUsesWith(PN); // Use the new PHI node now
604 DEBUG(std::cerr << " PHI replaces available value: %"
605 << OldVal->getName() << "\n");
607 // Loop over all of the blocks dominated by this PHI node, and change
608 // the AvailableBlocks entries to be the PHI node instead of the old
610 MarkOccurrenceAvailableInAllDominatedBlocks(PN, AFBlock);
612 AFBlock->getInstList().erase(OldVal); // Delete old instruction!
614 // The resultant PHI node is a new definition of the value!
615 Definitions.insert(std::make_pair(AFBlockID, PN));
617 // If the value is not defined in this block, that means that an
618 // inserted occurrence in a predecessor is now the live value for the
619 // region (occurs when hoisting loop invariants, f.e.). In this case,
620 // the PHI node should actually just be removed.
621 assert(PN->use_empty() && "No uses should exist for dead PHI node!");
622 PN->getParent()->getInstList().erase(PN);
625 // The resultant PHI node is a new definition of the value!
626 Definitions.insert(std::make_pair(AFBlockID, PN));
631 AvailableBlocks.clear();
636 } // End llvm namespace