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