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