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