Introduce and use a new MemDepResult class to hold the results of a memdep
[oota-llvm.git] / lib / Transforms / Scalar / GVN.cpp
1 //===- GVN.cpp - Eliminate redundant values and loads ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass performs global value numbering to eliminate fully redundant
11 // instructions.  It also performs simple dead load elimination.
12 //
13 // Note that this pass does the value numbering itself, it does not use the
14 // ValueNumbering analysis passes.
15 //
16 //===----------------------------------------------------------------------===//
17
18 #define DEBUG_TYPE "gvn"
19 #include "llvm/Transforms/Scalar.h"
20 #include "llvm/BasicBlock.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Function.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Value.h"
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/DepthFirstIterator.h"
28 #include "llvm/ADT/SmallPtrSet.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/Analysis/Dominators.h"
32 #include "llvm/Analysis/AliasAnalysis.h"
33 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
34 #include "llvm/Support/CFG.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Compiler.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
39 #include <cstdio>
40 using namespace llvm;
41
42 STATISTIC(NumGVNInstr, "Number of instructions deleted");
43 STATISTIC(NumGVNLoad, "Number of loads deleted");
44 STATISTIC(NumGVNPRE, "Number of instructions PRE'd");
45 STATISTIC(NumGVNBlocks, "Number of blocks merged");
46
47 static cl::opt<bool> EnablePRE("enable-pre",
48                                cl::init(true), cl::Hidden);
49
50 //===----------------------------------------------------------------------===//
51 //                         ValueTable Class
52 //===----------------------------------------------------------------------===//
53
54 /// This class holds the mapping between values and value numbers.  It is used
55 /// as an efficient mechanism to determine the expression-wise equivalence of
56 /// two values.
57 namespace {
58   struct VISIBILITY_HIDDEN Expression {
59     enum ExpressionOpcode { ADD, SUB, MUL, UDIV, SDIV, FDIV, UREM, SREM, 
60                             FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ, 
61                             ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE, 
62                             ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ, 
63                             FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE, 
64                             FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE, 
65                             FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
66                             SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
67                             FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT, 
68                             PTRTOINT, INTTOPTR, BITCAST, GEP, CALL, CONSTANT,
69                             EMPTY, TOMBSTONE };
70
71     ExpressionOpcode opcode;
72     const Type* type;
73     uint32_t firstVN;
74     uint32_t secondVN;
75     uint32_t thirdVN;
76     SmallVector<uint32_t, 4> varargs;
77     Value* function;
78   
79     Expression() { }
80     Expression(ExpressionOpcode o) : opcode(o) { }
81   
82     bool operator==(const Expression &other) const {
83       if (opcode != other.opcode)
84         return false;
85       else if (opcode == EMPTY || opcode == TOMBSTONE)
86         return true;
87       else if (type != other.type)
88         return false;
89       else if (function != other.function)
90         return false;
91       else if (firstVN != other.firstVN)
92         return false;
93       else if (secondVN != other.secondVN)
94         return false;
95       else if (thirdVN != other.thirdVN)
96         return false;
97       else {
98         if (varargs.size() != other.varargs.size())
99           return false;
100       
101         for (size_t i = 0; i < varargs.size(); ++i)
102           if (varargs[i] != other.varargs[i])
103             return false;
104     
105         return true;
106       }
107     }
108   
109     bool operator!=(const Expression &other) const {
110       if (opcode != other.opcode)
111         return true;
112       else if (opcode == EMPTY || opcode == TOMBSTONE)
113         return false;
114       else if (type != other.type)
115         return true;
116       else if (function != other.function)
117         return true;
118       else if (firstVN != other.firstVN)
119         return true;
120       else if (secondVN != other.secondVN)
121         return true;
122       else if (thirdVN != other.thirdVN)
123         return true;
124       else {
125         if (varargs.size() != other.varargs.size())
126           return true;
127       
128         for (size_t i = 0; i < varargs.size(); ++i)
129           if (varargs[i] != other.varargs[i])
130             return true;
131     
132           return false;
133       }
134     }
135   };
136   
137   class VISIBILITY_HIDDEN ValueTable {
138     private:
139       DenseMap<Value*, uint32_t> valueNumbering;
140       DenseMap<Expression, uint32_t> expressionNumbering;
141       AliasAnalysis* AA;
142       MemoryDependenceAnalysis* MD;
143       DominatorTree* DT;
144   
145       uint32_t nextValueNumber;
146     
147       Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
148       Expression::ExpressionOpcode getOpcode(CmpInst* C);
149       Expression::ExpressionOpcode getOpcode(CastInst* C);
150       Expression create_expression(BinaryOperator* BO);
151       Expression create_expression(CmpInst* C);
152       Expression create_expression(ShuffleVectorInst* V);
153       Expression create_expression(ExtractElementInst* C);
154       Expression create_expression(InsertElementInst* V);
155       Expression create_expression(SelectInst* V);
156       Expression create_expression(CastInst* C);
157       Expression create_expression(GetElementPtrInst* G);
158       Expression create_expression(CallInst* C);
159       Expression create_expression(Constant* C);
160     public:
161       ValueTable() : nextValueNumber(1) { }
162       uint32_t lookup_or_add(Value* V);
163       uint32_t lookup(Value* V) const;
164       void add(Value* V, uint32_t num);
165       void clear();
166       void erase(Value* v);
167       unsigned size();
168       void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
169       void setMemDep(MemoryDependenceAnalysis* M) { MD = M; }
170       void setDomTree(DominatorTree* D) { DT = D; }
171       uint32_t getNextUnusedValueNumber() { return nextValueNumber; }
172   };
173 }
174
175 namespace llvm {
176 template <> struct DenseMapInfo<Expression> {
177   static inline Expression getEmptyKey() {
178     return Expression(Expression::EMPTY);
179   }
180   
181   static inline Expression getTombstoneKey() {
182     return Expression(Expression::TOMBSTONE);
183   }
184   
185   static unsigned getHashValue(const Expression e) {
186     unsigned hash = e.opcode;
187     
188     hash = e.firstVN + hash * 37;
189     hash = e.secondVN + hash * 37;
190     hash = e.thirdVN + hash * 37;
191     
192     hash = ((unsigned)((uintptr_t)e.type >> 4) ^
193             (unsigned)((uintptr_t)e.type >> 9)) +
194            hash * 37;
195     
196     for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
197          E = e.varargs.end(); I != E; ++I)
198       hash = *I + hash * 37;
199     
200     hash = ((unsigned)((uintptr_t)e.function >> 4) ^
201             (unsigned)((uintptr_t)e.function >> 9)) +
202            hash * 37;
203     
204     return hash;
205   }
206   static bool isEqual(const Expression &LHS, const Expression &RHS) {
207     return LHS == RHS;
208   }
209   static bool isPod() { return true; }
210 };
211 }
212
213 //===----------------------------------------------------------------------===//
214 //                     ValueTable Internal Functions
215 //===----------------------------------------------------------------------===//
216 Expression::ExpressionOpcode ValueTable::getOpcode(BinaryOperator* BO) {
217   switch(BO->getOpcode()) {
218   default: // THIS SHOULD NEVER HAPPEN
219     assert(0 && "Binary operator with unknown opcode?");
220   case Instruction::Add:  return Expression::ADD;
221   case Instruction::Sub:  return Expression::SUB;
222   case Instruction::Mul:  return Expression::MUL;
223   case Instruction::UDiv: return Expression::UDIV;
224   case Instruction::SDiv: return Expression::SDIV;
225   case Instruction::FDiv: return Expression::FDIV;
226   case Instruction::URem: return Expression::UREM;
227   case Instruction::SRem: return Expression::SREM;
228   case Instruction::FRem: return Expression::FREM;
229   case Instruction::Shl:  return Expression::SHL;
230   case Instruction::LShr: return Expression::LSHR;
231   case Instruction::AShr: return Expression::ASHR;
232   case Instruction::And:  return Expression::AND;
233   case Instruction::Or:   return Expression::OR;
234   case Instruction::Xor:  return Expression::XOR;
235   }
236 }
237
238 Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
239   if (isa<ICmpInst>(C) || isa<VICmpInst>(C)) {
240     switch (C->getPredicate()) {
241     default:  // THIS SHOULD NEVER HAPPEN
242       assert(0 && "Comparison with unknown predicate?");
243     case ICmpInst::ICMP_EQ:  return Expression::ICMPEQ;
244     case ICmpInst::ICMP_NE:  return Expression::ICMPNE;
245     case ICmpInst::ICMP_UGT: return Expression::ICMPUGT;
246     case ICmpInst::ICMP_UGE: return Expression::ICMPUGE;
247     case ICmpInst::ICMP_ULT: return Expression::ICMPULT;
248     case ICmpInst::ICMP_ULE: return Expression::ICMPULE;
249     case ICmpInst::ICMP_SGT: return Expression::ICMPSGT;
250     case ICmpInst::ICMP_SGE: return Expression::ICMPSGE;
251     case ICmpInst::ICMP_SLT: return Expression::ICMPSLT;
252     case ICmpInst::ICMP_SLE: return Expression::ICMPSLE;
253     }
254   }
255   assert((isa<FCmpInst>(C) || isa<VFCmpInst>(C)) && "Unknown compare");
256   switch (C->getPredicate()) {
257   default: // THIS SHOULD NEVER HAPPEN
258     assert(0 && "Comparison with unknown predicate?");
259   case FCmpInst::FCMP_OEQ: return Expression::FCMPOEQ;
260   case FCmpInst::FCMP_OGT: return Expression::FCMPOGT;
261   case FCmpInst::FCMP_OGE: return Expression::FCMPOGE;
262   case FCmpInst::FCMP_OLT: return Expression::FCMPOLT;
263   case FCmpInst::FCMP_OLE: return Expression::FCMPOLE;
264   case FCmpInst::FCMP_ONE: return Expression::FCMPONE;
265   case FCmpInst::FCMP_ORD: return Expression::FCMPORD;
266   case FCmpInst::FCMP_UNO: return Expression::FCMPUNO;
267   case FCmpInst::FCMP_UEQ: return Expression::FCMPUEQ;
268   case FCmpInst::FCMP_UGT: return Expression::FCMPUGT;
269   case FCmpInst::FCMP_UGE: return Expression::FCMPUGE;
270   case FCmpInst::FCMP_ULT: return Expression::FCMPULT;
271   case FCmpInst::FCMP_ULE: return Expression::FCMPULE;
272   case FCmpInst::FCMP_UNE: return Expression::FCMPUNE;
273   }
274 }
275
276 Expression::ExpressionOpcode ValueTable::getOpcode(CastInst* C) {
277   switch(C->getOpcode()) {
278   default: // THIS SHOULD NEVER HAPPEN
279     assert(0 && "Cast operator with unknown opcode?");
280   case Instruction::Trunc:    return Expression::TRUNC;
281   case Instruction::ZExt:     return Expression::ZEXT;
282   case Instruction::SExt:     return Expression::SEXT;
283   case Instruction::FPToUI:   return Expression::FPTOUI;
284   case Instruction::FPToSI:   return Expression::FPTOSI;
285   case Instruction::UIToFP:   return Expression::UITOFP;
286   case Instruction::SIToFP:   return Expression::SITOFP;
287   case Instruction::FPTrunc:  return Expression::FPTRUNC;
288   case Instruction::FPExt:    return Expression::FPEXT;
289   case Instruction::PtrToInt: return Expression::PTRTOINT;
290   case Instruction::IntToPtr: return Expression::INTTOPTR;
291   case Instruction::BitCast:  return Expression::BITCAST;
292   }
293 }
294
295 Expression ValueTable::create_expression(CallInst* C) {
296   Expression e;
297   
298   e.type = C->getType();
299   e.firstVN = 0;
300   e.secondVN = 0;
301   e.thirdVN = 0;
302   e.function = C->getCalledFunction();
303   e.opcode = Expression::CALL;
304   
305   for (CallInst::op_iterator I = C->op_begin()+1, E = C->op_end();
306        I != E; ++I)
307     e.varargs.push_back(lookup_or_add(*I));
308   
309   return e;
310 }
311
312 Expression ValueTable::create_expression(BinaryOperator* BO) {
313   Expression e;
314     
315   e.firstVN = lookup_or_add(BO->getOperand(0));
316   e.secondVN = lookup_or_add(BO->getOperand(1));
317   e.thirdVN = 0;
318   e.function = 0;
319   e.type = BO->getType();
320   e.opcode = getOpcode(BO);
321   
322   return e;
323 }
324
325 Expression ValueTable::create_expression(CmpInst* C) {
326   Expression e;
327     
328   e.firstVN = lookup_or_add(C->getOperand(0));
329   e.secondVN = lookup_or_add(C->getOperand(1));
330   e.thirdVN = 0;
331   e.function = 0;
332   e.type = C->getType();
333   e.opcode = getOpcode(C);
334   
335   return e;
336 }
337
338 Expression ValueTable::create_expression(CastInst* C) {
339   Expression e;
340     
341   e.firstVN = lookup_or_add(C->getOperand(0));
342   e.secondVN = 0;
343   e.thirdVN = 0;
344   e.function = 0;
345   e.type = C->getType();
346   e.opcode = getOpcode(C);
347   
348   return e;
349 }
350
351 Expression ValueTable::create_expression(ShuffleVectorInst* S) {
352   Expression e;
353     
354   e.firstVN = lookup_or_add(S->getOperand(0));
355   e.secondVN = lookup_or_add(S->getOperand(1));
356   e.thirdVN = lookup_or_add(S->getOperand(2));
357   e.function = 0;
358   e.type = S->getType();
359   e.opcode = Expression::SHUFFLE;
360   
361   return e;
362 }
363
364 Expression ValueTable::create_expression(ExtractElementInst* E) {
365   Expression e;
366     
367   e.firstVN = lookup_or_add(E->getOperand(0));
368   e.secondVN = lookup_or_add(E->getOperand(1));
369   e.thirdVN = 0;
370   e.function = 0;
371   e.type = E->getType();
372   e.opcode = Expression::EXTRACT;
373   
374   return e;
375 }
376
377 Expression ValueTable::create_expression(InsertElementInst* I) {
378   Expression e;
379     
380   e.firstVN = lookup_or_add(I->getOperand(0));
381   e.secondVN = lookup_or_add(I->getOperand(1));
382   e.thirdVN = lookup_or_add(I->getOperand(2));
383   e.function = 0;
384   e.type = I->getType();
385   e.opcode = Expression::INSERT;
386   
387   return e;
388 }
389
390 Expression ValueTable::create_expression(SelectInst* I) {
391   Expression e;
392     
393   e.firstVN = lookup_or_add(I->getCondition());
394   e.secondVN = lookup_or_add(I->getTrueValue());
395   e.thirdVN = lookup_or_add(I->getFalseValue());
396   e.function = 0;
397   e.type = I->getType();
398   e.opcode = Expression::SELECT;
399   
400   return e;
401 }
402
403 Expression ValueTable::create_expression(GetElementPtrInst* G) {
404   Expression e;
405   
406   e.firstVN = lookup_or_add(G->getPointerOperand());
407   e.secondVN = 0;
408   e.thirdVN = 0;
409   e.function = 0;
410   e.type = G->getType();
411   e.opcode = Expression::GEP;
412   
413   for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
414        I != E; ++I)
415     e.varargs.push_back(lookup_or_add(*I));
416   
417   return e;
418 }
419
420 //===----------------------------------------------------------------------===//
421 //                     ValueTable External Functions
422 //===----------------------------------------------------------------------===//
423
424 /// add - Insert a value into the table with a specified value number.
425 void ValueTable::add(Value* V, uint32_t num) {
426   valueNumbering.insert(std::make_pair(V, num));
427 }
428
429 /// lookup_or_add - Returns the value number for the specified value, assigning
430 /// it a new number if it did not have one before.
431 uint32_t ValueTable::lookup_or_add(Value* V) {
432   DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
433   if (VI != valueNumbering.end())
434     return VI->second;
435   
436   if (CallInst* C = dyn_cast<CallInst>(V)) {
437     if (AA->doesNotAccessMemory(C)) {
438       Expression e = create_expression(C);
439     
440       DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
441       if (EI != expressionNumbering.end()) {
442         valueNumbering.insert(std::make_pair(V, EI->second));
443         return EI->second;
444       } else {
445         expressionNumbering.insert(std::make_pair(e, nextValueNumber));
446         valueNumbering.insert(std::make_pair(V, nextValueNumber));
447       
448         return nextValueNumber++;
449       }
450     } else if (AA->onlyReadsMemory(C)) {
451       Expression e = create_expression(C);
452       
453       if (expressionNumbering.find(e) == expressionNumbering.end()) {
454         expressionNumbering.insert(std::make_pair(e, nextValueNumber));
455         valueNumbering.insert(std::make_pair(V, nextValueNumber));
456         return nextValueNumber++;
457       }
458       
459       MemDepResult local_dep = MD->getDependency(C);
460       
461       if (local_dep.isNone()) {
462         valueNumbering.insert(std::make_pair(V, nextValueNumber));
463         return nextValueNumber++;
464       } else if (Instruction *LocalDepInst = local_dep.getInst()) {
465         // FIXME: INDENT PROPERLY!
466         if (!isa<CallInst>(LocalDepInst)) {
467           valueNumbering.insert(std::make_pair(V, nextValueNumber));
468           return nextValueNumber++;
469         }
470         
471         CallInst* local_cdep = cast<CallInst>(LocalDepInst);
472         
473         // FIXME: INDENT PROPERLY.
474         if (local_cdep->getCalledFunction() != C->getCalledFunction() ||
475             local_cdep->getNumOperands() != C->getNumOperands()) {
476           valueNumbering.insert(std::make_pair(V, nextValueNumber));
477           return nextValueNumber++;
478         } else if (!C->getCalledFunction()) { 
479           valueNumbering.insert(std::make_pair(V, nextValueNumber));
480           return nextValueNumber++;
481         } else {
482           for (unsigned i = 1; i < C->getNumOperands(); ++i) {
483             uint32_t c_vn = lookup_or_add(C->getOperand(i));
484             uint32_t cd_vn = lookup_or_add(local_cdep->getOperand(i));
485             if (c_vn != cd_vn) {
486               valueNumbering.insert(std::make_pair(V, nextValueNumber));
487               return nextValueNumber++;
488             }
489           }
490         
491           uint32_t v = lookup_or_add(local_cdep);
492           valueNumbering.insert(std::make_pair(V, v));
493           return v;
494         }
495       }
496       
497       
498       DenseMap<BasicBlock*, MemDepResult> deps;
499       MD->getNonLocalDependency(C, deps);
500       CallInst* cdep = 0;
501       
502       for (DenseMap<BasicBlock*, MemDepResult>
503              ::iterator I = deps.begin(), E = deps.end(); I != E; ++I) {
504         if (I->second.isNone()) {
505           valueNumbering.insert(std::make_pair(V, nextValueNumber));
506
507           return nextValueNumber++;
508         } else if (Instruction *NonLocalDepInst = I->second.getInst()) {
509           // FIXME: INDENT PROPERLY
510           // FIXME: All duplicated with non-local case.
511           if (DT->properlyDominates(I->first, C->getParent())) {
512             if (CallInst* CD = dyn_cast<CallInst>(NonLocalDepInst))
513               cdep = CD;
514             else {
515               valueNumbering.insert(std::make_pair(V, nextValueNumber));
516               return nextValueNumber++;
517             }
518           } else {
519             valueNumbering.insert(std::make_pair(V, nextValueNumber));
520             return nextValueNumber++;
521           }
522         }
523       }
524       
525       if (!cdep) {
526         valueNumbering.insert(std::make_pair(V, nextValueNumber));
527         return nextValueNumber++;
528       }
529       
530       if (cdep->getCalledFunction() != C->getCalledFunction() ||
531           cdep->getNumOperands() != C->getNumOperands()) {
532         valueNumbering.insert(std::make_pair(V, nextValueNumber));
533         return nextValueNumber++;
534       } else if (!C->getCalledFunction()) { 
535         valueNumbering.insert(std::make_pair(V, nextValueNumber));
536         return nextValueNumber++;
537       } else {
538         for (unsigned i = 1; i < C->getNumOperands(); ++i) {
539           uint32_t c_vn = lookup_or_add(C->getOperand(i));
540           uint32_t cd_vn = lookup_or_add(cdep->getOperand(i));
541           if (c_vn != cd_vn) {
542             valueNumbering.insert(std::make_pair(V, nextValueNumber));
543             return nextValueNumber++;
544           }
545         }
546         
547         uint32_t v = lookup_or_add(cdep);
548         valueNumbering.insert(std::make_pair(V, v));
549         return v;
550       }
551       
552     } else {
553       valueNumbering.insert(std::make_pair(V, nextValueNumber));
554       return nextValueNumber++;
555     }
556   } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
557     Expression e = create_expression(BO);
558     
559     DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
560     if (EI != expressionNumbering.end()) {
561       valueNumbering.insert(std::make_pair(V, EI->second));
562       return EI->second;
563     } else {
564       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
565       valueNumbering.insert(std::make_pair(V, nextValueNumber));
566       
567       return nextValueNumber++;
568     }
569   } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
570     Expression e = create_expression(C);
571     
572     DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
573     if (EI != expressionNumbering.end()) {
574       valueNumbering.insert(std::make_pair(V, EI->second));
575       return EI->second;
576     } else {
577       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
578       valueNumbering.insert(std::make_pair(V, nextValueNumber));
579       
580       return nextValueNumber++;
581     }
582   } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
583     Expression e = create_expression(U);
584     
585     DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
586     if (EI != expressionNumbering.end()) {
587       valueNumbering.insert(std::make_pair(V, EI->second));
588       return EI->second;
589     } else {
590       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
591       valueNumbering.insert(std::make_pair(V, nextValueNumber));
592       
593       return nextValueNumber++;
594     }
595   } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
596     Expression e = create_expression(U);
597     
598     DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
599     if (EI != expressionNumbering.end()) {
600       valueNumbering.insert(std::make_pair(V, EI->second));
601       return EI->second;
602     } else {
603       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
604       valueNumbering.insert(std::make_pair(V, nextValueNumber));
605       
606       return nextValueNumber++;
607     }
608   } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
609     Expression e = create_expression(U);
610     
611     DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
612     if (EI != expressionNumbering.end()) {
613       valueNumbering.insert(std::make_pair(V, EI->second));
614       return EI->second;
615     } else {
616       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
617       valueNumbering.insert(std::make_pair(V, nextValueNumber));
618       
619       return nextValueNumber++;
620     }
621   } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
622     Expression e = create_expression(U);
623     
624     DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
625     if (EI != expressionNumbering.end()) {
626       valueNumbering.insert(std::make_pair(V, EI->second));
627       return EI->second;
628     } else {
629       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
630       valueNumbering.insert(std::make_pair(V, nextValueNumber));
631       
632       return nextValueNumber++;
633     }
634   } else if (CastInst* U = dyn_cast<CastInst>(V)) {
635     Expression e = create_expression(U);
636     
637     DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
638     if (EI != expressionNumbering.end()) {
639       valueNumbering.insert(std::make_pair(V, EI->second));
640       return EI->second;
641     } else {
642       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
643       valueNumbering.insert(std::make_pair(V, nextValueNumber));
644       
645       return nextValueNumber++;
646     }
647   } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
648     Expression e = create_expression(U);
649     
650     DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
651     if (EI != expressionNumbering.end()) {
652       valueNumbering.insert(std::make_pair(V, EI->second));
653       return EI->second;
654     } else {
655       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
656       valueNumbering.insert(std::make_pair(V, nextValueNumber));
657       
658       return nextValueNumber++;
659     }
660   } else {
661     valueNumbering.insert(std::make_pair(V, nextValueNumber));
662     return nextValueNumber++;
663   }
664 }
665
666 /// lookup - Returns the value number of the specified value. Fails if
667 /// the value has not yet been numbered.
668 uint32_t ValueTable::lookup(Value* V) const {
669   DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
670   assert(VI != valueNumbering.end() && "Value not numbered?");
671   return VI->second;
672 }
673
674 /// clear - Remove all entries from the ValueTable
675 void ValueTable::clear() {
676   valueNumbering.clear();
677   expressionNumbering.clear();
678   nextValueNumber = 1;
679 }
680
681 /// erase - Remove a value from the value numbering
682 void ValueTable::erase(Value* V) {
683   valueNumbering.erase(V);
684 }
685
686 //===----------------------------------------------------------------------===//
687 //                         GVN Pass
688 //===----------------------------------------------------------------------===//
689
690 namespace {
691   struct VISIBILITY_HIDDEN ValueNumberScope {
692     ValueNumberScope* parent;
693     DenseMap<uint32_t, Value*> table;
694     
695     ValueNumberScope(ValueNumberScope* p) : parent(p) { }
696   };
697 }
698
699 namespace {
700
701   class VISIBILITY_HIDDEN GVN : public FunctionPass {
702     bool runOnFunction(Function &F);
703   public:
704     static char ID; // Pass identification, replacement for typeid
705     GVN() : FunctionPass(&ID) { }
706
707   private:
708     ValueTable VN;
709     DenseMap<BasicBlock*, ValueNumberScope*> localAvail;
710     
711     typedef DenseMap<Value*, SmallPtrSet<Instruction*, 4> > PhiMapType;
712     PhiMapType phiMap;
713     
714     
715     // This transformation requires dominator postdominator info
716     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
717       AU.addRequired<DominatorTree>();
718       AU.addRequired<MemoryDependenceAnalysis>();
719       AU.addRequired<AliasAnalysis>();
720       
721       AU.addPreserved<DominatorTree>();
722       AU.addPreserved<AliasAnalysis>();
723     }
724   
725     // Helper fuctions
726     // FIXME: eliminate or document these better
727     bool processLoad(LoadInst* L,
728                      DenseMap<Value*, LoadInst*> &lastLoad,
729                      SmallVectorImpl<Instruction*> &toErase);
730     bool processInstruction(Instruction* I,
731                             DenseMap<Value*, LoadInst*>& lastSeenLoad,
732                             SmallVectorImpl<Instruction*> &toErase);
733     bool processNonLocalLoad(LoadInst* L,
734                              SmallVectorImpl<Instruction*> &toErase);
735     bool processBlock(DomTreeNode* DTN);
736     Value *GetValueForBlock(BasicBlock *BB, LoadInst* orig,
737                             DenseMap<BasicBlock*, Value*> &Phis,
738                             bool top_level = false);
739     void dump(DenseMap<uint32_t, Value*>& d);
740     bool iterateOnFunction(Function &F);
741     Value* CollapsePhi(PHINode* p);
742     bool isSafeReplacement(PHINode* p, Instruction* inst);
743     bool performPRE(Function& F);
744     Value* lookupNumber(BasicBlock* BB, uint32_t num);
745     bool mergeBlockIntoPredecessor(BasicBlock* BB);
746     void cleanupGlobalSets();
747   };
748   
749   char GVN::ID = 0;
750 }
751
752 // createGVNPass - The public interface to this file...
753 FunctionPass *llvm::createGVNPass() { return new GVN(); }
754
755 static RegisterPass<GVN> X("gvn",
756                            "Global Value Numbering");
757
758 void GVN::dump(DenseMap<uint32_t, Value*>& d) {
759   printf("{\n");
760   for (DenseMap<uint32_t, Value*>::iterator I = d.begin(),
761        E = d.end(); I != E; ++I) {
762       printf("%d\n", I->first);
763       I->second->dump();
764   }
765   printf("}\n");
766 }
767
768 Value* GVN::CollapsePhi(PHINode* p) {
769   DominatorTree &DT = getAnalysis<DominatorTree>();
770   Value* constVal = p->hasConstantValue();
771   
772   if (!constVal) return 0;
773   
774   Instruction* inst = dyn_cast<Instruction>(constVal);
775   if (!inst)
776     return constVal;
777     
778   if (DT.dominates(inst, p))
779     if (isSafeReplacement(p, inst))
780       return inst;
781   return 0;
782 }
783
784 bool GVN::isSafeReplacement(PHINode* p, Instruction* inst) {
785   if (!isa<PHINode>(inst))
786     return true;
787   
788   for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end();
789        UI != E; ++UI)
790     if (PHINode* use_phi = dyn_cast<PHINode>(UI))
791       if (use_phi->getParent() == inst->getParent())
792         return false;
793   
794   return true;
795 }
796
797 /// GetValueForBlock - Get the value to use within the specified basic block.
798 /// available values are in Phis.
799 Value *GVN::GetValueForBlock(BasicBlock *BB, LoadInst* orig,
800                              DenseMap<BasicBlock*, Value*> &Phis,
801                              bool top_level) { 
802                                  
803   // If we have already computed this value, return the previously computed val.
804   DenseMap<BasicBlock*, Value*>::iterator V = Phis.find(BB);
805   if (V != Phis.end() && !top_level) return V->second;
806   
807   // If the block is unreachable, just return undef, since this path
808   // can't actually occur at runtime.
809   if (!getAnalysis<DominatorTree>().isReachableFromEntry(BB))
810     return Phis[BB] = UndefValue::get(orig->getType());
811   
812   BasicBlock* singlePred = BB->getSinglePredecessor();
813   if (singlePred) {
814     Value *ret = GetValueForBlock(singlePred, orig, Phis);
815     Phis[BB] = ret;
816     return ret;
817   }
818   
819   // Otherwise, the idom is the loop, so we need to insert a PHI node.  Do so
820   // now, then get values to fill in the incoming values for the PHI.
821   PHINode *PN = PHINode::Create(orig->getType(), orig->getName()+".rle",
822                                 BB->begin());
823   PN->reserveOperandSpace(std::distance(pred_begin(BB), pred_end(BB)));
824   
825   if (Phis.count(BB) == 0)
826     Phis.insert(std::make_pair(BB, PN));
827   
828   // Fill in the incoming values for the block.
829   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
830     Value* val = GetValueForBlock(*PI, orig, Phis);
831     PN->addIncoming(val, *PI);
832   }
833   
834   AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
835   AA.copyValue(orig, PN);
836   
837   // Attempt to collapse PHI nodes that are trivially redundant
838   Value* v = CollapsePhi(PN);
839   if (!v) {
840     // Cache our phi construction results
841     phiMap[orig->getPointerOperand()].insert(PN);
842     return PN;
843   }
844     
845   MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
846
847   MD.removeInstruction(PN);
848   PN->replaceAllUsesWith(v);
849
850   for (DenseMap<BasicBlock*, Value*>::iterator I = Phis.begin(),
851        E = Phis.end(); I != E; ++I)
852     if (I->second == PN)
853       I->second = v;
854
855   PN->eraseFromParent();
856
857   Phis[BB] = v;
858   return v;
859 }
860
861 /// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
862 /// non-local by performing PHI construction.
863 bool GVN::processNonLocalLoad(LoadInst* L,
864                               SmallVectorImpl<Instruction*> &toErase) {
865   MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
866   
867   // Find the non-local dependencies of the load
868   DenseMap<BasicBlock*, MemDepResult> deps;
869   MD.getNonLocalDependency(L, deps);
870   
871   // If we had to process more than one hundred blocks to find the
872   // dependencies, this load isn't worth worrying about.  Optimizing
873   // it will be too expensive.
874   if (deps.size() > 100)
875     return false;
876   
877   DenseMap<BasicBlock*, Value*> repl;
878   
879   // Filter out useless results (non-locals, etc)
880   for (DenseMap<BasicBlock*, MemDepResult>::iterator I = deps.begin(),
881        E = deps.end(); I != E; ++I) {
882     if (I->second.isNone())
883       return false;
884   
885     if (I->second.isNonLocal())
886       continue;
887   
888     if (StoreInst* S = dyn_cast<StoreInst>(I->second.getInst())) {
889       if (S->getPointerOperand() != L->getPointerOperand())
890         return false;
891       repl[I->first] = S->getOperand(0);
892     } else if (LoadInst* LD = dyn_cast<LoadInst>(I->second.getInst())) {
893       if (LD->getPointerOperand() != L->getPointerOperand())
894         return false;
895       repl[I->first] = LD;
896     } else {
897       return false;
898     }
899   }
900   
901   // Use cached PHI construction information from previous runs
902   SmallPtrSet<Instruction*, 4>& p = phiMap[L->getPointerOperand()];
903   for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
904        I != E; ++I) {
905     if ((*I)->getParent() == L->getParent()) {
906       MD.removeInstruction(L);
907       L->replaceAllUsesWith(*I);
908       toErase.push_back(L);
909       NumGVNLoad++;
910       return true;
911     }
912     
913     repl.insert(std::make_pair((*I)->getParent(), *I));
914   }
915   
916   // Perform PHI construction
917   SmallPtrSet<BasicBlock*, 4> visited;
918   Value* v = GetValueForBlock(L->getParent(), L, repl, true);
919   
920   MD.removeInstruction(L);
921   L->replaceAllUsesWith(v);
922   toErase.push_back(L);
923   NumGVNLoad++;
924
925   return true;
926 }
927
928 /// processLoad - Attempt to eliminate a load, first by eliminating it
929 /// locally, and then attempting non-local elimination if that fails.
930 bool GVN::processLoad(LoadInst *L, DenseMap<Value*, LoadInst*> &lastLoad,
931                       SmallVectorImpl<Instruction*> &toErase) {
932   if (L->isVolatile()) {
933     lastLoad[L->getPointerOperand()] = L;
934     return false;
935   }
936   
937   Value* pointer = L->getPointerOperand();
938   LoadInst*& last = lastLoad[pointer];
939   
940   // ... to a pointer that has been loaded from before...
941   MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
942   bool removedNonLocal = false;
943   MemDepResult dep = MD.getDependency(L);
944   if (dep.isNonLocal() &&
945       L->getParent() != &L->getParent()->getParent()->getEntryBlock()) {
946     removedNonLocal = processNonLocalLoad(L, toErase);
947     
948     if (!removedNonLocal)
949       last = L;
950     
951     return removedNonLocal;
952   }
953   
954   
955   bool deletedLoad = false;
956   
957   // Walk up the dependency chain until we either find
958   // a dependency we can use, or we can't walk any further
959   while (Instruction *DepInst = dep.getInst()) {
960     // ... that depends on a store ...
961     if (StoreInst* S = dyn_cast<StoreInst>(DepInst)) {
962       if (S->getPointerOperand() == pointer) {
963         // Remove it!
964         MD.removeInstruction(L);
965         
966         L->replaceAllUsesWith(S->getOperand(0));
967         toErase.push_back(L);
968         deletedLoad = true;
969         NumGVNLoad++;
970       }
971       
972       // Whether we removed it or not, we can't
973       // go any further
974       break;
975     } else if (!isa<LoadInst>(DepInst)) {
976       // Only want to handle loads below.
977       break;
978     } else if (!last) {
979       // If we don't depend on a store, and we haven't
980       // been loaded before, bail.
981       break;
982     } else if (DepInst == last) {
983       // Remove it!
984       MD.removeInstruction(L);
985       
986       L->replaceAllUsesWith(last);
987       toErase.push_back(L);
988       deletedLoad = true;
989       NumGVNLoad++;
990         
991       break;
992     } else {
993       dep = MD.getDependency(L, DepInst);
994     }
995   }
996
997   if (AllocationInst *DepAI = dyn_cast_or_null<AllocationInst>(dep.getInst())) {
998     // Check that this load is actually from the
999     // allocation we found
1000     if (L->getOperand(0)->getUnderlyingObject() == DepAI) {
1001       // If this load depends directly on an allocation, there isn't
1002       // anything stored there; therefore, we can optimize this load
1003       // to undef.
1004       MD.removeInstruction(L);
1005
1006       L->replaceAllUsesWith(UndefValue::get(L->getType()));
1007       toErase.push_back(L);
1008       deletedLoad = true;
1009       NumGVNLoad++;
1010     }
1011   }
1012
1013   if (!deletedLoad)
1014     last = L;
1015   
1016   return deletedLoad;
1017 }
1018
1019 Value* GVN::lookupNumber(BasicBlock* BB, uint32_t num) {
1020   DenseMap<BasicBlock*, ValueNumberScope*>::iterator I = localAvail.find(BB);
1021   if (I == localAvail.end())
1022     return 0;
1023   
1024   ValueNumberScope* locals = I->second;
1025   
1026   while (locals) {
1027     DenseMap<uint32_t, Value*>::iterator I = locals->table.find(num);
1028     if (I != locals->table.end())
1029       return I->second;
1030     else
1031       locals = locals->parent;
1032   }
1033   
1034   return 0;
1035 }
1036
1037 /// processInstruction - When calculating availability, handle an instruction
1038 /// by inserting it into the appropriate sets
1039 bool GVN::processInstruction(Instruction *I,
1040                              DenseMap<Value*, LoadInst*> &lastSeenLoad,
1041                              SmallVectorImpl<Instruction*> &toErase) {
1042   if (LoadInst* L = dyn_cast<LoadInst>(I)) {
1043     bool changed = processLoad(L, lastSeenLoad, toErase);
1044     
1045     if (!changed) {
1046       unsigned num = VN.lookup_or_add(L);
1047       localAvail[I->getParent()]->table.insert(std::make_pair(num, L));
1048     }
1049     
1050     return changed;
1051   }
1052   
1053   uint32_t nextNum = VN.getNextUnusedValueNumber();
1054   unsigned num = VN.lookup_or_add(I);
1055   
1056   // Allocations are always uniquely numbered, so we can save time and memory
1057   // by fast failing them.
1058   if (isa<AllocationInst>(I) || isa<TerminatorInst>(I)) {
1059     localAvail[I->getParent()]->table.insert(std::make_pair(num, I));
1060     return false;
1061   }
1062   
1063   // Collapse PHI nodes
1064   if (PHINode* p = dyn_cast<PHINode>(I)) {
1065     Value* constVal = CollapsePhi(p);
1066     
1067     if (constVal) {
1068       for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end();
1069            PI != PE; ++PI)
1070         if (PI->second.count(p))
1071           PI->second.erase(p);
1072         
1073       p->replaceAllUsesWith(constVal);
1074       toErase.push_back(p);
1075     } else {
1076       localAvail[I->getParent()]->table.insert(std::make_pair(num, I));
1077     }
1078   
1079   // If the number we were assigned was a brand new VN, then we don't
1080   // need to do a lookup to see if the number already exists
1081   // somewhere in the domtree: it can't!
1082   } else if (num == nextNum) {
1083     localAvail[I->getParent()]->table.insert(std::make_pair(num, I));
1084     
1085   // Perform value-number based elimination
1086   } else if (Value* repl = lookupNumber(I->getParent(), num)) {
1087     // Remove it!
1088     MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1089     MD.removeInstruction(I);
1090     
1091     VN.erase(I);
1092     I->replaceAllUsesWith(repl);
1093     toErase.push_back(I);
1094     return true;
1095   } else {
1096     localAvail[I->getParent()]->table.insert(std::make_pair(num, I));
1097   }
1098   
1099   return false;
1100 }
1101
1102 // GVN::runOnFunction - This is the main transformation entry point for a
1103 // function.
1104 //
1105 bool GVN::runOnFunction(Function& F) {
1106   VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
1107   VN.setMemDep(&getAnalysis<MemoryDependenceAnalysis>());
1108   VN.setDomTree(&getAnalysis<DominatorTree>());
1109   
1110   bool changed = false;
1111   bool shouldContinue = true;
1112   
1113   // Merge unconditional branches, allowing PRE to catch more
1114   // optimization opportunities.
1115   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) {
1116     BasicBlock* BB = FI;
1117     ++FI;
1118     bool removedBlock = MergeBlockIntoPredecessor(BB, this);
1119     if (removedBlock) NumGVNBlocks++;
1120     
1121     changed |= removedBlock;
1122   }
1123   
1124   while (shouldContinue) {
1125     shouldContinue = iterateOnFunction(F);
1126     changed |= shouldContinue;
1127   }
1128   
1129   if (EnablePRE) {
1130     bool PREChanged = true;
1131     while (PREChanged) {
1132       PREChanged = performPRE(F);
1133       changed |= PREChanged;
1134     }
1135   }
1136
1137   cleanupGlobalSets();
1138
1139   return changed;
1140 }
1141
1142
1143 bool GVN::processBlock(DomTreeNode* DTN) {
1144   BasicBlock* BB = DTN->getBlock();
1145
1146   SmallVector<Instruction*, 8> toErase;
1147   DenseMap<Value*, LoadInst*> lastSeenLoad;
1148   bool changed_function = false;
1149   
1150   if (DTN->getIDom())
1151     localAvail[BB] =
1152                   new ValueNumberScope(localAvail[DTN->getIDom()->getBlock()]);
1153   else
1154     localAvail[BB] = new ValueNumberScope(0);
1155   
1156   for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1157        BI != BE;) {
1158     changed_function |= processInstruction(BI, lastSeenLoad, toErase);
1159     if (toErase.empty()) {
1160       ++BI;
1161       continue;
1162     }
1163     
1164     // If we need some instructions deleted, do it now.
1165     NumGVNInstr += toErase.size();
1166     
1167     // Avoid iterator invalidation.
1168     bool AtStart = BI == BB->begin();
1169     if (!AtStart)
1170       --BI;
1171
1172     for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
1173          E = toErase.end(); I != E; ++I)
1174       (*I)->eraseFromParent();
1175
1176     if (AtStart)
1177       BI = BB->begin();
1178     else
1179       ++BI;
1180     
1181     toErase.clear();
1182   }
1183   
1184   return changed_function;
1185 }
1186
1187 /// performPRE - Perform a purely local form of PRE that looks for diamond
1188 /// control flow patterns and attempts to perform simple PRE at the join point.
1189 bool GVN::performPRE(Function& F) {
1190   bool changed = false;
1191   SmallVector<std::pair<TerminatorInst*, unsigned>, 4> toSplit;
1192   for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
1193        DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
1194     BasicBlock* CurrentBlock = *DI;
1195     
1196     // Nothing to PRE in the entry block.
1197     if (CurrentBlock == &F.getEntryBlock()) continue;
1198     
1199     for (BasicBlock::iterator BI = CurrentBlock->begin(),
1200          BE = CurrentBlock->end(); BI != BE; ) {
1201       if (isa<AllocationInst>(BI) || isa<TerminatorInst>(BI) ||
1202           isa<PHINode>(BI) || BI->mayReadFromMemory() ||
1203           BI->mayWriteToMemory()) {
1204         BI++;
1205         continue;
1206       }
1207       
1208       uint32_t valno = VN.lookup(BI);
1209       
1210       // Look for the predecessors for PRE opportunities.  We're
1211       // only trying to solve the basic diamond case, where
1212       // a value is computed in the successor and one predecessor,
1213       // but not the other.  We also explicitly disallow cases
1214       // where the successor is its own predecessor, because they're
1215       // more complicated to get right.
1216       unsigned numWith = 0;
1217       unsigned numWithout = 0;
1218       BasicBlock* PREPred = 0;
1219       DenseMap<BasicBlock*, Value*> predMap;
1220       for (pred_iterator PI = pred_begin(CurrentBlock),
1221            PE = pred_end(CurrentBlock); PI != PE; ++PI) {
1222         // We're not interested in PRE where the block is its
1223         // own predecessor, on in blocks with predecessors
1224         // that are not reachable.
1225         if (*PI == CurrentBlock) {
1226           numWithout = 2;
1227           break;
1228         } else if (!localAvail.count(*PI))  {
1229           numWithout = 2;
1230           break;
1231         }
1232         
1233         DenseMap<uint32_t, Value*>::iterator predV = 
1234                                             localAvail[*PI]->table.find(valno);
1235         if (predV == localAvail[*PI]->table.end()) {
1236           PREPred = *PI;
1237           numWithout++;
1238         } else if (predV->second == BI) {
1239           numWithout = 2;
1240         } else {
1241           predMap[*PI] = predV->second;
1242           numWith++;
1243         }
1244       }
1245       
1246       // Don't do PRE when it might increase code size, i.e. when
1247       // we would need to insert instructions in more than one pred.
1248       if (numWithout != 1 || numWith == 0) {
1249         BI++;
1250         continue;
1251       }
1252       
1253       // We can't do PRE safely on a critical edge, so instead we schedule
1254       // the edge to be split and perform the PRE the next time we iterate
1255       // on the function.
1256       unsigned succNum = 0;
1257       for (unsigned i = 0, e = PREPred->getTerminator()->getNumSuccessors();
1258            i != e; ++i)
1259         if (PREPred->getTerminator()->getSuccessor(i) == CurrentBlock) {
1260           succNum = i;
1261           break;
1262         }
1263         
1264       if (isCriticalEdge(PREPred->getTerminator(), succNum)) {
1265         toSplit.push_back(std::make_pair(PREPred->getTerminator(), succNum));
1266         changed = true;
1267         BI++;
1268         continue;
1269       }
1270       
1271       // Instantiate the expression the in predecessor that lacked it.
1272       // Because we are going top-down through the block, all value numbers
1273       // will be available in the predecessor by the time we need them.  Any
1274       // that weren't original present will have been instantiated earlier
1275       // in this loop.
1276       Instruction* PREInstr = BI->clone();
1277       bool success = true;
1278       for (unsigned i = 0; i < BI->getNumOperands(); ++i) {
1279         Value* op = BI->getOperand(i);
1280         if (isa<Argument>(op) || isa<Constant>(op) || isa<GlobalValue>(op))
1281           PREInstr->setOperand(i, op);
1282         else {
1283           Value* V = lookupNumber(PREPred, VN.lookup(op));
1284           if (!V) {
1285             success = false;
1286             break;
1287           } else
1288             PREInstr->setOperand(i, V);
1289         }
1290       }
1291       
1292       // Fail out if we encounter an operand that is not available in
1293       // the PRE predecessor.  This is typically because of loads which 
1294       // are not value numbered precisely.
1295       if (!success) {
1296         delete PREInstr;
1297         BI++;
1298         continue;
1299       }
1300       
1301       PREInstr->insertBefore(PREPred->getTerminator());
1302       PREInstr->setName(BI->getName() + ".pre");
1303       predMap[PREPred] = PREInstr;
1304       VN.add(PREInstr, valno);
1305       NumGVNPRE++;
1306       
1307       // Update the availability map to include the new instruction.
1308       localAvail[PREPred]->table.insert(std::make_pair(valno, PREInstr));
1309       
1310       // Create a PHI to make the value available in this block.
1311       PHINode* Phi = PHINode::Create(BI->getType(),
1312                                      BI->getName() + ".pre-phi",
1313                                      CurrentBlock->begin());
1314       for (pred_iterator PI = pred_begin(CurrentBlock),
1315            PE = pred_end(CurrentBlock); PI != PE; ++PI)
1316         Phi->addIncoming(predMap[*PI], *PI);
1317       
1318       VN.add(Phi, valno);
1319       localAvail[CurrentBlock]->table[valno] = Phi;
1320       
1321       BI->replaceAllUsesWith(Phi);
1322       VN.erase(BI);
1323       
1324       Instruction* erase = BI;
1325       BI++;
1326       erase->eraseFromParent();
1327       
1328       changed = true;
1329     }
1330   }
1331   
1332   for (SmallVector<std::pair<TerminatorInst*, unsigned>, 4>::iterator
1333        I = toSplit.begin(), E = toSplit.end(); I != E; ++I)
1334     SplitCriticalEdge(I->first, I->second, this);
1335   
1336   return changed || toSplit.size();
1337 }
1338
1339 // iterateOnFunction - Executes one iteration of GVN
1340 bool GVN::iterateOnFunction(Function &F) {
1341   DominatorTree &DT = getAnalysis<DominatorTree>();
1342
1343   cleanupGlobalSets();
1344
1345   // Top-down walk of the dominator tree
1346   bool changed = false;
1347   for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1348        DE = df_end(DT.getRootNode()); DI != DE; ++DI)
1349     changed |= processBlock(*DI);
1350   
1351   return changed;
1352 }
1353
1354 void GVN::cleanupGlobalSets() {
1355   VN.clear();
1356   phiMap.clear();
1357
1358   for (DenseMap<BasicBlock*, ValueNumberScope*>::iterator
1359        I = localAvail.begin(), E = localAvail.end(); I != E; ++I)
1360     delete I->second;
1361   localAvail.clear();
1362 }