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