make memset inference significantly more powerful: it can now handle
[oota-llvm.git] / lib / Transforms / Scalar / GVN.cpp
1 //===- GVN.cpp - Eliminate redundant values and loads ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass performs global value numbering to eliminate fully redundant
11 // instructions.  It also performs simple dead load elimination.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "gvn"
16 #include "llvm/Transforms/Scalar.h"
17 #include "llvm/BasicBlock.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Function.h"
21 #include "llvm/IntrinsicInst.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/ParameterAttributes.h"
24 #include "llvm/Value.h"
25 #include "llvm/ADT/BitVector.h"
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/DepthFirstIterator.h"
28 #include "llvm/ADT/SmallPtrSet.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/Analysis/Dominators.h"
32 #include "llvm/Analysis/AliasAnalysis.h"
33 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
34 #include "llvm/Support/CFG.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Compiler.h"
37 #include "llvm/Support/GetElementPtrTypeIterator.h"
38 #include "llvm/Target/TargetData.h"
39 #include <list>
40 using namespace llvm;
41
42 STATISTIC(NumGVNInstr, "Number of instructions deleted");
43 STATISTIC(NumGVNLoad, "Number of loads deleted");
44 STATISTIC(NumMemSetInfer, "Number of memsets inferred");
45
46 namespace {
47   cl::opt<bool>
48   FormMemSet("form-memset-from-stores",
49              cl::desc("Transform straight-line stores to memsets"),
50              cl::init(false), cl::Hidden);
51 }
52
53 //===----------------------------------------------------------------------===//
54 //                         ValueTable Class
55 //===----------------------------------------------------------------------===//
56
57 /// This class holds the mapping between values and value numbers.  It is used
58 /// as an efficient mechanism to determine the expression-wise equivalence of
59 /// two values.
60 namespace {
61   struct VISIBILITY_HIDDEN Expression {
62     enum ExpressionOpcode { ADD, SUB, MUL, UDIV, SDIV, FDIV, UREM, SREM, 
63                             FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ, 
64                             ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE, 
65                             ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ, 
66                             FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE, 
67                             FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE, 
68                             FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
69                             SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
70                             FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT, 
71                             PTRTOINT, INTTOPTR, BITCAST, GEP, CALL, EMPTY,
72                             TOMBSTONE };
73
74     ExpressionOpcode opcode;
75     const Type* type;
76     uint32_t firstVN;
77     uint32_t secondVN;
78     uint32_t thirdVN;
79     SmallVector<uint32_t, 4> varargs;
80     Value* function;
81   
82     Expression() { }
83     Expression(ExpressionOpcode o) : opcode(o) { }
84   
85     bool operator==(const Expression &other) const {
86       if (opcode != other.opcode)
87         return false;
88       else if (opcode == EMPTY || opcode == TOMBSTONE)
89         return true;
90       else if (type != other.type)
91         return false;
92       else if (function != other.function)
93         return false;
94       else if (firstVN != other.firstVN)
95         return false;
96       else if (secondVN != other.secondVN)
97         return false;
98       else if (thirdVN != other.thirdVN)
99         return false;
100       else {
101         if (varargs.size() != other.varargs.size())
102           return false;
103       
104         for (size_t i = 0; i < varargs.size(); ++i)
105           if (varargs[i] != other.varargs[i])
106             return false;
107     
108         return true;
109       }
110     }
111   
112     bool operator!=(const Expression &other) const {
113       if (opcode != other.opcode)
114         return true;
115       else if (opcode == EMPTY || opcode == TOMBSTONE)
116         return false;
117       else if (type != other.type)
118         return true;
119       else if (function != other.function)
120         return true;
121       else if (firstVN != other.firstVN)
122         return true;
123       else if (secondVN != other.secondVN)
124         return true;
125       else if (thirdVN != other.thirdVN)
126         return true;
127       else {
128         if (varargs.size() != other.varargs.size())
129           return true;
130       
131         for (size_t i = 0; i < varargs.size(); ++i)
132           if (varargs[i] != other.varargs[i])
133             return true;
134     
135           return false;
136       }
137     }
138   };
139   
140   class VISIBILITY_HIDDEN ValueTable {
141     private:
142       DenseMap<Value*, uint32_t> valueNumbering;
143       DenseMap<Expression, uint32_t> expressionNumbering;
144       AliasAnalysis* AA;
145   
146       uint32_t nextValueNumber;
147     
148       Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
149       Expression::ExpressionOpcode getOpcode(CmpInst* C);
150       Expression::ExpressionOpcode getOpcode(CastInst* C);
151       Expression create_expression(BinaryOperator* BO);
152       Expression create_expression(CmpInst* C);
153       Expression create_expression(ShuffleVectorInst* V);
154       Expression create_expression(ExtractElementInst* C);
155       Expression create_expression(InsertElementInst* V);
156       Expression create_expression(SelectInst* V);
157       Expression create_expression(CastInst* C);
158       Expression create_expression(GetElementPtrInst* G);
159       Expression create_expression(CallInst* C);
160     public:
161       ValueTable() : nextValueNumber(1) { }
162       uint32_t lookup_or_add(Value* V);
163       uint32_t lookup(Value* V) const;
164       void add(Value* V, uint32_t num);
165       void clear();
166       void erase(Value* v);
167       unsigned size();
168       void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
169       uint32_t hash_operand(Value* v);
170   };
171 }
172
173 namespace llvm {
174 template <> struct DenseMapInfo<Expression> {
175   static inline Expression getEmptyKey() {
176     return Expression(Expression::EMPTY);
177   }
178   
179   static inline Expression getTombstoneKey() {
180     return Expression(Expression::TOMBSTONE);
181   }
182   
183   static unsigned getHashValue(const Expression e) {
184     unsigned hash = e.opcode;
185     
186     hash = e.firstVN + hash * 37;
187     hash = e.secondVN + hash * 37;
188     hash = e.thirdVN + hash * 37;
189     
190     hash = ((unsigned)((uintptr_t)e.type >> 4) ^
191             (unsigned)((uintptr_t)e.type >> 9)) +
192            hash * 37;
193     
194     for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
195          E = e.varargs.end(); I != E; ++I)
196       hash = *I + hash * 37;
197     
198     hash = ((unsigned)((uintptr_t)e.function >> 4) ^
199             (unsigned)((uintptr_t)e.function >> 9)) +
200            hash * 37;
201     
202     return hash;
203   }
204   static bool isEqual(const Expression &LHS, const Expression &RHS) {
205     return LHS == RHS;
206   }
207   static bool isPod() { return true; }
208 };
209 }
210
211 //===----------------------------------------------------------------------===//
212 //                     ValueTable Internal Functions
213 //===----------------------------------------------------------------------===//
214 Expression::ExpressionOpcode ValueTable::getOpcode(BinaryOperator* BO) {
215   switch(BO->getOpcode()) {
216   default: // THIS SHOULD NEVER HAPPEN
217     assert(0 && "Binary operator with unknown opcode?");
218   case Instruction::Add:  return Expression::ADD;
219   case Instruction::Sub:  return Expression::SUB;
220   case Instruction::Mul:  return Expression::MUL;
221   case Instruction::UDiv: return Expression::UDIV;
222   case Instruction::SDiv: return Expression::SDIV;
223   case Instruction::FDiv: return Expression::FDIV;
224   case Instruction::URem: return Expression::UREM;
225   case Instruction::SRem: return Expression::SREM;
226   case Instruction::FRem: return Expression::FREM;
227   case Instruction::Shl:  return Expression::SHL;
228   case Instruction::LShr: return Expression::LSHR;
229   case Instruction::AShr: return Expression::ASHR;
230   case Instruction::And:  return Expression::AND;
231   case Instruction::Or:   return Expression::OR;
232   case Instruction::Xor:  return Expression::XOR;
233   }
234 }
235
236 Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
237   if (isa<ICmpInst>(C)) {
238     switch (C->getPredicate()) {
239     default:  // THIS SHOULD NEVER HAPPEN
240       assert(0 && "Comparison with unknown predicate?");
241     case ICmpInst::ICMP_EQ:  return Expression::ICMPEQ;
242     case ICmpInst::ICMP_NE:  return Expression::ICMPNE;
243     case ICmpInst::ICMP_UGT: return Expression::ICMPUGT;
244     case ICmpInst::ICMP_UGE: return Expression::ICMPUGE;
245     case ICmpInst::ICMP_ULT: return Expression::ICMPULT;
246     case ICmpInst::ICMP_ULE: return Expression::ICMPULE;
247     case ICmpInst::ICMP_SGT: return Expression::ICMPSGT;
248     case ICmpInst::ICMP_SGE: return Expression::ICMPSGE;
249     case ICmpInst::ICMP_SLT: return Expression::ICMPSLT;
250     case ICmpInst::ICMP_SLE: return Expression::ICMPSLE;
251     }
252   }
253   assert(isa<FCmpInst>(C) && "Unknown compare");
254   switch (C->getPredicate()) {
255   default: // THIS SHOULD NEVER HAPPEN
256     assert(0 && "Comparison with unknown predicate?");
257   case FCmpInst::FCMP_OEQ: return Expression::FCMPOEQ;
258   case FCmpInst::FCMP_OGT: return Expression::FCMPOGT;
259   case FCmpInst::FCMP_OGE: return Expression::FCMPOGE;
260   case FCmpInst::FCMP_OLT: return Expression::FCMPOLT;
261   case FCmpInst::FCMP_OLE: return Expression::FCMPOLE;
262   case FCmpInst::FCMP_ONE: return Expression::FCMPONE;
263   case FCmpInst::FCMP_ORD: return Expression::FCMPORD;
264   case FCmpInst::FCMP_UNO: return Expression::FCMPUNO;
265   case FCmpInst::FCMP_UEQ: return Expression::FCMPUEQ;
266   case FCmpInst::FCMP_UGT: return Expression::FCMPUGT;
267   case FCmpInst::FCMP_UGE: return Expression::FCMPUGE;
268   case FCmpInst::FCMP_ULT: return Expression::FCMPULT;
269   case FCmpInst::FCMP_ULE: return Expression::FCMPULE;
270   case FCmpInst::FCMP_UNE: return Expression::FCMPUNE;
271   }
272 }
273
274 Expression::ExpressionOpcode ValueTable::getOpcode(CastInst* C) {
275   switch(C->getOpcode()) {
276   default: // THIS SHOULD NEVER HAPPEN
277     assert(0 && "Cast operator with unknown opcode?");
278   case Instruction::Trunc:    return Expression::TRUNC;
279   case Instruction::ZExt:     return Expression::ZEXT;
280   case Instruction::SExt:     return Expression::SEXT;
281   case Instruction::FPToUI:   return Expression::FPTOUI;
282   case Instruction::FPToSI:   return Expression::FPTOSI;
283   case Instruction::UIToFP:   return Expression::UITOFP;
284   case Instruction::SIToFP:   return Expression::SITOFP;
285   case Instruction::FPTrunc:  return Expression::FPTRUNC;
286   case Instruction::FPExt:    return Expression::FPEXT;
287   case Instruction::PtrToInt: return Expression::PTRTOINT;
288   case Instruction::IntToPtr: return Expression::INTTOPTR;
289   case Instruction::BitCast:  return Expression::BITCAST;
290   }
291 }
292
293 uint32_t ValueTable::hash_operand(Value* v) {
294   if (CallInst* CI = dyn_cast<CallInst>(v))
295     if (!AA->doesNotAccessMemory(CI))
296       return nextValueNumber++;
297   
298   return lookup_or_add(v);
299 }
300
301 Expression ValueTable::create_expression(CallInst* C) {
302   Expression e;
303   
304   e.type = C->getType();
305   e.firstVN = 0;
306   e.secondVN = 0;
307   e.thirdVN = 0;
308   e.function = C->getCalledFunction();
309   e.opcode = Expression::CALL;
310   
311   for (CallInst::op_iterator I = C->op_begin()+1, E = C->op_end();
312        I != E; ++I)
313     e.varargs.push_back(hash_operand(*I));
314   
315   return e;
316 }
317
318 Expression ValueTable::create_expression(BinaryOperator* BO) {
319   Expression e;
320     
321   e.firstVN = hash_operand(BO->getOperand(0));
322   e.secondVN = hash_operand(BO->getOperand(1));
323   e.thirdVN = 0;
324   e.function = 0;
325   e.type = BO->getType();
326   e.opcode = getOpcode(BO);
327   
328   return e;
329 }
330
331 Expression ValueTable::create_expression(CmpInst* C) {
332   Expression e;
333     
334   e.firstVN = hash_operand(C->getOperand(0));
335   e.secondVN = hash_operand(C->getOperand(1));
336   e.thirdVN = 0;
337   e.function = 0;
338   e.type = C->getType();
339   e.opcode = getOpcode(C);
340   
341   return e;
342 }
343
344 Expression ValueTable::create_expression(CastInst* C) {
345   Expression e;
346     
347   e.firstVN = hash_operand(C->getOperand(0));
348   e.secondVN = 0;
349   e.thirdVN = 0;
350   e.function = 0;
351   e.type = C->getType();
352   e.opcode = getOpcode(C);
353   
354   return e;
355 }
356
357 Expression ValueTable::create_expression(ShuffleVectorInst* S) {
358   Expression e;
359     
360   e.firstVN = hash_operand(S->getOperand(0));
361   e.secondVN = hash_operand(S->getOperand(1));
362   e.thirdVN = hash_operand(S->getOperand(2));
363   e.function = 0;
364   e.type = S->getType();
365   e.opcode = Expression::SHUFFLE;
366   
367   return e;
368 }
369
370 Expression ValueTable::create_expression(ExtractElementInst* E) {
371   Expression e;
372     
373   e.firstVN = hash_operand(E->getOperand(0));
374   e.secondVN = hash_operand(E->getOperand(1));
375   e.thirdVN = 0;
376   e.function = 0;
377   e.type = E->getType();
378   e.opcode = Expression::EXTRACT;
379   
380   return e;
381 }
382
383 Expression ValueTable::create_expression(InsertElementInst* I) {
384   Expression e;
385     
386   e.firstVN = hash_operand(I->getOperand(0));
387   e.secondVN = hash_operand(I->getOperand(1));
388   e.thirdVN = hash_operand(I->getOperand(2));
389   e.function = 0;
390   e.type = I->getType();
391   e.opcode = Expression::INSERT;
392   
393   return e;
394 }
395
396 Expression ValueTable::create_expression(SelectInst* I) {
397   Expression e;
398     
399   e.firstVN = hash_operand(I->getCondition());
400   e.secondVN = hash_operand(I->getTrueValue());
401   e.thirdVN = hash_operand(I->getFalseValue());
402   e.function = 0;
403   e.type = I->getType();
404   e.opcode = Expression::SELECT;
405   
406   return e;
407 }
408
409 Expression ValueTable::create_expression(GetElementPtrInst* G) {
410   Expression e;
411     
412   e.firstVN = hash_operand(G->getPointerOperand());
413   e.secondVN = 0;
414   e.thirdVN = 0;
415   e.function = 0;
416   e.type = G->getType();
417   e.opcode = Expression::GEP;
418   
419   for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
420        I != E; ++I)
421     e.varargs.push_back(hash_operand(*I));
422   
423   return e;
424 }
425
426 //===----------------------------------------------------------------------===//
427 //                     ValueTable External Functions
428 //===----------------------------------------------------------------------===//
429
430 /// lookup_or_add - Returns the value number for the specified value, assigning
431 /// it a new number if it did not have one before.
432 uint32_t ValueTable::lookup_or_add(Value* V) {
433   DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
434   if (VI != valueNumbering.end())
435     return VI->second;
436   
437   if (CallInst* C = dyn_cast<CallInst>(V)) {
438     if (AA->onlyReadsMemory(C)) { // includes doesNotAccessMemory
439       Expression e = create_expression(C);
440     
441       DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
442       if (EI != expressionNumbering.end()) {
443         valueNumbering.insert(std::make_pair(V, EI->second));
444         return EI->second;
445       } else {
446         expressionNumbering.insert(std::make_pair(e, nextValueNumber));
447         valueNumbering.insert(std::make_pair(V, nextValueNumber));
448       
449         return nextValueNumber++;
450       }
451     } else {
452       valueNumbering.insert(std::make_pair(V, nextValueNumber));
453       return nextValueNumber++;
454     }
455   } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
456     Expression e = create_expression(BO);
457     
458     DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
459     if (EI != expressionNumbering.end()) {
460       valueNumbering.insert(std::make_pair(V, EI->second));
461       return EI->second;
462     } else {
463       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
464       valueNumbering.insert(std::make_pair(V, nextValueNumber));
465       
466       return nextValueNumber++;
467     }
468   } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
469     Expression e = create_expression(C);
470     
471     DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
472     if (EI != expressionNumbering.end()) {
473       valueNumbering.insert(std::make_pair(V, EI->second));
474       return EI->second;
475     } else {
476       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
477       valueNumbering.insert(std::make_pair(V, nextValueNumber));
478       
479       return nextValueNumber++;
480     }
481   } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
482     Expression e = create_expression(U);
483     
484     DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
485     if (EI != expressionNumbering.end()) {
486       valueNumbering.insert(std::make_pair(V, EI->second));
487       return EI->second;
488     } else {
489       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
490       valueNumbering.insert(std::make_pair(V, nextValueNumber));
491       
492       return nextValueNumber++;
493     }
494   } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
495     Expression e = create_expression(U);
496     
497     DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
498     if (EI != expressionNumbering.end()) {
499       valueNumbering.insert(std::make_pair(V, EI->second));
500       return EI->second;
501     } else {
502       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
503       valueNumbering.insert(std::make_pair(V, nextValueNumber));
504       
505       return nextValueNumber++;
506     }
507   } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
508     Expression e = create_expression(U);
509     
510     DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
511     if (EI != expressionNumbering.end()) {
512       valueNumbering.insert(std::make_pair(V, EI->second));
513       return EI->second;
514     } else {
515       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
516       valueNumbering.insert(std::make_pair(V, nextValueNumber));
517       
518       return nextValueNumber++;
519     }
520   } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
521     Expression e = create_expression(U);
522     
523     DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
524     if (EI != expressionNumbering.end()) {
525       valueNumbering.insert(std::make_pair(V, EI->second));
526       return EI->second;
527     } else {
528       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
529       valueNumbering.insert(std::make_pair(V, nextValueNumber));
530       
531       return nextValueNumber++;
532     }
533   } else if (CastInst* U = dyn_cast<CastInst>(V)) {
534     Expression e = create_expression(U);
535     
536     DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
537     if (EI != expressionNumbering.end()) {
538       valueNumbering.insert(std::make_pair(V, EI->second));
539       return EI->second;
540     } else {
541       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
542       valueNumbering.insert(std::make_pair(V, nextValueNumber));
543       
544       return nextValueNumber++;
545     }
546   } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
547     Expression e = create_expression(U);
548     
549     DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
550     if (EI != expressionNumbering.end()) {
551       valueNumbering.insert(std::make_pair(V, EI->second));
552       return EI->second;
553     } else {
554       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
555       valueNumbering.insert(std::make_pair(V, nextValueNumber));
556       
557       return nextValueNumber++;
558     }
559   } else {
560     valueNumbering.insert(std::make_pair(V, nextValueNumber));
561     return nextValueNumber++;
562   }
563 }
564
565 /// lookup - Returns the value number of the specified value. Fails if
566 /// the value has not yet been numbered.
567 uint32_t ValueTable::lookup(Value* V) const {
568   DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
569   assert(VI != valueNumbering.end() && "Value not numbered?");
570   return VI->second;
571 }
572
573 /// clear - Remove all entries from the ValueTable
574 void ValueTable::clear() {
575   valueNumbering.clear();
576   expressionNumbering.clear();
577   nextValueNumber = 1;
578 }
579
580 /// erase - Remove a value from the value numbering
581 void ValueTable::erase(Value* V) {
582   valueNumbering.erase(V);
583 }
584
585 //===----------------------------------------------------------------------===//
586 //                       ValueNumberedSet Class
587 //===----------------------------------------------------------------------===//
588 namespace {
589 class VISIBILITY_HIDDEN ValueNumberedSet {
590   private:
591     SmallPtrSet<Value*, 8> contents;
592     BitVector numbers;
593   public:
594     ValueNumberedSet() { numbers.resize(1); }
595     ValueNumberedSet(const ValueNumberedSet& other) {
596       numbers = other.numbers;
597       contents = other.contents;
598     }
599     
600     typedef SmallPtrSet<Value*, 8>::iterator iterator;
601     
602     iterator begin() { return contents.begin(); }
603     iterator end() { return contents.end(); }
604     
605     bool insert(Value* v) { return contents.insert(v); }
606     void insert(iterator I, iterator E) { contents.insert(I, E); }
607     void erase(Value* v) { contents.erase(v); }
608     unsigned count(Value* v) { return contents.count(v); }
609     size_t size() { return contents.size(); }
610     
611     void set(unsigned i)  {
612       if (i >= numbers.size())
613         numbers.resize(i+1);
614       
615       numbers.set(i);
616     }
617     
618     void operator=(const ValueNumberedSet& other) {
619       contents = other.contents;
620       numbers = other.numbers;
621     }
622     
623     void reset(unsigned i)  {
624       if (i < numbers.size())
625         numbers.reset(i);
626     }
627     
628     bool test(unsigned i)  {
629       if (i >= numbers.size())
630         return false;
631       
632       return numbers.test(i);
633     }
634     
635     void clear() {
636       contents.clear();
637       numbers.clear();
638     }
639 };
640 }
641
642 //===----------------------------------------------------------------------===//
643 //                         GVN Pass
644 //===----------------------------------------------------------------------===//
645
646 namespace {
647
648   class VISIBILITY_HIDDEN GVN : public FunctionPass {
649     bool runOnFunction(Function &F);
650   public:
651     static char ID; // Pass identification, replacement for typeid
652     GVN() : FunctionPass((intptr_t)&ID) { }
653
654   private:
655     ValueTable VN;
656     
657     DenseMap<BasicBlock*, ValueNumberedSet> availableOut;
658     
659     typedef DenseMap<Value*, SmallPtrSet<Instruction*, 4> > PhiMapType;
660     PhiMapType phiMap;
661     
662     
663     // This transformation requires dominator postdominator info
664     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
665       AU.setPreservesCFG();
666       AU.addRequired<DominatorTree>();
667       AU.addRequired<MemoryDependenceAnalysis>();
668       AU.addRequired<AliasAnalysis>();
669       AU.addRequired<TargetData>();
670       AU.addPreserved<AliasAnalysis>();
671       AU.addPreserved<MemoryDependenceAnalysis>();
672       AU.addPreserved<TargetData>();
673     }
674   
675     // Helper fuctions
676     // FIXME: eliminate or document these better
677     Value* find_leader(ValueNumberedSet& vals, uint32_t v) ;
678     void val_insert(ValueNumberedSet& s, Value* v);
679     bool processLoad(LoadInst* L,
680                      DenseMap<Value*, LoadInst*> &lastLoad,
681                      SmallVectorImpl<Instruction*> &toErase);
682     bool processStore(StoreInst *SI, SmallVectorImpl<Instruction*> &toErase);
683     bool processInstruction(Instruction* I,
684                             ValueNumberedSet& currAvail,
685                             DenseMap<Value*, LoadInst*>& lastSeenLoad,
686                             SmallVectorImpl<Instruction*> &toErase);
687     bool processNonLocalLoad(LoadInst* L,
688                              SmallVectorImpl<Instruction*> &toErase);
689     bool processMemCpy(MemCpyInst* M, MemCpyInst* MDep,
690                        SmallVectorImpl<Instruction*> &toErase);
691     bool performCallSlotOptzn(MemCpyInst* cpy, CallInst* C,
692                               SmallVectorImpl<Instruction*> &toErase);
693     Value *GetValueForBlock(BasicBlock *BB, LoadInst* orig,
694                             DenseMap<BasicBlock*, Value*> &Phis,
695                             bool top_level = false);
696     void dump(DenseMap<BasicBlock*, Value*>& d);
697     bool iterateOnFunction(Function &F);
698     Value* CollapsePhi(PHINode* p);
699     bool isSafeReplacement(PHINode* p, Instruction* inst);
700   };
701   
702   char GVN::ID = 0;
703 }
704
705 // createGVNPass - The public interface to this file...
706 FunctionPass *llvm::createGVNPass() { return new GVN(); }
707
708 static RegisterPass<GVN> X("gvn",
709                            "Global Value Numbering");
710
711 /// find_leader - Given a set and a value number, return the first
712 /// element of the set with that value number, or 0 if no such element
713 /// is present
714 Value* GVN::find_leader(ValueNumberedSet& vals, uint32_t v) {
715   if (!vals.test(v))
716     return 0;
717   
718   for (ValueNumberedSet::iterator I = vals.begin(), E = vals.end();
719        I != E; ++I)
720     if (v == VN.lookup(*I))
721       return *I;
722   
723   assert(0 && "No leader found, but present bit is set?");
724   return 0;
725 }
726
727 /// val_insert - Insert a value into a set only if there is not a value
728 /// with the same value number already in the set
729 void GVN::val_insert(ValueNumberedSet& s, Value* v) {
730   uint32_t num = VN.lookup(v);
731   if (!s.test(num))
732     s.insert(v);
733 }
734
735 void GVN::dump(DenseMap<BasicBlock*, Value*>& d) {
736   printf("{\n");
737   for (DenseMap<BasicBlock*, Value*>::iterator I = d.begin(),
738        E = d.end(); I != E; ++I) {
739     if (I->second == MemoryDependenceAnalysis::None)
740       printf("None\n");
741     else
742       I->second->dump();
743   }
744   printf("}\n");
745 }
746
747 Value* GVN::CollapsePhi(PHINode* p) {
748   DominatorTree &DT = getAnalysis<DominatorTree>();
749   Value* constVal = p->hasConstantValue();
750   
751   if (!constVal) return 0;
752   
753   Instruction* inst = dyn_cast<Instruction>(constVal);
754   if (!inst)
755     return constVal;
756     
757   if (DT.dominates(inst, p))
758     if (isSafeReplacement(p, inst))
759       return inst;
760   return 0;
761 }
762
763 bool GVN::isSafeReplacement(PHINode* p, Instruction* inst) {
764   if (!isa<PHINode>(inst))
765     return true;
766   
767   for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end();
768        UI != E; ++UI)
769     if (PHINode* use_phi = dyn_cast<PHINode>(UI))
770       if (use_phi->getParent() == inst->getParent())
771         return false;
772   
773   return true;
774 }
775
776 /// GetValueForBlock - Get the value to use within the specified basic block.
777 /// available values are in Phis.
778 Value *GVN::GetValueForBlock(BasicBlock *BB, LoadInst* orig,
779                              DenseMap<BasicBlock*, Value*> &Phis,
780                              bool top_level) { 
781                                  
782   // If we have already computed this value, return the previously computed val.
783   DenseMap<BasicBlock*, Value*>::iterator V = Phis.find(BB);
784   if (V != Phis.end() && !top_level) return V->second;
785   
786   BasicBlock* singlePred = BB->getSinglePredecessor();
787   if (singlePred) {
788     Value *ret = GetValueForBlock(singlePred, orig, Phis);
789     Phis[BB] = ret;
790     return ret;
791   }
792   
793   // Otherwise, the idom is the loop, so we need to insert a PHI node.  Do so
794   // now, then get values to fill in the incoming values for the PHI.
795   PHINode *PN = new PHINode(orig->getType(), orig->getName()+".rle",
796                             BB->begin());
797   PN->reserveOperandSpace(std::distance(pred_begin(BB), pred_end(BB)));
798   
799   if (Phis.count(BB) == 0)
800     Phis.insert(std::make_pair(BB, PN));
801   
802   // Fill in the incoming values for the block.
803   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
804     Value* val = GetValueForBlock(*PI, orig, Phis);
805     PN->addIncoming(val, *PI);
806   }
807   
808   AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
809   AA.copyValue(orig, PN);
810   
811   // Attempt to collapse PHI nodes that are trivially redundant
812   Value* v = CollapsePhi(PN);
813   if (!v) {
814     // Cache our phi construction results
815     phiMap[orig->getPointerOperand()].insert(PN);
816     return PN;
817   }
818     
819   MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
820
821   MD.removeInstruction(PN);
822   PN->replaceAllUsesWith(v);
823
824   for (DenseMap<BasicBlock*, Value*>::iterator I = Phis.begin(),
825        E = Phis.end(); I != E; ++I)
826     if (I->second == PN)
827       I->second = v;
828
829   PN->eraseFromParent();
830
831   Phis[BB] = v;
832   return v;
833 }
834
835 /// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
836 /// non-local by performing PHI construction.
837 bool GVN::processNonLocalLoad(LoadInst* L,
838                               SmallVectorImpl<Instruction*> &toErase) {
839   MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
840   
841   // Find the non-local dependencies of the load
842   DenseMap<BasicBlock*, Value*> deps;
843   MD.getNonLocalDependency(L, deps);
844   
845   DenseMap<BasicBlock*, Value*> repl;
846   
847   // Filter out useless results (non-locals, etc)
848   for (DenseMap<BasicBlock*, Value*>::iterator I = deps.begin(), E = deps.end();
849        I != E; ++I) {
850     if (I->second == MemoryDependenceAnalysis::None)
851       return false;
852   
853     if (I->second == MemoryDependenceAnalysis::NonLocal)
854       continue;
855   
856     if (StoreInst* S = dyn_cast<StoreInst>(I->second)) {
857       if (S->getPointerOperand() != L->getPointerOperand())
858         return false;
859       repl[I->first] = S->getOperand(0);
860     } else if (LoadInst* LD = dyn_cast<LoadInst>(I->second)) {
861       if (LD->getPointerOperand() != L->getPointerOperand())
862         return false;
863       repl[I->first] = LD;
864     } else {
865       return false;
866     }
867   }
868   
869   // Use cached PHI construction information from previous runs
870   SmallPtrSet<Instruction*, 4>& p = phiMap[L->getPointerOperand()];
871   for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
872        I != E; ++I) {
873     if ((*I)->getParent() == L->getParent()) {
874       MD.removeInstruction(L);
875       L->replaceAllUsesWith(*I);
876       toErase.push_back(L);
877       NumGVNLoad++;
878       return true;
879     }
880     
881     repl.insert(std::make_pair((*I)->getParent(), *I));
882   }
883   
884   // Perform PHI construction
885   SmallPtrSet<BasicBlock*, 4> visited;
886   Value* v = GetValueForBlock(L->getParent(), L, repl, true);
887   
888   MD.removeInstruction(L);
889   L->replaceAllUsesWith(v);
890   toErase.push_back(L);
891   NumGVNLoad++;
892
893   return true;
894 }
895
896 /// processLoad - Attempt to eliminate a load, first by eliminating it
897 /// locally, and then attempting non-local elimination if that fails.
898 bool GVN::processLoad(LoadInst *L, DenseMap<Value*, LoadInst*> &lastLoad,
899                       SmallVectorImpl<Instruction*> &toErase) {
900   if (L->isVolatile()) {
901     lastLoad[L->getPointerOperand()] = L;
902     return false;
903   }
904   
905   Value* pointer = L->getPointerOperand();
906   LoadInst*& last = lastLoad[pointer];
907   
908   // ... to a pointer that has been loaded from before...
909   MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
910   bool removedNonLocal = false;
911   Instruction* dep = MD.getDependency(L);
912   if (dep == MemoryDependenceAnalysis::NonLocal &&
913       L->getParent() != &L->getParent()->getParent()->getEntryBlock()) {
914     removedNonLocal = processNonLocalLoad(L, toErase);
915     
916     if (!removedNonLocal)
917       last = L;
918     
919     return removedNonLocal;
920   }
921   
922   
923   bool deletedLoad = false;
924   
925   // Walk up the dependency chain until we either find
926   // a dependency we can use, or we can't walk any further
927   while (dep != MemoryDependenceAnalysis::None &&
928          dep != MemoryDependenceAnalysis::NonLocal &&
929          (isa<LoadInst>(dep) || isa<StoreInst>(dep))) {
930     // ... that depends on a store ...
931     if (StoreInst* S = dyn_cast<StoreInst>(dep)) {
932       if (S->getPointerOperand() == pointer) {
933         // Remove it!
934         MD.removeInstruction(L);
935         
936         L->replaceAllUsesWith(S->getOperand(0));
937         toErase.push_back(L);
938         deletedLoad = true;
939         NumGVNLoad++;
940       }
941       
942       // Whether we removed it or not, we can't
943       // go any further
944       break;
945     } else if (!last) {
946       // If we don't depend on a store, and we haven't
947       // been loaded before, bail.
948       break;
949     } else if (dep == last) {
950       // Remove it!
951       MD.removeInstruction(L);
952       
953       L->replaceAllUsesWith(last);
954       toErase.push_back(L);
955       deletedLoad = true;
956       NumGVNLoad++;
957         
958       break;
959     } else {
960       dep = MD.getDependency(L, dep);
961     }
962   }
963
964   if (dep != MemoryDependenceAnalysis::None &&
965       dep != MemoryDependenceAnalysis::NonLocal &&
966       isa<AllocationInst>(dep)) {
967     // Check that this load is actually from the
968     // allocation we found
969     Value* v = L->getOperand(0);
970     while (true) {
971       if (BitCastInst *BC = dyn_cast<BitCastInst>(v))
972         v = BC->getOperand(0);
973       else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(v))
974         v = GEP->getOperand(0);
975       else
976         break;
977     }
978     if (v == dep) {
979       // If this load depends directly on an allocation, there isn't
980       // anything stored there; therefore, we can optimize this load
981       // to undef.
982       MD.removeInstruction(L);
983
984       L->replaceAllUsesWith(UndefValue::get(L->getType()));
985       toErase.push_back(L);
986       deletedLoad = true;
987       NumGVNLoad++;
988     }
989   }
990
991   if (!deletedLoad)
992     last = L;
993   
994   return deletedLoad;
995 }
996
997 /// isBytewiseValue - If the specified value can be set by repeating the same
998 /// byte in memory, return the i8 value that it is represented with.  This is
999 /// true for all i8 values obviously, but is also true for i32 0, i32 -1,
1000 /// i16 0xF0F0, double 0.0 etc.  If the value can't be handled with a repeated
1001 /// byte store (e.g. i16 0x1234), return null.
1002 static Value *isBytewiseValue(Value *V) {
1003   // All byte-wide stores are splatable, even of arbitrary variables.
1004   if (V->getType() == Type::Int8Ty) return V;
1005   
1006   // Constant float and double values can be handled as integer values if the
1007   // corresponding integer value is "byteable".  An important case is 0.0. 
1008   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1009     if (CFP->getType() == Type::FloatTy)
1010       V = ConstantExpr::getBitCast(CFP, Type::Int32Ty);
1011     if (CFP->getType() == Type::DoubleTy)
1012       V = ConstantExpr::getBitCast(CFP, Type::Int64Ty);
1013     // Don't handle long double formats, which have strange constraints.
1014   }
1015   
1016   // We can handle constant integers that are power of two in size and a 
1017   // multiple of 8 bits.
1018   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1019     unsigned Width = CI->getBitWidth();
1020     if (isPowerOf2_32(Width) && Width > 8) {
1021       // We can handle this value if the recursive binary decomposition is the
1022       // same at all levels.
1023       APInt Val = CI->getValue();
1024       APInt Val2;
1025       while (Val.getBitWidth() != 8) {
1026         unsigned NextWidth = Val.getBitWidth()/2;
1027         Val2  = Val.lshr(NextWidth);
1028         Val2.trunc(Val.getBitWidth()/2);
1029         Val.trunc(Val.getBitWidth()/2);
1030
1031         // If the top/bottom halves aren't the same, reject it.
1032         if (Val != Val2)
1033           return 0;
1034       }
1035       return ConstantInt::get(Val);
1036     }
1037   }
1038   
1039   // Conceptually, we could handle things like:
1040   //   %a = zext i8 %X to i16
1041   //   %b = shl i16 %a, 8
1042   //   %c = or i16 %a, %b
1043   // but until there is an example that actually needs this, it doesn't seem
1044   // worth worrying about.
1045   return 0;
1046 }
1047
1048 static int64_t GetOffsetFromIndex(const GetElementPtrInst *GEP, unsigned Idx,
1049                                   bool &VariableIdxFound, TargetData &TD) {
1050   // Skip over the first indices.
1051   gep_type_iterator GTI = gep_type_begin(GEP);
1052   for (unsigned i = 1; i != Idx; ++i, ++GTI)
1053     /*skip along*/;
1054   
1055   // Compute the offset implied by the rest of the indices.
1056   int64_t Offset = 0;
1057   for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
1058     ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
1059     if (OpC == 0)
1060       return VariableIdxFound = true;
1061     if (OpC->isZero()) continue;  // No offset.
1062
1063     // Handle struct indices, which add their field offset to the pointer.
1064     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1065       Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
1066       continue;
1067     }
1068     
1069     // Otherwise, we have a sequential type like an array or vector.  Multiply
1070     // the index by the ElementSize.
1071     uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
1072     Offset += Size*OpC->getSExtValue();
1073   }
1074
1075   return Offset;
1076 }
1077
1078 /// IsPointerOffset - Return true if Ptr1 is provably equal to Ptr2 plus a
1079 /// constant offset, and return that constant offset.  For example, Ptr1 might
1080 /// be &A[42], and Ptr2 might be &A[40].  In this case offset would be -8.
1081 static bool IsPointerOffset(Value *Ptr1, Value *Ptr2, int64_t &Offset,
1082                             TargetData &TD) {
1083   // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
1084   // base.  After that base, they may have some number of common (and
1085   // potentially variable) indices.  After that they handle some constant
1086   // offset, which determines their offset from each other.  At this point, we
1087   // handle no other case.
1088   GetElementPtrInst *GEP1 = dyn_cast<GetElementPtrInst>(Ptr1);
1089   GetElementPtrInst *GEP2 = dyn_cast<GetElementPtrInst>(Ptr2);
1090   if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0))
1091     return false;
1092   
1093   // Skip any common indices and track the GEP types.
1094   unsigned Idx = 1;
1095   for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
1096     if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
1097       break;
1098
1099   bool VariableIdxFound = false;
1100   int64_t Offset1 = GetOffsetFromIndex(GEP1, Idx, VariableIdxFound, TD);
1101   int64_t Offset2 = GetOffsetFromIndex(GEP2, Idx, VariableIdxFound, TD);
1102   if (VariableIdxFound) return false;
1103   
1104   Offset = Offset2-Offset1;
1105   return true;
1106 }
1107
1108
1109 /// MemsetRange - Represents a range of memset'd bytes with the ByteVal value.
1110 /// This allows us to analyze stores like:
1111 ///   store 0 -> P+1
1112 ///   store 0 -> P+0
1113 ///   store 0 -> P+3
1114 ///   store 0 -> P+2
1115 /// which sometimes happens with stores to arrays of structs etc.  When we see
1116 /// the first store, we make a range [1, 2).  The second store extends the range
1117 /// to [0, 2).  The third makes a new range [2, 3).  The fourth store joins the
1118 /// two ranges into [0, 3) which is memset'able.
1119 namespace {
1120 struct MemsetRange {
1121   // Start/End - A semi range that describes the span that this range covers.
1122   // The range is closed at the start and open at the end: [Start, End).  
1123   int64_t Start, End;
1124
1125   /// StartPtr - The getelementptr instruction that points to the start of the
1126   /// range.
1127   Value *StartPtr;
1128   
1129   /// Alignment - The known alignment of the first store.
1130   unsigned Alignment;
1131   
1132   /// TheStores - The actual stores that make up this range.
1133   SmallVector<StoreInst*, 16> TheStores;
1134 };
1135   
1136  
1137 class MemsetRanges {
1138   /// Ranges - A sorted list of the memset ranges.  We use std::list here
1139   /// because each element is relatively large and expensive to copy.
1140   std::list<MemsetRange> Ranges;
1141   typedef std::list<MemsetRange>::iterator range_iterator;
1142   TargetData &TD;
1143 public:
1144   MemsetRanges(TargetData &td) : TD(td) {}
1145   
1146   typedef std::list<MemsetRange>::const_iterator const_iterator;
1147   const_iterator begin() const { return Ranges.begin(); }
1148   const_iterator end() const { return Ranges.end(); }
1149   
1150   
1151   void addStore(int64_t OffsetFromFirst, StoreInst *SI);
1152 };
1153   
1154 }
1155
1156 /// addStore - Add a new store to the MemsetRanges data structure.  This adds a
1157 /// new range for the specified store at the specified offset, merging into
1158 /// existing ranges as appropriate.
1159 void MemsetRanges::addStore(int64_t Start, StoreInst *SI) {
1160   int64_t End = Start+TD.getTypeStoreSize(SI->getOperand(0)->getType());
1161   
1162   // Do a linear search of the ranges to see if this can be joined and/or to
1163   // find the insertion point in the list.  We keep the ranges sorted for
1164   // simplicity here.  This is a linear search of a linked list, which is ugly,
1165   // however the number of ranges is limited, so this won't get crazy slow.
1166   range_iterator I = Ranges.begin(), E = Ranges.end();
1167   
1168   while (I != E && Start > I->End)
1169     ++I;
1170   
1171   // We now know that I == E, in which case we didn't find anything to merge
1172   // with, or that Start <= I->End.  If End < I->Start or I == E, then we need
1173   // to insert a new range.  Handle this now.
1174   if (I == E || End < I->Start) {
1175     MemsetRange &R = *Ranges.insert(I, MemsetRange());
1176     R.Start        = Start;
1177     R.End          = End;
1178     R.StartPtr     = SI->getPointerOperand();
1179     R.Alignment    = SI->getAlignment();
1180     R.TheStores.push_back(SI);
1181     return;
1182   }
1183
1184   // This store overlaps with I, add it.
1185   I->TheStores.push_back(SI);
1186   
1187   // At this point, we may have an interval that completely contains our store.
1188   // If so, just add it to the interval and return.
1189   if (I->Start <= Start && I->End >= End)
1190     return;
1191   
1192   // Now we know that Start <= I->End and End >= I->Start so the range overlaps
1193   // but is not entirely contained within the range.
1194   
1195   // See if the range extends the start of the range.  In this case, it couldn't
1196   // possibly cause it to join the prior range, because otherwise we would have
1197   // stopped on *it*.
1198   if (Start < I->Start)
1199     I->Start = Start;
1200     
1201   // Now we know that Start <= I->End and Start >= I->Start (so the startpoint
1202   // is in or right at the end of I), and that End >= I->Start.  Extend I out to
1203   // End.
1204   if (End > I->End) {
1205     I->End = End;
1206     range_iterator NextI = I;;
1207     while (++NextI != E && End >= NextI->Start) {
1208       // Merge the range in.
1209       I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
1210       if (NextI->End > I->End)
1211         I->End = NextI->End;
1212       Ranges.erase(NextI);
1213       NextI = I;
1214     }
1215   }
1216 }
1217
1218
1219
1220 /// processStore - When GVN is scanning forward over instructions, we look for
1221 /// some other patterns to fold away.  In particular, this looks for stores to
1222 /// neighboring locations of memory.  If it sees enough consequtive ones
1223 /// (currently 4) it attempts to merge them together into a memcpy/memset.
1224 bool GVN::processStore(StoreInst *SI, SmallVectorImpl<Instruction*> &toErase) {
1225   if (!FormMemSet) return false;
1226   if (SI->isVolatile()) return false;
1227   
1228   // There are two cases that are interesting for this code to handle: memcpy
1229   // and memset.  Right now we only handle memset.
1230   
1231   // Ensure that the value being stored is something that can be memset'able a
1232   // byte at a time like "0" or "-1" or any width, as well as things like
1233   // 0xA0A0A0A0 and 0.0.
1234   Value *ByteVal = isBytewiseValue(SI->getOperand(0));
1235   if (!ByteVal)
1236     return false;
1237
1238   TargetData &TD = getAnalysis<TargetData>();
1239   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
1240
1241   // Okay, so we now have a single store that can be splatable.  Scan to find
1242   // all subsequent stores of the same value to offset from the same pointer.
1243   // Join these together into ranges, so we can decide whether contiguous blocks
1244   // are stored.
1245   MemsetRanges Ranges(TD);
1246   
1247   // Add our first pointer.
1248   Ranges.addStore(0, SI);
1249   Value *StartPtr = SI->getPointerOperand();
1250   
1251   BasicBlock::iterator BI = SI;
1252   for (++BI; !isa<TerminatorInst>(BI); ++BI) {
1253     if (isa<CallInst>(BI) || isa<InvokeInst>(BI)) { 
1254       // If the call is readnone, ignore it, otherwise bail out.  We don't even
1255       // allow readonly here because we don't want something like:
1256       // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
1257       if (AA.getModRefBehavior(CallSite::get(BI)) ==
1258             AliasAnalysis::DoesNotAccessMemory)
1259         continue;
1260       
1261       // TODO: If this is a memset, try to join it in.
1262       
1263       break;
1264     } else if (isa<VAArgInst>(BI) || isa<LoadInst>(BI))
1265       break;
1266
1267     // If this is a non-store instruction it is fine, ignore it.
1268     StoreInst *NextStore = dyn_cast<StoreInst>(BI);
1269     if (NextStore == 0) continue;
1270     
1271     // If this is a store, see if we can merge it in.
1272     if (NextStore->isVolatile()) break;
1273     
1274     // Check to see if this stored value is of the same byte-splattable value.
1275     if (ByteVal != isBytewiseValue(NextStore->getOperand(0)))
1276       break;
1277
1278     // Check to see if this store is to a constant offset from the start ptr.
1279     int64_t Offset;
1280     if (!IsPointerOffset(StartPtr, NextStore->getPointerOperand(), Offset, TD))
1281       break;
1282
1283     Ranges.addStore(Offset, NextStore);
1284   }
1285   
1286   Function *MemSetF = 0;
1287   
1288   // Now that we have full information about ranges, loop over the ranges and
1289   // emit memset's for anything big enough to be worthwhile.
1290   bool MadeChange = false;
1291   for (MemsetRanges::const_iterator I = Ranges.begin(), E = Ranges.end();
1292        I != E; ++I) {
1293     const MemsetRange &Range = *I;
1294
1295     // If we found less than 4 stores to merge, ignore the subrange: it isn't
1296     // worth losing type information in llvm IR to do the transformation.
1297     if (Range.TheStores.size() < 4)
1298       continue;
1299     
1300     // Otherwise, we do want to transform this!  Create a new memset.  We put
1301     // the memset right after the first store that we found in this block.  This
1302     // ensures that the caller will increment the iterator to the memset before
1303     // it deletes all the stores.
1304     BasicBlock::iterator InsertPt = SI; ++InsertPt;
1305   
1306     if (MemSetF == 0)
1307       MemSetF = Intrinsic::getDeclaration(SI->getParent()->getParent()
1308                                           ->getParent(), Intrinsic::memset_i64);
1309     
1310     // StartPtr may not dominate the starting point.  Instead of using it, base
1311     // the destination pointer off the input to the first store in the block.
1312     StartPtr = SI->getPointerOperand();
1313   
1314     // Cast the start ptr to be i8* as memset requires.
1315     const Type *i8Ptr = PointerType::getUnqual(Type::Int8Ty);
1316     if (StartPtr->getType() != i8Ptr)
1317       StartPtr = new BitCastInst(StartPtr, i8Ptr, StartPtr->getNameStart(),
1318                                  InsertPt);
1319   
1320     // Offset the pointer if needed.
1321     if (Range.Start)
1322       StartPtr = new GetElementPtrInst(StartPtr, ConstantInt::get(Type::Int64Ty,
1323                                                                   Range.Start),
1324                                        "ptroffset", InsertPt);
1325   
1326     Value *Ops[] = {
1327       StartPtr, ByteVal,   // Start, value
1328       ConstantInt::get(Type::Int64Ty, Range.End-Range.Start),  // size
1329       ConstantInt::get(Type::Int32Ty, Range.Alignment)   // align
1330     };
1331     new CallInst(MemSetF, Ops, Ops+4, "", InsertPt);
1332   
1333     // Zap all the stores.
1334     toErase.append(Range.TheStores.begin(), Range.TheStores.end());
1335     ++NumMemSetInfer;
1336     MadeChange = true;
1337   }
1338   
1339   return MadeChange;
1340 }
1341
1342
1343 /// performCallSlotOptzn - takes a memcpy and a call that it depends on,
1344 /// and checks for the possibility of a call slot optimization by having
1345 /// the call write its result directly into the destination of the memcpy.
1346 bool GVN::performCallSlotOptzn(MemCpyInst *cpy, CallInst *C,
1347                                SmallVectorImpl<Instruction*> &toErase) {
1348   // The general transformation to keep in mind is
1349   //
1350   //   call @func(..., src, ...)
1351   //   memcpy(dest, src, ...)
1352   //
1353   // ->
1354   //
1355   //   memcpy(dest, src, ...)
1356   //   call @func(..., dest, ...)
1357   //
1358   // Since moving the memcpy is technically awkward, we additionally check that
1359   // src only holds uninitialized values at the moment of the call, meaning that
1360   // the memcpy can be discarded rather than moved.
1361
1362   // Deliberately get the source and destination with bitcasts stripped away,
1363   // because we'll need to do type comparisons based on the underlying type.
1364   Value* cpyDest = cpy->getDest();
1365   Value* cpySrc = cpy->getSource();
1366   CallSite CS = CallSite::get(C);
1367
1368   // We need to be able to reason about the size of the memcpy, so we require
1369   // that it be a constant.
1370   ConstantInt* cpyLength = dyn_cast<ConstantInt>(cpy->getLength());
1371   if (!cpyLength)
1372     return false;
1373
1374   // Require that src be an alloca.  This simplifies the reasoning considerably.
1375   AllocaInst* srcAlloca = dyn_cast<AllocaInst>(cpySrc);
1376   if (!srcAlloca)
1377     return false;
1378
1379   // Check that all of src is copied to dest.
1380   TargetData& TD = getAnalysis<TargetData>();
1381
1382   ConstantInt* srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
1383   if (!srcArraySize)
1384     return false;
1385
1386   uint64_t srcSize = TD.getABITypeSize(srcAlloca->getAllocatedType()) *
1387     srcArraySize->getZExtValue();
1388
1389   if (cpyLength->getZExtValue() < srcSize)
1390     return false;
1391
1392   // Check that accessing the first srcSize bytes of dest will not cause a
1393   // trap.  Otherwise the transform is invalid since it might cause a trap
1394   // to occur earlier than it otherwise would.
1395   if (AllocaInst* A = dyn_cast<AllocaInst>(cpyDest)) {
1396     // The destination is an alloca.  Check it is larger than srcSize.
1397     ConstantInt* destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
1398     if (!destArraySize)
1399       return false;
1400
1401     uint64_t destSize = TD.getABITypeSize(A->getAllocatedType()) *
1402       destArraySize->getZExtValue();
1403
1404     if (destSize < srcSize)
1405       return false;
1406   } else if (Argument* A = dyn_cast<Argument>(cpyDest)) {
1407     // If the destination is an sret parameter then only accesses that are
1408     // outside of the returned struct type can trap.
1409     if (!A->hasStructRetAttr())
1410       return false;
1411
1412     const Type* StructTy = cast<PointerType>(A->getType())->getElementType();
1413     uint64_t destSize = TD.getABITypeSize(StructTy);
1414
1415     if (destSize < srcSize)
1416       return false;
1417   } else {
1418     return false;
1419   }
1420
1421   // Check that src is not accessed except via the call and the memcpy.  This
1422   // guarantees that it holds only undefined values when passed in (so the final
1423   // memcpy can be dropped), that it is not read or written between the call and
1424   // the memcpy, and that writing beyond the end of it is undefined.
1425   SmallVector<User*, 8> srcUseList(srcAlloca->use_begin(),
1426                                    srcAlloca->use_end());
1427   while (!srcUseList.empty()) {
1428     User* UI = srcUseList.back();
1429     srcUseList.pop_back();
1430
1431     if (isa<GetElementPtrInst>(UI) || isa<BitCastInst>(UI)) {
1432       for (User::use_iterator I = UI->use_begin(), E = UI->use_end();
1433            I != E; ++I)
1434         srcUseList.push_back(*I);
1435     } else if (UI != C && UI != cpy) {
1436       return false;
1437     }
1438   }
1439
1440   // Since we're changing the parameter to the callsite, we need to make sure
1441   // that what would be the new parameter dominates the callsite.
1442   DominatorTree& DT = getAnalysis<DominatorTree>();
1443   if (Instruction* cpyDestInst = dyn_cast<Instruction>(cpyDest))
1444     if (!DT.dominates(cpyDestInst, C))
1445       return false;
1446
1447   // In addition to knowing that the call does not access src in some
1448   // unexpected manner, for example via a global, which we deduce from
1449   // the use analysis, we also need to know that it does not sneakily
1450   // access dest.  We rely on AA to figure this out for us.
1451   AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
1452   if (AA.getModRefInfo(C, cpy->getRawDest(), srcSize) !=
1453       AliasAnalysis::NoModRef)
1454     return false;
1455
1456   // All the checks have passed, so do the transformation.
1457   for (unsigned i = 0; i < CS.arg_size(); ++i)
1458     if (CS.getArgument(i) == cpySrc) {
1459       if (cpySrc->getType() != cpyDest->getType())
1460         cpyDest = CastInst::createPointerCast(cpyDest, cpySrc->getType(),
1461                                               cpyDest->getName(), C);
1462       CS.setArgument(i, cpyDest);
1463     }
1464
1465   // Drop any cached information about the call, because we may have changed
1466   // its dependence information by changing its parameter.
1467   MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1468   MD.dropInstruction(C);
1469
1470   // Remove the memcpy
1471   MD.removeInstruction(cpy);
1472   toErase.push_back(cpy);
1473
1474   return true;
1475 }
1476
1477 /// processMemCpy - perform simplication of memcpy's.  If we have memcpy A which
1478 /// copies X to Y, and memcpy B which copies Y to Z, then we can rewrite B to be
1479 /// a memcpy from X to Z (or potentially a memmove, depending on circumstances).
1480 ///  This allows later passes to remove the first memcpy altogether.
1481 bool GVN::processMemCpy(MemCpyInst* M, MemCpyInst* MDep,
1482                         SmallVectorImpl<Instruction*> &toErase) {
1483   // We can only transforms memcpy's where the dest of one is the source of the
1484   // other
1485   if (M->getSource() != MDep->getDest())
1486     return false;
1487   
1488   // Second, the length of the memcpy's must be the same, or the preceeding one
1489   // must be larger than the following one.
1490   ConstantInt* C1 = dyn_cast<ConstantInt>(MDep->getLength());
1491   ConstantInt* C2 = dyn_cast<ConstantInt>(M->getLength());
1492   if (!C1 || !C2)
1493     return false;
1494   
1495   uint64_t DepSize = C1->getValue().getZExtValue();
1496   uint64_t CpySize = C2->getValue().getZExtValue();
1497   
1498   if (DepSize < CpySize)
1499     return false;
1500   
1501   // Finally, we have to make sure that the dest of the second does not
1502   // alias the source of the first
1503   AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
1504   if (AA.alias(M->getRawDest(), CpySize, MDep->getRawSource(), DepSize) !=
1505       AliasAnalysis::NoAlias)
1506     return false;
1507   else if (AA.alias(M->getRawDest(), CpySize, M->getRawSource(), CpySize) !=
1508            AliasAnalysis::NoAlias)
1509     return false;
1510   else if (AA.alias(MDep->getRawDest(), DepSize, MDep->getRawSource(), DepSize)
1511            != AliasAnalysis::NoAlias)
1512     return false;
1513   
1514   // If all checks passed, then we can transform these memcpy's
1515   Function* MemCpyFun = Intrinsic::getDeclaration(
1516                                  M->getParent()->getParent()->getParent(),
1517                                  M->getIntrinsicID());
1518     
1519   std::vector<Value*> args;
1520   args.push_back(M->getRawDest());
1521   args.push_back(MDep->getRawSource());
1522   args.push_back(M->getLength());
1523   args.push_back(M->getAlignment());
1524   
1525   CallInst* C = new CallInst(MemCpyFun, args.begin(), args.end(), "", M);
1526   
1527   MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1528   if (MD.getDependency(C) == MDep) {
1529     MD.dropInstruction(M);
1530     toErase.push_back(M);
1531     return true;
1532   }
1533   
1534   MD.removeInstruction(C);
1535   toErase.push_back(C);
1536   return false;
1537 }
1538
1539 /// processInstruction - When calculating availability, handle an instruction
1540 /// by inserting it into the appropriate sets
1541 bool GVN::processInstruction(Instruction *I, ValueNumberedSet &currAvail,
1542                              DenseMap<Value*, LoadInst*> &lastSeenLoad,
1543                              SmallVectorImpl<Instruction*> &toErase) {
1544   if (LoadInst* L = dyn_cast<LoadInst>(I))
1545     return processLoad(L, lastSeenLoad, toErase);
1546   
1547   if (StoreInst *SI = dyn_cast<StoreInst>(I))
1548     return processStore(SI, toErase);
1549   
1550   if (MemCpyInst* M = dyn_cast<MemCpyInst>(I)) {
1551     MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1552
1553     // The are two possible optimizations we can do for memcpy:
1554     //   a) memcpy-memcpy xform which exposes redundance for DSE
1555     //   b) call-memcpy xform for return slot optimization
1556     Instruction* dep = MD.getDependency(M);
1557     if (dep == MemoryDependenceAnalysis::None ||
1558         dep == MemoryDependenceAnalysis::NonLocal)
1559       return false;
1560     if (MemCpyInst *MemCpy = dyn_cast<MemCpyInst>(dep))
1561       return processMemCpy(M, MemCpy, toErase);
1562     if (CallInst* C = dyn_cast<CallInst>(dep))
1563       return performCallSlotOptzn(M, C, toErase);
1564     return false;
1565   }
1566   
1567   unsigned num = VN.lookup_or_add(I);
1568   
1569   // Collapse PHI nodes
1570   if (PHINode* p = dyn_cast<PHINode>(I)) {
1571     Value* constVal = CollapsePhi(p);
1572     
1573     if (constVal) {
1574       for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end();
1575            PI != PE; ++PI)
1576         if (PI->second.count(p))
1577           PI->second.erase(p);
1578         
1579       p->replaceAllUsesWith(constVal);
1580       toErase.push_back(p);
1581     }
1582   // Perform value-number based elimination
1583   } else if (currAvail.test(num)) {
1584     Value* repl = find_leader(currAvail, num);
1585     
1586     if (CallInst* CI = dyn_cast<CallInst>(I)) {
1587       AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
1588       if (!AA.doesNotAccessMemory(CI)) {
1589         MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1590         if (cast<Instruction>(repl)->getParent() != CI->getParent() ||
1591             MD.getDependency(CI) != MD.getDependency(cast<CallInst>(repl))) {
1592           // There must be an intervening may-alias store, so nothing from
1593           // this point on will be able to be replaced with the preceding call
1594           currAvail.erase(repl);
1595           currAvail.insert(I);
1596           
1597           return false;
1598         }
1599       }
1600     }
1601     
1602     // Remove it!
1603     MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1604     MD.removeInstruction(I);
1605     
1606     VN.erase(I);
1607     I->replaceAllUsesWith(repl);
1608     toErase.push_back(I);
1609     return true;
1610   } else if (!I->isTerminator()) {
1611     currAvail.set(num);
1612     currAvail.insert(I);
1613   }
1614   
1615   return false;
1616 }
1617
1618 // GVN::runOnFunction - This is the main transformation entry point for a
1619 // function.
1620 //
1621 bool GVN::runOnFunction(Function& F) {
1622   VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
1623   
1624   bool changed = false;
1625   bool shouldContinue = true;
1626   
1627   while (shouldContinue) {
1628     shouldContinue = iterateOnFunction(F);
1629     changed |= shouldContinue;
1630   }
1631   
1632   return changed;
1633 }
1634
1635
1636 // GVN::iterateOnFunction - Executes one iteration of GVN
1637 bool GVN::iterateOnFunction(Function &F) {
1638   // Clean out global sets from any previous functions
1639   VN.clear();
1640   availableOut.clear();
1641   phiMap.clear();
1642  
1643   bool changed_function = false;
1644   
1645   DominatorTree &DT = getAnalysis<DominatorTree>();   
1646   
1647   SmallVector<Instruction*, 4> toErase;
1648   DenseMap<Value*, LoadInst*> lastSeenLoad;
1649
1650   // Top-down walk of the dominator tree
1651   for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1652          E = df_end(DT.getRootNode()); DI != E; ++DI) {
1653     
1654     // Get the set to update for this block
1655     ValueNumberedSet& currAvail = availableOut[DI->getBlock()];     
1656     lastSeenLoad.clear();
1657
1658     BasicBlock* BB = DI->getBlock();
1659   
1660     // A block inherits AVAIL_OUT from its dominator
1661     if (DI->getIDom() != 0)
1662       currAvail = availableOut[DI->getIDom()->getBlock()];
1663
1664     for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1665          BI != BE; ) {
1666       changed_function |= processInstruction(BI, currAvail,
1667                                              lastSeenLoad, toErase);
1668       
1669       NumGVNInstr += toErase.size();
1670       
1671       // Avoid iterator invalidation
1672       ++BI;
1673
1674       for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
1675            E = toErase.end(); I != E; ++I)
1676         (*I)->eraseFromParent();
1677
1678       toErase.clear();
1679     }
1680   }
1681   
1682   return changed_function;
1683 }