f40d34f248871e550c3dd145ce1bd577bb2eb5b6
[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/ADT/DenseMap.h"
21 #include "llvm/ADT/DepthFirstIterator.h"
22 #include "llvm/ADT/Hashing.h"
23 #include "llvm/ADT/SetVector.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Analysis/CFG.h"
28 #include "llvm/Analysis/ConstantFolding.h"
29 #include "llvm/Analysis/InstructionSimplify.h"
30 #include "llvm/Analysis/Loads.h"
31 #include "llvm/Analysis/MemoryBuiltins.h"
32 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
33 #include "llvm/Analysis/PHITransAddr.h"
34 #include "llvm/Analysis/ValueTracking.h"
35 #include "llvm/IR/DataLayout.h"
36 #include "llvm/IR/Dominators.h"
37 #include "llvm/IR/GlobalVariable.h"
38 #include "llvm/IR/IRBuilder.h"
39 #include "llvm/IR/IntrinsicInst.h"
40 #include "llvm/IR/LLVMContext.h"
41 #include "llvm/IR/Metadata.h"
42 #include "llvm/IR/PatternMatch.h"
43 #include "llvm/Support/Allocator.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Target/TargetLibraryInfo.h"
47 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
48 #include "llvm/Transforms/Utils/SSAUpdater.h"
49 #include <vector>
50 using namespace llvm;
51 using namespace PatternMatch;
52
53 STATISTIC(NumGVNInstr,  "Number of instructions deleted");
54 STATISTIC(NumGVNLoad,   "Number of loads deleted");
55 STATISTIC(NumGVNPRE,    "Number of instructions PRE'd");
56 STATISTIC(NumGVNBlocks, "Number of blocks merged");
57 STATISTIC(NumGVNSimpl,  "Number of instructions simplified");
58 STATISTIC(NumGVNEqProp, "Number of equalities propagated");
59 STATISTIC(NumPRELoad,   "Number of loads PRE'd");
60
61 static cl::opt<bool> EnablePRE("enable-pre",
62                                cl::init(true), cl::Hidden);
63 static cl::opt<bool> EnableLoadPRE("enable-load-pre", cl::init(true));
64
65 // Maximum allowed recursion depth.
66 static cl::opt<uint32_t>
67 MaxRecurseDepth("max-recurse-depth", cl::Hidden, cl::init(1000), cl::ZeroOrMore,
68                 cl::desc("Max recurse depth (default = 1000)"));
69
70 //===----------------------------------------------------------------------===//
71 //                         ValueTable Class
72 //===----------------------------------------------------------------------===//
73
74 /// This class holds the mapping between values and value numbers.  It is used
75 /// as an efficient mechanism to determine the expression-wise equivalence of
76 /// two values.
77 namespace {
78   struct Expression {
79     uint32_t opcode;
80     Type *type;
81     SmallVector<uint32_t, 4> varargs;
82
83     Expression(uint32_t o = ~2U) : opcode(o) { }
84
85     bool operator==(const Expression &other) const {
86       if (opcode != other.opcode)
87         return false;
88       if (opcode == ~0U || opcode == ~1U)
89         return true;
90       if (type != other.type)
91         return false;
92       if (varargs != other.varargs)
93         return false;
94       return true;
95     }
96
97     friend hash_code hash_value(const Expression &Value) {
98       return hash_combine(Value.opcode, Value.type,
99                           hash_combine_range(Value.varargs.begin(),
100                                              Value.varargs.end()));
101     }
102   };
103
104   class ValueTable {
105     DenseMap<Value*, uint32_t> valueNumbering;
106     DenseMap<Expression, uint32_t> expressionNumbering;
107     AliasAnalysis *AA;
108     MemoryDependenceAnalysis *MD;
109     DominatorTree *DT;
110
111     uint32_t nextValueNumber;
112
113     Expression create_expression(Instruction* I);
114     Expression create_intrinsic_expression(CallInst *C, uint32_t opcode,
115                                            bool IsCommutative);
116     Expression create_cmp_expression(unsigned Opcode,
117                                      CmpInst::Predicate Predicate,
118                                      Value *LHS, Value *RHS);
119     uint32_t lookup_or_add_call(CallInst* C);
120   public:
121     ValueTable() : nextValueNumber(1) { }
122     uint32_t lookup_or_add(Value *V);
123     uint32_t lookup(Value *V) const;
124     uint32_t lookup_or_add_cmp(unsigned Opcode, CmpInst::Predicate Pred,
125                                Value *LHS, Value *RHS);
126     void add(Value *V, uint32_t num);
127     void clear();
128     void erase(Value *v);
129     void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
130     AliasAnalysis *getAliasAnalysis() const { return AA; }
131     void setMemDep(MemoryDependenceAnalysis* M) { MD = M; }
132     void setDomTree(DominatorTree* D) { DT = D; }
133     uint32_t getNextUnusedValueNumber() { return nextValueNumber; }
134     void verifyRemoved(const Value *) const;
135   };
136 }
137
138 namespace llvm {
139 template <> struct DenseMapInfo<Expression> {
140   static inline Expression getEmptyKey() {
141     return ~0U;
142   }
143
144   static inline Expression getTombstoneKey() {
145     return ~1U;
146   }
147
148   static unsigned getHashValue(const Expression e) {
149     using llvm::hash_value;
150     return static_cast<unsigned>(hash_value(e));
151   }
152   static bool isEqual(const Expression &LHS, const Expression &RHS) {
153     return LHS == RHS;
154   }
155 };
156
157 }
158
159 //===----------------------------------------------------------------------===//
160 //                     ValueTable Internal Functions
161 //===----------------------------------------------------------------------===//
162
163 Expression ValueTable::create_expression(Instruction *I) {
164   Expression e;
165   e.type = I->getType();
166   e.opcode = I->getOpcode();
167   for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
168        OI != OE; ++OI)
169     e.varargs.push_back(lookup_or_add(*OI));
170   if (I->isCommutative()) {
171     // Ensure that commutative instructions that only differ by a permutation
172     // of their operands get the same value number by sorting the operand value
173     // numbers.  Since all commutative instructions have two operands it is more
174     // efficient to sort by hand rather than using, say, std::sort.
175     assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
176     if (e.varargs[0] > e.varargs[1])
177       std::swap(e.varargs[0], e.varargs[1]);
178   }
179
180   if (CmpInst *C = dyn_cast<CmpInst>(I)) {
181     // Sort the operand value numbers so x<y and y>x get the same value number.
182     CmpInst::Predicate Predicate = C->getPredicate();
183     if (e.varargs[0] > e.varargs[1]) {
184       std::swap(e.varargs[0], e.varargs[1]);
185       Predicate = CmpInst::getSwappedPredicate(Predicate);
186     }
187     e.opcode = (C->getOpcode() << 8) | Predicate;
188   } else if (InsertValueInst *E = dyn_cast<InsertValueInst>(I)) {
189     for (InsertValueInst::idx_iterator II = E->idx_begin(), IE = E->idx_end();
190          II != IE; ++II)
191       e.varargs.push_back(*II);
192   }
193
194   return e;
195 }
196
197 Expression ValueTable::create_intrinsic_expression(CallInst *C, uint32_t opcode,
198                                                    bool IsCommutative) {
199   Expression e;
200   e.opcode = opcode;
201   StructType *ST = cast<StructType>(C->getType());
202   assert(ST);
203   e.type = *ST->element_begin();
204
205   for (unsigned i = 0, ei = C->getNumArgOperands(); i < ei; ++i)
206     e.varargs.push_back(lookup_or_add(C->getArgOperand(i)));
207   if (IsCommutative) {
208     // Ensure that commutative instructions that only differ by a permutation
209     // of their operands get the same value number by sorting the operand value
210     // numbers.  Since all commutative instructions have two operands it is more
211     // efficient to sort by hand rather than using, say, std::sort.
212     assert(C->getNumArgOperands() == 2 && "Unsupported commutative instruction!");
213     if (e.varargs[0] > e.varargs[1])
214       std::swap(e.varargs[0], e.varargs[1]);
215   }
216
217   return e;
218 }
219
220 Expression ValueTable::create_cmp_expression(unsigned Opcode,
221                                              CmpInst::Predicate Predicate,
222                                              Value *LHS, Value *RHS) {
223   assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
224          "Not a comparison!");
225   Expression e;
226   e.type = CmpInst::makeCmpResultType(LHS->getType());
227   e.varargs.push_back(lookup_or_add(LHS));
228   e.varargs.push_back(lookup_or_add(RHS));
229
230   // Sort the operand value numbers so x<y and y>x get the same value number.
231   if (e.varargs[0] > e.varargs[1]) {
232     std::swap(e.varargs[0], e.varargs[1]);
233     Predicate = CmpInst::getSwappedPredicate(Predicate);
234   }
235   e.opcode = (Opcode << 8) | Predicate;
236   return e;
237 }
238
239 //===----------------------------------------------------------------------===//
240 //                     ValueTable External Functions
241 //===----------------------------------------------------------------------===//
242
243 /// add - Insert a value into the table with a specified value number.
244 void ValueTable::add(Value *V, uint32_t num) {
245   valueNumbering.insert(std::make_pair(V, num));
246 }
247
248 uint32_t ValueTable::lookup_or_add_call(CallInst *C) {
249   if (AA->doesNotAccessMemory(C)) {
250     Expression exp = create_expression(C);
251     uint32_t &e = expressionNumbering[exp];
252     if (!e) e = nextValueNumber++;
253     valueNumbering[C] = e;
254     return e;
255   } else if (AA->onlyReadsMemory(C)) {
256     Expression exp = create_expression(C);
257     uint32_t &e = expressionNumbering[exp];
258     if (!e) {
259       e = nextValueNumber++;
260       valueNumbering[C] = e;
261       return e;
262     }
263     if (!MD) {
264       e = nextValueNumber++;
265       valueNumbering[C] = e;
266       return e;
267     }
268
269     MemDepResult local_dep = MD->getDependency(C);
270
271     if (!local_dep.isDef() && !local_dep.isNonLocal()) {
272       valueNumbering[C] =  nextValueNumber;
273       return nextValueNumber++;
274     }
275
276     if (local_dep.isDef()) {
277       CallInst* local_cdep = cast<CallInst>(local_dep.getInst());
278
279       if (local_cdep->getNumArgOperands() != C->getNumArgOperands()) {
280         valueNumbering[C] = nextValueNumber;
281         return nextValueNumber++;
282       }
283
284       for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) {
285         uint32_t c_vn = lookup_or_add(C->getArgOperand(i));
286         uint32_t cd_vn = lookup_or_add(local_cdep->getArgOperand(i));
287         if (c_vn != cd_vn) {
288           valueNumbering[C] = nextValueNumber;
289           return nextValueNumber++;
290         }
291       }
292
293       uint32_t v = lookup_or_add(local_cdep);
294       valueNumbering[C] = v;
295       return v;
296     }
297
298     // Non-local case.
299     const MemoryDependenceAnalysis::NonLocalDepInfo &deps =
300       MD->getNonLocalCallDependency(CallSite(C));
301     // FIXME: Move the checking logic to MemDep!
302     CallInst* cdep = 0;
303
304     // Check to see if we have a single dominating call instruction that is
305     // identical to C.
306     for (unsigned i = 0, e = deps.size(); i != e; ++i) {
307       const NonLocalDepEntry *I = &deps[i];
308       if (I->getResult().isNonLocal())
309         continue;
310
311       // We don't handle non-definitions.  If we already have a call, reject
312       // instruction dependencies.
313       if (!I->getResult().isDef() || cdep != 0) {
314         cdep = 0;
315         break;
316       }
317
318       CallInst *NonLocalDepCall = dyn_cast<CallInst>(I->getResult().getInst());
319       // FIXME: All duplicated with non-local case.
320       if (NonLocalDepCall && DT->properlyDominates(I->getBB(), C->getParent())){
321         cdep = NonLocalDepCall;
322         continue;
323       }
324
325       cdep = 0;
326       break;
327     }
328
329     if (!cdep) {
330       valueNumbering[C] = nextValueNumber;
331       return nextValueNumber++;
332     }
333
334     if (cdep->getNumArgOperands() != C->getNumArgOperands()) {
335       valueNumbering[C] = nextValueNumber;
336       return nextValueNumber++;
337     }
338     for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) {
339       uint32_t c_vn = lookup_or_add(C->getArgOperand(i));
340       uint32_t cd_vn = lookup_or_add(cdep->getArgOperand(i));
341       if (c_vn != cd_vn) {
342         valueNumbering[C] = nextValueNumber;
343         return nextValueNumber++;
344       }
345     }
346
347     uint32_t v = lookup_or_add(cdep);
348     valueNumbering[C] = v;
349     return v;
350
351   } else {
352     valueNumbering[C] = nextValueNumber;
353     return nextValueNumber++;
354   }
355 }
356
357 /// lookup_or_add - Returns the value number for the specified value, assigning
358 /// it a new number if it did not have one before.
359 uint32_t ValueTable::lookup_or_add(Value *V) {
360   DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
361   if (VI != valueNumbering.end())
362     return VI->second;
363
364   if (!isa<Instruction>(V)) {
365     valueNumbering[V] = nextValueNumber;
366     return nextValueNumber++;
367   }
368
369   Instruction* I = cast<Instruction>(V);
370   Expression exp;
371   switch (I->getOpcode()) {
372     case Instruction::Call: {
373       CallInst *C = cast<CallInst>(I);
374       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(C)) {
375         switch (II->getIntrinsicID()) {
376           case Intrinsic::sadd_with_overflow:
377           case Intrinsic::uadd_with_overflow:
378             exp = create_intrinsic_expression(C, Instruction::Add, true);
379             break;
380           case Intrinsic::ssub_with_overflow:
381           case Intrinsic::usub_with_overflow:
382             exp = create_intrinsic_expression(C, Instruction::Sub, false);
383             break;
384           case Intrinsic::smul_with_overflow:
385           case Intrinsic::umul_with_overflow:
386             exp = create_intrinsic_expression(C, Instruction::Mul, true);
387             break;
388           default:
389             return lookup_or_add_call(C);
390         }
391       } else {
392         return lookup_or_add_call(C);
393       }
394     } break;
395     case Instruction::Add:
396     case Instruction::FAdd:
397     case Instruction::Sub:
398     case Instruction::FSub:
399     case Instruction::Mul:
400     case Instruction::FMul:
401     case Instruction::UDiv:
402     case Instruction::SDiv:
403     case Instruction::FDiv:
404     case Instruction::URem:
405     case Instruction::SRem:
406     case Instruction::FRem:
407     case Instruction::Shl:
408     case Instruction::LShr:
409     case Instruction::AShr:
410     case Instruction::And:
411     case Instruction::Or:
412     case Instruction::Xor:
413     case Instruction::ICmp:
414     case Instruction::FCmp:
415     case Instruction::Trunc:
416     case Instruction::ZExt:
417     case Instruction::SExt:
418     case Instruction::FPToUI:
419     case Instruction::FPToSI:
420     case Instruction::UIToFP:
421     case Instruction::SIToFP:
422     case Instruction::FPTrunc:
423     case Instruction::FPExt:
424     case Instruction::PtrToInt:
425     case Instruction::IntToPtr:
426     case Instruction::BitCast:
427     case Instruction::Select:
428     case Instruction::ExtractElement:
429     case Instruction::InsertElement:
430     case Instruction::ShuffleVector:
431     case Instruction::InsertValue:
432     case Instruction::GetElementPtr:
433     case Instruction::ExtractValue:
434       exp = create_expression(I);
435       break;
436     default:
437       valueNumbering[V] = nextValueNumber;
438       return nextValueNumber++;
439   }
440
441   uint32_t& e = expressionNumbering[exp];
442   if (!e) e = nextValueNumber++;
443   valueNumbering[V] = e;
444   return e;
445 }
446
447 /// lookup - Returns the value number of the specified value. Fails if
448 /// the value has not yet been numbered.
449 uint32_t ValueTable::lookup(Value *V) const {
450   DenseMap<Value*, uint32_t>::const_iterator VI = valueNumbering.find(V);
451   assert(VI != valueNumbering.end() && "Value not numbered?");
452   return VI->second;
453 }
454
455 /// lookup_or_add_cmp - Returns the value number of the given comparison,
456 /// assigning it a new number if it did not have one before.  Useful when
457 /// we deduced the result of a comparison, but don't immediately have an
458 /// instruction realizing that comparison to hand.
459 uint32_t ValueTable::lookup_or_add_cmp(unsigned Opcode,
460                                        CmpInst::Predicate Predicate,
461                                        Value *LHS, Value *RHS) {
462   Expression exp = create_cmp_expression(Opcode, Predicate, LHS, RHS);
463   uint32_t& e = expressionNumbering[exp];
464   if (!e) e = nextValueNumber++;
465   return e;
466 }
467
468 /// clear - Remove all entries from the ValueTable.
469 void ValueTable::clear() {
470   valueNumbering.clear();
471   expressionNumbering.clear();
472   nextValueNumber = 1;
473 }
474
475 /// erase - Remove a value from the value numbering.
476 void ValueTable::erase(Value *V) {
477   valueNumbering.erase(V);
478 }
479
480 /// verifyRemoved - Verify that the value is removed from all internal data
481 /// structures.
482 void ValueTable::verifyRemoved(const Value *V) const {
483   for (DenseMap<Value*, uint32_t>::const_iterator
484          I = valueNumbering.begin(), E = valueNumbering.end(); I != E; ++I) {
485     assert(I->first != V && "Inst still occurs in value numbering map!");
486   }
487 }
488
489 //===----------------------------------------------------------------------===//
490 //                                GVN Pass
491 //===----------------------------------------------------------------------===//
492
493 namespace {
494   class GVN;
495   struct AvailableValueInBlock {
496     /// BB - The basic block in question.
497     BasicBlock *BB;
498     enum ValType {
499       SimpleVal,  // A simple offsetted value that is accessed.
500       LoadVal,    // A value produced by a load.
501       MemIntrin,  // A memory intrinsic which is loaded from.
502       UndefVal    // A UndefValue representing a value from dead block (which
503                   // is not yet physically removed from the CFG). 
504     };
505   
506     /// V - The value that is live out of the block.
507     PointerIntPair<Value *, 2, ValType> Val;
508   
509     /// Offset - The byte offset in Val that is interesting for the load query.
510     unsigned Offset;
511   
512     static AvailableValueInBlock get(BasicBlock *BB, Value *V,
513                                      unsigned Offset = 0) {
514       AvailableValueInBlock Res;
515       Res.BB = BB;
516       Res.Val.setPointer(V);
517       Res.Val.setInt(SimpleVal);
518       Res.Offset = Offset;
519       return Res;
520     }
521   
522     static AvailableValueInBlock getMI(BasicBlock *BB, MemIntrinsic *MI,
523                                        unsigned Offset = 0) {
524       AvailableValueInBlock Res;
525       Res.BB = BB;
526       Res.Val.setPointer(MI);
527       Res.Val.setInt(MemIntrin);
528       Res.Offset = Offset;
529       return Res;
530     }
531   
532     static AvailableValueInBlock getLoad(BasicBlock *BB, LoadInst *LI,
533                                          unsigned Offset = 0) {
534       AvailableValueInBlock Res;
535       Res.BB = BB;
536       Res.Val.setPointer(LI);
537       Res.Val.setInt(LoadVal);
538       Res.Offset = Offset;
539       return Res;
540     }
541
542     static AvailableValueInBlock getUndef(BasicBlock *BB) {
543       AvailableValueInBlock Res;
544       Res.BB = BB;
545       Res.Val.setPointer(0);
546       Res.Val.setInt(UndefVal);
547       Res.Offset = 0;
548       return Res;
549     }
550
551     bool isSimpleValue() const { return Val.getInt() == SimpleVal; }
552     bool isCoercedLoadValue() const { return Val.getInt() == LoadVal; }
553     bool isMemIntrinValue() const { return Val.getInt() == MemIntrin; }
554     bool isUndefValue() const { return Val.getInt() == UndefVal; }
555   
556     Value *getSimpleValue() const {
557       assert(isSimpleValue() && "Wrong accessor");
558       return Val.getPointer();
559     }
560   
561     LoadInst *getCoercedLoadValue() const {
562       assert(isCoercedLoadValue() && "Wrong accessor");
563       return cast<LoadInst>(Val.getPointer());
564     }
565   
566     MemIntrinsic *getMemIntrinValue() const {
567       assert(isMemIntrinValue() && "Wrong accessor");
568       return cast<MemIntrinsic>(Val.getPointer());
569     }
570   
571     /// MaterializeAdjustedValue - Emit code into this block to adjust the value
572     /// defined here to the specified type.  This handles various coercion cases.
573     Value *MaterializeAdjustedValue(Type *LoadTy, GVN &gvn) const;
574   };
575
576   class GVN : public FunctionPass {
577     bool NoLoads;
578     MemoryDependenceAnalysis *MD;
579     DominatorTree *DT;
580     const DataLayout *DL;
581     const TargetLibraryInfo *TLI;
582     SetVector<BasicBlock *> DeadBlocks;
583
584     ValueTable VN;
585
586     /// LeaderTable - A mapping from value numbers to lists of Value*'s that
587     /// have that value number.  Use findLeader to query it.
588     struct LeaderTableEntry {
589       Value *Val;
590       const BasicBlock *BB;
591       LeaderTableEntry *Next;
592     };
593     DenseMap<uint32_t, LeaderTableEntry> LeaderTable;
594     BumpPtrAllocator TableAllocator;
595
596     SmallVector<Instruction*, 8> InstrsToErase;
597
598     typedef SmallVector<NonLocalDepResult, 64> LoadDepVect;
599     typedef SmallVector<AvailableValueInBlock, 64> AvailValInBlkVect;
600     typedef SmallVector<BasicBlock*, 64> UnavailBlkVect;
601
602   public:
603     static char ID; // Pass identification, replacement for typeid
604     explicit GVN(bool noloads = false)
605         : FunctionPass(ID), NoLoads(noloads), MD(0) {
606       initializeGVNPass(*PassRegistry::getPassRegistry());
607     }
608
609     bool runOnFunction(Function &F) override;
610
611     /// markInstructionForDeletion - This removes the specified instruction from
612     /// our various maps and marks it for deletion.
613     void markInstructionForDeletion(Instruction *I) {
614       VN.erase(I);
615       InstrsToErase.push_back(I);
616     }
617
618     const DataLayout *getDataLayout() const { return DL; }
619     DominatorTree &getDominatorTree() const { return *DT; }
620     AliasAnalysis *getAliasAnalysis() const { return VN.getAliasAnalysis(); }
621     MemoryDependenceAnalysis &getMemDep() const { return *MD; }
622   private:
623     /// addToLeaderTable - Push a new Value to the LeaderTable onto the list for
624     /// its value number.
625     void addToLeaderTable(uint32_t N, Value *V, const BasicBlock *BB) {
626       LeaderTableEntry &Curr = LeaderTable[N];
627       if (!Curr.Val) {
628         Curr.Val = V;
629         Curr.BB = BB;
630         return;
631       }
632
633       LeaderTableEntry *Node = TableAllocator.Allocate<LeaderTableEntry>();
634       Node->Val = V;
635       Node->BB = BB;
636       Node->Next = Curr.Next;
637       Curr.Next = Node;
638     }
639
640     /// removeFromLeaderTable - Scan the list of values corresponding to a given
641     /// value number, and remove the given instruction if encountered.
642     void removeFromLeaderTable(uint32_t N, Instruction *I, BasicBlock *BB) {
643       LeaderTableEntry* Prev = 0;
644       LeaderTableEntry* Curr = &LeaderTable[N];
645
646       while (Curr->Val != I || Curr->BB != BB) {
647         Prev = Curr;
648         Curr = Curr->Next;
649       }
650
651       if (Prev) {
652         Prev->Next = Curr->Next;
653       } else {
654         if (!Curr->Next) {
655           Curr->Val = 0;
656           Curr->BB = 0;
657         } else {
658           LeaderTableEntry* Next = Curr->Next;
659           Curr->Val = Next->Val;
660           Curr->BB = Next->BB;
661           Curr->Next = Next->Next;
662         }
663       }
664     }
665
666     // List of critical edges to be split between iterations.
667     SmallVector<std::pair<TerminatorInst*, unsigned>, 4> toSplit;
668
669     // This transformation requires dominator postdominator info
670     void getAnalysisUsage(AnalysisUsage &AU) const override {
671       AU.addRequired<DominatorTreeWrapperPass>();
672       AU.addRequired<TargetLibraryInfo>();
673       if (!NoLoads)
674         AU.addRequired<MemoryDependenceAnalysis>();
675       AU.addRequired<AliasAnalysis>();
676
677       AU.addPreserved<DominatorTreeWrapperPass>();
678       AU.addPreserved<AliasAnalysis>();
679     }
680
681
682     // Helper fuctions of redundant load elimination 
683     bool processLoad(LoadInst *L);
684     bool processNonLocalLoad(LoadInst *L);
685     void AnalyzeLoadAvailability(LoadInst *LI, LoadDepVect &Deps, 
686                                  AvailValInBlkVect &ValuesPerBlock,
687                                  UnavailBlkVect &UnavailableBlocks);
688     bool PerformLoadPRE(LoadInst *LI, AvailValInBlkVect &ValuesPerBlock, 
689                         UnavailBlkVect &UnavailableBlocks);
690
691     // Other helper routines
692     bool processInstruction(Instruction *I);
693     bool processBlock(BasicBlock *BB);
694     void dump(DenseMap<uint32_t, Value*> &d);
695     bool iterateOnFunction(Function &F);
696     bool performPRE(Function &F);
697     Value *findLeader(const BasicBlock *BB, uint32_t num);
698     void cleanupGlobalSets();
699     void verifyRemoved(const Instruction *I) const;
700     bool splitCriticalEdges();
701     BasicBlock *splitCriticalEdges(BasicBlock *Pred, BasicBlock *Succ);
702     unsigned replaceAllDominatedUsesWith(Value *From, Value *To,
703                                          const BasicBlockEdge &Root);
704     bool propagateEquality(Value *LHS, Value *RHS, const BasicBlockEdge &Root);
705     bool processFoldableCondBr(BranchInst *BI);
706     void addDeadBlock(BasicBlock *BB);
707     void assignValNumForDeadCode();
708   };
709
710   char GVN::ID = 0;
711 }
712
713 // createGVNPass - The public interface to this file...
714 FunctionPass *llvm::createGVNPass(bool NoLoads) {
715   return new GVN(NoLoads);
716 }
717
718 INITIALIZE_PASS_BEGIN(GVN, "gvn", "Global Value Numbering", false, false)
719 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
720 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
721 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
722 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
723 INITIALIZE_PASS_END(GVN, "gvn", "Global Value Numbering", false, false)
724
725 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
726 void GVN::dump(DenseMap<uint32_t, Value*>& d) {
727   errs() << "{\n";
728   for (DenseMap<uint32_t, Value*>::iterator I = d.begin(),
729        E = d.end(); I != E; ++I) {
730       errs() << I->first << "\n";
731       I->second->dump();
732   }
733   errs() << "}\n";
734 }
735 #endif
736
737 /// IsValueFullyAvailableInBlock - Return true if we can prove that the value
738 /// we're analyzing is fully available in the specified block.  As we go, keep
739 /// track of which blocks we know are fully alive in FullyAvailableBlocks.  This
740 /// map is actually a tri-state map with the following values:
741 ///   0) we know the block *is not* fully available.
742 ///   1) we know the block *is* fully available.
743 ///   2) we do not know whether the block is fully available or not, but we are
744 ///      currently speculating that it will be.
745 ///   3) we are speculating for this block and have used that to speculate for
746 ///      other blocks.
747 static bool IsValueFullyAvailableInBlock(BasicBlock *BB,
748                             DenseMap<BasicBlock*, char> &FullyAvailableBlocks,
749                             uint32_t RecurseDepth) {
750   if (RecurseDepth > MaxRecurseDepth)
751     return false;
752
753   // Optimistically assume that the block is fully available and check to see
754   // if we already know about this block in one lookup.
755   std::pair<DenseMap<BasicBlock*, char>::iterator, char> IV =
756     FullyAvailableBlocks.insert(std::make_pair(BB, 2));
757
758   // If the entry already existed for this block, return the precomputed value.
759   if (!IV.second) {
760     // If this is a speculative "available" value, mark it as being used for
761     // speculation of other blocks.
762     if (IV.first->second == 2)
763       IV.first->second = 3;
764     return IV.first->second != 0;
765   }
766
767   // Otherwise, see if it is fully available in all predecessors.
768   pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
769
770   // If this block has no predecessors, it isn't live-in here.
771   if (PI == PE)
772     goto SpeculationFailure;
773
774   for (; PI != PE; ++PI)
775     // If the value isn't fully available in one of our predecessors, then it
776     // isn't fully available in this block either.  Undo our previous
777     // optimistic assumption and bail out.
778     if (!IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks,RecurseDepth+1))
779       goto SpeculationFailure;
780
781   return true;
782
783 // SpeculationFailure - If we get here, we found out that this is not, after
784 // all, a fully-available block.  We have a problem if we speculated on this and
785 // used the speculation to mark other blocks as available.
786 SpeculationFailure:
787   char &BBVal = FullyAvailableBlocks[BB];
788
789   // If we didn't speculate on this, just return with it set to false.
790   if (BBVal == 2) {
791     BBVal = 0;
792     return false;
793   }
794
795   // If we did speculate on this value, we could have blocks set to 1 that are
796   // incorrect.  Walk the (transitive) successors of this block and mark them as
797   // 0 if set to one.
798   SmallVector<BasicBlock*, 32> BBWorklist;
799   BBWorklist.push_back(BB);
800
801   do {
802     BasicBlock *Entry = BBWorklist.pop_back_val();
803     // Note that this sets blocks to 0 (unavailable) if they happen to not
804     // already be in FullyAvailableBlocks.  This is safe.
805     char &EntryVal = FullyAvailableBlocks[Entry];
806     if (EntryVal == 0) continue;  // Already unavailable.
807
808     // Mark as unavailable.
809     EntryVal = 0;
810
811     BBWorklist.append(succ_begin(Entry), succ_end(Entry));
812   } while (!BBWorklist.empty());
813
814   return false;
815 }
816
817
818 /// CanCoerceMustAliasedValueToLoad - Return true if
819 /// CoerceAvailableValueToLoadType will succeed.
820 static bool CanCoerceMustAliasedValueToLoad(Value *StoredVal,
821                                             Type *LoadTy,
822                                             const DataLayout &DL) {
823   // If the loaded or stored value is an first class array or struct, don't try
824   // to transform them.  We need to be able to bitcast to integer.
825   if (LoadTy->isStructTy() || LoadTy->isArrayTy() ||
826       StoredVal->getType()->isStructTy() ||
827       StoredVal->getType()->isArrayTy())
828     return false;
829
830   // The store has to be at least as big as the load.
831   if (DL.getTypeSizeInBits(StoredVal->getType()) <
832         DL.getTypeSizeInBits(LoadTy))
833     return false;
834
835   return true;
836 }
837
838 /// CoerceAvailableValueToLoadType - If we saw a store of a value to memory, and
839 /// then a load from a must-aliased pointer of a different type, try to coerce
840 /// the stored value.  LoadedTy is the type of the load we want to replace and
841 /// InsertPt is the place to insert new instructions.
842 ///
843 /// If we can't do it, return null.
844 static Value *CoerceAvailableValueToLoadType(Value *StoredVal,
845                                              Type *LoadedTy,
846                                              Instruction *InsertPt,
847                                              const DataLayout &DL) {
848   if (!CanCoerceMustAliasedValueToLoad(StoredVal, LoadedTy, DL))
849     return 0;
850
851   // If this is already the right type, just return it.
852   Type *StoredValTy = StoredVal->getType();
853
854   uint64_t StoreSize = DL.getTypeSizeInBits(StoredValTy);
855   uint64_t LoadSize = DL.getTypeSizeInBits(LoadedTy);
856
857   // If the store and reload are the same size, we can always reuse it.
858   if (StoreSize == LoadSize) {
859     // Pointer to Pointer -> use bitcast.
860     if (StoredValTy->getScalarType()->isPointerTy() &&
861         LoadedTy->getScalarType()->isPointerTy())
862       return new BitCastInst(StoredVal, LoadedTy, "", InsertPt);
863
864     // Convert source pointers to integers, which can be bitcast.
865     if (StoredValTy->getScalarType()->isPointerTy()) {
866       StoredValTy = DL.getIntPtrType(StoredValTy);
867       StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
868     }
869
870     Type *TypeToCastTo = LoadedTy;
871     if (TypeToCastTo->getScalarType()->isPointerTy())
872       TypeToCastTo = DL.getIntPtrType(TypeToCastTo);
873
874     if (StoredValTy != TypeToCastTo)
875       StoredVal = new BitCastInst(StoredVal, TypeToCastTo, "", InsertPt);
876
877     // Cast to pointer if the load needs a pointer type.
878     if (LoadedTy->getScalarType()->isPointerTy())
879       StoredVal = new IntToPtrInst(StoredVal, LoadedTy, "", InsertPt);
880
881     return StoredVal;
882   }
883
884   // If the loaded value is smaller than the available value, then we can
885   // extract out a piece from it.  If the available value is too small, then we
886   // can't do anything.
887   assert(StoreSize >= LoadSize && "CanCoerceMustAliasedValueToLoad fail");
888
889   // Convert source pointers to integers, which can be manipulated.
890   if (StoredValTy->getScalarType()->isPointerTy()) {
891     StoredValTy = DL.getIntPtrType(StoredValTy);
892     StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
893   }
894
895   // Convert vectors and fp to integer, which can be manipulated.
896   if (!StoredValTy->isIntegerTy()) {
897     StoredValTy = IntegerType::get(StoredValTy->getContext(), StoreSize);
898     StoredVal = new BitCastInst(StoredVal, StoredValTy, "", InsertPt);
899   }
900
901   // If this is a big-endian system, we need to shift the value down to the low
902   // bits so that a truncate will work.
903   if (DL.isBigEndian()) {
904     Constant *Val = ConstantInt::get(StoredVal->getType(), StoreSize-LoadSize);
905     StoredVal = BinaryOperator::CreateLShr(StoredVal, Val, "tmp", InsertPt);
906   }
907
908   // Truncate the integer to the right size now.
909   Type *NewIntTy = IntegerType::get(StoredValTy->getContext(), LoadSize);
910   StoredVal = new TruncInst(StoredVal, NewIntTy, "trunc", InsertPt);
911
912   if (LoadedTy == NewIntTy)
913     return StoredVal;
914
915   // If the result is a pointer, inttoptr.
916   if (LoadedTy->getScalarType()->isPointerTy())
917     return new IntToPtrInst(StoredVal, LoadedTy, "inttoptr", InsertPt);
918
919   // Otherwise, bitcast.
920   return new BitCastInst(StoredVal, LoadedTy, "bitcast", InsertPt);
921 }
922
923 /// AnalyzeLoadFromClobberingWrite - This function is called when we have a
924 /// memdep query of a load that ends up being a clobbering memory write (store,
925 /// memset, memcpy, memmove).  This means that the write *may* provide bits used
926 /// by the load but we can't be sure because the pointers don't mustalias.
927 ///
928 /// Check this case to see if there is anything more we can do before we give
929 /// up.  This returns -1 if we have to give up, or a byte number in the stored
930 /// value of the piece that feeds the load.
931 static int AnalyzeLoadFromClobberingWrite(Type *LoadTy, Value *LoadPtr,
932                                           Value *WritePtr,
933                                           uint64_t WriteSizeInBits,
934                                           const DataLayout &DL) {
935   // If the loaded or stored value is a first class array or struct, don't try
936   // to transform them.  We need to be able to bitcast to integer.
937   if (LoadTy->isStructTy() || LoadTy->isArrayTy())
938     return -1;
939
940   int64_t StoreOffset = 0, LoadOffset = 0;
941   Value *StoreBase = GetPointerBaseWithConstantOffset(WritePtr,StoreOffset,&DL);
942   Value *LoadBase = GetPointerBaseWithConstantOffset(LoadPtr, LoadOffset, &DL);
943   if (StoreBase != LoadBase)
944     return -1;
945
946   // If the load and store are to the exact same address, they should have been
947   // a must alias.  AA must have gotten confused.
948   // FIXME: Study to see if/when this happens.  One case is forwarding a memset
949   // to a load from the base of the memset.
950 #if 0
951   if (LoadOffset == StoreOffset) {
952     dbgs() << "STORE/LOAD DEP WITH COMMON POINTER MISSED:\n"
953     << "Base       = " << *StoreBase << "\n"
954     << "Store Ptr  = " << *WritePtr << "\n"
955     << "Store Offs = " << StoreOffset << "\n"
956     << "Load Ptr   = " << *LoadPtr << "\n";
957     abort();
958   }
959 #endif
960
961   // If the load and store don't overlap at all, the store doesn't provide
962   // anything to the load.  In this case, they really don't alias at all, AA
963   // must have gotten confused.
964   uint64_t LoadSize = DL.getTypeSizeInBits(LoadTy);
965
966   if ((WriteSizeInBits & 7) | (LoadSize & 7))
967     return -1;
968   uint64_t StoreSize = WriteSizeInBits >> 3;  // Convert to bytes.
969   LoadSize >>= 3;
970
971
972   bool isAAFailure = false;
973   if (StoreOffset < LoadOffset)
974     isAAFailure = StoreOffset+int64_t(StoreSize) <= LoadOffset;
975   else
976     isAAFailure = LoadOffset+int64_t(LoadSize) <= StoreOffset;
977
978   if (isAAFailure) {
979 #if 0
980     dbgs() << "STORE LOAD DEP WITH COMMON BASE:\n"
981     << "Base       = " << *StoreBase << "\n"
982     << "Store Ptr  = " << *WritePtr << "\n"
983     << "Store Offs = " << StoreOffset << "\n"
984     << "Load Ptr   = " << *LoadPtr << "\n";
985     abort();
986 #endif
987     return -1;
988   }
989
990   // If the Load isn't completely contained within the stored bits, we don't
991   // have all the bits to feed it.  We could do something crazy in the future
992   // (issue a smaller load then merge the bits in) but this seems unlikely to be
993   // valuable.
994   if (StoreOffset > LoadOffset ||
995       StoreOffset+StoreSize < LoadOffset+LoadSize)
996     return -1;
997
998   // Okay, we can do this transformation.  Return the number of bytes into the
999   // store that the load is.
1000   return LoadOffset-StoreOffset;
1001 }
1002
1003 /// AnalyzeLoadFromClobberingStore - This function is called when we have a
1004 /// memdep query of a load that ends up being a clobbering store.
1005 static int AnalyzeLoadFromClobberingStore(Type *LoadTy, Value *LoadPtr,
1006                                           StoreInst *DepSI,
1007                                           const DataLayout &DL) {
1008   // Cannot handle reading from store of first-class aggregate yet.
1009   if (DepSI->getValueOperand()->getType()->isStructTy() ||
1010       DepSI->getValueOperand()->getType()->isArrayTy())
1011     return -1;
1012
1013   Value *StorePtr = DepSI->getPointerOperand();
1014   uint64_t StoreSize =DL.getTypeSizeInBits(DepSI->getValueOperand()->getType());
1015   return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr,
1016                                         StorePtr, StoreSize, DL);
1017 }
1018
1019 /// AnalyzeLoadFromClobberingLoad - This function is called when we have a
1020 /// memdep query of a load that ends up being clobbered by another load.  See if
1021 /// the other load can feed into the second load.
1022 static int AnalyzeLoadFromClobberingLoad(Type *LoadTy, Value *LoadPtr,
1023                                          LoadInst *DepLI, const DataLayout &DL){
1024   // Cannot handle reading from store of first-class aggregate yet.
1025   if (DepLI->getType()->isStructTy() || DepLI->getType()->isArrayTy())
1026     return -1;
1027
1028   Value *DepPtr = DepLI->getPointerOperand();
1029   uint64_t DepSize = DL.getTypeSizeInBits(DepLI->getType());
1030   int R = AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, DepSize, DL);
1031   if (R != -1) return R;
1032
1033   // If we have a load/load clobber an DepLI can be widened to cover this load,
1034   // then we should widen it!
1035   int64_t LoadOffs = 0;
1036   const Value *LoadBase =
1037     GetPointerBaseWithConstantOffset(LoadPtr, LoadOffs, &DL);
1038   unsigned LoadSize = DL.getTypeStoreSize(LoadTy);
1039
1040   unsigned Size = MemoryDependenceAnalysis::
1041     getLoadLoadClobberFullWidthSize(LoadBase, LoadOffs, LoadSize, DepLI, DL);
1042   if (Size == 0) return -1;
1043
1044   return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, Size*8, DL);
1045 }
1046
1047
1048
1049 static int AnalyzeLoadFromClobberingMemInst(Type *LoadTy, Value *LoadPtr,
1050                                             MemIntrinsic *MI,
1051                                             const DataLayout &DL) {
1052   // If the mem operation is a non-constant size, we can't handle it.
1053   ConstantInt *SizeCst = dyn_cast<ConstantInt>(MI->getLength());
1054   if (SizeCst == 0) return -1;
1055   uint64_t MemSizeInBits = SizeCst->getZExtValue()*8;
1056
1057   // If this is memset, we just need to see if the offset is valid in the size
1058   // of the memset..
1059   if (MI->getIntrinsicID() == Intrinsic::memset)
1060     return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, MI->getDest(),
1061                                           MemSizeInBits, DL);
1062
1063   // If we have a memcpy/memmove, the only case we can handle is if this is a
1064   // copy from constant memory.  In that case, we can read directly from the
1065   // constant memory.
1066   MemTransferInst *MTI = cast<MemTransferInst>(MI);
1067
1068   Constant *Src = dyn_cast<Constant>(MTI->getSource());
1069   if (Src == 0) return -1;
1070
1071   GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Src, &DL));
1072   if (GV == 0 || !GV->isConstant()) return -1;
1073
1074   // See if the access is within the bounds of the transfer.
1075   int Offset = AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr,
1076                                               MI->getDest(), MemSizeInBits, DL);
1077   if (Offset == -1)
1078     return Offset;
1079
1080   unsigned AS = Src->getType()->getPointerAddressSpace();
1081   // Otherwise, see if we can constant fold a load from the constant with the
1082   // offset applied as appropriate.
1083   Src = ConstantExpr::getBitCast(Src,
1084                                  Type::getInt8PtrTy(Src->getContext(), AS));
1085   Constant *OffsetCst =
1086     ConstantInt::get(Type::getInt64Ty(Src->getContext()), (unsigned)Offset);
1087   Src = ConstantExpr::getGetElementPtr(Src, OffsetCst);
1088   Src = ConstantExpr::getBitCast(Src, PointerType::get(LoadTy, AS));
1089   if (ConstantFoldLoadFromConstPtr(Src, &DL))
1090     return Offset;
1091   return -1;
1092 }
1093
1094
1095 /// GetStoreValueForLoad - This function is called when we have a
1096 /// memdep query of a load that ends up being a clobbering store.  This means
1097 /// that the store provides bits used by the load but we the pointers don't
1098 /// mustalias.  Check this case to see if there is anything more we can do
1099 /// before we give up.
1100 static Value *GetStoreValueForLoad(Value *SrcVal, unsigned Offset,
1101                                    Type *LoadTy,
1102                                    Instruction *InsertPt, const DataLayout &DL){
1103   LLVMContext &Ctx = SrcVal->getType()->getContext();
1104
1105   uint64_t StoreSize = (DL.getTypeSizeInBits(SrcVal->getType()) + 7) / 8;
1106   uint64_t LoadSize = (DL.getTypeSizeInBits(LoadTy) + 7) / 8;
1107
1108   IRBuilder<> Builder(InsertPt->getParent(), InsertPt);
1109
1110   // Compute which bits of the stored value are being used by the load.  Convert
1111   // to an integer type to start with.
1112   if (SrcVal->getType()->getScalarType()->isPointerTy())
1113     SrcVal = Builder.CreatePtrToInt(SrcVal,
1114         DL.getIntPtrType(SrcVal->getType()));
1115   if (!SrcVal->getType()->isIntegerTy())
1116     SrcVal = Builder.CreateBitCast(SrcVal, IntegerType::get(Ctx, StoreSize*8));
1117
1118   // Shift the bits to the least significant depending on endianness.
1119   unsigned ShiftAmt;
1120   if (DL.isLittleEndian())
1121     ShiftAmt = Offset*8;
1122   else
1123     ShiftAmt = (StoreSize-LoadSize-Offset)*8;
1124
1125   if (ShiftAmt)
1126     SrcVal = Builder.CreateLShr(SrcVal, ShiftAmt);
1127
1128   if (LoadSize != StoreSize)
1129     SrcVal = Builder.CreateTrunc(SrcVal, IntegerType::get(Ctx, LoadSize*8));
1130
1131   return CoerceAvailableValueToLoadType(SrcVal, LoadTy, InsertPt, DL);
1132 }
1133
1134 /// GetLoadValueForLoad - This function is called when we have a
1135 /// memdep query of a load that ends up being a clobbering load.  This means
1136 /// that the load *may* provide bits used by the load but we can't be sure
1137 /// because the pointers don't mustalias.  Check this case to see if there is
1138 /// anything more we can do before we give up.
1139 static Value *GetLoadValueForLoad(LoadInst *SrcVal, unsigned Offset,
1140                                   Type *LoadTy, Instruction *InsertPt,
1141                                   GVN &gvn) {
1142   const DataLayout &DL = *gvn.getDataLayout();
1143   // If Offset+LoadTy exceeds the size of SrcVal, then we must be wanting to
1144   // widen SrcVal out to a larger load.
1145   unsigned SrcValSize = DL.getTypeStoreSize(SrcVal->getType());
1146   unsigned LoadSize = DL.getTypeStoreSize(LoadTy);
1147   if (Offset+LoadSize > SrcValSize) {
1148     assert(SrcVal->isSimple() && "Cannot widen volatile/atomic load!");
1149     assert(SrcVal->getType()->isIntegerTy() && "Can't widen non-integer load");
1150     // If we have a load/load clobber an DepLI can be widened to cover this
1151     // load, then we should widen it to the next power of 2 size big enough!
1152     unsigned NewLoadSize = Offset+LoadSize;
1153     if (!isPowerOf2_32(NewLoadSize))
1154       NewLoadSize = NextPowerOf2(NewLoadSize);
1155
1156     Value *PtrVal = SrcVal->getPointerOperand();
1157
1158     // Insert the new load after the old load.  This ensures that subsequent
1159     // memdep queries will find the new load.  We can't easily remove the old
1160     // load completely because it is already in the value numbering table.
1161     IRBuilder<> Builder(SrcVal->getParent(), ++BasicBlock::iterator(SrcVal));
1162     Type *DestPTy =
1163       IntegerType::get(LoadTy->getContext(), NewLoadSize*8);
1164     DestPTy = PointerType::get(DestPTy,
1165                                PtrVal->getType()->getPointerAddressSpace());
1166     Builder.SetCurrentDebugLocation(SrcVal->getDebugLoc());
1167     PtrVal = Builder.CreateBitCast(PtrVal, DestPTy);
1168     LoadInst *NewLoad = Builder.CreateLoad(PtrVal);
1169     NewLoad->takeName(SrcVal);
1170     NewLoad->setAlignment(SrcVal->getAlignment());
1171
1172     DEBUG(dbgs() << "GVN WIDENED LOAD: " << *SrcVal << "\n");
1173     DEBUG(dbgs() << "TO: " << *NewLoad << "\n");
1174
1175     // Replace uses of the original load with the wider load.  On a big endian
1176     // system, we need to shift down to get the relevant bits.
1177     Value *RV = NewLoad;
1178     if (DL.isBigEndian())
1179       RV = Builder.CreateLShr(RV,
1180                     NewLoadSize*8-SrcVal->getType()->getPrimitiveSizeInBits());
1181     RV = Builder.CreateTrunc(RV, SrcVal->getType());
1182     SrcVal->replaceAllUsesWith(RV);
1183
1184     // We would like to use gvn.markInstructionForDeletion here, but we can't
1185     // because the load is already memoized into the leader map table that GVN
1186     // tracks.  It is potentially possible to remove the load from the table,
1187     // but then there all of the operations based on it would need to be
1188     // rehashed.  Just leave the dead load around.
1189     gvn.getMemDep().removeInstruction(SrcVal);
1190     SrcVal = NewLoad;
1191   }
1192
1193   return GetStoreValueForLoad(SrcVal, Offset, LoadTy, InsertPt, DL);
1194 }
1195
1196
1197 /// GetMemInstValueForLoad - This function is called when we have a
1198 /// memdep query of a load that ends up being a clobbering mem intrinsic.
1199 static Value *GetMemInstValueForLoad(MemIntrinsic *SrcInst, unsigned Offset,
1200                                      Type *LoadTy, Instruction *InsertPt,
1201                                      const DataLayout &DL){
1202   LLVMContext &Ctx = LoadTy->getContext();
1203   uint64_t LoadSize = DL.getTypeSizeInBits(LoadTy)/8;
1204
1205   IRBuilder<> Builder(InsertPt->getParent(), InsertPt);
1206
1207   // We know that this method is only called when the mem transfer fully
1208   // provides the bits for the load.
1209   if (MemSetInst *MSI = dyn_cast<MemSetInst>(SrcInst)) {
1210     // memset(P, 'x', 1234) -> splat('x'), even if x is a variable, and
1211     // independently of what the offset is.
1212     Value *Val = MSI->getValue();
1213     if (LoadSize != 1)
1214       Val = Builder.CreateZExt(Val, IntegerType::get(Ctx, LoadSize*8));
1215
1216     Value *OneElt = Val;
1217
1218     // Splat the value out to the right number of bits.
1219     for (unsigned NumBytesSet = 1; NumBytesSet != LoadSize; ) {
1220       // If we can double the number of bytes set, do it.
1221       if (NumBytesSet*2 <= LoadSize) {
1222         Value *ShVal = Builder.CreateShl(Val, NumBytesSet*8);
1223         Val = Builder.CreateOr(Val, ShVal);
1224         NumBytesSet <<= 1;
1225         continue;
1226       }
1227
1228       // Otherwise insert one byte at a time.
1229       Value *ShVal = Builder.CreateShl(Val, 1*8);
1230       Val = Builder.CreateOr(OneElt, ShVal);
1231       ++NumBytesSet;
1232     }
1233
1234     return CoerceAvailableValueToLoadType(Val, LoadTy, InsertPt, DL);
1235   }
1236
1237   // Otherwise, this is a memcpy/memmove from a constant global.
1238   MemTransferInst *MTI = cast<MemTransferInst>(SrcInst);
1239   Constant *Src = cast<Constant>(MTI->getSource());
1240   unsigned AS = Src->getType()->getPointerAddressSpace();
1241
1242   // Otherwise, see if we can constant fold a load from the constant with the
1243   // offset applied as appropriate.
1244   Src = ConstantExpr::getBitCast(Src,
1245                                  Type::getInt8PtrTy(Src->getContext(), AS));
1246   Constant *OffsetCst =
1247     ConstantInt::get(Type::getInt64Ty(Src->getContext()), (unsigned)Offset);
1248   Src = ConstantExpr::getGetElementPtr(Src, OffsetCst);
1249   Src = ConstantExpr::getBitCast(Src, PointerType::get(LoadTy, AS));
1250   return ConstantFoldLoadFromConstPtr(Src, &DL);
1251 }
1252
1253
1254 /// ConstructSSAForLoadSet - Given a set of loads specified by ValuesPerBlock,
1255 /// construct SSA form, allowing us to eliminate LI.  This returns the value
1256 /// that should be used at LI's definition site.
1257 static Value *ConstructSSAForLoadSet(LoadInst *LI,
1258                          SmallVectorImpl<AvailableValueInBlock> &ValuesPerBlock,
1259                                      GVN &gvn) {
1260   // Check for the fully redundant, dominating load case.  In this case, we can
1261   // just use the dominating value directly.
1262   if (ValuesPerBlock.size() == 1 &&
1263       gvn.getDominatorTree().properlyDominates(ValuesPerBlock[0].BB,
1264                                                LI->getParent())) {
1265     assert(!ValuesPerBlock[0].isUndefValue() && "Dead BB dominate this block");
1266     return ValuesPerBlock[0].MaterializeAdjustedValue(LI->getType(), gvn);
1267   }
1268
1269   // Otherwise, we have to construct SSA form.
1270   SmallVector<PHINode*, 8> NewPHIs;
1271   SSAUpdater SSAUpdate(&NewPHIs);
1272   SSAUpdate.Initialize(LI->getType(), LI->getName());
1273
1274   Type *LoadTy = LI->getType();
1275
1276   for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i) {
1277     const AvailableValueInBlock &AV = ValuesPerBlock[i];
1278     BasicBlock *BB = AV.BB;
1279
1280     if (SSAUpdate.HasValueForBlock(BB))
1281       continue;
1282
1283     SSAUpdate.AddAvailableValue(BB, AV.MaterializeAdjustedValue(LoadTy, gvn));
1284   }
1285
1286   // Perform PHI construction.
1287   Value *V = SSAUpdate.GetValueInMiddleOfBlock(LI->getParent());
1288
1289   // If new PHI nodes were created, notify alias analysis.
1290   if (V->getType()->getScalarType()->isPointerTy()) {
1291     AliasAnalysis *AA = gvn.getAliasAnalysis();
1292
1293     for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i)
1294       AA->copyValue(LI, NewPHIs[i]);
1295
1296     // Now that we've copied information to the new PHIs, scan through
1297     // them again and inform alias analysis that we've added potentially
1298     // escaping uses to any values that are operands to these PHIs.
1299     for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i) {
1300       PHINode *P = NewPHIs[i];
1301       for (unsigned ii = 0, ee = P->getNumIncomingValues(); ii != ee; ++ii) {
1302         unsigned jj = PHINode::getOperandNumForIncomingValue(ii);
1303         AA->addEscapingUse(P->getOperandUse(jj));
1304       }
1305     }
1306   }
1307
1308   return V;
1309 }
1310
1311 Value *AvailableValueInBlock::MaterializeAdjustedValue(Type *LoadTy, GVN &gvn) const {
1312   Value *Res;
1313   if (isSimpleValue()) {
1314     Res = getSimpleValue();
1315     if (Res->getType() != LoadTy) {
1316       const DataLayout *DL = gvn.getDataLayout();
1317       assert(DL && "Need target data to handle type mismatch case");
1318       Res = GetStoreValueForLoad(Res, Offset, LoadTy, BB->getTerminator(),
1319                                  *DL);
1320   
1321       DEBUG(dbgs() << "GVN COERCED NONLOCAL VAL:\nOffset: " << Offset << "  "
1322                    << *getSimpleValue() << '\n'
1323                    << *Res << '\n' << "\n\n\n");
1324     }
1325   } else if (isCoercedLoadValue()) {
1326     LoadInst *Load = getCoercedLoadValue();
1327     if (Load->getType() == LoadTy && Offset == 0) {
1328       Res = Load;
1329     } else {
1330       Res = GetLoadValueForLoad(Load, Offset, LoadTy, BB->getTerminator(),
1331                                 gvn);
1332   
1333       DEBUG(dbgs() << "GVN COERCED NONLOCAL LOAD:\nOffset: " << Offset << "  "
1334                    << *getCoercedLoadValue() << '\n'
1335                    << *Res << '\n' << "\n\n\n");
1336     }
1337   } else if (isMemIntrinValue()) {
1338     const DataLayout *DL = gvn.getDataLayout();
1339     assert(DL && "Need target data to handle type mismatch case");
1340     Res = GetMemInstValueForLoad(getMemIntrinValue(), Offset,
1341                                  LoadTy, BB->getTerminator(), *DL);
1342     DEBUG(dbgs() << "GVN COERCED NONLOCAL MEM INTRIN:\nOffset: " << Offset
1343                  << "  " << *getMemIntrinValue() << '\n'
1344                  << *Res << '\n' << "\n\n\n");
1345   } else {
1346     assert(isUndefValue() && "Should be UndefVal");
1347     DEBUG(dbgs() << "GVN COERCED NONLOCAL Undef:\n";);
1348     return UndefValue::get(LoadTy);
1349   }
1350   return Res;
1351 }
1352
1353 static bool isLifetimeStart(const Instruction *Inst) {
1354   if (const IntrinsicInst* II = dyn_cast<IntrinsicInst>(Inst))
1355     return II->getIntrinsicID() == Intrinsic::lifetime_start;
1356   return false;
1357 }
1358
1359 void GVN::AnalyzeLoadAvailability(LoadInst *LI, LoadDepVect &Deps, 
1360                                   AvailValInBlkVect &ValuesPerBlock,
1361                                   UnavailBlkVect &UnavailableBlocks) {
1362
1363   // Filter out useless results (non-locals, etc).  Keep track of the blocks
1364   // where we have a value available in repl, also keep track of whether we see
1365   // dependencies that produce an unknown value for the load (such as a call
1366   // that could potentially clobber the load).
1367   unsigned NumDeps = Deps.size();
1368   for (unsigned i = 0, e = NumDeps; i != e; ++i) {
1369     BasicBlock *DepBB = Deps[i].getBB();
1370     MemDepResult DepInfo = Deps[i].getResult();
1371
1372     if (DeadBlocks.count(DepBB)) {
1373       // Dead dependent mem-op disguise as a load evaluating the same value
1374       // as the load in question.
1375       ValuesPerBlock.push_back(AvailableValueInBlock::getUndef(DepBB));
1376       continue;
1377     }
1378
1379     if (!DepInfo.isDef() && !DepInfo.isClobber()) {
1380       UnavailableBlocks.push_back(DepBB);
1381       continue;
1382     }
1383
1384     if (DepInfo.isClobber()) {
1385       // The address being loaded in this non-local block may not be the same as
1386       // the pointer operand of the load if PHI translation occurs.  Make sure
1387       // to consider the right address.
1388       Value *Address = Deps[i].getAddress();
1389
1390       // If the dependence is to a store that writes to a superset of the bits
1391       // read by the load, we can extract the bits we need for the load from the
1392       // stored value.
1393       if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInfo.getInst())) {
1394         if (DL && Address) {
1395           int Offset = AnalyzeLoadFromClobberingStore(LI->getType(), Address,
1396                                                       DepSI, *DL);
1397           if (Offset != -1) {
1398             ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1399                                                        DepSI->getValueOperand(),
1400                                                                 Offset));
1401             continue;
1402           }
1403         }
1404       }
1405
1406       // Check to see if we have something like this:
1407       //    load i32* P
1408       //    load i8* (P+1)
1409       // if we have this, replace the later with an extraction from the former.
1410       if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInfo.getInst())) {
1411         // If this is a clobber and L is the first instruction in its block, then
1412         // we have the first instruction in the entry block.
1413         if (DepLI != LI && Address && DL) {
1414           int Offset = AnalyzeLoadFromClobberingLoad(LI->getType(),
1415                                                      LI->getPointerOperand(),
1416                                                      DepLI, *DL);
1417
1418           if (Offset != -1) {
1419             ValuesPerBlock.push_back(AvailableValueInBlock::getLoad(DepBB,DepLI,
1420                                                                     Offset));
1421             continue;
1422           }
1423         }
1424       }
1425
1426       // If the clobbering value is a memset/memcpy/memmove, see if we can
1427       // forward a value on from it.
1428       if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(DepInfo.getInst())) {
1429         if (DL && Address) {
1430           int Offset = AnalyzeLoadFromClobberingMemInst(LI->getType(), Address,
1431                                                         DepMI, *DL);
1432           if (Offset != -1) {
1433             ValuesPerBlock.push_back(AvailableValueInBlock::getMI(DepBB, DepMI,
1434                                                                   Offset));
1435             continue;
1436           }
1437         }
1438       }
1439
1440       UnavailableBlocks.push_back(DepBB);
1441       continue;
1442     }
1443
1444     // DepInfo.isDef() here
1445
1446     Instruction *DepInst = DepInfo.getInst();
1447
1448     // Loading the allocation -> undef.
1449     if (isa<AllocaInst>(DepInst) || isMallocLikeFn(DepInst, TLI) ||
1450         // Loading immediately after lifetime begin -> undef.
1451         isLifetimeStart(DepInst)) {
1452       ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1453                                              UndefValue::get(LI->getType())));
1454       continue;
1455     }
1456
1457     if (StoreInst *S = dyn_cast<StoreInst>(DepInst)) {
1458       // Reject loads and stores that are to the same address but are of
1459       // different types if we have to.
1460       if (S->getValueOperand()->getType() != LI->getType()) {
1461         // If the stored value is larger or equal to the loaded value, we can
1462         // reuse it.
1463         if (DL == 0 || !CanCoerceMustAliasedValueToLoad(S->getValueOperand(),
1464                                                         LI->getType(), *DL)) {
1465           UnavailableBlocks.push_back(DepBB);
1466           continue;
1467         }
1468       }
1469
1470       ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1471                                                          S->getValueOperand()));
1472       continue;
1473     }
1474
1475     if (LoadInst *LD = dyn_cast<LoadInst>(DepInst)) {
1476       // If the types mismatch and we can't handle it, reject reuse of the load.
1477       if (LD->getType() != LI->getType()) {
1478         // If the stored value is larger or equal to the loaded value, we can
1479         // reuse it.
1480         if (DL == 0 || !CanCoerceMustAliasedValueToLoad(LD, LI->getType(),*DL)){
1481           UnavailableBlocks.push_back(DepBB);
1482           continue;
1483         }
1484       }
1485       ValuesPerBlock.push_back(AvailableValueInBlock::getLoad(DepBB, LD));
1486       continue;
1487     }
1488
1489     UnavailableBlocks.push_back(DepBB);
1490   }
1491 }
1492
1493 bool GVN::PerformLoadPRE(LoadInst *LI, AvailValInBlkVect &ValuesPerBlock, 
1494                          UnavailBlkVect &UnavailableBlocks) {
1495   // Okay, we have *some* definitions of the value.  This means that the value
1496   // is available in some of our (transitive) predecessors.  Lets think about
1497   // doing PRE of this load.  This will involve inserting a new load into the
1498   // predecessor when it's not available.  We could do this in general, but
1499   // prefer to not increase code size.  As such, we only do this when we know
1500   // that we only have to insert *one* load (which means we're basically moving
1501   // the load, not inserting a new one).
1502
1503   SmallPtrSet<BasicBlock *, 4> Blockers;
1504   for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1505     Blockers.insert(UnavailableBlocks[i]);
1506
1507   // Let's find the first basic block with more than one predecessor.  Walk
1508   // backwards through predecessors if needed.
1509   BasicBlock *LoadBB = LI->getParent();
1510   BasicBlock *TmpBB = LoadBB;
1511
1512   while (TmpBB->getSinglePredecessor()) {
1513     TmpBB = TmpBB->getSinglePredecessor();
1514     if (TmpBB == LoadBB) // Infinite (unreachable) loop.
1515       return false;
1516     if (Blockers.count(TmpBB))
1517       return false;
1518
1519     // If any of these blocks has more than one successor (i.e. if the edge we
1520     // just traversed was critical), then there are other paths through this
1521     // block along which the load may not be anticipated.  Hoisting the load
1522     // above this block would be adding the load to execution paths along
1523     // which it was not previously executed.
1524     if (TmpBB->getTerminator()->getNumSuccessors() != 1)
1525       return false;
1526   }
1527
1528   assert(TmpBB);
1529   LoadBB = TmpBB;
1530
1531   // Check to see how many predecessors have the loaded value fully
1532   // available.
1533   DenseMap<BasicBlock*, Value*> PredLoads;
1534   DenseMap<BasicBlock*, char> FullyAvailableBlocks;
1535   for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
1536     FullyAvailableBlocks[ValuesPerBlock[i].BB] = true;
1537   for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1538     FullyAvailableBlocks[UnavailableBlocks[i]] = false;
1539
1540   SmallVector<BasicBlock *, 4> CriticalEdgePred;
1541   for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB);
1542        PI != E; ++PI) {
1543     BasicBlock *Pred = *PI;
1544     if (IsValueFullyAvailableInBlock(Pred, FullyAvailableBlocks, 0)) {
1545       continue;
1546     }
1547     PredLoads[Pred] = 0;
1548
1549     if (Pred->getTerminator()->getNumSuccessors() != 1) {
1550       if (isa<IndirectBrInst>(Pred->getTerminator())) {
1551         DEBUG(dbgs() << "COULD NOT PRE LOAD BECAUSE OF INDBR CRITICAL EDGE '"
1552               << Pred->getName() << "': " << *LI << '\n');
1553         return false;
1554       }
1555
1556       if (LoadBB->isLandingPad()) {
1557         DEBUG(dbgs()
1558               << "COULD NOT PRE LOAD BECAUSE OF LANDING PAD CRITICAL EDGE '"
1559               << Pred->getName() << "': " << *LI << '\n');
1560         return false;
1561       }
1562
1563       CriticalEdgePred.push_back(Pred);
1564     }
1565   }
1566
1567   // Decide whether PRE is profitable for this load.
1568   unsigned NumUnavailablePreds = PredLoads.size();
1569   assert(NumUnavailablePreds != 0 &&
1570          "Fully available value should already be eliminated!");
1571
1572   // If this load is unavailable in multiple predecessors, reject it.
1573   // FIXME: If we could restructure the CFG, we could make a common pred with
1574   // all the preds that don't have an available LI and insert a new load into
1575   // that one block.
1576   if (NumUnavailablePreds != 1)
1577       return false;
1578
1579   // Split critical edges, and update the unavailable predecessors accordingly.
1580   for (SmallVectorImpl<BasicBlock *>::iterator I = CriticalEdgePred.begin(),
1581          E = CriticalEdgePred.end(); I != E; I++) {
1582     BasicBlock *OrigPred = *I;
1583     BasicBlock *NewPred = splitCriticalEdges(OrigPred, LoadBB);
1584     PredLoads.erase(OrigPred);
1585     PredLoads[NewPred] = 0;
1586     DEBUG(dbgs() << "Split critical edge " << OrigPred->getName() << "->"
1587                  << LoadBB->getName() << '\n');
1588   }
1589
1590   // Check if the load can safely be moved to all the unavailable predecessors.
1591   bool CanDoPRE = true;
1592   SmallVector<Instruction*, 8> NewInsts;
1593   for (DenseMap<BasicBlock*, Value*>::iterator I = PredLoads.begin(),
1594          E = PredLoads.end(); I != E; ++I) {
1595     BasicBlock *UnavailablePred = I->first;
1596
1597     // Do PHI translation to get its value in the predecessor if necessary.  The
1598     // returned pointer (if non-null) is guaranteed to dominate UnavailablePred.
1599
1600     // If all preds have a single successor, then we know it is safe to insert
1601     // the load on the pred (?!?), so we can insert code to materialize the
1602     // pointer if it is not available.
1603     PHITransAddr Address(LI->getPointerOperand(), DL);
1604     Value *LoadPtr = 0;
1605     LoadPtr = Address.PHITranslateWithInsertion(LoadBB, UnavailablePred,
1606                                                 *DT, NewInsts);
1607
1608     // If we couldn't find or insert a computation of this phi translated value,
1609     // we fail PRE.
1610     if (LoadPtr == 0) {
1611       DEBUG(dbgs() << "COULDN'T INSERT PHI TRANSLATED VALUE OF: "
1612             << *LI->getPointerOperand() << "\n");
1613       CanDoPRE = false;
1614       break;
1615     }
1616
1617     I->second = LoadPtr;
1618   }
1619
1620   if (!CanDoPRE) {
1621     while (!NewInsts.empty()) {
1622       Instruction *I = NewInsts.pop_back_val();
1623       if (MD) MD->removeInstruction(I);
1624       I->eraseFromParent();
1625     }
1626     // HINT:Don't revert the edge-splitting as following transformation may 
1627     // also need to split these critial edges.
1628     return !CriticalEdgePred.empty();
1629   }
1630
1631   // Okay, we can eliminate this load by inserting a reload in the predecessor
1632   // and using PHI construction to get the value in the other predecessors, do
1633   // it.
1634   DEBUG(dbgs() << "GVN REMOVING PRE LOAD: " << *LI << '\n');
1635   DEBUG(if (!NewInsts.empty())
1636           dbgs() << "INSERTED " << NewInsts.size() << " INSTS: "
1637                  << *NewInsts.back() << '\n');
1638
1639   // Assign value numbers to the new instructions.
1640   for (unsigned i = 0, e = NewInsts.size(); i != e; ++i) {
1641     // FIXME: We really _ought_ to insert these value numbers into their
1642     // parent's availability map.  However, in doing so, we risk getting into
1643     // ordering issues.  If a block hasn't been processed yet, we would be
1644     // marking a value as AVAIL-IN, which isn't what we intend.
1645     VN.lookup_or_add(NewInsts[i]);
1646   }
1647
1648   for (DenseMap<BasicBlock*, Value*>::iterator I = PredLoads.begin(),
1649          E = PredLoads.end(); I != E; ++I) {
1650     BasicBlock *UnavailablePred = I->first;
1651     Value *LoadPtr = I->second;
1652
1653     Instruction *NewLoad = new LoadInst(LoadPtr, LI->getName()+".pre", false,
1654                                         LI->getAlignment(),
1655                                         UnavailablePred->getTerminator());
1656
1657     // Transfer the old load's TBAA tag to the new load.
1658     if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa))
1659       NewLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1660
1661     // Transfer DebugLoc.
1662     NewLoad->setDebugLoc(LI->getDebugLoc());
1663
1664     // Add the newly created load.
1665     ValuesPerBlock.push_back(AvailableValueInBlock::get(UnavailablePred,
1666                                                         NewLoad));
1667     MD->invalidateCachedPointerInfo(LoadPtr);
1668     DEBUG(dbgs() << "GVN INSERTED " << *NewLoad << '\n');
1669   }
1670
1671   // Perform PHI construction.
1672   Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this);
1673   LI->replaceAllUsesWith(V);
1674   if (isa<PHINode>(V))
1675     V->takeName(LI);
1676   if (V->getType()->getScalarType()->isPointerTy())
1677     MD->invalidateCachedPointerInfo(V);
1678   markInstructionForDeletion(LI);
1679   ++NumPRELoad;
1680   return true;
1681 }
1682
1683 /// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
1684 /// non-local by performing PHI construction.
1685 bool GVN::processNonLocalLoad(LoadInst *LI) {
1686   // Step 1: Find the non-local dependencies of the load.
1687   LoadDepVect Deps;
1688   AliasAnalysis::Location Loc = VN.getAliasAnalysis()->getLocation(LI);
1689   MD->getNonLocalPointerDependency(Loc, true, LI->getParent(), Deps);
1690
1691   // If we had to process more than one hundred blocks to find the
1692   // dependencies, this load isn't worth worrying about.  Optimizing
1693   // it will be too expensive.
1694   unsigned NumDeps = Deps.size();
1695   if (NumDeps > 100)
1696     return false;
1697
1698   // If we had a phi translation failure, we'll have a single entry which is a
1699   // clobber in the current block.  Reject this early.
1700   if (NumDeps == 1 &&
1701       !Deps[0].getResult().isDef() && !Deps[0].getResult().isClobber()) {
1702     DEBUG(
1703       dbgs() << "GVN: non-local load ";
1704       LI->printAsOperand(dbgs());
1705       dbgs() << " has unknown dependencies\n";
1706     );
1707     return false;
1708   }
1709
1710   // Step 2: Analyze the availability of the load
1711   AvailValInBlkVect ValuesPerBlock;
1712   UnavailBlkVect UnavailableBlocks;
1713   AnalyzeLoadAvailability(LI, Deps, ValuesPerBlock, UnavailableBlocks);
1714
1715   // If we have no predecessors that produce a known value for this load, exit
1716   // early.
1717   if (ValuesPerBlock.empty())
1718     return false;
1719
1720   // Step 3: Eliminate fully redundancy.
1721   //
1722   // If all of the instructions we depend on produce a known value for this
1723   // load, then it is fully redundant and we can use PHI insertion to compute
1724   // its value.  Insert PHIs and remove the fully redundant value now.
1725   if (UnavailableBlocks.empty()) {
1726     DEBUG(dbgs() << "GVN REMOVING NONLOCAL LOAD: " << *LI << '\n');
1727
1728     // Perform PHI construction.
1729     Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this);
1730     LI->replaceAllUsesWith(V);
1731
1732     if (isa<PHINode>(V))
1733       V->takeName(LI);
1734     if (V->getType()->getScalarType()->isPointerTy())
1735       MD->invalidateCachedPointerInfo(V);
1736     markInstructionForDeletion(LI);
1737     ++NumGVNLoad;
1738     return true;
1739   }
1740
1741   // Step 4: Eliminate partial redundancy.
1742   if (!EnablePRE || !EnableLoadPRE)
1743     return false;
1744
1745   return PerformLoadPRE(LI, ValuesPerBlock, UnavailableBlocks);
1746 }
1747
1748
1749 static void patchReplacementInstruction(Instruction *I, Value *Repl) {
1750   // Patch the replacement so that it is not more restrictive than the value
1751   // being replaced.
1752   BinaryOperator *Op = dyn_cast<BinaryOperator>(I);
1753   BinaryOperator *ReplOp = dyn_cast<BinaryOperator>(Repl);
1754   if (Op && ReplOp && isa<OverflowingBinaryOperator>(Op) &&
1755       isa<OverflowingBinaryOperator>(ReplOp)) {
1756     if (ReplOp->hasNoSignedWrap() && !Op->hasNoSignedWrap())
1757       ReplOp->setHasNoSignedWrap(false);
1758     if (ReplOp->hasNoUnsignedWrap() && !Op->hasNoUnsignedWrap())
1759       ReplOp->setHasNoUnsignedWrap(false);
1760   }
1761   if (Instruction *ReplInst = dyn_cast<Instruction>(Repl)) {
1762     SmallVector<std::pair<unsigned, MDNode*>, 4> Metadata;
1763     ReplInst->getAllMetadataOtherThanDebugLoc(Metadata);
1764     for (int i = 0, n = Metadata.size(); i < n; ++i) {
1765       unsigned Kind = Metadata[i].first;
1766       MDNode *IMD = I->getMetadata(Kind);
1767       MDNode *ReplMD = Metadata[i].second;
1768       switch(Kind) {
1769       default:
1770         ReplInst->setMetadata(Kind, NULL); // Remove unknown metadata
1771         break;
1772       case LLVMContext::MD_dbg:
1773         llvm_unreachable("getAllMetadataOtherThanDebugLoc returned a MD_dbg");
1774       case LLVMContext::MD_tbaa:
1775         ReplInst->setMetadata(Kind, MDNode::getMostGenericTBAA(IMD, ReplMD));
1776         break;
1777       case LLVMContext::MD_range:
1778         ReplInst->setMetadata(Kind, MDNode::getMostGenericRange(IMD, ReplMD));
1779         break;
1780       case LLVMContext::MD_prof:
1781         llvm_unreachable("MD_prof in a non-terminator instruction");
1782         break;
1783       case LLVMContext::MD_fpmath:
1784         ReplInst->setMetadata(Kind, MDNode::getMostGenericFPMath(IMD, ReplMD));
1785         break;
1786       }
1787     }
1788   }
1789 }
1790
1791 static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
1792   patchReplacementInstruction(I, Repl);
1793   I->replaceAllUsesWith(Repl);
1794 }
1795
1796 /// processLoad - Attempt to eliminate a load, first by eliminating it
1797 /// locally, and then attempting non-local elimination if that fails.
1798 bool GVN::processLoad(LoadInst *L) {
1799   if (!MD)
1800     return false;
1801
1802   if (!L->isSimple())
1803     return false;
1804
1805   if (L->use_empty()) {
1806     markInstructionForDeletion(L);
1807     return true;
1808   }
1809
1810   // ... to a pointer that has been loaded from before...
1811   MemDepResult Dep = MD->getDependency(L);
1812
1813   // If we have a clobber and target data is around, see if this is a clobber
1814   // that we can fix up through code synthesis.
1815   if (Dep.isClobber() && DL) {
1816     // Check to see if we have something like this:
1817     //   store i32 123, i32* %P
1818     //   %A = bitcast i32* %P to i8*
1819     //   %B = gep i8* %A, i32 1
1820     //   %C = load i8* %B
1821     //
1822     // We could do that by recognizing if the clobber instructions are obviously
1823     // a common base + constant offset, and if the previous store (or memset)
1824     // completely covers this load.  This sort of thing can happen in bitfield
1825     // access code.
1826     Value *AvailVal = 0;
1827     if (StoreInst *DepSI = dyn_cast<StoreInst>(Dep.getInst())) {
1828       int Offset = AnalyzeLoadFromClobberingStore(L->getType(),
1829                                                   L->getPointerOperand(),
1830                                                   DepSI, *DL);
1831       if (Offset != -1)
1832         AvailVal = GetStoreValueForLoad(DepSI->getValueOperand(), Offset,
1833                                         L->getType(), L, *DL);
1834     }
1835
1836     // Check to see if we have something like this:
1837     //    load i32* P
1838     //    load i8* (P+1)
1839     // if we have this, replace the later with an extraction from the former.
1840     if (LoadInst *DepLI = dyn_cast<LoadInst>(Dep.getInst())) {
1841       // If this is a clobber and L is the first instruction in its block, then
1842       // we have the first instruction in the entry block.
1843       if (DepLI == L)
1844         return false;
1845
1846       int Offset = AnalyzeLoadFromClobberingLoad(L->getType(),
1847                                                  L->getPointerOperand(),
1848                                                  DepLI, *DL);
1849       if (Offset != -1)
1850         AvailVal = GetLoadValueForLoad(DepLI, Offset, L->getType(), L, *this);
1851     }
1852
1853     // If the clobbering value is a memset/memcpy/memmove, see if we can forward
1854     // a value on from it.
1855     if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(Dep.getInst())) {
1856       int Offset = AnalyzeLoadFromClobberingMemInst(L->getType(),
1857                                                     L->getPointerOperand(),
1858                                                     DepMI, *DL);
1859       if (Offset != -1)
1860         AvailVal = GetMemInstValueForLoad(DepMI, Offset, L->getType(), L, *DL);
1861     }
1862
1863     if (AvailVal) {
1864       DEBUG(dbgs() << "GVN COERCED INST:\n" << *Dep.getInst() << '\n'
1865             << *AvailVal << '\n' << *L << "\n\n\n");
1866
1867       // Replace the load!
1868       L->replaceAllUsesWith(AvailVal);
1869       if (AvailVal->getType()->getScalarType()->isPointerTy())
1870         MD->invalidateCachedPointerInfo(AvailVal);
1871       markInstructionForDeletion(L);
1872       ++NumGVNLoad;
1873       return true;
1874     }
1875   }
1876
1877   // If the value isn't available, don't do anything!
1878   if (Dep.isClobber()) {
1879     DEBUG(
1880       // fast print dep, using operator<< on instruction is too slow.
1881       dbgs() << "GVN: load ";
1882       L->printAsOperand(dbgs());
1883       Instruction *I = Dep.getInst();
1884       dbgs() << " is clobbered by " << *I << '\n';
1885     );
1886     return false;
1887   }
1888
1889   // If it is defined in another block, try harder.
1890   if (Dep.isNonLocal())
1891     return processNonLocalLoad(L);
1892
1893   if (!Dep.isDef()) {
1894     DEBUG(
1895       // fast print dep, using operator<< on instruction is too slow.
1896       dbgs() << "GVN: load ";
1897       L->printAsOperand(dbgs());
1898       dbgs() << " has unknown dependence\n";
1899     );
1900     return false;
1901   }
1902
1903   Instruction *DepInst = Dep.getInst();
1904   if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInst)) {
1905     Value *StoredVal = DepSI->getValueOperand();
1906
1907     // The store and load are to a must-aliased pointer, but they may not
1908     // actually have the same type.  See if we know how to reuse the stored
1909     // value (depending on its type).
1910     if (StoredVal->getType() != L->getType()) {
1911       if (DL) {
1912         StoredVal = CoerceAvailableValueToLoadType(StoredVal, L->getType(),
1913                                                    L, *DL);
1914         if (StoredVal == 0)
1915           return false;
1916
1917         DEBUG(dbgs() << "GVN COERCED STORE:\n" << *DepSI << '\n' << *StoredVal
1918                      << '\n' << *L << "\n\n\n");
1919       }
1920       else
1921         return false;
1922     }
1923
1924     // Remove it!
1925     L->replaceAllUsesWith(StoredVal);
1926     if (StoredVal->getType()->getScalarType()->isPointerTy())
1927       MD->invalidateCachedPointerInfo(StoredVal);
1928     markInstructionForDeletion(L);
1929     ++NumGVNLoad;
1930     return true;
1931   }
1932
1933   if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInst)) {
1934     Value *AvailableVal = DepLI;
1935
1936     // The loads are of a must-aliased pointer, but they may not actually have
1937     // the same type.  See if we know how to reuse the previously loaded value
1938     // (depending on its type).
1939     if (DepLI->getType() != L->getType()) {
1940       if (DL) {
1941         AvailableVal = CoerceAvailableValueToLoadType(DepLI, L->getType(),
1942                                                       L, *DL);
1943         if (AvailableVal == 0)
1944           return false;
1945
1946         DEBUG(dbgs() << "GVN COERCED LOAD:\n" << *DepLI << "\n" << *AvailableVal
1947                      << "\n" << *L << "\n\n\n");
1948       }
1949       else
1950         return false;
1951     }
1952
1953     // Remove it!
1954     patchAndReplaceAllUsesWith(L, AvailableVal);
1955     if (DepLI->getType()->getScalarType()->isPointerTy())
1956       MD->invalidateCachedPointerInfo(DepLI);
1957     markInstructionForDeletion(L);
1958     ++NumGVNLoad;
1959     return true;
1960   }
1961
1962   // If this load really doesn't depend on anything, then we must be loading an
1963   // undef value.  This can happen when loading for a fresh allocation with no
1964   // intervening stores, for example.
1965   if (isa<AllocaInst>(DepInst) || isMallocLikeFn(DepInst, TLI)) {
1966     L->replaceAllUsesWith(UndefValue::get(L->getType()));
1967     markInstructionForDeletion(L);
1968     ++NumGVNLoad;
1969     return true;
1970   }
1971
1972   // If this load occurs either right after a lifetime begin,
1973   // then the loaded value is undefined.
1974   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(DepInst)) {
1975     if (II->getIntrinsicID() == Intrinsic::lifetime_start) {
1976       L->replaceAllUsesWith(UndefValue::get(L->getType()));
1977       markInstructionForDeletion(L);
1978       ++NumGVNLoad;
1979       return true;
1980     }
1981   }
1982
1983   return false;
1984 }
1985
1986 // findLeader - In order to find a leader for a given value number at a
1987 // specific basic block, we first obtain the list of all Values for that number,
1988 // and then scan the list to find one whose block dominates the block in
1989 // question.  This is fast because dominator tree queries consist of only
1990 // a few comparisons of DFS numbers.
1991 Value *GVN::findLeader(const BasicBlock *BB, uint32_t num) {
1992   LeaderTableEntry Vals = LeaderTable[num];
1993   if (!Vals.Val) return 0;
1994
1995   Value *Val = 0;
1996   if (DT->dominates(Vals.BB, BB)) {
1997     Val = Vals.Val;
1998     if (isa<Constant>(Val)) return Val;
1999   }
2000
2001   LeaderTableEntry* Next = Vals.Next;
2002   while (Next) {
2003     if (DT->dominates(Next->BB, BB)) {
2004       if (isa<Constant>(Next->Val)) return Next->Val;
2005       if (!Val) Val = Next->Val;
2006     }
2007
2008     Next = Next->Next;
2009   }
2010
2011   return Val;
2012 }
2013
2014 /// replaceAllDominatedUsesWith - Replace all uses of 'From' with 'To' if the
2015 /// use is dominated by the given basic block.  Returns the number of uses that
2016 /// were replaced.
2017 unsigned GVN::replaceAllDominatedUsesWith(Value *From, Value *To,
2018                                           const BasicBlockEdge &Root) {
2019   unsigned Count = 0;
2020   for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
2021        UI != UE; ) {
2022     Use &U = *UI++;
2023
2024     if (DT->dominates(Root, U)) {
2025       U.set(To);
2026       ++Count;
2027     }
2028   }
2029   return Count;
2030 }
2031
2032 /// isOnlyReachableViaThisEdge - There is an edge from 'Src' to 'Dst'.  Return
2033 /// true if every path from the entry block to 'Dst' passes via this edge.  In
2034 /// particular 'Dst' must not be reachable via another edge from 'Src'.
2035 static bool isOnlyReachableViaThisEdge(const BasicBlockEdge &E,
2036                                        DominatorTree *DT) {
2037   // While in theory it is interesting to consider the case in which Dst has
2038   // more than one predecessor, because Dst might be part of a loop which is
2039   // only reachable from Src, in practice it is pointless since at the time
2040   // GVN runs all such loops have preheaders, which means that Dst will have
2041   // been changed to have only one predecessor, namely Src.
2042   const BasicBlock *Pred = E.getEnd()->getSinglePredecessor();
2043   const BasicBlock *Src = E.getStart();
2044   assert((!Pred || Pred == Src) && "No edge between these basic blocks!");
2045   (void)Src;
2046   return Pred != 0;
2047 }
2048
2049 /// propagateEquality - The given values are known to be equal in every block
2050 /// dominated by 'Root'.  Exploit this, for example by replacing 'LHS' with
2051 /// 'RHS' everywhere in the scope.  Returns whether a change was made.
2052 bool GVN::propagateEquality(Value *LHS, Value *RHS,
2053                             const BasicBlockEdge &Root) {
2054   SmallVector<std::pair<Value*, Value*>, 4> Worklist;
2055   Worklist.push_back(std::make_pair(LHS, RHS));
2056   bool Changed = false;
2057   // For speed, compute a conservative fast approximation to
2058   // DT->dominates(Root, Root.getEnd());
2059   bool RootDominatesEnd = isOnlyReachableViaThisEdge(Root, DT);
2060
2061   while (!Worklist.empty()) {
2062     std::pair<Value*, Value*> Item = Worklist.pop_back_val();
2063     LHS = Item.first; RHS = Item.second;
2064
2065     if (LHS == RHS) continue;
2066     assert(LHS->getType() == RHS->getType() && "Equality but unequal types!");
2067
2068     // Don't try to propagate equalities between constants.
2069     if (isa<Constant>(LHS) && isa<Constant>(RHS)) continue;
2070
2071     // Prefer a constant on the right-hand side, or an Argument if no constants.
2072     if (isa<Constant>(LHS) || (isa<Argument>(LHS) && !isa<Constant>(RHS)))
2073       std::swap(LHS, RHS);
2074     assert((isa<Argument>(LHS) || isa<Instruction>(LHS)) && "Unexpected value!");
2075
2076     // If there is no obvious reason to prefer the left-hand side over the right-
2077     // hand side, ensure the longest lived term is on the right-hand side, so the
2078     // shortest lived term will be replaced by the longest lived.  This tends to
2079     // expose more simplifications.
2080     uint32_t LVN = VN.lookup_or_add(LHS);
2081     if ((isa<Argument>(LHS) && isa<Argument>(RHS)) ||
2082         (isa<Instruction>(LHS) && isa<Instruction>(RHS))) {
2083       // Move the 'oldest' value to the right-hand side, using the value number as
2084       // a proxy for age.
2085       uint32_t RVN = VN.lookup_or_add(RHS);
2086       if (LVN < RVN) {
2087         std::swap(LHS, RHS);
2088         LVN = RVN;
2089       }
2090     }
2091
2092     // If value numbering later sees that an instruction in the scope is equal
2093     // to 'LHS' then ensure it will be turned into 'RHS'.  In order to preserve
2094     // the invariant that instructions only occur in the leader table for their
2095     // own value number (this is used by removeFromLeaderTable), do not do this
2096     // if RHS is an instruction (if an instruction in the scope is morphed into
2097     // LHS then it will be turned into RHS by the next GVN iteration anyway, so
2098     // using the leader table is about compiling faster, not optimizing better).
2099     // The leader table only tracks basic blocks, not edges. Only add to if we
2100     // have the simple case where the edge dominates the end.
2101     if (RootDominatesEnd && !isa<Instruction>(RHS))
2102       addToLeaderTable(LVN, RHS, Root.getEnd());
2103
2104     // Replace all occurrences of 'LHS' with 'RHS' everywhere in the scope.  As
2105     // LHS always has at least one use that is not dominated by Root, this will
2106     // never do anything if LHS has only one use.
2107     if (!LHS->hasOneUse()) {
2108       unsigned NumReplacements = replaceAllDominatedUsesWith(LHS, RHS, Root);
2109       Changed |= NumReplacements > 0;
2110       NumGVNEqProp += NumReplacements;
2111     }
2112
2113     // Now try to deduce additional equalities from this one.  For example, if the
2114     // known equality was "(A != B)" == "false" then it follows that A and B are
2115     // equal in the scope.  Only boolean equalities with an explicit true or false
2116     // RHS are currently supported.
2117     if (!RHS->getType()->isIntegerTy(1))
2118       // Not a boolean equality - bail out.
2119       continue;
2120     ConstantInt *CI = dyn_cast<ConstantInt>(RHS);
2121     if (!CI)
2122       // RHS neither 'true' nor 'false' - bail out.
2123       continue;
2124     // Whether RHS equals 'true'.  Otherwise it equals 'false'.
2125     bool isKnownTrue = CI->isAllOnesValue();
2126     bool isKnownFalse = !isKnownTrue;
2127
2128     // If "A && B" is known true then both A and B are known true.  If "A || B"
2129     // is known false then both A and B are known false.
2130     Value *A, *B;
2131     if ((isKnownTrue && match(LHS, m_And(m_Value(A), m_Value(B)))) ||
2132         (isKnownFalse && match(LHS, m_Or(m_Value(A), m_Value(B))))) {
2133       Worklist.push_back(std::make_pair(A, RHS));
2134       Worklist.push_back(std::make_pair(B, RHS));
2135       continue;
2136     }
2137
2138     // If we are propagating an equality like "(A == B)" == "true" then also
2139     // propagate the equality A == B.  When propagating a comparison such as
2140     // "(A >= B)" == "true", replace all instances of "A < B" with "false".
2141     if (ICmpInst *Cmp = dyn_cast<ICmpInst>(LHS)) {
2142       Value *Op0 = Cmp->getOperand(0), *Op1 = Cmp->getOperand(1);
2143
2144       // If "A == B" is known true, or "A != B" is known false, then replace
2145       // A with B everywhere in the scope.
2146       if ((isKnownTrue && Cmp->getPredicate() == CmpInst::ICMP_EQ) ||
2147           (isKnownFalse && Cmp->getPredicate() == CmpInst::ICMP_NE))
2148         Worklist.push_back(std::make_pair(Op0, Op1));
2149
2150       // If "A >= B" is known true, replace "A < B" with false everywhere.
2151       CmpInst::Predicate NotPred = Cmp->getInversePredicate();
2152       Constant *NotVal = ConstantInt::get(Cmp->getType(), isKnownFalse);
2153       // Since we don't have the instruction "A < B" immediately to hand, work out
2154       // the value number that it would have and use that to find an appropriate
2155       // instruction (if any).
2156       uint32_t NextNum = VN.getNextUnusedValueNumber();
2157       uint32_t Num = VN.lookup_or_add_cmp(Cmp->getOpcode(), NotPred, Op0, Op1);
2158       // If the number we were assigned was brand new then there is no point in
2159       // looking for an instruction realizing it: there cannot be one!
2160       if (Num < NextNum) {
2161         Value *NotCmp = findLeader(Root.getEnd(), Num);
2162         if (NotCmp && isa<Instruction>(NotCmp)) {
2163           unsigned NumReplacements =
2164             replaceAllDominatedUsesWith(NotCmp, NotVal, Root);
2165           Changed |= NumReplacements > 0;
2166           NumGVNEqProp += NumReplacements;
2167         }
2168       }
2169       // Ensure that any instruction in scope that gets the "A < B" value number
2170       // is replaced with false.
2171       // The leader table only tracks basic blocks, not edges. Only add to if we
2172       // have the simple case where the edge dominates the end.
2173       if (RootDominatesEnd)
2174         addToLeaderTable(Num, NotVal, Root.getEnd());
2175
2176       continue;
2177     }
2178   }
2179
2180   return Changed;
2181 }
2182
2183 static bool normalOpAfterIntrinsic(Instruction *I, Value *Repl)
2184 {
2185   switch (I->getOpcode()) {
2186     case Instruction::Add:
2187       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Repl))
2188           return II->getIntrinsicID() == Intrinsic::sadd_with_overflow
2189               || II->getIntrinsicID() == Intrinsic::uadd_with_overflow;
2190       return false;
2191     case Instruction::Sub:
2192       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Repl))
2193           return II->getIntrinsicID() == Intrinsic::ssub_with_overflow
2194               || II->getIntrinsicID() == Intrinsic::usub_with_overflow;
2195       return false;
2196     case Instruction::Mul:
2197       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Repl))
2198           return II->getIntrinsicID() == Intrinsic::smul_with_overflow
2199               || II->getIntrinsicID() == Intrinsic::umul_with_overflow;
2200       return false;
2201     default:
2202       return false;
2203   }
2204 }
2205
2206 static bool intrinsicAterNormalOp(Instruction *I, Value *Repl)
2207 {
2208   IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
2209   if (!II)
2210     return false;
2211
2212   Instruction *RI = dyn_cast<Instruction>(Repl);
2213   if (!RI)
2214     return false;
2215
2216   switch (RI->getOpcode()) {
2217     case Instruction::Add:
2218       return II->getIntrinsicID() == Intrinsic::sadd_with_overflow
2219           || II->getIntrinsicID() == Intrinsic::uadd_with_overflow;
2220     case Instruction::Sub:
2221       return II->getIntrinsicID() == Intrinsic::ssub_with_overflow
2222           || II->getIntrinsicID() == Intrinsic::usub_with_overflow;
2223     case Instruction::Mul:
2224       return II->getIntrinsicID() == Intrinsic::smul_with_overflow
2225           || II->getIntrinsicID() == Intrinsic::umul_with_overflow;
2226     default:
2227       return false;
2228   }
2229 }
2230
2231 /// processInstruction - When calculating availability, handle an instruction
2232 /// by inserting it into the appropriate sets
2233 bool GVN::processInstruction(Instruction *I) {
2234   // Ignore dbg info intrinsics.
2235   if (isa<DbgInfoIntrinsic>(I))
2236     return false;
2237
2238   // If the instruction can be easily simplified then do so now in preference
2239   // to value numbering it.  Value numbering often exposes redundancies, for
2240   // example if it determines that %y is equal to %x then the instruction
2241   // "%z = and i32 %x, %y" becomes "%z = and i32 %x, %x" which we now simplify.
2242   if (Value *V = SimplifyInstruction(I, DL, TLI, DT)) {
2243     I->replaceAllUsesWith(V);
2244     if (MD && V->getType()->getScalarType()->isPointerTy())
2245       MD->invalidateCachedPointerInfo(V);
2246     markInstructionForDeletion(I);
2247     ++NumGVNSimpl;
2248     return true;
2249   }
2250
2251   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
2252     if (processLoad(LI))
2253       return true;
2254
2255     unsigned Num = VN.lookup_or_add(LI);
2256     addToLeaderTable(Num, LI, LI->getParent());
2257     return false;
2258   }
2259
2260   // For conditional branches, we can perform simple conditional propagation on
2261   // the condition value itself.
2262   if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
2263     if (!BI->isConditional())
2264       return false;
2265
2266     if (isa<Constant>(BI->getCondition()))
2267       return processFoldableCondBr(BI);
2268
2269     Value *BranchCond = BI->getCondition();
2270     BasicBlock *TrueSucc = BI->getSuccessor(0);
2271     BasicBlock *FalseSucc = BI->getSuccessor(1);
2272     // Avoid multiple edges early.
2273     if (TrueSucc == FalseSucc)
2274       return false;
2275
2276     BasicBlock *Parent = BI->getParent();
2277     bool Changed = false;
2278
2279     Value *TrueVal = ConstantInt::getTrue(TrueSucc->getContext());
2280     BasicBlockEdge TrueE(Parent, TrueSucc);
2281     Changed |= propagateEquality(BranchCond, TrueVal, TrueE);
2282
2283     Value *FalseVal = ConstantInt::getFalse(FalseSucc->getContext());
2284     BasicBlockEdge FalseE(Parent, FalseSucc);
2285     Changed |= propagateEquality(BranchCond, FalseVal, FalseE);
2286
2287     return Changed;
2288   }
2289
2290   // For switches, propagate the case values into the case destinations.
2291   if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
2292     Value *SwitchCond = SI->getCondition();
2293     BasicBlock *Parent = SI->getParent();
2294     bool Changed = false;
2295
2296     // Remember how many outgoing edges there are to every successor.
2297     SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
2298     for (unsigned i = 0, n = SI->getNumSuccessors(); i != n; ++i)
2299       ++SwitchEdges[SI->getSuccessor(i)];
2300
2301     for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
2302          i != e; ++i) {
2303       BasicBlock *Dst = i.getCaseSuccessor();
2304       // If there is only a single edge, propagate the case value into it.
2305       if (SwitchEdges.lookup(Dst) == 1) {
2306         BasicBlockEdge E(Parent, Dst);
2307         Changed |= propagateEquality(SwitchCond, i.getCaseValue(), E);
2308       }
2309     }
2310     return Changed;
2311   }
2312
2313   // Instructions with void type don't return a value, so there's
2314   // no point in trying to find redundancies in them.
2315   if (I->getType()->isVoidTy()) return false;
2316
2317   uint32_t NextNum = VN.getNextUnusedValueNumber();
2318   unsigned Num = VN.lookup_or_add(I);
2319
2320   // Allocations are always uniquely numbered, so we can save time and memory
2321   // by fast failing them.
2322   if (isa<AllocaInst>(I) || isa<TerminatorInst>(I) || isa<PHINode>(I)) {
2323     addToLeaderTable(Num, I, I->getParent());
2324     return false;
2325   }
2326
2327   // If the number we were assigned was a brand new VN, then we don't
2328   // need to do a lookup to see if the number already exists
2329   // somewhere in the domtree: it can't!
2330   if (Num >= NextNum) {
2331     addToLeaderTable(Num, I, I->getParent());
2332     return false;
2333   }
2334
2335   // Perform fast-path value-number based elimination of values inherited from
2336   // dominators.
2337   Value *repl = findLeader(I->getParent(), Num);
2338   if (repl == 0) {
2339     // Failure, just remember this instance for future use.
2340     addToLeaderTable(Num, I, I->getParent());
2341     return false;
2342   }
2343
2344   if (normalOpAfterIntrinsic(I, repl)) {
2345     // An intrinsic followed by a normal operation (e.g. sadd_with_overflow
2346     // followed by a sadd): replace the second instruction with an extract.
2347     IntrinsicInst *II = cast<IntrinsicInst>(repl);
2348     assert(II);
2349     repl = ExtractValueInst::Create(II, 0, I->getName() + ".repl", I);
2350   } else if (intrinsicAterNormalOp(I, repl)) {
2351     // A normal operation followed by an intrinsic (e.g. sadd followed by a
2352     // sadd_with_overflow).
2353     // Clone the intrinsic, and insert it before the replacing instruction. Then
2354     // replace the (current) instruction with the cloned one. In a subsequent
2355     // run, the original replacement (the non-intrinsic) will be be replaced by
2356     // the new intrinsic.
2357     Instruction *RI = dyn_cast<Instruction>(repl);
2358     assert(RI);
2359     Instruction *newIntrinsic = I->clone();
2360     newIntrinsic->setName(I->getName() + ".repl");
2361     newIntrinsic->insertBefore(RI);
2362     repl = newIntrinsic;
2363   }
2364
2365   // Remove it!
2366   patchAndReplaceAllUsesWith(I, repl);
2367   if (MD && repl->getType()->getScalarType()->isPointerTy())
2368     MD->invalidateCachedPointerInfo(repl);
2369   markInstructionForDeletion(I);
2370   return true;
2371 }
2372
2373 /// runOnFunction - This is the main transformation entry point for a function.
2374 bool GVN::runOnFunction(Function& F) {
2375   if (skipOptnoneFunction(F))
2376     return false;
2377
2378   if (!NoLoads)
2379     MD = &getAnalysis<MemoryDependenceAnalysis>();
2380   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2381   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
2382   DL = DLP ? &DLP->getDataLayout() : 0;
2383   TLI = &getAnalysis<TargetLibraryInfo>();
2384   VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
2385   VN.setMemDep(MD);
2386   VN.setDomTree(DT);
2387
2388   bool Changed = false;
2389   bool ShouldContinue = true;
2390
2391   // Merge unconditional branches, allowing PRE to catch more
2392   // optimization opportunities.
2393   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) {
2394     BasicBlock *BB = FI++;
2395
2396     bool removedBlock = MergeBlockIntoPredecessor(BB, this);
2397     if (removedBlock) ++NumGVNBlocks;
2398
2399     Changed |= removedBlock;
2400   }
2401
2402   unsigned Iteration = 0;
2403   while (ShouldContinue) {
2404     DEBUG(dbgs() << "GVN iteration: " << Iteration << "\n");
2405     ShouldContinue = iterateOnFunction(F);
2406     Changed |= ShouldContinue;
2407     ++Iteration;
2408   }
2409
2410   if (EnablePRE) {
2411     // Fabricate val-num for dead-code in order to suppress assertion in
2412     // performPRE().
2413     assignValNumForDeadCode();
2414     bool PREChanged = true;
2415     while (PREChanged) {
2416       PREChanged = performPRE(F);
2417       Changed |= PREChanged;
2418     }
2419   }
2420
2421   // FIXME: Should perform GVN again after PRE does something.  PRE can move
2422   // computations into blocks where they become fully redundant.  Note that
2423   // we can't do this until PRE's critical edge splitting updates memdep.
2424   // Actually, when this happens, we should just fully integrate PRE into GVN.
2425
2426   cleanupGlobalSets();
2427   // Do not cleanup DeadBlocks in cleanupGlobalSets() as it's called for each
2428   // iteration. 
2429   DeadBlocks.clear();
2430
2431   return Changed;
2432 }
2433
2434
2435 bool GVN::processBlock(BasicBlock *BB) {
2436   // FIXME: Kill off InstrsToErase by doing erasing eagerly in a helper function
2437   // (and incrementing BI before processing an instruction).
2438   assert(InstrsToErase.empty() &&
2439          "We expect InstrsToErase to be empty across iterations");
2440   if (DeadBlocks.count(BB))
2441     return false;
2442
2443   bool ChangedFunction = false;
2444
2445   for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
2446        BI != BE;) {
2447     ChangedFunction |= processInstruction(BI);
2448     if (InstrsToErase.empty()) {
2449       ++BI;
2450       continue;
2451     }
2452
2453     // If we need some instructions deleted, do it now.
2454     NumGVNInstr += InstrsToErase.size();
2455
2456     // Avoid iterator invalidation.
2457     bool AtStart = BI == BB->begin();
2458     if (!AtStart)
2459       --BI;
2460
2461     for (SmallVectorImpl<Instruction *>::iterator I = InstrsToErase.begin(),
2462          E = InstrsToErase.end(); I != E; ++I) {
2463       DEBUG(dbgs() << "GVN removed: " << **I << '\n');
2464       if (MD) MD->removeInstruction(*I);
2465       DEBUG(verifyRemoved(*I));
2466       (*I)->eraseFromParent();
2467     }
2468     InstrsToErase.clear();
2469
2470     if (AtStart)
2471       BI = BB->begin();
2472     else
2473       ++BI;
2474   }
2475
2476   return ChangedFunction;
2477 }
2478
2479 /// performPRE - Perform a purely local form of PRE that looks for diamond
2480 /// control flow patterns and attempts to perform simple PRE at the join point.
2481 bool GVN::performPRE(Function &F) {
2482   bool Changed = false;
2483   SmallVector<std::pair<Value*, BasicBlock*>, 8> predMap;
2484   for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
2485        DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
2486     BasicBlock *CurrentBlock = *DI;
2487
2488     // Nothing to PRE in the entry block.
2489     if (CurrentBlock == &F.getEntryBlock()) continue;
2490
2491     // Don't perform PRE on a landing pad.
2492     if (CurrentBlock->isLandingPad()) continue;
2493
2494     for (BasicBlock::iterator BI = CurrentBlock->begin(),
2495          BE = CurrentBlock->end(); BI != BE; ) {
2496       Instruction *CurInst = BI++;
2497
2498       if (isa<AllocaInst>(CurInst) ||
2499           isa<TerminatorInst>(CurInst) || isa<PHINode>(CurInst) ||
2500           CurInst->getType()->isVoidTy() ||
2501           CurInst->mayReadFromMemory() || CurInst->mayHaveSideEffects() ||
2502           isa<DbgInfoIntrinsic>(CurInst))
2503         continue;
2504
2505       // Don't do PRE on compares. The PHI would prevent CodeGenPrepare from
2506       // sinking the compare again, and it would force the code generator to
2507       // move the i1 from processor flags or predicate registers into a general
2508       // purpose register.
2509       if (isa<CmpInst>(CurInst))
2510         continue;
2511
2512       // We don't currently value number ANY inline asm calls.
2513       if (CallInst *CallI = dyn_cast<CallInst>(CurInst))
2514         if (CallI->isInlineAsm())
2515           continue;
2516
2517       uint32_t ValNo = VN.lookup(CurInst);
2518
2519       // Look for the predecessors for PRE opportunities.  We're
2520       // only trying to solve the basic diamond case, where
2521       // a value is computed in the successor and one predecessor,
2522       // but not the other.  We also explicitly disallow cases
2523       // where the successor is its own predecessor, because they're
2524       // more complicated to get right.
2525       unsigned NumWith = 0;
2526       unsigned NumWithout = 0;
2527       BasicBlock *PREPred = 0;
2528       predMap.clear();
2529
2530       for (pred_iterator PI = pred_begin(CurrentBlock),
2531            PE = pred_end(CurrentBlock); PI != PE; ++PI) {
2532         BasicBlock *P = *PI;
2533         // We're not interested in PRE where the block is its
2534         // own predecessor, or in blocks with predecessors
2535         // that are not reachable.
2536         if (P == CurrentBlock) {
2537           NumWithout = 2;
2538           break;
2539         } else if (!DT->isReachableFromEntry(P))  {
2540           NumWithout = 2;
2541           break;
2542         }
2543
2544         Value* predV = findLeader(P, ValNo);
2545         if (predV == 0) {
2546           predMap.push_back(std::make_pair(static_cast<Value *>(0), P));
2547           PREPred = P;
2548           ++NumWithout;
2549         } else if (predV == CurInst) {
2550           /* CurInst dominates this predecessor. */
2551           NumWithout = 2;
2552           break;
2553         } else {
2554           predMap.push_back(std::make_pair(predV, P));
2555           ++NumWith;
2556         }
2557       }
2558
2559       // Don't do PRE when it might increase code size, i.e. when
2560       // we would need to insert instructions in more than one pred.
2561       if (NumWithout != 1 || NumWith == 0)
2562         continue;
2563
2564       // Don't do PRE across indirect branch.
2565       if (isa<IndirectBrInst>(PREPred->getTerminator()))
2566         continue;
2567
2568       // We can't do PRE safely on a critical edge, so instead we schedule
2569       // the edge to be split and perform the PRE the next time we iterate
2570       // on the function.
2571       unsigned SuccNum = GetSuccessorNumber(PREPred, CurrentBlock);
2572       if (isCriticalEdge(PREPred->getTerminator(), SuccNum)) {
2573         toSplit.push_back(std::make_pair(PREPred->getTerminator(), SuccNum));
2574         continue;
2575       }
2576
2577       // Instantiate the expression in the predecessor that lacked it.
2578       // Because we are going top-down through the block, all value numbers
2579       // will be available in the predecessor by the time we need them.  Any
2580       // that weren't originally present will have been instantiated earlier
2581       // in this loop.
2582       Instruction *PREInstr = CurInst->clone();
2583       bool success = true;
2584       for (unsigned i = 0, e = CurInst->getNumOperands(); i != e; ++i) {
2585         Value *Op = PREInstr->getOperand(i);
2586         if (isa<Argument>(Op) || isa<Constant>(Op) || isa<GlobalValue>(Op))
2587           continue;
2588
2589         if (Value *V = findLeader(PREPred, VN.lookup(Op))) {
2590           PREInstr->setOperand(i, V);
2591         } else {
2592           success = false;
2593           break;
2594         }
2595       }
2596
2597       // Fail out if we encounter an operand that is not available in
2598       // the PRE predecessor.  This is typically because of loads which
2599       // are not value numbered precisely.
2600       if (!success) {
2601         DEBUG(verifyRemoved(PREInstr));
2602         delete PREInstr;
2603         continue;
2604       }
2605
2606       PREInstr->insertBefore(PREPred->getTerminator());
2607       PREInstr->setName(CurInst->getName() + ".pre");
2608       PREInstr->setDebugLoc(CurInst->getDebugLoc());
2609       VN.add(PREInstr, ValNo);
2610       ++NumGVNPRE;
2611
2612       // Update the availability map to include the new instruction.
2613       addToLeaderTable(ValNo, PREInstr, PREPred);
2614
2615       // Create a PHI to make the value available in this block.
2616       PHINode* Phi = PHINode::Create(CurInst->getType(), predMap.size(),
2617                                      CurInst->getName() + ".pre-phi",
2618                                      CurrentBlock->begin());
2619       for (unsigned i = 0, e = predMap.size(); i != e; ++i) {
2620         if (Value *V = predMap[i].first)
2621           Phi->addIncoming(V, predMap[i].second);
2622         else
2623           Phi->addIncoming(PREInstr, PREPred);
2624       }
2625
2626       VN.add(Phi, ValNo);
2627       addToLeaderTable(ValNo, Phi, CurrentBlock);
2628       Phi->setDebugLoc(CurInst->getDebugLoc());
2629       CurInst->replaceAllUsesWith(Phi);
2630       if (Phi->getType()->getScalarType()->isPointerTy()) {
2631         // Because we have added a PHI-use of the pointer value, it has now
2632         // "escaped" from alias analysis' perspective.  We need to inform
2633         // AA of this.
2634         for (unsigned ii = 0, ee = Phi->getNumIncomingValues(); ii != ee;
2635              ++ii) {
2636           unsigned jj = PHINode::getOperandNumForIncomingValue(ii);
2637           VN.getAliasAnalysis()->addEscapingUse(Phi->getOperandUse(jj));
2638         }
2639
2640         if (MD)
2641           MD->invalidateCachedPointerInfo(Phi);
2642       }
2643       VN.erase(CurInst);
2644       removeFromLeaderTable(ValNo, CurInst, CurrentBlock);
2645
2646       DEBUG(dbgs() << "GVN PRE removed: " << *CurInst << '\n');
2647       if (MD) MD->removeInstruction(CurInst);
2648       DEBUG(verifyRemoved(CurInst));
2649       CurInst->eraseFromParent();
2650       Changed = true;
2651     }
2652   }
2653
2654   if (splitCriticalEdges())
2655     Changed = true;
2656
2657   return Changed;
2658 }
2659
2660 /// Split the critical edge connecting the given two blocks, and return
2661 /// the block inserted to the critical edge.
2662 BasicBlock *GVN::splitCriticalEdges(BasicBlock *Pred, BasicBlock *Succ) {
2663   BasicBlock *BB = SplitCriticalEdge(Pred, Succ, this);
2664   if (MD)
2665     MD->invalidateCachedPredecessors();
2666   return BB;
2667 }
2668
2669 /// splitCriticalEdges - Split critical edges found during the previous
2670 /// iteration that may enable further optimization.
2671 bool GVN::splitCriticalEdges() {
2672   if (toSplit.empty())
2673     return false;
2674   do {
2675     std::pair<TerminatorInst*, unsigned> Edge = toSplit.pop_back_val();
2676     SplitCriticalEdge(Edge.first, Edge.second, this);
2677   } while (!toSplit.empty());
2678   if (MD) MD->invalidateCachedPredecessors();
2679   return true;
2680 }
2681
2682 /// iterateOnFunction - Executes one iteration of GVN
2683 bool GVN::iterateOnFunction(Function &F) {
2684   cleanupGlobalSets();
2685
2686   // Top-down walk of the dominator tree
2687   bool Changed = false;
2688 #if 0
2689   // Needed for value numbering with phi construction to work.
2690   ReversePostOrderTraversal<Function*> RPOT(&F);
2691   for (ReversePostOrderTraversal<Function*>::rpo_iterator RI = RPOT.begin(),
2692        RE = RPOT.end(); RI != RE; ++RI)
2693     Changed |= processBlock(*RI);
2694 #else
2695   // Save the blocks this function have before transformation begins. GVN may
2696   // split critical edge, and hence may invalidate the RPO/DT iterator.
2697   //
2698   std::vector<BasicBlock *> BBVect;
2699   BBVect.reserve(256);
2700   for (df_iterator<DomTreeNode*> DI = df_begin(DT->getRootNode()),
2701        DE = df_end(DT->getRootNode()); DI != DE; ++DI)
2702     BBVect.push_back(DI->getBlock());
2703
2704   for (std::vector<BasicBlock *>::iterator I = BBVect.begin(), E = BBVect.end();
2705        I != E; I++)
2706     Changed |= processBlock(*I);
2707 #endif
2708
2709   return Changed;
2710 }
2711
2712 void GVN::cleanupGlobalSets() {
2713   VN.clear();
2714   LeaderTable.clear();
2715   TableAllocator.Reset();
2716 }
2717
2718 /// verifyRemoved - Verify that the specified instruction does not occur in our
2719 /// internal data structures.
2720 void GVN::verifyRemoved(const Instruction *Inst) const {
2721   VN.verifyRemoved(Inst);
2722
2723   // Walk through the value number scope to make sure the instruction isn't
2724   // ferreted away in it.
2725   for (DenseMap<uint32_t, LeaderTableEntry>::const_iterator
2726        I = LeaderTable.begin(), E = LeaderTable.end(); I != E; ++I) {
2727     const LeaderTableEntry *Node = &I->second;
2728     assert(Node->Val != Inst && "Inst still in value numbering scope!");
2729
2730     while (Node->Next) {
2731       Node = Node->Next;
2732       assert(Node->Val != Inst && "Inst still in value numbering scope!");
2733     }
2734   }
2735 }
2736
2737 // BB is declared dead, which implied other blocks become dead as well. This
2738 // function is to add all these blocks to "DeadBlocks". For the dead blocks'
2739 // live successors, update their phi nodes by replacing the operands
2740 // corresponding to dead blocks with UndefVal.
2741 //
2742 void GVN::addDeadBlock(BasicBlock *BB) {
2743   SmallVector<BasicBlock *, 4> NewDead;
2744   SmallSetVector<BasicBlock *, 4> DF;
2745
2746   NewDead.push_back(BB);
2747   while (!NewDead.empty()) {
2748     BasicBlock *D = NewDead.pop_back_val();
2749     if (DeadBlocks.count(D))
2750       continue;
2751
2752     // All blocks dominated by D are dead.
2753     SmallVector<BasicBlock *, 8> Dom;
2754     DT->getDescendants(D, Dom);
2755     DeadBlocks.insert(Dom.begin(), Dom.end());
2756     
2757     // Figure out the dominance-frontier(D).
2758     for (SmallVectorImpl<BasicBlock *>::iterator I = Dom.begin(),
2759            E = Dom.end(); I != E; I++) {
2760       BasicBlock *B = *I;
2761       for (succ_iterator SI = succ_begin(B), SE = succ_end(B); SI != SE; SI++) {
2762         BasicBlock *S = *SI;
2763         if (DeadBlocks.count(S))
2764           continue;
2765
2766         bool AllPredDead = true;
2767         for (pred_iterator PI = pred_begin(S), PE = pred_end(S); PI != PE; PI++)
2768           if (!DeadBlocks.count(*PI)) {
2769             AllPredDead = false;
2770             break;
2771           }
2772
2773         if (!AllPredDead) {
2774           // S could be proved dead later on. That is why we don't update phi
2775           // operands at this moment.
2776           DF.insert(S);
2777         } else {
2778           // While S is not dominated by D, it is dead by now. This could take
2779           // place if S already have a dead predecessor before D is declared
2780           // dead.
2781           NewDead.push_back(S);
2782         }
2783       }
2784     }
2785   }
2786
2787   // For the dead blocks' live successors, update their phi nodes by replacing
2788   // the operands corresponding to dead blocks with UndefVal.
2789   for(SmallSetVector<BasicBlock *, 4>::iterator I = DF.begin(), E = DF.end();
2790         I != E; I++) {
2791     BasicBlock *B = *I;
2792     if (DeadBlocks.count(B))
2793       continue;
2794
2795     SmallVector<BasicBlock *, 4> Preds(pred_begin(B), pred_end(B));
2796     for (SmallVectorImpl<BasicBlock *>::iterator PI = Preds.begin(),
2797            PE = Preds.end(); PI != PE; PI++) {
2798       BasicBlock *P = *PI;
2799
2800       if (!DeadBlocks.count(P))
2801         continue;
2802
2803       if (isCriticalEdge(P->getTerminator(), GetSuccessorNumber(P, B))) {
2804         if (BasicBlock *S = splitCriticalEdges(P, B))
2805           DeadBlocks.insert(P = S);
2806       }
2807
2808       for (BasicBlock::iterator II = B->begin(); isa<PHINode>(II); ++II) {
2809         PHINode &Phi = cast<PHINode>(*II);
2810         Phi.setIncomingValue(Phi.getBasicBlockIndex(P),
2811                              UndefValue::get(Phi.getType()));
2812       }
2813     }
2814   }
2815 }
2816
2817 // If the given branch is recognized as a foldable branch (i.e. conditional
2818 // branch with constant condition), it will perform following analyses and
2819 // transformation.
2820 //  1) If the dead out-coming edge is a critical-edge, split it. Let 
2821 //     R be the target of the dead out-coming edge.
2822 //  1) Identify the set of dead blocks implied by the branch's dead outcoming
2823 //     edge. The result of this step will be {X| X is dominated by R}
2824 //  2) Identify those blocks which haves at least one dead prodecessor. The
2825 //     result of this step will be dominance-frontier(R).
2826 //  3) Update the PHIs in DF(R) by replacing the operands corresponding to 
2827 //     dead blocks with "UndefVal" in an hope these PHIs will optimized away.
2828 //
2829 // Return true iff *NEW* dead code are found.
2830 bool GVN::processFoldableCondBr(BranchInst *BI) {
2831   if (!BI || BI->isUnconditional())
2832     return false;
2833
2834   ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
2835   if (!Cond)
2836     return false;
2837
2838   BasicBlock *DeadRoot = Cond->getZExtValue() ? 
2839                          BI->getSuccessor(1) : BI->getSuccessor(0);
2840   if (DeadBlocks.count(DeadRoot))
2841     return false;
2842
2843   if (!DeadRoot->getSinglePredecessor())
2844     DeadRoot = splitCriticalEdges(BI->getParent(), DeadRoot);
2845
2846   addDeadBlock(DeadRoot);
2847   return true;
2848 }
2849
2850 // performPRE() will trigger assert if it come across an instruciton without
2851 // associated val-num. As it normally has far more live instructions than dead
2852 // instructions, it makes more sense just to "fabricate" a val-number for the
2853 // dead code than checking if instruction involved is dead or not.
2854 void GVN::assignValNumForDeadCode() {
2855   for (SetVector<BasicBlock *>::iterator I = DeadBlocks.begin(),
2856         E = DeadBlocks.end(); I != E; I++) {
2857     BasicBlock *BB = *I;
2858     for (BasicBlock::iterator II = BB->begin(), EE = BB->end();
2859           II != EE; II++) {
2860       Instruction *Inst = &*II;
2861       unsigned ValNum = VN.lookup_or_add(Inst);
2862       addToLeaderTable(ValNum, Inst, BB);
2863     }
2864   }
2865 }