GVN.cpp revision 333c40096561218bc3597cf153c0a3895274414c
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/IntrinsicInst.h"
25#include "llvm/LLVMContext.h"
26#include "llvm/Value.h"
27#include "llvm/ADT/DenseMap.h"
28#include "llvm/ADT/DepthFirstIterator.h"
29#include "llvm/ADT/PostOrderIterator.h"
30#include "llvm/ADT/SmallPtrSet.h"
31#include "llvm/ADT/SmallVector.h"
32#include "llvm/ADT/Statistic.h"
33#include "llvm/Analysis/Dominators.h"
34#include "llvm/Analysis/AliasAnalysis.h"
35#include "llvm/Analysis/MemoryDependenceAnalysis.h"
36#include "llvm/Support/CFG.h"
37#include "llvm/Support/CommandLine.h"
38#include "llvm/Support/Compiler.h"
39#include "llvm/Support/Debug.h"
40#include "llvm/Transforms/Utils/BasicBlockUtils.h"
41#include "llvm/Transforms/Utils/Local.h"
42#include <cstdio>
43using namespace llvm;
44
45STATISTIC(NumGVNInstr,  "Number of instructions deleted");
46STATISTIC(NumGVNLoad,   "Number of loads deleted");
47STATISTIC(NumGVNPRE,    "Number of instructions PRE'd");
48STATISTIC(NumGVNBlocks, "Number of blocks merged");
49STATISTIC(NumPRELoad,   "Number of loads PRE'd");
50
51static cl::opt<bool> EnablePRE("enable-pre",
52                               cl::init(true), cl::Hidden);
53static cl::opt<bool> EnableLoadPRE("enable-load-pre", cl::init(true));
54
55//===----------------------------------------------------------------------===//
56//                         ValueTable Class
57//===----------------------------------------------------------------------===//
58
59/// This class holds the mapping between values and value numbers.  It is used
60/// as an efficient mechanism to determine the expression-wise equivalence of
61/// two values.
62namespace {
63  struct VISIBILITY_HIDDEN Expression {
64    enum ExpressionOpcode { ADD, FADD, SUB, FSUB, MUL, FMUL,
65                            UDIV, SDIV, FDIV, UREM, SREM,
66                            FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ,
67                            ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE,
68                            ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ,
69                            FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE,
70                            FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE,
71                            FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
72                            SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
73                            FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT,
74                            PTRTOINT, INTTOPTR, BITCAST, GEP, CALL, CONSTANT,
75                            EMPTY, TOMBSTONE };
76
77    ExpressionOpcode opcode;
78    const Type* type;
79    uint32_t firstVN;
80    uint32_t secondVN;
81    uint32_t thirdVN;
82    SmallVector<uint32_t, 4> varargs;
83    Value* function;
84
85    Expression() { }
86    Expression(ExpressionOpcode o) : opcode(o) { }
87
88    bool operator==(const Expression &other) const {
89      if (opcode != other.opcode)
90        return false;
91      else if (opcode == EMPTY || opcode == TOMBSTONE)
92        return true;
93      else if (type != other.type)
94        return false;
95      else if (function != other.function)
96        return false;
97      else if (firstVN != other.firstVN)
98        return false;
99      else if (secondVN != other.secondVN)
100        return false;
101      else if (thirdVN != other.thirdVN)
102        return false;
103      else {
104        if (varargs.size() != other.varargs.size())
105          return false;
106
107        for (size_t i = 0; i < varargs.size(); ++i)
108          if (varargs[i] != other.varargs[i])
109            return false;
110
111        return true;
112      }
113    }
114
115    bool operator!=(const Expression &other) const {
116      return !(*this == other);
117    }
118  };
119
120  class VISIBILITY_HIDDEN ValueTable {
121    private:
122      DenseMap<Value*, uint32_t> valueNumbering;
123      DenseMap<Expression, uint32_t> expressionNumbering;
124      AliasAnalysis* AA;
125      MemoryDependenceAnalysis* MD;
126      DominatorTree* DT;
127
128      uint32_t nextValueNumber;
129
130      Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
131      Expression::ExpressionOpcode getOpcode(CmpInst* C);
132      Expression::ExpressionOpcode getOpcode(CastInst* C);
133      Expression create_expression(BinaryOperator* BO);
134      Expression create_expression(CmpInst* C);
135      Expression create_expression(ShuffleVectorInst* V);
136      Expression create_expression(ExtractElementInst* C);
137      Expression create_expression(InsertElementInst* V);
138      Expression create_expression(SelectInst* V);
139      Expression create_expression(CastInst* C);
140      Expression create_expression(GetElementPtrInst* G);
141      Expression create_expression(CallInst* C);
142      Expression create_expression(Constant* C);
143    public:
144      ValueTable() : nextValueNumber(1) { }
145      uint32_t lookup_or_add(Value* V);
146      uint32_t lookup(Value* V) const;
147      void add(Value* V, uint32_t num);
148      void clear();
149      void erase(Value* v);
150      unsigned size();
151      void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
152      AliasAnalysis *getAliasAnalysis() const { return AA; }
153      void setMemDep(MemoryDependenceAnalysis* M) { MD = M; }
154      void setDomTree(DominatorTree* D) { DT = D; }
155      uint32_t getNextUnusedValueNumber() { return nextValueNumber; }
156      void verifyRemoved(const Value *) const;
157  };
158}
159
160namespace llvm {
161template <> struct DenseMapInfo<Expression> {
162  static inline Expression getEmptyKey() {
163    return Expression(Expression::EMPTY);
164  }
165
166  static inline Expression getTombstoneKey() {
167    return Expression(Expression::TOMBSTONE);
168  }
169
170  static unsigned getHashValue(const Expression e) {
171    unsigned hash = e.opcode;
172
173    hash = e.firstVN + hash * 37;
174    hash = e.secondVN + hash * 37;
175    hash = e.thirdVN + hash * 37;
176
177    hash = ((unsigned)((uintptr_t)e.type >> 4) ^
178            (unsigned)((uintptr_t)e.type >> 9)) +
179           hash * 37;
180
181    for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
182         E = e.varargs.end(); I != E; ++I)
183      hash = *I + hash * 37;
184
185    hash = ((unsigned)((uintptr_t)e.function >> 4) ^
186            (unsigned)((uintptr_t)e.function >> 9)) +
187           hash * 37;
188
189    return hash;
190  }
191  static bool isEqual(const Expression &LHS, const Expression &RHS) {
192    return LHS == RHS;
193  }
194  static bool isPod() { return true; }
195};
196}
197
198//===----------------------------------------------------------------------===//
199//                     ValueTable Internal Functions
200//===----------------------------------------------------------------------===//
201Expression::ExpressionOpcode ValueTable::getOpcode(BinaryOperator* BO) {
202  switch(BO->getOpcode()) {
203  default: // THIS SHOULD NEVER HAPPEN
204    assert(0 && "Binary operator with unknown opcode?");
205  case Instruction::Add:  return Expression::ADD;
206  case Instruction::FAdd: return Expression::FADD;
207  case Instruction::Sub:  return Expression::SUB;
208  case Instruction::FSub: return Expression::FSUB;
209  case Instruction::Mul:  return Expression::MUL;
210  case Instruction::FMul: return Expression::FMUL;
211  case Instruction::UDiv: return Expression::UDIV;
212  case Instruction::SDiv: return Expression::SDIV;
213  case Instruction::FDiv: return Expression::FDIV;
214  case Instruction::URem: return Expression::UREM;
215  case Instruction::SRem: return Expression::SREM;
216  case Instruction::FRem: return Expression::FREM;
217  case Instruction::Shl:  return Expression::SHL;
218  case Instruction::LShr: return Expression::LSHR;
219  case Instruction::AShr: return Expression::ASHR;
220  case Instruction::And:  return Expression::AND;
221  case Instruction::Or:   return Expression::OR;
222  case Instruction::Xor:  return Expression::XOR;
223  }
224}
225
226Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
227  if (isa<ICmpInst>(C)) {
228    switch (C->getPredicate()) {
229    default:  // THIS SHOULD NEVER HAPPEN
230      assert(0 && "Comparison with unknown predicate?");
231    case ICmpInst::ICMP_EQ:  return Expression::ICMPEQ;
232    case ICmpInst::ICMP_NE:  return Expression::ICMPNE;
233    case ICmpInst::ICMP_UGT: return Expression::ICMPUGT;
234    case ICmpInst::ICMP_UGE: return Expression::ICMPUGE;
235    case ICmpInst::ICMP_ULT: return Expression::ICMPULT;
236    case ICmpInst::ICMP_ULE: return Expression::ICMPULE;
237    case ICmpInst::ICMP_SGT: return Expression::ICMPSGT;
238    case ICmpInst::ICMP_SGE: return Expression::ICMPSGE;
239    case ICmpInst::ICMP_SLT: return Expression::ICMPSLT;
240    case ICmpInst::ICMP_SLE: return Expression::ICMPSLE;
241    }
242  } else {
243    switch (C->getPredicate()) {
244    default: // THIS SHOULD NEVER HAPPEN
245      assert(0 && "Comparison with unknown predicate?");
246    case FCmpInst::FCMP_OEQ: return Expression::FCMPOEQ;
247    case FCmpInst::FCMP_OGT: return Expression::FCMPOGT;
248    case FCmpInst::FCMP_OGE: return Expression::FCMPOGE;
249    case FCmpInst::FCMP_OLT: return Expression::FCMPOLT;
250    case FCmpInst::FCMP_OLE: return Expression::FCMPOLE;
251    case FCmpInst::FCMP_ONE: return Expression::FCMPONE;
252    case FCmpInst::FCMP_ORD: return Expression::FCMPORD;
253    case FCmpInst::FCMP_UNO: return Expression::FCMPUNO;
254    case FCmpInst::FCMP_UEQ: return Expression::FCMPUEQ;
255    case FCmpInst::FCMP_UGT: return Expression::FCMPUGT;
256    case FCmpInst::FCMP_UGE: return Expression::FCMPUGE;
257    case FCmpInst::FCMP_ULT: return Expression::FCMPULT;
258    case FCmpInst::FCMP_ULE: return Expression::FCMPULE;
259    case FCmpInst::FCMP_UNE: return Expression::FCMPUNE;
260    }
261  }
262}
263
264Expression::ExpressionOpcode ValueTable::getOpcode(CastInst* C) {
265  switch(C->getOpcode()) {
266  default: // THIS SHOULD NEVER HAPPEN
267    assert(0 && "Cast operator with unknown opcode?");
268  case Instruction::Trunc:    return Expression::TRUNC;
269  case Instruction::ZExt:     return Expression::ZEXT;
270  case Instruction::SExt:     return Expression::SEXT;
271  case Instruction::FPToUI:   return Expression::FPTOUI;
272  case Instruction::FPToSI:   return Expression::FPTOSI;
273  case Instruction::UIToFP:   return Expression::UITOFP;
274  case Instruction::SIToFP:   return Expression::SITOFP;
275  case Instruction::FPTrunc:  return Expression::FPTRUNC;
276  case Instruction::FPExt:    return Expression::FPEXT;
277  case Instruction::PtrToInt: return Expression::PTRTOINT;
278  case Instruction::IntToPtr: return Expression::INTTOPTR;
279  case Instruction::BitCast:  return Expression::BITCAST;
280  }
281}
282
283Expression ValueTable::create_expression(CallInst* C) {
284  Expression e;
285
286  e.type = C->getType();
287  e.firstVN = 0;
288  e.secondVN = 0;
289  e.thirdVN = 0;
290  e.function = C->getCalledFunction();
291  e.opcode = Expression::CALL;
292
293  for (CallInst::op_iterator I = C->op_begin()+1, E = C->op_end();
294       I != E; ++I)
295    e.varargs.push_back(lookup_or_add(*I));
296
297  return e;
298}
299
300Expression ValueTable::create_expression(BinaryOperator* BO) {
301  Expression e;
302
303  e.firstVN = lookup_or_add(BO->getOperand(0));
304  e.secondVN = lookup_or_add(BO->getOperand(1));
305  e.thirdVN = 0;
306  e.function = 0;
307  e.type = BO->getType();
308  e.opcode = getOpcode(BO);
309
310  return e;
311}
312
313Expression ValueTable::create_expression(CmpInst* C) {
314  Expression e;
315
316  e.firstVN = lookup_or_add(C->getOperand(0));
317  e.secondVN = lookup_or_add(C->getOperand(1));
318  e.thirdVN = 0;
319  e.function = 0;
320  e.type = C->getType();
321  e.opcode = getOpcode(C);
322
323  return e;
324}
325
326Expression ValueTable::create_expression(CastInst* C) {
327  Expression e;
328
329  e.firstVN = lookup_or_add(C->getOperand(0));
330  e.secondVN = 0;
331  e.thirdVN = 0;
332  e.function = 0;
333  e.type = C->getType();
334  e.opcode = getOpcode(C);
335
336  return e;
337}
338
339Expression ValueTable::create_expression(ShuffleVectorInst* S) {
340  Expression e;
341
342  e.firstVN = lookup_or_add(S->getOperand(0));
343  e.secondVN = lookup_or_add(S->getOperand(1));
344  e.thirdVN = lookup_or_add(S->getOperand(2));
345  e.function = 0;
346  e.type = S->getType();
347  e.opcode = Expression::SHUFFLE;
348
349  return e;
350}
351
352Expression ValueTable::create_expression(ExtractElementInst* E) {
353  Expression e;
354
355  e.firstVN = lookup_or_add(E->getOperand(0));
356  e.secondVN = lookup_or_add(E->getOperand(1));
357  e.thirdVN = 0;
358  e.function = 0;
359  e.type = E->getType();
360  e.opcode = Expression::EXTRACT;
361
362  return e;
363}
364
365Expression ValueTable::create_expression(InsertElementInst* I) {
366  Expression e;
367
368  e.firstVN = lookup_or_add(I->getOperand(0));
369  e.secondVN = lookup_or_add(I->getOperand(1));
370  e.thirdVN = lookup_or_add(I->getOperand(2));
371  e.function = 0;
372  e.type = I->getType();
373  e.opcode = Expression::INSERT;
374
375  return e;
376}
377
378Expression ValueTable::create_expression(SelectInst* I) {
379  Expression e;
380
381  e.firstVN = lookup_or_add(I->getCondition());
382  e.secondVN = lookup_or_add(I->getTrueValue());
383  e.thirdVN = lookup_or_add(I->getFalseValue());
384  e.function = 0;
385  e.type = I->getType();
386  e.opcode = Expression::SELECT;
387
388  return e;
389}
390
391Expression ValueTable::create_expression(GetElementPtrInst* G) {
392  Expression e;
393
394  e.firstVN = lookup_or_add(G->getPointerOperand());
395  e.secondVN = 0;
396  e.thirdVN = 0;
397  e.function = 0;
398  e.type = G->getType();
399  e.opcode = Expression::GEP;
400
401  for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
402       I != E; ++I)
403    e.varargs.push_back(lookup_or_add(*I));
404
405  return e;
406}
407
408//===----------------------------------------------------------------------===//
409//                     ValueTable External Functions
410//===----------------------------------------------------------------------===//
411
412/// add - Insert a value into the table with a specified value number.
413void ValueTable::add(Value* V, uint32_t num) {
414  valueNumbering.insert(std::make_pair(V, num));
415}
416
417/// lookup_or_add - Returns the value number for the specified value, assigning
418/// it a new number if it did not have one before.
419uint32_t ValueTable::lookup_or_add(Value* V) {
420  DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
421  if (VI != valueNumbering.end())
422    return VI->second;
423
424  if (CallInst* C = dyn_cast<CallInst>(V)) {
425    if (AA->doesNotAccessMemory(C)) {
426      Expression e = create_expression(C);
427
428      DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
429      if (EI != expressionNumbering.end()) {
430        valueNumbering.insert(std::make_pair(V, EI->second));
431        return EI->second;
432      } else {
433        expressionNumbering.insert(std::make_pair(e, nextValueNumber));
434        valueNumbering.insert(std::make_pair(V, nextValueNumber));
435
436        return nextValueNumber++;
437      }
438    } else if (AA->onlyReadsMemory(C)) {
439      Expression e = create_expression(C);
440
441      if (expressionNumbering.find(e) == expressionNumbering.end()) {
442        expressionNumbering.insert(std::make_pair(e, nextValueNumber));
443        valueNumbering.insert(std::make_pair(V, nextValueNumber));
444        return nextValueNumber++;
445      }
446
447      MemDepResult local_dep = MD->getDependency(C);
448
449      if (!local_dep.isDef() && !local_dep.isNonLocal()) {
450        valueNumbering.insert(std::make_pair(V, nextValueNumber));
451        return nextValueNumber++;
452      }
453
454      if (local_dep.isDef()) {
455        CallInst* local_cdep = cast<CallInst>(local_dep.getInst());
456
457        if (local_cdep->getNumOperands() != C->getNumOperands()) {
458          valueNumbering.insert(std::make_pair(V, nextValueNumber));
459          return nextValueNumber++;
460        }
461
462        for (unsigned i = 1; i < C->getNumOperands(); ++i) {
463          uint32_t c_vn = lookup_or_add(C->getOperand(i));
464          uint32_t cd_vn = lookup_or_add(local_cdep->getOperand(i));
465          if (c_vn != cd_vn) {
466            valueNumbering.insert(std::make_pair(V, nextValueNumber));
467            return nextValueNumber++;
468          }
469        }
470
471        uint32_t v = lookup_or_add(local_cdep);
472        valueNumbering.insert(std::make_pair(V, v));
473        return v;
474      }
475
476      // Non-local case.
477      const MemoryDependenceAnalysis::NonLocalDepInfo &deps =
478        MD->getNonLocalCallDependency(CallSite(C));
479      // FIXME: call/call dependencies for readonly calls should return def, not
480      // clobber!  Move the checking logic to MemDep!
481      CallInst* cdep = 0;
482
483      // Check to see if we have a single dominating call instruction that is
484      // identical to C.
485      for (unsigned i = 0, e = deps.size(); i != e; ++i) {
486        const MemoryDependenceAnalysis::NonLocalDepEntry *I = &deps[i];
487        // Ignore non-local dependencies.
488        if (I->second.isNonLocal())
489          continue;
490
491        // We don't handle non-depedencies.  If we already have a call, reject
492        // instruction dependencies.
493        if (I->second.isClobber() || cdep != 0) {
494          cdep = 0;
495          break;
496        }
497
498        CallInst *NonLocalDepCall = dyn_cast<CallInst>(I->second.getInst());
499        // FIXME: All duplicated with non-local case.
500        if (NonLocalDepCall && DT->properlyDominates(I->first, C->getParent())){
501          cdep = NonLocalDepCall;
502          continue;
503        }
504
505        cdep = 0;
506        break;
507      }
508
509      if (!cdep) {
510        valueNumbering.insert(std::make_pair(V, nextValueNumber));
511        return nextValueNumber++;
512      }
513
514      if (cdep->getNumOperands() != C->getNumOperands()) {
515        valueNumbering.insert(std::make_pair(V, nextValueNumber));
516        return nextValueNumber++;
517      }
518      for (unsigned i = 1; i < C->getNumOperands(); ++i) {
519        uint32_t c_vn = lookup_or_add(C->getOperand(i));
520        uint32_t cd_vn = lookup_or_add(cdep->getOperand(i));
521        if (c_vn != cd_vn) {
522          valueNumbering.insert(std::make_pair(V, nextValueNumber));
523          return nextValueNumber++;
524        }
525      }
526
527      uint32_t v = lookup_or_add(cdep);
528      valueNumbering.insert(std::make_pair(V, v));
529      return v;
530
531    } else {
532      valueNumbering.insert(std::make_pair(V, nextValueNumber));
533      return nextValueNumber++;
534    }
535  } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
536    Expression e = create_expression(BO);
537
538    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
539    if (EI != expressionNumbering.end()) {
540      valueNumbering.insert(std::make_pair(V, EI->second));
541      return EI->second;
542    } else {
543      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
544      valueNumbering.insert(std::make_pair(V, nextValueNumber));
545
546      return nextValueNumber++;
547    }
548  } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
549    Expression e = create_expression(C);
550
551    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
552    if (EI != expressionNumbering.end()) {
553      valueNumbering.insert(std::make_pair(V, EI->second));
554      return EI->second;
555    } else {
556      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
557      valueNumbering.insert(std::make_pair(V, nextValueNumber));
558
559      return nextValueNumber++;
560    }
561  } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
562    Expression e = create_expression(U);
563
564    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
565    if (EI != expressionNumbering.end()) {
566      valueNumbering.insert(std::make_pair(V, EI->second));
567      return EI->second;
568    } else {
569      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
570      valueNumbering.insert(std::make_pair(V, nextValueNumber));
571
572      return nextValueNumber++;
573    }
574  } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
575    Expression e = create_expression(U);
576
577    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
578    if (EI != expressionNumbering.end()) {
579      valueNumbering.insert(std::make_pair(V, EI->second));
580      return EI->second;
581    } else {
582      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
583      valueNumbering.insert(std::make_pair(V, nextValueNumber));
584
585      return nextValueNumber++;
586    }
587  } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
588    Expression e = create_expression(U);
589
590    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
591    if (EI != expressionNumbering.end()) {
592      valueNumbering.insert(std::make_pair(V, EI->second));
593      return EI->second;
594    } else {
595      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
596      valueNumbering.insert(std::make_pair(V, nextValueNumber));
597
598      return nextValueNumber++;
599    }
600  } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
601    Expression e = create_expression(U);
602
603    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
604    if (EI != expressionNumbering.end()) {
605      valueNumbering.insert(std::make_pair(V, EI->second));
606      return EI->second;
607    } else {
608      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
609      valueNumbering.insert(std::make_pair(V, nextValueNumber));
610
611      return nextValueNumber++;
612    }
613  } else if (CastInst* U = dyn_cast<CastInst>(V)) {
614    Expression e = create_expression(U);
615
616    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
617    if (EI != expressionNumbering.end()) {
618      valueNumbering.insert(std::make_pair(V, EI->second));
619      return EI->second;
620    } else {
621      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
622      valueNumbering.insert(std::make_pair(V, nextValueNumber));
623
624      return nextValueNumber++;
625    }
626  } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
627    Expression e = create_expression(U);
628
629    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
630    if (EI != expressionNumbering.end()) {
631      valueNumbering.insert(std::make_pair(V, EI->second));
632      return EI->second;
633    } else {
634      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
635      valueNumbering.insert(std::make_pair(V, nextValueNumber));
636
637      return nextValueNumber++;
638    }
639  } else {
640    valueNumbering.insert(std::make_pair(V, nextValueNumber));
641    return nextValueNumber++;
642  }
643}
644
645/// lookup - Returns the value number of the specified value. Fails if
646/// the value has not yet been numbered.
647uint32_t ValueTable::lookup(Value* V) const {
648  DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
649  assert(VI != valueNumbering.end() && "Value not numbered?");
650  return VI->second;
651}
652
653/// clear - Remove all entries from the ValueTable
654void ValueTable::clear() {
655  valueNumbering.clear();
656  expressionNumbering.clear();
657  nextValueNumber = 1;
658}
659
660/// erase - Remove a value from the value numbering
661void ValueTable::erase(Value* V) {
662  valueNumbering.erase(V);
663}
664
665/// verifyRemoved - Verify that the value is removed from all internal data
666/// structures.
667void ValueTable::verifyRemoved(const Value *V) const {
668  for (DenseMap<Value*, uint32_t>::iterator
669         I = valueNumbering.begin(), E = valueNumbering.end(); I != E; ++I) {
670    assert(I->first != V && "Inst still occurs in value numbering map!");
671  }
672}
673
674//===----------------------------------------------------------------------===//
675//                                GVN Pass
676//===----------------------------------------------------------------------===//
677
678namespace {
679  struct VISIBILITY_HIDDEN ValueNumberScope {
680    ValueNumberScope* parent;
681    DenseMap<uint32_t, Value*> table;
682
683    ValueNumberScope(ValueNumberScope* p) : parent(p) { }
684  };
685}
686
687namespace {
688
689  class VISIBILITY_HIDDEN GVN : public FunctionPass {
690    bool runOnFunction(Function &F);
691  public:
692    static char ID; // Pass identification, replacement for typeid
693    GVN() : FunctionPass(&ID) { }
694
695  private:
696    MemoryDependenceAnalysis *MD;
697    DominatorTree *DT;
698
699    ValueTable VN;
700    DenseMap<BasicBlock*, ValueNumberScope*> localAvail;
701
702    typedef DenseMap<Value*, SmallPtrSet<Instruction*, 4> > PhiMapType;
703    PhiMapType phiMap;
704
705
706    // This transformation requires dominator postdominator info
707    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
708      AU.addRequired<DominatorTree>();
709      AU.addRequired<MemoryDependenceAnalysis>();
710      AU.addRequired<AliasAnalysis>();
711
712      AU.addPreserved<DominatorTree>();
713      AU.addPreserved<AliasAnalysis>();
714    }
715
716    // Helper fuctions
717    // FIXME: eliminate or document these better
718    bool processLoad(LoadInst* L,
719                     SmallVectorImpl<Instruction*> &toErase);
720    bool processInstruction(Instruction* I,
721                            SmallVectorImpl<Instruction*> &toErase);
722    bool processNonLocalLoad(LoadInst* L,
723                             SmallVectorImpl<Instruction*> &toErase);
724    bool processBlock(BasicBlock* BB);
725    Value *GetValueForBlock(BasicBlock *BB, Instruction* orig,
726                            DenseMap<BasicBlock*, Value*> &Phis,
727                            bool top_level = false);
728    void dump(DenseMap<uint32_t, Value*>& d);
729    bool iterateOnFunction(Function &F);
730    Value* CollapsePhi(PHINode* p);
731    bool isSafeReplacement(PHINode* p, Instruction* inst);
732    bool performPRE(Function& F);
733    Value* lookupNumber(BasicBlock* BB, uint32_t num);
734    bool mergeBlockIntoPredecessor(BasicBlock* BB);
735    Value* AttemptRedundancyElimination(Instruction* orig, unsigned valno);
736    void cleanupGlobalSets();
737    void verifyRemoved(const Instruction *I) const;
738  };
739
740  char GVN::ID = 0;
741}
742
743// createGVNPass - The public interface to this file...
744FunctionPass *llvm::createGVNPass() { return new GVN(); }
745
746static RegisterPass<GVN> X("gvn",
747                           "Global Value Numbering");
748
749void GVN::dump(DenseMap<uint32_t, Value*>& d) {
750  printf("{\n");
751  for (DenseMap<uint32_t, Value*>::iterator I = d.begin(),
752       E = d.end(); I != E; ++I) {
753      printf("%d\n", I->first);
754      I->second->dump();
755  }
756  printf("}\n");
757}
758
759Value* GVN::CollapsePhi(PHINode* p) {
760  Value* constVal = p->hasConstantValue();
761  if (!constVal) return 0;
762
763  Instruction* inst = dyn_cast<Instruction>(constVal);
764  if (!inst)
765    return constVal;
766
767  if (DT->dominates(inst, p))
768    if (isSafeReplacement(p, inst))
769      return inst;
770  return 0;
771}
772
773bool GVN::isSafeReplacement(PHINode* p, Instruction* inst) {
774  if (!isa<PHINode>(inst))
775    return true;
776
777  for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end();
778       UI != E; ++UI)
779    if (PHINode* use_phi = dyn_cast<PHINode>(UI))
780      if (use_phi->getParent() == inst->getParent())
781        return false;
782
783  return true;
784}
785
786/// GetValueForBlock - Get the value to use within the specified basic block.
787/// available values are in Phis.
788Value *GVN::GetValueForBlock(BasicBlock *BB, Instruction* orig,
789                             DenseMap<BasicBlock*, Value*> &Phis,
790                             bool top_level) {
791
792  // If we have already computed this value, return the previously computed val.
793  DenseMap<BasicBlock*, Value*>::iterator V = Phis.find(BB);
794  if (V != Phis.end() && !top_level) return V->second;
795
796  // If the block is unreachable, just return undef, since this path
797  // can't actually occur at runtime.
798  if (!DT->isReachableFromEntry(BB))
799    return Phis[BB] = Context->getUndef(orig->getType());
800
801  if (BasicBlock *Pred = BB->getSinglePredecessor()) {
802    Value *ret = GetValueForBlock(Pred, orig, Phis);
803    Phis[BB] = ret;
804    return ret;
805  }
806
807  // Get the number of predecessors of this block so we can reserve space later.
808  // If there is already a PHI in it, use the #preds from it, otherwise count.
809  // Getting it from the PHI is constant time.
810  unsigned NumPreds;
811  if (PHINode *ExistingPN = dyn_cast<PHINode>(BB->begin()))
812    NumPreds = ExistingPN->getNumIncomingValues();
813  else
814    NumPreds = std::distance(pred_begin(BB), pred_end(BB));
815
816  // Otherwise, the idom is the loop, so we need to insert a PHI node.  Do so
817  // now, then get values to fill in the incoming values for the PHI.
818  PHINode *PN = PHINode::Create(orig->getType(), orig->getName()+".rle",
819                                BB->begin());
820  PN->reserveOperandSpace(NumPreds);
821
822  Phis.insert(std::make_pair(BB, PN));
823
824  // Fill in the incoming values for the block.
825  for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
826    Value* val = GetValueForBlock(*PI, orig, Phis);
827    PN->addIncoming(val, *PI);
828  }
829
830  VN.getAliasAnalysis()->copyValue(orig, PN);
831
832  // Attempt to collapse PHI nodes that are trivially redundant
833  Value* v = CollapsePhi(PN);
834  if (!v) {
835    // Cache our phi construction results
836    if (LoadInst* L = dyn_cast<LoadInst>(orig))
837      phiMap[L->getPointerOperand()].insert(PN);
838    else
839      phiMap[orig].insert(PN);
840
841    return PN;
842  }
843
844  PN->replaceAllUsesWith(v);
845  if (isa<PointerType>(v->getType()))
846    MD->invalidateCachedPointerInfo(v);
847
848  for (DenseMap<BasicBlock*, Value*>::iterator I = Phis.begin(),
849       E = Phis.end(); I != E; ++I)
850    if (I->second == PN)
851      I->second = v;
852
853  DEBUG(cerr << "GVN removed: " << *PN);
854  MD->removeInstruction(PN);
855  PN->eraseFromParent();
856  DEBUG(verifyRemoved(PN));
857
858  Phis[BB] = v;
859  return v;
860}
861
862/// IsValueFullyAvailableInBlock - Return true if we can prove that the value
863/// we're analyzing is fully available in the specified block.  As we go, keep
864/// track of which blocks we know are fully alive in FullyAvailableBlocks.  This
865/// map is actually a tri-state map with the following values:
866///   0) we know the block *is not* fully available.
867///   1) we know the block *is* fully available.
868///   2) we do not know whether the block is fully available or not, but we are
869///      currently speculating that it will be.
870///   3) we are speculating for this block and have used that to speculate for
871///      other blocks.
872static bool IsValueFullyAvailableInBlock(BasicBlock *BB,
873                            DenseMap<BasicBlock*, char> &FullyAvailableBlocks) {
874  // Optimistically assume that the block is fully available and check to see
875  // if we already know about this block in one lookup.
876  std::pair<DenseMap<BasicBlock*, char>::iterator, char> IV =
877    FullyAvailableBlocks.insert(std::make_pair(BB, 2));
878
879  // If the entry already existed for this block, return the precomputed value.
880  if (!IV.second) {
881    // If this is a speculative "available" value, mark it as being used for
882    // speculation of other blocks.
883    if (IV.first->second == 2)
884      IV.first->second = 3;
885    return IV.first->second != 0;
886  }
887
888  // Otherwise, see if it is fully available in all predecessors.
889  pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
890
891  // If this block has no predecessors, it isn't live-in here.
892  if (PI == PE)
893    goto SpeculationFailure;
894
895  for (; PI != PE; ++PI)
896    // If the value isn't fully available in one of our predecessors, then it
897    // isn't fully available in this block either.  Undo our previous
898    // optimistic assumption and bail out.
899    if (!IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks))
900      goto SpeculationFailure;
901
902  return true;
903
904// SpeculationFailure - If we get here, we found out that this is not, after
905// all, a fully-available block.  We have a problem if we speculated on this and
906// used the speculation to mark other blocks as available.
907SpeculationFailure:
908  char &BBVal = FullyAvailableBlocks[BB];
909
910  // If we didn't speculate on this, just return with it set to false.
911  if (BBVal == 2) {
912    BBVal = 0;
913    return false;
914  }
915
916  // If we did speculate on this value, we could have blocks set to 1 that are
917  // incorrect.  Walk the (transitive) successors of this block and mark them as
918  // 0 if set to one.
919  SmallVector<BasicBlock*, 32> BBWorklist;
920  BBWorklist.push_back(BB);
921
922  while (!BBWorklist.empty()) {
923    BasicBlock *Entry = BBWorklist.pop_back_val();
924    // Note that this sets blocks to 0 (unavailable) if they happen to not
925    // already be in FullyAvailableBlocks.  This is safe.
926    char &EntryVal = FullyAvailableBlocks[Entry];
927    if (EntryVal == 0) continue;  // Already unavailable.
928
929    // Mark as unavailable.
930    EntryVal = 0;
931
932    for (succ_iterator I = succ_begin(Entry), E = succ_end(Entry); I != E; ++I)
933      BBWorklist.push_back(*I);
934  }
935
936  return false;
937}
938
939/// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
940/// non-local by performing PHI construction.
941bool GVN::processNonLocalLoad(LoadInst *LI,
942                              SmallVectorImpl<Instruction*> &toErase) {
943  // Find the non-local dependencies of the load.
944  SmallVector<MemoryDependenceAnalysis::NonLocalDepEntry, 64> Deps;
945  MD->getNonLocalPointerDependency(LI->getOperand(0), true, LI->getParent(),
946                                   Deps);
947  //DEBUG(cerr << "INVESTIGATING NONLOCAL LOAD: " << Deps.size() << *LI);
948
949  // If we had to process more than one hundred blocks to find the
950  // dependencies, this load isn't worth worrying about.  Optimizing
951  // it will be too expensive.
952  if (Deps.size() > 100)
953    return false;
954
955  // If we had a phi translation failure, we'll have a single entry which is a
956  // clobber in the current block.  Reject this early.
957  if (Deps.size() == 1 && Deps[0].second.isClobber()) {
958    DEBUG(
959      DOUT << "GVN: non-local load ";
960      WriteAsOperand(*DOUT.stream(), LI);
961      DOUT << " is clobbered by " << *Deps[0].second.getInst();
962    );
963    return false;
964  }
965
966  // Filter out useless results (non-locals, etc).  Keep track of the blocks
967  // where we have a value available in repl, also keep track of whether we see
968  // dependencies that produce an unknown value for the load (such as a call
969  // that could potentially clobber the load).
970  SmallVector<std::pair<BasicBlock*, Value*>, 16> ValuesPerBlock;
971  SmallVector<BasicBlock*, 16> UnavailableBlocks;
972
973  for (unsigned i = 0, e = Deps.size(); i != e; ++i) {
974    BasicBlock *DepBB = Deps[i].first;
975    MemDepResult DepInfo = Deps[i].second;
976
977    if (DepInfo.isClobber()) {
978      UnavailableBlocks.push_back(DepBB);
979      continue;
980    }
981
982    Instruction *DepInst = DepInfo.getInst();
983
984    // Loading the allocation -> undef.
985    if (isa<AllocationInst>(DepInst)) {
986      ValuesPerBlock.push_back(std::make_pair(DepBB,
987                                            Context->getUndef(LI->getType())));
988      continue;
989    }
990
991    if (StoreInst* S = dyn_cast<StoreInst>(DepInst)) {
992      // Reject loads and stores that are to the same address but are of
993      // different types.
994      // NOTE: 403.gcc does have this case (e.g. in readonly_fields_p) because
995      // of bitfield access, it would be interesting to optimize for it at some
996      // point.
997      if (S->getOperand(0)->getType() != LI->getType()) {
998        UnavailableBlocks.push_back(DepBB);
999        continue;
1000      }
1001
1002      ValuesPerBlock.push_back(std::make_pair(DepBB, S->getOperand(0)));
1003
1004    } else if (LoadInst* LD = dyn_cast<LoadInst>(DepInst)) {
1005      if (LD->getType() != LI->getType()) {
1006        UnavailableBlocks.push_back(DepBB);
1007        continue;
1008      }
1009      ValuesPerBlock.push_back(std::make_pair(DepBB, LD));
1010    } else {
1011      UnavailableBlocks.push_back(DepBB);
1012      continue;
1013    }
1014  }
1015
1016  // If we have no predecessors that produce a known value for this load, exit
1017  // early.
1018  if (ValuesPerBlock.empty()) return false;
1019
1020  // If all of the instructions we depend on produce a known value for this
1021  // load, then it is fully redundant and we can use PHI insertion to compute
1022  // its value.  Insert PHIs and remove the fully redundant value now.
1023  if (UnavailableBlocks.empty()) {
1024    // Use cached PHI construction information from previous runs
1025    SmallPtrSet<Instruction*, 4> &p = phiMap[LI->getPointerOperand()];
1026    // FIXME: What does phiMap do? Are we positive it isn't getting invalidated?
1027    for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
1028         I != E; ++I) {
1029      if ((*I)->getParent() == LI->getParent()) {
1030        DEBUG(cerr << "GVN REMOVING NONLOCAL LOAD #1: " << *LI);
1031        LI->replaceAllUsesWith(*I);
1032        if (isa<PointerType>((*I)->getType()))
1033          MD->invalidateCachedPointerInfo(*I);
1034        toErase.push_back(LI);
1035        NumGVNLoad++;
1036        return true;
1037      }
1038
1039      ValuesPerBlock.push_back(std::make_pair((*I)->getParent(), *I));
1040    }
1041
1042    DEBUG(cerr << "GVN REMOVING NONLOCAL LOAD: " << *LI);
1043
1044    DenseMap<BasicBlock*, Value*> BlockReplValues;
1045    BlockReplValues.insert(ValuesPerBlock.begin(), ValuesPerBlock.end());
1046    // Perform PHI construction.
1047    Value* v = GetValueForBlock(LI->getParent(), LI, BlockReplValues, true);
1048    LI->replaceAllUsesWith(v);
1049
1050    if (isa<PHINode>(v))
1051      v->takeName(LI);
1052    if (isa<PointerType>(v->getType()))
1053      MD->invalidateCachedPointerInfo(v);
1054    toErase.push_back(LI);
1055    NumGVNLoad++;
1056    return true;
1057  }
1058
1059  if (!EnablePRE || !EnableLoadPRE)
1060    return false;
1061
1062  // Okay, we have *some* definitions of the value.  This means that the value
1063  // is available in some of our (transitive) predecessors.  Lets think about
1064  // doing PRE of this load.  This will involve inserting a new load into the
1065  // predecessor when it's not available.  We could do this in general, but
1066  // prefer to not increase code size.  As such, we only do this when we know
1067  // that we only have to insert *one* load (which means we're basically moving
1068  // the load, not inserting a new one).
1069
1070  SmallPtrSet<BasicBlock *, 4> Blockers;
1071  for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1072    Blockers.insert(UnavailableBlocks[i]);
1073
1074  // Lets find first basic block with more than one predecessor.  Walk backwards
1075  // through predecessors if needed.
1076  BasicBlock *LoadBB = LI->getParent();
1077  BasicBlock *TmpBB = LoadBB;
1078
1079  bool isSinglePred = false;
1080  bool allSingleSucc = true;
1081  while (TmpBB->getSinglePredecessor()) {
1082    isSinglePred = true;
1083    TmpBB = TmpBB->getSinglePredecessor();
1084    if (!TmpBB) // If haven't found any, bail now.
1085      return false;
1086    if (TmpBB == LoadBB) // Infinite (unreachable) loop.
1087      return false;
1088    if (Blockers.count(TmpBB))
1089      return false;
1090    if (TmpBB->getTerminator()->getNumSuccessors() != 1)
1091      allSingleSucc = false;
1092  }
1093
1094  assert(TmpBB);
1095  LoadBB = TmpBB;
1096
1097  // If we have a repl set with LI itself in it, this means we have a loop where
1098  // at least one of the values is LI.  Since this means that we won't be able
1099  // to eliminate LI even if we insert uses in the other predecessors, we will
1100  // end up increasing code size.  Reject this by scanning for LI.
1101  for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
1102    if (ValuesPerBlock[i].second == LI)
1103      return false;
1104
1105  if (isSinglePred) {
1106    bool isHot = false;
1107    for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
1108      if (Instruction *I = dyn_cast<Instruction>(ValuesPerBlock[i].second))
1109	// "Hot" Instruction is in some loop (because it dominates its dep.
1110	// instruction).
1111	if (DT->dominates(LI, I)) {
1112	  isHot = true;
1113	  break;
1114	}
1115
1116    // We are interested only in "hot" instructions. We don't want to do any
1117    // mis-optimizations here.
1118    if (!isHot)
1119      return false;
1120  }
1121
1122  // Okay, we have some hope :).  Check to see if the loaded value is fully
1123  // available in all but one predecessor.
1124  // FIXME: If we could restructure the CFG, we could make a common pred with
1125  // all the preds that don't have an available LI and insert a new load into
1126  // that one block.
1127  BasicBlock *UnavailablePred = 0;
1128
1129  DenseMap<BasicBlock*, char> FullyAvailableBlocks;
1130  for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
1131    FullyAvailableBlocks[ValuesPerBlock[i].first] = true;
1132  for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1133    FullyAvailableBlocks[UnavailableBlocks[i]] = false;
1134
1135  for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB);
1136       PI != E; ++PI) {
1137    if (IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks))
1138      continue;
1139
1140    // If this load is not available in multiple predecessors, reject it.
1141    if (UnavailablePred && UnavailablePred != *PI)
1142      return false;
1143    UnavailablePred = *PI;
1144  }
1145
1146  assert(UnavailablePred != 0 &&
1147         "Fully available value should be eliminated above!");
1148
1149  // If the loaded pointer is PHI node defined in this block, do PHI translation
1150  // to get its value in the predecessor.
1151  Value *LoadPtr = LI->getOperand(0)->DoPHITranslation(LoadBB, UnavailablePred);
1152
1153  // Make sure the value is live in the predecessor.  If it was defined by a
1154  // non-PHI instruction in this block, we don't know how to recompute it above.
1155  if (Instruction *LPInst = dyn_cast<Instruction>(LoadPtr))
1156    if (!DT->dominates(LPInst->getParent(), UnavailablePred)) {
1157      DEBUG(cerr << "COULDN'T PRE LOAD BECAUSE PTR IS UNAVAILABLE IN PRED: "
1158                 << *LPInst << *LI << "\n");
1159      return false;
1160    }
1161
1162  // We don't currently handle critical edges :(
1163  if (UnavailablePred->getTerminator()->getNumSuccessors() != 1) {
1164    DEBUG(cerr << "COULD NOT PRE LOAD BECAUSE OF CRITICAL EDGE '"
1165                << UnavailablePred->getName() << "': " << *LI);
1166    return false;
1167  }
1168
1169  // Make sure it is valid to move this load here.  We have to watch out for:
1170  //  @1 = getelementptr (i8* p, ...
1171  //  test p and branch if == 0
1172  //  load @1
1173  // It is valid to have the getelementptr before the test, even if p can be 0,
1174  // as getelementptr only does address arithmetic.
1175  // If we are not pushing the value through any multiple-successor blocks
1176  // we do not have this case.  Otherwise, check that the load is safe to
1177  // put anywhere; this can be improved, but should be conservatively safe.
1178  if (!allSingleSucc &&
1179      !isSafeToLoadUnconditionally(LoadPtr, UnavailablePred->getTerminator()))
1180    return false;
1181
1182  // Okay, we can eliminate this load by inserting a reload in the predecessor
1183  // and using PHI construction to get the value in the other predecessors, do
1184  // it.
1185  DEBUG(cerr << "GVN REMOVING PRE LOAD: " << *LI);
1186
1187  Value *NewLoad = new LoadInst(LoadPtr, LI->getName()+".pre", false,
1188                                LI->getAlignment(),
1189                                UnavailablePred->getTerminator());
1190
1191  SmallPtrSet<Instruction*, 4> &p = phiMap[LI->getPointerOperand()];
1192  for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
1193       I != E; ++I)
1194    ValuesPerBlock.push_back(std::make_pair((*I)->getParent(), *I));
1195
1196  DenseMap<BasicBlock*, Value*> BlockReplValues;
1197  BlockReplValues.insert(ValuesPerBlock.begin(), ValuesPerBlock.end());
1198  BlockReplValues[UnavailablePred] = NewLoad;
1199
1200  // Perform PHI construction.
1201  Value* v = GetValueForBlock(LI->getParent(), LI, BlockReplValues, true);
1202  LI->replaceAllUsesWith(v);
1203  if (isa<PHINode>(v))
1204    v->takeName(LI);
1205  if (isa<PointerType>(v->getType()))
1206    MD->invalidateCachedPointerInfo(v);
1207  toErase.push_back(LI);
1208  NumPRELoad++;
1209  return true;
1210}
1211
1212/// processLoad - Attempt to eliminate a load, first by eliminating it
1213/// locally, and then attempting non-local elimination if that fails.
1214bool GVN::processLoad(LoadInst *L, SmallVectorImpl<Instruction*> &toErase) {
1215  if (L->isVolatile())
1216    return false;
1217
1218  Value* pointer = L->getPointerOperand();
1219
1220  // ... to a pointer that has been loaded from before...
1221  MemDepResult dep = MD->getDependency(L);
1222
1223  // If the value isn't available, don't do anything!
1224  if (dep.isClobber()) {
1225    DEBUG(
1226      // fast print dep, using operator<< on instruction would be too slow
1227      DOUT << "GVN: load ";
1228      WriteAsOperand(*DOUT.stream(), L);
1229      Instruction *I = dep.getInst();
1230      DOUT << " is clobbered by " << *I;
1231    );
1232    return false;
1233  }
1234
1235  // If it is defined in another block, try harder.
1236  if (dep.isNonLocal())
1237    return processNonLocalLoad(L, toErase);
1238
1239  Instruction *DepInst = dep.getInst();
1240  if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInst)) {
1241    // Only forward substitute stores to loads of the same type.
1242    // FIXME: Could do better!
1243    if (DepSI->getPointerOperand()->getType() != pointer->getType())
1244      return false;
1245
1246    // Remove it!
1247    L->replaceAllUsesWith(DepSI->getOperand(0));
1248    if (isa<PointerType>(DepSI->getOperand(0)->getType()))
1249      MD->invalidateCachedPointerInfo(DepSI->getOperand(0));
1250    toErase.push_back(L);
1251    NumGVNLoad++;
1252    return true;
1253  }
1254
1255  if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInst)) {
1256    // Only forward substitute stores to loads of the same type.
1257    // FIXME: Could do better! load i32 -> load i8 -> truncate on little endian.
1258    if (DepLI->getType() != L->getType())
1259      return false;
1260
1261    // Remove it!
1262    L->replaceAllUsesWith(DepLI);
1263    if (isa<PointerType>(DepLI->getType()))
1264      MD->invalidateCachedPointerInfo(DepLI);
1265    toErase.push_back(L);
1266    NumGVNLoad++;
1267    return true;
1268  }
1269
1270  // If this load really doesn't depend on anything, then we must be loading an
1271  // undef value.  This can happen when loading for a fresh allocation with no
1272  // intervening stores, for example.
1273  if (isa<AllocationInst>(DepInst)) {
1274    L->replaceAllUsesWith(Context->getUndef(L->getType()));
1275    toErase.push_back(L);
1276    NumGVNLoad++;
1277    return true;
1278  }
1279
1280  return false;
1281}
1282
1283Value* GVN::lookupNumber(BasicBlock* BB, uint32_t num) {
1284  DenseMap<BasicBlock*, ValueNumberScope*>::iterator I = localAvail.find(BB);
1285  if (I == localAvail.end())
1286    return 0;
1287
1288  ValueNumberScope* locals = I->second;
1289
1290  while (locals) {
1291    DenseMap<uint32_t, Value*>::iterator I = locals->table.find(num);
1292    if (I != locals->table.end())
1293      return I->second;
1294    else
1295      locals = locals->parent;
1296  }
1297
1298  return 0;
1299}
1300
1301/// AttemptRedundancyElimination - If the "fast path" of redundancy elimination
1302/// by inheritance from the dominator fails, see if we can perform phi
1303/// construction to eliminate the redundancy.
1304Value* GVN::AttemptRedundancyElimination(Instruction* orig, unsigned valno) {
1305  BasicBlock* BaseBlock = orig->getParent();
1306
1307  SmallPtrSet<BasicBlock*, 4> Visited;
1308  SmallVector<BasicBlock*, 8> Stack;
1309  Stack.push_back(BaseBlock);
1310
1311  DenseMap<BasicBlock*, Value*> Results;
1312
1313  // Walk backwards through our predecessors, looking for instances of the
1314  // value number we're looking for.  Instances are recorded in the Results
1315  // map, which is then used to perform phi construction.
1316  while (!Stack.empty()) {
1317    BasicBlock* Current = Stack.back();
1318    Stack.pop_back();
1319
1320    // If we've walked all the way to a proper dominator, then give up. Cases
1321    // where the instance is in the dominator will have been caught by the fast
1322    // path, and any cases that require phi construction further than this are
1323    // probably not worth it anyways.  Note that this is a SIGNIFICANT compile
1324    // time improvement.
1325    if (DT->properlyDominates(Current, orig->getParent())) return 0;
1326
1327    DenseMap<BasicBlock*, ValueNumberScope*>::iterator LA =
1328                                                       localAvail.find(Current);
1329    if (LA == localAvail.end()) return 0;
1330    DenseMap<uint32_t, Value*>::iterator V = LA->second->table.find(valno);
1331
1332    if (V != LA->second->table.end()) {
1333      // Found an instance, record it.
1334      Results.insert(std::make_pair(Current, V->second));
1335      continue;
1336    }
1337
1338    // If we reach the beginning of the function, then give up.
1339    if (pred_begin(Current) == pred_end(Current))
1340      return 0;
1341
1342    for (pred_iterator PI = pred_begin(Current), PE = pred_end(Current);
1343         PI != PE; ++PI)
1344      if (Visited.insert(*PI))
1345        Stack.push_back(*PI);
1346  }
1347
1348  // If we didn't find instances, give up.  Otherwise, perform phi construction.
1349  if (Results.size() == 0)
1350    return 0;
1351  else
1352    return GetValueForBlock(BaseBlock, orig, Results, true);
1353}
1354
1355/// processInstruction - When calculating availability, handle an instruction
1356/// by inserting it into the appropriate sets
1357bool GVN::processInstruction(Instruction *I,
1358                             SmallVectorImpl<Instruction*> &toErase) {
1359  if (LoadInst* L = dyn_cast<LoadInst>(I)) {
1360    bool changed = processLoad(L, toErase);
1361
1362    if (!changed) {
1363      unsigned num = VN.lookup_or_add(L);
1364      localAvail[I->getParent()]->table.insert(std::make_pair(num, L));
1365    }
1366
1367    return changed;
1368  }
1369
1370  uint32_t nextNum = VN.getNextUnusedValueNumber();
1371  unsigned num = VN.lookup_or_add(I);
1372
1373  if (BranchInst* BI = dyn_cast<BranchInst>(I)) {
1374    localAvail[I->getParent()]->table.insert(std::make_pair(num, I));
1375
1376    if (!BI->isConditional() || isa<Constant>(BI->getCondition()))
1377      return false;
1378
1379    Value* branchCond = BI->getCondition();
1380    uint32_t condVN = VN.lookup_or_add(branchCond);
1381
1382    BasicBlock* trueSucc = BI->getSuccessor(0);
1383    BasicBlock* falseSucc = BI->getSuccessor(1);
1384
1385    if (trueSucc->getSinglePredecessor())
1386      localAvail[trueSucc]->table[condVN] = Context->getConstantIntTrue();
1387    if (falseSucc->getSinglePredecessor())
1388      localAvail[falseSucc]->table[condVN] = Context->getConstantIntFalse();
1389
1390    return false;
1391
1392  // Allocations are always uniquely numbered, so we can save time and memory
1393  // by fast failing them.
1394  } else if (isa<AllocationInst>(I) || isa<TerminatorInst>(I)) {
1395    localAvail[I->getParent()]->table.insert(std::make_pair(num, I));
1396    return false;
1397  }
1398
1399  // Collapse PHI nodes
1400  if (PHINode* p = dyn_cast<PHINode>(I)) {
1401    Value* constVal = CollapsePhi(p);
1402
1403    if (constVal) {
1404      for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end();
1405           PI != PE; ++PI)
1406        PI->second.erase(p);
1407
1408      p->replaceAllUsesWith(constVal);
1409      if (isa<PointerType>(constVal->getType()))
1410        MD->invalidateCachedPointerInfo(constVal);
1411      VN.erase(p);
1412
1413      toErase.push_back(p);
1414    } else {
1415      localAvail[I->getParent()]->table.insert(std::make_pair(num, I));
1416    }
1417
1418  // If the number we were assigned was a brand new VN, then we don't
1419  // need to do a lookup to see if the number already exists
1420  // somewhere in the domtree: it can't!
1421  } else if (num == nextNum) {
1422    localAvail[I->getParent()]->table.insert(std::make_pair(num, I));
1423
1424  // Perform fast-path value-number based elimination of values inherited from
1425  // dominators.
1426  } else if (Value* repl = lookupNumber(I->getParent(), num)) {
1427    // Remove it!
1428    VN.erase(I);
1429    I->replaceAllUsesWith(repl);
1430    if (isa<PointerType>(repl->getType()))
1431      MD->invalidateCachedPointerInfo(repl);
1432    toErase.push_back(I);
1433    return true;
1434
1435#if 0
1436  // Perform slow-pathvalue-number based elimination with phi construction.
1437  } else if (Value* repl = AttemptRedundancyElimination(I, num)) {
1438    // Remove it!
1439    VN.erase(I);
1440    I->replaceAllUsesWith(repl);
1441    if (isa<PointerType>(repl->getType()))
1442      MD->invalidateCachedPointerInfo(repl);
1443    toErase.push_back(I);
1444    return true;
1445#endif
1446  } else {
1447    localAvail[I->getParent()]->table.insert(std::make_pair(num, I));
1448  }
1449
1450  return false;
1451}
1452
1453/// runOnFunction - This is the main transformation entry point for a function.
1454bool GVN::runOnFunction(Function& F) {
1455  MD = &getAnalysis<MemoryDependenceAnalysis>();
1456  DT = &getAnalysis<DominatorTree>();
1457  VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
1458  VN.setMemDep(MD);
1459  VN.setDomTree(DT);
1460
1461  bool changed = false;
1462  bool shouldContinue = true;
1463
1464  // Merge unconditional branches, allowing PRE to catch more
1465  // optimization opportunities.
1466  for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) {
1467    BasicBlock* BB = FI;
1468    ++FI;
1469    bool removedBlock = MergeBlockIntoPredecessor(BB, this);
1470    if (removedBlock) NumGVNBlocks++;
1471
1472    changed |= removedBlock;
1473  }
1474
1475  unsigned Iteration = 0;
1476
1477  while (shouldContinue) {
1478    DEBUG(cerr << "GVN iteration: " << Iteration << "\n");
1479    shouldContinue = iterateOnFunction(F);
1480    changed |= shouldContinue;
1481    ++Iteration;
1482  }
1483
1484  if (EnablePRE) {
1485    bool PREChanged = true;
1486    while (PREChanged) {
1487      PREChanged = performPRE(F);
1488      changed |= PREChanged;
1489    }
1490  }
1491  // FIXME: Should perform GVN again after PRE does something.  PRE can move
1492  // computations into blocks where they become fully redundant.  Note that
1493  // we can't do this until PRE's critical edge splitting updates memdep.
1494  // Actually, when this happens, we should just fully integrate PRE into GVN.
1495
1496  cleanupGlobalSets();
1497
1498  return changed;
1499}
1500
1501
1502bool GVN::processBlock(BasicBlock* BB) {
1503  // FIXME: Kill off toErase by doing erasing eagerly in a helper function (and
1504  // incrementing BI before processing an instruction).
1505  SmallVector<Instruction*, 8> toErase;
1506  bool changed_function = false;
1507
1508  for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1509       BI != BE;) {
1510    changed_function |= processInstruction(BI, toErase);
1511    if (toErase.empty()) {
1512      ++BI;
1513      continue;
1514    }
1515
1516    // If we need some instructions deleted, do it now.
1517    NumGVNInstr += toErase.size();
1518
1519    // Avoid iterator invalidation.
1520    bool AtStart = BI == BB->begin();
1521    if (!AtStart)
1522      --BI;
1523
1524    for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
1525         E = toErase.end(); I != E; ++I) {
1526      DEBUG(cerr << "GVN removed: " << **I);
1527      MD->removeInstruction(*I);
1528      (*I)->eraseFromParent();
1529      DEBUG(verifyRemoved(*I));
1530    }
1531    toErase.clear();
1532
1533    if (AtStart)
1534      BI = BB->begin();
1535    else
1536      ++BI;
1537  }
1538
1539  return changed_function;
1540}
1541
1542/// performPRE - Perform a purely local form of PRE that looks for diamond
1543/// control flow patterns and attempts to perform simple PRE at the join point.
1544bool GVN::performPRE(Function& F) {
1545  bool Changed = false;
1546  SmallVector<std::pair<TerminatorInst*, unsigned>, 4> toSplit;
1547  DenseMap<BasicBlock*, Value*> predMap;
1548  for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
1549       DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
1550    BasicBlock* CurrentBlock = *DI;
1551
1552    // Nothing to PRE in the entry block.
1553    if (CurrentBlock == &F.getEntryBlock()) continue;
1554
1555    for (BasicBlock::iterator BI = CurrentBlock->begin(),
1556         BE = CurrentBlock->end(); BI != BE; ) {
1557      Instruction *CurInst = BI++;
1558
1559      if (isa<AllocationInst>(CurInst) || isa<TerminatorInst>(CurInst) ||
1560          isa<PHINode>(CurInst) || (CurInst->getType() == Type::VoidTy) ||
1561          CurInst->mayReadFromMemory() || CurInst->mayHaveSideEffects() ||
1562          isa<DbgInfoIntrinsic>(CurInst))
1563        continue;
1564
1565      uint32_t valno = VN.lookup(CurInst);
1566
1567      // Look for the predecessors for PRE opportunities.  We're
1568      // only trying to solve the basic diamond case, where
1569      // a value is computed in the successor and one predecessor,
1570      // but not the other.  We also explicitly disallow cases
1571      // where the successor is its own predecessor, because they're
1572      // more complicated to get right.
1573      unsigned numWith = 0;
1574      unsigned numWithout = 0;
1575      BasicBlock* PREPred = 0;
1576      predMap.clear();
1577
1578      for (pred_iterator PI = pred_begin(CurrentBlock),
1579           PE = pred_end(CurrentBlock); PI != PE; ++PI) {
1580        // We're not interested in PRE where the block is its
1581        // own predecessor, on in blocks with predecessors
1582        // that are not reachable.
1583        if (*PI == CurrentBlock) {
1584          numWithout = 2;
1585          break;
1586        } else if (!localAvail.count(*PI))  {
1587          numWithout = 2;
1588          break;
1589        }
1590
1591        DenseMap<uint32_t, Value*>::iterator predV =
1592                                            localAvail[*PI]->table.find(valno);
1593        if (predV == localAvail[*PI]->table.end()) {
1594          PREPred = *PI;
1595          numWithout++;
1596        } else if (predV->second == CurInst) {
1597          numWithout = 2;
1598        } else {
1599          predMap[*PI] = predV->second;
1600          numWith++;
1601        }
1602      }
1603
1604      // Don't do PRE when it might increase code size, i.e. when
1605      // we would need to insert instructions in more than one pred.
1606      if (numWithout != 1 || numWith == 0)
1607        continue;
1608
1609      // We can't do PRE safely on a critical edge, so instead we schedule
1610      // the edge to be split and perform the PRE the next time we iterate
1611      // on the function.
1612      unsigned succNum = 0;
1613      for (unsigned i = 0, e = PREPred->getTerminator()->getNumSuccessors();
1614           i != e; ++i)
1615        if (PREPred->getTerminator()->getSuccessor(i) == CurrentBlock) {
1616          succNum = i;
1617          break;
1618        }
1619
1620      if (isCriticalEdge(PREPred->getTerminator(), succNum)) {
1621        toSplit.push_back(std::make_pair(PREPred->getTerminator(), succNum));
1622        continue;
1623      }
1624
1625      // Instantiate the expression the in predecessor that lacked it.
1626      // Because we are going top-down through the block, all value numbers
1627      // will be available in the predecessor by the time we need them.  Any
1628      // that weren't original present will have been instantiated earlier
1629      // in this loop.
1630      Instruction* PREInstr = CurInst->clone(*Context);
1631      bool success = true;
1632      for (unsigned i = 0, e = CurInst->getNumOperands(); i != e; ++i) {
1633        Value *Op = PREInstr->getOperand(i);
1634        if (isa<Argument>(Op) || isa<Constant>(Op) || isa<GlobalValue>(Op))
1635          continue;
1636
1637        if (Value *V = lookupNumber(PREPred, VN.lookup(Op))) {
1638          PREInstr->setOperand(i, V);
1639        } else {
1640          success = false;
1641          break;
1642        }
1643      }
1644
1645      // Fail out if we encounter an operand that is not available in
1646      // the PRE predecessor.  This is typically because of loads which
1647      // are not value numbered precisely.
1648      if (!success) {
1649        delete PREInstr;
1650        DEBUG(verifyRemoved(PREInstr));
1651        continue;
1652      }
1653
1654      PREInstr->insertBefore(PREPred->getTerminator());
1655      PREInstr->setName(CurInst->getName() + ".pre");
1656      predMap[PREPred] = PREInstr;
1657      VN.add(PREInstr, valno);
1658      NumGVNPRE++;
1659
1660      // Update the availability map to include the new instruction.
1661      localAvail[PREPred]->table.insert(std::make_pair(valno, PREInstr));
1662
1663      // Create a PHI to make the value available in this block.
1664      PHINode* Phi = PHINode::Create(CurInst->getType(),
1665                                     CurInst->getName() + ".pre-phi",
1666                                     CurrentBlock->begin());
1667      for (pred_iterator PI = pred_begin(CurrentBlock),
1668           PE = pred_end(CurrentBlock); PI != PE; ++PI)
1669        Phi->addIncoming(predMap[*PI], *PI);
1670
1671      VN.add(Phi, valno);
1672      localAvail[CurrentBlock]->table[valno] = Phi;
1673
1674      CurInst->replaceAllUsesWith(Phi);
1675      if (isa<PointerType>(Phi->getType()))
1676        MD->invalidateCachedPointerInfo(Phi);
1677      VN.erase(CurInst);
1678
1679      DEBUG(cerr << "GVN PRE removed: " << *CurInst);
1680      MD->removeInstruction(CurInst);
1681      CurInst->eraseFromParent();
1682      DEBUG(verifyRemoved(CurInst));
1683      Changed = true;
1684    }
1685  }
1686
1687  for (SmallVector<std::pair<TerminatorInst*, unsigned>, 4>::iterator
1688       I = toSplit.begin(), E = toSplit.end(); I != E; ++I)
1689    SplitCriticalEdge(I->first, I->second, this);
1690
1691  return Changed || toSplit.size();
1692}
1693
1694/// iterateOnFunction - Executes one iteration of GVN
1695bool GVN::iterateOnFunction(Function &F) {
1696  cleanupGlobalSets();
1697
1698  for (df_iterator<DomTreeNode*> DI = df_begin(DT->getRootNode()),
1699       DE = df_end(DT->getRootNode()); DI != DE; ++DI) {
1700    if (DI->getIDom())
1701      localAvail[DI->getBlock()] =
1702                   new ValueNumberScope(localAvail[DI->getIDom()->getBlock()]);
1703    else
1704      localAvail[DI->getBlock()] = new ValueNumberScope(0);
1705  }
1706
1707  // Top-down walk of the dominator tree
1708  bool changed = false;
1709#if 0
1710  // Needed for value numbering with phi construction to work.
1711  ReversePostOrderTraversal<Function*> RPOT(&F);
1712  for (ReversePostOrderTraversal<Function*>::rpo_iterator RI = RPOT.begin(),
1713       RE = RPOT.end(); RI != RE; ++RI)
1714    changed |= processBlock(*RI);
1715#else
1716  for (df_iterator<DomTreeNode*> DI = df_begin(DT->getRootNode()),
1717       DE = df_end(DT->getRootNode()); DI != DE; ++DI)
1718    changed |= processBlock(DI->getBlock());
1719#endif
1720
1721  return changed;
1722}
1723
1724void GVN::cleanupGlobalSets() {
1725  VN.clear();
1726  phiMap.clear();
1727
1728  for (DenseMap<BasicBlock*, ValueNumberScope*>::iterator
1729       I = localAvail.begin(), E = localAvail.end(); I != E; ++I)
1730    delete I->second;
1731  localAvail.clear();
1732}
1733
1734/// verifyRemoved - Verify that the specified instruction does not occur in our
1735/// internal data structures.
1736void GVN::verifyRemoved(const Instruction *Inst) const {
1737  VN.verifyRemoved(Inst);
1738
1739  // Walk through the PHI map to make sure the instruction isn't hiding in there
1740  // somewhere.
1741  for (PhiMapType::iterator
1742         I = phiMap.begin(), E = phiMap.end(); I != E; ++I) {
1743    assert(I->first != Inst && "Inst is still a key in PHI map!");
1744
1745    for (SmallPtrSet<Instruction*, 4>::iterator
1746           II = I->second.begin(), IE = I->second.end(); II != IE; ++II) {
1747      assert(*II != Inst && "Inst is still a value in PHI map!");
1748    }
1749  }
1750
1751  // Walk through the value number scope to make sure the instruction isn't
1752  // ferreted away in it.
1753  for (DenseMap<BasicBlock*, ValueNumberScope*>::iterator
1754         I = localAvail.begin(), E = localAvail.end(); I != E; ++I) {
1755    const ValueNumberScope *VNS = I->second;
1756
1757    while (VNS) {
1758      for (DenseMap<uint32_t, Value*>::iterator
1759             II = VNS->table.begin(), IE = VNS->table.end(); II != IE; ++II) {
1760        assert(II->second != Inst && "Inst still in value numbering scope!");
1761      }
1762
1763      VNS = VNS->parent;
1764    }
1765  }
1766}
1767