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