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