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