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