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