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