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