41a23ed6c7cf2123cc470e41d354b1d309862408
[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   AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
861   AA.copyValue(orig, PN);
862   
863   // Attempt to collapse PHI nodes that are trivially redundant
864   Value* v = CollapsePhi(PN);
865   if (v) {
866     MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
867
868     MD.removeInstruction(PN);
869     PN->replaceAllUsesWith(v);
870
871     for (DenseMap<BasicBlock*, Value*>::iterator I = Phis.begin(),
872          E = Phis.end(); I != E; ++I)
873       if (I->second == PN)
874         I->second = v;
875
876     PN->eraseFromParent();
877
878     Phis[BB] = v;
879
880     return v;
881   }
882
883   // Cache our phi construction results
884   phiMap[orig->getPointerOperand()].insert(PN);
885   return PN;
886 }
887
888 /// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
889 /// non-local by performing PHI construction.
890 bool GVN::processNonLocalLoad(LoadInst* L,
891                               SmallVector<Instruction*, 4>& toErase) {
892   MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
893   
894   // Find the non-local dependencies of the load
895   DenseMap<BasicBlock*, Value*> deps;
896   MD.getNonLocalDependency(L, deps);
897   
898   DenseMap<BasicBlock*, Value*> repl;
899   
900   // Filter out useless results (non-locals, etc)
901   for (DenseMap<BasicBlock*, Value*>::iterator I = deps.begin(), E = deps.end();
902        I != E; ++I)
903     if (I->second == MemoryDependenceAnalysis::None) {
904       return false;
905     } else if (I->second == MemoryDependenceAnalysis::NonLocal) {
906       continue;
907     } else if (StoreInst* S = dyn_cast<StoreInst>(I->second)) {
908       if (S->getPointerOperand() == L->getPointerOperand())
909         repl[I->first] = S->getOperand(0);
910       else
911         return false;
912     } else if (LoadInst* LD = dyn_cast<LoadInst>(I->second)) {
913       if (LD->getPointerOperand() == L->getPointerOperand())
914         repl[I->first] = LD;
915       else
916         return false;
917     } else {
918       return false;
919     }
920   
921   // Use cached PHI construction information from previous runs
922   SmallPtrSet<Instruction*, 4>& p = phiMap[L->getPointerOperand()];
923   for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
924        I != E; ++I) {
925     if ((*I)->getParent() == L->getParent()) {
926       MD.removeInstruction(L);
927       L->replaceAllUsesWith(*I);
928       toErase.push_back(L);
929       NumGVNLoad++;
930       
931       return true;
932     } else {
933       repl.insert(std::make_pair((*I)->getParent(), *I));
934     }
935   }
936   
937   // Perform PHI construction
938   SmallPtrSet<BasicBlock*, 4> visited;
939   Value* v = GetValueForBlock(L->getParent(), L, repl, true);
940   
941   MD.removeInstruction(L);
942   L->replaceAllUsesWith(v);
943   toErase.push_back(L);
944   NumGVNLoad++;
945
946   return true;
947 }
948
949 /// processLoad - Attempt to eliminate a load, first by eliminating it
950 /// locally, and then attempting non-local elimination if that fails.
951 bool GVN::processLoad(LoadInst* L,
952                          DenseMap<Value*, LoadInst*>& lastLoad,
953                          SmallVector<Instruction*, 4>& toErase) {
954   if (L->isVolatile()) {
955     lastLoad[L->getPointerOperand()] = L;
956     return false;
957   }
958   
959   Value* pointer = L->getPointerOperand();
960   LoadInst*& last = lastLoad[pointer];
961   
962   // ... to a pointer that has been loaded from before...
963   MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
964   bool removedNonLocal = false;
965   Instruction* dep = MD.getDependency(L);
966   if (dep == MemoryDependenceAnalysis::NonLocal &&
967       L->getParent() != &L->getParent()->getParent()->getEntryBlock()) {
968     removedNonLocal = processNonLocalLoad(L, toErase);
969     
970     if (!removedNonLocal)
971       last = L;
972     
973     return removedNonLocal;
974   }
975   
976   
977   bool deletedLoad = false;
978   
979   // Walk up the dependency chain until we either find
980   // a dependency we can use, or we can't walk any further
981   while (dep != MemoryDependenceAnalysis::None &&
982          dep != MemoryDependenceAnalysis::NonLocal &&
983          (isa<LoadInst>(dep) || isa<StoreInst>(dep))) {
984     // ... that depends on a store ...
985     if (StoreInst* S = dyn_cast<StoreInst>(dep)) {
986       if (S->getPointerOperand() == pointer) {
987         // Remove it!
988         MD.removeInstruction(L);
989         
990         L->replaceAllUsesWith(S->getOperand(0));
991         toErase.push_back(L);
992         deletedLoad = true;
993         NumGVNLoad++;
994       }
995       
996       // Whether we removed it or not, we can't
997       // go any further
998       break;
999     } else if (!last) {
1000       // If we don't depend on a store, and we haven't
1001       // been loaded before, bail.
1002       break;
1003     } else if (dep == last) {
1004       // Remove it!
1005       MD.removeInstruction(L);
1006       
1007       L->replaceAllUsesWith(last);
1008       toErase.push_back(L);
1009       deletedLoad = true;
1010       NumGVNLoad++;
1011         
1012       break;
1013     } else {
1014       dep = MD.getDependency(L, dep);
1015     }
1016   }
1017
1018   if (dep != MemoryDependenceAnalysis::None &&
1019       dep != MemoryDependenceAnalysis::NonLocal &&
1020       isa<AllocationInst>(dep)) {
1021     // Check that this load is actually from the
1022     // allocation we found
1023     Value* v = L->getOperand(0);
1024     while (true) {
1025       if (BitCastInst *BC = dyn_cast<BitCastInst>(v))
1026         v = BC->getOperand(0);
1027       else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(v))
1028         v = GEP->getOperand(0);
1029       else
1030         break;
1031     }
1032     if (v == dep) {
1033       // If this load depends directly on an allocation, there isn't
1034       // anything stored there; therefore, we can optimize this load
1035       // to undef.
1036       MD.removeInstruction(L);
1037
1038       L->replaceAllUsesWith(UndefValue::get(L->getType()));
1039       toErase.push_back(L);
1040       deletedLoad = true;
1041       NumGVNLoad++;
1042     }
1043   }
1044
1045   if (!deletedLoad)
1046     last = L;
1047   
1048   return deletedLoad;
1049 }
1050
1051 /// processMemCpy - perform simplication of memcpy's.  If we have memcpy A which
1052 /// copies X to Y, and memcpy B which copies Y to Z, then we can rewrite B to be
1053 /// a memcpy from X to Z (or potentially a memmove, depending on circumstances).
1054 ///  This allows later passes to remove the first memcpy altogether.
1055 bool GVN::processMemCpy(MemCpyInst* M,
1056                         SmallVector<Instruction*, 4>& toErase) {
1057   MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1058   
1059   // First, we have to check that the dependency is another memcpy
1060   Instruction* dep = MD.getDependency(M);
1061   if  (dep == MemoryDependenceAnalysis::None ||
1062        dep == MemoryDependenceAnalysis::NonLocal ||
1063        !isa<MemCpyInst>(dep))
1064     return false;
1065   
1066   // We can only transforms memcpy's where the dest of one is the source of the
1067   // other
1068   MemCpyInst* MDep = cast<MemCpyInst>(dep);
1069   if (M->getSource() != MDep->getDest())
1070     return false;
1071   
1072   // Second, the length of the memcpy's must be the same, or the preceeding one
1073   // must be larger than the following one.
1074   ConstantInt* C1 = dyn_cast<ConstantInt>(MDep->getLength());
1075   ConstantInt* C2 = dyn_cast<ConstantInt>(M->getLength());
1076   if (!C1 || !C2)
1077     return false;
1078   
1079   uint64_t CpySize = C1->getValue().getZExtValue();
1080   uint64_t DepSize = C2->getValue().getZExtValue();
1081   
1082   if (DepSize < CpySize)
1083     return false;
1084   
1085   // Finally, we have to make sure that the dest of the second does not
1086   // alias the source of the first
1087   AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
1088   if (AA.alias(M->getRawDest(), CpySize, MDep->getRawSource(), DepSize) !=
1089       AliasAnalysis::NoAlias)
1090     return false;
1091   else if (AA.alias(M->getRawDest(), CpySize, M->getRawSource(), CpySize) !=
1092            AliasAnalysis::NoAlias)
1093     return false;
1094   else if (AA.alias(MDep->getRawDest(), DepSize, MDep->getRawSource(), DepSize)
1095            != AliasAnalysis::NoAlias)
1096     return false;
1097   
1098   // If all checks passed, then we can transform these memcpy's
1099   bool is32bit = M->getIntrinsicID() == Intrinsic::memcpy_i32;
1100   Function* MemMoveFun = Intrinsic::getDeclaration(
1101                                  M->getParent()->getParent()->getParent(),
1102                                  is32bit ? Intrinsic::memcpy_i32 : 
1103                                            Intrinsic::memcpy_i64);
1104     
1105   std::vector<Value*> args;
1106   args.push_back(M->getRawDest());
1107   args.push_back(MDep->getRawSource());
1108   args.push_back(M->getLength());
1109   args.push_back(M->getAlignment());
1110   
1111   CallInst* C = new CallInst(MemMoveFun, args.begin(), args.end(), "", M);
1112   
1113   if (MD.getDependency(C) == MDep) {
1114     MD.dropInstruction(M);
1115     toErase.push_back(M);
1116     return true;
1117   } else {
1118     MD.removeInstruction(C);
1119     toErase.push_back(C);
1120     return false;
1121   }
1122 }
1123
1124 /// processInstruction - When calculating availability, handle an instruction
1125 /// by inserting it into the appropriate sets
1126 bool GVN::processInstruction(Instruction* I,
1127                                 ValueNumberedSet& currAvail,
1128                                 DenseMap<Value*, LoadInst*>& lastSeenLoad,
1129                                 SmallVector<Instruction*, 4>& toErase) {
1130   if (LoadInst* L = dyn_cast<LoadInst>(I)) {
1131     return processLoad(L, lastSeenLoad, toErase);
1132   } else if (MemCpyInst* M = dyn_cast<MemCpyInst>(I)) {
1133     return processMemCpy(M, toErase);
1134   }
1135   
1136   unsigned num = VN.lookup_or_add(I);
1137   
1138   // Collapse PHI nodes
1139   if (PHINode* p = dyn_cast<PHINode>(I)) {
1140     Value* constVal = CollapsePhi(p);
1141     
1142     if (constVal) {
1143       for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end();
1144            PI != PE; ++PI)
1145         if (PI->second.count(p))
1146           PI->second.erase(p);
1147         
1148       p->replaceAllUsesWith(constVal);
1149       toErase.push_back(p);
1150     }
1151   // Perform value-number based elimination
1152   } else if (currAvail.test(num)) {
1153     Value* repl = find_leader(currAvail, num);
1154     
1155     if (CallInst* CI = dyn_cast<CallInst>(I)) {
1156       AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
1157       if (!AA.doesNotAccessMemory(CI)) {
1158         MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1159         if (cast<Instruction>(repl)->getParent() != CI->getParent() ||
1160             MD.getDependency(CI) != MD.getDependency(cast<CallInst>(repl))) {
1161           // There must be an intervening may-alias store, so nothing from
1162           // this point on will be able to be replaced with the preceding call
1163           currAvail.erase(repl);
1164           currAvail.insert(I);
1165           
1166           return false;
1167         }
1168       }
1169     }
1170     
1171     // Remove it!
1172     MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1173     MD.removeInstruction(I);
1174     
1175     VN.erase(I);
1176     I->replaceAllUsesWith(repl);
1177     toErase.push_back(I);
1178     return true;
1179   } else if (!I->isTerminator()) {
1180     currAvail.set(num);
1181     currAvail.insert(I);
1182   }
1183   
1184   return false;
1185 }
1186
1187 // GVN::runOnFunction - This is the main transformation entry point for a
1188 // function.
1189 //
1190 bool GVN::runOnFunction(Function& F) {
1191   VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
1192   
1193   bool changed = false;
1194   bool shouldContinue = true;
1195   
1196   while (shouldContinue) {
1197     shouldContinue = iterateOnFunction(F);
1198     changed |= shouldContinue;
1199   }
1200   
1201   return changed;
1202 }
1203
1204
1205 // GVN::iterateOnFunction - Executes one iteration of GVN
1206 bool GVN::iterateOnFunction(Function &F) {
1207   // Clean out global sets from any previous functions
1208   VN.clear();
1209   availableOut.clear();
1210   phiMap.clear();
1211  
1212   bool changed_function = false;
1213   
1214   DominatorTree &DT = getAnalysis<DominatorTree>();   
1215   
1216   SmallVector<Instruction*, 4> toErase;
1217   
1218   // Top-down walk of the dominator tree
1219   for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1220          E = df_end(DT.getRootNode()); DI != E; ++DI) {
1221     
1222     // Get the set to update for this block
1223     ValueNumberedSet& currAvail = availableOut[DI->getBlock()];     
1224     DenseMap<Value*, LoadInst*> lastSeenLoad;
1225     
1226     BasicBlock* BB = DI->getBlock();
1227   
1228     // A block inherits AVAIL_OUT from its dominator
1229     if (DI->getIDom() != 0)
1230       currAvail = availableOut[DI->getIDom()->getBlock()];
1231
1232     for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1233          BI != BE; ) {
1234       changed_function |= processInstruction(BI, currAvail,
1235                                              lastSeenLoad, toErase);
1236       
1237       NumGVNInstr += toErase.size();
1238       
1239       // Avoid iterator invalidation
1240       ++BI;
1241
1242       for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
1243            E = toErase.end(); I != E; ++I) {
1244         (*I)->eraseFromParent();
1245       }
1246
1247       toErase.clear();
1248     }
1249   }
1250   
1251   return changed_function;
1252 }