Print llvm code one function at a time.
[oota-llvm.git] / lib / Transforms / Scalar / PRE.cpp
1 //===- PRE.cpp - Partial Redundancy Elimination ---------------------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the well-known Partial Redundancy Elimination
11 // optimization, using an SSA formulation based on e-paths.  See this paper for
12 // more information:
13 //
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
17 //
18 // This file actually implements a sparse version of the algorithm, using SSA
19 // and CFG properties instead of bit-vectors.
20 //
21 //===----------------------------------------------------------------------===//
22
23 #include "llvm/Pass.h"
24 #include "llvm/Function.h"
25 #include "llvm/Type.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/Support/CFG.h"
28 #include "llvm/Analysis/Dominators.h"
29 #include "llvm/Analysis/PostDominators.h"
30 #include "llvm/Analysis/ValueNumbering.h"
31 #include "llvm/Transforms/Scalar.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/ADT/DepthFirstIterator.h"
34 #include "llvm/ADT/PostOrderIterator.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/hash_set"
37 #include "llvm/ADT/hash_map"
38 using namespace llvm;
39
40 namespace {
41   Statistic<> NumExprsEliminated("pre", "Number of expressions constantified");
42   Statistic<> NumRedundant      ("pre", "Number of redundant exprs eliminated");
43   Statistic<> NumInserted       ("pre", "Number of expressions inserted");
44
45   struct PRE : public FunctionPass {
46     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
47       AU.addRequiredID(BreakCriticalEdgesID);  // No critical edges for now!
48       AU.addRequired<PostDominatorTree>();
49       AU.addRequired<PostDominanceFrontier>();
50       AU.addRequired<DominatorSet>();
51       AU.addRequired<DominatorTree>();
52       AU.addRequired<DominanceFrontier>();
53       AU.addRequired<ValueNumbering>();
54     }
55     virtual bool runOnFunction(Function &F);
56
57   private:
58     // Block information - Map basic blocks in a function back and forth to
59     // unsigned integers.
60     std::vector<BasicBlock*> BlockMapping;
61     hash_map<BasicBlock*, unsigned> BlockNumbering;
62
63     // ProcessedExpressions - Keep track of which expressions have already been
64     // processed.
65     hash_set<Instruction*> ProcessedExpressions;
66
67     // Provide access to the various analyses used...
68     DominatorSet      *DS;
69     DominatorTree     *DT; PostDominatorTree *PDT;
70     DominanceFrontier *DF; PostDominanceFrontier *PDF;
71     ValueNumbering    *VN;
72
73     // AvailableBlocks - Contain a mapping of blocks with available expression
74     // values to the expression value itself.  This can be used as an efficient
75     // way to find out if the expression is available in the block, and if so,
76     // which version to use.  This map is only used while processing a single
77     // expression.
78     //
79     typedef hash_map<BasicBlock*, Instruction*> AvailableBlocksTy;
80     AvailableBlocksTy AvailableBlocks;
81
82     bool ProcessBlock(BasicBlock *BB);
83     
84     // Anticipatibility calculation...
85     void MarkPostDominatingBlocksAnticipatible(PostDominatorTree::Node *N,
86                                                std::vector<char> &AntBlocks,
87                                                Instruction *Occurrence);
88     void CalculateAnticipatiblityForOccurrence(unsigned BlockNo,
89                                               std::vector<char> &AntBlocks,
90                                               Instruction *Occurrence);
91     void CalculateAnticipatibleBlocks(const std::map<unsigned, Instruction*> &D,
92                                       std::vector<char> &AnticipatibleBlocks);
93
94     // PRE for an expression
95     void MarkOccurrenceAvailableInAllDominatedBlocks(Instruction *Occurrence,
96                                                      BasicBlock *StartBlock);
97     void ReplaceDominatedAvailableOccurrencesWith(Instruction *NewOcc,
98                                                   DominatorTree::Node *N);
99     bool ProcessExpression(Instruction *I);
100   };
101
102   RegisterOpt<PRE> Z("pre", "Partial Redundancy Elimination");
103 }
104
105
106 bool PRE::runOnFunction(Function &F) {
107   VN  = &getAnalysis<ValueNumbering>();
108   DS  = &getAnalysis<DominatorSet>();
109   DT  = &getAnalysis<DominatorTree>();
110   DF  = &getAnalysis<DominanceFrontier>();
111   PDT = &getAnalysis<PostDominatorTree>();
112   PDF = &getAnalysis<PostDominanceFrontier>();
113
114   DEBUG(std::cerr << "\n*** Running PRE on func '" << F.getName() << "'...\n");
115
116   // Number the basic blocks based on a reverse post-order traversal of the CFG
117   // so that all predecessors of a block (ignoring back edges) are visited
118   // before a block is visited.
119   //
120   BlockMapping.reserve(F.size());
121   {
122     ReversePostOrderTraversal<Function*> RPOT(&F);
123     DEBUG(std::cerr << "Block order: ");
124     for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
125            E = RPOT.end(); I != E; ++I) {
126       // Keep track of mapping...
127       BasicBlock *BB = *I;
128       BlockNumbering.insert(std::make_pair(BB, BlockMapping.size()));
129       BlockMapping.push_back(BB);
130       DEBUG(std::cerr << BB->getName() << " ");
131     }
132     DEBUG(std::cerr << "\n");
133   }
134
135   // Traverse the current function depth-first in dominator-tree order.  This
136   // ensures that we see all definitions before their uses (except for PHI
137   // nodes), allowing us to hoist dependent expressions correctly.
138   bool Changed = false;
139   for (unsigned i = 0, e = BlockMapping.size(); i != e; ++i)
140     Changed |= ProcessBlock(BlockMapping[i]);
141
142   // Free memory
143   BlockMapping.clear();
144   BlockNumbering.clear();
145   ProcessedExpressions.clear();
146   return Changed;
147 }
148
149
150 // ProcessBlock - Process any expressions first seen in this block...
151 //
152 bool PRE::ProcessBlock(BasicBlock *BB) {
153   bool Changed = false;
154
155   // DISABLED: This pass invalidates iterators and then uses them.
156   return false;
157
158   // PRE expressions first defined in this block...
159   for (BasicBlock::iterator I = BB->begin(); I != BB->end(); )
160     if (ProcessExpression(I++))
161       Changed = true;
162
163   return Changed;
164 }
165
166 void PRE::MarkPostDominatingBlocksAnticipatible(PostDominatorTree::Node *N,
167                                                 std::vector<char> &AntBlocks,
168                                                 Instruction *Occurrence) {
169   unsigned BlockNo = BlockNumbering[N->getBlock()];
170
171   if (AntBlocks[BlockNo]) return;  // Already known to be anticipatible??
172
173   // Check to see if any of the operands are defined in this block, if so, the
174   // entry of this block does not anticipate the expression.  This computes
175   // "transparency".
176   for (unsigned i = 0, e = Occurrence->getNumOperands(); i != e; ++i)
177     if (Instruction *I = dyn_cast<Instruction>(Occurrence->getOperand(i)))
178       if (I->getParent() == N->getBlock())  // Operand is defined in this block!
179         return;
180
181   if (isa<LoadInst>(Occurrence))
182     return;        // FIXME: compute transparency for load instructions using AA
183
184   // Insert block into AntBlocks list...
185   AntBlocks[BlockNo] = true;
186
187   for (PostDominatorTree::Node::iterator I = N->begin(), E = N->end(); I != E;
188        ++I)
189     MarkPostDominatingBlocksAnticipatible(*I, AntBlocks, Occurrence);
190 }
191
192 void PRE::CalculateAnticipatiblityForOccurrence(unsigned BlockNo,
193                                                 std::vector<char> &AntBlocks,
194                                                 Instruction *Occurrence) {
195   if (AntBlocks[BlockNo]) return;  // Block already anticipatible!
196
197   BasicBlock *BB = BlockMapping[BlockNo];
198
199   // For each occurrence, mark all post-dominated blocks as anticipatible...
200   MarkPostDominatingBlocksAnticipatible(PDT->getNode(BB), AntBlocks,
201                                         Occurrence);
202
203   // Next, mark any blocks in the post-dominance frontier as anticipatible iff
204   // all successors are anticipatible.
205   //
206   PostDominanceFrontier::iterator PDFI = PDF->find(BB);
207   if (PDFI != DF->end())
208     for (std::set<BasicBlock*>::iterator DI = PDFI->second.begin();
209          DI != PDFI->second.end(); ++DI) {
210       BasicBlock *PDFBlock = *DI;
211       bool AllSuccessorsAnticipatible = true;
212       for (succ_iterator SI = succ_begin(PDFBlock), SE = succ_end(PDFBlock);
213            SI != SE; ++SI)
214         if (!AntBlocks[BlockNumbering[*SI]]) {
215           AllSuccessorsAnticipatible = false;
216           break;
217         }
218
219       if (AllSuccessorsAnticipatible)
220         CalculateAnticipatiblityForOccurrence(BlockNumbering[PDFBlock],
221                                               AntBlocks, Occurrence);
222     }
223 }
224
225
226 void PRE::CalculateAnticipatibleBlocks(const std::map<unsigned,
227                                                       Instruction*> &Defs,
228                                        std::vector<char> &AntBlocks) {
229   // Initialize to zeros...
230   AntBlocks.resize(BlockMapping.size());
231
232   // Loop over all of the expressions...
233   for (std::map<unsigned, Instruction*>::const_iterator I = Defs.begin(),
234          E = Defs.end(); I != E; ++I)
235     CalculateAnticipatiblityForOccurrence(I->first, AntBlocks, I->second);
236 }
237
238 /// MarkOccurrenceAvailableInAllDominatedBlocks - Add entries to AvailableBlocks
239 /// for all nodes dominated by the occurrence to indicate that it is now the
240 /// available occurrence to use in any of these blocks.
241 ///
242 void PRE::MarkOccurrenceAvailableInAllDominatedBlocks(Instruction *Occurrence,
243                                                       BasicBlock *BB) {
244   // FIXME: There are much more efficient ways to get the blocks dominated
245   // by a block.  Use them.
246   //
247   DominatorTree::Node *N = DT->getNode(Occurrence->getParent());
248   for (df_iterator<DominatorTree::Node*> DI = df_begin(N), E = df_end(N);
249        DI != E; ++DI)
250     AvailableBlocks[(*DI)->getBlock()] = Occurrence;
251 }
252
253 /// ReplaceDominatedAvailableOccurrencesWith - This loops over the region
254 /// dominated by N, replacing any available expressions with NewOcc.
255 void PRE::ReplaceDominatedAvailableOccurrencesWith(Instruction *NewOcc,
256                                                    DominatorTree::Node *N) {
257   BasicBlock *BB = N->getBlock();
258   Instruction *&ExistingAvailableVal = AvailableBlocks[BB];
259
260   // If there isn't a definition already active in this node, make this the new
261   // active definition...
262   if (ExistingAvailableVal == 0) {
263     ExistingAvailableVal = NewOcc;
264     
265     for (DominatorTree::Node::iterator I = N->begin(), E = N->end(); I != E;++I)
266       ReplaceDominatedAvailableOccurrencesWith(NewOcc, *I);
267   } else {
268     // If there is already an active definition in this block, replace it with
269     // NewOcc, and force it into all dominated blocks.
270     DEBUG(std::cerr << "  Replacing dominated occ %"
271           << ExistingAvailableVal->getName() << " with %" << NewOcc->getName()
272           << "\n");
273     assert(ExistingAvailableVal != NewOcc && "NewOcc already inserted??");
274     ExistingAvailableVal->replaceAllUsesWith(NewOcc);
275     ++NumRedundant;
276
277     assert(ExistingAvailableVal->getParent() == BB &&
278            "OldOcc not defined in current block?");
279     BB->getInstList().erase(ExistingAvailableVal);
280
281     // Mark NewOCC as the Available expression in all blocks dominated by BB
282     for (df_iterator<DominatorTree::Node*> DI = df_begin(N), E = df_end(N);
283          DI != E; ++DI)
284       AvailableBlocks[(*DI)->getBlock()] = NewOcc;
285   }  
286 }
287
288
289 /// ProcessExpression - Given an expression (instruction) process the
290 /// instruction to remove any partial redundancies induced by equivalent
291 /// computations.  Note that we only need to PRE each expression once, so we
292 /// keep track of whether an expression has been PRE'd already, and don't PRE an
293 /// expression again.  Expressions may be seen multiple times because process
294 /// the entire equivalence class at once, which may leave expressions later in
295 /// the control path.
296 ///
297 bool PRE::ProcessExpression(Instruction *Expr) {
298   if (Expr->mayWriteToMemory() || Expr->getType() == Type::VoidTy ||
299       isa<PHINode>(Expr))
300     return false;         // Cannot move expression
301   if (ProcessedExpressions.count(Expr)) return false; // Already processed.
302
303   // Ok, this is the first time we have seen the expression.  Build a set of
304   // equivalent expressions using SSA def/use information.  We consider
305   // expressions to be equivalent if they are the same opcode and have
306   // equivalent operands.  As a special case for SSA, values produced by PHI
307   // nodes are considered to be equivalent to all of their operands.
308   //
309   std::vector<Value*> Values;
310   VN->getEqualNumberNodes(Expr, Values);
311
312 #if 0
313   // FIXME: This should handle PHI nodes correctly.  To do this, we need to
314   // consider expressions of the following form equivalent to this set of
315   // expressions:
316   //
317   // If an operand is a PHI node, add any occurrences of the expression with the
318   // PHI operand replaced with the PHI node operands.  This is only valid if the
319   // PHI operand occurrences exist in blocks post-dominated by the incoming edge
320   // of the PHI node.
321 #endif
322
323   // We have to be careful to handle expression definitions which dominated by
324   // other expressions.  These can be directly eliminated in favor of their
325   // dominating value.  Keep track of which blocks contain definitions (the key)
326   // and if a block contains a definition, which instruction it is.
327   //
328   std::map<unsigned, Instruction*> Definitions;
329   Definitions.insert(std::make_pair(BlockNumbering[Expr->getParent()], Expr));
330
331   bool Changed = false;
332
333   // Look at all of the equal values.  If any of the values is not an
334   // instruction, replace all other expressions immediately with it (it must be
335   // an argument or a constant or something). Otherwise, convert the list of
336   // values into a list of expression (instruction) definitions ordering
337   // according to their dominator tree ordering.
338   //
339   Value *NonInstValue = 0;
340   for (unsigned i = 0, e = Values.size(); i != e; ++i)
341     if (Instruction *I = dyn_cast<Instruction>(Values[i])) {
342       Instruction *&BlockInst = Definitions[BlockNumbering[I->getParent()]];
343       if (BlockInst && BlockInst != I) {    // Eliminate direct redundancy
344         if (DS->dominates(I, BlockInst)) {  // I dom BlockInst
345           BlockInst->replaceAllUsesWith(I);
346           BlockInst->getParent()->getInstList().erase(BlockInst);
347         } else {                            // BlockInst dom I
348           I->replaceAllUsesWith(BlockInst);
349           I->getParent()->getInstList().erase(I);
350           I = BlockInst;
351         }
352         ++NumRedundant;
353       }
354       BlockInst = I;
355     } else {
356       NonInstValue = Values[i];
357     }
358
359   std::vector<Value*>().swap(Values);  // Done with the values list
360
361   if (NonInstValue) {
362     // This is the good, though unlikely, case where we find out that this
363     // expression is equal to a constant or argument directly.  We can replace
364     // this and all of the other equivalent instructions with the value
365     // directly.
366     //
367     for (std::map<unsigned, Instruction*>::iterator I = Definitions.begin(),
368            E = Definitions.end(); I != E; ++I) {
369       Instruction *Inst = I->second;
370       // Replace the value with the specified non-instruction value.
371       Inst->replaceAllUsesWith(NonInstValue);       // Fixup any uses
372       Inst->getParent()->getInstList().erase(Inst); // Erase the instruction
373     }
374     NumExprsEliminated += Definitions.size();
375     return true;   // Program modified!
376   }
377
378   // There are no expressions equal to this one.  Exit early.
379   assert(!Definitions.empty() && "no equal expressions??");
380 #if 0
381   if (Definitions.size() == 1) {
382     ProcessedExpressions.insert(Definitions.begin()->second);
383     return Changed;
384   }
385 #endif
386   DEBUG(std::cerr << "\n====--- Expression: " << *Expr);
387   const Type *ExprType = Expr->getType();
388
389   // AnticipatibleBlocks - Blocks where the current expression is anticipatible.
390   // This is logically std::vector<bool> but using 'char' for performance.
391   std::vector<char> AnticipatibleBlocks;
392
393   // Calculate all of the blocks which the current expression is anticipatible.
394   CalculateAnticipatibleBlocks(Definitions, AnticipatibleBlocks);
395
396   // Print out anticipatible blocks...
397   DEBUG(std::cerr << "AntBlocks: ";
398         for (unsigned i = 0, e = AnticipatibleBlocks.size(); i != e; ++i)
399           if (AnticipatibleBlocks[i])
400             std::cerr << BlockMapping[i]->getName() <<" ";
401         std::cerr << "\n";);
402   
403
404
405   // AvailabilityFrontier - Calculates the availability frontier for the current
406   // expression.  The availability frontier contains the blocks on the dominance
407   // frontier of the current available expressions, iff they anticipate a
408   // definition of the expression.
409   hash_set<unsigned> AvailabilityFrontier;
410
411   Instruction *NonPHIOccurrence = 0;
412
413   while (!Definitions.empty() || !AvailabilityFrontier.empty()) {
414     if (!Definitions.empty() &&
415         (AvailabilityFrontier.empty() ||
416          Definitions.begin()->first < *AvailabilityFrontier.begin())) {
417       Instruction *Occurrence = Definitions.begin()->second;
418       BasicBlock *BB = Occurrence->getParent();
419       Definitions.erase(Definitions.begin());
420
421       DEBUG(std::cerr << "PROCESSING Occurrence: " << *Occurrence);
422
423       // Check to see if there is already an incoming value for this block...
424       AvailableBlocksTy::iterator LBI = AvailableBlocks.find(BB);
425       if (LBI != AvailableBlocks.end()) {
426         // Yes, there is a dominating definition for this block.  Replace this
427         // occurrence with the incoming value.
428         if (LBI->second != Occurrence) {
429           DEBUG(std::cerr << "  replacing with: " << *LBI->second);
430           Occurrence->replaceAllUsesWith(LBI->second);
431           BB->getInstList().erase(Occurrence);   // Delete instruction
432           ++NumRedundant;
433         }
434       } else {
435         ProcessedExpressions.insert(Occurrence);
436         if (!isa<PHINode>(Occurrence))
437           NonPHIOccurrence = Occurrence;  // Keep an occurrence of this expr
438
439         // Okay, there is no incoming value for this block, so this expression
440         // is a new definition that is good for this block and all blocks
441         // dominated by it.  Add this information to the AvailableBlocks map.
442         //
443         MarkOccurrenceAvailableInAllDominatedBlocks(Occurrence, BB);
444
445         // Update the dominance frontier for the definitions so far... if a node
446         // in the dominator frontier now has all of its predecessors available,
447         // and the block is in an anticipatible region, we can insert a PHI node
448         // in that block.
449         DominanceFrontier::iterator DFI = DF->find(BB);
450         if (DFI != DF->end()) {
451           for (std::set<BasicBlock*>::iterator DI = DFI->second.begin();
452                DI != DFI->second.end(); ++DI) {
453             BasicBlock *DFBlock = *DI;
454             unsigned DFBlockID = BlockNumbering[DFBlock];
455             if (AnticipatibleBlocks[DFBlockID]) {
456               // Check to see if any of the predecessors of this block on the
457               // frontier are not available...
458               bool AnyNotAvailable = false;
459               for (pred_iterator PI = pred_begin(DFBlock),
460                      PE = pred_end(DFBlock); PI != PE; ++PI)
461                 if (!AvailableBlocks.count(*PI)) {
462                   AnyNotAvailable = true;
463                   break;
464                 }
465             
466               // If any predecessor blocks are not available, add the node to
467               // the current expression dominance frontier.
468               if (AnyNotAvailable) {
469                 AvailabilityFrontier.insert(DFBlockID);
470               } else {
471                 // This block is no longer in the availability frontier, it IS
472                 // available.
473                 AvailabilityFrontier.erase(DFBlockID);
474
475                 // If all of the predecessor blocks are available (and the block
476                 // anticipates a definition along the path to the exit), we need
477                 // to insert a new PHI node in this block.  This block serves as
478                 // a new definition for the expression, extending the available
479                 // region.
480                 //
481                 PHINode *PN = new PHINode(ExprType, Expr->getName()+".pre",
482                                           DFBlock->begin());
483                 ProcessedExpressions.insert(PN);
484
485                 DEBUG(std::cerr << "  INSERTING PHI on frontier: " << *PN);
486
487                 // Add the incoming blocks for the PHI node
488                 for (pred_iterator PI = pred_begin(DFBlock),
489                        PE = pred_end(DFBlock); PI != PE; ++PI)
490                   if (*PI != DFBlock)
491                     PN->addIncoming(AvailableBlocks[*PI], *PI);
492                   else                          // edge from the current block
493                     PN->addIncoming(PN, DFBlock);
494
495                 Instruction *&BlockOcc = Definitions[DFBlockID];
496                 if (BlockOcc) {
497                   DEBUG(std::cerr <<"    PHI superceeds occurrence: "<<
498                         *BlockOcc);
499                   BlockOcc->replaceAllUsesWith(PN);
500                   BlockOcc->getParent()->getInstList().erase(BlockOcc);
501                   ++NumRedundant;
502                 }
503                 BlockOcc = PN;
504               }
505             }
506           }
507         }
508       }
509
510     } else {
511       // Otherwise we must be looking at a node in the availability frontier!
512       unsigned AFBlockID = *AvailabilityFrontier.begin();
513       AvailabilityFrontier.erase(AvailabilityFrontier.begin());
514       BasicBlock *AFBlock = BlockMapping[AFBlockID];
515
516       // We eliminate the partial redundancy on this frontier by inserting a PHI
517       // node into this block, merging any incoming available versions into the
518       // PHI and inserting a new computation into predecessors without an
519       // incoming value.  Note that we would have to insert the expression on
520       // the edge if the predecessor didn't anticipate the expression and we
521       // didn't break critical edges.
522       //
523       PHINode *PN = new PHINode(ExprType, Expr->getName()+".PRE",
524                                 AFBlock->begin());
525       DEBUG(std::cerr << "INSERTING PHI for PR: " << *PN);
526
527       // If there is a pending occurrence in this block, make sure to replace it
528       // with the PHI node...
529       std::map<unsigned, Instruction*>::iterator EDFI =
530         Definitions.find(AFBlockID);
531       if (EDFI != Definitions.end()) {
532         // There is already an occurrence in this block.  Replace it with PN and
533         // remove it.
534         Instruction *OldOcc = EDFI->second;
535         DEBUG(std::cerr << "  Replaces occurrence: " << *OldOcc);
536         OldOcc->replaceAllUsesWith(PN);
537         AFBlock->getInstList().erase(OldOcc);
538         Definitions.erase(EDFI);
539         ++NumRedundant;
540       }
541
542       for (pred_iterator PI = pred_begin(AFBlock), PE = pred_end(AFBlock);
543            PI != PE; ++PI) {
544         BasicBlock *Pred = *PI;
545         AvailableBlocksTy::iterator LBI = AvailableBlocks.find(Pred);
546         if (LBI != AvailableBlocks.end()) {    // If there is a available value
547           PN->addIncoming(LBI->second, Pred);  // for this pred, use it.
548         } else {                         // No available value yet...
549           unsigned PredID = BlockNumbering[Pred];
550
551           // Is the predecessor the same block that we inserted the PHI into?
552           // (self loop)
553           if (Pred == AFBlock) {
554             // Yes, reuse the incoming value here...
555             PN->addIncoming(PN, Pred);
556           } else {
557             // No, we must insert a new computation into this block and add it
558             // to the definitions list...
559             assert(NonPHIOccurrence && "No non-phi occurrences seen so far???");
560             Instruction *New = NonPHIOccurrence->clone();
561             New->setName(NonPHIOccurrence->getName() + ".PRE-inserted");
562             ProcessedExpressions.insert(New);
563
564             DEBUG(std::cerr << "  INSERTING OCCURRRENCE: " << *New);
565
566             // Insert it into the bottom of the predecessor, right before the
567             // terminator instruction...
568             Pred->getInstList().insert(Pred->getTerminator(), New);
569
570             // Make this block be the available definition for any blocks it
571             // dominates.  The ONLY case that this can affect more than just the
572             // block itself is when we are moving a computation to a loop
573             // header.  In all other cases, because we don't have critical
574             // edges, the node is guaranteed to only dominate itself.
575             //
576             ReplaceDominatedAvailableOccurrencesWith(New, DT->getNode(Pred));
577
578             // Add it as an incoming value on this edge to the PHI node
579             PN->addIncoming(New, Pred);
580             NonPHIOccurrence = New;
581             NumInserted++;
582           }
583         }
584       }
585
586       // Find out if there is already an available value in this block.  If so,
587       // we need to replace the available value with the PHI node.  This can
588       // only happen when we just inserted a PHI node on a backedge.
589       //
590       AvailableBlocksTy::iterator LBBlockAvailableValIt =
591         AvailableBlocks.find(AFBlock);
592       if (LBBlockAvailableValIt != AvailableBlocks.end()) {
593         if (LBBlockAvailableValIt->second->getParent() == AFBlock) {
594           Instruction *OldVal = LBBlockAvailableValIt->second;
595           OldVal->replaceAllUsesWith(PN);        // Use the new PHI node now
596           ++NumRedundant;
597           DEBUG(std::cerr << "  PHI replaces available value: %"
598                 << OldVal->getName() << "\n");
599           
600           // Loop over all of the blocks dominated by this PHI node, and change
601           // the AvailableBlocks entries to be the PHI node instead of the old
602           // instruction.
603           MarkOccurrenceAvailableInAllDominatedBlocks(PN, AFBlock);
604           
605           AFBlock->getInstList().erase(OldVal);  // Delete old instruction!
606
607           // The resultant PHI node is a new definition of the value!
608           Definitions.insert(std::make_pair(AFBlockID, PN));
609         } else {
610           // If the value is not defined in this block, that means that an
611           // inserted occurrence in a predecessor is now the live value for the
612           // region (occurs when hoisting loop invariants, f.e.).  In this case,
613           // the PHI node should actually just be removed.
614           assert(PN->use_empty() && "No uses should exist for dead PHI node!");
615           PN->getParent()->getInstList().erase(PN);            
616         }
617       } else {
618         // The resultant PHI node is a new definition of the value!
619         Definitions.insert(std::make_pair(AFBlockID, PN));
620       }
621     }
622   }
623
624   AvailableBlocks.clear();
625
626   return Changed;
627 }
628