ef6c3389c97a4b7f06e8aaa15bda5c7417f49181
[oota-llvm.git] / lib / Transforms / Scalar / GVN.cpp
1 //===- GVN.cpp - Eliminate redundant values and loads ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass performs global value numbering to eliminate fully redundant
11 // instructions.  It also performs simple dead load elimination.
12 //
13 // Note that this pass does the value numbering itself; it does not use the
14 // ValueNumbering analysis passes.
15 //
16 //===----------------------------------------------------------------------===//
17
18 #define DEBUG_TYPE "gvn"
19 #include "llvm/Transforms/Scalar.h"
20 #include "llvm/BasicBlock.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Function.h"
24 #include "llvm/IntrinsicInst.h"
25 #include "llvm/LLVMContext.h"
26 #include "llvm/Operator.h"
27 #include "llvm/Value.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/DepthFirstIterator.h"
30 #include "llvm/ADT/PostOrderIterator.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/Analysis/Dominators.h"
35 #include "llvm/Analysis/AliasAnalysis.h"
36 #include "llvm/Analysis/MallocHelper.h"
37 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
38 #include "llvm/Support/CFG.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/GetElementPtrTypeIterator.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/Target/TargetData.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include "llvm/Transforms/Utils/Local.h"
47 #include "llvm/Transforms/Utils/SSAUpdater.h"
48 #include <cstdio>
49 using namespace llvm;
50
51 STATISTIC(NumGVNInstr,  "Number of instructions deleted");
52 STATISTIC(NumGVNLoad,   "Number of loads deleted");
53 STATISTIC(NumGVNPRE,    "Number of instructions PRE'd");
54 STATISTIC(NumGVNBlocks, "Number of blocks merged");
55 STATISTIC(NumPRELoad,   "Number of loads PRE'd");
56
57 static cl::opt<bool> EnablePRE("enable-pre",
58                                cl::init(true), cl::Hidden);
59 static cl::opt<bool> EnableLoadPRE("enable-load-pre", cl::init(true));
60
61 //===----------------------------------------------------------------------===//
62 //                         ValueTable Class
63 //===----------------------------------------------------------------------===//
64
65 /// This class holds the mapping between values and value numbers.  It is used
66 /// as an efficient mechanism to determine the expression-wise equivalence of
67 /// two values.
68 namespace {
69   struct Expression {
70     enum ExpressionOpcode { ADD, FADD, SUB, FSUB, MUL, FMUL,
71                             UDIV, SDIV, FDIV, UREM, SREM,
72                             FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ,
73                             ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE,
74                             ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ,
75                             FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE,
76                             FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE,
77                             FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
78                             SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
79                             FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT,
80                             PTRTOINT, INTTOPTR, BITCAST, GEP, CALL, CONSTANT,
81                             INSERTVALUE, EXTRACTVALUE, EMPTY, TOMBSTONE };
82
83     ExpressionOpcode opcode;
84     const Type* type;
85     SmallVector<uint32_t, 4> varargs;
86     Value *function;
87
88     Expression() { }
89     Expression(ExpressionOpcode o) : opcode(o) { }
90
91     bool operator==(const Expression &other) const {
92       if (opcode != other.opcode)
93         return false;
94       else if (opcode == EMPTY || opcode == TOMBSTONE)
95         return true;
96       else if (type != other.type)
97         return false;
98       else if (function != other.function)
99         return false;
100       else {
101         if (varargs.size() != other.varargs.size())
102           return false;
103
104         for (size_t i = 0; i < varargs.size(); ++i)
105           if (varargs[i] != other.varargs[i])
106             return false;
107
108         return true;
109       }
110     }
111
112     bool operator!=(const Expression &other) const {
113       return !(*this == other);
114     }
115   };
116
117   class ValueTable {
118     private:
119       DenseMap<Value*, uint32_t> valueNumbering;
120       DenseMap<Expression, uint32_t> expressionNumbering;
121       AliasAnalysis* AA;
122       MemoryDependenceAnalysis* MD;
123       DominatorTree* DT;
124
125       uint32_t nextValueNumber;
126
127       Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
128       Expression::ExpressionOpcode getOpcode(CmpInst* C);
129       Expression::ExpressionOpcode getOpcode(CastInst* C);
130       Expression create_expression(BinaryOperator* BO);
131       Expression create_expression(CmpInst* C);
132       Expression create_expression(ShuffleVectorInst* V);
133       Expression create_expression(ExtractElementInst* C);
134       Expression create_expression(InsertElementInst* V);
135       Expression create_expression(SelectInst* V);
136       Expression create_expression(CastInst* C);
137       Expression create_expression(GetElementPtrInst* G);
138       Expression create_expression(CallInst* C);
139       Expression create_expression(Constant* C);
140       Expression create_expression(ExtractValueInst* C);
141       Expression create_expression(InsertValueInst* C);
142       
143       uint32_t lookup_or_add_call(CallInst* C);
144     public:
145       ValueTable() : nextValueNumber(1) { }
146       uint32_t lookup_or_add(Value *V);
147       uint32_t lookup(Value *V) const;
148       void add(Value *V, uint32_t num);
149       void clear();
150       void erase(Value *v);
151       unsigned size();
152       void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
153       AliasAnalysis *getAliasAnalysis() const { return AA; }
154       void setMemDep(MemoryDependenceAnalysis* M) { MD = M; }
155       void setDomTree(DominatorTree* D) { DT = D; }
156       uint32_t getNextUnusedValueNumber() { return nextValueNumber; }
157       void verifyRemoved(const Value *) const;
158   };
159 }
160
161 namespace llvm {
162 template <> struct DenseMapInfo<Expression> {
163   static inline Expression getEmptyKey() {
164     return Expression(Expression::EMPTY);
165   }
166
167   static inline Expression getTombstoneKey() {
168     return Expression(Expression::TOMBSTONE);
169   }
170
171   static unsigned getHashValue(const Expression e) {
172     unsigned hash = e.opcode;
173
174     hash = ((unsigned)((uintptr_t)e.type >> 4) ^
175             (unsigned)((uintptr_t)e.type >> 9));
176
177     for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
178          E = e.varargs.end(); I != E; ++I)
179       hash = *I + hash * 37;
180
181     hash = ((unsigned)((uintptr_t)e.function >> 4) ^
182             (unsigned)((uintptr_t)e.function >> 9)) +
183            hash * 37;
184
185     return hash;
186   }
187   static bool isEqual(const Expression &LHS, const Expression &RHS) {
188     return LHS == RHS;
189   }
190   static bool isPod() { return true; }
191 };
192 }
193
194 //===----------------------------------------------------------------------===//
195 //                     ValueTable Internal Functions
196 //===----------------------------------------------------------------------===//
197 Expression::ExpressionOpcode ValueTable::getOpcode(BinaryOperator* BO) {
198   switch(BO->getOpcode()) {
199   default: // THIS SHOULD NEVER HAPPEN
200     llvm_unreachable("Binary operator with unknown opcode?");
201   case Instruction::Add:  return Expression::ADD;
202   case Instruction::FAdd: return Expression::FADD;
203   case Instruction::Sub:  return Expression::SUB;
204   case Instruction::FSub: return Expression::FSUB;
205   case Instruction::Mul:  return Expression::MUL;
206   case Instruction::FMul: return Expression::FMUL;
207   case Instruction::UDiv: return Expression::UDIV;
208   case Instruction::SDiv: return Expression::SDIV;
209   case Instruction::FDiv: return Expression::FDIV;
210   case Instruction::URem: return Expression::UREM;
211   case Instruction::SRem: return Expression::SREM;
212   case Instruction::FRem: return Expression::FREM;
213   case Instruction::Shl:  return Expression::SHL;
214   case Instruction::LShr: return Expression::LSHR;
215   case Instruction::AShr: return Expression::ASHR;
216   case Instruction::And:  return Expression::AND;
217   case Instruction::Or:   return Expression::OR;
218   case Instruction::Xor:  return Expression::XOR;
219   }
220 }
221
222 Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
223   if (isa<ICmpInst>(C)) {
224     switch (C->getPredicate()) {
225     default:  // THIS SHOULD NEVER HAPPEN
226       llvm_unreachable("Comparison with unknown predicate?");
227     case ICmpInst::ICMP_EQ:  return Expression::ICMPEQ;
228     case ICmpInst::ICMP_NE:  return Expression::ICMPNE;
229     case ICmpInst::ICMP_UGT: return Expression::ICMPUGT;
230     case ICmpInst::ICMP_UGE: return Expression::ICMPUGE;
231     case ICmpInst::ICMP_ULT: return Expression::ICMPULT;
232     case ICmpInst::ICMP_ULE: return Expression::ICMPULE;
233     case ICmpInst::ICMP_SGT: return Expression::ICMPSGT;
234     case ICmpInst::ICMP_SGE: return Expression::ICMPSGE;
235     case ICmpInst::ICMP_SLT: return Expression::ICMPSLT;
236     case ICmpInst::ICMP_SLE: return Expression::ICMPSLE;
237     }
238   } else {
239     switch (C->getPredicate()) {
240     default: // THIS SHOULD NEVER HAPPEN
241       llvm_unreachable("Comparison with unknown predicate?");
242     case FCmpInst::FCMP_OEQ: return Expression::FCMPOEQ;
243     case FCmpInst::FCMP_OGT: return Expression::FCMPOGT;
244     case FCmpInst::FCMP_OGE: return Expression::FCMPOGE;
245     case FCmpInst::FCMP_OLT: return Expression::FCMPOLT;
246     case FCmpInst::FCMP_OLE: return Expression::FCMPOLE;
247     case FCmpInst::FCMP_ONE: return Expression::FCMPONE;
248     case FCmpInst::FCMP_ORD: return Expression::FCMPORD;
249     case FCmpInst::FCMP_UNO: return Expression::FCMPUNO;
250     case FCmpInst::FCMP_UEQ: return Expression::FCMPUEQ;
251     case FCmpInst::FCMP_UGT: return Expression::FCMPUGT;
252     case FCmpInst::FCMP_UGE: return Expression::FCMPUGE;
253     case FCmpInst::FCMP_ULT: return Expression::FCMPULT;
254     case FCmpInst::FCMP_ULE: return Expression::FCMPULE;
255     case FCmpInst::FCMP_UNE: return Expression::FCMPUNE;
256     }
257   }
258 }
259
260 Expression::ExpressionOpcode ValueTable::getOpcode(CastInst* C) {
261   switch(C->getOpcode()) {
262   default: // THIS SHOULD NEVER HAPPEN
263     llvm_unreachable("Cast operator with unknown opcode?");
264   case Instruction::Trunc:    return Expression::TRUNC;
265   case Instruction::ZExt:     return Expression::ZEXT;
266   case Instruction::SExt:     return Expression::SEXT;
267   case Instruction::FPToUI:   return Expression::FPTOUI;
268   case Instruction::FPToSI:   return Expression::FPTOSI;
269   case Instruction::UIToFP:   return Expression::UITOFP;
270   case Instruction::SIToFP:   return Expression::SITOFP;
271   case Instruction::FPTrunc:  return Expression::FPTRUNC;
272   case Instruction::FPExt:    return Expression::FPEXT;
273   case Instruction::PtrToInt: return Expression::PTRTOINT;
274   case Instruction::IntToPtr: return Expression::INTTOPTR;
275   case Instruction::BitCast:  return Expression::BITCAST;
276   }
277 }
278
279 Expression ValueTable::create_expression(CallInst* C) {
280   Expression e;
281
282   e.type = C->getType();
283   e.function = C->getCalledFunction();
284   e.opcode = Expression::CALL;
285
286   for (CallInst::op_iterator I = C->op_begin()+1, E = C->op_end();
287        I != E; ++I)
288     e.varargs.push_back(lookup_or_add(*I));
289
290   return e;
291 }
292
293 Expression ValueTable::create_expression(BinaryOperator* BO) {
294   Expression e;
295   e.varargs.push_back(lookup_or_add(BO->getOperand(0)));
296   e.varargs.push_back(lookup_or_add(BO->getOperand(1)));
297   e.function = 0;
298   e.type = BO->getType();
299   e.opcode = getOpcode(BO);
300
301   return e;
302 }
303
304 Expression ValueTable::create_expression(CmpInst* C) {
305   Expression e;
306
307   e.varargs.push_back(lookup_or_add(C->getOperand(0)));
308   e.varargs.push_back(lookup_or_add(C->getOperand(1)));
309   e.function = 0;
310   e.type = C->getType();
311   e.opcode = getOpcode(C);
312
313   return e;
314 }
315
316 Expression ValueTable::create_expression(CastInst* C) {
317   Expression e;
318
319   e.varargs.push_back(lookup_or_add(C->getOperand(0)));
320   e.function = 0;
321   e.type = C->getType();
322   e.opcode = getOpcode(C);
323
324   return e;
325 }
326
327 Expression ValueTable::create_expression(ShuffleVectorInst* S) {
328   Expression e;
329
330   e.varargs.push_back(lookup_or_add(S->getOperand(0)));
331   e.varargs.push_back(lookup_or_add(S->getOperand(1)));
332   e.varargs.push_back(lookup_or_add(S->getOperand(2)));
333   e.function = 0;
334   e.type = S->getType();
335   e.opcode = Expression::SHUFFLE;
336
337   return e;
338 }
339
340 Expression ValueTable::create_expression(ExtractElementInst* E) {
341   Expression e;
342
343   e.varargs.push_back(lookup_or_add(E->getOperand(0)));
344   e.varargs.push_back(lookup_or_add(E->getOperand(1)));
345   e.function = 0;
346   e.type = E->getType();
347   e.opcode = Expression::EXTRACT;
348
349   return e;
350 }
351
352 Expression ValueTable::create_expression(InsertElementInst* I) {
353   Expression e;
354
355   e.varargs.push_back(lookup_or_add(I->getOperand(0)));
356   e.varargs.push_back(lookup_or_add(I->getOperand(1)));
357   e.varargs.push_back(lookup_or_add(I->getOperand(2)));
358   e.function = 0;
359   e.type = I->getType();
360   e.opcode = Expression::INSERT;
361
362   return e;
363 }
364
365 Expression ValueTable::create_expression(SelectInst* I) {
366   Expression e;
367
368   e.varargs.push_back(lookup_or_add(I->getCondition()));
369   e.varargs.push_back(lookup_or_add(I->getTrueValue()));
370   e.varargs.push_back(lookup_or_add(I->getFalseValue()));
371   e.function = 0;
372   e.type = I->getType();
373   e.opcode = Expression::SELECT;
374
375   return e;
376 }
377
378 Expression ValueTable::create_expression(GetElementPtrInst* G) {
379   Expression e;
380
381   e.varargs.push_back(lookup_or_add(G->getPointerOperand()));
382   e.function = 0;
383   e.type = G->getType();
384   e.opcode = Expression::GEP;
385
386   for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
387        I != E; ++I)
388     e.varargs.push_back(lookup_or_add(*I));
389
390   return e;
391 }
392
393 Expression ValueTable::create_expression(ExtractValueInst* E) {
394   Expression e;
395
396   e.varargs.push_back(lookup_or_add(E->getAggregateOperand()));
397   for (ExtractValueInst::idx_iterator II = E->idx_begin(), IE = E->idx_end();
398        II != IE; ++II)
399     e.varargs.push_back(*II);
400   e.function = 0;
401   e.type = E->getType();
402   e.opcode = Expression::EXTRACTVALUE;
403
404   return e;
405 }
406
407 Expression ValueTable::create_expression(InsertValueInst* E) {
408   Expression e;
409
410   e.varargs.push_back(lookup_or_add(E->getAggregateOperand()));
411   e.varargs.push_back(lookup_or_add(E->getInsertedValueOperand()));
412   for (InsertValueInst::idx_iterator II = E->idx_begin(), IE = E->idx_end();
413        II != IE; ++II)
414     e.varargs.push_back(*II);
415   e.function = 0;
416   e.type = E->getType();
417   e.opcode = Expression::INSERTVALUE;
418
419   return e;
420 }
421
422 //===----------------------------------------------------------------------===//
423 //                     ValueTable External Functions
424 //===----------------------------------------------------------------------===//
425
426 /// add - Insert a value into the table with a specified value number.
427 void ValueTable::add(Value *V, uint32_t num) {
428   valueNumbering.insert(std::make_pair(V, num));
429 }
430
431 uint32_t ValueTable::lookup_or_add_call(CallInst* C) {
432   if (AA->doesNotAccessMemory(C)) {
433     Expression exp = create_expression(C);
434     uint32_t& e = expressionNumbering[exp];
435     if (!e) e = nextValueNumber++;
436     valueNumbering[C] = e;
437     return e;
438   } else if (AA->onlyReadsMemory(C)) {
439     Expression exp = create_expression(C);
440     uint32_t& e = expressionNumbering[exp];
441     if (!e) {
442       e = nextValueNumber++;
443       valueNumbering[C] = e;
444       return e;
445     }
446
447     MemDepResult local_dep = MD->getDependency(C);
448
449     if (!local_dep.isDef() && !local_dep.isNonLocal()) {
450       valueNumbering[C] =  nextValueNumber;
451       return nextValueNumber++;
452     }
453
454     if (local_dep.isDef()) {
455       CallInst* local_cdep = cast<CallInst>(local_dep.getInst());
456
457       if (local_cdep->getNumOperands() != C->getNumOperands()) {
458         valueNumbering[C] = nextValueNumber;
459         return nextValueNumber++;
460       }
461
462       for (unsigned i = 1; i < C->getNumOperands(); ++i) {
463         uint32_t c_vn = lookup_or_add(C->getOperand(i));
464         uint32_t cd_vn = lookup_or_add(local_cdep->getOperand(i));
465         if (c_vn != cd_vn) {
466           valueNumbering[C] = nextValueNumber;
467           return nextValueNumber++;
468         }
469       }
470
471       uint32_t v = lookup_or_add(local_cdep);
472       valueNumbering[C] = v;
473       return v;
474     }
475
476     // Non-local case.
477     const MemoryDependenceAnalysis::NonLocalDepInfo &deps =
478       MD->getNonLocalCallDependency(CallSite(C));
479     // FIXME: call/call dependencies for readonly calls should return def, not
480     // clobber!  Move the checking logic to MemDep!
481     CallInst* cdep = 0;
482
483     // Check to see if we have a single dominating call instruction that is
484     // identical to C.
485     for (unsigned i = 0, e = deps.size(); i != e; ++i) {
486       const MemoryDependenceAnalysis::NonLocalDepEntry *I = &deps[i];
487       // Ignore non-local dependencies.
488       if (I->second.isNonLocal())
489         continue;
490
491       // We don't handle non-depedencies.  If we already have a call, reject
492       // instruction dependencies.
493       if (I->second.isClobber() || cdep != 0) {
494         cdep = 0;
495         break;
496       }
497
498       CallInst *NonLocalDepCall = dyn_cast<CallInst>(I->second.getInst());
499       // FIXME: All duplicated with non-local case.
500       if (NonLocalDepCall && DT->properlyDominates(I->first, C->getParent())){
501         cdep = NonLocalDepCall;
502         continue;
503       }
504
505       cdep = 0;
506       break;
507     }
508
509     if (!cdep) {
510       valueNumbering[C] = nextValueNumber;
511       return nextValueNumber++;
512     }
513
514     if (cdep->getNumOperands() != C->getNumOperands()) {
515       valueNumbering[C] = nextValueNumber;
516       return nextValueNumber++;
517     }
518     for (unsigned i = 1; i < C->getNumOperands(); ++i) {
519       uint32_t c_vn = lookup_or_add(C->getOperand(i));
520       uint32_t cd_vn = lookup_or_add(cdep->getOperand(i));
521       if (c_vn != cd_vn) {
522         valueNumbering[C] = nextValueNumber;
523         return nextValueNumber++;
524       }
525     }
526
527     uint32_t v = lookup_or_add(cdep);
528     valueNumbering[C] = v;
529     return v;
530
531   } else {
532     valueNumbering[C] = nextValueNumber;
533     return nextValueNumber++;
534   }
535 }
536
537 /// lookup_or_add - Returns the value number for the specified value, assigning
538 /// it a new number if it did not have one before.
539 uint32_t ValueTable::lookup_or_add(Value *V) {
540   DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
541   if (VI != valueNumbering.end())
542     return VI->second;
543
544   if (!isa<Instruction>(V)) {
545     valueNumbering[V] = nextValueNumber;
546     return nextValueNumber++;
547   }
548   
549   Instruction* I = cast<Instruction>(V);
550   Expression exp;
551   switch (I->getOpcode()) {
552     case Instruction::Call:
553       return lookup_or_add_call(cast<CallInst>(I));
554     case Instruction::Add:
555     case Instruction::FAdd:
556     case Instruction::Sub:
557     case Instruction::FSub:
558     case Instruction::Mul:
559     case Instruction::FMul:
560     case Instruction::UDiv:
561     case Instruction::SDiv:
562     case Instruction::FDiv:
563     case Instruction::URem:
564     case Instruction::SRem:
565     case Instruction::FRem:
566     case Instruction::Shl:
567     case Instruction::LShr:
568     case Instruction::AShr:
569     case Instruction::And:
570     case Instruction::Or :
571     case Instruction::Xor:
572       exp = create_expression(cast<BinaryOperator>(I));
573       break;
574     case Instruction::ICmp:
575     case Instruction::FCmp:
576       exp = create_expression(cast<CmpInst>(I));
577       break;
578     case Instruction::Trunc:
579     case Instruction::ZExt:
580     case Instruction::SExt:
581     case Instruction::FPToUI:
582     case Instruction::FPToSI:
583     case Instruction::UIToFP:
584     case Instruction::SIToFP:
585     case Instruction::FPTrunc:
586     case Instruction::FPExt:
587     case Instruction::PtrToInt:
588     case Instruction::IntToPtr:
589     case Instruction::BitCast:
590       exp = create_expression(cast<CastInst>(I));
591       break;
592     case Instruction::Select:
593       exp = create_expression(cast<SelectInst>(I));
594       break;
595     case Instruction::ExtractElement:
596       exp = create_expression(cast<ExtractElementInst>(I));
597       break;
598     case Instruction::InsertElement:
599       exp = create_expression(cast<InsertElementInst>(I));
600       break;
601     case Instruction::ShuffleVector:
602       exp = create_expression(cast<ShuffleVectorInst>(I));
603       break;
604     case Instruction::ExtractValue:
605       exp = create_expression(cast<ExtractValueInst>(I));
606       break;
607     case Instruction::InsertValue:
608       exp = create_expression(cast<InsertValueInst>(I));
609       break;      
610     case Instruction::GetElementPtr:
611       exp = create_expression(cast<GetElementPtrInst>(I));
612       break;
613     default:
614       valueNumbering[V] = nextValueNumber;
615       return nextValueNumber++;
616   }
617
618   uint32_t& e = expressionNumbering[exp];
619   if (!e) e = nextValueNumber++;
620   valueNumbering[V] = e;
621   return e;
622 }
623
624 /// lookup - Returns the value number of the specified value. Fails if
625 /// the value has not yet been numbered.
626 uint32_t ValueTable::lookup(Value *V) const {
627   DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
628   assert(VI != valueNumbering.end() && "Value not numbered?");
629   return VI->second;
630 }
631
632 /// clear - Remove all entries from the ValueTable
633 void ValueTable::clear() {
634   valueNumbering.clear();
635   expressionNumbering.clear();
636   nextValueNumber = 1;
637 }
638
639 /// erase - Remove a value from the value numbering
640 void ValueTable::erase(Value *V) {
641   valueNumbering.erase(V);
642 }
643
644 /// verifyRemoved - Verify that the value is removed from all internal data
645 /// structures.
646 void ValueTable::verifyRemoved(const Value *V) const {
647   for (DenseMap<Value*, uint32_t>::iterator
648          I = valueNumbering.begin(), E = valueNumbering.end(); I != E; ++I) {
649     assert(I->first != V && "Inst still occurs in value numbering map!");
650   }
651 }
652
653 //===----------------------------------------------------------------------===//
654 //                                GVN Pass
655 //===----------------------------------------------------------------------===//
656
657 namespace {
658   struct ValueNumberScope {
659     ValueNumberScope* parent;
660     DenseMap<uint32_t, Value*> table;
661
662     ValueNumberScope(ValueNumberScope* p) : parent(p) { }
663   };
664 }
665
666 namespace {
667
668   class GVN : public FunctionPass {
669     bool runOnFunction(Function &F);
670   public:
671     static char ID; // Pass identification, replacement for typeid
672     GVN() : FunctionPass(&ID) { }
673
674   private:
675     MemoryDependenceAnalysis *MD;
676     DominatorTree *DT;
677
678     ValueTable VN;
679     DenseMap<BasicBlock*, ValueNumberScope*> localAvail;
680
681     // This transformation requires dominator postdominator info
682     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
683       AU.addRequired<DominatorTree>();
684       AU.addRequired<MemoryDependenceAnalysis>();
685       AU.addRequired<AliasAnalysis>();
686
687       AU.addPreserved<DominatorTree>();
688       AU.addPreserved<AliasAnalysis>();
689     }
690
691     // Helper fuctions
692     // FIXME: eliminate or document these better
693     bool processLoad(LoadInst* L,
694                      SmallVectorImpl<Instruction*> &toErase);
695     bool processInstruction(Instruction *I,
696                             SmallVectorImpl<Instruction*> &toErase);
697     bool processNonLocalLoad(LoadInst* L,
698                              SmallVectorImpl<Instruction*> &toErase);
699     bool processBlock(BasicBlock *BB);
700     void dump(DenseMap<uint32_t, Value*>& d);
701     bool iterateOnFunction(Function &F);
702     Value *CollapsePhi(PHINode* p);
703     bool performPRE(Function& F);
704     Value *lookupNumber(BasicBlock *BB, uint32_t num);
705     void cleanupGlobalSets();
706     void verifyRemoved(const Instruction *I) const;
707   };
708
709   char GVN::ID = 0;
710 }
711
712 // createGVNPass - The public interface to this file...
713 FunctionPass *llvm::createGVNPass() { return new GVN(); }
714
715 static RegisterPass<GVN> X("gvn",
716                            "Global Value Numbering");
717
718 void GVN::dump(DenseMap<uint32_t, Value*>& d) {
719   printf("{\n");
720   for (DenseMap<uint32_t, Value*>::iterator I = d.begin(),
721        E = d.end(); I != E; ++I) {
722       printf("%d\n", I->first);
723       I->second->dump();
724   }
725   printf("}\n");
726 }
727
728 static bool isSafeReplacement(PHINode* p, Instruction *inst) {
729   if (!isa<PHINode>(inst))
730     return true;
731
732   for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end();
733        UI != E; ++UI)
734     if (PHINode* use_phi = dyn_cast<PHINode>(UI))
735       if (use_phi->getParent() == inst->getParent())
736         return false;
737
738   return true;
739 }
740
741 Value *GVN::CollapsePhi(PHINode *PN) {
742   Value *ConstVal = PN->hasConstantValue(DT);
743   if (!ConstVal) return 0;
744
745   Instruction *Inst = dyn_cast<Instruction>(ConstVal);
746   if (!Inst)
747     return ConstVal;
748
749   if (DT->dominates(Inst, PN))
750     if (isSafeReplacement(PN, Inst))
751       return Inst;
752   return 0;
753 }
754
755 /// IsValueFullyAvailableInBlock - Return true if we can prove that the value
756 /// we're analyzing is fully available in the specified block.  As we go, keep
757 /// track of which blocks we know are fully alive in FullyAvailableBlocks.  This
758 /// map is actually a tri-state map with the following values:
759 ///   0) we know the block *is not* fully available.
760 ///   1) we know the block *is* fully available.
761 ///   2) we do not know whether the block is fully available or not, but we are
762 ///      currently speculating that it will be.
763 ///   3) we are speculating for this block and have used that to speculate for
764 ///      other blocks.
765 static bool IsValueFullyAvailableInBlock(BasicBlock *BB,
766                             DenseMap<BasicBlock*, char> &FullyAvailableBlocks) {
767   // Optimistically assume that the block is fully available and check to see
768   // if we already know about this block in one lookup.
769   std::pair<DenseMap<BasicBlock*, char>::iterator, char> IV =
770     FullyAvailableBlocks.insert(std::make_pair(BB, 2));
771
772   // If the entry already existed for this block, return the precomputed value.
773   if (!IV.second) {
774     // If this is a speculative "available" value, mark it as being used for
775     // speculation of other blocks.
776     if (IV.first->second == 2)
777       IV.first->second = 3;
778     return IV.first->second != 0;
779   }
780
781   // Otherwise, see if it is fully available in all predecessors.
782   pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
783
784   // If this block has no predecessors, it isn't live-in here.
785   if (PI == PE)
786     goto SpeculationFailure;
787
788   for (; PI != PE; ++PI)
789     // If the value isn't fully available in one of our predecessors, then it
790     // isn't fully available in this block either.  Undo our previous
791     // optimistic assumption and bail out.
792     if (!IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks))
793       goto SpeculationFailure;
794
795   return true;
796
797 // SpeculationFailure - If we get here, we found out that this is not, after
798 // all, a fully-available block.  We have a problem if we speculated on this and
799 // used the speculation to mark other blocks as available.
800 SpeculationFailure:
801   char &BBVal = FullyAvailableBlocks[BB];
802
803   // If we didn't speculate on this, just return with it set to false.
804   if (BBVal == 2) {
805     BBVal = 0;
806     return false;
807   }
808
809   // If we did speculate on this value, we could have blocks set to 1 that are
810   // incorrect.  Walk the (transitive) successors of this block and mark them as
811   // 0 if set to one.
812   SmallVector<BasicBlock*, 32> BBWorklist;
813   BBWorklist.push_back(BB);
814
815   while (!BBWorklist.empty()) {
816     BasicBlock *Entry = BBWorklist.pop_back_val();
817     // Note that this sets blocks to 0 (unavailable) if they happen to not
818     // already be in FullyAvailableBlocks.  This is safe.
819     char &EntryVal = FullyAvailableBlocks[Entry];
820     if (EntryVal == 0) continue;  // Already unavailable.
821
822     // Mark as unavailable.
823     EntryVal = 0;
824
825     for (succ_iterator I = succ_begin(Entry), E = succ_end(Entry); I != E; ++I)
826       BBWorklist.push_back(*I);
827   }
828
829   return false;
830 }
831
832
833 /// CanCoerceMustAliasedValueToLoad - Return true if
834 /// CoerceAvailableValueToLoadType will succeed.
835 static bool CanCoerceMustAliasedValueToLoad(Value *StoredVal,
836                                             const Type *LoadTy,
837                                             const TargetData &TD) {
838   // If the loaded or stored value is an first class array or struct, don't try
839   // to transform them.  We need to be able to bitcast to integer.
840   if (isa<StructType>(LoadTy) || isa<ArrayType>(LoadTy) ||
841       isa<StructType>(StoredVal->getType()) ||
842       isa<ArrayType>(StoredVal->getType()))
843     return false;
844   
845   // The store has to be at least as big as the load.
846   if (TD.getTypeSizeInBits(StoredVal->getType()) <
847         TD.getTypeSizeInBits(LoadTy))
848     return false;
849   
850   return true;
851 }
852   
853
854 /// CoerceAvailableValueToLoadType - If we saw a store of a value to memory, and
855 /// then a load from a must-aliased pointer of a different type, try to coerce
856 /// the stored value.  LoadedTy is the type of the load we want to replace and
857 /// InsertPt is the place to insert new instructions.
858 ///
859 /// If we can't do it, return null.
860 static Value *CoerceAvailableValueToLoadType(Value *StoredVal, 
861                                              const Type *LoadedTy,
862                                              Instruction *InsertPt,
863                                              const TargetData &TD) {
864   if (!CanCoerceMustAliasedValueToLoad(StoredVal, LoadedTy, TD))
865     return 0;
866   
867   const Type *StoredValTy = StoredVal->getType();
868   
869   uint64_t StoreSize = TD.getTypeSizeInBits(StoredValTy);
870   uint64_t LoadSize = TD.getTypeSizeInBits(LoadedTy);
871   
872   // If the store and reload are the same size, we can always reuse it.
873   if (StoreSize == LoadSize) {
874     if (isa<PointerType>(StoredValTy) && isa<PointerType>(LoadedTy)) {
875       // Pointer to Pointer -> use bitcast.
876       return new BitCastInst(StoredVal, LoadedTy, "", InsertPt);
877     }
878     
879     // Convert source pointers to integers, which can be bitcast.
880     if (isa<PointerType>(StoredValTy)) {
881       StoredValTy = TD.getIntPtrType(StoredValTy->getContext());
882       StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
883     }
884     
885     const Type *TypeToCastTo = LoadedTy;
886     if (isa<PointerType>(TypeToCastTo))
887       TypeToCastTo = TD.getIntPtrType(StoredValTy->getContext());
888     
889     if (StoredValTy != TypeToCastTo)
890       StoredVal = new BitCastInst(StoredVal, TypeToCastTo, "", InsertPt);
891     
892     // Cast to pointer if the load needs a pointer type.
893     if (isa<PointerType>(LoadedTy))
894       StoredVal = new IntToPtrInst(StoredVal, LoadedTy, "", InsertPt);
895     
896     return StoredVal;
897   }
898   
899   // If the loaded value is smaller than the available value, then we can
900   // extract out a piece from it.  If the available value is too small, then we
901   // can't do anything.
902   assert(StoreSize >= LoadSize && "CanCoerceMustAliasedValueToLoad fail");
903   
904   // Convert source pointers to integers, which can be manipulated.
905   if (isa<PointerType>(StoredValTy)) {
906     StoredValTy = TD.getIntPtrType(StoredValTy->getContext());
907     StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
908   }
909   
910   // Convert vectors and fp to integer, which can be manipulated.
911   if (!isa<IntegerType>(StoredValTy)) {
912     StoredValTy = IntegerType::get(StoredValTy->getContext(), StoreSize);
913     StoredVal = new BitCastInst(StoredVal, StoredValTy, "", InsertPt);
914   }
915   
916   // If this is a big-endian system, we need to shift the value down to the low
917   // bits so that a truncate will work.
918   if (TD.isBigEndian()) {
919     Constant *Val = ConstantInt::get(StoredVal->getType(), StoreSize-LoadSize);
920     StoredVal = BinaryOperator::CreateLShr(StoredVal, Val, "tmp", InsertPt);
921   }
922   
923   // Truncate the integer to the right size now.
924   const Type *NewIntTy = IntegerType::get(StoredValTy->getContext(), LoadSize);
925   StoredVal = new TruncInst(StoredVal, NewIntTy, "trunc", InsertPt);
926   
927   if (LoadedTy == NewIntTy)
928     return StoredVal;
929   
930   // If the result is a pointer, inttoptr.
931   if (isa<PointerType>(LoadedTy))
932     return new IntToPtrInst(StoredVal, LoadedTy, "inttoptr", InsertPt);
933   
934   // Otherwise, bitcast.
935   return new BitCastInst(StoredVal, LoadedTy, "bitcast", InsertPt);
936 }
937
938 /// GetBaseWithConstantOffset - Analyze the specified pointer to see if it can
939 /// be expressed as a base pointer plus a constant offset.  Return the base and
940 /// offset to the caller.
941 static Value *GetBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
942                                         const TargetData &TD) {
943   Operator *PtrOp = dyn_cast<Operator>(Ptr);
944   if (PtrOp == 0) return Ptr;
945   
946   // Just look through bitcasts.
947   if (PtrOp->getOpcode() == Instruction::BitCast)
948     return GetBaseWithConstantOffset(PtrOp->getOperand(0), Offset, TD);
949   
950   // If this is a GEP with constant indices, we can look through it.
951   GEPOperator *GEP = dyn_cast<GEPOperator>(PtrOp);
952   if (GEP == 0 || !GEP->hasAllConstantIndices()) return Ptr;
953   
954   gep_type_iterator GTI = gep_type_begin(GEP);
955   for (User::op_iterator I = GEP->idx_begin(), E = GEP->idx_end(); I != E;
956        ++I, ++GTI) {
957     ConstantInt *OpC = cast<ConstantInt>(*I);
958     if (OpC->isZero()) continue;
959     
960     // Handle a struct and array indices which add their offset to the pointer.
961     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
962       Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
963     } else {
964       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
965       Offset += OpC->getSExtValue()*Size;
966     }
967   }
968   
969   // Re-sign extend from the pointer size if needed to get overflow edge cases
970   // right.
971   unsigned PtrSize = TD.getPointerSizeInBits();
972   if (PtrSize < 64)
973     Offset = (Offset << (64-PtrSize)) >> (64-PtrSize);
974   
975   return GetBaseWithConstantOffset(GEP->getPointerOperand(), Offset, TD);
976 }
977
978
979 /// AnalyzeLoadFromClobberingStore - This function is called when we have a
980 /// memdep query of a load that ends up being a clobbering store.  This means
981 /// that the store *may* provide bits used by the load but we can't be sure
982 /// because the pointers don't mustalias.  Check this case to see if there is
983 /// anything more we can do before we give up.  This returns -1 if we have to
984 /// give up, or a byte number in the stored value of the piece that feeds the
985 /// load.
986 static int AnalyzeLoadFromClobberingStore(LoadInst *L, StoreInst *DepSI,
987                                           const TargetData &TD) {
988   // If the loaded or stored value is an first class array or struct, don't try
989   // to transform them.  We need to be able to bitcast to integer.
990   if (isa<StructType>(L->getType()) || isa<ArrayType>(L->getType()) ||
991       isa<StructType>(DepSI->getOperand(0)->getType()) ||
992       isa<ArrayType>(DepSI->getOperand(0)->getType()))
993     return -1;
994   
995   int64_t StoreOffset = 0, LoadOffset = 0;
996   Value *StoreBase = 
997     GetBaseWithConstantOffset(DepSI->getPointerOperand(), StoreOffset, TD);
998   Value *LoadBase = 
999     GetBaseWithConstantOffset(L->getPointerOperand(), LoadOffset, TD);
1000   if (StoreBase != LoadBase)
1001     return -1;
1002   
1003   // If the load and store are to the exact same address, they should have been
1004   // a must alias.  AA must have gotten confused.
1005   // FIXME: Study to see if/when this happens.
1006   if (LoadOffset == StoreOffset) {
1007 #if 0
1008     errs() << "STORE/LOAD DEP WITH COMMON POINTER MISSED:\n"
1009     << "Base       = " << *StoreBase << "\n"
1010     << "Store Ptr  = " << *DepSI->getPointerOperand() << "\n"
1011     << "Store Offs = " << StoreOffset << " - " << *DepSI << "\n"
1012     << "Load Ptr   = " << *L->getPointerOperand() << "\n"
1013     << "Load Offs  = " << LoadOffset << " - " << *L << "\n\n";
1014     errs() << "'" << L->getParent()->getParent()->getName() << "'"
1015     << *L->getParent();
1016 #endif
1017     return -1;
1018   }
1019   
1020   // If the load and store don't overlap at all, the store doesn't provide
1021   // anything to the load.  In this case, they really don't alias at all, AA
1022   // must have gotten confused.
1023   // FIXME: Investigate cases where this bails out, e.g. rdar://7238614. Then
1024   // remove this check, as it is duplicated with what we have below.
1025   uint64_t StoreSize = TD.getTypeSizeInBits(DepSI->getOperand(0)->getType());
1026   uint64_t LoadSize = TD.getTypeSizeInBits(L->getType());
1027   
1028   if ((StoreSize & 7) | (LoadSize & 7))
1029     return -1;
1030   StoreSize >>= 3;  // Convert to bytes.
1031   LoadSize >>= 3;
1032   
1033   
1034   bool isAAFailure = false;
1035   if (StoreOffset < LoadOffset) {
1036     isAAFailure = StoreOffset+int64_t(StoreSize) <= LoadOffset;
1037   } else {
1038     isAAFailure = LoadOffset+int64_t(LoadSize) <= StoreOffset;
1039   }
1040   if (isAAFailure) {
1041 #if 0
1042     errs() << "STORE LOAD DEP WITH COMMON BASE:\n"
1043     << "Base       = " << *StoreBase << "\n"
1044     << "Store Ptr  = " << *DepSI->getPointerOperand() << "\n"
1045     << "Store Offs = " << StoreOffset << " - " << *DepSI << "\n"
1046     << "Load Ptr   = " << *L->getPointerOperand() << "\n"
1047     << "Load Offs  = " << LoadOffset << " - " << *L << "\n\n";
1048     errs() << "'" << L->getParent()->getParent()->getName() << "'"
1049     << *L->getParent();
1050 #endif
1051     return -1;
1052   }
1053   
1054   // If the Load isn't completely contained within the stored bits, we don't
1055   // have all the bits to feed it.  We could do something crazy in the future
1056   // (issue a smaller load then merge the bits in) but this seems unlikely to be
1057   // valuable.
1058   if (StoreOffset > LoadOffset ||
1059       StoreOffset+StoreSize < LoadOffset+LoadSize)
1060     return -1;
1061   
1062   // Okay, we can do this transformation.  Return the number of bytes into the
1063   // store that the load is.
1064   return LoadOffset-StoreOffset;
1065 }  
1066
1067
1068 /// GetStoreValueForLoad - This function is called when we have a
1069 /// memdep query of a load that ends up being a clobbering store.  This means
1070 /// that the store *may* provide bits used by the load but we can't be sure
1071 /// because the pointers don't mustalias.  Check this case to see if there is
1072 /// anything more we can do before we give up.
1073 static Value *GetStoreValueForLoad(Value *SrcVal, unsigned Offset,
1074                                    const Type *LoadTy,
1075                                    Instruction *InsertPt, const TargetData &TD){
1076   LLVMContext &Ctx = SrcVal->getType()->getContext();
1077   
1078   uint64_t StoreSize = TD.getTypeSizeInBits(SrcVal->getType())/8;
1079   uint64_t LoadSize = TD.getTypeSizeInBits(LoadTy)/8;
1080   
1081   
1082   // Compute which bits of the stored value are being used by the load.  Convert
1083   // to an integer type to start with.
1084   if (isa<PointerType>(SrcVal->getType()))
1085     SrcVal = new PtrToIntInst(SrcVal, TD.getIntPtrType(Ctx), "tmp", InsertPt);
1086   if (!isa<IntegerType>(SrcVal->getType()))
1087     SrcVal = new BitCastInst(SrcVal, IntegerType::get(Ctx, StoreSize*8),
1088                              "tmp", InsertPt);
1089   
1090   // Shift the bits to the least significant depending on endianness.
1091   unsigned ShiftAmt;
1092   if (TD.isLittleEndian()) {
1093     ShiftAmt = Offset*8;
1094   } else {
1095     ShiftAmt = (StoreSize-LoadSize-Offset)*8;
1096   }
1097   
1098   if (ShiftAmt)
1099     SrcVal = BinaryOperator::CreateLShr(SrcVal,
1100                 ConstantInt::get(SrcVal->getType(), ShiftAmt), "tmp", InsertPt);
1101   
1102   if (LoadSize != StoreSize)
1103     SrcVal = new TruncInst(SrcVal, IntegerType::get(Ctx, LoadSize*8),
1104                            "tmp", InsertPt);
1105   
1106   return CoerceAvailableValueToLoadType(SrcVal, LoadTy, InsertPt, TD);
1107 }
1108
1109 struct AvailableValueInBlock {
1110   /// BB - The basic block in question.
1111   BasicBlock *BB;
1112   /// V - The value that is live out of the block.
1113   Value *V;
1114   /// Offset - The byte offset in V that is interesting for the load query.
1115   unsigned Offset;
1116   
1117   static AvailableValueInBlock get(BasicBlock *BB, Value *V,
1118                                    unsigned Offset = 0) {
1119     AvailableValueInBlock Res;
1120     Res.BB = BB;
1121     Res.V = V;
1122     Res.Offset = Offset;
1123     return Res;
1124   }
1125 };
1126
1127 /// ConstructSSAForLoadSet - Given a set of loads specified by ValuesPerBlock,
1128 /// construct SSA form, allowing us to eliminate LI.  This returns the value
1129 /// that should be used at LI's definition site.
1130 static Value *ConstructSSAForLoadSet(LoadInst *LI, 
1131                          SmallVectorImpl<AvailableValueInBlock> &ValuesPerBlock,
1132                                      const TargetData *TD,
1133                                      AliasAnalysis *AA) {
1134   SmallVector<PHINode*, 8> NewPHIs;
1135   SSAUpdater SSAUpdate(&NewPHIs);
1136   SSAUpdate.Initialize(LI);
1137   
1138   const Type *LoadTy = LI->getType();
1139   
1140   for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i) {
1141     BasicBlock *BB = ValuesPerBlock[i].BB;
1142     Value *AvailableVal = ValuesPerBlock[i].V;
1143     unsigned Offset = ValuesPerBlock[i].Offset;
1144     
1145     if (SSAUpdate.HasValueForBlock(BB))
1146       continue;
1147     
1148     if (AvailableVal->getType() != LoadTy) {
1149       assert(TD && "Need target data to handle type mismatch case");
1150       AvailableVal = GetStoreValueForLoad(AvailableVal, Offset, LoadTy,
1151                                           BB->getTerminator(), *TD);
1152       
1153       if (Offset) {
1154         DEBUG(errs() << "GVN COERCED NONLOCAL VAL:\n"
1155               << *ValuesPerBlock[i].V << '\n'
1156               << *AvailableVal << '\n' << "\n\n\n");
1157       }
1158       
1159       
1160       DEBUG(errs() << "GVN COERCED NONLOCAL VAL:\n"
1161             << *ValuesPerBlock[i].V << '\n'
1162             << *AvailableVal << '\n' << "\n\n\n");
1163     }
1164     
1165     SSAUpdate.AddAvailableValue(BB, AvailableVal);
1166   }
1167   
1168   // Perform PHI construction.
1169   Value *V = SSAUpdate.GetValueInMiddleOfBlock(LI->getParent());
1170   
1171   // If new PHI nodes were created, notify alias analysis.
1172   if (isa<PointerType>(V->getType()))
1173     for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i)
1174       AA->copyValue(LI, NewPHIs[i]);
1175
1176   return V;
1177 }
1178
1179 /// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
1180 /// non-local by performing PHI construction.
1181 bool GVN::processNonLocalLoad(LoadInst *LI,
1182                               SmallVectorImpl<Instruction*> &toErase) {
1183   // Find the non-local dependencies of the load.
1184   SmallVector<MemoryDependenceAnalysis::NonLocalDepEntry, 64> Deps;
1185   MD->getNonLocalPointerDependency(LI->getOperand(0), true, LI->getParent(),
1186                                    Deps);
1187   //DEBUG(errs() << "INVESTIGATING NONLOCAL LOAD: "
1188   //             << Deps.size() << *LI << '\n');
1189
1190   // If we had to process more than one hundred blocks to find the
1191   // dependencies, this load isn't worth worrying about.  Optimizing
1192   // it will be too expensive.
1193   if (Deps.size() > 100)
1194     return false;
1195
1196   // If we had a phi translation failure, we'll have a single entry which is a
1197   // clobber in the current block.  Reject this early.
1198   if (Deps.size() == 1 && Deps[0].second.isClobber()) {
1199     DEBUG(
1200       errs() << "GVN: non-local load ";
1201       WriteAsOperand(errs(), LI);
1202       errs() << " is clobbered by " << *Deps[0].second.getInst() << '\n';
1203     );
1204     return false;
1205   }
1206
1207   // Filter out useless results (non-locals, etc).  Keep track of the blocks
1208   // where we have a value available in repl, also keep track of whether we see
1209   // dependencies that produce an unknown value for the load (such as a call
1210   // that could potentially clobber the load).
1211   SmallVector<AvailableValueInBlock, 16> ValuesPerBlock;
1212   SmallVector<BasicBlock*, 16> UnavailableBlocks;
1213
1214   const TargetData *TD = 0;
1215   
1216   for (unsigned i = 0, e = Deps.size(); i != e; ++i) {
1217     BasicBlock *DepBB = Deps[i].first;
1218     MemDepResult DepInfo = Deps[i].second;
1219
1220     if (DepInfo.isClobber()) {
1221       // If the dependence is to a store that writes to a superset of the bits
1222       // read by the load, we can extract the bits we need for the load from the
1223       // stored value.
1224       if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInfo.getInst())) {
1225         if (TD == 0)
1226           TD = getAnalysisIfAvailable<TargetData>();
1227         if (TD) {
1228           int Offset = AnalyzeLoadFromClobberingStore(LI, DepSI, *TD);
1229           if (Offset != -1) {
1230             ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1231                                                            DepSI->getOperand(0),
1232                                                                 Offset));
1233             continue;
1234           }
1235         }
1236       }
1237       
1238       // FIXME: Handle memset/memcpy.
1239       UnavailableBlocks.push_back(DepBB);
1240       continue;
1241     }
1242
1243     Instruction *DepInst = DepInfo.getInst();
1244
1245     // Loading the allocation -> undef.
1246     if (isa<AllocationInst>(DepInst) || isMalloc(DepInst)) {
1247       ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1248                                              UndefValue::get(LI->getType())));
1249       continue;
1250     }
1251
1252     if (StoreInst *S = dyn_cast<StoreInst>(DepInst)) {
1253       // Reject loads and stores that are to the same address but are of
1254       // different types if we have to.
1255       if (S->getOperand(0)->getType() != LI->getType()) {
1256         if (TD == 0)
1257           TD = getAnalysisIfAvailable<TargetData>();
1258         
1259         // If the stored value is larger or equal to the loaded value, we can
1260         // reuse it.
1261         if (TD == 0 || !CanCoerceMustAliasedValueToLoad(S->getOperand(0),
1262                                                         LI->getType(), *TD)) {
1263           UnavailableBlocks.push_back(DepBB);
1264           continue;
1265         }
1266       }
1267
1268       ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1269                                                           S->getOperand(0)));
1270       continue;
1271     }
1272     
1273     if (LoadInst *LD = dyn_cast<LoadInst>(DepInst)) {
1274       // If the types mismatch and we can't handle it, reject reuse of the load.
1275       if (LD->getType() != LI->getType()) {
1276         if (TD == 0)
1277           TD = getAnalysisIfAvailable<TargetData>();
1278         
1279         // If the stored value is larger or equal to the loaded value, we can
1280         // reuse it.
1281         if (TD == 0 || !CanCoerceMustAliasedValueToLoad(LD, LI->getType(),*TD)){
1282           UnavailableBlocks.push_back(DepBB);
1283           continue;
1284         }          
1285       }
1286       ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB, LD));
1287       continue;
1288     }
1289     
1290     UnavailableBlocks.push_back(DepBB);
1291     continue;
1292   }
1293
1294   // If we have no predecessors that produce a known value for this load, exit
1295   // early.
1296   if (ValuesPerBlock.empty()) return false;
1297
1298   // If all of the instructions we depend on produce a known value for this
1299   // load, then it is fully redundant and we can use PHI insertion to compute
1300   // its value.  Insert PHIs and remove the fully redundant value now.
1301   if (UnavailableBlocks.empty()) {
1302     DEBUG(errs() << "GVN REMOVING NONLOCAL LOAD: " << *LI << '\n');
1303     
1304     // Perform PHI construction.
1305     Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, TD,
1306                                       VN.getAliasAnalysis());
1307     LI->replaceAllUsesWith(V);
1308
1309     if (isa<PHINode>(V))
1310       V->takeName(LI);
1311     if (isa<PointerType>(V->getType()))
1312       MD->invalidateCachedPointerInfo(V);
1313     toErase.push_back(LI);
1314     NumGVNLoad++;
1315     return true;
1316   }
1317
1318   if (!EnablePRE || !EnableLoadPRE)
1319     return false;
1320
1321   // Okay, we have *some* definitions of the value.  This means that the value
1322   // is available in some of our (transitive) predecessors.  Lets think about
1323   // doing PRE of this load.  This will involve inserting a new load into the
1324   // predecessor when it's not available.  We could do this in general, but
1325   // prefer to not increase code size.  As such, we only do this when we know
1326   // that we only have to insert *one* load (which means we're basically moving
1327   // the load, not inserting a new one).
1328
1329   SmallPtrSet<BasicBlock *, 4> Blockers;
1330   for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1331     Blockers.insert(UnavailableBlocks[i]);
1332
1333   // Lets find first basic block with more than one predecessor.  Walk backwards
1334   // through predecessors if needed.
1335   BasicBlock *LoadBB = LI->getParent();
1336   BasicBlock *TmpBB = LoadBB;
1337
1338   bool isSinglePred = false;
1339   bool allSingleSucc = true;
1340   while (TmpBB->getSinglePredecessor()) {
1341     isSinglePred = true;
1342     TmpBB = TmpBB->getSinglePredecessor();
1343     if (!TmpBB) // If haven't found any, bail now.
1344       return false;
1345     if (TmpBB == LoadBB) // Infinite (unreachable) loop.
1346       return false;
1347     if (Blockers.count(TmpBB))
1348       return false;
1349     if (TmpBB->getTerminator()->getNumSuccessors() != 1)
1350       allSingleSucc = false;
1351   }
1352
1353   assert(TmpBB);
1354   LoadBB = TmpBB;
1355
1356   // If we have a repl set with LI itself in it, this means we have a loop where
1357   // at least one of the values is LI.  Since this means that we won't be able
1358   // to eliminate LI even if we insert uses in the other predecessors, we will
1359   // end up increasing code size.  Reject this by scanning for LI.
1360   for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
1361     if (ValuesPerBlock[i].V == LI)
1362       return false;
1363
1364   if (isSinglePred) {
1365     bool isHot = false;
1366     for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
1367       if (Instruction *I = dyn_cast<Instruction>(ValuesPerBlock[i].V))
1368         // "Hot" Instruction is in some loop (because it dominates its dep.
1369         // instruction).
1370         if (DT->dominates(LI, I)) {
1371           isHot = true;
1372           break;
1373         }
1374
1375     // We are interested only in "hot" instructions. We don't want to do any
1376     // mis-optimizations here.
1377     if (!isHot)
1378       return false;
1379   }
1380
1381   // Okay, we have some hope :).  Check to see if the loaded value is fully
1382   // available in all but one predecessor.
1383   // FIXME: If we could restructure the CFG, we could make a common pred with
1384   // all the preds that don't have an available LI and insert a new load into
1385   // that one block.
1386   BasicBlock *UnavailablePred = 0;
1387
1388   DenseMap<BasicBlock*, char> FullyAvailableBlocks;
1389   for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
1390     FullyAvailableBlocks[ValuesPerBlock[i].BB] = true;
1391   for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1392     FullyAvailableBlocks[UnavailableBlocks[i]] = false;
1393
1394   for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB);
1395        PI != E; ++PI) {
1396     if (IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks))
1397       continue;
1398
1399     // If this load is not available in multiple predecessors, reject it.
1400     if (UnavailablePred && UnavailablePred != *PI)
1401       return false;
1402     UnavailablePred = *PI;
1403   }
1404
1405   assert(UnavailablePred != 0 &&
1406          "Fully available value should be eliminated above!");
1407
1408   // If the loaded pointer is PHI node defined in this block, do PHI translation
1409   // to get its value in the predecessor.
1410   Value *LoadPtr = LI->getOperand(0)->DoPHITranslation(LoadBB, UnavailablePred);
1411
1412   // Make sure the value is live in the predecessor.  If it was defined by a
1413   // non-PHI instruction in this block, we don't know how to recompute it above.
1414   if (Instruction *LPInst = dyn_cast<Instruction>(LoadPtr))
1415     if (!DT->dominates(LPInst->getParent(), UnavailablePred)) {
1416       DEBUG(errs() << "COULDN'T PRE LOAD BECAUSE PTR IS UNAVAILABLE IN PRED: "
1417                    << *LPInst << '\n' << *LI << "\n");
1418       return false;
1419     }
1420
1421   // We don't currently handle critical edges :(
1422   if (UnavailablePred->getTerminator()->getNumSuccessors() != 1) {
1423     DEBUG(errs() << "COULD NOT PRE LOAD BECAUSE OF CRITICAL EDGE '"
1424                  << UnavailablePred->getName() << "': " << *LI << '\n');
1425     return false;
1426   }
1427
1428   // Make sure it is valid to move this load here.  We have to watch out for:
1429   //  @1 = getelementptr (i8* p, ...
1430   //  test p and branch if == 0
1431   //  load @1
1432   // It is valid to have the getelementptr before the test, even if p can be 0,
1433   // as getelementptr only does address arithmetic.
1434   // If we are not pushing the value through any multiple-successor blocks
1435   // we do not have this case.  Otherwise, check that the load is safe to
1436   // put anywhere; this can be improved, but should be conservatively safe.
1437   if (!allSingleSucc &&
1438       !isSafeToLoadUnconditionally(LoadPtr, UnavailablePred->getTerminator()))
1439     return false;
1440
1441   // Okay, we can eliminate this load by inserting a reload in the predecessor
1442   // and using PHI construction to get the value in the other predecessors, do
1443   // it.
1444   DEBUG(errs() << "GVN REMOVING PRE LOAD: " << *LI << '\n');
1445
1446   Value *NewLoad = new LoadInst(LoadPtr, LI->getName()+".pre", false,
1447                                 LI->getAlignment(),
1448                                 UnavailablePred->getTerminator());
1449
1450   // Add the newly created load.
1451   ValuesPerBlock.push_back(AvailableValueInBlock::get(UnavailablePred,NewLoad));
1452
1453   // Perform PHI construction.
1454   Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, TD,
1455                                     VN.getAliasAnalysis());
1456   LI->replaceAllUsesWith(V);
1457   if (isa<PHINode>(V))
1458     V->takeName(LI);
1459   if (isa<PointerType>(V->getType()))
1460     MD->invalidateCachedPointerInfo(V);
1461   toErase.push_back(LI);
1462   NumPRELoad++;
1463   return true;
1464 }
1465
1466 /// processLoad - Attempt to eliminate a load, first by eliminating it
1467 /// locally, and then attempting non-local elimination if that fails.
1468 bool GVN::processLoad(LoadInst *L, SmallVectorImpl<Instruction*> &toErase) {
1469   if (L->isVolatile())
1470     return false;
1471
1472   // ... to a pointer that has been loaded from before...
1473   MemDepResult Dep = MD->getDependency(L);
1474
1475   // If the value isn't available, don't do anything!
1476   if (Dep.isClobber()) {
1477     // FIXME: We should handle memset/memcpy/memmove as dependent instructions
1478     // to forward the value if available.
1479     //if (isa<MemIntrinsic>(Dep.getInst()))
1480     //errs() << "LOAD DEPENDS ON MEM: " << *L << "\n" << *Dep.getInst()<<"\n\n";
1481     
1482     // Check to see if we have something like this:
1483     //   store i32 123, i32* %P
1484     //   %A = bitcast i32* %P to i8*
1485     //   %B = gep i8* %A, i32 1
1486     //   %C = load i8* %B
1487     //
1488     // We could do that by recognizing if the clobber instructions are obviously
1489     // a common base + constant offset, and if the previous store (or memset)
1490     // completely covers this load.  This sort of thing can happen in bitfield
1491     // access code.
1492     if (StoreInst *DepSI = dyn_cast<StoreInst>(Dep.getInst()))
1493       if (const TargetData *TD = getAnalysisIfAvailable<TargetData>()) {
1494         int Offset = AnalyzeLoadFromClobberingStore(L, DepSI, *TD);
1495         if (Offset != -1) {
1496           Value *AvailVal = GetStoreValueForLoad(DepSI->getOperand(0), Offset,
1497                                                  L->getType(), L, *TD);
1498           DEBUG(errs() << "GVN COERCED STORE BITS:\n" << *DepSI << '\n'
1499                        << *AvailVal << '\n' << *L << "\n\n\n");
1500     
1501           // Replace the load!
1502           L->replaceAllUsesWith(AvailVal);
1503           if (isa<PointerType>(AvailVal->getType()))
1504             MD->invalidateCachedPointerInfo(AvailVal);
1505           toErase.push_back(L);
1506           NumGVNLoad++;
1507           return true;
1508         }
1509       }
1510     
1511     DEBUG(
1512       // fast print dep, using operator<< on instruction would be too slow
1513       errs() << "GVN: load ";
1514       WriteAsOperand(errs(), L);
1515       Instruction *I = Dep.getInst();
1516       errs() << " is clobbered by " << *I << '\n';
1517     );
1518     return false;
1519   }
1520
1521   // If it is defined in another block, try harder.
1522   if (Dep.isNonLocal())
1523     return processNonLocalLoad(L, toErase);
1524
1525   Instruction *DepInst = Dep.getInst();
1526   if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInst)) {
1527     Value *StoredVal = DepSI->getOperand(0);
1528     
1529     // The store and load are to a must-aliased pointer, but they may not
1530     // actually have the same type.  See if we know how to reuse the stored
1531     // value (depending on its type).
1532     const TargetData *TD = 0;
1533     if (StoredVal->getType() != L->getType() &&
1534         (TD = getAnalysisIfAvailable<TargetData>())) {
1535       StoredVal = CoerceAvailableValueToLoadType(StoredVal, L->getType(),
1536                                                  L, *TD);
1537       if (StoredVal == 0)
1538         return false;
1539       
1540       DEBUG(errs() << "GVN COERCED STORE:\n" << *DepSI << '\n' << *StoredVal
1541                    << '\n' << *L << "\n\n\n");
1542     }
1543
1544     // Remove it!
1545     L->replaceAllUsesWith(StoredVal);
1546     if (isa<PointerType>(StoredVal->getType()))
1547       MD->invalidateCachedPointerInfo(StoredVal);
1548     toErase.push_back(L);
1549     NumGVNLoad++;
1550     return true;
1551   }
1552
1553   if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInst)) {
1554     Value *AvailableVal = DepLI;
1555     
1556     // The loads are of a must-aliased pointer, but they may not actually have
1557     // the same type.  See if we know how to reuse the previously loaded value
1558     // (depending on its type).
1559     const TargetData *TD = 0;
1560     if (DepLI->getType() != L->getType() &&
1561         (TD = getAnalysisIfAvailable<TargetData>())) {
1562       AvailableVal = CoerceAvailableValueToLoadType(DepLI, L->getType(), L,*TD);
1563       if (AvailableVal == 0)
1564         return false;
1565       
1566       DEBUG(errs() << "GVN COERCED LOAD:\n" << *DepLI << "\n" << *AvailableVal
1567                    << "\n" << *L << "\n\n\n");
1568     }
1569     
1570     // Remove it!
1571     L->replaceAllUsesWith(AvailableVal);
1572     if (isa<PointerType>(DepLI->getType()))
1573       MD->invalidateCachedPointerInfo(DepLI);
1574     toErase.push_back(L);
1575     NumGVNLoad++;
1576     return true;
1577   }
1578
1579   // If this load really doesn't depend on anything, then we must be loading an
1580   // undef value.  This can happen when loading for a fresh allocation with no
1581   // intervening stores, for example.
1582   if (isa<AllocationInst>(DepInst) || isMalloc(DepInst)) {
1583     L->replaceAllUsesWith(UndefValue::get(L->getType()));
1584     toErase.push_back(L);
1585     NumGVNLoad++;
1586     return true;
1587   }
1588
1589   return false;
1590 }
1591
1592 Value *GVN::lookupNumber(BasicBlock *BB, uint32_t num) {
1593   DenseMap<BasicBlock*, ValueNumberScope*>::iterator I = localAvail.find(BB);
1594   if (I == localAvail.end())
1595     return 0;
1596
1597   ValueNumberScope *Locals = I->second;
1598   while (Locals) {
1599     DenseMap<uint32_t, Value*>::iterator I = Locals->table.find(num);
1600     if (I != Locals->table.end())
1601       return I->second;
1602     Locals = Locals->parent;
1603   }
1604
1605   return 0;
1606 }
1607
1608
1609 /// processInstruction - When calculating availability, handle an instruction
1610 /// by inserting it into the appropriate sets
1611 bool GVN::processInstruction(Instruction *I,
1612                              SmallVectorImpl<Instruction*> &toErase) {
1613   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1614     bool Changed = processLoad(LI, toErase);
1615
1616     if (!Changed) {
1617       unsigned Num = VN.lookup_or_add(LI);
1618       localAvail[I->getParent()]->table.insert(std::make_pair(Num, LI));
1619     }
1620
1621     return Changed;
1622   }
1623
1624   uint32_t NextNum = VN.getNextUnusedValueNumber();
1625   unsigned Num = VN.lookup_or_add(I);
1626
1627   if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1628     localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
1629
1630     if (!BI->isConditional() || isa<Constant>(BI->getCondition()))
1631       return false;
1632
1633     Value *BranchCond = BI->getCondition();
1634     uint32_t CondVN = VN.lookup_or_add(BranchCond);
1635
1636     BasicBlock *TrueSucc = BI->getSuccessor(0);
1637     BasicBlock *FalseSucc = BI->getSuccessor(1);
1638
1639     if (TrueSucc->getSinglePredecessor())
1640       localAvail[TrueSucc]->table[CondVN] =
1641         ConstantInt::getTrue(TrueSucc->getContext());
1642     if (FalseSucc->getSinglePredecessor())
1643       localAvail[FalseSucc]->table[CondVN] =
1644         ConstantInt::getFalse(TrueSucc->getContext());
1645
1646     return false;
1647
1648   // Allocations are always uniquely numbered, so we can save time and memory
1649   // by fast failing them.
1650   } else if (isa<AllocationInst>(I) || isa<TerminatorInst>(I)) {
1651     localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
1652     return false;
1653   }
1654
1655   // Collapse PHI nodes
1656   if (PHINode* p = dyn_cast<PHINode>(I)) {
1657     Value *constVal = CollapsePhi(p);
1658
1659     if (constVal) {
1660       p->replaceAllUsesWith(constVal);
1661       if (isa<PointerType>(constVal->getType()))
1662         MD->invalidateCachedPointerInfo(constVal);
1663       VN.erase(p);
1664
1665       toErase.push_back(p);
1666     } else {
1667       localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
1668     }
1669
1670   // If the number we were assigned was a brand new VN, then we don't
1671   // need to do a lookup to see if the number already exists
1672   // somewhere in the domtree: it can't!
1673   } else if (Num == NextNum) {
1674     localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
1675
1676   // Perform fast-path value-number based elimination of values inherited from
1677   // dominators.
1678   } else if (Value *repl = lookupNumber(I->getParent(), Num)) {
1679     // Remove it!
1680     VN.erase(I);
1681     I->replaceAllUsesWith(repl);
1682     if (isa<PointerType>(repl->getType()))
1683       MD->invalidateCachedPointerInfo(repl);
1684     toErase.push_back(I);
1685     return true;
1686
1687   } else {
1688     localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
1689   }
1690
1691   return false;
1692 }
1693
1694 /// runOnFunction - This is the main transformation entry point for a function.
1695 bool GVN::runOnFunction(Function& F) {
1696   MD = &getAnalysis<MemoryDependenceAnalysis>();
1697   DT = &getAnalysis<DominatorTree>();
1698   VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
1699   VN.setMemDep(MD);
1700   VN.setDomTree(DT);
1701
1702   bool Changed = false;
1703   bool ShouldContinue = true;
1704
1705   // Merge unconditional branches, allowing PRE to catch more
1706   // optimization opportunities.
1707   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) {
1708     BasicBlock *BB = FI;
1709     ++FI;
1710     bool removedBlock = MergeBlockIntoPredecessor(BB, this);
1711     if (removedBlock) NumGVNBlocks++;
1712
1713     Changed |= removedBlock;
1714   }
1715
1716   unsigned Iteration = 0;
1717
1718   while (ShouldContinue) {
1719     DEBUG(errs() << "GVN iteration: " << Iteration << "\n");
1720     ShouldContinue = iterateOnFunction(F);
1721     Changed |= ShouldContinue;
1722     ++Iteration;
1723   }
1724
1725   if (EnablePRE) {
1726     bool PREChanged = true;
1727     while (PREChanged) {
1728       PREChanged = performPRE(F);
1729       Changed |= PREChanged;
1730     }
1731   }
1732   // FIXME: Should perform GVN again after PRE does something.  PRE can move
1733   // computations into blocks where they become fully redundant.  Note that
1734   // we can't do this until PRE's critical edge splitting updates memdep.
1735   // Actually, when this happens, we should just fully integrate PRE into GVN.
1736
1737   cleanupGlobalSets();
1738
1739   return Changed;
1740 }
1741
1742
1743 bool GVN::processBlock(BasicBlock *BB) {
1744   // FIXME: Kill off toErase by doing erasing eagerly in a helper function (and
1745   // incrementing BI before processing an instruction).
1746   SmallVector<Instruction*, 8> toErase;
1747   bool ChangedFunction = false;
1748
1749   for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1750        BI != BE;) {
1751     ChangedFunction |= processInstruction(BI, toErase);
1752     if (toErase.empty()) {
1753       ++BI;
1754       continue;
1755     }
1756
1757     // If we need some instructions deleted, do it now.
1758     NumGVNInstr += toErase.size();
1759
1760     // Avoid iterator invalidation.
1761     bool AtStart = BI == BB->begin();
1762     if (!AtStart)
1763       --BI;
1764
1765     for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
1766          E = toErase.end(); I != E; ++I) {
1767       DEBUG(errs() << "GVN removed: " << **I << '\n');
1768       MD->removeInstruction(*I);
1769       (*I)->eraseFromParent();
1770       DEBUG(verifyRemoved(*I));
1771     }
1772     toErase.clear();
1773
1774     if (AtStart)
1775       BI = BB->begin();
1776     else
1777       ++BI;
1778   }
1779
1780   return ChangedFunction;
1781 }
1782
1783 /// performPRE - Perform a purely local form of PRE that looks for diamond
1784 /// control flow patterns and attempts to perform simple PRE at the join point.
1785 bool GVN::performPRE(Function& F) {
1786   bool Changed = false;
1787   SmallVector<std::pair<TerminatorInst*, unsigned>, 4> toSplit;
1788   DenseMap<BasicBlock*, Value*> predMap;
1789   for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
1790        DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
1791     BasicBlock *CurrentBlock = *DI;
1792
1793     // Nothing to PRE in the entry block.
1794     if (CurrentBlock == &F.getEntryBlock()) continue;
1795
1796     for (BasicBlock::iterator BI = CurrentBlock->begin(),
1797          BE = CurrentBlock->end(); BI != BE; ) {
1798       Instruction *CurInst = BI++;
1799
1800       if (isa<AllocationInst>(CurInst) ||
1801           isa<TerminatorInst>(CurInst) || isa<PHINode>(CurInst) ||
1802           CurInst->getType()->isVoidTy() ||
1803           CurInst->mayReadFromMemory() || CurInst->mayHaveSideEffects() ||
1804           isa<DbgInfoIntrinsic>(CurInst))
1805         continue;
1806
1807       uint32_t ValNo = VN.lookup(CurInst);
1808
1809       // Look for the predecessors for PRE opportunities.  We're
1810       // only trying to solve the basic diamond case, where
1811       // a value is computed in the successor and one predecessor,
1812       // but not the other.  We also explicitly disallow cases
1813       // where the successor is its own predecessor, because they're
1814       // more complicated to get right.
1815       unsigned NumWith = 0;
1816       unsigned NumWithout = 0;
1817       BasicBlock *PREPred = 0;
1818       predMap.clear();
1819
1820       for (pred_iterator PI = pred_begin(CurrentBlock),
1821            PE = pred_end(CurrentBlock); PI != PE; ++PI) {
1822         // We're not interested in PRE where the block is its
1823         // own predecessor, on in blocks with predecessors
1824         // that are not reachable.
1825         if (*PI == CurrentBlock) {
1826           NumWithout = 2;
1827           break;
1828         } else if (!localAvail.count(*PI))  {
1829           NumWithout = 2;
1830           break;
1831         }
1832
1833         DenseMap<uint32_t, Value*>::iterator predV =
1834                                             localAvail[*PI]->table.find(ValNo);
1835         if (predV == localAvail[*PI]->table.end()) {
1836           PREPred = *PI;
1837           NumWithout++;
1838         } else if (predV->second == CurInst) {
1839           NumWithout = 2;
1840         } else {
1841           predMap[*PI] = predV->second;
1842           NumWith++;
1843         }
1844       }
1845
1846       // Don't do PRE when it might increase code size, i.e. when
1847       // we would need to insert instructions in more than one pred.
1848       if (NumWithout != 1 || NumWith == 0)
1849         continue;
1850
1851       // We can't do PRE safely on a critical edge, so instead we schedule
1852       // the edge to be split and perform the PRE the next time we iterate
1853       // on the function.
1854       unsigned SuccNum = 0;
1855       for (unsigned i = 0, e = PREPred->getTerminator()->getNumSuccessors();
1856            i != e; ++i)
1857         if (PREPred->getTerminator()->getSuccessor(i) == CurrentBlock) {
1858           SuccNum = i;
1859           break;
1860         }
1861
1862       if (isCriticalEdge(PREPred->getTerminator(), SuccNum)) {
1863         toSplit.push_back(std::make_pair(PREPred->getTerminator(), SuccNum));
1864         continue;
1865       }
1866
1867       // Instantiate the expression the in predecessor that lacked it.
1868       // Because we are going top-down through the block, all value numbers
1869       // will be available in the predecessor by the time we need them.  Any
1870       // that weren't original present will have been instantiated earlier
1871       // in this loop.
1872       Instruction *PREInstr = CurInst->clone();
1873       bool success = true;
1874       for (unsigned i = 0, e = CurInst->getNumOperands(); i != e; ++i) {
1875         Value *Op = PREInstr->getOperand(i);
1876         if (isa<Argument>(Op) || isa<Constant>(Op) || isa<GlobalValue>(Op))
1877           continue;
1878
1879         if (Value *V = lookupNumber(PREPred, VN.lookup(Op))) {
1880           PREInstr->setOperand(i, V);
1881         } else {
1882           success = false;
1883           break;
1884         }
1885       }
1886
1887       // Fail out if we encounter an operand that is not available in
1888       // the PRE predecessor.  This is typically because of loads which
1889       // are not value numbered precisely.
1890       if (!success) {
1891         delete PREInstr;
1892         DEBUG(verifyRemoved(PREInstr));
1893         continue;
1894       }
1895
1896       PREInstr->insertBefore(PREPred->getTerminator());
1897       PREInstr->setName(CurInst->getName() + ".pre");
1898       predMap[PREPred] = PREInstr;
1899       VN.add(PREInstr, ValNo);
1900       NumGVNPRE++;
1901
1902       // Update the availability map to include the new instruction.
1903       localAvail[PREPred]->table.insert(std::make_pair(ValNo, PREInstr));
1904
1905       // Create a PHI to make the value available in this block.
1906       PHINode* Phi = PHINode::Create(CurInst->getType(),
1907                                      CurInst->getName() + ".pre-phi",
1908                                      CurrentBlock->begin());
1909       for (pred_iterator PI = pred_begin(CurrentBlock),
1910            PE = pred_end(CurrentBlock); PI != PE; ++PI)
1911         Phi->addIncoming(predMap[*PI], *PI);
1912
1913       VN.add(Phi, ValNo);
1914       localAvail[CurrentBlock]->table[ValNo] = Phi;
1915
1916       CurInst->replaceAllUsesWith(Phi);
1917       if (isa<PointerType>(Phi->getType()))
1918         MD->invalidateCachedPointerInfo(Phi);
1919       VN.erase(CurInst);
1920
1921       DEBUG(errs() << "GVN PRE removed: " << *CurInst << '\n');
1922       MD->removeInstruction(CurInst);
1923       CurInst->eraseFromParent();
1924       DEBUG(verifyRemoved(CurInst));
1925       Changed = true;
1926     }
1927   }
1928
1929   for (SmallVector<std::pair<TerminatorInst*, unsigned>, 4>::iterator
1930        I = toSplit.begin(), E = toSplit.end(); I != E; ++I)
1931     SplitCriticalEdge(I->first, I->second, this);
1932
1933   return Changed || toSplit.size();
1934 }
1935
1936 /// iterateOnFunction - Executes one iteration of GVN
1937 bool GVN::iterateOnFunction(Function &F) {
1938   cleanupGlobalSets();
1939
1940   for (df_iterator<DomTreeNode*> DI = df_begin(DT->getRootNode()),
1941        DE = df_end(DT->getRootNode()); DI != DE; ++DI) {
1942     if (DI->getIDom())
1943       localAvail[DI->getBlock()] =
1944                    new ValueNumberScope(localAvail[DI->getIDom()->getBlock()]);
1945     else
1946       localAvail[DI->getBlock()] = new ValueNumberScope(0);
1947   }
1948
1949   // Top-down walk of the dominator tree
1950   bool Changed = false;
1951 #if 0
1952   // Needed for value numbering with phi construction to work.
1953   ReversePostOrderTraversal<Function*> RPOT(&F);
1954   for (ReversePostOrderTraversal<Function*>::rpo_iterator RI = RPOT.begin(),
1955        RE = RPOT.end(); RI != RE; ++RI)
1956     Changed |= processBlock(*RI);
1957 #else
1958   for (df_iterator<DomTreeNode*> DI = df_begin(DT->getRootNode()),
1959        DE = df_end(DT->getRootNode()); DI != DE; ++DI)
1960     Changed |= processBlock(DI->getBlock());
1961 #endif
1962
1963   return Changed;
1964 }
1965
1966 void GVN::cleanupGlobalSets() {
1967   VN.clear();
1968
1969   for (DenseMap<BasicBlock*, ValueNumberScope*>::iterator
1970        I = localAvail.begin(), E = localAvail.end(); I != E; ++I)
1971     delete I->second;
1972   localAvail.clear();
1973 }
1974
1975 /// verifyRemoved - Verify that the specified instruction does not occur in our
1976 /// internal data structures.
1977 void GVN::verifyRemoved(const Instruction *Inst) const {
1978   VN.verifyRemoved(Inst);
1979
1980   // Walk through the value number scope to make sure the instruction isn't
1981   // ferreted away in it.
1982   for (DenseMap<BasicBlock*, ValueNumberScope*>::iterator
1983          I = localAvail.begin(), E = localAvail.end(); I != E; ++I) {
1984     const ValueNumberScope *VNS = I->second;
1985
1986     while (VNS) {
1987       for (DenseMap<uint32_t, Value*>::iterator
1988              II = VNS->table.begin(), IE = VNS->table.end(); II != IE; ++II) {
1989         assert(II->second != Inst && "Inst still in value numbering scope!");
1990       }
1991
1992       VNS = VNS->parent;
1993     }
1994   }
1995 }