Improve a hotspot that was making build_sets() slower by calling lookup() too
[oota-llvm.git] / lib / Transforms / Scalar / GVNPRE.cpp
1 //===- GVNPRE.cpp - Eliminate redundant values and expressions ------------===//
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 a hybrid of global value numbering and partial redundancy
11 // elimination, known as GVN-PRE.  It performs partial redundancy elimination on
12 // values, rather than lexical expressions, allowing a more comprehensive view 
13 // the optimization.  It replaces redundant values with uses of earlier 
14 // occurences of the same value.  While this is beneficial in that it eliminates
15 // unneeded computation, it also increases register pressure by creating large
16 // live ranges, and should be used with caution on platforms that are very 
17 // sensitive to register pressure.
18 //
19 //===----------------------------------------------------------------------===//
20
21 #define DEBUG_TYPE "gvnpre"
22 #include "llvm/Value.h"
23 #include "llvm/Transforms/Scalar.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Function.h"
26 #include "llvm/DerivedTypes.h"
27 #include "llvm/Analysis/Dominators.h"
28 #include "llvm/ADT/BitVector.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/DepthFirstIterator.h"
31 #include "llvm/ADT/PostOrderIterator.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
35 #include "llvm/Support/CFG.h"
36 #include "llvm/Support/Compiler.h"
37 #include "llvm/Support/Debug.h"
38 #include <algorithm>
39 #include <deque>
40 #include <map>
41 #include <vector>
42 #include <set>
43 using namespace llvm;
44
45 //===----------------------------------------------------------------------===//
46 //                         ValueTable Class
47 //===----------------------------------------------------------------------===//
48
49 /// This class holds the mapping between values and value numbers.  It is used
50 /// as an efficient mechanism to determine the expression-wise equivalence of
51 /// two values.
52
53 namespace {
54   class VISIBILITY_HIDDEN ValueTable {
55     public:
56       struct Expression {
57         enum ExpressionOpcode { ADD, SUB, MUL, UDIV, SDIV, FDIV, UREM, SREM, 
58                               FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ, 
59                               ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE, 
60                               ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ, 
61                               FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE, 
62                               FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE, 
63                               FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
64                               SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
65                               FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT, 
66                               PTRTOINT, INTTOPTR, BITCAST, GEP};
67     
68         ExpressionOpcode opcode;
69         const Type* type;
70         uint32_t firstVN;
71         uint32_t secondVN;
72         uint32_t thirdVN;
73         std::vector<uint32_t> varargs;
74       
75         bool operator< (const Expression& other) const {
76           if (opcode < other.opcode)
77             return true;
78           else if (opcode > other.opcode)
79             return false;
80           else if (type < other.type)
81             return true;
82           else if (type > other.type)
83             return false;
84           else if (firstVN < other.firstVN)
85             return true;
86           else if (firstVN > other.firstVN)
87             return false;
88           else if (secondVN < other.secondVN)
89             return true;
90           else if (secondVN > other.secondVN)
91             return false;
92           else if (thirdVN < other.thirdVN)
93             return true;
94           else if (thirdVN > other.thirdVN)
95             return false;
96           else {
97             if (varargs.size() < other.varargs.size())
98               return true;
99             else if (varargs.size() > other.varargs.size())
100               return false;
101             
102             for (size_t i = 0; i < varargs.size(); ++i)
103               if (varargs[i] < other.varargs[i])
104                 return true;
105               else if (varargs[i] > other.varargs[i])
106                 return false;
107           
108             return false;
109           }
110         }
111       };
112     
113     private:
114       DenseMap<Value*, uint32_t> valueNumbering;
115       std::map<Expression, uint32_t> expressionNumbering;
116   
117       uint32_t nextValueNumber;
118     
119       Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
120       Expression::ExpressionOpcode getOpcode(CmpInst* C);
121       Expression::ExpressionOpcode getOpcode(CastInst* C);
122       Expression create_expression(BinaryOperator* BO);
123       Expression create_expression(CmpInst* C);
124       Expression create_expression(ShuffleVectorInst* V);
125       Expression create_expression(ExtractElementInst* C);
126       Expression create_expression(InsertElementInst* V);
127       Expression create_expression(SelectInst* V);
128       Expression create_expression(CastInst* C);
129       Expression create_expression(GetElementPtrInst* G);
130     public:
131       ValueTable() { nextValueNumber = 1; }
132       uint32_t lookup_or_add(Value* V);
133       uint32_t lookup(Value* V) const;
134       void add(Value* V, uint32_t num);
135       void clear();
136       void erase(Value* v);
137       unsigned size();
138   };
139 }
140
141 //===----------------------------------------------------------------------===//
142 //                     ValueTable Internal Functions
143 //===----------------------------------------------------------------------===//
144 ValueTable::Expression::ExpressionOpcode 
145                              ValueTable::getOpcode(BinaryOperator* BO) {
146   switch(BO->getOpcode()) {
147     case Instruction::Add:
148       return Expression::ADD;
149     case Instruction::Sub:
150       return Expression::SUB;
151     case Instruction::Mul:
152       return Expression::MUL;
153     case Instruction::UDiv:
154       return Expression::UDIV;
155     case Instruction::SDiv:
156       return Expression::SDIV;
157     case Instruction::FDiv:
158       return Expression::FDIV;
159     case Instruction::URem:
160       return Expression::UREM;
161     case Instruction::SRem:
162       return Expression::SREM;
163     case Instruction::FRem:
164       return Expression::FREM;
165     case Instruction::Shl:
166       return Expression::SHL;
167     case Instruction::LShr:
168       return Expression::LSHR;
169     case Instruction::AShr:
170       return Expression::ASHR;
171     case Instruction::And:
172       return Expression::AND;
173     case Instruction::Or:
174       return Expression::OR;
175     case Instruction::Xor:
176       return Expression::XOR;
177     
178     // THIS SHOULD NEVER HAPPEN
179     default:
180       assert(0 && "Binary operator with unknown opcode?");
181       return Expression::ADD;
182   }
183 }
184
185 ValueTable::Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
186   if (C->getOpcode() == Instruction::ICmp) {
187     switch (C->getPredicate()) {
188       case ICmpInst::ICMP_EQ:
189         return Expression::ICMPEQ;
190       case ICmpInst::ICMP_NE:
191         return Expression::ICMPNE;
192       case ICmpInst::ICMP_UGT:
193         return Expression::ICMPUGT;
194       case ICmpInst::ICMP_UGE:
195         return Expression::ICMPUGE;
196       case ICmpInst::ICMP_ULT:
197         return Expression::ICMPULT;
198       case ICmpInst::ICMP_ULE:
199         return Expression::ICMPULE;
200       case ICmpInst::ICMP_SGT:
201         return Expression::ICMPSGT;
202       case ICmpInst::ICMP_SGE:
203         return Expression::ICMPSGE;
204       case ICmpInst::ICMP_SLT:
205         return Expression::ICMPSLT;
206       case ICmpInst::ICMP_SLE:
207         return Expression::ICMPSLE;
208       
209       // THIS SHOULD NEVER HAPPEN
210       default:
211         assert(0 && "Comparison with unknown predicate?");
212         return Expression::ICMPEQ;
213     }
214   } else {
215     switch (C->getPredicate()) {
216       case FCmpInst::FCMP_OEQ:
217         return Expression::FCMPOEQ;
218       case FCmpInst::FCMP_OGT:
219         return Expression::FCMPOGT;
220       case FCmpInst::FCMP_OGE:
221         return Expression::FCMPOGE;
222       case FCmpInst::FCMP_OLT:
223         return Expression::FCMPOLT;
224       case FCmpInst::FCMP_OLE:
225         return Expression::FCMPOLE;
226       case FCmpInst::FCMP_ONE:
227         return Expression::FCMPONE;
228       case FCmpInst::FCMP_ORD:
229         return Expression::FCMPORD;
230       case FCmpInst::FCMP_UNO:
231         return Expression::FCMPUNO;
232       case FCmpInst::FCMP_UEQ:
233         return Expression::FCMPUEQ;
234       case FCmpInst::FCMP_UGT:
235         return Expression::FCMPUGT;
236       case FCmpInst::FCMP_UGE:
237         return Expression::FCMPUGE;
238       case FCmpInst::FCMP_ULT:
239         return Expression::FCMPULT;
240       case FCmpInst::FCMP_ULE:
241         return Expression::FCMPULE;
242       case FCmpInst::FCMP_UNE:
243         return Expression::FCMPUNE;
244       
245       // THIS SHOULD NEVER HAPPEN
246       default:
247         assert(0 && "Comparison with unknown predicate?");
248         return Expression::FCMPOEQ;
249     }
250   }
251 }
252
253 ValueTable::Expression::ExpressionOpcode 
254                              ValueTable::getOpcode(CastInst* C) {
255   switch(C->getOpcode()) {
256     case Instruction::Trunc:
257       return Expression::TRUNC;
258     case Instruction::ZExt:
259       return Expression::ZEXT;
260     case Instruction::SExt:
261       return Expression::SEXT;
262     case Instruction::FPToUI:
263       return Expression::FPTOUI;
264     case Instruction::FPToSI:
265       return Expression::FPTOSI;
266     case Instruction::UIToFP:
267       return Expression::UITOFP;
268     case Instruction::SIToFP:
269       return Expression::SITOFP;
270     case Instruction::FPTrunc:
271       return Expression::FPTRUNC;
272     case Instruction::FPExt:
273       return Expression::FPEXT;
274     case Instruction::PtrToInt:
275       return Expression::PTRTOINT;
276     case Instruction::IntToPtr:
277       return Expression::INTTOPTR;
278     case Instruction::BitCast:
279       return Expression::BITCAST;
280     
281     // THIS SHOULD NEVER HAPPEN
282     default:
283       assert(0 && "Cast operator with unknown opcode?");
284       return Expression::BITCAST;
285   }
286 }
287
288 ValueTable::Expression ValueTable::create_expression(BinaryOperator* BO) {
289   Expression e;
290     
291   e.firstVN = lookup_or_add(BO->getOperand(0));
292   e.secondVN = lookup_or_add(BO->getOperand(1));
293   e.thirdVN = 0;
294   e.type = BO->getType();
295   e.opcode = getOpcode(BO);
296   
297   return e;
298 }
299
300 ValueTable::Expression ValueTable::create_expression(CmpInst* C) {
301   Expression e;
302     
303   e.firstVN = lookup_or_add(C->getOperand(0));
304   e.secondVN = lookup_or_add(C->getOperand(1));
305   e.thirdVN = 0;
306   e.type = C->getType();
307   e.opcode = getOpcode(C);
308   
309   return e;
310 }
311
312 ValueTable::Expression ValueTable::create_expression(CastInst* C) {
313   Expression e;
314     
315   e.firstVN = lookup_or_add(C->getOperand(0));
316   e.secondVN = 0;
317   e.thirdVN = 0;
318   e.type = C->getType();
319   e.opcode = getOpcode(C);
320   
321   return e;
322 }
323
324 ValueTable::Expression ValueTable::create_expression(ShuffleVectorInst* S) {
325   Expression e;
326     
327   e.firstVN = lookup_or_add(S->getOperand(0));
328   e.secondVN = lookup_or_add(S->getOperand(1));
329   e.thirdVN = lookup_or_add(S->getOperand(2));
330   e.type = S->getType();
331   e.opcode = Expression::SHUFFLE;
332   
333   return e;
334 }
335
336 ValueTable::Expression ValueTable::create_expression(ExtractElementInst* E) {
337   Expression e;
338     
339   e.firstVN = lookup_or_add(E->getOperand(0));
340   e.secondVN = lookup_or_add(E->getOperand(1));
341   e.thirdVN = 0;
342   e.type = E->getType();
343   e.opcode = Expression::EXTRACT;
344   
345   return e;
346 }
347
348 ValueTable::Expression ValueTable::create_expression(InsertElementInst* I) {
349   Expression e;
350     
351   e.firstVN = lookup_or_add(I->getOperand(0));
352   e.secondVN = lookup_or_add(I->getOperand(1));
353   e.thirdVN = lookup_or_add(I->getOperand(2));
354   e.type = I->getType();
355   e.opcode = Expression::INSERT;
356   
357   return e;
358 }
359
360 ValueTable::Expression ValueTable::create_expression(SelectInst* I) {
361   Expression e;
362     
363   e.firstVN = lookup_or_add(I->getCondition());
364   e.secondVN = lookup_or_add(I->getTrueValue());
365   e.thirdVN = lookup_or_add(I->getFalseValue());
366   e.type = I->getType();
367   e.opcode = Expression::SELECT;
368   
369   return e;
370 }
371
372 ValueTable::Expression ValueTable::create_expression(GetElementPtrInst* G) {
373   Expression e;
374     
375   e.firstVN = lookup_or_add(G->getPointerOperand());
376   e.secondVN = 0;
377   e.thirdVN = 0;
378   e.type = G->getType();
379   e.opcode = Expression::SELECT;
380   
381   for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
382        I != E; ++I)
383     e.varargs.push_back(lookup_or_add(*I));
384   
385   return e;
386 }
387
388 //===----------------------------------------------------------------------===//
389 //                     ValueTable External Functions
390 //===----------------------------------------------------------------------===//
391
392 /// lookup_or_add - Returns the value number for the specified value, assigning
393 /// it a new number if it did not have one before.
394 uint32_t ValueTable::lookup_or_add(Value* V) {
395   DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
396   if (VI != valueNumbering.end())
397     return VI->second;
398   
399   
400   if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
401     Expression e = create_expression(BO);
402     
403     std::map<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
404     if (EI != expressionNumbering.end()) {
405       valueNumbering.insert(std::make_pair(V, EI->second));
406       return EI->second;
407     } else {
408       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
409       valueNumbering.insert(std::make_pair(V, nextValueNumber));
410       
411       return nextValueNumber++;
412     }
413   } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
414     Expression e = create_expression(C);
415     
416     std::map<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
417     if (EI != expressionNumbering.end()) {
418       valueNumbering.insert(std::make_pair(V, EI->second));
419       return EI->second;
420     } else {
421       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
422       valueNumbering.insert(std::make_pair(V, nextValueNumber));
423       
424       return nextValueNumber++;
425     }
426   } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
427     Expression e = create_expression(U);
428     
429     std::map<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
430     if (EI != expressionNumbering.end()) {
431       valueNumbering.insert(std::make_pair(V, EI->second));
432       return EI->second;
433     } else {
434       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
435       valueNumbering.insert(std::make_pair(V, nextValueNumber));
436       
437       return nextValueNumber++;
438     }
439   } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
440     Expression e = create_expression(U);
441     
442     std::map<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
443     if (EI != expressionNumbering.end()) {
444       valueNumbering.insert(std::make_pair(V, EI->second));
445       return EI->second;
446     } else {
447       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
448       valueNumbering.insert(std::make_pair(V, nextValueNumber));
449       
450       return nextValueNumber++;
451     }
452   } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
453     Expression e = create_expression(U);
454     
455     std::map<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
456     if (EI != expressionNumbering.end()) {
457       valueNumbering.insert(std::make_pair(V, EI->second));
458       return EI->second;
459     } else {
460       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
461       valueNumbering.insert(std::make_pair(V, nextValueNumber));
462       
463       return nextValueNumber++;
464     }
465   } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
466     Expression e = create_expression(U);
467     
468     std::map<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
469     if (EI != expressionNumbering.end()) {
470       valueNumbering.insert(std::make_pair(V, EI->second));
471       return EI->second;
472     } else {
473       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
474       valueNumbering.insert(std::make_pair(V, nextValueNumber));
475       
476       return nextValueNumber++;
477     }
478   } else if (CastInst* U = dyn_cast<CastInst>(V)) {
479     Expression e = create_expression(U);
480     
481     std::map<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
482     if (EI != expressionNumbering.end()) {
483       valueNumbering.insert(std::make_pair(V, EI->second));
484       return EI->second;
485     } else {
486       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
487       valueNumbering.insert(std::make_pair(V, nextValueNumber));
488       
489       return nextValueNumber++;
490     }
491   } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
492     Expression e = create_expression(U);
493     
494     std::map<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
495     if (EI != expressionNumbering.end()) {
496       valueNumbering.insert(std::make_pair(V, EI->second));
497       return EI->second;
498     } else {
499       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
500       valueNumbering.insert(std::make_pair(V, nextValueNumber));
501       
502       return nextValueNumber++;
503     }
504   } else {
505     valueNumbering.insert(std::make_pair(V, nextValueNumber));
506     return nextValueNumber++;
507   }
508 }
509
510 /// lookup - Returns the value number of the specified value. Fails if
511 /// the value has not yet been numbered.
512 uint32_t ValueTable::lookup(Value* V) const {
513   DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
514   if (VI != valueNumbering.end())
515     return VI->second;
516   else
517     assert(0 && "Value not numbered?");
518   
519   return 0;
520 }
521
522 /// add - Add the specified value with the given value number, removing
523 /// its old number, if any
524 void ValueTable::add(Value* V, uint32_t num) {
525   DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
526   if (VI != valueNumbering.end())
527     valueNumbering.erase(VI);
528   valueNumbering.insert(std::make_pair(V, num));
529 }
530
531 /// clear - Remove all entries from the ValueTable
532 void ValueTable::clear() {
533   valueNumbering.clear();
534   expressionNumbering.clear();
535   nextValueNumber = 1;
536 }
537
538 /// erase - Remove a value from the value numbering
539 void ValueTable::erase(Value* V) {
540   valueNumbering.erase(V);
541 }
542
543 /// size - Return the number of assigned value numbers
544 unsigned ValueTable::size() {
545   // NOTE: zero is never assigned
546   return nextValueNumber;
547 }
548
549 //===----------------------------------------------------------------------===//
550 //                         ValueTable Class
551 //===----------------------------------------------------------------------===//
552
553 class ValueNumberedSet {
554   private:
555     SmallPtrSet<Value*, 8> contents;
556     BitVector numbers;
557   public:
558     ValueNumberedSet() { numbers.resize(1); }
559     
560     typedef SmallPtrSet<Value*, 8>::iterator iterator;
561     
562     iterator begin() { return contents.begin(); }
563     iterator end() { return contents.end(); }
564     
565     bool insert(Value* v) { return contents.insert(v); }
566     void insert(iterator I, iterator E) { contents.insert(I, E); }
567     void erase(Value* v) { contents.erase(v); }
568     size_t size() { return contents.size(); }
569     
570     void set(unsigned i)  {
571       if (i >= numbers.size())
572         numbers.resize(i+1);
573       
574       numbers.set(i);
575     }
576     
577     void copyNumbers(ValueNumberedSet& other) {
578       numbers = other.numbers;
579     }
580     
581     void reset(unsigned i)  {
582       if (i < numbers.size())
583         numbers.reset(i);
584     }
585     
586     bool test(unsigned i)  {
587       if (i >= numbers.size())
588         return false;
589       
590       return numbers.test(i);
591     }
592     
593     void clear() {
594       contents.clear();
595       numbers.clear();
596     }
597 };
598
599 //===----------------------------------------------------------------------===//
600 //                         GVNPRE Pass
601 //===----------------------------------------------------------------------===//
602
603 namespace {
604
605   class VISIBILITY_HIDDEN GVNPRE : public FunctionPass {
606     bool runOnFunction(Function &F);
607   public:
608     static char ID; // Pass identification, replacement for typeid
609     GVNPRE() : FunctionPass((intptr_t)&ID) { }
610
611   private:
612     ValueTable VN;
613     std::vector<Instruction*> createdExpressions;
614     
615     std::map<BasicBlock*, ValueNumberedSet> availableOut;
616     std::map<BasicBlock*, ValueNumberedSet> anticipatedIn;
617     std::map<BasicBlock*, ValueNumberedSet> generatedPhis;
618     
619     // This transformation requires dominator postdominator info
620     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
621       AU.setPreservesCFG();
622       AU.addRequiredID(BreakCriticalEdgesID);
623       AU.addRequired<UnifyFunctionExitNodes>();
624       AU.addRequired<DominatorTree>();
625     }
626   
627     // Helper fuctions
628     // FIXME: eliminate or document these better
629     void dump(ValueNumberedSet& s) const ;
630     void clean(ValueNumberedSet& set) ;
631     Value* find_leader(ValueNumberedSet& vals, uint32_t v) ;
632     Value* phi_translate(Value* V, BasicBlock* pred, BasicBlock* succ) ;
633     void phi_translate_set(ValueNumberedSet& anticIn, BasicBlock* pred,
634                            BasicBlock* succ, ValueNumberedSet& out) ;
635     
636     void topo_sort(ValueNumberedSet& set,
637                    std::vector<Value*>& vec) ;
638     
639     void cleanup() ;
640     bool elimination() ;
641     
642     void val_insert(ValueNumberedSet& s, Value* v) ;
643     void val_replace(ValueNumberedSet& s, Value* v) ;
644     bool dependsOnInvoke(Value* V) ;
645     void buildsets_availout(BasicBlock::iterator I,
646                             ValueNumberedSet& currAvail,
647                             ValueNumberedSet& currPhis,
648                             ValueNumberedSet& currExps,
649                             SmallPtrSet<Value*, 16>& currTemps) ;
650     bool buildsets_anticout(BasicBlock* BB,
651                             ValueNumberedSet& anticOut,
652                             std::set<BasicBlock*>& visited) ;
653     unsigned buildsets_anticin(BasicBlock* BB,
654                            ValueNumberedSet& anticOut,
655                            ValueNumberedSet& currExps,
656                            SmallPtrSet<Value*, 16>& currTemps,
657                            std::set<BasicBlock*>& visited) ;
658     void buildsets(Function& F) ;
659     
660     void insertion_pre(Value* e, BasicBlock* BB,
661                        std::map<BasicBlock*, Value*>& avail,
662                       std::map<BasicBlock*,ValueNumberedSet>& new_set) ;
663     unsigned insertion_mergepoint(std::vector<Value*>& workList,
664                                   df_iterator<DomTreeNode*>& D,
665                       std::map<BasicBlock*, ValueNumberedSet>& new_set) ;
666     bool insertion(Function& F) ;
667   
668   };
669   
670   char GVNPRE::ID = 0;
671   
672 }
673
674 // createGVNPREPass - The public interface to this file...
675 FunctionPass *llvm::createGVNPREPass() { return new GVNPRE(); }
676
677 RegisterPass<GVNPRE> X("gvnpre",
678                        "Global Value Numbering/Partial Redundancy Elimination");
679
680
681 STATISTIC(NumInsertedVals, "Number of values inserted");
682 STATISTIC(NumInsertedPhis, "Number of PHI nodes inserted");
683 STATISTIC(NumEliminated, "Number of redundant instructions eliminated");
684
685 /// find_leader - Given a set and a value number, return the first
686 /// element of the set with that value number, or 0 if no such element
687 /// is present
688 Value* GVNPRE::find_leader(ValueNumberedSet& vals, uint32_t v) {
689   if (!vals.test(v))
690     return 0;
691   
692   for (ValueNumberedSet::iterator I = vals.begin(), E = vals.end();
693        I != E; ++I)
694     if (v == VN.lookup(*I))
695       return *I;
696   
697   return 0;
698 }
699
700 /// val_insert - Insert a value into a set only if there is not a value
701 /// with the same value number already in the set
702 void GVNPRE::val_insert(ValueNumberedSet& s, Value* v) {
703   uint32_t num = VN.lookup(v);
704   if (!s.test(num))
705     s.insert(v);
706 }
707
708 /// val_replace - Insert a value into a set, replacing any values already in
709 /// the set that have the same value number
710 void GVNPRE::val_replace(ValueNumberedSet& s, Value* v) {
711   uint32_t num = VN.lookup(v);
712   Value* leader = find_leader(s, num);
713   while (leader != 0) {
714     s.erase(leader);
715     leader = find_leader(s, num);
716   }
717   s.insert(v);
718 }
719
720 /// phi_translate - Given a value, its parent block, and a predecessor of its
721 /// parent, translate the value into legal for the predecessor block.  This 
722 /// means translating its operands (and recursively, their operands) through
723 /// any phi nodes in the parent into values available in the predecessor
724 Value* GVNPRE::phi_translate(Value* V, BasicBlock* pred, BasicBlock* succ) {
725   if (V == 0)
726     return 0;
727   
728   // Unary Operations
729   if (CastInst* U = dyn_cast<CastInst>(V)) {
730     Value* newOp1 = 0;
731     if (isa<Instruction>(U->getOperand(0)))
732       newOp1 = phi_translate(U->getOperand(0), pred, succ);
733     else
734       newOp1 = U->getOperand(0);
735     
736     if (newOp1 == 0)
737       return 0;
738     
739     if (newOp1 != U->getOperand(0)) {
740       Instruction* newVal = 0;
741       if (CastInst* C = dyn_cast<CastInst>(U))
742         newVal = CastInst::create(C->getOpcode(),
743                                   newOp1, C->getType(),
744                                   C->getName()+".expr");
745       
746       uint32_t v = VN.lookup_or_add(newVal);
747       
748       Value* leader = find_leader(availableOut[pred], v);
749       if (leader == 0) {
750         createdExpressions.push_back(newVal);
751         return newVal;
752       } else {
753         VN.erase(newVal);
754         delete newVal;
755         return leader;
756       }
757     }
758   
759   // Binary Operations
760   } if (isa<BinaryOperator>(V) || isa<CmpInst>(V) || 
761       isa<ExtractElementInst>(V)) {
762     User* U = cast<User>(V);
763     
764     Value* newOp1 = 0;
765     if (isa<Instruction>(U->getOperand(0)))
766       newOp1 = phi_translate(U->getOperand(0), pred, succ);
767     else
768       newOp1 = U->getOperand(0);
769     
770     if (newOp1 == 0)
771       return 0;
772     
773     Value* newOp2 = 0;
774     if (isa<Instruction>(U->getOperand(1)))
775       newOp2 = phi_translate(U->getOperand(1), pred, succ);
776     else
777       newOp2 = U->getOperand(1);
778     
779     if (newOp2 == 0)
780       return 0;
781     
782     if (newOp1 != U->getOperand(0) || newOp2 != U->getOperand(1)) {
783       Instruction* newVal = 0;
784       if (BinaryOperator* BO = dyn_cast<BinaryOperator>(U))
785         newVal = BinaryOperator::create(BO->getOpcode(),
786                                         newOp1, newOp2,
787                                         BO->getName()+".expr");
788       else if (CmpInst* C = dyn_cast<CmpInst>(U))
789         newVal = CmpInst::create(C->getOpcode(),
790                                  C->getPredicate(),
791                                  newOp1, newOp2,
792                                  C->getName()+".expr");
793       else if (ExtractElementInst* E = dyn_cast<ExtractElementInst>(U))
794         newVal = new ExtractElementInst(newOp1, newOp2, E->getName()+".expr");
795       
796       uint32_t v = VN.lookup_or_add(newVal);
797       
798       Value* leader = find_leader(availableOut[pred], v);
799       if (leader == 0) {
800         createdExpressions.push_back(newVal);
801         return newVal;
802       } else {
803         VN.erase(newVal);
804         delete newVal;
805         return leader;
806       }
807     }
808   
809   // Ternary Operations
810   } else if (isa<ShuffleVectorInst>(V) || isa<InsertElementInst>(V) ||
811              isa<SelectInst>(V)) {
812     User* U = cast<User>(V);
813     
814     Value* newOp1 = 0;
815     if (isa<Instruction>(U->getOperand(0)))
816       newOp1 = phi_translate(U->getOperand(0), pred, succ);
817     else
818       newOp1 = U->getOperand(0);
819     
820     if (newOp1 == 0)
821       return 0;
822     
823     Value* newOp2 = 0;
824     if (isa<Instruction>(U->getOperand(1)))
825       newOp2 = phi_translate(U->getOperand(1), pred, succ);
826     else
827       newOp2 = U->getOperand(1);
828     
829     if (newOp2 == 0)
830       return 0;
831     
832     Value* newOp3 = 0;
833     if (isa<Instruction>(U->getOperand(2)))
834       newOp3 = phi_translate(U->getOperand(2), pred, succ);
835     else
836       newOp3 = U->getOperand(2);
837     
838     if (newOp3 == 0)
839       return 0;
840     
841     if (newOp1 != U->getOperand(0) ||
842         newOp2 != U->getOperand(1) ||
843         newOp3 != U->getOperand(2)) {
844       Instruction* newVal = 0;
845       if (ShuffleVectorInst* S = dyn_cast<ShuffleVectorInst>(U))
846         newVal = new ShuffleVectorInst(newOp1, newOp2, newOp3,
847                                        S->getName()+".expr");
848       else if (InsertElementInst* I = dyn_cast<InsertElementInst>(U))
849         newVal = new InsertElementInst(newOp1, newOp2, newOp3,
850                                        I->getName()+".expr");
851       else if (SelectInst* I = dyn_cast<SelectInst>(U))
852         newVal = new SelectInst(newOp1, newOp2, newOp3, I->getName()+".expr");
853       
854       uint32_t v = VN.lookup_or_add(newVal);
855       
856       Value* leader = find_leader(availableOut[pred], v);
857       if (leader == 0) {
858         createdExpressions.push_back(newVal);
859         return newVal;
860       } else {
861         VN.erase(newVal);
862         delete newVal;
863         return leader;
864       }
865     }
866   
867   // Varargs operators
868   } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
869     Value* newOp1 = 0;
870     if (isa<Instruction>(U->getPointerOperand()))
871       newOp1 = phi_translate(U->getPointerOperand(), pred, succ);
872     else
873       newOp1 = U->getPointerOperand();
874     
875     if (newOp1 == 0)
876       return 0;
877     
878     bool changed_idx = false;
879     std::vector<Value*> newIdx;
880     for (GetElementPtrInst::op_iterator I = U->idx_begin(), E = U->idx_end();
881          I != E; ++I)
882       if (isa<Instruction>(*I)) {
883         Value* newVal = phi_translate(*I, pred, succ);
884         newIdx.push_back(newVal);
885         if (newVal != *I)
886           changed_idx = true;
887       } else {
888         newIdx.push_back(*I);
889       }
890     
891     if (newOp1 != U->getPointerOperand() || changed_idx) {
892       Instruction* newVal = new GetElementPtrInst(newOp1,
893                                        &newIdx[0], newIdx.size(),
894                                        U->getName()+".expr");
895       
896       uint32_t v = VN.lookup_or_add(newVal);
897       
898       Value* leader = find_leader(availableOut[pred], v);
899       if (leader == 0) {
900         createdExpressions.push_back(newVal);
901         return newVal;
902       } else {
903         VN.erase(newVal);
904         delete newVal;
905         return leader;
906       }
907     }
908   
909   // PHI Nodes
910   } else if (PHINode* P = dyn_cast<PHINode>(V)) {
911     if (P->getParent() == succ)
912       return P->getIncomingValueForBlock(pred);
913   }
914   
915   return V;
916 }
917
918 /// phi_translate_set - Perform phi translation on every element of a set
919 void GVNPRE::phi_translate_set(ValueNumberedSet& anticIn,
920                               BasicBlock* pred, BasicBlock* succ,
921                               ValueNumberedSet& out) {
922   for (ValueNumberedSet::iterator I = anticIn.begin(),
923        E = anticIn.end(); I != E; ++I) {
924     Value* V = phi_translate(*I, pred, succ);
925     if (V != 0 && !out.test(VN.lookup_or_add(V))) {
926       out.insert(V);
927       out.set(VN.lookup(V));
928     }
929   }
930 }
931
932 /// dependsOnInvoke - Test if a value has an phi node as an operand, any of 
933 /// whose inputs is an invoke instruction.  If this is true, we cannot safely
934 /// PRE the instruction or anything that depends on it.
935 bool GVNPRE::dependsOnInvoke(Value* V) {
936   if (PHINode* p = dyn_cast<PHINode>(V)) {
937     for (PHINode::op_iterator I = p->op_begin(), E = p->op_end(); I != E; ++I)
938       if (isa<InvokeInst>(*I))
939         return true;
940     return false;
941   } else {
942     return false;
943   }
944 }
945
946 /// clean - Remove all non-opaque values from the set whose operands are not
947 /// themselves in the set, as well as all values that depend on invokes (see 
948 /// above)
949 void GVNPRE::clean(ValueNumberedSet& set) {
950   std::vector<Value*> worklist;
951   worklist.reserve(set.size());
952   topo_sort(set, worklist);
953   
954   for (unsigned i = 0; i < worklist.size(); ++i) {
955     Value* v = worklist[i];
956     
957     // Handle unary ops
958     if (CastInst* U = dyn_cast<CastInst>(v)) {
959       bool lhsValid = !isa<Instruction>(U->getOperand(0));
960       lhsValid |= set.test(VN.lookup(U->getOperand(0)));
961       if (lhsValid)
962         lhsValid = !dependsOnInvoke(U->getOperand(0));
963       
964       if (!lhsValid) {
965         set.erase(U);
966         set.reset(VN.lookup(U));
967       }
968     
969     // Handle binary ops
970     } else if (isa<BinaryOperator>(v) || isa<CmpInst>(v) ||
971         isa<ExtractElementInst>(v)) {
972       User* U = cast<User>(v);
973       
974       bool lhsValid = !isa<Instruction>(U->getOperand(0));
975       lhsValid |= set.test(VN.lookup(U->getOperand(0)));
976       if (lhsValid)
977         lhsValid = !dependsOnInvoke(U->getOperand(0));
978     
979       bool rhsValid = !isa<Instruction>(U->getOperand(1));
980       rhsValid |= set.test(VN.lookup(U->getOperand(1)));
981       if (rhsValid)
982         rhsValid = !dependsOnInvoke(U->getOperand(1));
983       
984       if (!lhsValid || !rhsValid) {
985         set.erase(U);
986         set.reset(VN.lookup(U));
987       }
988     
989     // Handle ternary ops
990     } else if (isa<ShuffleVectorInst>(v) || isa<InsertElementInst>(v) ||
991                isa<SelectInst>(v)) {
992       User* U = cast<User>(v);
993     
994       bool lhsValid = !isa<Instruction>(U->getOperand(0));
995       lhsValid |= set.test(VN.lookup(U->getOperand(0)));
996       if (lhsValid)
997         lhsValid = !dependsOnInvoke(U->getOperand(0));
998       
999       bool rhsValid = !isa<Instruction>(U->getOperand(1));
1000       rhsValid |= set.test(VN.lookup(U->getOperand(1)));
1001       if (rhsValid)
1002         rhsValid = !dependsOnInvoke(U->getOperand(1));
1003       
1004       bool thirdValid = !isa<Instruction>(U->getOperand(2));
1005       thirdValid |= set.test(VN.lookup(U->getOperand(2)));
1006       if (thirdValid)
1007         thirdValid = !dependsOnInvoke(U->getOperand(2));
1008     
1009       if (!lhsValid || !rhsValid || !thirdValid) {
1010         set.erase(U);
1011         set.reset(VN.lookup(U));
1012       }
1013     
1014     // Handle varargs ops
1015     } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(v)) {
1016       bool ptrValid = !isa<Instruction>(U->getPointerOperand());
1017       ptrValid |= set.test(VN.lookup(U->getPointerOperand()));
1018       if (ptrValid)
1019         ptrValid = !dependsOnInvoke(U->getPointerOperand());
1020       
1021       bool varValid = true;
1022       for (GetElementPtrInst::op_iterator I = U->idx_begin(), E = U->idx_end();
1023            I != E; ++I)
1024         if (varValid) {
1025           varValid &= !isa<Instruction>(*I) || set.test(VN.lookup(*I));
1026           varValid &= !dependsOnInvoke(*I);
1027         }
1028     
1029       if (!ptrValid || !varValid) {
1030         set.erase(U);
1031         set.reset(VN.lookup(U));
1032       }
1033     }
1034   }
1035 }
1036
1037 /// topo_sort - Given a set of values, sort them by topological
1038 /// order into the provided vector.
1039 void GVNPRE::topo_sort(ValueNumberedSet& set, std::vector<Value*>& vec) {
1040   SmallPtrSet<Value*, 16> visited;
1041   std::vector<Value*> stack;
1042   for (ValueNumberedSet::iterator I = set.begin(), E = set.end();
1043        I != E; ++I) {
1044     if (visited.count(*I) == 0)
1045       stack.push_back(*I);
1046     
1047     while (!stack.empty()) {
1048       Value* e = stack.back();
1049       
1050       // Handle unary ops
1051       if (CastInst* U = dyn_cast<CastInst>(e)) {
1052         Value* l = find_leader(set, VN.lookup(U->getOperand(0)));
1053     
1054         if (l != 0 && isa<Instruction>(l) &&
1055             visited.count(l) == 0)
1056           stack.push_back(l);
1057         else {
1058           vec.push_back(e);
1059           visited.insert(e);
1060           stack.pop_back();
1061         }
1062       
1063       // Handle binary ops
1064       } else if (isa<BinaryOperator>(e) || isa<CmpInst>(e) ||
1065           isa<ExtractElementInst>(e)) {
1066         User* U = cast<User>(e);
1067         Value* l = find_leader(set, VN.lookup(U->getOperand(0)));
1068         Value* r = find_leader(set, VN.lookup(U->getOperand(1)));
1069     
1070         if (l != 0 && isa<Instruction>(l) &&
1071             visited.count(l) == 0)
1072           stack.push_back(l);
1073         else if (r != 0 && isa<Instruction>(r) &&
1074                  visited.count(r) == 0)
1075           stack.push_back(r);
1076         else {
1077           vec.push_back(e);
1078           visited.insert(e);
1079           stack.pop_back();
1080         }
1081       
1082       // Handle ternary ops
1083       } else if (isa<InsertElementInst>(e) || isa<ShuffleVectorInst>(e) ||
1084                  isa<SelectInst>(e)) {
1085         User* U = cast<User>(e);
1086         Value* l = find_leader(set, VN.lookup(U->getOperand(0)));
1087         Value* r = find_leader(set, VN.lookup(U->getOperand(1)));
1088         Value* m = find_leader(set, VN.lookup(U->getOperand(2)));
1089       
1090         if (l != 0 && isa<Instruction>(l) &&
1091             visited.count(l) == 0)
1092           stack.push_back(l);
1093         else if (r != 0 && isa<Instruction>(r) &&
1094                  visited.count(r) == 0)
1095           stack.push_back(r);
1096         else if (m != 0 && isa<Instruction>(m) &&
1097                  visited.count(m) == 0)
1098           stack.push_back(m);
1099         else {
1100           vec.push_back(e);
1101           visited.insert(e);
1102           stack.pop_back();
1103         }
1104       
1105       // Handle vararg ops
1106       } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(e)) {
1107         Value* p = find_leader(set, VN.lookup(U->getPointerOperand()));
1108         
1109         if (p != 0 && isa<Instruction>(p) &&
1110             visited.count(p) == 0)
1111           stack.push_back(p);
1112         else {
1113           bool push_va = false;
1114           for (GetElementPtrInst::op_iterator I = U->idx_begin(),
1115                E = U->idx_end(); I != E; ++I) {
1116             Value * v = find_leader(set, VN.lookup(*I));
1117             if (v != 0 && isa<Instruction>(v) && visited.count(v) == 0) {
1118               stack.push_back(v);
1119               push_va = true;
1120             }
1121           }
1122           
1123           if (!push_va) {
1124             vec.push_back(e);
1125             visited.insert(e);
1126             stack.pop_back();
1127           }
1128         }
1129       
1130       // Handle opaque ops
1131       } else {
1132         visited.insert(e);
1133         vec.push_back(e);
1134         stack.pop_back();
1135       }
1136     }
1137     
1138     stack.clear();
1139   }
1140 }
1141
1142 /// dump - Dump a set of values to standard error
1143 void GVNPRE::dump(ValueNumberedSet& s) const {
1144   DOUT << "{ ";
1145   for (ValueNumberedSet::iterator I = s.begin(), E = s.end();
1146        I != E; ++I) {
1147     DOUT << "" << VN.lookup(*I) << ": ";
1148     DEBUG((*I)->dump());
1149   }
1150   DOUT << "}\n\n";
1151 }
1152
1153 /// elimination - Phase 3 of the main algorithm.  Perform full redundancy 
1154 /// elimination by walking the dominator tree and removing any instruction that 
1155 /// is dominated by another instruction with the same value number.
1156 bool GVNPRE::elimination() {
1157   DOUT << "\n\nPhase 3: Elimination\n\n";
1158   
1159   bool changed_function = false;
1160   
1161   std::vector<std::pair<Instruction*, Value*> > replace;
1162   std::vector<Instruction*> erase;
1163   
1164   DominatorTree& DT = getAnalysis<DominatorTree>();
1165   
1166   for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1167          E = df_end(DT.getRootNode()); DI != E; ++DI) {
1168     BasicBlock* BB = DI->getBlock();
1169     
1170     //DOUT << "Block: " << BB->getName() << "\n";
1171     //dump(availableOut[BB]);
1172     //DOUT << "\n\n";
1173     
1174     for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1175          BI != BE; ++BI) {
1176
1177       if (isa<BinaryOperator>(BI) || isa<CmpInst>(BI) ||
1178           isa<ShuffleVectorInst>(BI) || isa<InsertElementInst>(BI) ||
1179           isa<ExtractElementInst>(BI) || isa<SelectInst>(BI) ||
1180           isa<CastInst>(BI) || isa<GetElementPtrInst>(BI)) {
1181          Value *leader = find_leader(availableOut[BB], VN.lookup(BI));
1182   
1183         if (leader != 0)
1184           if (Instruction* Instr = dyn_cast<Instruction>(leader))
1185             if (Instr->getParent() != 0 && Instr != BI) {
1186               replace.push_back(std::make_pair(BI, leader));
1187               erase.push_back(BI);
1188               ++NumEliminated;
1189             }
1190       }
1191     }
1192   }
1193   
1194   while (!replace.empty()) {
1195     std::pair<Instruction*, Value*> rep = replace.back();
1196     replace.pop_back();
1197     rep.first->replaceAllUsesWith(rep.second);
1198     changed_function = true;
1199   }
1200     
1201   for (std::vector<Instruction*>::iterator I = erase.begin(), E = erase.end();
1202        I != E; ++I)
1203      (*I)->eraseFromParent();
1204   
1205   return changed_function;
1206 }
1207
1208 /// cleanup - Delete any extraneous values that were created to represent
1209 /// expressions without leaders.
1210 void GVNPRE::cleanup() {
1211   while (!createdExpressions.empty()) {
1212     Instruction* I = createdExpressions.back();
1213     createdExpressions.pop_back();
1214     
1215     delete I;
1216   }
1217 }
1218
1219 /// buildsets_availout - When calculating availability, handle an instruction
1220 /// by inserting it into the appropriate sets
1221 void GVNPRE::buildsets_availout(BasicBlock::iterator I,
1222                                 ValueNumberedSet& currAvail,
1223                                 ValueNumberedSet& currPhis,
1224                                 ValueNumberedSet& currExps,
1225                                 SmallPtrSet<Value*, 16>& currTemps) {
1226   // Handle PHI nodes
1227   if (PHINode* p = dyn_cast<PHINode>(I)) {
1228     unsigned num = VN.lookup_or_add(p);
1229     
1230     currPhis.insert(p);
1231     currPhis.set(num);
1232   
1233   // Handle unary ops
1234   } else if (CastInst* U = dyn_cast<CastInst>(I)) {
1235     Value* leftValue = U->getOperand(0);
1236     
1237     unsigned num = VN.lookup_or_add(U);
1238       
1239     if (isa<Instruction>(leftValue))
1240       if (!currExps.test(VN.lookup(leftValue))) {
1241         currExps.insert(leftValue);
1242         currExps.set(VN.lookup(leftValue));
1243       }
1244     
1245     if (!currExps.test(num)) {
1246       currExps.insert(U);
1247       currExps.set(num);
1248     }
1249   
1250   // Handle binary ops
1251   } else if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
1252              isa<ExtractElementInst>(I)) {
1253     User* U = cast<User>(I);
1254     Value* leftValue = U->getOperand(0);
1255     Value* rightValue = U->getOperand(1);
1256     
1257     unsigned num = VN.lookup_or_add(U);
1258       
1259     if (isa<Instruction>(leftValue))
1260       if (!currExps.test(VN.lookup(leftValue))) {
1261         currExps.insert(leftValue);
1262         currExps.set(VN.lookup(leftValue));
1263       }
1264     
1265     if (isa<Instruction>(rightValue))
1266       if (!currExps.test(VN.lookup(rightValue))) {
1267         currExps.insert(rightValue);
1268         currExps.set(VN.lookup(rightValue));
1269       }
1270     
1271     if (!currExps.test(num)) {
1272       currExps.insert(U);
1273       currExps.set(num);
1274     }
1275     
1276   // Handle ternary ops
1277   } else if (isa<InsertElementInst>(I) || isa<ShuffleVectorInst>(I) ||
1278              isa<SelectInst>(I)) {
1279     User* U = cast<User>(I);
1280     Value* leftValue = U->getOperand(0);
1281     Value* rightValue = U->getOperand(1);
1282     Value* thirdValue = U->getOperand(2);
1283       
1284     VN.lookup_or_add(U);
1285     
1286     unsigned num = VN.lookup_or_add(U);
1287     
1288     if (isa<Instruction>(leftValue))
1289       if (!currExps.test(VN.lookup(leftValue))) {
1290         currExps.insert(leftValue);
1291         currExps.set(VN.lookup(leftValue));
1292       }
1293     if (isa<Instruction>(rightValue))
1294       if (!currExps.test(VN.lookup(rightValue))) {
1295         currExps.insert(rightValue);
1296         currExps.set(VN.lookup(rightValue));
1297       }
1298     if (isa<Instruction>(thirdValue))
1299       if (!currExps.test(VN.lookup(thirdValue))) {
1300         currExps.insert(thirdValue);
1301         currExps.set(VN.lookup(thirdValue));
1302       }
1303     
1304     if (!currExps.test(num)) {
1305       currExps.insert(U);
1306       currExps.set(num);
1307     }
1308     
1309   // Handle vararg ops
1310   } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(I)) {
1311     Value* ptrValue = U->getPointerOperand();
1312       
1313     VN.lookup_or_add(U);
1314     
1315     unsigned num = VN.lookup_or_add(U);
1316     
1317     if (isa<Instruction>(ptrValue))
1318       if (!currExps.test(VN.lookup(ptrValue))) {
1319         currExps.insert(ptrValue);
1320         currExps.set(VN.lookup(ptrValue));
1321       }
1322     
1323     for (GetElementPtrInst::op_iterator OI = U->idx_begin(), OE = U->idx_end();
1324          OI != OE; ++OI)
1325       if (isa<Instruction>(*OI) && !currExps.test(VN.lookup(*OI))) {
1326         currExps.insert(*OI);
1327         currExps.set(VN.lookup(*OI));
1328       }
1329     
1330     if (!currExps.test(VN.lookup(U))) {
1331       currExps.insert(U);
1332       currExps.set(num);
1333     }
1334     
1335   // Handle opaque ops
1336   } else if (!I->isTerminator()){
1337     VN.lookup_or_add(I);
1338     
1339     currTemps.insert(I);
1340   }
1341     
1342   if (!I->isTerminator())
1343     if (!currAvail.test(VN.lookup(I))) {
1344       currAvail.insert(I);
1345       currAvail.set(VN.lookup(I));
1346     }
1347 }
1348
1349 /// buildsets_anticout - When walking the postdom tree, calculate the ANTIC_OUT
1350 /// set as a function of the ANTIC_IN set of the block's predecessors
1351 bool GVNPRE::buildsets_anticout(BasicBlock* BB,
1352                                 ValueNumberedSet& anticOut,
1353                                 std::set<BasicBlock*>& visited) {
1354   if (BB->getTerminator()->getNumSuccessors() == 1) {
1355     if (BB->getTerminator()->getSuccessor(0) != BB &&
1356         visited.count(BB->getTerminator()->getSuccessor(0)) == 0) {
1357           DOUT << "DEFER: " << BB->getName() << "\n";
1358       return true;
1359     }
1360     else {
1361       phi_translate_set(anticipatedIn[BB->getTerminator()->getSuccessor(0)],
1362                         BB,  BB->getTerminator()->getSuccessor(0), anticOut);
1363     }
1364   } else if (BB->getTerminator()->getNumSuccessors() > 1) {
1365     BasicBlock* first = BB->getTerminator()->getSuccessor(0);
1366     for (ValueNumberedSet::iterator I = anticipatedIn[first].begin(),
1367          E = anticipatedIn[first].end(); I != E; ++I) {
1368       anticOut.insert(*I);
1369       anticOut.set(VN.lookup(*I));
1370     }
1371     
1372     for (unsigned i = 1; i < BB->getTerminator()->getNumSuccessors(); ++i) {
1373       BasicBlock* currSucc = BB->getTerminator()->getSuccessor(i);
1374       ValueNumberedSet& succAnticIn = anticipatedIn[currSucc];
1375       
1376       std::vector<Value*> temp;
1377       
1378       for (ValueNumberedSet::iterator I = anticOut.begin(),
1379            E = anticOut.end(); I != E; ++I)
1380         if (!succAnticIn.test(VN.lookup(*I)))
1381           temp.push_back(*I);
1382
1383       for (std::vector<Value*>::iterator I = temp.begin(), E = temp.end();
1384            I != E; ++I) {
1385         anticOut.erase(*I);
1386         anticOut.reset(VN.lookup(*I));
1387       }
1388     }
1389   }
1390   
1391   return false;
1392 }
1393
1394 /// buildsets_anticin - Walk the postdom tree, calculating ANTIC_OUT for
1395 /// each block.  ANTIC_IN is then a function of ANTIC_OUT and the GEN
1396 /// sets populated in buildsets_availout
1397 unsigned GVNPRE::buildsets_anticin(BasicBlock* BB,
1398                                ValueNumberedSet& anticOut,
1399                                ValueNumberedSet& currExps,
1400                                SmallPtrSet<Value*, 16>& currTemps,
1401                                std::set<BasicBlock*>& visited) {
1402   ValueNumberedSet& anticIn = anticipatedIn[BB];
1403   unsigned old = anticIn.size();
1404       
1405   bool defer = buildsets_anticout(BB, anticOut, visited);
1406   if (defer)
1407     return 0;
1408   
1409   anticIn.clear();
1410   
1411   for (ValueNumberedSet::iterator I = anticOut.begin(),
1412        E = anticOut.end(); I != E; ++I) {
1413     anticIn.insert(*I);
1414     anticIn.set(VN.lookup(*I));
1415   }
1416   for (ValueNumberedSet::iterator I = currExps.begin(),
1417        E = currExps.end(); I != E; ++I) {
1418     if (!anticIn.test(VN.lookup(*I))) {
1419       anticIn.insert(*I);
1420       anticIn.set(VN.lookup(*I));
1421     }
1422   } 
1423   
1424   for (SmallPtrSet<Value*, 16>::iterator I = currTemps.begin(),
1425        E = currTemps.end(); I != E; ++I) {
1426     anticIn.erase(*I);
1427     anticIn.reset(VN.lookup(*I));
1428   }
1429   
1430   clean(anticIn);
1431   anticOut.clear();
1432   
1433   if (old != anticIn.size())
1434     return 2;
1435   else
1436     return 1;
1437 }
1438
1439 /// buildsets - Phase 1 of the main algorithm.  Construct the AVAIL_OUT
1440 /// and the ANTIC_IN sets.
1441 void GVNPRE::buildsets(Function& F) {
1442   std::map<BasicBlock*, ValueNumberedSet> generatedExpressions;
1443   std::map<BasicBlock*, SmallPtrSet<Value*, 16> > generatedTemporaries;
1444
1445   DominatorTree &DT = getAnalysis<DominatorTree>();   
1446   
1447   // Phase 1, Part 1: calculate AVAIL_OUT
1448   
1449   // Top-down walk of the dominator tree
1450   for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1451          E = df_end(DT.getRootNode()); DI != E; ++DI) {
1452     
1453     // Get the sets to update for this block
1454     ValueNumberedSet& currExps = generatedExpressions[DI->getBlock()];
1455     ValueNumberedSet& currPhis = generatedPhis[DI->getBlock()];
1456     SmallPtrSet<Value*, 16>& currTemps = generatedTemporaries[DI->getBlock()];
1457     ValueNumberedSet& currAvail = availableOut[DI->getBlock()];     
1458     
1459     BasicBlock* BB = DI->getBlock();
1460   
1461     // A block inherits AVAIL_OUT from its dominator
1462     if (DI->getIDom() != 0) {
1463       currAvail.insert(availableOut[DI->getIDom()->getBlock()].begin(),
1464                        availableOut[DI->getIDom()->getBlock()].end());
1465     
1466       currAvail.copyNumbers(availableOut[DI->getIDom()->getBlock()]);
1467     }
1468
1469     for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1470          BI != BE; ++BI)
1471       buildsets_availout(BI, currAvail, currPhis, currExps,
1472                          currTemps);
1473       
1474   }
1475
1476   // Phase 1, Part 2: calculate ANTIC_IN
1477   
1478   std::set<BasicBlock*> visited;
1479   SmallPtrSet<BasicBlock*, 4> block_changed;
1480   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
1481     block_changed.insert(FI);
1482   
1483   bool changed = true;
1484   unsigned iterations = 0;
1485   
1486   while (changed) {
1487     changed = false;
1488     ValueNumberedSet anticOut;
1489     
1490     // Postorder walk of the CFG
1491     for (po_iterator<BasicBlock*> BBI = po_begin(&F.getEntryBlock()),
1492          BBE = po_end(&F.getEntryBlock()); BBI != BBE; ++BBI) {
1493       BasicBlock* BB = *BBI;
1494       
1495       if (block_changed.count(BB) != 0) {
1496         unsigned ret = buildsets_anticin(BB, anticOut,generatedExpressions[BB],
1497                                          generatedTemporaries[BB], visited);
1498       
1499         if (ret == 0) {
1500           changed = true;
1501           continue;
1502         } else {
1503           visited.insert(BB);
1504         
1505           if (ret == 2)
1506            for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1507                  PI != PE; ++PI) {
1508               block_changed.insert(*PI);
1509            }
1510           else
1511             block_changed.erase(BB);
1512         
1513           changed |= (ret == 2);
1514         }
1515       }
1516     }
1517     
1518     iterations++;
1519   }
1520   
1521   DOUT << "ITERATIONS: " << iterations << "\n";
1522 }
1523
1524 /// insertion_pre - When a partial redundancy has been identified, eliminate it
1525 /// by inserting appropriate values into the predecessors and a phi node in
1526 /// the main block
1527 void GVNPRE::insertion_pre(Value* e, BasicBlock* BB,
1528                            std::map<BasicBlock*, Value*>& avail,
1529                     std::map<BasicBlock*, ValueNumberedSet>& new_sets) {
1530   for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
1531     DOUT << "PRED: " << (*PI)->getName() << "\n";
1532     Value* e2 = avail[*PI];
1533     if (!availableOut[*PI].test(VN.lookup(e2))) {
1534       User* U = cast<User>(e2);
1535       
1536       Value* s1 = 0;
1537       if (isa<BinaryOperator>(U->getOperand(0)) || 
1538           isa<CmpInst>(U->getOperand(0)) ||
1539           isa<ShuffleVectorInst>(U->getOperand(0)) ||
1540           isa<ExtractElementInst>(U->getOperand(0)) ||
1541           isa<InsertElementInst>(U->getOperand(0)) ||
1542           isa<SelectInst>(U->getOperand(0)) ||
1543           isa<CastInst>(U->getOperand(0)) ||
1544           isa<GetElementPtrInst>(U->getOperand(0)))
1545         s1 = find_leader(availableOut[*PI], VN.lookup(U->getOperand(0)));
1546       else
1547         s1 = U->getOperand(0);
1548       
1549       Value* s2 = 0;
1550       
1551       if (isa<BinaryOperator>(U) || 
1552           isa<CmpInst>(U) ||
1553           isa<ShuffleVectorInst>(U) ||
1554           isa<ExtractElementInst>(U) ||
1555           isa<InsertElementInst>(U) ||
1556           isa<SelectInst>(U))
1557         if (isa<BinaryOperator>(U->getOperand(1)) || 
1558             isa<CmpInst>(U->getOperand(1)) ||
1559             isa<ShuffleVectorInst>(U->getOperand(1)) ||
1560             isa<ExtractElementInst>(U->getOperand(1)) ||
1561             isa<InsertElementInst>(U->getOperand(1)) ||
1562             isa<SelectInst>(U->getOperand(1)) ||
1563             isa<CastInst>(U->getOperand(1)) ||
1564             isa<GetElementPtrInst>(U->getOperand(1))) {
1565           s2 = find_leader(availableOut[*PI], VN.lookup(U->getOperand(1)));
1566         } else {
1567           s2 = U->getOperand(1);
1568         }
1569       
1570       // Ternary Operators
1571       Value* s3 = 0;
1572       if (isa<ShuffleVectorInst>(U) ||
1573           isa<InsertElementInst>(U) ||
1574           isa<SelectInst>(U))
1575         if (isa<BinaryOperator>(U->getOperand(2)) || 
1576             isa<CmpInst>(U->getOperand(2)) ||
1577             isa<ShuffleVectorInst>(U->getOperand(2)) ||
1578             isa<ExtractElementInst>(U->getOperand(2)) ||
1579             isa<InsertElementInst>(U->getOperand(2)) ||
1580             isa<SelectInst>(U->getOperand(2)) ||
1581             isa<CastInst>(U->getOperand(2)) ||
1582             isa<GetElementPtrInst>(U->getOperand(2))) {
1583           s3 = find_leader(availableOut[*PI], VN.lookup(U->getOperand(2)));
1584         } else {
1585           s3 = U->getOperand(2);
1586         }
1587       
1588       // Vararg operators
1589       std::vector<Value*> sVarargs;
1590       if (GetElementPtrInst* G = dyn_cast<GetElementPtrInst>(U)) {
1591         for (GetElementPtrInst::op_iterator OI = G->idx_begin(),
1592              OE = G->idx_end(); OI != OE; ++OI) {
1593           if (isa<BinaryOperator>(*OI) || 
1594               isa<CmpInst>(*OI) ||
1595               isa<ShuffleVectorInst>(*OI) ||
1596               isa<ExtractElementInst>(*OI) ||
1597               isa<InsertElementInst>(*OI) ||
1598               isa<SelectInst>(*OI) ||
1599               isa<CastInst>(*OI) ||
1600               isa<GetElementPtrInst>(*OI)) {
1601             sVarargs.push_back(find_leader(availableOut[*PI], 
1602                                VN.lookup(*OI)));
1603           } else {
1604             sVarargs.push_back(*OI);
1605           }
1606         }
1607       }
1608       
1609       Value* newVal = 0;
1610       if (BinaryOperator* BO = dyn_cast<BinaryOperator>(U))
1611         newVal = BinaryOperator::create(BO->getOpcode(), s1, s2,
1612                                         BO->getName()+".gvnpre",
1613                                         (*PI)->getTerminator());
1614       else if (CmpInst* C = dyn_cast<CmpInst>(U))
1615         newVal = CmpInst::create(C->getOpcode(), C->getPredicate(), s1, s2,
1616                                  C->getName()+".gvnpre", 
1617                                  (*PI)->getTerminator());
1618       else if (ShuffleVectorInst* S = dyn_cast<ShuffleVectorInst>(U))
1619         newVal = new ShuffleVectorInst(s1, s2, s3, S->getName()+".gvnpre",
1620                                        (*PI)->getTerminator());
1621       else if (InsertElementInst* S = dyn_cast<InsertElementInst>(U))
1622         newVal = new InsertElementInst(s1, s2, s3, S->getName()+".gvnpre",
1623                                        (*PI)->getTerminator());
1624       else if (ExtractElementInst* S = dyn_cast<ExtractElementInst>(U))
1625         newVal = new ExtractElementInst(s1, s2, S->getName()+".gvnpre",
1626                                         (*PI)->getTerminator());
1627       else if (SelectInst* S = dyn_cast<SelectInst>(U))
1628         newVal = new SelectInst(s1, s2, s3, S->getName()+".gvnpre",
1629                                 (*PI)->getTerminator());
1630       else if (CastInst* C = dyn_cast<CastInst>(U))
1631         newVal = CastInst::create(C->getOpcode(), s1, C->getType(),
1632                                   C->getName()+".gvnpre", 
1633                                   (*PI)->getTerminator());
1634       else if (GetElementPtrInst* G = dyn_cast<GetElementPtrInst>(U))
1635         newVal = new GetElementPtrInst(s1, &sVarargs[0], sVarargs.size(), 
1636                                        G->getName()+".gvnpre", 
1637                                        (*PI)->getTerminator());
1638                                 
1639                   
1640       VN.add(newVal, VN.lookup(U));
1641                   
1642       ValueNumberedSet& predAvail = availableOut[*PI];
1643       val_replace(predAvail, newVal);
1644       val_replace(new_sets[*PI], newVal);
1645       predAvail.set(VN.lookup(newVal));
1646             
1647       std::map<BasicBlock*, Value*>::iterator av = avail.find(*PI);
1648       if (av != avail.end())
1649         avail.erase(av);
1650       avail.insert(std::make_pair(*PI, newVal));
1651                   
1652       ++NumInsertedVals;
1653     }
1654   }
1655               
1656   PHINode* p = 0;
1657               
1658   for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
1659     if (p == 0)
1660       p = new PHINode(avail[*PI]->getType(), "gvnpre-join", BB->begin());
1661     
1662     p->addIncoming(avail[*PI], *PI);
1663   }
1664
1665   VN.add(p, VN.lookup(e));
1666   val_replace(availableOut[BB], p);
1667   availableOut[BB].set(VN.lookup(e));
1668   generatedPhis[BB].insert(p);
1669   generatedPhis[BB].set(VN.lookup(e));
1670   new_sets[BB].insert(p);
1671   new_sets[BB].set(VN.lookup(e));
1672               
1673   ++NumInsertedPhis;
1674 }
1675
1676 /// insertion_mergepoint - When walking the dom tree, check at each merge
1677 /// block for the possibility of a partial redundancy.  If present, eliminate it
1678 unsigned GVNPRE::insertion_mergepoint(std::vector<Value*>& workList,
1679                                       df_iterator<DomTreeNode*>& D,
1680                     std::map<BasicBlock*, ValueNumberedSet >& new_sets) {
1681   bool changed_function = false;
1682   bool new_stuff = false;
1683   
1684   BasicBlock* BB = D->getBlock();
1685   for (unsigned i = 0; i < workList.size(); ++i) {
1686     Value* e = workList[i];
1687           
1688     if (isa<BinaryOperator>(e) || isa<CmpInst>(e) ||
1689         isa<ExtractElementInst>(e) || isa<InsertElementInst>(e) ||
1690         isa<ShuffleVectorInst>(e) || isa<SelectInst>(e) || isa<CastInst>(e) ||
1691         isa<GetElementPtrInst>(e)) {
1692       if (availableOut[D->getIDom()->getBlock()].test(VN.lookup(e)))
1693         continue;
1694             
1695       std::map<BasicBlock*, Value*> avail;
1696       bool by_some = false;
1697       bool all_same = true;
1698       Value * first_s = 0;
1699             
1700       for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;
1701            ++PI) {
1702         Value *e2 = phi_translate(e, *PI, BB);
1703         Value *e3 = find_leader(availableOut[*PI], VN.lookup(e2));
1704               
1705         if (e3 == 0) {
1706           std::map<BasicBlock*, Value*>::iterator av = avail.find(*PI);
1707           if (av != avail.end())
1708             avail.erase(av);
1709           avail.insert(std::make_pair(*PI, e2));
1710           all_same = false;
1711         } else {
1712           std::map<BasicBlock*, Value*>::iterator av = avail.find(*PI);
1713           if (av != avail.end())
1714             avail.erase(av);
1715           avail.insert(std::make_pair(*PI, e3));
1716                 
1717           by_some = true;
1718           if (first_s == 0)
1719             first_s = e3;
1720           else if (first_s != e3)
1721             all_same = false;
1722         }
1723       }
1724             
1725       if (by_some && !all_same &&
1726           !generatedPhis[BB].test(VN.lookup(e))) {
1727         insertion_pre(e, BB, avail, new_sets);
1728               
1729         changed_function = true;
1730         new_stuff = true;
1731       }
1732     }
1733   }
1734   
1735   unsigned retval = 0;
1736   if (changed_function)
1737     retval += 1;
1738   if (new_stuff)
1739     retval += 2;
1740   
1741   return retval;
1742 }
1743
1744 /// insert - Phase 2 of the main algorithm.  Walk the dominator tree looking for
1745 /// merge points.  When one is found, check for a partial redundancy.  If one is
1746 /// present, eliminate it.  Repeat this walk until no changes are made.
1747 bool GVNPRE::insertion(Function& F) {
1748   bool changed_function = false;
1749
1750   DominatorTree &DT = getAnalysis<DominatorTree>();  
1751   
1752   std::map<BasicBlock*, ValueNumberedSet> new_sets;
1753   bool new_stuff = true;
1754   while (new_stuff) {
1755     new_stuff = false;
1756     for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1757          E = df_end(DT.getRootNode()); DI != E; ++DI) {
1758       BasicBlock* BB = DI->getBlock();
1759       
1760       if (BB == 0)
1761         continue;
1762       
1763       ValueNumberedSet& availOut = availableOut[BB];
1764       ValueNumberedSet& anticIn = anticipatedIn[BB];
1765       
1766       // Replace leaders with leaders inherited from dominator
1767       if (DI->getIDom() != 0) {
1768         ValueNumberedSet& dom_set = new_sets[DI->getIDom()->getBlock()];
1769         for (ValueNumberedSet::iterator I = dom_set.begin(),
1770              E = dom_set.end(); I != E; ++I) {
1771           val_replace(new_sets[BB], *I);
1772           val_replace(availOut, *I);
1773         }
1774       }
1775       
1776       // If there is more than one predecessor...
1777       if (pred_begin(BB) != pred_end(BB) && ++pred_begin(BB) != pred_end(BB)) {
1778         std::vector<Value*> workList;
1779         workList.reserve(anticIn.size());
1780         topo_sort(anticIn, workList);
1781         
1782         unsigned result = insertion_mergepoint(workList, DI, new_sets);
1783         if (result & 1)
1784           changed_function = true;
1785         if (result & 2)
1786           new_stuff = true;
1787       }
1788     }
1789   }
1790   
1791   return changed_function;
1792 }
1793
1794 // GVNPRE::runOnFunction - This is the main transformation entry point for a
1795 // function.
1796 //
1797 bool GVNPRE::runOnFunction(Function &F) {
1798   // Clean out global sets from any previous functions
1799   VN.clear();
1800   createdExpressions.clear();
1801   availableOut.clear();
1802   anticipatedIn.clear();
1803   generatedPhis.clear();
1804  
1805   bool changed_function = false;
1806   
1807   // Phase 1: BuildSets
1808   // This phase calculates the AVAIL_OUT and ANTIC_IN sets
1809   buildsets(F);
1810   
1811   // Phase 2: Insert
1812   // This phase inserts values to make partially redundant values
1813   // fully redundant
1814   changed_function |= insertion(F);
1815   
1816   // Phase 3: Eliminate
1817   // This phase performs trivial full redundancy elimination
1818   changed_function |= elimination();
1819   
1820   // Phase 4: Cleanup
1821   // This phase cleans up values that were created solely
1822   // as leaders for expressions
1823   cleanup();
1824   
1825   return changed_function;
1826 }