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