GVN.cpp revision 6c4d8e3ee444408eed715308ade4e0b674715cfb
1//===- GVN.cpp - Eliminate redundant values and loads ------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass performs global value numbering to eliminate fully redundant
11// instructions.  It also performs simple dead load elimination.
12//
13// Note that this pass does the value numbering itself, it does not use the
14// ValueNumbering analysis passes.
15//
16//===----------------------------------------------------------------------===//
17
18#define DEBUG_TYPE "gvn"
19#include "llvm/Transforms/Scalar.h"
20#include "llvm/BasicBlock.h"
21#include "llvm/Constants.h"
22#include "llvm/DerivedTypes.h"
23#include "llvm/Function.h"
24#include "llvm/Instructions.h"
25#include "llvm/Value.h"
26#include "llvm/ADT/DenseMap.h"
27#include "llvm/ADT/DepthFirstIterator.h"
28#include "llvm/ADT/SmallPtrSet.h"
29#include "llvm/ADT/SmallVector.h"
30#include "llvm/ADT/Statistic.h"
31#include "llvm/Analysis/Dominators.h"
32#include "llvm/Analysis/AliasAnalysis.h"
33#include "llvm/Analysis/MemoryDependenceAnalysis.h"
34#include "llvm/Support/CFG.h"
35#include "llvm/Support/CommandLine.h"
36#include "llvm/Support/Compiler.h"
37#include "llvm/Support/Debug.h"
38#include "llvm/Transforms/Utils/BasicBlockUtils.h"
39using namespace llvm;
40
41STATISTIC(NumGVNInstr, "Number of instructions deleted");
42STATISTIC(NumGVNLoad, "Number of loads deleted");
43STATISTIC(NumGVNPRE, "Number of instructions PRE'd");
44STATISTIC(NumGVNBlocks, "Number of blocks merged");
45
46static cl::opt<bool> EnablePRE("enable-pre",
47                               cl::init(true), cl::Hidden);
48
49//===----------------------------------------------------------------------===//
50//                         ValueTable Class
51//===----------------------------------------------------------------------===//
52
53/// This class holds the mapping between values and value numbers.  It is used
54/// as an efficient mechanism to determine the expression-wise equivalence of
55/// two values.
56namespace {
57  struct VISIBILITY_HIDDEN Expression {
58    enum ExpressionOpcode { ADD, SUB, MUL, UDIV, SDIV, FDIV, UREM, SREM,
59                            FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ,
60                            ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE,
61                            ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ,
62                            FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE,
63                            FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE,
64                            FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
65                            SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
66                            FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT,
67                            PTRTOINT, INTTOPTR, BITCAST, GEP, CALL, CONSTANT,
68                            EMPTY, TOMBSTONE };
69
70    ExpressionOpcode opcode;
71    const Type* type;
72    uint32_t firstVN;
73    uint32_t secondVN;
74    uint32_t thirdVN;
75    SmallVector<uint32_t, 4> varargs;
76    Value* function;
77
78    Expression() { }
79    Expression(ExpressionOpcode o) : opcode(o) { }
80
81    bool operator==(const Expression &other) const {
82      if (opcode != other.opcode)
83        return false;
84      else if (opcode == EMPTY || opcode == TOMBSTONE)
85        return true;
86      else if (type != other.type)
87        return false;
88      else if (function != other.function)
89        return false;
90      else if (firstVN != other.firstVN)
91        return false;
92      else if (secondVN != other.secondVN)
93        return false;
94      else if (thirdVN != other.thirdVN)
95        return false;
96      else {
97        if (varargs.size() != other.varargs.size())
98          return false;
99
100        for (size_t i = 0; i < varargs.size(); ++i)
101          if (varargs[i] != other.varargs[i])
102            return false;
103
104        return true;
105      }
106    }
107
108    bool operator!=(const Expression &other) const {
109      if (opcode != other.opcode)
110        return true;
111      else if (opcode == EMPTY || opcode == TOMBSTONE)
112        return false;
113      else if (type != other.type)
114        return true;
115      else if (function != other.function)
116        return true;
117      else if (firstVN != other.firstVN)
118        return true;
119      else if (secondVN != other.secondVN)
120        return true;
121      else if (thirdVN != other.thirdVN)
122        return true;
123      else {
124        if (varargs.size() != other.varargs.size())
125          return true;
126
127        for (size_t i = 0; i < varargs.size(); ++i)
128          if (varargs[i] != other.varargs[i])
129            return true;
130
131          return false;
132      }
133    }
134  };
135
136  class VISIBILITY_HIDDEN ValueTable {
137    private:
138      DenseMap<Value*, uint32_t> valueNumbering;
139      DenseMap<Expression, uint32_t> expressionNumbering;
140      AliasAnalysis* AA;
141      MemoryDependenceAnalysis* MD;
142      DominatorTree* DT;
143
144      uint32_t nextValueNumber;
145
146      Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
147      Expression::ExpressionOpcode getOpcode(CmpInst* C);
148      Expression::ExpressionOpcode getOpcode(CastInst* C);
149      Expression create_expression(BinaryOperator* BO);
150      Expression create_expression(CmpInst* C);
151      Expression create_expression(ShuffleVectorInst* V);
152      Expression create_expression(ExtractElementInst* C);
153      Expression create_expression(InsertElementInst* V);
154      Expression create_expression(SelectInst* V);
155      Expression create_expression(CastInst* C);
156      Expression create_expression(GetElementPtrInst* G);
157      Expression create_expression(CallInst* C);
158      Expression create_expression(Constant* C);
159    public:
160      ValueTable() : nextValueNumber(1) { }
161      uint32_t lookup_or_add(Value* V);
162      uint32_t lookup(Value* V) const;
163      void add(Value* V, uint32_t num);
164      void clear();
165      void erase(Value* v);
166      unsigned size();
167      void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
168      void setMemDep(MemoryDependenceAnalysis* M) { MD = M; }
169      void setDomTree(DominatorTree* D) { DT = D; }
170      uint32_t getNextUnusedValueNumber() { return nextValueNumber; }
171  };
172}
173
174namespace llvm {
175template <> struct DenseMapInfo<Expression> {
176  static inline Expression getEmptyKey() {
177    return Expression(Expression::EMPTY);
178  }
179
180  static inline Expression getTombstoneKey() {
181    return Expression(Expression::TOMBSTONE);
182  }
183
184  static unsigned getHashValue(const Expression e) {
185    unsigned hash = e.opcode;
186
187    hash = e.firstVN + hash * 37;
188    hash = e.secondVN + hash * 37;
189    hash = e.thirdVN + hash * 37;
190
191    hash = ((unsigned)((uintptr_t)e.type >> 4) ^
192            (unsigned)((uintptr_t)e.type >> 9)) +
193           hash * 37;
194
195    for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
196         E = e.varargs.end(); I != E; ++I)
197      hash = *I + hash * 37;
198
199    hash = ((unsigned)((uintptr_t)e.function >> 4) ^
200            (unsigned)((uintptr_t)e.function >> 9)) +
201           hash * 37;
202
203    return hash;
204  }
205  static bool isEqual(const Expression &LHS, const Expression &RHS) {
206    return LHS == RHS;
207  }
208  static bool isPod() { return true; }
209};
210}
211
212//===----------------------------------------------------------------------===//
213//                     ValueTable Internal Functions
214//===----------------------------------------------------------------------===//
215Expression::ExpressionOpcode ValueTable::getOpcode(BinaryOperator* BO) {
216  switch(BO->getOpcode()) {
217  default: // THIS SHOULD NEVER HAPPEN
218    assert(0 && "Binary operator with unknown opcode?");
219  case Instruction::Add:  return Expression::ADD;
220  case Instruction::Sub:  return Expression::SUB;
221  case Instruction::Mul:  return Expression::MUL;
222  case Instruction::UDiv: return Expression::UDIV;
223  case Instruction::SDiv: return Expression::SDIV;
224  case Instruction::FDiv: return Expression::FDIV;
225  case Instruction::URem: return Expression::UREM;
226  case Instruction::SRem: return Expression::SREM;
227  case Instruction::FRem: return Expression::FREM;
228  case Instruction::Shl:  return Expression::SHL;
229  case Instruction::LShr: return Expression::LSHR;
230  case Instruction::AShr: return Expression::ASHR;
231  case Instruction::And:  return Expression::AND;
232  case Instruction::Or:   return Expression::OR;
233  case Instruction::Xor:  return Expression::XOR;
234  }
235}
236
237Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
238  if (isa<ICmpInst>(C) || isa<VICmpInst>(C)) {
239    switch (C->getPredicate()) {
240    default:  // THIS SHOULD NEVER HAPPEN
241      assert(0 && "Comparison with unknown predicate?");
242    case ICmpInst::ICMP_EQ:  return Expression::ICMPEQ;
243    case ICmpInst::ICMP_NE:  return Expression::ICMPNE;
244    case ICmpInst::ICMP_UGT: return Expression::ICMPUGT;
245    case ICmpInst::ICMP_UGE: return Expression::ICMPUGE;
246    case ICmpInst::ICMP_ULT: return Expression::ICMPULT;
247    case ICmpInst::ICMP_ULE: return Expression::ICMPULE;
248    case ICmpInst::ICMP_SGT: return Expression::ICMPSGT;
249    case ICmpInst::ICMP_SGE: return Expression::ICMPSGE;
250    case ICmpInst::ICMP_SLT: return Expression::ICMPSLT;
251    case ICmpInst::ICMP_SLE: return Expression::ICMPSLE;
252    }
253  }
254  assert((isa<FCmpInst>(C) || isa<VFCmpInst>(C)) && "Unknown compare");
255  switch (C->getPredicate()) {
256  default: // THIS SHOULD NEVER HAPPEN
257    assert(0 && "Comparison with unknown predicate?");
258  case FCmpInst::FCMP_OEQ: return Expression::FCMPOEQ;
259  case FCmpInst::FCMP_OGT: return Expression::FCMPOGT;
260  case FCmpInst::FCMP_OGE: return Expression::FCMPOGE;
261  case FCmpInst::FCMP_OLT: return Expression::FCMPOLT;
262  case FCmpInst::FCMP_OLE: return Expression::FCMPOLE;
263  case FCmpInst::FCMP_ONE: return Expression::FCMPONE;
264  case FCmpInst::FCMP_ORD: return Expression::FCMPORD;
265  case FCmpInst::FCMP_UNO: return Expression::FCMPUNO;
266  case FCmpInst::FCMP_UEQ: return Expression::FCMPUEQ;
267  case FCmpInst::FCMP_UGT: return Expression::FCMPUGT;
268  case FCmpInst::FCMP_UGE: return Expression::FCMPUGE;
269  case FCmpInst::FCMP_ULT: return Expression::FCMPULT;
270  case FCmpInst::FCMP_ULE: return Expression::FCMPULE;
271  case FCmpInst::FCMP_UNE: return Expression::FCMPUNE;
272  }
273}
274
275Expression::ExpressionOpcode ValueTable::getOpcode(CastInst* C) {
276  switch(C->getOpcode()) {
277  default: // THIS SHOULD NEVER HAPPEN
278    assert(0 && "Cast operator with unknown opcode?");
279  case Instruction::Trunc:    return Expression::TRUNC;
280  case Instruction::ZExt:     return Expression::ZEXT;
281  case Instruction::SExt:     return Expression::SEXT;
282  case Instruction::FPToUI:   return Expression::FPTOUI;
283  case Instruction::FPToSI:   return Expression::FPTOSI;
284  case Instruction::UIToFP:   return Expression::UITOFP;
285  case Instruction::SIToFP:   return Expression::SITOFP;
286  case Instruction::FPTrunc:  return Expression::FPTRUNC;
287  case Instruction::FPExt:    return Expression::FPEXT;
288  case Instruction::PtrToInt: return Expression::PTRTOINT;
289  case Instruction::IntToPtr: return Expression::INTTOPTR;
290  case Instruction::BitCast:  return Expression::BITCAST;
291  }
292}
293
294Expression ValueTable::create_expression(CallInst* C) {
295  Expression e;
296
297  e.type = C->getType();
298  e.firstVN = 0;
299  e.secondVN = 0;
300  e.thirdVN = 0;
301  e.function = C->getCalledFunction();
302  e.opcode = Expression::CALL;
303
304  for (CallInst::op_iterator I = C->op_begin()+1, E = C->op_end();
305       I != E; ++I)
306    e.varargs.push_back(lookup_or_add(*I));
307
308  return e;
309}
310
311Expression ValueTable::create_expression(BinaryOperator* BO) {
312  Expression e;
313
314  e.firstVN = lookup_or_add(BO->getOperand(0));
315  e.secondVN = lookup_or_add(BO->getOperand(1));
316  e.thirdVN = 0;
317  e.function = 0;
318  e.type = BO->getType();
319  e.opcode = getOpcode(BO);
320
321  return e;
322}
323
324Expression ValueTable::create_expression(CmpInst* C) {
325  Expression e;
326
327  e.firstVN = lookup_or_add(C->getOperand(0));
328  e.secondVN = lookup_or_add(C->getOperand(1));
329  e.thirdVN = 0;
330  e.function = 0;
331  e.type = C->getType();
332  e.opcode = getOpcode(C);
333
334  return e;
335}
336
337Expression ValueTable::create_expression(CastInst* C) {
338  Expression e;
339
340  e.firstVN = lookup_or_add(C->getOperand(0));
341  e.secondVN = 0;
342  e.thirdVN = 0;
343  e.function = 0;
344  e.type = C->getType();
345  e.opcode = getOpcode(C);
346
347  return e;
348}
349
350Expression ValueTable::create_expression(ShuffleVectorInst* S) {
351  Expression e;
352
353  e.firstVN = lookup_or_add(S->getOperand(0));
354  e.secondVN = lookup_or_add(S->getOperand(1));
355  e.thirdVN = lookup_or_add(S->getOperand(2));
356  e.function = 0;
357  e.type = S->getType();
358  e.opcode = Expression::SHUFFLE;
359
360  return e;
361}
362
363Expression ValueTable::create_expression(ExtractElementInst* E) {
364  Expression e;
365
366  e.firstVN = lookup_or_add(E->getOperand(0));
367  e.secondVN = lookup_or_add(E->getOperand(1));
368  e.thirdVN = 0;
369  e.function = 0;
370  e.type = E->getType();
371  e.opcode = Expression::EXTRACT;
372
373  return e;
374}
375
376Expression ValueTable::create_expression(InsertElementInst* I) {
377  Expression e;
378
379  e.firstVN = lookup_or_add(I->getOperand(0));
380  e.secondVN = lookup_or_add(I->getOperand(1));
381  e.thirdVN = lookup_or_add(I->getOperand(2));
382  e.function = 0;
383  e.type = I->getType();
384  e.opcode = Expression::INSERT;
385
386  return e;
387}
388
389Expression ValueTable::create_expression(SelectInst* I) {
390  Expression e;
391
392  e.firstVN = lookup_or_add(I->getCondition());
393  e.secondVN = lookup_or_add(I->getTrueValue());
394  e.thirdVN = lookup_or_add(I->getFalseValue());
395  e.function = 0;
396  e.type = I->getType();
397  e.opcode = Expression::SELECT;
398
399  return e;
400}
401
402Expression ValueTable::create_expression(GetElementPtrInst* G) {
403  Expression e;
404
405  e.firstVN = lookup_or_add(G->getPointerOperand());
406  e.secondVN = 0;
407  e.thirdVN = 0;
408  e.function = 0;
409  e.type = G->getType();
410  e.opcode = Expression::GEP;
411
412  for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
413       I != E; ++I)
414    e.varargs.push_back(lookup_or_add(*I));
415
416  return e;
417}
418
419//===----------------------------------------------------------------------===//
420//                     ValueTable External Functions
421//===----------------------------------------------------------------------===//
422
423/// add - Insert a value into the table with a specified value number.
424void ValueTable::add(Value* V, uint32_t num) {
425  valueNumbering.insert(std::make_pair(V, num));
426}
427
428/// lookup_or_add - Returns the value number for the specified value, assigning
429/// it a new number if it did not have one before.
430uint32_t ValueTable::lookup_or_add(Value* V) {
431  DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
432  if (VI != valueNumbering.end())
433    return VI->second;
434
435  if (CallInst* C = dyn_cast<CallInst>(V)) {
436    if (AA->doesNotAccessMemory(C)) {
437      Expression e = create_expression(C);
438
439      DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
440      if (EI != expressionNumbering.end()) {
441        valueNumbering.insert(std::make_pair(V, EI->second));
442        return EI->second;
443      } else {
444        expressionNumbering.insert(std::make_pair(e, nextValueNumber));
445        valueNumbering.insert(std::make_pair(V, nextValueNumber));
446
447        return nextValueNumber++;
448      }
449    } else if (AA->onlyReadsMemory(C)) {
450      Expression e = create_expression(C);
451
452      if (expressionNumbering.find(e) == expressionNumbering.end()) {
453        expressionNumbering.insert(std::make_pair(e, nextValueNumber));
454        valueNumbering.insert(std::make_pair(V, nextValueNumber));
455        return nextValueNumber++;
456      }
457
458      Instruction* local_dep = MD->getDependency(C);
459
460      if (local_dep == MemoryDependenceAnalysis::None) {
461        valueNumbering.insert(std::make_pair(V, nextValueNumber));
462        return nextValueNumber++;
463      } else if (local_dep != MemoryDependenceAnalysis::NonLocal) {
464        if (!isa<CallInst>(local_dep)) {
465          valueNumbering.insert(std::make_pair(V, nextValueNumber));
466          return nextValueNumber++;
467        }
468
469        CallInst* local_cdep = cast<CallInst>(local_dep);
470
471        if (local_cdep->getCalledFunction() != C->getCalledFunction() ||
472            local_cdep->getNumOperands() != C->getNumOperands()) {
473          valueNumbering.insert(std::make_pair(V, nextValueNumber));
474          return nextValueNumber++;
475        } else if (!C->getCalledFunction()) {
476          valueNumbering.insert(std::make_pair(V, nextValueNumber));
477          return nextValueNumber++;
478        } else {
479          for (unsigned i = 1; i < C->getNumOperands(); ++i) {
480            uint32_t c_vn = lookup_or_add(C->getOperand(i));
481            uint32_t cd_vn = lookup_or_add(local_cdep->getOperand(i));
482            if (c_vn != cd_vn) {
483              valueNumbering.insert(std::make_pair(V, nextValueNumber));
484              return nextValueNumber++;
485            }
486          }
487
488          uint32_t v = lookup_or_add(local_cdep);
489          valueNumbering.insert(std::make_pair(V, v));
490          return v;
491        }
492      }
493
494
495      DenseMap<BasicBlock*, Value*> deps;
496      MD->getNonLocalDependency(C, deps);
497      CallInst* cdep = 0;
498
499      for (DenseMap<BasicBlock*, Value*>::iterator I = deps.begin(),
500           E = deps.end(); I != E; ++I) {
501        if (I->second == MemoryDependenceAnalysis::None) {
502          valueNumbering.insert(std::make_pair(V, nextValueNumber));
503
504          return nextValueNumber++;
505        } else if (I->second != MemoryDependenceAnalysis::NonLocal) {
506          if (DT->properlyDominates(I->first, C->getParent())) {
507            if (CallInst* CD = dyn_cast<CallInst>(I->second))
508              cdep = CD;
509            else {
510              valueNumbering.insert(std::make_pair(V, nextValueNumber));
511              return nextValueNumber++;
512            }
513          } else {
514            valueNumbering.insert(std::make_pair(V, nextValueNumber));
515            return nextValueNumber++;
516          }
517        }
518      }
519
520      if (!cdep) {
521        valueNumbering.insert(std::make_pair(V, nextValueNumber));
522        return nextValueNumber++;
523      }
524
525      if (cdep->getCalledFunction() != C->getCalledFunction() ||
526          cdep->getNumOperands() != C->getNumOperands()) {
527        valueNumbering.insert(std::make_pair(V, nextValueNumber));
528        return nextValueNumber++;
529      } else if (!C->getCalledFunction()) {
530        valueNumbering.insert(std::make_pair(V, nextValueNumber));
531        return nextValueNumber++;
532      } else {
533        for (unsigned i = 1; i < C->getNumOperands(); ++i) {
534          uint32_t c_vn = lookup_or_add(C->getOperand(i));
535          uint32_t cd_vn = lookup_or_add(cdep->getOperand(i));
536          if (c_vn != cd_vn) {
537            valueNumbering.insert(std::make_pair(V, nextValueNumber));
538            return nextValueNumber++;
539          }
540        }
541
542        uint32_t v = lookup_or_add(cdep);
543        valueNumbering.insert(std::make_pair(V, v));
544        return v;
545      }
546
547    } else {
548      valueNumbering.insert(std::make_pair(V, nextValueNumber));
549      return nextValueNumber++;
550    }
551  } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
552    Expression e = create_expression(BO);
553
554    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
555    if (EI != expressionNumbering.end()) {
556      valueNumbering.insert(std::make_pair(V, EI->second));
557      return EI->second;
558    } else {
559      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
560      valueNumbering.insert(std::make_pair(V, nextValueNumber));
561
562      return nextValueNumber++;
563    }
564  } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
565    Expression e = create_expression(C);
566
567    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
568    if (EI != expressionNumbering.end()) {
569      valueNumbering.insert(std::make_pair(V, EI->second));
570      return EI->second;
571    } else {
572      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
573      valueNumbering.insert(std::make_pair(V, nextValueNumber));
574
575      return nextValueNumber++;
576    }
577  } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
578    Expression e = create_expression(U);
579
580    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
581    if (EI != expressionNumbering.end()) {
582      valueNumbering.insert(std::make_pair(V, EI->second));
583      return EI->second;
584    } else {
585      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
586      valueNumbering.insert(std::make_pair(V, nextValueNumber));
587
588      return nextValueNumber++;
589    }
590  } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
591    Expression e = create_expression(U);
592
593    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
594    if (EI != expressionNumbering.end()) {
595      valueNumbering.insert(std::make_pair(V, EI->second));
596      return EI->second;
597    } else {
598      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
599      valueNumbering.insert(std::make_pair(V, nextValueNumber));
600
601      return nextValueNumber++;
602    }
603  } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
604    Expression e = create_expression(U);
605
606    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
607    if (EI != expressionNumbering.end()) {
608      valueNumbering.insert(std::make_pair(V, EI->second));
609      return EI->second;
610    } else {
611      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
612      valueNumbering.insert(std::make_pair(V, nextValueNumber));
613
614      return nextValueNumber++;
615    }
616  } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
617    Expression e = create_expression(U);
618
619    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
620    if (EI != expressionNumbering.end()) {
621      valueNumbering.insert(std::make_pair(V, EI->second));
622      return EI->second;
623    } else {
624      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
625      valueNumbering.insert(std::make_pair(V, nextValueNumber));
626
627      return nextValueNumber++;
628    }
629  } else if (CastInst* U = dyn_cast<CastInst>(V)) {
630    Expression e = create_expression(U);
631
632    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
633    if (EI != expressionNumbering.end()) {
634      valueNumbering.insert(std::make_pair(V, EI->second));
635      return EI->second;
636    } else {
637      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
638      valueNumbering.insert(std::make_pair(V, nextValueNumber));
639
640      return nextValueNumber++;
641    }
642  } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
643    Expression e = create_expression(U);
644
645    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
646    if (EI != expressionNumbering.end()) {
647      valueNumbering.insert(std::make_pair(V, EI->second));
648      return EI->second;
649    } else {
650      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
651      valueNumbering.insert(std::make_pair(V, nextValueNumber));
652
653      return nextValueNumber++;
654    }
655  } else {
656    valueNumbering.insert(std::make_pair(V, nextValueNumber));
657    return nextValueNumber++;
658  }
659}
660
661/// lookup - Returns the value number of the specified value. Fails if
662/// the value has not yet been numbered.
663uint32_t ValueTable::lookup(Value* V) const {
664  DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
665  assert(VI != valueNumbering.end() && "Value not numbered?");
666  return VI->second;
667}
668
669/// clear - Remove all entries from the ValueTable
670void ValueTable::clear() {
671  valueNumbering.clear();
672  expressionNumbering.clear();
673  nextValueNumber = 1;
674}
675
676/// erase - Remove a value from the value numbering
677void ValueTable::erase(Value* V) {
678  valueNumbering.erase(V);
679}
680
681//===----------------------------------------------------------------------===//
682//                         GVN Pass
683//===----------------------------------------------------------------------===//
684
685namespace llvm {
686  template<> struct DenseMapInfo<uint32_t> {
687    static inline uint32_t getEmptyKey() { return ~0; }
688    static inline uint32_t getTombstoneKey() { return ~0 - 1; }
689    static unsigned getHashValue(const uint32_t& Val) { return Val * 37; }
690    static bool isPod() { return true; }
691    static bool isEqual(const uint32_t& LHS, const uint32_t& RHS) {
692      return LHS == RHS;
693    }
694  };
695}
696
697namespace {
698  struct VISIBILITY_HIDDEN ValueNumberScope {
699    ValueNumberScope* parent;
700    DenseMap<uint32_t, Value*> table;
701
702    ValueNumberScope(ValueNumberScope* p) : parent(p) { }
703  };
704}
705
706namespace {
707
708  class VISIBILITY_HIDDEN GVN : public FunctionPass {
709    bool runOnFunction(Function &F);
710  public:
711    static char ID; // Pass identification, replacement for typeid
712    GVN() : FunctionPass((intptr_t)&ID) { }
713
714  private:
715    ValueTable VN;
716    DenseMap<BasicBlock*, ValueNumberScope*> localAvail;
717
718    typedef DenseMap<Value*, SmallPtrSet<Instruction*, 4> > PhiMapType;
719    PhiMapType phiMap;
720
721
722    // This transformation requires dominator postdominator info
723    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
724      AU.addRequired<DominatorTree>();
725      AU.addRequired<MemoryDependenceAnalysis>();
726      AU.addRequired<AliasAnalysis>();
727
728      AU.addPreserved<DominatorTree>();
729      AU.addPreserved<AliasAnalysis>();
730    }
731
732    // Helper fuctions
733    // FIXME: eliminate or document these better
734    bool processLoad(LoadInst* L,
735                     DenseMap<Value*, LoadInst*> &lastLoad,
736                     SmallVectorImpl<Instruction*> &toErase);
737    bool processInstruction(Instruction* I,
738                            DenseMap<Value*, LoadInst*>& lastSeenLoad,
739                            SmallVectorImpl<Instruction*> &toErase);
740    bool processNonLocalLoad(LoadInst* L,
741                             SmallVectorImpl<Instruction*> &toErase);
742    bool processBlock(DomTreeNode* DTN);
743    Value *GetValueForBlock(BasicBlock *BB, LoadInst* orig,
744                            DenseMap<BasicBlock*, Value*> &Phis,
745                            bool top_level = false);
746    void dump(DenseMap<uint32_t, Value*>& d);
747    bool iterateOnFunction(Function &F);
748    Value* CollapsePhi(PHINode* p);
749    bool isSafeReplacement(PHINode* p, Instruction* inst);
750    bool performPRE(Function& F);
751    Value* lookupNumber(BasicBlock* BB, uint32_t num);
752    bool mergeBlockIntoPredecessor(BasicBlock* BB);
753  };
754
755  char GVN::ID = 0;
756}
757
758// createGVNPass - The public interface to this file...
759FunctionPass *llvm::createGVNPass() { return new GVN(); }
760
761static RegisterPass<GVN> X("gvn",
762                           "Global Value Numbering");
763
764void GVN::dump(DenseMap<uint32_t, Value*>& d) {
765  printf("{\n");
766  for (DenseMap<uint32_t, Value*>::iterator I = d.begin(),
767       E = d.end(); I != E; ++I) {
768      printf("%d\n", I->first);
769      I->second->dump();
770  }
771  printf("}\n");
772}
773
774Value* GVN::CollapsePhi(PHINode* p) {
775  DominatorTree &DT = getAnalysis<DominatorTree>();
776  Value* constVal = p->hasConstantValue();
777
778  if (!constVal) return 0;
779
780  Instruction* inst = dyn_cast<Instruction>(constVal);
781  if (!inst)
782    return constVal;
783
784  if (DT.dominates(inst, p))
785    if (isSafeReplacement(p, inst))
786      return inst;
787  return 0;
788}
789
790bool GVN::isSafeReplacement(PHINode* p, Instruction* inst) {
791  if (!isa<PHINode>(inst))
792    return true;
793
794  for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end();
795       UI != E; ++UI)
796    if (PHINode* use_phi = dyn_cast<PHINode>(UI))
797      if (use_phi->getParent() == inst->getParent())
798        return false;
799
800  return true;
801}
802
803/// GetValueForBlock - Get the value to use within the specified basic block.
804/// available values are in Phis.
805Value *GVN::GetValueForBlock(BasicBlock *BB, LoadInst* orig,
806                             DenseMap<BasicBlock*, Value*> &Phis,
807                             bool top_level) {
808
809  // If we have already computed this value, return the previously computed val.
810  DenseMap<BasicBlock*, Value*>::iterator V = Phis.find(BB);
811  if (V != Phis.end() && !top_level) return V->second;
812
813  // If the block is unreachable, just return undef, since this path
814  // can't actually occur at runtime.
815  if (!getAnalysis<DominatorTree>().isReachableFromEntry(BB))
816    return Phis[BB] = UndefValue::get(orig->getType());
817
818  BasicBlock* singlePred = BB->getSinglePredecessor();
819  if (singlePred) {
820    Value *ret = GetValueForBlock(singlePred, orig, Phis);
821    Phis[BB] = ret;
822    return ret;
823  }
824
825  // Otherwise, the idom is the loop, so we need to insert a PHI node.  Do so
826  // now, then get values to fill in the incoming values for the PHI.
827  PHINode *PN = PHINode::Create(orig->getType(), orig->getName()+".rle",
828                                BB->begin());
829  PN->reserveOperandSpace(std::distance(pred_begin(BB), pred_end(BB)));
830
831  if (Phis.count(BB) == 0)
832    Phis.insert(std::make_pair(BB, PN));
833
834  // Fill in the incoming values for the block.
835  for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
836    Value* val = GetValueForBlock(*PI, orig, Phis);
837    PN->addIncoming(val, *PI);
838  }
839
840  AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
841  AA.copyValue(orig, PN);
842
843  // Attempt to collapse PHI nodes that are trivially redundant
844  Value* v = CollapsePhi(PN);
845  if (!v) {
846    // Cache our phi construction results
847    phiMap[orig->getPointerOperand()].insert(PN);
848    return PN;
849  }
850
851  MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
852
853  MD.removeInstruction(PN);
854  PN->replaceAllUsesWith(v);
855
856  for (DenseMap<BasicBlock*, Value*>::iterator I = Phis.begin(),
857       E = Phis.end(); I != E; ++I)
858    if (I->second == PN)
859      I->second = v;
860
861  PN->eraseFromParent();
862
863  Phis[BB] = v;
864  return v;
865}
866
867/// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
868/// non-local by performing PHI construction.
869bool GVN::processNonLocalLoad(LoadInst* L,
870                              SmallVectorImpl<Instruction*> &toErase) {
871  MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
872
873  // Find the non-local dependencies of the load
874  DenseMap<BasicBlock*, Value*> deps;
875  MD.getNonLocalDependency(L, deps);
876
877  DenseMap<BasicBlock*, Value*> repl;
878
879  // Filter out useless results (non-locals, etc)
880  for (DenseMap<BasicBlock*, Value*>::iterator I = deps.begin(), E = deps.end();
881       I != E; ++I) {
882    if (I->second == MemoryDependenceAnalysis::None)
883      return false;
884
885    if (I->second == MemoryDependenceAnalysis::NonLocal)
886      continue;
887
888    if (StoreInst* S = dyn_cast<StoreInst>(I->second)) {
889      if (S->getPointerOperand() != L->getPointerOperand())
890        return false;
891      repl[I->first] = S->getOperand(0);
892    } else if (LoadInst* LD = dyn_cast<LoadInst>(I->second)) {
893      if (LD->getPointerOperand() != L->getPointerOperand())
894        return false;
895      repl[I->first] = LD;
896    } else {
897      return false;
898    }
899  }
900
901  // Use cached PHI construction information from previous runs
902  SmallPtrSet<Instruction*, 4>& p = phiMap[L->getPointerOperand()];
903  for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
904       I != E; ++I) {
905    if ((*I)->getParent() == L->getParent()) {
906      MD.removeInstruction(L);
907      L->replaceAllUsesWith(*I);
908      toErase.push_back(L);
909      NumGVNLoad++;
910      return true;
911    }
912
913    repl.insert(std::make_pair((*I)->getParent(), *I));
914  }
915
916  // Perform PHI construction
917  SmallPtrSet<BasicBlock*, 4> visited;
918  Value* v = GetValueForBlock(L->getParent(), L, repl, true);
919
920  MD.removeInstruction(L);
921  L->replaceAllUsesWith(v);
922  toErase.push_back(L);
923  NumGVNLoad++;
924
925  return true;
926}
927
928/// processLoad - Attempt to eliminate a load, first by eliminating it
929/// locally, and then attempting non-local elimination if that fails.
930bool GVN::processLoad(LoadInst *L, DenseMap<Value*, LoadInst*> &lastLoad,
931                      SmallVectorImpl<Instruction*> &toErase) {
932  if (L->isVolatile()) {
933    lastLoad[L->getPointerOperand()] = L;
934    return false;
935  }
936
937  Value* pointer = L->getPointerOperand();
938  LoadInst*& last = lastLoad[pointer];
939
940  // ... to a pointer that has been loaded from before...
941  MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
942  bool removedNonLocal = false;
943  Instruction* dep = MD.getDependency(L);
944  if (dep == MemoryDependenceAnalysis::NonLocal &&
945      L->getParent() != &L->getParent()->getParent()->getEntryBlock()) {
946    removedNonLocal = processNonLocalLoad(L, toErase);
947
948    if (!removedNonLocal)
949      last = L;
950
951    return removedNonLocal;
952  }
953
954
955  bool deletedLoad = false;
956
957  // Walk up the dependency chain until we either find
958  // a dependency we can use, or we can't walk any further
959  while (dep != MemoryDependenceAnalysis::None &&
960         dep != MemoryDependenceAnalysis::NonLocal &&
961         (isa<LoadInst>(dep) || isa<StoreInst>(dep))) {
962    // ... that depends on a store ...
963    if (StoreInst* S = dyn_cast<StoreInst>(dep)) {
964      if (S->getPointerOperand() == pointer) {
965        // Remove it!
966        MD.removeInstruction(L);
967
968        L->replaceAllUsesWith(S->getOperand(0));
969        toErase.push_back(L);
970        deletedLoad = true;
971        NumGVNLoad++;
972      }
973
974      // Whether we removed it or not, we can't
975      // go any further
976      break;
977    } else if (!last) {
978      // If we don't depend on a store, and we haven't
979      // been loaded before, bail.
980      break;
981    } else if (dep == last) {
982      // Remove it!
983      MD.removeInstruction(L);
984
985      L->replaceAllUsesWith(last);
986      toErase.push_back(L);
987      deletedLoad = true;
988      NumGVNLoad++;
989
990      break;
991    } else {
992      dep = MD.getDependency(L, dep);
993    }
994  }
995
996  if (dep != MemoryDependenceAnalysis::None &&
997      dep != MemoryDependenceAnalysis::NonLocal &&
998      isa<AllocationInst>(dep)) {
999    // Check that this load is actually from the
1000    // allocation we found
1001    Value* v = L->getOperand(0);
1002    while (true) {
1003      if (BitCastInst *BC = dyn_cast<BitCastInst>(v))
1004        v = BC->getOperand(0);
1005      else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(v))
1006        v = GEP->getOperand(0);
1007      else
1008        break;
1009    }
1010    if (v == dep) {
1011      // If this load depends directly on an allocation, there isn't
1012      // anything stored there; therefore, we can optimize this load
1013      // to undef.
1014      MD.removeInstruction(L);
1015
1016      L->replaceAllUsesWith(UndefValue::get(L->getType()));
1017      toErase.push_back(L);
1018      deletedLoad = true;
1019      NumGVNLoad++;
1020    }
1021  }
1022
1023  if (!deletedLoad)
1024    last = L;
1025
1026  return deletedLoad;
1027}
1028
1029Value* GVN::lookupNumber(BasicBlock* BB, uint32_t num) {
1030  DenseMap<BasicBlock*, ValueNumberScope*>::iterator I = localAvail.find(BB);
1031  if (I == localAvail.end())
1032    return 0;
1033
1034  ValueNumberScope* locals = I->second;
1035
1036  while (locals) {
1037    DenseMap<uint32_t, Value*>::iterator I = locals->table.find(num);
1038    if (I != locals->table.end())
1039      return I->second;
1040    else
1041      locals = locals->parent;
1042  }
1043
1044  return 0;
1045}
1046
1047/// processInstruction - When calculating availability, handle an instruction
1048/// by inserting it into the appropriate sets
1049bool GVN::processInstruction(Instruction *I,
1050                             DenseMap<Value*, LoadInst*> &lastSeenLoad,
1051                             SmallVectorImpl<Instruction*> &toErase) {
1052  if (LoadInst* L = dyn_cast<LoadInst>(I)) {
1053    bool changed = processLoad(L, lastSeenLoad, toErase);
1054
1055    if (!changed) {
1056      unsigned num = VN.lookup_or_add(L);
1057      localAvail[I->getParent()]->table.insert(std::make_pair(num, L));
1058    }
1059
1060    return changed;
1061  }
1062
1063  uint32_t nextNum = VN.getNextUnusedValueNumber();
1064  unsigned num = VN.lookup_or_add(I);
1065
1066  // Allocations are always uniquely numbered, so we can save time and memory
1067  // by fast failing them.
1068  if (isa<AllocationInst>(I) || isa<TerminatorInst>(I)) {
1069    localAvail[I->getParent()]->table.insert(std::make_pair(num, I));
1070    return false;
1071  }
1072
1073  // Collapse PHI nodes
1074  if (PHINode* p = dyn_cast<PHINode>(I)) {
1075    Value* constVal = CollapsePhi(p);
1076
1077    if (constVal) {
1078      for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end();
1079           PI != PE; ++PI)
1080        if (PI->second.count(p))
1081          PI->second.erase(p);
1082
1083      p->replaceAllUsesWith(constVal);
1084      toErase.push_back(p);
1085    } else {
1086      localAvail[I->getParent()]->table.insert(std::make_pair(num, I));
1087    }
1088
1089  // If the number we were assigned was a brand new VN, then we don't
1090  // need to do a lookup to see if the number already exists
1091  // somewhere in the domtree: it can't!
1092  } else if (num == nextNum) {
1093    localAvail[I->getParent()]->table.insert(std::make_pair(num, I));
1094
1095  // Perform value-number based elimination
1096  } else if (Value* repl = lookupNumber(I->getParent(), num)) {
1097    // Remove it!
1098    MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1099    MD.removeInstruction(I);
1100
1101    VN.erase(I);
1102    I->replaceAllUsesWith(repl);
1103    toErase.push_back(I);
1104    return true;
1105  } else {
1106    localAvail[I->getParent()]->table.insert(std::make_pair(num, I));
1107  }
1108
1109  return false;
1110}
1111
1112// GVN::runOnFunction - This is the main transformation entry point for a
1113// function.
1114//
1115bool GVN::runOnFunction(Function& F) {
1116  VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
1117  VN.setMemDep(&getAnalysis<MemoryDependenceAnalysis>());
1118  VN.setDomTree(&getAnalysis<DominatorTree>());
1119
1120  bool changed = false;
1121  bool shouldContinue = true;
1122
1123  // Merge unconditional branches, allowing PRE to catch more
1124  // optimization opportunities.
1125  for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) {
1126    BasicBlock* BB = FI;
1127    ++FI;
1128    bool removedBlock = MergeBlockIntoPredecessor(BB, this);
1129    if (removedBlock) NumGVNBlocks++;
1130
1131    changed |= removedBlock;
1132  }
1133
1134  while (shouldContinue) {
1135    shouldContinue = iterateOnFunction(F);
1136    changed |= shouldContinue;
1137  }
1138
1139  if (EnablePRE) {
1140    bool PREChanged = false;
1141    while ((PREChanged = performPRE(F)))
1142      changed |= PREChanged;
1143  }
1144
1145  return changed;
1146}
1147
1148
1149bool GVN::processBlock(DomTreeNode* DTN) {
1150  BasicBlock* BB = DTN->getBlock();
1151
1152  SmallVector<Instruction*, 8> toErase;
1153  DenseMap<Value*, LoadInst*> lastSeenLoad;
1154  bool changed_function = false;
1155
1156  if (DTN->getIDom())
1157    localAvail[BB] =
1158                  new ValueNumberScope(localAvail[DTN->getIDom()->getBlock()]);
1159  else
1160    localAvail[BB] = new ValueNumberScope(0);
1161
1162  for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1163       BI != BE;) {
1164    changed_function |= processInstruction(BI, lastSeenLoad, toErase);
1165    if (toErase.empty()) {
1166      ++BI;
1167      continue;
1168    }
1169
1170    // If we need some instructions deleted, do it now.
1171    NumGVNInstr += toErase.size();
1172
1173    // Avoid iterator invalidation.
1174    bool AtStart = BI == BB->begin();
1175    if (!AtStart)
1176      --BI;
1177
1178    for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
1179         E = toErase.end(); I != E; ++I)
1180      (*I)->eraseFromParent();
1181
1182    if (AtStart)
1183      BI = BB->begin();
1184    else
1185      ++BI;
1186
1187    toErase.clear();
1188  }
1189
1190  return changed_function;
1191}
1192
1193/// performPRE - Perform a purely local form of PRE that looks for diamond
1194/// control flow patterns and attempts to perform simple PRE at the join point.
1195bool GVN::performPRE(Function& F) {
1196  bool changed = false;
1197  SmallVector<std::pair<TerminatorInst*, unsigned>, 4> toSplit;
1198  for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
1199       DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
1200    BasicBlock* CurrentBlock = *DI;
1201
1202    // Nothing to PRE in the entry block.
1203    if (CurrentBlock == &F.getEntryBlock()) continue;
1204
1205    for (BasicBlock::iterator BI = CurrentBlock->begin(),
1206         BE = CurrentBlock->end(); BI != BE; ) {
1207      if (isa<AllocationInst>(BI) || isa<TerminatorInst>(BI) ||
1208          isa<PHINode>(BI) || BI->mayReadFromMemory() ||
1209          BI->mayWriteToMemory()) {
1210        BI++;
1211        continue;
1212      }
1213
1214      uint32_t valno = VN.lookup(BI);
1215
1216      // Look for the predecessors for PRE opportunities.  We're
1217      // only trying to solve the basic diamond case, where
1218      // a value is computed in the successor and one predecessor,
1219      // but not the other.  We also explicitly disallow cases
1220      // where the successor is its own predecessor, because they're
1221      // more complicated to get right.
1222      unsigned numWith = 0;
1223      unsigned numWithout = 0;
1224      BasicBlock* PREPred = 0;
1225      DenseMap<BasicBlock*, Value*> predMap;
1226      for (pred_iterator PI = pred_begin(CurrentBlock),
1227           PE = pred_end(CurrentBlock); PI != PE; ++PI) {
1228        // We're not interested in PRE where the block is its
1229        // own predecessor, on in blocks with predecessors
1230        // that are not reachable.
1231        if (*PI == CurrentBlock) {
1232          numWithout = 2;
1233          break;
1234        } else if (!localAvail.count(*PI))  {
1235          numWithout = 2;
1236          break;
1237        }
1238
1239        DenseMap<uint32_t, Value*>::iterator predV =
1240                                            localAvail[*PI]->table.find(valno);
1241        if (predV == localAvail[*PI]->table.end()) {
1242          PREPred = *PI;
1243          numWithout++;
1244        } else if (predV->second == BI) {
1245          numWithout = 2;
1246        } else {
1247          predMap[*PI] = predV->second;
1248          numWith++;
1249        }
1250      }
1251
1252      // Don't do PRE when it might increase code size, i.e. when
1253      // we would need to insert instructions in more than one pred.
1254      if (numWithout != 1 || numWith == 0) {
1255        BI++;
1256        continue;
1257      }
1258
1259      // We can't do PRE safely on a critical edge, so instead we schedule
1260      // the edge to be split and perform the PRE the next time we iterate
1261      // on the function.
1262      unsigned succNum = 0;
1263      for (unsigned i = 0, e = PREPred->getTerminator()->getNumSuccessors();
1264           i != e; ++i)
1265        if (PREPred->getTerminator()->getSuccessor(i) == PREPred) {
1266          succNum = i;
1267          break;
1268        }
1269
1270      if (isCriticalEdge(PREPred->getTerminator(), succNum)) {
1271        toSplit.push_back(std::make_pair(PREPred->getTerminator(), succNum));
1272        changed = true;
1273        BI++;
1274        continue;
1275      }
1276
1277      // Instantiate the expression the in predecessor that lacked it.
1278      // Because we are going top-down through the block, all value numbers
1279      // will be available in the predecessor by the time we need them.  Any
1280      // that weren't original present will have been instantiated earlier
1281      // in this loop.
1282      Instruction* PREInstr = BI->clone();
1283      bool success = true;
1284      for (unsigned i = 0; i < BI->getNumOperands(); ++i) {
1285        Value* op = BI->getOperand(i);
1286        if (isa<Argument>(op) || isa<Constant>(op) || isa<GlobalValue>(op))
1287          PREInstr->setOperand(i, op);
1288        else {
1289          Value* V = lookupNumber(PREPred, VN.lookup(op));
1290          if (!V) {
1291            success = false;
1292            break;
1293          } else
1294            PREInstr->setOperand(i, V);
1295        }
1296      }
1297
1298      // Fail out if we encounter an operand that is not available in
1299      // the PRE predecessor.  This is typically because of loads which
1300      // are not value numbered precisely.
1301      if (!success) {
1302        delete PREInstr;
1303        BI++;
1304        continue;
1305      }
1306
1307      PREInstr->insertBefore(PREPred->getTerminator());
1308      PREInstr->setName(BI->getName() + ".pre");
1309      predMap[PREPred] = PREInstr;
1310      VN.add(PREInstr, valno);
1311      NumGVNPRE++;
1312
1313      // Update the availability map to include the new instruction.
1314      localAvail[PREPred]->table.insert(std::make_pair(valno, PREInstr));
1315
1316      // Create a PHI to make the value available in this block.
1317      PHINode* Phi = PHINode::Create(BI->getType(),
1318                                     BI->getName() + ".pre-phi",
1319                                     CurrentBlock->begin());
1320      for (pred_iterator PI = pred_begin(CurrentBlock),
1321           PE = pred_end(CurrentBlock); PI != PE; ++PI)
1322        Phi->addIncoming(predMap[*PI], *PI);
1323
1324      VN.add(Phi, valno);
1325      localAvail[CurrentBlock]->table[valno] = Phi;
1326
1327      BI->replaceAllUsesWith(Phi);
1328      VN.erase(BI);
1329
1330      Instruction* erase = BI;
1331      BI++;
1332      erase->eraseFromParent();
1333
1334      changed = true;
1335    }
1336  }
1337
1338  for (SmallVector<std::pair<TerminatorInst*, unsigned>, 4>::iterator
1339       I = toSplit.begin(), E = toSplit.end(); I != E; ++I)
1340    SplitCriticalEdge(I->first, I->second, this);
1341
1342  return changed || toSplit.size();
1343}
1344
1345// iterateOnFunction - Executes one iteration of GVN
1346bool GVN::iterateOnFunction(Function &F) {
1347  // Clean out global sets from any previous functions
1348  VN.clear();
1349  phiMap.clear();
1350
1351  for (DenseMap<BasicBlock*, ValueNumberScope*>::iterator
1352       I = localAvail.begin(), E = localAvail.end(); I != E; ++I)
1353    delete I->second;
1354  localAvail.clear();
1355
1356  DominatorTree &DT = getAnalysis<DominatorTree>();
1357
1358  // Top-down walk of the dominator tree
1359  bool changed = false;
1360  for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1361       DE = df_end(DT.getRootNode()); DI != DE; ++DI)
1362    changed |= processBlock(*DI);
1363
1364  return changed;
1365}
1366