33c8f675f8dd8d560a17554557e3422cb0caa030
[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 unsigned ConstantExpr::getPredicate() const {
758   assert(getOpcode() == Instruction::FCmp || 
759          getOpcode() == Instruction::ICmp);
760   return ((const CompareConstantExpr*)this)->predicate;
761 }
762
763 /// getWithOperandReplaced - Return a constant expression identical to this
764 /// one, but with the specified operand set to the specified value.
765 Constant *
766 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
767   assert(OpNo < getNumOperands() && "Operand num is out of range!");
768   assert(Op->getType() == getOperand(OpNo)->getType() &&
769          "Replacing operand with value of different type!");
770   if (getOperand(OpNo) == Op)
771     return const_cast<ConstantExpr*>(this);
772   
773   Constant *Op0, *Op1, *Op2;
774   switch (getOpcode()) {
775   case Instruction::Trunc:
776   case Instruction::ZExt:
777   case Instruction::SExt:
778   case Instruction::FPTrunc:
779   case Instruction::FPExt:
780   case Instruction::UIToFP:
781   case Instruction::SIToFP:
782   case Instruction::FPToUI:
783   case Instruction::FPToSI:
784   case Instruction::PtrToInt:
785   case Instruction::IntToPtr:
786   case Instruction::BitCast:
787     return ConstantExpr::getCast(getOpcode(), Op, getType());
788   case Instruction::Select:
789     Op0 = (OpNo == 0) ? Op : getOperand(0);
790     Op1 = (OpNo == 1) ? Op : getOperand(1);
791     Op2 = (OpNo == 2) ? Op : getOperand(2);
792     return ConstantExpr::getSelect(Op0, Op1, Op2);
793   case Instruction::InsertElement:
794     Op0 = (OpNo == 0) ? Op : getOperand(0);
795     Op1 = (OpNo == 1) ? Op : getOperand(1);
796     Op2 = (OpNo == 2) ? Op : getOperand(2);
797     return ConstantExpr::getInsertElement(Op0, Op1, Op2);
798   case Instruction::ExtractElement:
799     Op0 = (OpNo == 0) ? Op : getOperand(0);
800     Op1 = (OpNo == 1) ? Op : getOperand(1);
801     return ConstantExpr::getExtractElement(Op0, Op1);
802   case Instruction::ShuffleVector:
803     Op0 = (OpNo == 0) ? Op : getOperand(0);
804     Op1 = (OpNo == 1) ? Op : getOperand(1);
805     Op2 = (OpNo == 2) ? Op : getOperand(2);
806     return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
807   case Instruction::GetElementPtr: {
808     SmallVector<Constant*, 8> Ops;
809     Ops.resize(getNumOperands()-1);
810     for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
811       Ops[i-1] = getOperand(i);
812     if (OpNo == 0)
813       return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
814     Ops[OpNo-1] = Op;
815     return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
816   }
817   default:
818     assert(getNumOperands() == 2 && "Must be binary operator?");
819     Op0 = (OpNo == 0) ? Op : getOperand(0);
820     Op1 = (OpNo == 1) ? Op : getOperand(1);
821     return ConstantExpr::get(getOpcode(), Op0, Op1);
822   }
823 }
824
825 /// getWithOperands - This returns the current constant expression with the
826 /// operands replaced with the specified values.  The specified operands must
827 /// match count and type with the existing ones.
828 Constant *ConstantExpr::
829 getWithOperands(Constant* const *Ops, unsigned NumOps) const {
830   assert(NumOps == getNumOperands() && "Operand count mismatch!");
831   bool AnyChange = false;
832   for (unsigned i = 0; i != NumOps; ++i) {
833     assert(Ops[i]->getType() == getOperand(i)->getType() &&
834            "Operand type mismatch!");
835     AnyChange |= Ops[i] != getOperand(i);
836   }
837   if (!AnyChange)  // No operands changed, return self.
838     return const_cast<ConstantExpr*>(this);
839
840   switch (getOpcode()) {
841   case Instruction::Trunc:
842   case Instruction::ZExt:
843   case Instruction::SExt:
844   case Instruction::FPTrunc:
845   case Instruction::FPExt:
846   case Instruction::UIToFP:
847   case Instruction::SIToFP:
848   case Instruction::FPToUI:
849   case Instruction::FPToSI:
850   case Instruction::PtrToInt:
851   case Instruction::IntToPtr:
852   case Instruction::BitCast:
853     return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
854   case Instruction::Select:
855     return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
856   case Instruction::InsertElement:
857     return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
858   case Instruction::ExtractElement:
859     return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
860   case Instruction::ShuffleVector:
861     return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
862   case Instruction::GetElementPtr:
863     return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
864   case Instruction::ICmp:
865   case Instruction::FCmp:
866     return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
867   default:
868     assert(getNumOperands() == 2 && "Must be binary operator?");
869     return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
870   }
871 }
872
873
874 //===----------------------------------------------------------------------===//
875 //                      isValueValidForType implementations
876
877 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
878   unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
879   if (Ty == Type::Int1Ty)
880     return Val == 0 || Val == 1;
881   if (NumBits >= 64)
882     return true; // always true, has to fit in largest type
883   uint64_t Max = (1ll << NumBits) - 1;
884   return Val <= Max;
885 }
886
887 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
888   unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
889   if (Ty == Type::Int1Ty)
890     return Val == 0 || Val == 1 || Val == -1;
891   if (NumBits >= 64)
892     return true; // always true, has to fit in largest type
893   int64_t Min = -(1ll << (NumBits-1));
894   int64_t Max = (1ll << (NumBits-1)) - 1;
895   return (Val >= Min && Val <= Max);
896 }
897
898 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
899   // convert modifies in place, so make a copy.
900   APFloat Val2 = APFloat(Val);
901   bool losesInfo;
902   switch (Ty->getTypeID()) {
903   default:
904     return false;         // These can't be represented as floating point!
905
906   // FIXME rounding mode needs to be more flexible
907   case Type::FloatTyID: {
908     if (&Val2.getSemantics() == &APFloat::IEEEsingle)
909       return true;
910     Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
911     return !losesInfo;
912   }
913   case Type::DoubleTyID: {
914     if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
915         &Val2.getSemantics() == &APFloat::IEEEdouble)
916       return true;
917     Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
918     return !losesInfo;
919   }
920   case Type::X86_FP80TyID:
921     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
922            &Val2.getSemantics() == &APFloat::IEEEdouble ||
923            &Val2.getSemantics() == &APFloat::x87DoubleExtended;
924   case Type::FP128TyID:
925     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
926            &Val2.getSemantics() == &APFloat::IEEEdouble ||
927            &Val2.getSemantics() == &APFloat::IEEEquad;
928   case Type::PPC_FP128TyID:
929     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
930            &Val2.getSemantics() == &APFloat::IEEEdouble ||
931            &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
932   }
933 }
934
935 //===----------------------------------------------------------------------===//
936 //                      Factory Function Implementation
937
938
939 // The number of operands for each ConstantCreator::create method is
940 // determined by the ConstantTraits template.
941 // ConstantCreator - A class that is used to create constants by
942 // ValueMap*.  This class should be partially specialized if there is
943 // something strange that needs to be done to interface to the ctor for the
944 // constant.
945 //
946 namespace llvm {
947   template<class ValType>
948   struct ConstantTraits;
949
950   template<typename T, typename Alloc>
951   struct VISIBILITY_HIDDEN ConstantTraits< std::vector<T, Alloc> > {
952     static unsigned uses(const std::vector<T, Alloc>& v) {
953       return v.size();
954     }
955   };
956
957   template<class ConstantClass, class TypeClass, class ValType>
958   struct VISIBILITY_HIDDEN ConstantCreator {
959     static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
960       return new(ConstantTraits<ValType>::uses(V)) ConstantClass(Ty, V);
961     }
962   };
963
964   template<class ConstantClass, class TypeClass>
965   struct VISIBILITY_HIDDEN ConvertConstantType {
966     static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
967       llvm_unreachable("This type cannot be converted!");
968     }
969   };
970
971   template<class ValType, class TypeClass, class ConstantClass,
972            bool HasLargeKey = false  /*true for arrays and structs*/ >
973   class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
974   public:
975     typedef std::pair<const Type*, ValType> MapKey;
976     typedef std::map<MapKey, Constant *> MapTy;
977     typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
978     typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
979   private:
980     /// Map - This is the main map from the element descriptor to the Constants.
981     /// This is the primary way we avoid creating two of the same shape
982     /// constant.
983     MapTy Map;
984     
985     /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
986     /// from the constants to their element in Map.  This is important for
987     /// removal of constants from the array, which would otherwise have to scan
988     /// through the map with very large keys.
989     InverseMapTy InverseMap;
990
991     /// AbstractTypeMap - Map for abstract type constants.
992     ///
993     AbstractTypeMapTy AbstractTypeMap;
994     
995     /// ValueMapLock - Mutex for this map.
996     sys::SmartMutex<true> ValueMapLock;
997
998   public:
999     // NOTE: This function is not locked.  It is the caller's responsibility
1000     // to enforce proper synchronization.
1001     typename MapTy::iterator map_end() { return Map.end(); }
1002     
1003     /// InsertOrGetItem - Return an iterator for the specified element.
1004     /// If the element exists in the map, the returned iterator points to the
1005     /// entry and Exists=true.  If not, the iterator points to the newly
1006     /// inserted entry and returns Exists=false.  Newly inserted entries have
1007     /// I->second == 0, and should be filled in.
1008     /// NOTE: This function is not locked.  It is the caller's responsibility
1009     // to enforce proper synchronization.
1010     typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
1011                                    &InsertVal,
1012                                    bool &Exists) {
1013       std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
1014       Exists = !IP.second;
1015       return IP.first;
1016     }
1017     
1018 private:
1019     typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
1020       if (HasLargeKey) {
1021         typename InverseMapTy::iterator IMI = InverseMap.find(CP);
1022         assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
1023                IMI->second->second == CP &&
1024                "InverseMap corrupt!");
1025         return IMI->second;
1026       }
1027       
1028       typename MapTy::iterator I =
1029         Map.find(MapKey(static_cast<const TypeClass*>(CP->getRawType()),
1030                         getValType(CP)));
1031       if (I == Map.end() || I->second != CP) {
1032         // FIXME: This should not use a linear scan.  If this gets to be a
1033         // performance problem, someone should look at this.
1034         for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
1035           /* empty */;
1036       }
1037       return I;
1038     }
1039     
1040     ConstantClass* Create(const TypeClass *Ty, const ValType &V,
1041                           typename MapTy::iterator I) {
1042       ConstantClass* Result =
1043         ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
1044
1045       assert(Result->getType() == Ty && "Type specified is not correct!");
1046       I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
1047
1048       if (HasLargeKey)  // Remember the reverse mapping if needed.
1049         InverseMap.insert(std::make_pair(Result, I));
1050
1051       // If the type of the constant is abstract, make sure that an entry
1052       // exists for it in the AbstractTypeMap.
1053       if (Ty->isAbstract()) {
1054         typename AbstractTypeMapTy::iterator TI = 
1055                                                  AbstractTypeMap.find(Ty);
1056
1057         if (TI == AbstractTypeMap.end()) {
1058           // Add ourselves to the ATU list of the type.
1059           cast<DerivedType>(Ty)->addAbstractTypeUser(this);
1060
1061           AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
1062         }
1063       }
1064       
1065       return Result;
1066     }
1067 public:
1068     
1069     /// getOrCreate - Return the specified constant from the map, creating it if
1070     /// necessary.
1071     ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
1072       sys::SmartScopedLock<true> Lock(ValueMapLock);
1073       MapKey Lookup(Ty, V);
1074       ConstantClass* Result = 0;
1075       
1076       typename MapTy::iterator I = Map.find(Lookup);
1077       // Is it in the map?  
1078       if (I != Map.end())
1079         Result = static_cast<ConstantClass *>(I->second);
1080         
1081       if (!Result) {
1082         // If no preexisting value, create one now...
1083         Result = Create(Ty, V, I);
1084       }
1085         
1086       return Result;
1087     }
1088
1089     void remove(ConstantClass *CP) {
1090       sys::SmartScopedLock<true> Lock(ValueMapLock);
1091       typename MapTy::iterator I = FindExistingElement(CP);
1092       assert(I != Map.end() && "Constant not found in constant table!");
1093       assert(I->second == CP && "Didn't find correct element?");
1094
1095       if (HasLargeKey)  // Remember the reverse mapping if needed.
1096         InverseMap.erase(CP);
1097       
1098       // Now that we found the entry, make sure this isn't the entry that
1099       // the AbstractTypeMap points to.
1100       const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
1101       if (Ty->isAbstract()) {
1102         assert(AbstractTypeMap.count(Ty) &&
1103                "Abstract type not in AbstractTypeMap?");
1104         typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
1105         if (ATMEntryIt == I) {
1106           // Yes, we are removing the representative entry for this type.
1107           // See if there are any other entries of the same type.
1108           typename MapTy::iterator TmpIt = ATMEntryIt;
1109
1110           // First check the entry before this one...
1111           if (TmpIt != Map.begin()) {
1112             --TmpIt;
1113             if (TmpIt->first.first != Ty) // Not the same type, move back...
1114               ++TmpIt;
1115           }
1116
1117           // If we didn't find the same type, try to move forward...
1118           if (TmpIt == ATMEntryIt) {
1119             ++TmpIt;
1120             if (TmpIt == Map.end() || TmpIt->first.first != Ty)
1121               --TmpIt;   // No entry afterwards with the same type
1122           }
1123
1124           // If there is another entry in the map of the same abstract type,
1125           // update the AbstractTypeMap entry now.
1126           if (TmpIt != ATMEntryIt) {
1127             ATMEntryIt = TmpIt;
1128           } else {
1129             // Otherwise, we are removing the last instance of this type
1130             // from the table.  Remove from the ATM, and from user list.
1131             cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
1132             AbstractTypeMap.erase(Ty);
1133           }
1134         }
1135       }
1136
1137       Map.erase(I);
1138     }
1139
1140     
1141     /// MoveConstantToNewSlot - If we are about to change C to be the element
1142     /// specified by I, update our internal data structures to reflect this
1143     /// fact.
1144     /// NOTE: This function is not locked. It is the responsibility of the
1145     /// caller to enforce proper synchronization if using this method.
1146     void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
1147       // First, remove the old location of the specified constant in the map.
1148       typename MapTy::iterator OldI = FindExistingElement(C);
1149       assert(OldI != Map.end() && "Constant not found in constant table!");
1150       assert(OldI->second == C && "Didn't find correct element?");
1151       
1152       // If this constant is the representative element for its abstract type,
1153       // update the AbstractTypeMap so that the representative element is I.
1154       if (C->getType()->isAbstract()) {
1155         typename AbstractTypeMapTy::iterator ATI =
1156             AbstractTypeMap.find(C->getType());
1157         assert(ATI != AbstractTypeMap.end() &&
1158                "Abstract type not in AbstractTypeMap?");
1159         if (ATI->second == OldI)
1160           ATI->second = I;
1161       }
1162       
1163       // Remove the old entry from the map.
1164       Map.erase(OldI);
1165       
1166       // Update the inverse map so that we know that this constant is now
1167       // located at descriptor I.
1168       if (HasLargeKey) {
1169         assert(I->second == C && "Bad inversemap entry!");
1170         InverseMap[C] = I;
1171       }
1172     }
1173     
1174     void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
1175       sys::SmartScopedLock<true> Lock(ValueMapLock);
1176       typename AbstractTypeMapTy::iterator I =
1177         AbstractTypeMap.find(cast<Type>(OldTy));
1178
1179       assert(I != AbstractTypeMap.end() &&
1180              "Abstract type not in AbstractTypeMap?");
1181
1182       // Convert a constant at a time until the last one is gone.  The last one
1183       // leaving will remove() itself, causing the AbstractTypeMapEntry to be
1184       // eliminated eventually.
1185       do {
1186         ConvertConstantType<ConstantClass,
1187                             TypeClass>::convert(
1188                                 static_cast<ConstantClass *>(I->second->second),
1189                                                 cast<TypeClass>(NewTy));
1190
1191         I = AbstractTypeMap.find(cast<Type>(OldTy));
1192       } while (I != AbstractTypeMap.end());
1193     }
1194
1195     // If the type became concrete without being refined to any other existing
1196     // type, we just remove ourselves from the ATU list.
1197     void typeBecameConcrete(const DerivedType *AbsTy) {
1198       AbsTy->removeAbstractTypeUser(this);
1199     }
1200
1201     void dump() const {
1202       DOUT << "Constant.cpp: ValueMap\n";
1203     }
1204   };
1205 }
1206
1207
1208
1209 //---- ConstantAggregateZero::get() implementation...
1210 //
1211 namespace llvm {
1212   // ConstantAggregateZero does not take extra "value" argument...
1213   template<class ValType>
1214   struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
1215     static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
1216       return new ConstantAggregateZero(Ty);
1217     }
1218   };
1219
1220   template<>
1221   struct ConvertConstantType<ConstantAggregateZero, Type> {
1222     static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1223       // Make everyone now use a constant of the new type...
1224       Constant *New = ConstantAggregateZero::get(NewTy);
1225       assert(New != OldC && "Didn't replace constant??");
1226       OldC->uncheckedReplaceAllUsesWith(New);
1227       OldC->destroyConstant();     // This constant is now dead, destroy it.
1228     }
1229   };
1230 }
1231
1232 static ManagedStatic<ValueMap<char, Type, 
1233                               ConstantAggregateZero> > AggZeroConstants;
1234
1235 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1236
1237 ConstantAggregateZero *ConstantAggregateZero::get(const Type *Ty) {
1238   assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
1239          "Cannot create an aggregate zero of non-aggregate type!");
1240   
1241   // Implicitly locked.
1242   return AggZeroConstants->getOrCreate(Ty, 0);
1243 }
1244
1245 /// destroyConstant - Remove the constant from the constant table...
1246 ///
1247 void ConstantAggregateZero::destroyConstant() {
1248   // Implicitly locked.
1249   AggZeroConstants->remove(this);
1250   destroyConstantImpl();
1251 }
1252
1253 //---- ConstantArray::get() implementation...
1254 //
1255 namespace llvm {
1256   template<>
1257   struct ConvertConstantType<ConstantArray, ArrayType> {
1258     static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1259       // Make everyone now use a constant of the new type...
1260       std::vector<Constant*> C;
1261       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1262         C.push_back(cast<Constant>(OldC->getOperand(i)));
1263       Constant *New = ConstantArray::get(NewTy, C);
1264       assert(New != OldC && "Didn't replace constant??");
1265       OldC->uncheckedReplaceAllUsesWith(New);
1266       OldC->destroyConstant();    // This constant is now dead, destroy it.
1267     }
1268   };
1269 }
1270
1271 static std::vector<Constant*> getValType(ConstantArray *CA) {
1272   std::vector<Constant*> Elements;
1273   Elements.reserve(CA->getNumOperands());
1274   for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1275     Elements.push_back(cast<Constant>(CA->getOperand(i)));
1276   return Elements;
1277 }
1278
1279 typedef ValueMap<std::vector<Constant*>, ArrayType, 
1280                  ConstantArray, true /*largekey*/> ArrayConstantsTy;
1281 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
1282
1283 Constant *ConstantArray::get(const ArrayType *Ty,
1284                              const std::vector<Constant*> &V) {
1285   // If this is an all-zero array, return a ConstantAggregateZero object
1286   if (!V.empty()) {
1287     Constant *C = V[0];
1288     if (!C->isNullValue()) {
1289       // Implicitly locked.
1290       return ArrayConstants->getOrCreate(Ty, V);
1291     }
1292     for (unsigned i = 1, e = V.size(); i != e; ++i)
1293       if (V[i] != C) {
1294         // Implicitly locked.
1295         return ArrayConstants->getOrCreate(Ty, V);
1296       }
1297   }
1298   
1299   return ConstantAggregateZero::get(Ty);
1300 }
1301
1302 /// destroyConstant - Remove the constant from the constant table...
1303 ///
1304 void ConstantArray::destroyConstant() {
1305   // Implicitly locked.
1306   ArrayConstants->remove(this);
1307   destroyConstantImpl();
1308 }
1309
1310 /// ConstantArray::get(const string&) - Return an array that is initialized to
1311 /// contain the specified string.  If length is zero then a null terminator is 
1312 /// added to the specified string so that it may be used in a natural way. 
1313 /// Otherwise, the length parameter specifies how much of the string to use 
1314 /// and it won't be null terminated.
1315 ///
1316 Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
1317   std::vector<Constant*> ElementVals;
1318   for (unsigned i = 0; i < Str.length(); ++i)
1319     ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
1320
1321   // Add a null terminator to the string...
1322   if (AddNull) {
1323     ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
1324   }
1325
1326   ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
1327   return ConstantArray::get(ATy, ElementVals);
1328 }
1329
1330 /// isString - This method returns true if the array is an array of i8, and 
1331 /// if the elements of the array are all ConstantInt's.
1332 bool ConstantArray::isString() const {
1333   // Check the element type for i8...
1334   if (getType()->getElementType() != Type::Int8Ty)
1335     return false;
1336   // Check the elements to make sure they are all integers, not constant
1337   // expressions.
1338   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1339     if (!isa<ConstantInt>(getOperand(i)))
1340       return false;
1341   return true;
1342 }
1343
1344 /// isCString - This method returns true if the array is a string (see
1345 /// isString) and it ends in a null byte \\0 and does not contains any other
1346 /// null bytes except its terminator.
1347 bool ConstantArray::isCString() const {
1348   // Check the element type for i8...
1349   if (getType()->getElementType() != Type::Int8Ty)
1350     return false;
1351
1352   // Last element must be a null.
1353   if (!getOperand(getNumOperands()-1)->isNullValue())
1354     return false;
1355   // Other elements must be non-null integers.
1356   for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1357     if (!isa<ConstantInt>(getOperand(i)))
1358       return false;
1359     if (getOperand(i)->isNullValue())
1360       return false;
1361   }
1362   return true;
1363 }
1364
1365
1366 /// getAsString - If the sub-element type of this array is i8
1367 /// then this method converts the array to an std::string and returns it.
1368 /// Otherwise, it asserts out.
1369 ///
1370 std::string ConstantArray::getAsString() const {
1371   assert(isString() && "Not a string!");
1372   std::string Result;
1373   Result.reserve(getNumOperands());
1374   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1375     Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
1376   return Result;
1377 }
1378
1379
1380 //---- ConstantStruct::get() implementation...
1381 //
1382
1383 namespace llvm {
1384   template<>
1385   struct ConvertConstantType<ConstantStruct, StructType> {
1386     static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1387       // Make everyone now use a constant of the new type...
1388       std::vector<Constant*> C;
1389       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1390         C.push_back(cast<Constant>(OldC->getOperand(i)));
1391       Constant *New = ConstantStruct::get(NewTy, C);
1392       assert(New != OldC && "Didn't replace constant??");
1393
1394       OldC->uncheckedReplaceAllUsesWith(New);
1395       OldC->destroyConstant();    // This constant is now dead, destroy it.
1396     }
1397   };
1398 }
1399
1400 typedef ValueMap<std::vector<Constant*>, StructType,
1401                  ConstantStruct, true /*largekey*/> StructConstantsTy;
1402 static ManagedStatic<StructConstantsTy> StructConstants;
1403
1404 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1405   std::vector<Constant*> Elements;
1406   Elements.reserve(CS->getNumOperands());
1407   for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1408     Elements.push_back(cast<Constant>(CS->getOperand(i)));
1409   return Elements;
1410 }
1411
1412 Constant *ConstantStruct::get(const StructType *Ty,
1413                               const std::vector<Constant*> &V) {
1414   // Create a ConstantAggregateZero value if all elements are zeros...
1415   for (unsigned i = 0, e = V.size(); i != e; ++i)
1416     if (!V[i]->isNullValue())
1417       // Implicitly locked.
1418       return StructConstants->getOrCreate(Ty, V);
1419
1420   return ConstantAggregateZero::get(Ty);
1421 }
1422
1423 Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
1424   std::vector<const Type*> StructEls;
1425   StructEls.reserve(V.size());
1426   for (unsigned i = 0, e = V.size(); i != e; ++i)
1427     StructEls.push_back(V[i]->getType());
1428   return get(StructType::get(StructEls, packed), V);
1429 }
1430
1431 // destroyConstant - Remove the constant from the constant table...
1432 //
1433 void ConstantStruct::destroyConstant() {
1434   // Implicitly locked.
1435   StructConstants->remove(this);
1436   destroyConstantImpl();
1437 }
1438
1439 //---- ConstantVector::get() implementation...
1440 //
1441 namespace llvm {
1442   template<>
1443   struct ConvertConstantType<ConstantVector, VectorType> {
1444     static void convert(ConstantVector *OldC, const VectorType *NewTy) {
1445       // Make everyone now use a constant of the new type...
1446       std::vector<Constant*> C;
1447       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1448         C.push_back(cast<Constant>(OldC->getOperand(i)));
1449       Constant *New = ConstantVector::get(NewTy, C);
1450       assert(New != OldC && "Didn't replace constant??");
1451       OldC->uncheckedReplaceAllUsesWith(New);
1452       OldC->destroyConstant();    // This constant is now dead, destroy it.
1453     }
1454   };
1455 }
1456
1457 static std::vector<Constant*> getValType(ConstantVector *CP) {
1458   std::vector<Constant*> Elements;
1459   Elements.reserve(CP->getNumOperands());
1460   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1461     Elements.push_back(CP->getOperand(i));
1462   return Elements;
1463 }
1464
1465 static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
1466                               ConstantVector> > VectorConstants;
1467
1468 Constant *ConstantVector::get(const VectorType *Ty,
1469                               const std::vector<Constant*> &V) {
1470   assert(!V.empty() && "Vectors can't be empty");
1471   // If this is an all-undef or alll-zero vector, return a
1472   // ConstantAggregateZero or UndefValue.
1473   Constant *C = V[0];
1474   bool isZero = C->isNullValue();
1475   bool isUndef = isa<UndefValue>(C);
1476
1477   if (isZero || isUndef) {
1478     for (unsigned i = 1, e = V.size(); i != e; ++i)
1479       if (V[i] != C) {
1480         isZero = isUndef = false;
1481         break;
1482       }
1483   }
1484   
1485   if (isZero)
1486     return ConstantAggregateZero::get(Ty);
1487   if (isUndef)
1488     return UndefValue::get(Ty);
1489     
1490   // Implicitly locked.
1491   return VectorConstants->getOrCreate(Ty, V);
1492 }
1493
1494 Constant *ConstantVector::get(const std::vector<Constant*> &V) {
1495   assert(!V.empty() && "Cannot infer type if V is empty");
1496   return get(VectorType::get(V.front()->getType(),V.size()), V);
1497 }
1498
1499 // destroyConstant - Remove the constant from the constant table...
1500 //
1501 void ConstantVector::destroyConstant() {
1502   // Implicitly locked.
1503   VectorConstants->remove(this);
1504   destroyConstantImpl();
1505 }
1506
1507 /// This function will return true iff every element in this vector constant
1508 /// is set to all ones.
1509 /// @returns true iff this constant's emements are all set to all ones.
1510 /// @brief Determine if the value is all ones.
1511 bool ConstantVector::isAllOnesValue() const {
1512   // Check out first element.
1513   const Constant *Elt = getOperand(0);
1514   const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1515   if (!CI || !CI->isAllOnesValue()) return false;
1516   // Then make sure all remaining elements point to the same value.
1517   for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1518     if (getOperand(I) != Elt) return false;
1519   }
1520   return true;
1521 }
1522
1523 /// getSplatValue - If this is a splat constant, where all of the
1524 /// elements have the same value, return that value. Otherwise return null.
1525 Constant *ConstantVector::getSplatValue() {
1526   // Check out first element.
1527   Constant *Elt = getOperand(0);
1528   // Then make sure all remaining elements point to the same value.
1529   for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1530     if (getOperand(I) != Elt) return 0;
1531   return Elt;
1532 }
1533
1534 //---- ConstantPointerNull::get() implementation...
1535 //
1536
1537 namespace llvm {
1538   // ConstantPointerNull does not take extra "value" argument...
1539   template<class ValType>
1540   struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1541     static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1542       return new ConstantPointerNull(Ty);
1543     }
1544   };
1545
1546   template<>
1547   struct ConvertConstantType<ConstantPointerNull, PointerType> {
1548     static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1549       // Make everyone now use a constant of the new type...
1550       Constant *New = ConstantPointerNull::get(NewTy);
1551       assert(New != OldC && "Didn't replace constant??");
1552       OldC->uncheckedReplaceAllUsesWith(New);
1553       OldC->destroyConstant();     // This constant is now dead, destroy it.
1554     }
1555   };
1556 }
1557
1558 static ManagedStatic<ValueMap<char, PointerType, 
1559                               ConstantPointerNull> > NullPtrConstants;
1560
1561 static char getValType(ConstantPointerNull *) {
1562   return 0;
1563 }
1564
1565
1566 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1567   // Implicitly locked.
1568   return NullPtrConstants->getOrCreate(Ty, 0);
1569 }
1570
1571 // destroyConstant - Remove the constant from the constant table...
1572 //
1573 void ConstantPointerNull::destroyConstant() {
1574   // Implicitly locked.
1575   NullPtrConstants->remove(this);
1576   destroyConstantImpl();
1577 }
1578
1579
1580 //---- UndefValue::get() implementation...
1581 //
1582
1583 namespace llvm {
1584   // UndefValue does not take extra "value" argument...
1585   template<class ValType>
1586   struct ConstantCreator<UndefValue, Type, ValType> {
1587     static UndefValue *create(const Type *Ty, const ValType &V) {
1588       return new UndefValue(Ty);
1589     }
1590   };
1591
1592   template<>
1593   struct ConvertConstantType<UndefValue, Type> {
1594     static void convert(UndefValue *OldC, const Type *NewTy) {
1595       // Make everyone now use a constant of the new type.
1596       Constant *New = UndefValue::get(NewTy);
1597       assert(New != OldC && "Didn't replace constant??");
1598       OldC->uncheckedReplaceAllUsesWith(New);
1599       OldC->destroyConstant();     // This constant is now dead, destroy it.
1600     }
1601   };
1602 }
1603
1604 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1605
1606 static char getValType(UndefValue *) {
1607   return 0;
1608 }
1609
1610
1611 UndefValue *UndefValue::get(const Type *Ty) {
1612   // Implicitly locked.
1613   return UndefValueConstants->getOrCreate(Ty, 0);
1614 }
1615
1616 // destroyConstant - Remove the constant from the constant table.
1617 //
1618 void UndefValue::destroyConstant() {
1619   // Implicitly locked.
1620   UndefValueConstants->remove(this);
1621   destroyConstantImpl();
1622 }
1623
1624 //---- MDString::get() implementation
1625 //
1626
1627 MDString::MDString(const char *begin, const char *end)
1628   : Constant(Type::MetadataTy, MDStringVal, 0, 0),
1629     StrBegin(begin), StrEnd(end) {}
1630
1631 static ManagedStatic<StringMap<MDString*> > MDStringCache;
1632
1633 MDString *MDString::get(const char *StrBegin, const char *StrEnd) {
1634   sys::SmartScopedWriter<true> Writer(*ConstantsLock);
1635   StringMapEntry<MDString *> &Entry = MDStringCache->GetOrCreateValue(
1636                                         StrBegin, StrEnd);
1637   MDString *&S = Entry.getValue();
1638   if (!S) S = new MDString(Entry.getKeyData(),
1639                            Entry.getKeyData() + Entry.getKeyLength());
1640
1641   return S;
1642 }
1643
1644 MDString *MDString::get(const std::string &Str) {
1645   sys::SmartScopedWriter<true> Writer(*ConstantsLock);
1646   StringMapEntry<MDString *> &Entry = MDStringCache->GetOrCreateValue(
1647                                         Str.data(), Str.data() + Str.size());
1648   MDString *&S = Entry.getValue();
1649   if (!S) S = new MDString(Entry.getKeyData(),
1650                            Entry.getKeyData() + Entry.getKeyLength());
1651
1652   return S;
1653 }
1654
1655 void MDString::destroyConstant() {
1656   sys::SmartScopedWriter<true> Writer(*ConstantsLock);
1657   MDStringCache->erase(MDStringCache->find(StrBegin, StrEnd));
1658   destroyConstantImpl();
1659 }
1660
1661 //---- MDNode::get() implementation
1662 //
1663
1664 static ManagedStatic<FoldingSet<MDNode> > MDNodeSet;
1665
1666 MDNode::MDNode(Value*const* Vals, unsigned NumVals)
1667   : Constant(Type::MetadataTy, MDNodeVal, 0, 0) {
1668   for (unsigned i = 0; i != NumVals; ++i)
1669     Node.push_back(ElementVH(Vals[i], this));
1670 }
1671
1672 void MDNode::Profile(FoldingSetNodeID &ID) const {
1673   for (const_elem_iterator I = elem_begin(), E = elem_end(); I != E; ++I)
1674     ID.AddPointer(*I);
1675 }
1676
1677 MDNode *MDNode::get(Value*const* Vals, unsigned NumVals) {
1678   FoldingSetNodeID ID;
1679   for (unsigned i = 0; i != NumVals; ++i)
1680     ID.AddPointer(Vals[i]);
1681
1682   ConstantsLock->reader_acquire();
1683   void *InsertPoint;
1684   MDNode *N = MDNodeSet->FindNodeOrInsertPos(ID, InsertPoint);
1685   ConstantsLock->reader_release();
1686   
1687   if (!N) {
1688     sys::SmartScopedWriter<true> Writer(*ConstantsLock);
1689     N = MDNodeSet->FindNodeOrInsertPos(ID, InsertPoint);
1690     if (!N) {
1691       // InsertPoint will have been set by the FindNodeOrInsertPos call.
1692       N = new(0) MDNode(Vals, NumVals);
1693       MDNodeSet->InsertNode(N, InsertPoint);
1694     }
1695   }
1696   return N;
1697 }
1698
1699 void MDNode::destroyConstant() {
1700   sys::SmartScopedWriter<true> Writer(*ConstantsLock); 
1701   MDNodeSet->RemoveNode(this);
1702   
1703   destroyConstantImpl();
1704 }
1705
1706 //---- ConstantExpr::get() implementations...
1707 //
1708
1709 namespace {
1710
1711 struct ExprMapKeyType {
1712   typedef SmallVector<unsigned, 4> IndexList;
1713
1714   ExprMapKeyType(unsigned opc,
1715       const std::vector<Constant*> &ops,
1716       unsigned short pred = 0,
1717       const IndexList &inds = IndexList())
1718         : opcode(opc), predicate(pred), operands(ops), indices(inds) {}
1719   uint16_t opcode;
1720   uint16_t predicate;
1721   std::vector<Constant*> operands;
1722   IndexList indices;
1723   bool operator==(const ExprMapKeyType& that) const {
1724     return this->opcode == that.opcode &&
1725            this->predicate == that.predicate &&
1726            this->operands == that.operands &&
1727            this->indices == that.indices;
1728   }
1729   bool operator<(const ExprMapKeyType & that) const {
1730     return this->opcode < that.opcode ||
1731       (this->opcode == that.opcode && this->predicate < that.predicate) ||
1732       (this->opcode == that.opcode && this->predicate == that.predicate &&
1733        this->operands < that.operands) ||
1734       (this->opcode == that.opcode && this->predicate == that.predicate &&
1735        this->operands == that.operands && this->indices < that.indices);
1736   }
1737
1738   bool operator!=(const ExprMapKeyType& that) const {
1739     return !(*this == that);
1740   }
1741 };
1742
1743 }
1744
1745 namespace llvm {
1746   template<>
1747   struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1748     static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1749         unsigned short pred = 0) {
1750       if (Instruction::isCast(V.opcode))
1751         return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1752       if ((V.opcode >= Instruction::BinaryOpsBegin &&
1753            V.opcode < Instruction::BinaryOpsEnd))
1754         return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1755       if (V.opcode == Instruction::Select)
1756         return new SelectConstantExpr(V.operands[0], V.operands[1], 
1757                                       V.operands[2]);
1758       if (V.opcode == Instruction::ExtractElement)
1759         return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1760       if (V.opcode == Instruction::InsertElement)
1761         return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1762                                              V.operands[2]);
1763       if (V.opcode == Instruction::ShuffleVector)
1764         return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1765                                              V.operands[2]);
1766       if (V.opcode == Instruction::InsertValue)
1767         return new InsertValueConstantExpr(V.operands[0], V.operands[1],
1768                                            V.indices, Ty);
1769       if (V.opcode == Instruction::ExtractValue)
1770         return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
1771       if (V.opcode == Instruction::GetElementPtr) {
1772         std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1773         return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
1774       }
1775
1776       // The compare instructions are weird. We have to encode the predicate
1777       // value and it is combined with the instruction opcode by multiplying
1778       // the opcode by one hundred. We must decode this to get the predicate.
1779       if (V.opcode == Instruction::ICmp)
1780         return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate, 
1781                                        V.operands[0], V.operands[1]);
1782       if (V.opcode == Instruction::FCmp) 
1783         return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate, 
1784                                        V.operands[0], V.operands[1]);
1785       llvm_unreachable("Invalid ConstantExpr!");
1786       return 0;
1787     }
1788   };
1789
1790   template<>
1791   struct ConvertConstantType<ConstantExpr, Type> {
1792     static void convert(ConstantExpr *OldC, const Type *NewTy) {
1793       Constant *New;
1794       switch (OldC->getOpcode()) {
1795       case Instruction::Trunc:
1796       case Instruction::ZExt:
1797       case Instruction::SExt:
1798       case Instruction::FPTrunc:
1799       case Instruction::FPExt:
1800       case Instruction::UIToFP:
1801       case Instruction::SIToFP:
1802       case Instruction::FPToUI:
1803       case Instruction::FPToSI:
1804       case Instruction::PtrToInt:
1805       case Instruction::IntToPtr:
1806       case Instruction::BitCast:
1807         New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0), 
1808                                     NewTy);
1809         break;
1810       case Instruction::Select:
1811         New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1812                                         OldC->getOperand(1),
1813                                         OldC->getOperand(2));
1814         break;
1815       default:
1816         assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1817                OldC->getOpcode() <  Instruction::BinaryOpsEnd);
1818         New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1819                                   OldC->getOperand(1));
1820         break;
1821       case Instruction::GetElementPtr:
1822         // Make everyone now use a constant of the new type...
1823         std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1824         New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1825                                                &Idx[0], Idx.size());
1826         break;
1827       }
1828
1829       assert(New != OldC && "Didn't replace constant??");
1830       OldC->uncheckedReplaceAllUsesWith(New);
1831       OldC->destroyConstant();    // This constant is now dead, destroy it.
1832     }
1833   };
1834 } // end namespace llvm
1835
1836
1837 static ExprMapKeyType getValType(ConstantExpr *CE) {
1838   std::vector<Constant*> Operands;
1839   Operands.reserve(CE->getNumOperands());
1840   for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1841     Operands.push_back(cast<Constant>(CE->getOperand(i)));
1842   return ExprMapKeyType(CE->getOpcode(), Operands, 
1843       CE->isCompare() ? CE->getPredicate() : 0,
1844       CE->hasIndices() ?
1845         CE->getIndices() : SmallVector<unsigned, 4>());
1846 }
1847
1848 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1849                               ConstantExpr> > ExprConstants;
1850
1851 /// This is a utility function to handle folding of casts and lookup of the
1852 /// cast in the ExprConstants map. It is used by the various get* methods below.
1853 static inline Constant *getFoldedCast(
1854   Instruction::CastOps opc, Constant *C, const Type *Ty) {
1855   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1856   // Fold a few common cases
1857   if (Constant *FC = 
1858                     ConstantFoldCastInstruction(getGlobalContext(), opc, C, Ty))
1859     return FC;
1860
1861   // Look up the constant in the table first to ensure uniqueness
1862   std::vector<Constant*> argVec(1, C);
1863   ExprMapKeyType Key(opc, argVec);
1864   
1865   // Implicitly locked.
1866   return ExprConstants->getOrCreate(Ty, Key);
1867 }
1868  
1869 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1870   Instruction::CastOps opc = Instruction::CastOps(oc);
1871   assert(Instruction::isCast(opc) && "opcode out of range");
1872   assert(C && Ty && "Null arguments to getCast");
1873   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1874
1875   switch (opc) {
1876     default:
1877       llvm_unreachable("Invalid cast opcode");
1878       break;
1879     case Instruction::Trunc:    return getTrunc(C, Ty);
1880     case Instruction::ZExt:     return getZExt(C, Ty);
1881     case Instruction::SExt:     return getSExt(C, Ty);
1882     case Instruction::FPTrunc:  return getFPTrunc(C, Ty);
1883     case Instruction::FPExt:    return getFPExtend(C, Ty);
1884     case Instruction::UIToFP:   return getUIToFP(C, Ty);
1885     case Instruction::SIToFP:   return getSIToFP(C, Ty);
1886     case Instruction::FPToUI:   return getFPToUI(C, Ty);
1887     case Instruction::FPToSI:   return getFPToSI(C, Ty);
1888     case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1889     case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1890     case Instruction::BitCast:  return getBitCast(C, Ty);
1891   }
1892   return 0;
1893
1894
1895 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1896   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1897     return getCast(Instruction::BitCast, C, Ty);
1898   return getCast(Instruction::ZExt, C, Ty);
1899 }
1900
1901 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1902   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1903     return getCast(Instruction::BitCast, C, Ty);
1904   return getCast(Instruction::SExt, C, Ty);
1905 }
1906
1907 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1908   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1909     return getCast(Instruction::BitCast, C, Ty);
1910   return getCast(Instruction::Trunc, C, Ty);
1911 }
1912
1913 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1914   assert(isa<PointerType>(S->getType()) && "Invalid cast");
1915   assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1916
1917   if (Ty->isInteger())
1918     return getCast(Instruction::PtrToInt, S, Ty);
1919   return getCast(Instruction::BitCast, S, Ty);
1920 }
1921
1922 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty, 
1923                                        bool isSigned) {
1924   assert(C->getType()->isIntOrIntVector() &&
1925          Ty->isIntOrIntVector() && "Invalid cast");
1926   unsigned SrcBits = C->getType()->getScalarSizeInBits();
1927   unsigned DstBits = Ty->getScalarSizeInBits();
1928   Instruction::CastOps opcode =
1929     (SrcBits == DstBits ? Instruction::BitCast :
1930      (SrcBits > DstBits ? Instruction::Trunc :
1931       (isSigned ? Instruction::SExt : Instruction::ZExt)));
1932   return getCast(opcode, C, Ty);
1933 }
1934
1935 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1936   assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1937          "Invalid cast");
1938   unsigned SrcBits = C->getType()->getScalarSizeInBits();
1939   unsigned DstBits = Ty->getScalarSizeInBits();
1940   if (SrcBits == DstBits)
1941     return C; // Avoid a useless cast
1942   Instruction::CastOps opcode =
1943      (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1944   return getCast(opcode, C, Ty);
1945 }
1946
1947 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1948 #ifndef NDEBUG
1949   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1950   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1951 #endif
1952   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1953   assert(C->getType()->isIntOrIntVector() && "Trunc operand must be integer");
1954   assert(Ty->isIntOrIntVector() && "Trunc produces only integral");
1955   assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1956          "SrcTy must be larger than DestTy for Trunc!");
1957
1958   return getFoldedCast(Instruction::Trunc, C, Ty);
1959 }
1960
1961 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1962 #ifndef NDEBUG
1963   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1964   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1965 #endif
1966   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1967   assert(C->getType()->isIntOrIntVector() && "SExt operand must be integral");
1968   assert(Ty->isIntOrIntVector() && "SExt produces only integer");
1969   assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1970          "SrcTy must be smaller than DestTy for SExt!");
1971
1972   return getFoldedCast(Instruction::SExt, C, Ty);
1973 }
1974
1975 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1976 #ifndef NDEBUG
1977   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1978   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1979 #endif
1980   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1981   assert(C->getType()->isIntOrIntVector() && "ZEXt operand must be integral");
1982   assert(Ty->isIntOrIntVector() && "ZExt produces only integer");
1983   assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1984          "SrcTy must be smaller than DestTy for ZExt!");
1985
1986   return getFoldedCast(Instruction::ZExt, C, Ty);
1987 }
1988
1989 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1990 #ifndef NDEBUG
1991   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1992   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1993 #endif
1994   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1995   assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1996          C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1997          "This is an illegal floating point truncation!");
1998   return getFoldedCast(Instruction::FPTrunc, C, Ty);
1999 }
2000
2001 Constant *ConstantExpr::getFPExtend(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()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2008          C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
2009          "This is an illegal floating point extension!");
2010   return getFoldedCast(Instruction::FPExt, C, Ty);
2011 }
2012
2013 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
2014 #ifndef NDEBUG
2015   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2016   bool toVec = Ty->getTypeID() == Type::VectorTyID;
2017 #endif
2018   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2019   assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
2020          "This is an illegal uint to floating point cast!");
2021   return getFoldedCast(Instruction::UIToFP, C, Ty);
2022 }
2023
2024 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
2025 #ifndef NDEBUG
2026   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2027   bool toVec = Ty->getTypeID() == Type::VectorTyID;
2028 #endif
2029   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2030   assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
2031          "This is an illegal sint to floating point cast!");
2032   return getFoldedCast(Instruction::SIToFP, C, Ty);
2033 }
2034
2035 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
2036 #ifndef NDEBUG
2037   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2038   bool toVec = Ty->getTypeID() == Type::VectorTyID;
2039 #endif
2040   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2041   assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
2042          "This is an illegal floating point to uint cast!");
2043   return getFoldedCast(Instruction::FPToUI, C, Ty);
2044 }
2045
2046 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
2047 #ifndef NDEBUG
2048   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2049   bool toVec = Ty->getTypeID() == Type::VectorTyID;
2050 #endif
2051   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2052   assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
2053          "This is an illegal floating point to sint cast!");
2054   return getFoldedCast(Instruction::FPToSI, C, Ty);
2055 }
2056
2057 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
2058   assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
2059   assert(DstTy->isInteger() && "PtrToInt destination must be integral");
2060   return getFoldedCast(Instruction::PtrToInt, C, DstTy);
2061 }
2062
2063 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
2064   assert(C->getType()->isInteger() && "IntToPtr source must be integral");
2065   assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
2066   return getFoldedCast(Instruction::IntToPtr, C, DstTy);
2067 }
2068
2069 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
2070   // BitCast implies a no-op cast of type only. No bits change.  However, you 
2071   // can't cast pointers to anything but pointers.
2072 #ifndef NDEBUG
2073   const Type *SrcTy = C->getType();
2074   assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
2075          "BitCast cannot cast pointer to non-pointer and vice versa");
2076
2077   // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
2078   // or nonptr->ptr). For all the other types, the cast is okay if source and 
2079   // destination bit widths are identical.
2080   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
2081   unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
2082 #endif
2083   assert(SrcBitSize == DstBitSize && "BitCast requires types of same width");
2084   
2085   // It is common to ask for a bitcast of a value to its own type, handle this
2086   // speedily.
2087   if (C->getType() == DstTy) return C;
2088   
2089   return getFoldedCast(Instruction::BitCast, C, DstTy);
2090 }
2091
2092 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
2093                               Constant *C1, Constant *C2) {
2094   // Check the operands for consistency first
2095   assert(Opcode >= Instruction::BinaryOpsBegin &&
2096          Opcode <  Instruction::BinaryOpsEnd   &&
2097          "Invalid opcode in binary constant expression");
2098   assert(C1->getType() == C2->getType() &&
2099          "Operand types in binary constant expression should match");
2100
2101   if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
2102     if (Constant *FC = ConstantFoldBinaryInstruction(
2103                                             getGlobalContext(), Opcode, C1, C2))
2104       return FC;          // Fold a few common cases...
2105
2106   std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
2107   ExprMapKeyType Key(Opcode, argVec);
2108   
2109   // Implicitly locked.
2110   return ExprConstants->getOrCreate(ReqTy, Key);
2111 }
2112
2113 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
2114                                      Constant *C1, Constant *C2) {
2115   switch (predicate) {
2116     default: llvm_unreachable("Invalid CmpInst predicate");
2117     case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
2118     case CmpInst::FCMP_OGE:   case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
2119     case CmpInst::FCMP_ONE:   case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
2120     case CmpInst::FCMP_UEQ:   case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
2121     case CmpInst::FCMP_ULT:   case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
2122     case CmpInst::FCMP_TRUE:
2123       return getFCmp(predicate, C1, C2);
2124
2125     case CmpInst::ICMP_EQ:  case CmpInst::ICMP_NE:  case CmpInst::ICMP_UGT:
2126     case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
2127     case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
2128     case CmpInst::ICMP_SLE:
2129       return getICmp(predicate, C1, C2);
2130   }
2131 }
2132
2133 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
2134   // API compatibility: Adjust integer opcodes to floating-point opcodes.
2135   if (C1->getType()->isFPOrFPVector()) {
2136     if (Opcode == Instruction::Add) Opcode = Instruction::FAdd;
2137     else if (Opcode == Instruction::Sub) Opcode = Instruction::FSub;
2138     else if (Opcode == Instruction::Mul) Opcode = Instruction::FMul;
2139   }
2140 #ifndef NDEBUG
2141   switch (Opcode) {
2142   case Instruction::Add:
2143   case Instruction::Sub:
2144   case Instruction::Mul:
2145     assert(C1->getType() == C2->getType() && "Op types should be identical!");
2146     assert(C1->getType()->isIntOrIntVector() &&
2147            "Tried to create an integer operation on a non-integer type!");
2148     break;
2149   case Instruction::FAdd:
2150   case Instruction::FSub:
2151   case Instruction::FMul:
2152     assert(C1->getType() == C2->getType() && "Op types should be identical!");
2153     assert(C1->getType()->isFPOrFPVector() &&
2154            "Tried to create a floating-point operation on a "
2155            "non-floating-point type!");
2156     break;
2157   case Instruction::UDiv: 
2158   case Instruction::SDiv: 
2159     assert(C1->getType() == C2->getType() && "Op types should be identical!");
2160     assert(C1->getType()->isIntOrIntVector() &&
2161            "Tried to create an arithmetic operation on a non-arithmetic type!");
2162     break;
2163   case Instruction::FDiv:
2164     assert(C1->getType() == C2->getType() && "Op types should be identical!");
2165     assert(C1->getType()->isFPOrFPVector() &&
2166            "Tried to create an arithmetic operation on a non-arithmetic type!");
2167     break;
2168   case Instruction::URem: 
2169   case Instruction::SRem: 
2170     assert(C1->getType() == C2->getType() && "Op types should be identical!");
2171     assert(C1->getType()->isIntOrIntVector() &&
2172            "Tried to create an arithmetic operation on a non-arithmetic type!");
2173     break;
2174   case Instruction::FRem:
2175     assert(C1->getType() == C2->getType() && "Op types should be identical!");
2176     assert(C1->getType()->isFPOrFPVector() &&
2177            "Tried to create an arithmetic operation on a non-arithmetic type!");
2178     break;
2179   case Instruction::And:
2180   case Instruction::Or:
2181   case Instruction::Xor:
2182     assert(C1->getType() == C2->getType() && "Op types should be identical!");
2183     assert(C1->getType()->isIntOrIntVector() &&
2184            "Tried to create a logical operation on a non-integral type!");
2185     break;
2186   case Instruction::Shl:
2187   case Instruction::LShr:
2188   case Instruction::AShr:
2189     assert(C1->getType() == C2->getType() && "Op types should be identical!");
2190     assert(C1->getType()->isIntOrIntVector() &&
2191            "Tried to create a shift operation on a non-integer type!");
2192     break;
2193   default:
2194     break;
2195   }
2196 #endif
2197
2198   return getTy(C1->getType(), Opcode, C1, C2);
2199 }
2200
2201 Constant *ConstantExpr::getCompare(unsigned short pred, 
2202                             Constant *C1, Constant *C2) {
2203   assert(C1->getType() == C2->getType() && "Op types should be identical!");
2204   return getCompareTy(pred, C1, C2);
2205 }
2206
2207 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
2208                                     Constant *V1, Constant *V2) {
2209   assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
2210
2211   if (ReqTy == V1->getType())
2212     if (Constant *SC = ConstantFoldSelectInstruction(
2213                                                 getGlobalContext(), C, V1, V2))
2214       return SC;        // Fold common cases
2215
2216   std::vector<Constant*> argVec(3, C);
2217   argVec[1] = V1;
2218   argVec[2] = V2;
2219   ExprMapKeyType Key(Instruction::Select, argVec);
2220   
2221   // Implicitly locked.
2222   return ExprConstants->getOrCreate(ReqTy, Key);
2223 }
2224
2225 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
2226                                            Value* const *Idxs,
2227                                            unsigned NumIdx) {
2228   assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
2229                                            Idxs+NumIdx) ==
2230          cast<PointerType>(ReqTy)->getElementType() &&
2231          "GEP indices invalid!");
2232
2233   if (Constant *FC = ConstantFoldGetElementPtr(
2234                                getGlobalContext(), C, (Constant**)Idxs, NumIdx))
2235     return FC;          // Fold a few common cases...
2236
2237   assert(isa<PointerType>(C->getType()) &&
2238          "Non-pointer type for constant GetElementPtr expression");
2239   // Look up the constant in the table first to ensure uniqueness
2240   std::vector<Constant*> ArgVec;
2241   ArgVec.reserve(NumIdx+1);
2242   ArgVec.push_back(C);
2243   for (unsigned i = 0; i != NumIdx; ++i)
2244     ArgVec.push_back(cast<Constant>(Idxs[i]));
2245   const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
2246
2247   // Implicitly locked.
2248   return ExprConstants->getOrCreate(ReqTy, Key);
2249 }
2250
2251 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
2252                                          unsigned NumIdx) {
2253   // Get the result type of the getelementptr!
2254   const Type *Ty = 
2255     GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
2256   assert(Ty && "GEP indices invalid!");
2257   unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
2258   return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
2259 }
2260
2261 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
2262                                          unsigned NumIdx) {
2263   return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
2264 }
2265
2266
2267 Constant *
2268 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2269   assert(LHS->getType() == RHS->getType());
2270   assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE && 
2271          pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
2272
2273   if (Constant *FC = ConstantFoldCompareInstruction(
2274                                              getGlobalContext(),pred, LHS, RHS))
2275     return FC;          // Fold a few common cases...
2276
2277   // Look up the constant in the table first to ensure uniqueness
2278   std::vector<Constant*> ArgVec;
2279   ArgVec.push_back(LHS);
2280   ArgVec.push_back(RHS);
2281   // Get the key type with both the opcode and predicate
2282   const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
2283
2284   // Implicitly locked.
2285   return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2286 }
2287
2288 Constant *
2289 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2290   assert(LHS->getType() == RHS->getType());
2291   assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
2292
2293   if (Constant *FC = ConstantFoldCompareInstruction(
2294                                             getGlobalContext(), pred, LHS, RHS))
2295     return FC;          // Fold a few common cases...
2296
2297   // Look up the constant in the table first to ensure uniqueness
2298   std::vector<Constant*> ArgVec;
2299   ArgVec.push_back(LHS);
2300   ArgVec.push_back(RHS);
2301   // Get the key type with both the opcode and predicate
2302   const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
2303   
2304   // Implicitly locked.
2305   return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2306 }
2307
2308 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
2309                                             Constant *Idx) {
2310   if (Constant *FC = ConstantFoldExtractElementInstruction(
2311                                                   getGlobalContext(), Val, Idx))
2312     return FC;          // Fold a few common cases...
2313   // Look up the constant in the table first to ensure uniqueness
2314   std::vector<Constant*> ArgVec(1, Val);
2315   ArgVec.push_back(Idx);
2316   const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
2317   
2318   // Implicitly locked.
2319   return ExprConstants->getOrCreate(ReqTy, Key);
2320 }
2321
2322 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
2323   assert(isa<VectorType>(Val->getType()) &&
2324          "Tried to create extractelement operation on non-vector type!");
2325   assert(Idx->getType() == Type::Int32Ty &&
2326          "Extractelement index must be i32 type!");
2327   return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
2328                              Val, Idx);
2329 }
2330
2331 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
2332                                            Constant *Elt, Constant *Idx) {
2333   if (Constant *FC = ConstantFoldInsertElementInstruction(
2334                                             getGlobalContext(), Val, Elt, Idx))
2335     return FC;          // Fold a few common cases...
2336   // Look up the constant in the table first to ensure uniqueness
2337   std::vector<Constant*> ArgVec(1, Val);
2338   ArgVec.push_back(Elt);
2339   ArgVec.push_back(Idx);
2340   const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
2341   
2342   // Implicitly locked.
2343   return ExprConstants->getOrCreate(ReqTy, Key);
2344 }
2345
2346 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt, 
2347                                          Constant *Idx) {
2348   assert(isa<VectorType>(Val->getType()) &&
2349          "Tried to create insertelement operation on non-vector type!");
2350   assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
2351          && "Insertelement types must match!");
2352   assert(Idx->getType() == Type::Int32Ty &&
2353          "Insertelement index must be i32 type!");
2354   return getInsertElementTy(Val->getType(), Val, Elt, Idx);
2355 }
2356
2357 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
2358                                            Constant *V2, Constant *Mask) {
2359   if (Constant *FC = ConstantFoldShuffleVectorInstruction(
2360                                               getGlobalContext(), V1, V2, Mask))
2361     return FC;          // Fold a few common cases...
2362   // Look up the constant in the table first to ensure uniqueness
2363   std::vector<Constant*> ArgVec(1, V1);
2364   ArgVec.push_back(V2);
2365   ArgVec.push_back(Mask);
2366   const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
2367   
2368   // Implicitly locked.
2369   return ExprConstants->getOrCreate(ReqTy, Key);
2370 }
2371
2372 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2, 
2373                                          Constant *Mask) {
2374   assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2375          "Invalid shuffle vector constant expr operands!");
2376
2377   unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
2378   const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
2379   const Type *ShufTy = VectorType::get(EltTy, NElts);
2380   return getShuffleVectorTy(ShufTy, V1, V2, Mask);
2381 }
2382
2383 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
2384                                          Constant *Val,
2385                                         const unsigned *Idxs, unsigned NumIdx) {
2386   assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2387                                           Idxs+NumIdx) == Val->getType() &&
2388          "insertvalue indices invalid!");
2389   assert(Agg->getType() == ReqTy &&
2390          "insertvalue type invalid!");
2391   assert(Agg->getType()->isFirstClassType() &&
2392          "Non-first-class type for constant InsertValue expression");
2393   Constant *FC = ConstantFoldInsertValueInstruction(
2394                                     getGlobalContext(), Agg, Val, Idxs, NumIdx);
2395   assert(FC && "InsertValue constant expr couldn't be folded!");
2396   return FC;
2397 }
2398
2399 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
2400                                      const unsigned *IdxList, unsigned NumIdx) {
2401   assert(Agg->getType()->isFirstClassType() &&
2402          "Tried to create insertelement operation on non-first-class type!");
2403
2404   const Type *ReqTy = Agg->getType();
2405 #ifndef NDEBUG
2406   const Type *ValTy =
2407     ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2408 #endif
2409   assert(ValTy == Val->getType() && "insertvalue indices invalid!");
2410   return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
2411 }
2412
2413 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
2414                                         const unsigned *Idxs, unsigned NumIdx) {
2415   assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2416                                           Idxs+NumIdx) == ReqTy &&
2417          "extractvalue indices invalid!");
2418   assert(Agg->getType()->isFirstClassType() &&
2419          "Non-first-class type for constant extractvalue expression");
2420   Constant *FC = ConstantFoldExtractValueInstruction(
2421                                          getGlobalContext(), Agg, Idxs, NumIdx);
2422   assert(FC && "ExtractValue constant expr couldn't be folded!");
2423   return FC;
2424 }
2425
2426 Constant *ConstantExpr::getExtractValue(Constant *Agg,
2427                                      const unsigned *IdxList, unsigned NumIdx) {
2428   assert(Agg->getType()->isFirstClassType() &&
2429          "Tried to create extractelement operation on non-first-class type!");
2430
2431   const Type *ReqTy =
2432     ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2433   assert(ReqTy && "extractvalue indices invalid!");
2434   return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
2435 }
2436
2437 // destroyConstant - Remove the constant from the constant table...
2438 //
2439 void ConstantExpr::destroyConstant() {
2440   // Implicitly locked.
2441   ExprConstants->remove(this);
2442   destroyConstantImpl();
2443 }
2444
2445 const char *ConstantExpr::getOpcodeName() const {
2446   return Instruction::getOpcodeName(getOpcode());
2447 }
2448
2449 //===----------------------------------------------------------------------===//
2450 //                replaceUsesOfWithOnConstant implementations
2451
2452 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2453 /// 'From' to be uses of 'To'.  This must update the uniquing data structures
2454 /// etc.
2455 ///
2456 /// Note that we intentionally replace all uses of From with To here.  Consider
2457 /// a large array that uses 'From' 1000 times.  By handling this case all here,
2458 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2459 /// single invocation handles all 1000 uses.  Handling them one at a time would
2460 /// work, but would be really slow because it would have to unique each updated
2461 /// array instance.
2462 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
2463                                                 Use *U) {
2464   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2465   Constant *ToC = cast<Constant>(To);
2466
2467   std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
2468   Lookup.first.first = getType();
2469   Lookup.second = this;
2470
2471   std::vector<Constant*> &Values = Lookup.first.second;
2472   Values.reserve(getNumOperands());  // Build replacement array.
2473
2474   // Fill values with the modified operands of the constant array.  Also, 
2475   // compute whether this turns into an all-zeros array.
2476   bool isAllZeros = false;
2477   unsigned NumUpdated = 0;
2478   if (!ToC->isNullValue()) {
2479     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2480       Constant *Val = cast<Constant>(O->get());
2481       if (Val == From) {
2482         Val = ToC;
2483         ++NumUpdated;
2484       }
2485       Values.push_back(Val);
2486     }
2487   } else {
2488     isAllZeros = true;
2489     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2490       Constant *Val = cast<Constant>(O->get());
2491       if (Val == From) {
2492         Val = ToC;
2493         ++NumUpdated;
2494       }
2495       Values.push_back(Val);
2496       if (isAllZeros) isAllZeros = Val->isNullValue();
2497     }
2498   }
2499   
2500   Constant *Replacement = 0;
2501   if (isAllZeros) {
2502     Replacement = ConstantAggregateZero::get(getType());
2503   } else {
2504     // Check to see if we have this array type already.
2505     sys::SmartScopedWriter<true> Writer(*ConstantsLock);
2506     bool Exists;
2507     ArrayConstantsTy::MapTy::iterator I =
2508       ArrayConstants->InsertOrGetItem(Lookup, Exists);
2509     
2510     if (Exists) {
2511       Replacement = I->second;
2512     } else {
2513       // Okay, the new shape doesn't exist in the system yet.  Instead of
2514       // creating a new constant array, inserting it, replaceallusesof'ing the
2515       // old with the new, then deleting the old... just update the current one
2516       // in place!
2517       ArrayConstants->MoveConstantToNewSlot(this, I);
2518       
2519       // Update to the new value.  Optimize for the case when we have a single
2520       // operand that we're changing, but handle bulk updates efficiently.
2521       if (NumUpdated == 1) {
2522         unsigned OperandToUpdate = U-OperandList;
2523         assert(getOperand(OperandToUpdate) == From &&
2524                "ReplaceAllUsesWith broken!");
2525         setOperand(OperandToUpdate, ToC);
2526       } else {
2527         for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2528           if (getOperand(i) == From)
2529             setOperand(i, ToC);
2530       }
2531       return;
2532     }
2533   }
2534  
2535   // Otherwise, I do need to replace this with an existing value.
2536   assert(Replacement != this && "I didn't contain From!");
2537   
2538   // Everyone using this now uses the replacement.
2539   uncheckedReplaceAllUsesWith(Replacement);
2540   
2541   // Delete the old constant!
2542   destroyConstant();
2543 }
2544
2545 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2546                                                  Use *U) {
2547   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2548   Constant *ToC = cast<Constant>(To);
2549
2550   unsigned OperandToUpdate = U-OperandList;
2551   assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2552
2553   std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
2554   Lookup.first.first = getType();
2555   Lookup.second = this;
2556   std::vector<Constant*> &Values = Lookup.first.second;
2557   Values.reserve(getNumOperands());  // Build replacement struct.
2558   
2559   
2560   // Fill values with the modified operands of the constant struct.  Also, 
2561   // compute whether this turns into an all-zeros struct.
2562   bool isAllZeros = false;
2563   if (!ToC->isNullValue()) {
2564     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2565       Values.push_back(cast<Constant>(O->get()));
2566   } else {
2567     isAllZeros = true;
2568     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2569       Constant *Val = cast<Constant>(O->get());
2570       Values.push_back(Val);
2571       if (isAllZeros) isAllZeros = Val->isNullValue();
2572     }
2573   }
2574   Values[OperandToUpdate] = ToC;
2575   
2576   Constant *Replacement = 0;
2577   if (isAllZeros) {
2578     Replacement = ConstantAggregateZero::get(getType());
2579   } else {
2580     // Check to see if we have this array type already.
2581     sys::SmartScopedWriter<true> Writer(*ConstantsLock);
2582     bool Exists;
2583     StructConstantsTy::MapTy::iterator I =
2584       StructConstants->InsertOrGetItem(Lookup, Exists);
2585     
2586     if (Exists) {
2587       Replacement = I->second;
2588     } else {
2589       // Okay, the new shape doesn't exist in the system yet.  Instead of
2590       // creating a new constant struct, inserting it, replaceallusesof'ing the
2591       // old with the new, then deleting the old... just update the current one
2592       // in place!
2593       StructConstants->MoveConstantToNewSlot(this, I);
2594       
2595       // Update to the new value.
2596       setOperand(OperandToUpdate, ToC);
2597       return;
2598     }
2599   }
2600   
2601   assert(Replacement != this && "I didn't contain From!");
2602   
2603   // Everyone using this now uses the replacement.
2604   uncheckedReplaceAllUsesWith(Replacement);
2605   
2606   // Delete the old constant!
2607   destroyConstant();
2608 }
2609
2610 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2611                                                  Use *U) {
2612   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2613   
2614   std::vector<Constant*> Values;
2615   Values.reserve(getNumOperands());  // Build replacement array...
2616   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2617     Constant *Val = getOperand(i);
2618     if (Val == From) Val = cast<Constant>(To);
2619     Values.push_back(Val);
2620   }
2621   
2622   Constant *Replacement = ConstantVector::get(getType(), Values);
2623   assert(Replacement != this && "I didn't contain From!");
2624   
2625   // Everyone using this now uses the replacement.
2626   uncheckedReplaceAllUsesWith(Replacement);
2627   
2628   // Delete the old constant!
2629   destroyConstant();
2630 }
2631
2632 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2633                                                Use *U) {
2634   assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2635   Constant *To = cast<Constant>(ToV);
2636   
2637   Constant *Replacement = 0;
2638   if (getOpcode() == Instruction::GetElementPtr) {
2639     SmallVector<Constant*, 8> Indices;
2640     Constant *Pointer = getOperand(0);
2641     Indices.reserve(getNumOperands()-1);
2642     if (Pointer == From) Pointer = To;
2643     
2644     for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2645       Constant *Val = getOperand(i);
2646       if (Val == From) Val = To;
2647       Indices.push_back(Val);
2648     }
2649     Replacement = ConstantExpr::getGetElementPtr(Pointer,
2650                                                  &Indices[0], Indices.size());
2651   } else if (getOpcode() == Instruction::ExtractValue) {
2652     Constant *Agg = getOperand(0);
2653     if (Agg == From) Agg = To;
2654     
2655     const SmallVector<unsigned, 4> &Indices = getIndices();
2656     Replacement = ConstantExpr::getExtractValue(Agg,
2657                                                 &Indices[0], Indices.size());
2658   } else if (getOpcode() == Instruction::InsertValue) {
2659     Constant *Agg = getOperand(0);
2660     Constant *Val = getOperand(1);
2661     if (Agg == From) Agg = To;
2662     if (Val == From) Val = To;
2663     
2664     const SmallVector<unsigned, 4> &Indices = getIndices();
2665     Replacement = ConstantExpr::getInsertValue(Agg, Val,
2666                                                &Indices[0], Indices.size());
2667   } else if (isCast()) {
2668     assert(getOperand(0) == From && "Cast only has one use!");
2669     Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2670   } else if (getOpcode() == Instruction::Select) {
2671     Constant *C1 = getOperand(0);
2672     Constant *C2 = getOperand(1);
2673     Constant *C3 = getOperand(2);
2674     if (C1 == From) C1 = To;
2675     if (C2 == From) C2 = To;
2676     if (C3 == From) C3 = To;
2677     Replacement = ConstantExpr::getSelect(C1, C2, C3);
2678   } else if (getOpcode() == Instruction::ExtractElement) {
2679     Constant *C1 = getOperand(0);
2680     Constant *C2 = getOperand(1);
2681     if (C1 == From) C1 = To;
2682     if (C2 == From) C2 = To;
2683     Replacement = ConstantExpr::getExtractElement(C1, C2);
2684   } else if (getOpcode() == Instruction::InsertElement) {
2685     Constant *C1 = getOperand(0);
2686     Constant *C2 = getOperand(1);
2687     Constant *C3 = getOperand(1);
2688     if (C1 == From) C1 = To;
2689     if (C2 == From) C2 = To;
2690     if (C3 == From) C3 = To;
2691     Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2692   } else if (getOpcode() == Instruction::ShuffleVector) {
2693     Constant *C1 = getOperand(0);
2694     Constant *C2 = getOperand(1);
2695     Constant *C3 = getOperand(2);
2696     if (C1 == From) C1 = To;
2697     if (C2 == From) C2 = To;
2698     if (C3 == From) C3 = To;
2699     Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2700   } else if (isCompare()) {
2701     Constant *C1 = getOperand(0);
2702     Constant *C2 = getOperand(1);
2703     if (C1 == From) C1 = To;
2704     if (C2 == From) C2 = To;
2705     if (getOpcode() == Instruction::ICmp)
2706       Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2707     else {
2708       assert(getOpcode() == Instruction::FCmp);
2709       Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2710     }
2711   } else if (getNumOperands() == 2) {
2712     Constant *C1 = getOperand(0);
2713     Constant *C2 = getOperand(1);
2714     if (C1 == From) C1 = To;
2715     if (C2 == From) C2 = To;
2716     Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2717   } else {
2718     llvm_unreachable("Unknown ConstantExpr type!");
2719     return;
2720   }
2721   
2722   assert(Replacement != this && "I didn't contain From!");
2723   
2724   // Everyone using this now uses the replacement.
2725   uncheckedReplaceAllUsesWith(Replacement);
2726   
2727   // Delete the old constant!
2728   destroyConstant();
2729 }
2730
2731 void MDNode::replaceElement(Value *From, Value *To) {
2732   SmallVector<Value*, 4> Values;
2733   Values.reserve(getNumElements());  // Build replacement array...
2734   for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
2735     Value *Val = getElement(i);
2736     if (Val == From) Val = To;
2737     Values.push_back(Val);
2738   }
2739
2740   MDNode *Replacement = MDNode::get(&Values[0], Values.size());
2741   assert(Replacement != this && "I didn't contain From!");
2742
2743   uncheckedReplaceAllUsesWith(Replacement);
2744
2745   destroyConstant();
2746 }