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