Move a bit more functionality to LLVMContext, which apparently wasn't being used...
[oota-llvm.git] / lib / VMCore / Constants.cpp
1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
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 file implements the Constant* classes...
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Constants.h"
15 #include "ConstantFold.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/GlobalValue.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/MDNode.h"
20 #include "llvm/Module.h"
21 #include "llvm/ADT/FoldingSet.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/StringMap.h"
24 #include "llvm/Support/Compiler.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/ManagedStatic.h"
28 #include "llvm/Support/MathExtras.h"
29 #include "llvm/System/Mutex.h"
30 #include "llvm/System/RWMutex.h"
31 #include "llvm/System/Threading.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include <algorithm>
35 #include <map>
36 using namespace llvm;
37
38 //===----------------------------------------------------------------------===//
39 //                              Constant Class
40 //===----------------------------------------------------------------------===//
41
42 // Becomes a no-op when multithreading is disabled.
43 ManagedStatic<sys::SmartRWMutex<true> > ConstantsLock;
44
45 void Constant::destroyConstantImpl() {
46   // When a Constant is destroyed, there may be lingering
47   // references to the constant by other constants in the constant pool.  These
48   // constants are implicitly dependent on the module that is being deleted,
49   // but they don't know that.  Because we only find out when the CPV is
50   // deleted, we must now notify all of our users (that should only be
51   // Constants) that they are, in fact, invalid now and should be deleted.
52   //
53   while (!use_empty()) {
54     Value *V = use_back();
55 #ifndef NDEBUG      // Only in -g mode...
56     if (!isa<Constant>(V))
57       DOUT << "While deleting: " << *this
58            << "\n\nUse still stuck around after Def is destroyed: "
59            << *V << "\n\n";
60 #endif
61     assert(isa<Constant>(V) && "References remain to Constant being destroyed");
62     Constant *CV = cast<Constant>(V);
63     CV->destroyConstant();
64
65     // The constant should remove itself from our use list...
66     assert((use_empty() || use_back() != V) && "Constant not removed!");
67   }
68
69   // Value has no outstanding references it is safe to delete it now...
70   delete this;
71 }
72
73 /// canTrap - Return true if evaluation of this constant could trap.  This is
74 /// true for things like constant expressions that could divide by zero.
75 bool Constant::canTrap() const {
76   assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
77   // The only thing that could possibly trap are constant exprs.
78   const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
79   if (!CE) return false;
80   
81   // ConstantExpr traps if any operands can trap. 
82   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
83     if (getOperand(i)->canTrap()) 
84       return true;
85
86   // Otherwise, only specific operations can trap.
87   switch (CE->getOpcode()) {
88   default:
89     return false;
90   case Instruction::UDiv:
91   case Instruction::SDiv:
92   case Instruction::FDiv:
93   case Instruction::URem:
94   case Instruction::SRem:
95   case Instruction::FRem:
96     // Div and rem can trap if the RHS is not known to be non-zero.
97     if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
98       return true;
99     return false;
100   }
101 }
102
103 /// ContainsRelocations - Return true if the constant value contains relocations
104 /// which cannot be resolved at compile time. Kind argument is used to filter
105 /// only 'interesting' sorts of relocations.
106 bool Constant::ContainsRelocations(unsigned Kind) const {
107   if (const GlobalValue* GV = dyn_cast<GlobalValue>(this)) {
108     bool isLocal = GV->hasLocalLinkage();
109     if ((Kind & Reloc::Local) && isLocal) {
110       // Global has local linkage and 'local' kind of relocations are
111       // requested
112       return true;
113     }
114
115     if ((Kind & Reloc::Global) && !isLocal) {
116       // Global has non-local linkage and 'global' kind of relocations are
117       // requested
118       return true;
119     }
120
121     return false;
122   }
123
124   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
125     if (getOperand(i)->ContainsRelocations(Kind))
126       return true;
127
128   return false;
129 }
130
131 /// getVectorElements - This method, which is only valid on constant of vector
132 /// type, returns the elements of the vector in the specified smallvector.
133 /// This handles breaking down a vector undef into undef elements, etc.  For
134 /// constant exprs and other cases we can't handle, we return an empty vector.
135 void Constant::getVectorElements(LLVMContext &Context,
136                                  SmallVectorImpl<Constant*> &Elts) const {
137   assert(isa<VectorType>(getType()) && "Not a vector constant!");
138   
139   if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
140     for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
141       Elts.push_back(CV->getOperand(i));
142     return;
143   }
144   
145   const VectorType *VT = cast<VectorType>(getType());
146   if (isa<ConstantAggregateZero>(this)) {
147     Elts.assign(VT->getNumElements(), 
148                 Context.getNullValue(VT->getElementType()));
149     return;
150   }
151   
152   if (isa<UndefValue>(this)) {
153     Elts.assign(VT->getNumElements(), Context.getUndef(VT->getElementType()));
154     return;
155   }
156   
157   // Unknown type, must be constant expr etc.
158 }
159
160
161
162 //===----------------------------------------------------------------------===//
163 //                                ConstantInt
164 //===----------------------------------------------------------------------===//
165
166 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
167   : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
168   assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
169 }
170
171 ConstantInt *ConstantInt::TheTrueVal = 0;
172 ConstantInt *ConstantInt::TheFalseVal = 0;
173
174 namespace llvm {
175   void CleanupTrueFalse(void *) {
176     ConstantInt::ResetTrueFalse();
177   }
178 }
179
180 static ManagedCleanup<llvm::CleanupTrueFalse> TrueFalseCleanup;
181
182 ConstantInt *ConstantInt::CreateTrueFalseVals(bool WhichOne) {
183   assert(TheTrueVal == 0 && TheFalseVal == 0);
184   TheTrueVal  = get(Type::Int1Ty, 1);
185   TheFalseVal = get(Type::Int1Ty, 0);
186   
187   // Ensure that llvm_shutdown nulls out TheTrueVal/TheFalseVal.
188   TrueFalseCleanup.Register();
189   
190   return WhichOne ? TheTrueVal : TheFalseVal;
191 }
192
193
194 namespace {
195   struct DenseMapAPIntKeyInfo {
196     struct KeyTy {
197       APInt val;
198       const Type* type;
199       KeyTy(const APInt& V, const Type* Ty) : val(V), type(Ty) {}
200       KeyTy(const KeyTy& that) : val(that.val), type(that.type) {}
201       bool operator==(const KeyTy& that) const {
202         return type == that.type && this->val == that.val;
203       }
204       bool operator!=(const KeyTy& that) const {
205         return !this->operator==(that);
206       }
207     };
208     static inline KeyTy getEmptyKey() { return KeyTy(APInt(1,0), 0); }
209     static inline KeyTy getTombstoneKey() { return KeyTy(APInt(1,1), 0); }
210     static unsigned getHashValue(const KeyTy &Key) {
211       return DenseMapInfo<void*>::getHashValue(Key.type) ^ 
212         Key.val.getHashValue();
213     }
214     static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
215       return LHS == RHS;
216     }
217     static bool isPod() { return false; }
218   };
219 }
220
221
222 typedef DenseMap<DenseMapAPIntKeyInfo::KeyTy, ConstantInt*, 
223                  DenseMapAPIntKeyInfo> IntMapTy;
224 static ManagedStatic<IntMapTy> IntConstants;
225
226 ConstantInt *ConstantInt::get(const IntegerType *Ty,
227                               uint64_t V, bool isSigned) {
228   return get(APInt(Ty->getBitWidth(), V, isSigned));
229 }
230
231 Constant *ConstantInt::get(const Type *Ty, uint64_t V, bool isSigned) {
232   Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
233
234   // For vectors, broadcast the value.
235   if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
236     return
237       ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
238
239   return C;
240 }
241
242 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap 
243 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
244 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
245 // compare APInt's of different widths, which would violate an APInt class
246 // invariant which generates an assertion.
247 ConstantInt *ConstantInt::get(const APInt& V) {
248   // Get the corresponding integer type for the bit width of the value.
249   const IntegerType *ITy = IntegerType::get(V.getBitWidth());
250   // get an existing value or the insertion position
251   DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
252   
253   ConstantsLock->reader_acquire();
254   ConstantInt *&Slot = (*IntConstants)[Key]; 
255   ConstantsLock->reader_release();
256     
257   if (!Slot) {
258     sys::SmartScopedWriter<true> Writer(*ConstantsLock);
259     ConstantInt *&NewSlot = (*IntConstants)[Key]; 
260     if (!Slot) {
261       NewSlot = new ConstantInt(ITy, V);
262     }
263     
264     return NewSlot;
265   } else {
266     return Slot;
267   }
268 }
269
270 Constant *ConstantInt::get(const Type *Ty, const APInt &V) {
271   ConstantInt *C = ConstantInt::get(V);
272   assert(C->getType() == Ty->getScalarType() &&
273          "ConstantInt type doesn't match the type implied by its value!");
274
275   // For vectors, broadcast the value.
276   if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
277     return
278       ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
279
280   return C;
281 }
282
283 //===----------------------------------------------------------------------===//
284 //                                ConstantFP
285 //===----------------------------------------------------------------------===//
286
287 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
288   if (Ty == Type::FloatTy)
289     return &APFloat::IEEEsingle;
290   if (Ty == Type::DoubleTy)
291     return &APFloat::IEEEdouble;
292   if (Ty == Type::X86_FP80Ty)
293     return &APFloat::x87DoubleExtended;
294   else if (Ty == Type::FP128Ty)
295     return &APFloat::IEEEquad;
296   
297   assert(Ty == Type::PPC_FP128Ty && "Unknown FP format");
298   return &APFloat::PPCDoubleDouble;
299 }
300
301 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
302   : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
303   assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
304          "FP type Mismatch");
305 }
306
307 bool ConstantFP::isNullValue() const {
308   return Val.isZero() && !Val.isNegative();
309 }
310
311 bool ConstantFP::isExactlyValue(const APFloat& V) const {
312   return Val.bitwiseIsEqual(V);
313 }
314
315 namespace {
316   struct DenseMapAPFloatKeyInfo {
317     struct KeyTy {
318       APFloat val;
319       KeyTy(const APFloat& V) : val(V){}
320       KeyTy(const KeyTy& that) : val(that.val) {}
321       bool operator==(const KeyTy& that) const {
322         return this->val.bitwiseIsEqual(that.val);
323       }
324       bool operator!=(const KeyTy& that) const {
325         return !this->operator==(that);
326       }
327     };
328     static inline KeyTy getEmptyKey() { 
329       return KeyTy(APFloat(APFloat::Bogus,1));
330     }
331     static inline KeyTy getTombstoneKey() { 
332       return KeyTy(APFloat(APFloat::Bogus,2)); 
333     }
334     static unsigned getHashValue(const KeyTy &Key) {
335       return Key.val.getHashValue();
336     }
337     static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
338       return LHS == RHS;
339     }
340     static bool isPod() { return false; }
341   };
342 }
343
344 //---- ConstantFP::get() implementation...
345 //
346 typedef DenseMap<DenseMapAPFloatKeyInfo::KeyTy, ConstantFP*, 
347                  DenseMapAPFloatKeyInfo> FPMapTy;
348
349 static ManagedStatic<FPMapTy> FPConstants;
350
351 ConstantFP *ConstantFP::get(const APFloat &V) {
352   DenseMapAPFloatKeyInfo::KeyTy Key(V);
353   
354   ConstantsLock->reader_acquire();
355   ConstantFP *&Slot = (*FPConstants)[Key];
356   ConstantsLock->reader_release();
357     
358   if (!Slot) {
359     sys::SmartScopedWriter<true> Writer(*ConstantsLock);
360     ConstantFP *&NewSlot = (*FPConstants)[Key];
361     if (!NewSlot) {
362       const Type *Ty;
363       if (&V.getSemantics() == &APFloat::IEEEsingle)
364         Ty = Type::FloatTy;
365       else if (&V.getSemantics() == &APFloat::IEEEdouble)
366         Ty = Type::DoubleTy;
367       else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
368         Ty = Type::X86_FP80Ty;
369       else if (&V.getSemantics() == &APFloat::IEEEquad)
370         Ty = Type::FP128Ty;
371       else {
372         assert(&V.getSemantics() == &APFloat::PPCDoubleDouble && 
373                "Unknown FP format");
374         Ty = Type::PPC_FP128Ty;
375       }
376       NewSlot = new ConstantFP(Ty, V);
377     }
378     
379     return NewSlot;
380   }
381   
382   return Slot;
383 }
384
385 //===----------------------------------------------------------------------===//
386 //                            ConstantXXX Classes
387 //===----------------------------------------------------------------------===//
388
389
390 ConstantArray::ConstantArray(const ArrayType *T,
391                              const std::vector<Constant*> &V)
392   : Constant(T, ConstantArrayVal,
393              OperandTraits<ConstantArray>::op_end(this) - V.size(),
394              V.size()) {
395   assert(V.size() == T->getNumElements() &&
396          "Invalid initializer vector for constant array");
397   Use *OL = OperandList;
398   for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
399        I != E; ++I, ++OL) {
400     Constant *C = *I;
401     assert((C->getType() == T->getElementType() ||
402             (T->isAbstract() &&
403              C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
404            "Initializer for array element doesn't match array element type!");
405     *OL = C;
406   }
407 }
408
409
410 ConstantStruct::ConstantStruct(const StructType *T,
411                                const std::vector<Constant*> &V)
412   : Constant(T, ConstantStructVal,
413              OperandTraits<ConstantStruct>::op_end(this) - V.size(),
414              V.size()) {
415   assert(V.size() == T->getNumElements() &&
416          "Invalid initializer vector for constant structure");
417   Use *OL = OperandList;
418   for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
419        I != E; ++I, ++OL) {
420     Constant *C = *I;
421     assert((C->getType() == T->getElementType(I-V.begin()) ||
422             ((T->getElementType(I-V.begin())->isAbstract() ||
423               C->getType()->isAbstract()) &&
424              T->getElementType(I-V.begin())->getTypeID() == 
425                    C->getType()->getTypeID())) &&
426            "Initializer for struct element doesn't match struct element type!");
427     *OL = C;
428   }
429 }
430
431
432 ConstantVector::ConstantVector(const VectorType *T,
433                                const std::vector<Constant*> &V)
434   : Constant(T, ConstantVectorVal,
435              OperandTraits<ConstantVector>::op_end(this) - V.size(),
436              V.size()) {
437   Use *OL = OperandList;
438     for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
439          I != E; ++I, ++OL) {
440       Constant *C = *I;
441       assert((C->getType() == T->getElementType() ||
442             (T->isAbstract() &&
443              C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
444            "Initializer for vector element doesn't match vector element type!");
445     *OL = C;
446   }
447 }
448
449
450 namespace llvm {
451 // We declare several classes private to this file, so use an anonymous
452 // namespace
453 namespace {
454
455 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
456 /// behind the scenes to implement unary constant exprs.
457 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
458   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
459 public:
460   // allocate space for exactly one operand
461   void *operator new(size_t s) {
462     return User::operator new(s, 1);
463   }
464   UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
465     : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
466     Op<0>() = C;
467   }
468   /// Transparently provide more efficient getOperand methods.
469   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
470 };
471
472 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
473 /// behind the scenes to implement binary constant exprs.
474 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
475   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
476 public:
477   // allocate space for exactly two operands
478   void *operator new(size_t s) {
479     return User::operator new(s, 2);
480   }
481   BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
482     : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
483     Op<0>() = C1;
484     Op<1>() = C2;
485   }
486   /// Transparently provide more efficient getOperand methods.
487   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
488 };
489
490 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
491 /// behind the scenes to implement select constant exprs.
492 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
493   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
494 public:
495   // allocate space for exactly three operands
496   void *operator new(size_t s) {
497     return User::operator new(s, 3);
498   }
499   SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
500     : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
501     Op<0>() = C1;
502     Op<1>() = C2;
503     Op<2>() = C3;
504   }
505   /// Transparently provide more efficient getOperand methods.
506   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
507 };
508
509 /// ExtractElementConstantExpr - This class is private to
510 /// Constants.cpp, and is used behind the scenes to implement
511 /// extractelement constant exprs.
512 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
513   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
514 public:
515   // allocate space for exactly two operands
516   void *operator new(size_t s) {
517     return User::operator new(s, 2);
518   }
519   ExtractElementConstantExpr(Constant *C1, Constant *C2)
520     : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(), 
521                    Instruction::ExtractElement, &Op<0>(), 2) {
522     Op<0>() = C1;
523     Op<1>() = C2;
524   }
525   /// Transparently provide more efficient getOperand methods.
526   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
527 };
528
529 /// InsertElementConstantExpr - This class is private to
530 /// Constants.cpp, and is used behind the scenes to implement
531 /// insertelement constant exprs.
532 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
533   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
534 public:
535   // allocate space for exactly three operands
536   void *operator new(size_t s) {
537     return User::operator new(s, 3);
538   }
539   InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
540     : ConstantExpr(C1->getType(), Instruction::InsertElement, 
541                    &Op<0>(), 3) {
542     Op<0>() = C1;
543     Op<1>() = C2;
544     Op<2>() = C3;
545   }
546   /// Transparently provide more efficient getOperand methods.
547   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
548 };
549
550 /// ShuffleVectorConstantExpr - This class is private to
551 /// Constants.cpp, and is used behind the scenes to implement
552 /// shufflevector constant exprs.
553 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
554   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
555 public:
556   // allocate space for exactly three operands
557   void *operator new(size_t s) {
558     return User::operator new(s, 3);
559   }
560   ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
561   : ConstantExpr(VectorType::get(
562                    cast<VectorType>(C1->getType())->getElementType(),
563                    cast<VectorType>(C3->getType())->getNumElements()),
564                  Instruction::ShuffleVector, 
565                  &Op<0>(), 3) {
566     Op<0>() = C1;
567     Op<1>() = C2;
568     Op<2>() = C3;
569   }
570   /// Transparently provide more efficient getOperand methods.
571   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
572 };
573
574 /// ExtractValueConstantExpr - This class is private to
575 /// Constants.cpp, and is used behind the scenes to implement
576 /// extractvalue constant exprs.
577 class VISIBILITY_HIDDEN ExtractValueConstantExpr : public ConstantExpr {
578   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
579 public:
580   // allocate space for exactly one operand
581   void *operator new(size_t s) {
582     return User::operator new(s, 1);
583   }
584   ExtractValueConstantExpr(Constant *Agg,
585                            const SmallVector<unsigned, 4> &IdxList,
586                            const Type *DestTy)
587     : ConstantExpr(DestTy, Instruction::ExtractValue, &Op<0>(), 1),
588       Indices(IdxList) {
589     Op<0>() = Agg;
590   }
591
592   /// Indices - These identify which value to extract.
593   const SmallVector<unsigned, 4> Indices;
594
595   /// Transparently provide more efficient getOperand methods.
596   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
597 };
598
599 /// InsertValueConstantExpr - This class is private to
600 /// Constants.cpp, and is used behind the scenes to implement
601 /// insertvalue constant exprs.
602 class VISIBILITY_HIDDEN InsertValueConstantExpr : public ConstantExpr {
603   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
604 public:
605   // allocate space for exactly one operand
606   void *operator new(size_t s) {
607     return User::operator new(s, 2);
608   }
609   InsertValueConstantExpr(Constant *Agg, Constant *Val,
610                           const SmallVector<unsigned, 4> &IdxList,
611                           const Type *DestTy)
612     : ConstantExpr(DestTy, Instruction::InsertValue, &Op<0>(), 2),
613       Indices(IdxList) {
614     Op<0>() = Agg;
615     Op<1>() = Val;
616   }
617
618   /// Indices - These identify the position for the insertion.
619   const SmallVector<unsigned, 4> Indices;
620
621   /// Transparently provide more efficient getOperand methods.
622   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
623 };
624
625
626 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
627 /// used behind the scenes to implement getelementpr constant exprs.
628 class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
629   GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
630                             const Type *DestTy);
631 public:
632   static GetElementPtrConstantExpr *Create(Constant *C,
633                                            const std::vector<Constant*>&IdxList,
634                                            const Type *DestTy) {
635     return new(IdxList.size() + 1)
636       GetElementPtrConstantExpr(C, IdxList, DestTy);
637   }
638   /// Transparently provide more efficient getOperand methods.
639   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
640 };
641
642 // CompareConstantExpr - This class is private to Constants.cpp, and is used
643 // behind the scenes to implement ICmp and FCmp constant expressions. This is
644 // needed in order to store the predicate value for these instructions.
645 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
646   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
647   // allocate space for exactly two operands
648   void *operator new(size_t s) {
649     return User::operator new(s, 2);
650   }
651   unsigned short predicate;
652   CompareConstantExpr(const Type *ty, Instruction::OtherOps opc,
653                       unsigned short pred,  Constant* LHS, Constant* RHS)
654     : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
655     Op<0>() = LHS;
656     Op<1>() = RHS;
657   }
658   /// Transparently provide more efficient getOperand methods.
659   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
660 };
661
662 } // end anonymous namespace
663
664 template <>
665 struct OperandTraits<UnaryConstantExpr> : FixedNumOperandTraits<1> {
666 };
667 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
668
669 template <>
670 struct OperandTraits<BinaryConstantExpr> : FixedNumOperandTraits<2> {
671 };
672 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
673
674 template <>
675 struct OperandTraits<SelectConstantExpr> : FixedNumOperandTraits<3> {
676 };
677 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
678
679 template <>
680 struct OperandTraits<ExtractElementConstantExpr> : FixedNumOperandTraits<2> {
681 };
682 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
683
684 template <>
685 struct OperandTraits<InsertElementConstantExpr> : FixedNumOperandTraits<3> {
686 };
687 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
688
689 template <>
690 struct OperandTraits<ShuffleVectorConstantExpr> : FixedNumOperandTraits<3> {
691 };
692 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
693
694 template <>
695 struct OperandTraits<ExtractValueConstantExpr> : FixedNumOperandTraits<1> {
696 };
697 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractValueConstantExpr, Value)
698
699 template <>
700 struct OperandTraits<InsertValueConstantExpr> : FixedNumOperandTraits<2> {
701 };
702 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueConstantExpr, Value)
703
704 template <>
705 struct OperandTraits<GetElementPtrConstantExpr> : VariadicOperandTraits<1> {
706 };
707
708 GetElementPtrConstantExpr::GetElementPtrConstantExpr
709   (Constant *C,
710    const std::vector<Constant*> &IdxList,
711    const Type *DestTy)
712     : ConstantExpr(DestTy, Instruction::GetElementPtr,
713                    OperandTraits<GetElementPtrConstantExpr>::op_end(this)
714                    - (IdxList.size()+1),
715                    IdxList.size()+1) {
716   OperandList[0] = C;
717   for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
718     OperandList[i+1] = IdxList[i];
719 }
720
721 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
722
723
724 template <>
725 struct OperandTraits<CompareConstantExpr> : FixedNumOperandTraits<2> {
726 };
727 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
728
729
730 } // End llvm namespace
731
732
733 // Utility function for determining if a ConstantExpr is a CastOp or not. This
734 // can't be inline because we don't want to #include Instruction.h into
735 // Constant.h
736 bool ConstantExpr::isCast() const {
737   return Instruction::isCast(getOpcode());
738 }
739
740 bool ConstantExpr::isCompare() const {
741   return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
742 }
743
744 bool ConstantExpr::hasIndices() const {
745   return getOpcode() == Instruction::ExtractValue ||
746          getOpcode() == Instruction::InsertValue;
747 }
748
749 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
750   if (const ExtractValueConstantExpr *EVCE =
751         dyn_cast<ExtractValueConstantExpr>(this))
752     return EVCE->Indices;
753
754   return cast<InsertValueConstantExpr>(this)->Indices;
755 }
756
757 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
758   return get(Instruction::Add, C1, C2);
759 }
760 Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
761   return get(Instruction::FAdd, C1, C2);
762 }
763 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
764   return get(Instruction::Sub, C1, C2);
765 }
766 Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
767   return get(Instruction::FSub, C1, C2);
768 }
769 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
770   return get(Instruction::Mul, C1, C2);
771 }
772 Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
773   return get(Instruction::FMul, C1, C2);
774 }
775 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
776   return get(Instruction::UDiv, C1, C2);
777 }
778 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
779   return get(Instruction::SDiv, C1, C2);
780 }
781 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
782   return get(Instruction::FDiv, C1, C2);
783 }
784 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
785   return get(Instruction::URem, C1, C2);
786 }
787 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
788   return get(Instruction::SRem, C1, C2);
789 }
790 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
791   return get(Instruction::FRem, C1, C2);
792 }
793 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
794   return get(Instruction::And, C1, C2);
795 }
796 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
797   return get(Instruction::Or, C1, C2);
798 }
799 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
800   return get(Instruction::Xor, C1, C2);
801 }
802 unsigned ConstantExpr::getPredicate() const {
803   assert(getOpcode() == Instruction::FCmp || 
804          getOpcode() == Instruction::ICmp);
805   return ((const CompareConstantExpr*)this)->predicate;
806 }
807 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
808   return get(Instruction::Shl, C1, C2);
809 }
810 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
811   return get(Instruction::LShr, C1, C2);
812 }
813 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
814   return get(Instruction::AShr, C1, C2);
815 }
816
817 /// getWithOperandReplaced - Return a constant expression identical to this
818 /// one, but with the specified operand set to the specified value.
819 Constant *
820 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
821   assert(OpNo < getNumOperands() && "Operand num is out of range!");
822   assert(Op->getType() == getOperand(OpNo)->getType() &&
823          "Replacing operand with value of different type!");
824   if (getOperand(OpNo) == Op)
825     return const_cast<ConstantExpr*>(this);
826   
827   Constant *Op0, *Op1, *Op2;
828   switch (getOpcode()) {
829   case Instruction::Trunc:
830   case Instruction::ZExt:
831   case Instruction::SExt:
832   case Instruction::FPTrunc:
833   case Instruction::FPExt:
834   case Instruction::UIToFP:
835   case Instruction::SIToFP:
836   case Instruction::FPToUI:
837   case Instruction::FPToSI:
838   case Instruction::PtrToInt:
839   case Instruction::IntToPtr:
840   case Instruction::BitCast:
841     return ConstantExpr::getCast(getOpcode(), Op, getType());
842   case Instruction::Select:
843     Op0 = (OpNo == 0) ? Op : getOperand(0);
844     Op1 = (OpNo == 1) ? Op : getOperand(1);
845     Op2 = (OpNo == 2) ? Op : getOperand(2);
846     return ConstantExpr::getSelect(Op0, Op1, Op2);
847   case Instruction::InsertElement:
848     Op0 = (OpNo == 0) ? Op : getOperand(0);
849     Op1 = (OpNo == 1) ? Op : getOperand(1);
850     Op2 = (OpNo == 2) ? Op : getOperand(2);
851     return ConstantExpr::getInsertElement(Op0, Op1, Op2);
852   case Instruction::ExtractElement:
853     Op0 = (OpNo == 0) ? Op : getOperand(0);
854     Op1 = (OpNo == 1) ? Op : getOperand(1);
855     return ConstantExpr::getExtractElement(Op0, Op1);
856   case Instruction::ShuffleVector:
857     Op0 = (OpNo == 0) ? Op : getOperand(0);
858     Op1 = (OpNo == 1) ? Op : getOperand(1);
859     Op2 = (OpNo == 2) ? Op : getOperand(2);
860     return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
861   case Instruction::GetElementPtr: {
862     SmallVector<Constant*, 8> Ops;
863     Ops.resize(getNumOperands()-1);
864     for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
865       Ops[i-1] = getOperand(i);
866     if (OpNo == 0)
867       return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
868     Ops[OpNo-1] = Op;
869     return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
870   }
871   default:
872     assert(getNumOperands() == 2 && "Must be binary operator?");
873     Op0 = (OpNo == 0) ? Op : getOperand(0);
874     Op1 = (OpNo == 1) ? Op : getOperand(1);
875     return ConstantExpr::get(getOpcode(), Op0, Op1);
876   }
877 }
878
879 /// getWithOperands - This returns the current constant expression with the
880 /// operands replaced with the specified values.  The specified operands must
881 /// match count and type with the existing ones.
882 Constant *ConstantExpr::
883 getWithOperands(Constant* const *Ops, unsigned NumOps) const {
884   assert(NumOps == getNumOperands() && "Operand count mismatch!");
885   bool AnyChange = false;
886   for (unsigned i = 0; i != NumOps; ++i) {
887     assert(Ops[i]->getType() == getOperand(i)->getType() &&
888            "Operand type mismatch!");
889     AnyChange |= Ops[i] != getOperand(i);
890   }
891   if (!AnyChange)  // No operands changed, return self.
892     return const_cast<ConstantExpr*>(this);
893
894   switch (getOpcode()) {
895   case Instruction::Trunc:
896   case Instruction::ZExt:
897   case Instruction::SExt:
898   case Instruction::FPTrunc:
899   case Instruction::FPExt:
900   case Instruction::UIToFP:
901   case Instruction::SIToFP:
902   case Instruction::FPToUI:
903   case Instruction::FPToSI:
904   case Instruction::PtrToInt:
905   case Instruction::IntToPtr:
906   case Instruction::BitCast:
907     return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
908   case Instruction::Select:
909     return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
910   case Instruction::InsertElement:
911     return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
912   case Instruction::ExtractElement:
913     return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
914   case Instruction::ShuffleVector:
915     return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
916   case Instruction::GetElementPtr:
917     return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
918   case Instruction::ICmp:
919   case Instruction::FCmp:
920     return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
921   default:
922     assert(getNumOperands() == 2 && "Must be binary operator?");
923     return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
924   }
925 }
926
927
928 //===----------------------------------------------------------------------===//
929 //                      isValueValidForType implementations
930
931 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
932   unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
933   if (Ty == Type::Int1Ty)
934     return Val == 0 || Val == 1;
935   if (NumBits >= 64)
936     return true; // always true, has to fit in largest type
937   uint64_t Max = (1ll << NumBits) - 1;
938   return Val <= Max;
939 }
940
941 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
942   unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
943   if (Ty == Type::Int1Ty)
944     return Val == 0 || Val == 1 || Val == -1;
945   if (NumBits >= 64)
946     return true; // always true, has to fit in largest type
947   int64_t Min = -(1ll << (NumBits-1));
948   int64_t Max = (1ll << (NumBits-1)) - 1;
949   return (Val >= Min && Val <= Max);
950 }
951
952 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
953   // convert modifies in place, so make a copy.
954   APFloat Val2 = APFloat(Val);
955   bool losesInfo;
956   switch (Ty->getTypeID()) {
957   default:
958     return false;         // These can't be represented as floating point!
959
960   // FIXME rounding mode needs to be more flexible
961   case Type::FloatTyID: {
962     if (&Val2.getSemantics() == &APFloat::IEEEsingle)
963       return true;
964     Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
965     return !losesInfo;
966   }
967   case Type::DoubleTyID: {
968     if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
969         &Val2.getSemantics() == &APFloat::IEEEdouble)
970       return true;
971     Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
972     return !losesInfo;
973   }
974   case Type::X86_FP80TyID:
975     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
976            &Val2.getSemantics() == &APFloat::IEEEdouble ||
977            &Val2.getSemantics() == &APFloat::x87DoubleExtended;
978   case Type::FP128TyID:
979     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
980            &Val2.getSemantics() == &APFloat::IEEEdouble ||
981            &Val2.getSemantics() == &APFloat::IEEEquad;
982   case Type::PPC_FP128TyID:
983     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
984            &Val2.getSemantics() == &APFloat::IEEEdouble ||
985            &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
986   }
987 }
988
989 //===----------------------------------------------------------------------===//
990 //                      Factory Function Implementation
991
992
993 // The number of operands for each ConstantCreator::create method is
994 // determined by the ConstantTraits template.
995 // ConstantCreator - A class that is used to create constants by
996 // ValueMap*.  This class should be partially specialized if there is
997 // something strange that needs to be done to interface to the ctor for the
998 // constant.
999 //
1000 namespace llvm {
1001   template<class ValType>
1002   struct ConstantTraits;
1003
1004   template<typename T, typename Alloc>
1005   struct VISIBILITY_HIDDEN ConstantTraits< std::vector<T, Alloc> > {
1006     static unsigned uses(const std::vector<T, Alloc>& v) {
1007       return v.size();
1008     }
1009   };
1010
1011   template<class ConstantClass, class TypeClass, class ValType>
1012   struct VISIBILITY_HIDDEN ConstantCreator {
1013     static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
1014       return new(ConstantTraits<ValType>::uses(V)) ConstantClass(Ty, V);
1015     }
1016   };
1017
1018   template<class ConstantClass, class TypeClass>
1019   struct VISIBILITY_HIDDEN ConvertConstantType {
1020     static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
1021       LLVM_UNREACHABLE("This type cannot be converted!");
1022     }
1023   };
1024
1025   template<class ValType, class TypeClass, class ConstantClass,
1026            bool HasLargeKey = false  /*true for arrays and structs*/ >
1027   class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
1028   public:
1029     typedef std::pair<const Type*, ValType> MapKey;
1030     typedef std::map<MapKey, Constant *> MapTy;
1031     typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
1032     typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
1033   private:
1034     /// Map - This is the main map from the element descriptor to the Constants.
1035     /// This is the primary way we avoid creating two of the same shape
1036     /// constant.
1037     MapTy Map;
1038     
1039     /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
1040     /// from the constants to their element in Map.  This is important for
1041     /// removal of constants from the array, which would otherwise have to scan
1042     /// through the map with very large keys.
1043     InverseMapTy InverseMap;
1044
1045     /// AbstractTypeMap - Map for abstract type constants.
1046     ///
1047     AbstractTypeMapTy AbstractTypeMap;
1048     
1049     /// ValueMapLock - Mutex for this map.
1050     sys::SmartMutex<true> ValueMapLock;
1051
1052   public:
1053     // NOTE: This function is not locked.  It is the caller's responsibility
1054     // to enforce proper synchronization.
1055     typename MapTy::iterator map_end() { return Map.end(); }
1056     
1057     /// InsertOrGetItem - Return an iterator for the specified element.
1058     /// If the element exists in the map, the returned iterator points to the
1059     /// entry and Exists=true.  If not, the iterator points to the newly
1060     /// inserted entry and returns Exists=false.  Newly inserted entries have
1061     /// I->second == 0, and should be filled in.
1062     /// NOTE: This function is not locked.  It is the caller's responsibility
1063     // to enforce proper synchronization.
1064     typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
1065                                    &InsertVal,
1066                                    bool &Exists) {
1067       std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
1068       Exists = !IP.second;
1069       return IP.first;
1070     }
1071     
1072 private:
1073     typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
1074       if (HasLargeKey) {
1075         typename InverseMapTy::iterator IMI = InverseMap.find(CP);
1076         assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
1077                IMI->second->second == CP &&
1078                "InverseMap corrupt!");
1079         return IMI->second;
1080       }
1081       
1082       typename MapTy::iterator I =
1083         Map.find(MapKey(static_cast<const TypeClass*>(CP->getRawType()),
1084                         getValType(CP)));
1085       if (I == Map.end() || I->second != CP) {
1086         // FIXME: This should not use a linear scan.  If this gets to be a
1087         // performance problem, someone should look at this.
1088         for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
1089           /* empty */;
1090       }
1091       return I;
1092     }
1093     
1094     ConstantClass* Create(const TypeClass *Ty, const ValType &V,
1095                           typename MapTy::iterator I) {
1096       ConstantClass* Result =
1097         ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
1098
1099       assert(Result->getType() == Ty && "Type specified is not correct!");
1100       I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
1101
1102       if (HasLargeKey)  // Remember the reverse mapping if needed.
1103         InverseMap.insert(std::make_pair(Result, I));
1104
1105       // If the type of the constant is abstract, make sure that an entry
1106       // exists for it in the AbstractTypeMap.
1107       if (Ty->isAbstract()) {
1108         typename AbstractTypeMapTy::iterator TI = 
1109                                                  AbstractTypeMap.find(Ty);
1110
1111         if (TI == AbstractTypeMap.end()) {
1112           // Add ourselves to the ATU list of the type.
1113           cast<DerivedType>(Ty)->addAbstractTypeUser(this);
1114
1115           AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
1116         }
1117       }
1118       
1119       return Result;
1120     }
1121 public:
1122     
1123     /// getOrCreate - Return the specified constant from the map, creating it if
1124     /// necessary.
1125     ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
1126       sys::SmartScopedLock<true> Lock(ValueMapLock);
1127       MapKey Lookup(Ty, V);
1128       ConstantClass* Result = 0;
1129       
1130       typename MapTy::iterator I = Map.find(Lookup);
1131       // Is it in the map?  
1132       if (I != Map.end())
1133         Result = static_cast<ConstantClass *>(I->second);
1134         
1135       if (!Result) {
1136         // If no preexisting value, create one now...
1137         Result = Create(Ty, V, I);
1138       }
1139         
1140       return Result;
1141     }
1142
1143     void remove(ConstantClass *CP) {
1144       sys::SmartScopedLock<true> Lock(ValueMapLock);
1145       typename MapTy::iterator I = FindExistingElement(CP);
1146       assert(I != Map.end() && "Constant not found in constant table!");
1147       assert(I->second == CP && "Didn't find correct element?");
1148
1149       if (HasLargeKey)  // Remember the reverse mapping if needed.
1150         InverseMap.erase(CP);
1151       
1152       // Now that we found the entry, make sure this isn't the entry that
1153       // the AbstractTypeMap points to.
1154       const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
1155       if (Ty->isAbstract()) {
1156         assert(AbstractTypeMap.count(Ty) &&
1157                "Abstract type not in AbstractTypeMap?");
1158         typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
1159         if (ATMEntryIt == I) {
1160           // Yes, we are removing the representative entry for this type.
1161           // See if there are any other entries of the same type.
1162           typename MapTy::iterator TmpIt = ATMEntryIt;
1163
1164           // First check the entry before this one...
1165           if (TmpIt != Map.begin()) {
1166             --TmpIt;
1167             if (TmpIt->first.first != Ty) // Not the same type, move back...
1168               ++TmpIt;
1169           }
1170
1171           // If we didn't find the same type, try to move forward...
1172           if (TmpIt == ATMEntryIt) {
1173             ++TmpIt;
1174             if (TmpIt == Map.end() || TmpIt->first.first != Ty)
1175               --TmpIt;   // No entry afterwards with the same type
1176           }
1177
1178           // If there is another entry in the map of the same abstract type,
1179           // update the AbstractTypeMap entry now.
1180           if (TmpIt != ATMEntryIt) {
1181             ATMEntryIt = TmpIt;
1182           } else {
1183             // Otherwise, we are removing the last instance of this type
1184             // from the table.  Remove from the ATM, and from user list.
1185             cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
1186             AbstractTypeMap.erase(Ty);
1187           }
1188         }
1189       }
1190
1191       Map.erase(I);
1192     }
1193
1194     
1195     /// MoveConstantToNewSlot - If we are about to change C to be the element
1196     /// specified by I, update our internal data structures to reflect this
1197     /// fact.
1198     /// NOTE: This function is not locked. It is the responsibility of the
1199     /// caller to enforce proper synchronization if using this method.
1200     void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
1201       // First, remove the old location of the specified constant in the map.
1202       typename MapTy::iterator OldI = FindExistingElement(C);
1203       assert(OldI != Map.end() && "Constant not found in constant table!");
1204       assert(OldI->second == C && "Didn't find correct element?");
1205       
1206       // If this constant is the representative element for its abstract type,
1207       // update the AbstractTypeMap so that the representative element is I.
1208       if (C->getType()->isAbstract()) {
1209         typename AbstractTypeMapTy::iterator ATI =
1210             AbstractTypeMap.find(C->getType());
1211         assert(ATI != AbstractTypeMap.end() &&
1212                "Abstract type not in AbstractTypeMap?");
1213         if (ATI->second == OldI)
1214           ATI->second = I;
1215       }
1216       
1217       // Remove the old entry from the map.
1218       Map.erase(OldI);
1219       
1220       // Update the inverse map so that we know that this constant is now
1221       // located at descriptor I.
1222       if (HasLargeKey) {
1223         assert(I->second == C && "Bad inversemap entry!");
1224         InverseMap[C] = I;
1225       }
1226     }
1227     
1228     void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
1229       sys::SmartScopedLock<true> Lock(ValueMapLock);
1230       typename AbstractTypeMapTy::iterator I =
1231         AbstractTypeMap.find(cast<Type>(OldTy));
1232
1233       assert(I != AbstractTypeMap.end() &&
1234              "Abstract type not in AbstractTypeMap?");
1235
1236       // Convert a constant at a time until the last one is gone.  The last one
1237       // leaving will remove() itself, causing the AbstractTypeMapEntry to be
1238       // eliminated eventually.
1239       do {
1240         ConvertConstantType<ConstantClass,
1241                             TypeClass>::convert(
1242                                 static_cast<ConstantClass *>(I->second->second),
1243                                                 cast<TypeClass>(NewTy));
1244
1245         I = AbstractTypeMap.find(cast<Type>(OldTy));
1246       } while (I != AbstractTypeMap.end());
1247     }
1248
1249     // If the type became concrete without being refined to any other existing
1250     // type, we just remove ourselves from the ATU list.
1251     void typeBecameConcrete(const DerivedType *AbsTy) {
1252       AbsTy->removeAbstractTypeUser(this);
1253     }
1254
1255     void dump() const {
1256       DOUT << "Constant.cpp: ValueMap\n";
1257     }
1258   };
1259 }
1260
1261
1262
1263 //---- ConstantAggregateZero::get() implementation...
1264 //
1265 namespace llvm {
1266   // ConstantAggregateZero does not take extra "value" argument...
1267   template<class ValType>
1268   struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
1269     static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
1270       return new ConstantAggregateZero(Ty);
1271     }
1272   };
1273
1274   template<>
1275   struct ConvertConstantType<ConstantAggregateZero, Type> {
1276     static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1277       // Make everyone now use a constant of the new type...
1278       Constant *New = ConstantAggregateZero::get(NewTy);
1279       assert(New != OldC && "Didn't replace constant??");
1280       OldC->uncheckedReplaceAllUsesWith(New);
1281       OldC->destroyConstant();     // This constant is now dead, destroy it.
1282     }
1283   };
1284 }
1285
1286 static ManagedStatic<ValueMap<char, Type, 
1287                               ConstantAggregateZero> > AggZeroConstants;
1288
1289 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1290
1291 ConstantAggregateZero *ConstantAggregateZero::get(const Type *Ty) {
1292   assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
1293          "Cannot create an aggregate zero of non-aggregate type!");
1294   
1295   // Implicitly locked.
1296   return AggZeroConstants->getOrCreate(Ty, 0);
1297 }
1298
1299 /// destroyConstant - Remove the constant from the constant table...
1300 ///
1301 void ConstantAggregateZero::destroyConstant() {
1302   // Implicitly locked.
1303   AggZeroConstants->remove(this);
1304   destroyConstantImpl();
1305 }
1306
1307 //---- ConstantArray::get() implementation...
1308 //
1309 namespace llvm {
1310   template<>
1311   struct ConvertConstantType<ConstantArray, ArrayType> {
1312     static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1313       // Make everyone now use a constant of the new type...
1314       std::vector<Constant*> C;
1315       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1316         C.push_back(cast<Constant>(OldC->getOperand(i)));
1317       Constant *New = ConstantArray::get(NewTy, C);
1318       assert(New != OldC && "Didn't replace constant??");
1319       OldC->uncheckedReplaceAllUsesWith(New);
1320       OldC->destroyConstant();    // This constant is now dead, destroy it.
1321     }
1322   };
1323 }
1324
1325 static std::vector<Constant*> getValType(ConstantArray *CA) {
1326   std::vector<Constant*> Elements;
1327   Elements.reserve(CA->getNumOperands());
1328   for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1329     Elements.push_back(cast<Constant>(CA->getOperand(i)));
1330   return Elements;
1331 }
1332
1333 typedef ValueMap<std::vector<Constant*>, ArrayType, 
1334                  ConstantArray, true /*largekey*/> ArrayConstantsTy;
1335 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
1336
1337 Constant *ConstantArray::get(const ArrayType *Ty,
1338                              const std::vector<Constant*> &V) {
1339   // If this is an all-zero array, return a ConstantAggregateZero object
1340   if (!V.empty()) {
1341     Constant *C = V[0];
1342     if (!C->isNullValue()) {
1343       // Implicitly locked.
1344       return ArrayConstants->getOrCreate(Ty, V);
1345     }
1346     for (unsigned i = 1, e = V.size(); i != e; ++i)
1347       if (V[i] != C) {
1348         // Implicitly locked.
1349         return ArrayConstants->getOrCreate(Ty, V);
1350       }
1351   }
1352   
1353   return ConstantAggregateZero::get(Ty);
1354 }
1355
1356 /// destroyConstant - Remove the constant from the constant table...
1357 ///
1358 void ConstantArray::destroyConstant() {
1359   // Implicitly locked.
1360   ArrayConstants->remove(this);
1361   destroyConstantImpl();
1362 }
1363
1364 /// ConstantArray::get(const string&) - Return an array that is initialized to
1365 /// contain the specified string.  If length is zero then a null terminator is 
1366 /// added to the specified string so that it may be used in a natural way. 
1367 /// Otherwise, the length parameter specifies how much of the string to use 
1368 /// and it won't be null terminated.
1369 ///
1370 Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
1371   std::vector<Constant*> ElementVals;
1372   for (unsigned i = 0; i < Str.length(); ++i)
1373     ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
1374
1375   // Add a null terminator to the string...
1376   if (AddNull) {
1377     ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
1378   }
1379
1380   ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
1381   return ConstantArray::get(ATy, ElementVals);
1382 }
1383
1384 /// isString - This method returns true if the array is an array of i8, and 
1385 /// if the elements of the array are all ConstantInt's.
1386 bool ConstantArray::isString() const {
1387   // Check the element type for i8...
1388   if (getType()->getElementType() != Type::Int8Ty)
1389     return false;
1390   // Check the elements to make sure they are all integers, not constant
1391   // expressions.
1392   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1393     if (!isa<ConstantInt>(getOperand(i)))
1394       return false;
1395   return true;
1396 }
1397
1398 /// isCString - This method returns true if the array is a string (see
1399 /// isString) and it ends in a null byte \\0 and does not contains any other
1400 /// null bytes except its terminator.
1401 bool ConstantArray::isCString() const {
1402   // Check the element type for i8...
1403   if (getType()->getElementType() != Type::Int8Ty)
1404     return false;
1405
1406   // Last element must be a null.
1407   if (!getOperand(getNumOperands()-1)->isNullValue())
1408     return false;
1409   // Other elements must be non-null integers.
1410   for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1411     if (!isa<ConstantInt>(getOperand(i)))
1412       return false;
1413     if (getOperand(i)->isNullValue())
1414       return false;
1415   }
1416   return true;
1417 }
1418
1419
1420 /// getAsString - If the sub-element type of this array is i8
1421 /// then this method converts the array to an std::string and returns it.
1422 /// Otherwise, it asserts out.
1423 ///
1424 std::string ConstantArray::getAsString() const {
1425   assert(isString() && "Not a string!");
1426   std::string Result;
1427   Result.reserve(getNumOperands());
1428   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1429     Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
1430   return Result;
1431 }
1432
1433
1434 //---- ConstantStruct::get() implementation...
1435 //
1436
1437 namespace llvm {
1438   template<>
1439   struct ConvertConstantType<ConstantStruct, StructType> {
1440     static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1441       // Make everyone now use a constant of the new type...
1442       std::vector<Constant*> C;
1443       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1444         C.push_back(cast<Constant>(OldC->getOperand(i)));
1445       Constant *New = ConstantStruct::get(NewTy, C);
1446       assert(New != OldC && "Didn't replace constant??");
1447
1448       OldC->uncheckedReplaceAllUsesWith(New);
1449       OldC->destroyConstant();    // This constant is now dead, destroy it.
1450     }
1451   };
1452 }
1453
1454 typedef ValueMap<std::vector<Constant*>, StructType,
1455                  ConstantStruct, true /*largekey*/> StructConstantsTy;
1456 static ManagedStatic<StructConstantsTy> StructConstants;
1457
1458 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1459   std::vector<Constant*> Elements;
1460   Elements.reserve(CS->getNumOperands());
1461   for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1462     Elements.push_back(cast<Constant>(CS->getOperand(i)));
1463   return Elements;
1464 }
1465
1466 Constant *ConstantStruct::get(const StructType *Ty,
1467                               const std::vector<Constant*> &V) {
1468   // Create a ConstantAggregateZero value if all elements are zeros...
1469   for (unsigned i = 0, e = V.size(); i != e; ++i)
1470     if (!V[i]->isNullValue())
1471       // Implicitly locked.
1472       return StructConstants->getOrCreate(Ty, V);
1473
1474   return ConstantAggregateZero::get(Ty);
1475 }
1476
1477 Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
1478   std::vector<const Type*> StructEls;
1479   StructEls.reserve(V.size());
1480   for (unsigned i = 0, e = V.size(); i != e; ++i)
1481     StructEls.push_back(V[i]->getType());
1482   return get(StructType::get(StructEls, packed), V);
1483 }
1484
1485 // destroyConstant - Remove the constant from the constant table...
1486 //
1487 void ConstantStruct::destroyConstant() {
1488   // Implicitly locked.
1489   StructConstants->remove(this);
1490   destroyConstantImpl();
1491 }
1492
1493 //---- ConstantVector::get() implementation...
1494 //
1495 namespace llvm {
1496   template<>
1497   struct ConvertConstantType<ConstantVector, VectorType> {
1498     static void convert(ConstantVector *OldC, const VectorType *NewTy) {
1499       // Make everyone now use a constant of the new type...
1500       std::vector<Constant*> C;
1501       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1502         C.push_back(cast<Constant>(OldC->getOperand(i)));
1503       Constant *New = ConstantVector::get(NewTy, C);
1504       assert(New != OldC && "Didn't replace constant??");
1505       OldC->uncheckedReplaceAllUsesWith(New);
1506       OldC->destroyConstant();    // This constant is now dead, destroy it.
1507     }
1508   };
1509 }
1510
1511 static std::vector<Constant*> getValType(ConstantVector *CP) {
1512   std::vector<Constant*> Elements;
1513   Elements.reserve(CP->getNumOperands());
1514   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1515     Elements.push_back(CP->getOperand(i));
1516   return Elements;
1517 }
1518
1519 static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
1520                               ConstantVector> > VectorConstants;
1521
1522 Constant *ConstantVector::get(const VectorType *Ty,
1523                               const std::vector<Constant*> &V) {
1524   assert(!V.empty() && "Vectors can't be empty");
1525   // If this is an all-undef or alll-zero vector, return a
1526   // ConstantAggregateZero or UndefValue.
1527   Constant *C = V[0];
1528   bool isZero = C->isNullValue();
1529   bool isUndef = isa<UndefValue>(C);
1530
1531   if (isZero || isUndef) {
1532     for (unsigned i = 1, e = V.size(); i != e; ++i)
1533       if (V[i] != C) {
1534         isZero = isUndef = false;
1535         break;
1536       }
1537   }
1538   
1539   if (isZero)
1540     return ConstantAggregateZero::get(Ty);
1541   if (isUndef)
1542     return UndefValue::get(Ty);
1543     
1544   // Implicitly locked.
1545   return VectorConstants->getOrCreate(Ty, V);
1546 }
1547
1548 Constant *ConstantVector::get(const std::vector<Constant*> &V) {
1549   assert(!V.empty() && "Cannot infer type if V is empty");
1550   return get(VectorType::get(V.front()->getType(),V.size()), V);
1551 }
1552
1553 // destroyConstant - Remove the constant from the constant table...
1554 //
1555 void ConstantVector::destroyConstant() {
1556   // Implicitly locked.
1557   VectorConstants->remove(this);
1558   destroyConstantImpl();
1559 }
1560
1561 /// This function will return true iff every element in this vector constant
1562 /// is set to all ones.
1563 /// @returns true iff this constant's emements are all set to all ones.
1564 /// @brief Determine if the value is all ones.
1565 bool ConstantVector::isAllOnesValue() const {
1566   // Check out first element.
1567   const Constant *Elt = getOperand(0);
1568   const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1569   if (!CI || !CI->isAllOnesValue()) return false;
1570   // Then make sure all remaining elements point to the same value.
1571   for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1572     if (getOperand(I) != Elt) return false;
1573   }
1574   return true;
1575 }
1576
1577 /// getSplatValue - If this is a splat constant, where all of the
1578 /// elements have the same value, return that value. Otherwise return null.
1579 Constant *ConstantVector::getSplatValue() {
1580   // Check out first element.
1581   Constant *Elt = getOperand(0);
1582   // Then make sure all remaining elements point to the same value.
1583   for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1584     if (getOperand(I) != Elt) return 0;
1585   return Elt;
1586 }
1587
1588 //---- ConstantPointerNull::get() implementation...
1589 //
1590
1591 namespace llvm {
1592   // ConstantPointerNull does not take extra "value" argument...
1593   template<class ValType>
1594   struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1595     static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1596       return new ConstantPointerNull(Ty);
1597     }
1598   };
1599
1600   template<>
1601   struct ConvertConstantType<ConstantPointerNull, PointerType> {
1602     static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1603       // Make everyone now use a constant of the new type...
1604       Constant *New = ConstantPointerNull::get(NewTy);
1605       assert(New != OldC && "Didn't replace constant??");
1606       OldC->uncheckedReplaceAllUsesWith(New);
1607       OldC->destroyConstant();     // This constant is now dead, destroy it.
1608     }
1609   };
1610 }
1611
1612 static ManagedStatic<ValueMap<char, PointerType, 
1613                               ConstantPointerNull> > NullPtrConstants;
1614
1615 static char getValType(ConstantPointerNull *) {
1616   return 0;
1617 }
1618
1619
1620 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1621   // Implicitly locked.
1622   return NullPtrConstants->getOrCreate(Ty, 0);
1623 }
1624
1625 // destroyConstant - Remove the constant from the constant table...
1626 //
1627 void ConstantPointerNull::destroyConstant() {
1628   // Implicitly locked.
1629   NullPtrConstants->remove(this);
1630   destroyConstantImpl();
1631 }
1632
1633
1634 //---- UndefValue::get() implementation...
1635 //
1636
1637 namespace llvm {
1638   // UndefValue does not take extra "value" argument...
1639   template<class ValType>
1640   struct ConstantCreator<UndefValue, Type, ValType> {
1641     static UndefValue *create(const Type *Ty, const ValType &V) {
1642       return new UndefValue(Ty);
1643     }
1644   };
1645
1646   template<>
1647   struct ConvertConstantType<UndefValue, Type> {
1648     static void convert(UndefValue *OldC, const Type *NewTy) {
1649       // Make everyone now use a constant of the new type.
1650       Constant *New = UndefValue::get(NewTy);
1651       assert(New != OldC && "Didn't replace constant??");
1652       OldC->uncheckedReplaceAllUsesWith(New);
1653       OldC->destroyConstant();     // This constant is now dead, destroy it.
1654     }
1655   };
1656 }
1657
1658 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1659
1660 static char getValType(UndefValue *) {
1661   return 0;
1662 }
1663
1664
1665 UndefValue *UndefValue::get(const Type *Ty) {
1666   // Implicitly locked.
1667   return UndefValueConstants->getOrCreate(Ty, 0);
1668 }
1669
1670 // destroyConstant - Remove the constant from the constant table.
1671 //
1672 void UndefValue::destroyConstant() {
1673   // Implicitly locked.
1674   UndefValueConstants->remove(this);
1675   destroyConstantImpl();
1676 }
1677
1678 //---- MDString::get() implementation
1679 //
1680
1681 MDString::MDString(const char *begin, const char *end)
1682   : Constant(Type::MetadataTy, MDStringVal, 0, 0),
1683     StrBegin(begin), StrEnd(end) {}
1684
1685 static ManagedStatic<StringMap<MDString*> > MDStringCache;
1686
1687 MDString *MDString::get(const char *StrBegin, const char *StrEnd) {
1688   sys::SmartScopedWriter<true> Writer(*ConstantsLock);
1689   StringMapEntry<MDString *> &Entry = MDStringCache->GetOrCreateValue(
1690                                         StrBegin, StrEnd);
1691   MDString *&S = Entry.getValue();
1692   if (!S) S = new MDString(Entry.getKeyData(),
1693                            Entry.getKeyData() + Entry.getKeyLength());
1694
1695   return S;
1696 }
1697
1698 MDString *MDString::get(const std::string &Str) {
1699   sys::SmartScopedWriter<true> Writer(*ConstantsLock);
1700   StringMapEntry<MDString *> &Entry = MDStringCache->GetOrCreateValue(
1701                                         Str.data(), Str.data() + Str.size());
1702   MDString *&S = Entry.getValue();
1703   if (!S) S = new MDString(Entry.getKeyData(),
1704                            Entry.getKeyData() + Entry.getKeyLength());
1705
1706   return S;
1707 }
1708
1709 void MDString::destroyConstant() {
1710   sys::SmartScopedWriter<true> Writer(*ConstantsLock);
1711   MDStringCache->erase(MDStringCache->find(StrBegin, StrEnd));
1712   destroyConstantImpl();
1713 }
1714
1715 //---- MDNode::get() implementation
1716 //
1717
1718 static ManagedStatic<FoldingSet<MDNode> > MDNodeSet;
1719
1720 MDNode::MDNode(Value*const* Vals, unsigned NumVals)
1721   : Constant(Type::MetadataTy, MDNodeVal, 0, 0) {
1722   for (unsigned i = 0; i != NumVals; ++i)
1723     Node.push_back(ElementVH(Vals[i], this));
1724 }
1725
1726 void MDNode::Profile(FoldingSetNodeID &ID) const {
1727   for (const_elem_iterator I = elem_begin(), E = elem_end(); I != E; ++I)
1728     ID.AddPointer(*I);
1729 }
1730
1731 MDNode *MDNode::get(Value*const* Vals, unsigned NumVals) {
1732   FoldingSetNodeID ID;
1733   for (unsigned i = 0; i != NumVals; ++i)
1734     ID.AddPointer(Vals[i]);
1735
1736   ConstantsLock->reader_acquire();
1737   void *InsertPoint;
1738   MDNode *N = MDNodeSet->FindNodeOrInsertPos(ID, InsertPoint);
1739   ConstantsLock->reader_release();
1740   
1741   if (!N) {
1742     sys::SmartScopedWriter<true> Writer(*ConstantsLock);
1743     N = MDNodeSet->FindNodeOrInsertPos(ID, InsertPoint);
1744     if (!N) {
1745       // InsertPoint will have been set by the FindNodeOrInsertPos call.
1746       N = new(0) MDNode(Vals, NumVals);
1747       MDNodeSet->InsertNode(N, InsertPoint);
1748     }
1749   }
1750   return N;
1751 }
1752
1753 void MDNode::destroyConstant() {
1754   sys::SmartScopedWriter<true> Writer(*ConstantsLock); 
1755   MDNodeSet->RemoveNode(this);
1756   
1757   destroyConstantImpl();
1758 }
1759
1760 //---- ConstantExpr::get() implementations...
1761 //
1762
1763 namespace {
1764
1765 struct ExprMapKeyType {
1766   typedef SmallVector<unsigned, 4> IndexList;
1767
1768   ExprMapKeyType(unsigned opc,
1769       const std::vector<Constant*> &ops,
1770       unsigned short pred = 0,
1771       const IndexList &inds = IndexList())
1772         : opcode(opc), predicate(pred), operands(ops), indices(inds) {}
1773   uint16_t opcode;
1774   uint16_t predicate;
1775   std::vector<Constant*> operands;
1776   IndexList indices;
1777   bool operator==(const ExprMapKeyType& that) const {
1778     return this->opcode == that.opcode &&
1779            this->predicate == that.predicate &&
1780            this->operands == that.operands &&
1781            this->indices == that.indices;
1782   }
1783   bool operator<(const ExprMapKeyType & that) const {
1784     return this->opcode < that.opcode ||
1785       (this->opcode == that.opcode && this->predicate < that.predicate) ||
1786       (this->opcode == that.opcode && this->predicate == that.predicate &&
1787        this->operands < that.operands) ||
1788       (this->opcode == that.opcode && this->predicate == that.predicate &&
1789        this->operands == that.operands && this->indices < that.indices);
1790   }
1791
1792   bool operator!=(const ExprMapKeyType& that) const {
1793     return !(*this == that);
1794   }
1795 };
1796
1797 }
1798
1799 namespace llvm {
1800   template<>
1801   struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1802     static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1803         unsigned short pred = 0) {
1804       if (Instruction::isCast(V.opcode))
1805         return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1806       if ((V.opcode >= Instruction::BinaryOpsBegin &&
1807            V.opcode < Instruction::BinaryOpsEnd))
1808         return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1809       if (V.opcode == Instruction::Select)
1810         return new SelectConstantExpr(V.operands[0], V.operands[1], 
1811                                       V.operands[2]);
1812       if (V.opcode == Instruction::ExtractElement)
1813         return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1814       if (V.opcode == Instruction::InsertElement)
1815         return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1816                                              V.operands[2]);
1817       if (V.opcode == Instruction::ShuffleVector)
1818         return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1819                                              V.operands[2]);
1820       if (V.opcode == Instruction::InsertValue)
1821         return new InsertValueConstantExpr(V.operands[0], V.operands[1],
1822                                            V.indices, Ty);
1823       if (V.opcode == Instruction::ExtractValue)
1824         return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
1825       if (V.opcode == Instruction::GetElementPtr) {
1826         std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1827         return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
1828       }
1829
1830       // The compare instructions are weird. We have to encode the predicate
1831       // value and it is combined with the instruction opcode by multiplying
1832       // the opcode by one hundred. We must decode this to get the predicate.
1833       if (V.opcode == Instruction::ICmp)
1834         return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate, 
1835                                        V.operands[0], V.operands[1]);
1836       if (V.opcode == Instruction::FCmp) 
1837         return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate, 
1838                                        V.operands[0], V.operands[1]);
1839       LLVM_UNREACHABLE("Invalid ConstantExpr!");
1840       return 0;
1841     }
1842   };
1843
1844   template<>
1845   struct ConvertConstantType<ConstantExpr, Type> {
1846     static void convert(ConstantExpr *OldC, const Type *NewTy) {
1847       Constant *New;
1848       switch (OldC->getOpcode()) {
1849       case Instruction::Trunc:
1850       case Instruction::ZExt:
1851       case Instruction::SExt:
1852       case Instruction::FPTrunc:
1853       case Instruction::FPExt:
1854       case Instruction::UIToFP:
1855       case Instruction::SIToFP:
1856       case Instruction::FPToUI:
1857       case Instruction::FPToSI:
1858       case Instruction::PtrToInt:
1859       case Instruction::IntToPtr:
1860       case Instruction::BitCast:
1861         New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0), 
1862                                     NewTy);
1863         break;
1864       case Instruction::Select:
1865         New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1866                                         OldC->getOperand(1),
1867                                         OldC->getOperand(2));
1868         break;
1869       default:
1870         assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1871                OldC->getOpcode() <  Instruction::BinaryOpsEnd);
1872         New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1873                                   OldC->getOperand(1));
1874         break;
1875       case Instruction::GetElementPtr:
1876         // Make everyone now use a constant of the new type...
1877         std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1878         New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1879                                                &Idx[0], Idx.size());
1880         break;
1881       }
1882
1883       assert(New != OldC && "Didn't replace constant??");
1884       OldC->uncheckedReplaceAllUsesWith(New);
1885       OldC->destroyConstant();    // This constant is now dead, destroy it.
1886     }
1887   };
1888 } // end namespace llvm
1889
1890
1891 static ExprMapKeyType getValType(ConstantExpr *CE) {
1892   std::vector<Constant*> Operands;
1893   Operands.reserve(CE->getNumOperands());
1894   for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1895     Operands.push_back(cast<Constant>(CE->getOperand(i)));
1896   return ExprMapKeyType(CE->getOpcode(), Operands, 
1897       CE->isCompare() ? CE->getPredicate() : 0,
1898       CE->hasIndices() ?
1899         CE->getIndices() : SmallVector<unsigned, 4>());
1900 }
1901
1902 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1903                               ConstantExpr> > ExprConstants;
1904
1905 /// This is a utility function to handle folding of casts and lookup of the
1906 /// cast in the ExprConstants map. It is used by the various get* methods below.
1907 static inline Constant *getFoldedCast(
1908   Instruction::CastOps opc, Constant *C, const Type *Ty) {
1909   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1910   // Fold a few common cases
1911   if (Constant *FC = 
1912                     ConstantFoldCastInstruction(getGlobalContext(), opc, C, Ty))
1913     return FC;
1914
1915   // Look up the constant in the table first to ensure uniqueness
1916   std::vector<Constant*> argVec(1, C);
1917   ExprMapKeyType Key(opc, argVec);
1918   
1919   // Implicitly locked.
1920   return ExprConstants->getOrCreate(Ty, Key);
1921 }
1922  
1923 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1924   Instruction::CastOps opc = Instruction::CastOps(oc);
1925   assert(Instruction::isCast(opc) && "opcode out of range");
1926   assert(C && Ty && "Null arguments to getCast");
1927   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1928
1929   switch (opc) {
1930     default:
1931       LLVM_UNREACHABLE("Invalid cast opcode");
1932       break;
1933     case Instruction::Trunc:    return getTrunc(C, Ty);
1934     case Instruction::ZExt:     return getZExt(C, Ty);
1935     case Instruction::SExt:     return getSExt(C, Ty);
1936     case Instruction::FPTrunc:  return getFPTrunc(C, Ty);
1937     case Instruction::FPExt:    return getFPExtend(C, Ty);
1938     case Instruction::UIToFP:   return getUIToFP(C, Ty);
1939     case Instruction::SIToFP:   return getSIToFP(C, Ty);
1940     case Instruction::FPToUI:   return getFPToUI(C, Ty);
1941     case Instruction::FPToSI:   return getFPToSI(C, Ty);
1942     case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1943     case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1944     case Instruction::BitCast:  return getBitCast(C, Ty);
1945   }
1946   return 0;
1947
1948
1949 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1950   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1951     return getCast(Instruction::BitCast, C, Ty);
1952   return getCast(Instruction::ZExt, C, Ty);
1953 }
1954
1955 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1956   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1957     return getCast(Instruction::BitCast, C, Ty);
1958   return getCast(Instruction::SExt, C, Ty);
1959 }
1960
1961 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1962   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1963     return getCast(Instruction::BitCast, C, Ty);
1964   return getCast(Instruction::Trunc, C, Ty);
1965 }
1966
1967 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1968   assert(isa<PointerType>(S->getType()) && "Invalid cast");
1969   assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1970
1971   if (Ty->isInteger())
1972     return getCast(Instruction::PtrToInt, S, Ty);
1973   return getCast(Instruction::BitCast, S, Ty);
1974 }
1975
1976 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty, 
1977                                        bool isSigned) {
1978   assert(C->getType()->isIntOrIntVector() &&
1979          Ty->isIntOrIntVector() && "Invalid cast");
1980   unsigned SrcBits = C->getType()->getScalarSizeInBits();
1981   unsigned DstBits = Ty->getScalarSizeInBits();
1982   Instruction::CastOps opcode =
1983     (SrcBits == DstBits ? Instruction::BitCast :
1984      (SrcBits > DstBits ? Instruction::Trunc :
1985       (isSigned ? Instruction::SExt : Instruction::ZExt)));
1986   return getCast(opcode, C, Ty);
1987 }
1988
1989 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1990   assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1991          "Invalid cast");
1992   unsigned SrcBits = C->getType()->getScalarSizeInBits();
1993   unsigned DstBits = Ty->getScalarSizeInBits();
1994   if (SrcBits == DstBits)
1995     return C; // Avoid a useless cast
1996   Instruction::CastOps opcode =
1997      (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1998   return getCast(opcode, C, Ty);
1999 }
2000
2001 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
2002 #ifndef NDEBUG
2003   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2004   bool toVec = Ty->getTypeID() == Type::VectorTyID;
2005 #endif
2006   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2007   assert(C->getType()->isIntOrIntVector() && "Trunc operand must be integer");
2008   assert(Ty->isIntOrIntVector() && "Trunc produces only integral");
2009   assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
2010          "SrcTy must be larger than DestTy for Trunc!");
2011
2012   return getFoldedCast(Instruction::Trunc, C, Ty);
2013 }
2014
2015 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
2016 #ifndef NDEBUG
2017   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2018   bool toVec = Ty->getTypeID() == Type::VectorTyID;
2019 #endif
2020   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2021   assert(C->getType()->isIntOrIntVector() && "SExt operand must be integral");
2022   assert(Ty->isIntOrIntVector() && "SExt produces only integer");
2023   assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
2024          "SrcTy must be smaller than DestTy for SExt!");
2025
2026   return getFoldedCast(Instruction::SExt, C, Ty);
2027 }
2028
2029 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
2030 #ifndef NDEBUG
2031   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2032   bool toVec = Ty->getTypeID() == Type::VectorTyID;
2033 #endif
2034   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2035   assert(C->getType()->isIntOrIntVector() && "ZEXt operand must be integral");
2036   assert(Ty->isIntOrIntVector() && "ZExt produces only integer");
2037   assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
2038          "SrcTy must be smaller than DestTy for ZExt!");
2039
2040   return getFoldedCast(Instruction::ZExt, C, Ty);
2041 }
2042
2043 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
2044 #ifndef NDEBUG
2045   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2046   bool toVec = Ty->getTypeID() == Type::VectorTyID;
2047 #endif
2048   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2049   assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2050          C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
2051          "This is an illegal floating point truncation!");
2052   return getFoldedCast(Instruction::FPTrunc, C, Ty);
2053 }
2054
2055 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
2056 #ifndef NDEBUG
2057   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2058   bool toVec = Ty->getTypeID() == Type::VectorTyID;
2059 #endif
2060   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2061   assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2062          C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
2063          "This is an illegal floating point extension!");
2064   return getFoldedCast(Instruction::FPExt, C, Ty);
2065 }
2066
2067 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
2068 #ifndef NDEBUG
2069   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2070   bool toVec = Ty->getTypeID() == Type::VectorTyID;
2071 #endif
2072   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2073   assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
2074          "This is an illegal uint to floating point cast!");
2075   return getFoldedCast(Instruction::UIToFP, C, Ty);
2076 }
2077
2078 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
2079 #ifndef NDEBUG
2080   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2081   bool toVec = Ty->getTypeID() == Type::VectorTyID;
2082 #endif
2083   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2084   assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
2085          "This is an illegal sint to floating point cast!");
2086   return getFoldedCast(Instruction::SIToFP, C, Ty);
2087 }
2088
2089 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
2090 #ifndef NDEBUG
2091   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2092   bool toVec = Ty->getTypeID() == Type::VectorTyID;
2093 #endif
2094   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2095   assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
2096          "This is an illegal floating point to uint cast!");
2097   return getFoldedCast(Instruction::FPToUI, C, Ty);
2098 }
2099
2100 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
2101 #ifndef NDEBUG
2102   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2103   bool toVec = Ty->getTypeID() == Type::VectorTyID;
2104 #endif
2105   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2106   assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
2107          "This is an illegal floating point to sint cast!");
2108   return getFoldedCast(Instruction::FPToSI, C, Ty);
2109 }
2110
2111 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
2112   assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
2113   assert(DstTy->isInteger() && "PtrToInt destination must be integral");
2114   return getFoldedCast(Instruction::PtrToInt, C, DstTy);
2115 }
2116
2117 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
2118   assert(C->getType()->isInteger() && "IntToPtr source must be integral");
2119   assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
2120   return getFoldedCast(Instruction::IntToPtr, C, DstTy);
2121 }
2122
2123 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
2124   // BitCast implies a no-op cast of type only. No bits change.  However, you 
2125   // can't cast pointers to anything but pointers.
2126 #ifndef NDEBUG
2127   const Type *SrcTy = C->getType();
2128   assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
2129          "BitCast cannot cast pointer to non-pointer and vice versa");
2130
2131   // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
2132   // or nonptr->ptr). For all the other types, the cast is okay if source and 
2133   // destination bit widths are identical.
2134   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
2135   unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
2136 #endif
2137   assert(SrcBitSize == DstBitSize && "BitCast requires types of same width");
2138   
2139   // It is common to ask for a bitcast of a value to its own type, handle this
2140   // speedily.
2141   if (C->getType() == DstTy) return C;
2142   
2143   return getFoldedCast(Instruction::BitCast, C, DstTy);
2144 }
2145
2146 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
2147                               Constant *C1, Constant *C2) {
2148   // Check the operands for consistency first
2149   assert(Opcode >= Instruction::BinaryOpsBegin &&
2150          Opcode <  Instruction::BinaryOpsEnd   &&
2151          "Invalid opcode in binary constant expression");
2152   assert(C1->getType() == C2->getType() &&
2153          "Operand types in binary constant expression should match");
2154
2155   if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
2156     if (Constant *FC = ConstantFoldBinaryInstruction(
2157                                             getGlobalContext(), Opcode, C1, C2))
2158       return FC;          // Fold a few common cases...
2159
2160   std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
2161   ExprMapKeyType Key(Opcode, argVec);
2162   
2163   // Implicitly locked.
2164   return ExprConstants->getOrCreate(ReqTy, Key);
2165 }
2166
2167 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
2168                                      Constant *C1, Constant *C2) {
2169   switch (predicate) {
2170     default: LLVM_UNREACHABLE("Invalid CmpInst predicate");
2171     case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
2172     case CmpInst::FCMP_OGE:   case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
2173     case CmpInst::FCMP_ONE:   case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
2174     case CmpInst::FCMP_UEQ:   case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
2175     case CmpInst::FCMP_ULT:   case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
2176     case CmpInst::FCMP_TRUE:
2177       return getFCmp(predicate, C1, C2);
2178
2179     case CmpInst::ICMP_EQ:  case CmpInst::ICMP_NE:  case CmpInst::ICMP_UGT:
2180     case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
2181     case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
2182     case CmpInst::ICMP_SLE:
2183       return getICmp(predicate, C1, C2);
2184   }
2185 }
2186
2187 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
2188   // API compatibility: Adjust integer opcodes to floating-point opcodes.
2189   if (C1->getType()->isFPOrFPVector()) {
2190     if (Opcode == Instruction::Add) Opcode = Instruction::FAdd;
2191     else if (Opcode == Instruction::Sub) Opcode = Instruction::FSub;
2192     else if (Opcode == Instruction::Mul) Opcode = Instruction::FMul;
2193   }
2194 #ifndef NDEBUG
2195   switch (Opcode) {
2196   case Instruction::Add:
2197   case Instruction::Sub:
2198   case Instruction::Mul:
2199     assert(C1->getType() == C2->getType() && "Op types should be identical!");
2200     assert(C1->getType()->isIntOrIntVector() &&
2201            "Tried to create an integer operation on a non-integer type!");
2202     break;
2203   case Instruction::FAdd:
2204   case Instruction::FSub:
2205   case Instruction::FMul:
2206     assert(C1->getType() == C2->getType() && "Op types should be identical!");
2207     assert(C1->getType()->isFPOrFPVector() &&
2208            "Tried to create a floating-point operation on a "
2209            "non-floating-point type!");
2210     break;
2211   case Instruction::UDiv: 
2212   case Instruction::SDiv: 
2213     assert(C1->getType() == C2->getType() && "Op types should be identical!");
2214     assert(C1->getType()->isIntOrIntVector() &&
2215            "Tried to create an arithmetic operation on a non-arithmetic type!");
2216     break;
2217   case Instruction::FDiv:
2218     assert(C1->getType() == C2->getType() && "Op types should be identical!");
2219     assert(C1->getType()->isFPOrFPVector() &&
2220            "Tried to create an arithmetic operation on a non-arithmetic type!");
2221     break;
2222   case Instruction::URem: 
2223   case Instruction::SRem: 
2224     assert(C1->getType() == C2->getType() && "Op types should be identical!");
2225     assert(C1->getType()->isIntOrIntVector() &&
2226            "Tried to create an arithmetic operation on a non-arithmetic type!");
2227     break;
2228   case Instruction::FRem:
2229     assert(C1->getType() == C2->getType() && "Op types should be identical!");
2230     assert(C1->getType()->isFPOrFPVector() &&
2231            "Tried to create an arithmetic operation on a non-arithmetic type!");
2232     break;
2233   case Instruction::And:
2234   case Instruction::Or:
2235   case Instruction::Xor:
2236     assert(C1->getType() == C2->getType() && "Op types should be identical!");
2237     assert(C1->getType()->isIntOrIntVector() &&
2238            "Tried to create a logical operation on a non-integral type!");
2239     break;
2240   case Instruction::Shl:
2241   case Instruction::LShr:
2242   case Instruction::AShr:
2243     assert(C1->getType() == C2->getType() && "Op types should be identical!");
2244     assert(C1->getType()->isIntOrIntVector() &&
2245            "Tried to create a shift operation on a non-integer type!");
2246     break;
2247   default:
2248     break;
2249   }
2250 #endif
2251
2252   return getTy(C1->getType(), Opcode, C1, C2);
2253 }
2254
2255 Constant *ConstantExpr::getCompare(unsigned short pred, 
2256                             Constant *C1, Constant *C2) {
2257   assert(C1->getType() == C2->getType() && "Op types should be identical!");
2258   return getCompareTy(pred, C1, C2);
2259 }
2260
2261 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
2262                                     Constant *V1, Constant *V2) {
2263   assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
2264
2265   if (ReqTy == V1->getType())
2266     if (Constant *SC = ConstantFoldSelectInstruction(
2267                                                 getGlobalContext(), C, V1, V2))
2268       return SC;        // Fold common cases
2269
2270   std::vector<Constant*> argVec(3, C);
2271   argVec[1] = V1;
2272   argVec[2] = V2;
2273   ExprMapKeyType Key(Instruction::Select, argVec);
2274   
2275   // Implicitly locked.
2276   return ExprConstants->getOrCreate(ReqTy, Key);
2277 }
2278
2279 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
2280                                            Value* const *Idxs,
2281                                            unsigned NumIdx) {
2282   assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
2283                                            Idxs+NumIdx) ==
2284          cast<PointerType>(ReqTy)->getElementType() &&
2285          "GEP indices invalid!");
2286
2287   if (Constant *FC = ConstantFoldGetElementPtr(
2288                                getGlobalContext(), C, (Constant**)Idxs, NumIdx))
2289     return FC;          // Fold a few common cases...
2290
2291   assert(isa<PointerType>(C->getType()) &&
2292          "Non-pointer type for constant GetElementPtr expression");
2293   // Look up the constant in the table first to ensure uniqueness
2294   std::vector<Constant*> ArgVec;
2295   ArgVec.reserve(NumIdx+1);
2296   ArgVec.push_back(C);
2297   for (unsigned i = 0; i != NumIdx; ++i)
2298     ArgVec.push_back(cast<Constant>(Idxs[i]));
2299   const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
2300
2301   // Implicitly locked.
2302   return ExprConstants->getOrCreate(ReqTy, Key);
2303 }
2304
2305 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
2306                                          unsigned NumIdx) {
2307   // Get the result type of the getelementptr!
2308   const Type *Ty = 
2309     GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
2310   assert(Ty && "GEP indices invalid!");
2311   unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
2312   return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
2313 }
2314
2315 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
2316                                          unsigned NumIdx) {
2317   return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
2318 }
2319
2320
2321 Constant *
2322 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2323   assert(LHS->getType() == RHS->getType());
2324   assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE && 
2325          pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
2326
2327   if (Constant *FC = ConstantFoldCompareInstruction(
2328                                              getGlobalContext(),pred, LHS, RHS))
2329     return FC;          // Fold a few common cases...
2330
2331   // Look up the constant in the table first to ensure uniqueness
2332   std::vector<Constant*> ArgVec;
2333   ArgVec.push_back(LHS);
2334   ArgVec.push_back(RHS);
2335   // Get the key type with both the opcode and predicate
2336   const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
2337
2338   // Implicitly locked.
2339   return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2340 }
2341
2342 Constant *
2343 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2344   assert(LHS->getType() == RHS->getType());
2345   assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
2346
2347   if (Constant *FC = ConstantFoldCompareInstruction(
2348                                             getGlobalContext(), pred, LHS, RHS))
2349     return FC;          // Fold a few common cases...
2350
2351   // Look up the constant in the table first to ensure uniqueness
2352   std::vector<Constant*> ArgVec;
2353   ArgVec.push_back(LHS);
2354   ArgVec.push_back(RHS);
2355   // Get the key type with both the opcode and predicate
2356   const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
2357   
2358   // Implicitly locked.
2359   return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2360 }
2361
2362 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
2363                                             Constant *Idx) {
2364   if (Constant *FC = ConstantFoldExtractElementInstruction(
2365                                                   getGlobalContext(), Val, Idx))
2366     return FC;          // Fold a few common cases...
2367   // Look up the constant in the table first to ensure uniqueness
2368   std::vector<Constant*> ArgVec(1, Val);
2369   ArgVec.push_back(Idx);
2370   const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
2371   
2372   // Implicitly locked.
2373   return ExprConstants->getOrCreate(ReqTy, Key);
2374 }
2375
2376 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
2377   assert(isa<VectorType>(Val->getType()) &&
2378          "Tried to create extractelement operation on non-vector type!");
2379   assert(Idx->getType() == Type::Int32Ty &&
2380          "Extractelement index must be i32 type!");
2381   return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
2382                              Val, Idx);
2383 }
2384
2385 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
2386                                            Constant *Elt, Constant *Idx) {
2387   if (Constant *FC = ConstantFoldInsertElementInstruction(
2388                                             getGlobalContext(), Val, Elt, Idx))
2389     return FC;          // Fold a few common cases...
2390   // Look up the constant in the table first to ensure uniqueness
2391   std::vector<Constant*> ArgVec(1, Val);
2392   ArgVec.push_back(Elt);
2393   ArgVec.push_back(Idx);
2394   const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
2395   
2396   // Implicitly locked.
2397   return ExprConstants->getOrCreate(ReqTy, Key);
2398 }
2399
2400 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt, 
2401                                          Constant *Idx) {
2402   assert(isa<VectorType>(Val->getType()) &&
2403          "Tried to create insertelement operation on non-vector type!");
2404   assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
2405          && "Insertelement types must match!");
2406   assert(Idx->getType() == Type::Int32Ty &&
2407          "Insertelement index must be i32 type!");
2408   return getInsertElementTy(Val->getType(), Val, Elt, Idx);
2409 }
2410
2411 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
2412                                            Constant *V2, Constant *Mask) {
2413   if (Constant *FC = ConstantFoldShuffleVectorInstruction(
2414                                               getGlobalContext(), V1, V2, Mask))
2415     return FC;          // Fold a few common cases...
2416   // Look up the constant in the table first to ensure uniqueness
2417   std::vector<Constant*> ArgVec(1, V1);
2418   ArgVec.push_back(V2);
2419   ArgVec.push_back(Mask);
2420   const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
2421   
2422   // Implicitly locked.
2423   return ExprConstants->getOrCreate(ReqTy, Key);
2424 }
2425
2426 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2, 
2427                                          Constant *Mask) {
2428   assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2429          "Invalid shuffle vector constant expr operands!");
2430
2431   unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
2432   const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
2433   const Type *ShufTy = VectorType::get(EltTy, NElts);
2434   return getShuffleVectorTy(ShufTy, V1, V2, Mask);
2435 }
2436
2437 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
2438                                          Constant *Val,
2439                                         const unsigned *Idxs, unsigned NumIdx) {
2440   assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2441                                           Idxs+NumIdx) == Val->getType() &&
2442          "insertvalue indices invalid!");
2443   assert(Agg->getType() == ReqTy &&
2444          "insertvalue type invalid!");
2445   assert(Agg->getType()->isFirstClassType() &&
2446          "Non-first-class type for constant InsertValue expression");
2447   Constant *FC = ConstantFoldInsertValueInstruction(
2448                                     getGlobalContext(), Agg, Val, Idxs, NumIdx);
2449   assert(FC && "InsertValue constant expr couldn't be folded!");
2450   return FC;
2451 }
2452
2453 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
2454                                      const unsigned *IdxList, unsigned NumIdx) {
2455   assert(Agg->getType()->isFirstClassType() &&
2456          "Tried to create insertelement operation on non-first-class type!");
2457
2458   const Type *ReqTy = Agg->getType();
2459 #ifndef NDEBUG
2460   const Type *ValTy =
2461     ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2462 #endif
2463   assert(ValTy == Val->getType() && "insertvalue indices invalid!");
2464   return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
2465 }
2466
2467 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
2468                                         const unsigned *Idxs, unsigned NumIdx) {
2469   assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2470                                           Idxs+NumIdx) == ReqTy &&
2471          "extractvalue indices invalid!");
2472   assert(Agg->getType()->isFirstClassType() &&
2473          "Non-first-class type for constant extractvalue expression");
2474   Constant *FC = ConstantFoldExtractValueInstruction(
2475                                          getGlobalContext(), Agg, Idxs, NumIdx);
2476   assert(FC && "ExtractValue constant expr couldn't be folded!");
2477   return FC;
2478 }
2479
2480 Constant *ConstantExpr::getExtractValue(Constant *Agg,
2481                                      const unsigned *IdxList, unsigned NumIdx) {
2482   assert(Agg->getType()->isFirstClassType() &&
2483          "Tried to create extractelement operation on non-first-class type!");
2484
2485   const Type *ReqTy =
2486     ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2487   assert(ReqTy && "extractvalue indices invalid!");
2488   return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
2489 }
2490
2491 // destroyConstant - Remove the constant from the constant table...
2492 //
2493 void ConstantExpr::destroyConstant() {
2494   // Implicitly locked.
2495   ExprConstants->remove(this);
2496   destroyConstantImpl();
2497 }
2498
2499 const char *ConstantExpr::getOpcodeName() const {
2500   return Instruction::getOpcodeName(getOpcode());
2501 }
2502
2503 //===----------------------------------------------------------------------===//
2504 //                replaceUsesOfWithOnConstant implementations
2505
2506 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2507 /// 'From' to be uses of 'To'.  This must update the uniquing data structures
2508 /// etc.
2509 ///
2510 /// Note that we intentionally replace all uses of From with To here.  Consider
2511 /// a large array that uses 'From' 1000 times.  By handling this case all here,
2512 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2513 /// single invocation handles all 1000 uses.  Handling them one at a time would
2514 /// work, but would be really slow because it would have to unique each updated
2515 /// array instance.
2516 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
2517                                                 Use *U) {
2518   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2519   Constant *ToC = cast<Constant>(To);
2520
2521   std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
2522   Lookup.first.first = getType();
2523   Lookup.second = this;
2524
2525   std::vector<Constant*> &Values = Lookup.first.second;
2526   Values.reserve(getNumOperands());  // Build replacement array.
2527
2528   // Fill values with the modified operands of the constant array.  Also, 
2529   // compute whether this turns into an all-zeros array.
2530   bool isAllZeros = false;
2531   unsigned NumUpdated = 0;
2532   if (!ToC->isNullValue()) {
2533     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2534       Constant *Val = cast<Constant>(O->get());
2535       if (Val == From) {
2536         Val = ToC;
2537         ++NumUpdated;
2538       }
2539       Values.push_back(Val);
2540     }
2541   } else {
2542     isAllZeros = true;
2543     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2544       Constant *Val = cast<Constant>(O->get());
2545       if (Val == From) {
2546         Val = ToC;
2547         ++NumUpdated;
2548       }
2549       Values.push_back(Val);
2550       if (isAllZeros) isAllZeros = Val->isNullValue();
2551     }
2552   }
2553   
2554   Constant *Replacement = 0;
2555   if (isAllZeros) {
2556     Replacement = ConstantAggregateZero::get(getType());
2557   } else {
2558     // Check to see if we have this array type already.
2559     sys::SmartScopedWriter<true> Writer(*ConstantsLock);
2560     bool Exists;
2561     ArrayConstantsTy::MapTy::iterator I =
2562       ArrayConstants->InsertOrGetItem(Lookup, Exists);
2563     
2564     if (Exists) {
2565       Replacement = I->second;
2566     } else {
2567       // Okay, the new shape doesn't exist in the system yet.  Instead of
2568       // creating a new constant array, inserting it, replaceallusesof'ing the
2569       // old with the new, then deleting the old... just update the current one
2570       // in place!
2571       ArrayConstants->MoveConstantToNewSlot(this, I);
2572       
2573       // Update to the new value.  Optimize for the case when we have a single
2574       // operand that we're changing, but handle bulk updates efficiently.
2575       if (NumUpdated == 1) {
2576         unsigned OperandToUpdate = U-OperandList;
2577         assert(getOperand(OperandToUpdate) == From &&
2578                "ReplaceAllUsesWith broken!");
2579         setOperand(OperandToUpdate, ToC);
2580       } else {
2581         for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2582           if (getOperand(i) == From)
2583             setOperand(i, ToC);
2584       }
2585       return;
2586     }
2587   }
2588  
2589   // Otherwise, I do need to replace this with an existing value.
2590   assert(Replacement != this && "I didn't contain From!");
2591   
2592   // Everyone using this now uses the replacement.
2593   uncheckedReplaceAllUsesWith(Replacement);
2594   
2595   // Delete the old constant!
2596   destroyConstant();
2597 }
2598
2599 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2600                                                  Use *U) {
2601   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2602   Constant *ToC = cast<Constant>(To);
2603
2604   unsigned OperandToUpdate = U-OperandList;
2605   assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2606
2607   std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
2608   Lookup.first.first = getType();
2609   Lookup.second = this;
2610   std::vector<Constant*> &Values = Lookup.first.second;
2611   Values.reserve(getNumOperands());  // Build replacement struct.
2612   
2613   
2614   // Fill values with the modified operands of the constant struct.  Also, 
2615   // compute whether this turns into an all-zeros struct.
2616   bool isAllZeros = false;
2617   if (!ToC->isNullValue()) {
2618     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2619       Values.push_back(cast<Constant>(O->get()));
2620   } else {
2621     isAllZeros = true;
2622     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2623       Constant *Val = cast<Constant>(O->get());
2624       Values.push_back(Val);
2625       if (isAllZeros) isAllZeros = Val->isNullValue();
2626     }
2627   }
2628   Values[OperandToUpdate] = ToC;
2629   
2630   Constant *Replacement = 0;
2631   if (isAllZeros) {
2632     Replacement = ConstantAggregateZero::get(getType());
2633   } else {
2634     // Check to see if we have this array type already.
2635     sys::SmartScopedWriter<true> Writer(*ConstantsLock);
2636     bool Exists;
2637     StructConstantsTy::MapTy::iterator I =
2638       StructConstants->InsertOrGetItem(Lookup, Exists);
2639     
2640     if (Exists) {
2641       Replacement = I->second;
2642     } else {
2643       // Okay, the new shape doesn't exist in the system yet.  Instead of
2644       // creating a new constant struct, inserting it, replaceallusesof'ing the
2645       // old with the new, then deleting the old... just update the current one
2646       // in place!
2647       StructConstants->MoveConstantToNewSlot(this, I);
2648       
2649       // Update to the new value.
2650       setOperand(OperandToUpdate, ToC);
2651       return;
2652     }
2653   }
2654   
2655   assert(Replacement != this && "I didn't contain From!");
2656   
2657   // Everyone using this now uses the replacement.
2658   uncheckedReplaceAllUsesWith(Replacement);
2659   
2660   // Delete the old constant!
2661   destroyConstant();
2662 }
2663
2664 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2665                                                  Use *U) {
2666   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2667   
2668   std::vector<Constant*> Values;
2669   Values.reserve(getNumOperands());  // Build replacement array...
2670   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2671     Constant *Val = getOperand(i);
2672     if (Val == From) Val = cast<Constant>(To);
2673     Values.push_back(Val);
2674   }
2675   
2676   Constant *Replacement = ConstantVector::get(getType(), Values);
2677   assert(Replacement != this && "I didn't contain From!");
2678   
2679   // Everyone using this now uses the replacement.
2680   uncheckedReplaceAllUsesWith(Replacement);
2681   
2682   // Delete the old constant!
2683   destroyConstant();
2684 }
2685
2686 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2687                                                Use *U) {
2688   assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2689   Constant *To = cast<Constant>(ToV);
2690   
2691   Constant *Replacement = 0;
2692   if (getOpcode() == Instruction::GetElementPtr) {
2693     SmallVector<Constant*, 8> Indices;
2694     Constant *Pointer = getOperand(0);
2695     Indices.reserve(getNumOperands()-1);
2696     if (Pointer == From) Pointer = To;
2697     
2698     for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2699       Constant *Val = getOperand(i);
2700       if (Val == From) Val = To;
2701       Indices.push_back(Val);
2702     }
2703     Replacement = ConstantExpr::getGetElementPtr(Pointer,
2704                                                  &Indices[0], Indices.size());
2705   } else if (getOpcode() == Instruction::ExtractValue) {
2706     Constant *Agg = getOperand(0);
2707     if (Agg == From) Agg = To;
2708     
2709     const SmallVector<unsigned, 4> &Indices = getIndices();
2710     Replacement = ConstantExpr::getExtractValue(Agg,
2711                                                 &Indices[0], Indices.size());
2712   } else if (getOpcode() == Instruction::InsertValue) {
2713     Constant *Agg = getOperand(0);
2714     Constant *Val = getOperand(1);
2715     if (Agg == From) Agg = To;
2716     if (Val == From) Val = To;
2717     
2718     const SmallVector<unsigned, 4> &Indices = getIndices();
2719     Replacement = ConstantExpr::getInsertValue(Agg, Val,
2720                                                &Indices[0], Indices.size());
2721   } else if (isCast()) {
2722     assert(getOperand(0) == From && "Cast only has one use!");
2723     Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2724   } else if (getOpcode() == Instruction::Select) {
2725     Constant *C1 = getOperand(0);
2726     Constant *C2 = getOperand(1);
2727     Constant *C3 = getOperand(2);
2728     if (C1 == From) C1 = To;
2729     if (C2 == From) C2 = To;
2730     if (C3 == From) C3 = To;
2731     Replacement = ConstantExpr::getSelect(C1, C2, C3);
2732   } else if (getOpcode() == Instruction::ExtractElement) {
2733     Constant *C1 = getOperand(0);
2734     Constant *C2 = getOperand(1);
2735     if (C1 == From) C1 = To;
2736     if (C2 == From) C2 = To;
2737     Replacement = ConstantExpr::getExtractElement(C1, C2);
2738   } else if (getOpcode() == Instruction::InsertElement) {
2739     Constant *C1 = getOperand(0);
2740     Constant *C2 = getOperand(1);
2741     Constant *C3 = getOperand(1);
2742     if (C1 == From) C1 = To;
2743     if (C2 == From) C2 = To;
2744     if (C3 == From) C3 = To;
2745     Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2746   } else if (getOpcode() == Instruction::ShuffleVector) {
2747     Constant *C1 = getOperand(0);
2748     Constant *C2 = getOperand(1);
2749     Constant *C3 = getOperand(2);
2750     if (C1 == From) C1 = To;
2751     if (C2 == From) C2 = To;
2752     if (C3 == From) C3 = To;
2753     Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2754   } else if (isCompare()) {
2755     Constant *C1 = getOperand(0);
2756     Constant *C2 = getOperand(1);
2757     if (C1 == From) C1 = To;
2758     if (C2 == From) C2 = To;
2759     if (getOpcode() == Instruction::ICmp)
2760       Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2761     else {
2762       assert(getOpcode() == Instruction::FCmp);
2763       Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2764     }
2765   } else if (getNumOperands() == 2) {
2766     Constant *C1 = getOperand(0);
2767     Constant *C2 = getOperand(1);
2768     if (C1 == From) C1 = To;
2769     if (C2 == From) C2 = To;
2770     Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2771   } else {
2772     LLVM_UNREACHABLE("Unknown ConstantExpr type!");
2773     return;
2774   }
2775   
2776   assert(Replacement != this && "I didn't contain From!");
2777   
2778   // Everyone using this now uses the replacement.
2779   uncheckedReplaceAllUsesWith(Replacement);
2780   
2781   // Delete the old constant!
2782   destroyConstant();
2783 }
2784
2785 void MDNode::replaceElement(Value *From, Value *To) {
2786   SmallVector<Value*, 4> Values;
2787   Values.reserve(getNumElements());  // Build replacement array...
2788   for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
2789     Value *Val = getElement(i);
2790     if (Val == From) Val = To;
2791     Values.push_back(Val);
2792   }
2793
2794   MDNode *Replacement = MDNode::get(&Values[0], Values.size());
2795   assert(Replacement != this && "I didn't contain From!");
2796
2797   uncheckedReplaceAllUsesWith(Replacement);
2798
2799   destroyConstant();
2800 }