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