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