move some methods, no other changes
[oota-llvm.git] / lib / VMCore / Constants.cpp
1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 "ConstantFolding.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/GlobalValue.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/SymbolTable.h"
20 #include "llvm/Module.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/Support/MathExtras.h"
23 #include <algorithm>
24 #include <iostream>
25 using namespace llvm;
26
27 ConstantBool *ConstantBool::True  = new ConstantBool(true);
28 ConstantBool *ConstantBool::False = new ConstantBool(false);
29
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       std::cerr << "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 // Static constructor to create a '0' constant of arbitrary type...
64 Constant *Constant::getNullValue(const Type *Ty) {
65   switch (Ty->getTypeID()) {
66   case Type::BoolTyID: {
67     static Constant *NullBool = ConstantBool::get(false);
68     return NullBool;
69   }
70   case Type::SByteTyID: {
71     static Constant *NullSByte = ConstantSInt::get(Type::SByteTy, 0);
72     return NullSByte;
73   }
74   case Type::UByteTyID: {
75     static Constant *NullUByte = ConstantUInt::get(Type::UByteTy, 0);
76     return NullUByte;
77   }
78   case Type::ShortTyID: {
79     static Constant *NullShort = ConstantSInt::get(Type::ShortTy, 0);
80     return NullShort;
81   }
82   case Type::UShortTyID: {
83     static Constant *NullUShort = ConstantUInt::get(Type::UShortTy, 0);
84     return NullUShort;
85   }
86   case Type::IntTyID: {
87     static Constant *NullInt = ConstantSInt::get(Type::IntTy, 0);
88     return NullInt;
89   }
90   case Type::UIntTyID: {
91     static Constant *NullUInt = ConstantUInt::get(Type::UIntTy, 0);
92     return NullUInt;
93   }
94   case Type::LongTyID: {
95     static Constant *NullLong = ConstantSInt::get(Type::LongTy, 0);
96     return NullLong;
97   }
98   case Type::ULongTyID: {
99     static Constant *NullULong = ConstantUInt::get(Type::ULongTy, 0);
100     return NullULong;
101   }
102
103   case Type::FloatTyID: {
104     static Constant *NullFloat = ConstantFP::get(Type::FloatTy, 0);
105     return NullFloat;
106   }
107   case Type::DoubleTyID: {
108     static Constant *NullDouble = ConstantFP::get(Type::DoubleTy, 0);
109     return NullDouble;
110   }
111
112   case Type::PointerTyID:
113     return ConstantPointerNull::get(cast<PointerType>(Ty));
114
115   case Type::StructTyID:
116   case Type::ArrayTyID:
117   case Type::PackedTyID:
118     return ConstantAggregateZero::get(Ty);
119   default:
120     // Function, Label, or Opaque type?
121     assert(!"Cannot create a null constant of that type!");
122     return 0;
123   }
124 }
125
126 // Static constructor to create the maximum constant of an integral type...
127 ConstantIntegral *ConstantIntegral::getMaxValue(const Type *Ty) {
128   switch (Ty->getTypeID()) {
129   case Type::BoolTyID:   return ConstantBool::True;
130   case Type::SByteTyID:
131   case Type::ShortTyID:
132   case Type::IntTyID:
133   case Type::LongTyID: {
134     // Calculate 011111111111111...
135     unsigned TypeBits = Ty->getPrimitiveSize()*8;
136     int64_t Val = INT64_MAX;             // All ones
137     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
138     return ConstantSInt::get(Ty, Val);
139   }
140
141   case Type::UByteTyID:
142   case Type::UShortTyID:
143   case Type::UIntTyID:
144   case Type::ULongTyID:  return getAllOnesValue(Ty);
145
146   default: return 0;
147   }
148 }
149
150 // Static constructor to create the minimum constant for an integral type...
151 ConstantIntegral *ConstantIntegral::getMinValue(const Type *Ty) {
152   switch (Ty->getTypeID()) {
153   case Type::BoolTyID:   return ConstantBool::False;
154   case Type::SByteTyID:
155   case Type::ShortTyID:
156   case Type::IntTyID:
157   case Type::LongTyID: {
158      // Calculate 1111111111000000000000
159      unsigned TypeBits = Ty->getPrimitiveSize()*8;
160      int64_t Val = -1;                    // All ones
161      Val <<= TypeBits-1;                  // Shift over to the right spot
162      return ConstantSInt::get(Ty, Val);
163   }
164
165   case Type::UByteTyID:
166   case Type::UShortTyID:
167   case Type::UIntTyID:
168   case Type::ULongTyID:  return ConstantUInt::get(Ty, 0);
169
170   default: return 0;
171   }
172 }
173
174 // Static constructor to create an integral constant with all bits set
175 ConstantIntegral *ConstantIntegral::getAllOnesValue(const Type *Ty) {
176   switch (Ty->getTypeID()) {
177   case Type::BoolTyID:   return ConstantBool::True;
178   case Type::SByteTyID:
179   case Type::ShortTyID:
180   case Type::IntTyID:
181   case Type::LongTyID:   return ConstantSInt::get(Ty, -1);
182
183   case Type::UByteTyID:
184   case Type::UShortTyID:
185   case Type::UIntTyID:
186   case Type::ULongTyID: {
187     // Calculate ~0 of the right type...
188     unsigned TypeBits = Ty->getPrimitiveSize()*8;
189     uint64_t Val = ~0ULL;                // All ones
190     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
191     return ConstantUInt::get(Ty, Val);
192   }
193   default: return 0;
194   }
195 }
196
197 bool ConstantUInt::isAllOnesValue() const {
198   unsigned TypeBits = getType()->getPrimitiveSize()*8;
199   uint64_t Val = ~0ULL;                // All ones
200   Val >>= 64-TypeBits;                 // Shift out inappropriate bits
201   return getValue() == Val;
202 }
203
204
205 //===----------------------------------------------------------------------===//
206 //                            ConstantXXX Classes
207 //===----------------------------------------------------------------------===//
208
209 //===----------------------------------------------------------------------===//
210 //                             Normal Constructors
211
212 ConstantIntegral::ConstantIntegral(const Type *Ty, ValueTy VT, uint64_t V)
213   : Constant(Ty, VT, 0, 0) {
214     Val.Unsigned = V;
215 }
216
217 ConstantBool::ConstantBool(bool V) 
218   : ConstantIntegral(Type::BoolTy, ConstantBoolVal, V) {
219 }
220
221 ConstantInt::ConstantInt(const Type *Ty, ValueTy VT, uint64_t V)
222   : ConstantIntegral(Ty, VT, V) {
223 }
224
225 ConstantSInt::ConstantSInt(const Type *Ty, int64_t V)
226   : ConstantInt(Ty, ConstantSIntVal, V) {
227   assert(Ty->isInteger() && Ty->isSigned() &&
228          "Illegal type for signed integer constant!");
229   assert(isValueValidForType(Ty, V) && "Value too large for type!");
230 }
231
232 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V)
233   : ConstantInt(Ty, ConstantUIntVal, V) {
234   assert(Ty->isInteger() && Ty->isUnsigned() &&
235          "Illegal type for unsigned integer constant!");
236   assert(isValueValidForType(Ty, V) && "Value too large for type!");
237 }
238
239 ConstantFP::ConstantFP(const Type *Ty, double V)
240   : Constant(Ty, ConstantFPVal, 0, 0) {
241   assert(isValueValidForType(Ty, V) && "Value too large for type!");
242   Val = V;
243 }
244
245 ConstantArray::ConstantArray(const ArrayType *T,
246                              const std::vector<Constant*> &V)
247   : Constant(T, ConstantArrayVal, new Use[V.size()], V.size()) {
248   assert(V.size() == T->getNumElements() &&
249          "Invalid initializer vector for constant array");
250   Use *OL = OperandList;
251   for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
252        I != E; ++I, ++OL) {
253     Constant *E = *I;
254     assert((E->getType() == T->getElementType() ||
255             (T->isAbstract() &&
256              E->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
257            "Initializer for array element doesn't match array element type!");
258     OL->init(E, this);
259   }
260 }
261
262 ConstantArray::~ConstantArray() {
263   delete [] OperandList;
264 }
265
266 ConstantStruct::ConstantStruct(const StructType *T,
267                                const std::vector<Constant*> &V)
268   : Constant(T, ConstantStructVal, new Use[V.size()], V.size()) {
269   assert(V.size() == T->getNumElements() &&
270          "Invalid initializer vector for constant structure");
271   Use *OL = OperandList;
272   for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
273        I != E; ++I, ++OL) {
274     Constant *E = *I;
275     assert((E->getType() == T->getElementType(I-V.begin()) ||
276             ((T->getElementType(I-V.begin())->isAbstract() ||
277               E->getType()->isAbstract()) &&
278              T->getElementType(I-V.begin())->getTypeID() == 
279                    E->getType()->getTypeID())) &&
280            "Initializer for struct element doesn't match struct element type!");
281     OL->init(E, this);
282   }
283 }
284
285 ConstantStruct::~ConstantStruct() {
286   delete [] OperandList;
287 }
288
289
290 ConstantPacked::ConstantPacked(const PackedType *T,
291                                const std::vector<Constant*> &V)
292   : Constant(T, ConstantPackedVal, new Use[V.size()], V.size()) {
293   Use *OL = OperandList;
294     for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
295          I != E; ++I, ++OL) {
296       Constant *E = *I;
297       assert((E->getType() == T->getElementType() ||
298             (T->isAbstract() &&
299              E->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
300            "Initializer for packed element doesn't match packed element type!");
301     OL->init(E, this);
302   }
303 }
304
305 ConstantPacked::~ConstantPacked() {
306   delete [] OperandList;
307 }
308
309 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
310 /// behind the scenes to implement unary constant exprs.
311 class UnaryConstantExpr : public ConstantExpr {
312   Use Op;
313 public:
314   UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
315     : ConstantExpr(Ty, Opcode, &Op, 1), Op(C, this) {}
316 };
317
318 static bool isSetCC(unsigned Opcode) {
319   return Opcode == Instruction::SetEQ || Opcode == Instruction::SetNE ||
320          Opcode == Instruction::SetLT || Opcode == Instruction::SetGT ||
321          Opcode == Instruction::SetLE || Opcode == Instruction::SetGE;
322 }
323
324 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
325 /// behind the scenes to implement binary constant exprs.
326 class BinaryConstantExpr : public ConstantExpr {
327   Use Ops[2];
328 public:
329   BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
330     : ConstantExpr(isSetCC(Opcode) ? Type::BoolTy : C1->getType(),
331                    Opcode, Ops, 2) {
332     Ops[0].init(C1, this);
333     Ops[1].init(C2, this);
334   }
335 };
336
337 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
338 /// behind the scenes to implement select constant exprs.
339 class SelectConstantExpr : public ConstantExpr {
340   Use Ops[3];
341 public:
342   SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
343     : ConstantExpr(C2->getType(), Instruction::Select, Ops, 3) {
344     Ops[0].init(C1, this);
345     Ops[1].init(C2, this);
346     Ops[2].init(C3, this);
347   }
348 };
349
350 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
351 /// used behind the scenes to implement getelementpr constant exprs.
352 struct GetElementPtrConstantExpr : public ConstantExpr {
353   GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
354                             const Type *DestTy)
355     : ConstantExpr(DestTy, Instruction::GetElementPtr,
356                    new Use[IdxList.size()+1], IdxList.size()+1) {
357     OperandList[0].init(C, this);
358     for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
359       OperandList[i+1].init(IdxList[i], this);
360   }
361   ~GetElementPtrConstantExpr() {
362     delete [] OperandList;
363   }
364 };
365
366 /// ConstantExpr::get* - Return some common constants without having to
367 /// specify the full Instruction::OPCODE identifier.
368 ///
369 Constant *ConstantExpr::getNeg(Constant *C) {
370   if (!C->getType()->isFloatingPoint())
371     return get(Instruction::Sub, getNullValue(C->getType()), C);
372   else
373     return get(Instruction::Sub, ConstantFP::get(C->getType(), -0.0), C);
374 }
375 Constant *ConstantExpr::getNot(Constant *C) {
376   assert(isa<ConstantIntegral>(C) && "Cannot NOT a nonintegral type!");
377   return get(Instruction::Xor, C,
378              ConstantIntegral::getAllOnesValue(C->getType()));
379 }
380 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
381   return get(Instruction::Add, C1, C2);
382 }
383 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
384   return get(Instruction::Sub, C1, C2);
385 }
386 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
387   return get(Instruction::Mul, C1, C2);
388 }
389 Constant *ConstantExpr::getDiv(Constant *C1, Constant *C2) {
390   return get(Instruction::Div, C1, C2);
391 }
392 Constant *ConstantExpr::getRem(Constant *C1, Constant *C2) {
393   return get(Instruction::Rem, C1, C2);
394 }
395 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
396   return get(Instruction::And, C1, C2);
397 }
398 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
399   return get(Instruction::Or, C1, C2);
400 }
401 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
402   return get(Instruction::Xor, C1, C2);
403 }
404 Constant *ConstantExpr::getSetEQ(Constant *C1, Constant *C2) {
405   return get(Instruction::SetEQ, C1, C2);
406 }
407 Constant *ConstantExpr::getSetNE(Constant *C1, Constant *C2) {
408   return get(Instruction::SetNE, C1, C2);
409 }
410 Constant *ConstantExpr::getSetLT(Constant *C1, Constant *C2) {
411   return get(Instruction::SetLT, C1, C2);
412 }
413 Constant *ConstantExpr::getSetGT(Constant *C1, Constant *C2) {
414   return get(Instruction::SetGT, C1, C2);
415 }
416 Constant *ConstantExpr::getSetLE(Constant *C1, Constant *C2) {
417   return get(Instruction::SetLE, C1, C2);
418 }
419 Constant *ConstantExpr::getSetGE(Constant *C1, Constant *C2) {
420   return get(Instruction::SetGE, C1, C2);
421 }
422 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
423   return get(Instruction::Shl, C1, C2);
424 }
425 Constant *ConstantExpr::getShr(Constant *C1, Constant *C2) {
426   return get(Instruction::Shr, C1, C2);
427 }
428
429 Constant *ConstantExpr::getUShr(Constant *C1, Constant *C2) {
430   if (C1->getType()->isUnsigned()) return getShr(C1, C2);
431   return getCast(getShr(getCast(C1,
432                     C1->getType()->getUnsignedVersion()), C2), C1->getType());
433 }
434
435 Constant *ConstantExpr::getSShr(Constant *C1, Constant *C2) {
436   if (C1->getType()->isSigned()) return getShr(C1, C2);
437   return getCast(getShr(getCast(C1,
438                         C1->getType()->getSignedVersion()), C2), C1->getType());
439 }
440
441
442 //===----------------------------------------------------------------------===//
443 //                      isValueValidForType implementations
444
445 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
446   switch (Ty->getTypeID()) {
447   default:
448     return false;         // These can't be represented as integers!!!
449     // Signed types...
450   case Type::SByteTyID:
451     return (Val <= INT8_MAX && Val >= INT8_MIN);
452   case Type::ShortTyID:
453     return (Val <= INT16_MAX && Val >= INT16_MIN);
454   case Type::IntTyID:
455     return (Val <= int(INT32_MAX) && Val >= int(INT32_MIN));
456   case Type::LongTyID:
457     return true;          // This is the largest type...
458   }
459 }
460
461 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
462   switch (Ty->getTypeID()) {
463   default:
464     return false;         // These can't be represented as integers!!!
465
466     // Unsigned types...
467   case Type::UByteTyID:
468     return (Val <= UINT8_MAX);
469   case Type::UShortTyID:
470     return (Val <= UINT16_MAX);
471   case Type::UIntTyID:
472     return (Val <= UINT32_MAX);
473   case Type::ULongTyID:
474     return true;          // This is the largest type...
475   }
476 }
477
478 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
479   switch (Ty->getTypeID()) {
480   default:
481     return false;         // These can't be represented as floating point!
482
483     // TODO: Figure out how to test if a double can be cast to a float!
484   case Type::FloatTyID:
485   case Type::DoubleTyID:
486     return true;          // This is the largest type...
487   }
488 };
489
490 //===----------------------------------------------------------------------===//
491 //                      Factory Function Implementation
492
493 // ConstantCreator - A class that is used to create constants by
494 // ValueMap*.  This class should be partially specialized if there is
495 // something strange that needs to be done to interface to the ctor for the
496 // constant.
497 //
498 namespace llvm {
499   template<class ConstantClass, class TypeClass, class ValType>
500   struct ConstantCreator {
501     static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
502       return new ConstantClass(Ty, V);
503     }
504   };
505
506   template<class ConstantClass, class TypeClass>
507   struct ConvertConstantType {
508     static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
509       assert(0 && "This type cannot be converted!\n");
510       abort();
511     }
512   };
513 }
514
515 namespace {
516   template<class ValType, class TypeClass, class ConstantClass>
517   class ValueMap : public AbstractTypeUser {
518     typedef std::pair<const TypeClass*, ValType> MapKey;
519     typedef std::map<MapKey, ConstantClass *> MapTy;
520     typedef typename MapTy::iterator MapIterator;
521     MapTy Map;
522
523     typedef std::map<const TypeClass*, MapIterator> AbstractTypeMapTy;
524     AbstractTypeMapTy AbstractTypeMap;
525
526     friend void Constant::clearAllValueMaps();
527   private:
528     void clear(std::vector<Constant *> &Constants) {
529       for(MapIterator I = Map.begin(); I != Map.end(); ++I)
530         Constants.push_back(I->second);
531       Map.clear();
532       AbstractTypeMap.clear();
533     }
534
535   public:
536     // getOrCreate - Return the specified constant from the map, creating it if
537     // necessary.
538     ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
539       MapKey Lookup(Ty, V);
540       MapIterator I = Map.lower_bound(Lookup);
541       if (I != Map.end() && I->first == Lookup)
542         return I->second;  // Is it in the map?
543
544       // If no preexisting value, create one now...
545       ConstantClass *Result =
546         ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
547
548
549       /// FIXME: why does this assert fail when loading 176.gcc?
550       //assert(Result->getType() == Ty && "Type specified is not correct!");
551       I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
552
553       // If the type of the constant is abstract, make sure that an entry exists
554       // for it in the AbstractTypeMap.
555       if (Ty->isAbstract()) {
556         typename AbstractTypeMapTy::iterator TI =
557           AbstractTypeMap.lower_bound(Ty);
558
559         if (TI == AbstractTypeMap.end() || TI->first != Ty) {
560           // Add ourselves to the ATU list of the type.
561           cast<DerivedType>(Ty)->addAbstractTypeUser(this);
562
563           AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
564         }
565       }
566       return Result;
567     }
568
569     void remove(ConstantClass *CP) {
570       MapIterator I = Map.find(MapKey((TypeClass*)CP->getRawType(),
571                                       getValType(CP)));
572       if (I == Map.end() || I->second != CP) {
573         // FIXME: This should not use a linear scan.  If this gets to be a
574         // performance problem, someone should look at this.
575         for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
576           /* empty */;
577       }
578
579       assert(I != Map.end() && "Constant not found in constant table!");
580       assert(I->second == CP && "Didn't find correct element?");
581
582       // Now that we found the entry, make sure this isn't the entry that
583       // the AbstractTypeMap points to.
584       const TypeClass *Ty = I->first.first;
585       if (Ty->isAbstract()) {
586         assert(AbstractTypeMap.count(Ty) &&
587                "Abstract type not in AbstractTypeMap?");
588         MapIterator &ATMEntryIt = AbstractTypeMap[Ty];
589         if (ATMEntryIt == I) {
590           // Yes, we are removing the representative entry for this type.
591           // See if there are any other entries of the same type.
592           MapIterator TmpIt = ATMEntryIt;
593
594           // First check the entry before this one...
595           if (TmpIt != Map.begin()) {
596             --TmpIt;
597             if (TmpIt->first.first != Ty) // Not the same type, move back...
598               ++TmpIt;
599           }
600
601           // If we didn't find the same type, try to move forward...
602           if (TmpIt == ATMEntryIt) {
603             ++TmpIt;
604             if (TmpIt == Map.end() || TmpIt->first.first != Ty)
605               --TmpIt;   // No entry afterwards with the same type
606           }
607
608           // If there is another entry in the map of the same abstract type,
609           // update the AbstractTypeMap entry now.
610           if (TmpIt != ATMEntryIt) {
611             ATMEntryIt = TmpIt;
612           } else {
613             // Otherwise, we are removing the last instance of this type
614             // from the table.  Remove from the ATM, and from user list.
615             cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
616             AbstractTypeMap.erase(Ty);
617           }
618         }
619       }
620
621       Map.erase(I);
622     }
623
624     void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
625       typename AbstractTypeMapTy::iterator I =
626         AbstractTypeMap.find(cast<TypeClass>(OldTy));
627
628       assert(I != AbstractTypeMap.end() &&
629              "Abstract type not in AbstractTypeMap?");
630
631       // Convert a constant at a time until the last one is gone.  The last one
632       // leaving will remove() itself, causing the AbstractTypeMapEntry to be
633       // eliminated eventually.
634       do {
635         ConvertConstantType<ConstantClass,
636                             TypeClass>::convert(I->second->second,
637                                                 cast<TypeClass>(NewTy));
638
639         I = AbstractTypeMap.find(cast<TypeClass>(OldTy));
640       } while (I != AbstractTypeMap.end());
641     }
642
643     // If the type became concrete without being refined to any other existing
644     // type, we just remove ourselves from the ATU list.
645     void typeBecameConcrete(const DerivedType *AbsTy) {
646       AbsTy->removeAbstractTypeUser(this);
647     }
648
649     void dump() const {
650       std::cerr << "Constant.cpp: ValueMap\n";
651     }
652   };
653 }
654
655 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
656 //
657 static ValueMap< int64_t, Type, ConstantSInt> SIntConstants;
658 static ValueMap<uint64_t, Type, ConstantUInt> UIntConstants;
659
660 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
661   return SIntConstants.getOrCreate(Ty, V);
662 }
663
664 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
665   return UIntConstants.getOrCreate(Ty, V);
666 }
667
668 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
669   assert(V <= 127 && "Can only be used with very small positive constants!");
670   if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
671   return ConstantUInt::get(Ty, V);
672 }
673
674 //---- ConstantFP::get() implementation...
675 //
676 namespace llvm {
677   template<>
678   struct ConstantCreator<ConstantFP, Type, uint64_t> {
679     static ConstantFP *create(const Type *Ty, uint64_t V) {
680       assert(Ty == Type::DoubleTy);
681       return new ConstantFP(Ty, BitsToDouble(V));
682     }
683   };
684   template<>
685   struct ConstantCreator<ConstantFP, Type, uint32_t> {
686     static ConstantFP *create(const Type *Ty, uint32_t V) {
687       assert(Ty == Type::FloatTy);
688       return new ConstantFP(Ty, BitsToFloat(V));
689     }
690   };
691 }
692
693 static ValueMap<uint64_t, Type, ConstantFP> DoubleConstants;
694 static ValueMap<uint32_t, Type, ConstantFP> FloatConstants;
695
696 bool ConstantFP::isNullValue() const {
697   return DoubleToBits(Val) == 0;
698 }
699
700 bool ConstantFP::isExactlyValue(double V) const {
701   return DoubleToBits(V) == DoubleToBits(Val);
702 }
703
704
705 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
706   if (Ty == Type::FloatTy) {
707     // Force the value through memory to normalize it.
708     return FloatConstants.getOrCreate(Ty, FloatToBits(V));
709   } else {
710     assert(Ty == Type::DoubleTy);
711     return DoubleConstants.getOrCreate(Ty, DoubleToBits(V));
712   }
713 }
714
715 //---- ConstantAggregateZero::get() implementation...
716 //
717 namespace llvm {
718   // ConstantAggregateZero does not take extra "value" argument...
719   template<class ValType>
720   struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
721     static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
722       return new ConstantAggregateZero(Ty);
723     }
724   };
725
726   template<>
727   struct ConvertConstantType<ConstantAggregateZero, Type> {
728     static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
729       // Make everyone now use a constant of the new type...
730       Constant *New = ConstantAggregateZero::get(NewTy);
731       assert(New != OldC && "Didn't replace constant??");
732       OldC->uncheckedReplaceAllUsesWith(New);
733       OldC->destroyConstant();     // This constant is now dead, destroy it.
734     }
735   };
736 }
737
738 static ValueMap<char, Type, ConstantAggregateZero> AggZeroConstants;
739
740 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
741
742 Constant *ConstantAggregateZero::get(const Type *Ty) {
743   return AggZeroConstants.getOrCreate(Ty, 0);
744 }
745
746 // destroyConstant - Remove the constant from the constant table...
747 //
748 void ConstantAggregateZero::destroyConstant() {
749   AggZeroConstants.remove(this);
750   destroyConstantImpl();
751 }
752
753 void ConstantAggregateZero::replaceUsesOfWithOnConstant(Value *From, Value *To,
754                                                         bool DisableChecking) {
755   assert(0 && "No uses!");
756   abort();
757 }
758
759
760
761 //---- ConstantArray::get() implementation...
762 //
763 namespace llvm {
764   template<>
765   struct ConvertConstantType<ConstantArray, ArrayType> {
766     static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
767       // Make everyone now use a constant of the new type...
768       std::vector<Constant*> C;
769       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
770         C.push_back(cast<Constant>(OldC->getOperand(i)));
771       Constant *New = ConstantArray::get(NewTy, C);
772       assert(New != OldC && "Didn't replace constant??");
773       OldC->uncheckedReplaceAllUsesWith(New);
774       OldC->destroyConstant();    // This constant is now dead, destroy it.
775     }
776   };
777 }
778
779 static std::vector<Constant*> getValType(ConstantArray *CA) {
780   std::vector<Constant*> Elements;
781   Elements.reserve(CA->getNumOperands());
782   for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
783     Elements.push_back(cast<Constant>(CA->getOperand(i)));
784   return Elements;
785 }
786
787 static ValueMap<std::vector<Constant*>, ArrayType,
788                 ConstantArray> ArrayConstants;
789
790 Constant *ConstantArray::get(const ArrayType *Ty,
791                              const std::vector<Constant*> &V) {
792   // If this is an all-zero array, return a ConstantAggregateZero object
793   if (!V.empty()) {
794     Constant *C = V[0];
795     if (!C->isNullValue())
796       return ArrayConstants.getOrCreate(Ty, V);
797     for (unsigned i = 1, e = V.size(); i != e; ++i)
798       if (V[i] != C)
799         return ArrayConstants.getOrCreate(Ty, V);
800   }
801   return ConstantAggregateZero::get(Ty);
802 }
803
804 // destroyConstant - Remove the constant from the constant table...
805 //
806 void ConstantArray::destroyConstant() {
807   ArrayConstants.remove(this);
808   destroyConstantImpl();
809 }
810
811 // ConstantArray::get(const string&) - Return an array that is initialized to
812 // contain the specified string.  A null terminator is added to the specified
813 // string so that it may be used in a natural way...
814 //
815 Constant *ConstantArray::get(const std::string &Str) {
816   std::vector<Constant*> ElementVals;
817
818   for (unsigned i = 0; i < Str.length(); ++i)
819     ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
820
821   // Add a null terminator to the string...
822   ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
823
824   ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
825   return ConstantArray::get(ATy, ElementVals);
826 }
827
828 /// isString - This method returns true if the array is an array of sbyte or
829 /// ubyte, and if the elements of the array are all ConstantInt's.
830 bool ConstantArray::isString() const {
831   // Check the element type for sbyte or ubyte...
832   if (getType()->getElementType() != Type::UByteTy &&
833       getType()->getElementType() != Type::SByteTy)
834     return false;
835   // Check the elements to make sure they are all integers, not constant
836   // expressions.
837   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
838     if (!isa<ConstantInt>(getOperand(i)))
839       return false;
840   return true;
841 }
842
843 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
844 // then this method converts the array to an std::string and returns it.
845 // Otherwise, it asserts out.
846 //
847 std::string ConstantArray::getAsString() const {
848   assert(isString() && "Not a string!");
849   std::string Result;
850   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
851     Result += (char)cast<ConstantInt>(getOperand(i))->getRawValue();
852   return Result;
853 }
854
855
856 //---- ConstantStruct::get() implementation...
857 //
858
859 namespace llvm {
860   template<>
861   struct ConvertConstantType<ConstantStruct, StructType> {
862     static void convert(ConstantStruct *OldC, const StructType *NewTy) {
863       // Make everyone now use a constant of the new type...
864       std::vector<Constant*> C;
865       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
866         C.push_back(cast<Constant>(OldC->getOperand(i)));
867       Constant *New = ConstantStruct::get(NewTy, C);
868       assert(New != OldC && "Didn't replace constant??");
869
870       OldC->uncheckedReplaceAllUsesWith(New);
871       OldC->destroyConstant();    // This constant is now dead, destroy it.
872     }
873   };
874 }
875
876 static ValueMap<std::vector<Constant*>, StructType,
877                 ConstantStruct> StructConstants;
878
879 static std::vector<Constant*> getValType(ConstantStruct *CS) {
880   std::vector<Constant*> Elements;
881   Elements.reserve(CS->getNumOperands());
882   for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
883     Elements.push_back(cast<Constant>(CS->getOperand(i)));
884   return Elements;
885 }
886
887 Constant *ConstantStruct::get(const StructType *Ty,
888                               const std::vector<Constant*> &V) {
889   // Create a ConstantAggregateZero value if all elements are zeros...
890   for (unsigned i = 0, e = V.size(); i != e; ++i)
891     if (!V[i]->isNullValue())
892       return StructConstants.getOrCreate(Ty, V);
893
894   return ConstantAggregateZero::get(Ty);
895 }
896
897 Constant *ConstantStruct::get(const std::vector<Constant*> &V) {
898   std::vector<const Type*> StructEls;
899   StructEls.reserve(V.size());
900   for (unsigned i = 0, e = V.size(); i != e; ++i)
901     StructEls.push_back(V[i]->getType());
902   return get(StructType::get(StructEls), V);
903 }
904
905 // destroyConstant - Remove the constant from the constant table...
906 //
907 void ConstantStruct::destroyConstant() {
908   StructConstants.remove(this);
909   destroyConstantImpl();
910 }
911
912 //---- ConstantPacked::get() implementation...
913 //
914 namespace llvm {
915   template<>
916   struct ConvertConstantType<ConstantPacked, PackedType> {
917     static void convert(ConstantPacked *OldC, const PackedType *NewTy) {
918       // Make everyone now use a constant of the new type...
919       std::vector<Constant*> C;
920       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
921         C.push_back(cast<Constant>(OldC->getOperand(i)));
922       Constant *New = ConstantPacked::get(NewTy, C);
923       assert(New != OldC && "Didn't replace constant??");
924       OldC->uncheckedReplaceAllUsesWith(New);
925       OldC->destroyConstant();    // This constant is now dead, destroy it.
926     }
927   };
928 }
929
930 static std::vector<Constant*> getValType(ConstantPacked *CP) {
931   std::vector<Constant*> Elements;
932   Elements.reserve(CP->getNumOperands());
933   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
934     Elements.push_back(CP->getOperand(i));
935   return Elements;
936 }
937
938 static ValueMap<std::vector<Constant*>, PackedType,
939                 ConstantPacked> PackedConstants;
940
941 Constant *ConstantPacked::get(const PackedType *Ty,
942                               const std::vector<Constant*> &V) {
943   // If this is an all-zero packed, return a ConstantAggregateZero object
944   if (!V.empty()) {
945     Constant *C = V[0];
946     if (!C->isNullValue())
947       return PackedConstants.getOrCreate(Ty, V);
948     for (unsigned i = 1, e = V.size(); i != e; ++i)
949       if (V[i] != C)
950         return PackedConstants.getOrCreate(Ty, V);
951   }
952   return ConstantAggregateZero::get(Ty);
953 }
954
955 Constant *ConstantPacked::get(const std::vector<Constant*> &V) {
956   assert(!V.empty() && "Cannot infer type if V is empty");
957   return get(PackedType::get(V.front()->getType(),V.size()), V);
958 }
959
960 // destroyConstant - Remove the constant from the constant table...
961 //
962 void ConstantPacked::destroyConstant() {
963   PackedConstants.remove(this);
964   destroyConstantImpl();
965 }
966
967 //---- ConstantPointerNull::get() implementation...
968 //
969
970 namespace llvm {
971   // ConstantPointerNull does not take extra "value" argument...
972   template<class ValType>
973   struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
974     static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
975       return new ConstantPointerNull(Ty);
976     }
977   };
978
979   template<>
980   struct ConvertConstantType<ConstantPointerNull, PointerType> {
981     static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
982       // Make everyone now use a constant of the new type...
983       Constant *New = ConstantPointerNull::get(NewTy);
984       assert(New != OldC && "Didn't replace constant??");
985       OldC->uncheckedReplaceAllUsesWith(New);
986       OldC->destroyConstant();     // This constant is now dead, destroy it.
987     }
988   };
989 }
990
991 static ValueMap<char, PointerType, ConstantPointerNull> NullPtrConstants;
992
993 static char getValType(ConstantPointerNull *) {
994   return 0;
995 }
996
997
998 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
999   return NullPtrConstants.getOrCreate(Ty, 0);
1000 }
1001
1002 // destroyConstant - Remove the constant from the constant table...
1003 //
1004 void ConstantPointerNull::destroyConstant() {
1005   NullPtrConstants.remove(this);
1006   destroyConstantImpl();
1007 }
1008
1009
1010 //---- UndefValue::get() implementation...
1011 //
1012
1013 namespace llvm {
1014   // UndefValue does not take extra "value" argument...
1015   template<class ValType>
1016   struct ConstantCreator<UndefValue, Type, ValType> {
1017     static UndefValue *create(const Type *Ty, const ValType &V) {
1018       return new UndefValue(Ty);
1019     }
1020   };
1021
1022   template<>
1023   struct ConvertConstantType<UndefValue, Type> {
1024     static void convert(UndefValue *OldC, const Type *NewTy) {
1025       // Make everyone now use a constant of the new type.
1026       Constant *New = UndefValue::get(NewTy);
1027       assert(New != OldC && "Didn't replace constant??");
1028       OldC->uncheckedReplaceAllUsesWith(New);
1029       OldC->destroyConstant();     // This constant is now dead, destroy it.
1030     }
1031   };
1032 }
1033
1034 static ValueMap<char, Type, UndefValue> UndefValueConstants;
1035
1036 static char getValType(UndefValue *) {
1037   return 0;
1038 }
1039
1040
1041 UndefValue *UndefValue::get(const Type *Ty) {
1042   return UndefValueConstants.getOrCreate(Ty, 0);
1043 }
1044
1045 // destroyConstant - Remove the constant from the constant table.
1046 //
1047 void UndefValue::destroyConstant() {
1048   UndefValueConstants.remove(this);
1049   destroyConstantImpl();
1050 }
1051
1052
1053
1054
1055 //---- ConstantExpr::get() implementations...
1056 //
1057 typedef std::pair<unsigned, std::vector<Constant*> > ExprMapKeyType;
1058
1059 namespace llvm {
1060   template<>
1061   struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1062     static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V) {
1063       if (V.first == Instruction::Cast)
1064         return new UnaryConstantExpr(Instruction::Cast, V.second[0], Ty);
1065       if ((V.first >= Instruction::BinaryOpsBegin &&
1066            V.first < Instruction::BinaryOpsEnd) ||
1067           V.first == Instruction::Shl || V.first == Instruction::Shr)
1068         return new BinaryConstantExpr(V.first, V.second[0], V.second[1]);
1069       if (V.first == Instruction::Select)
1070         return new SelectConstantExpr(V.second[0], V.second[1], V.second[2]);
1071
1072       assert(V.first == Instruction::GetElementPtr && "Invalid ConstantExpr!");
1073
1074       std::vector<Constant*> IdxList(V.second.begin()+1, V.second.end());
1075       return new GetElementPtrConstantExpr(V.second[0], IdxList, Ty);
1076     }
1077   };
1078
1079   template<>
1080   struct ConvertConstantType<ConstantExpr, Type> {
1081     static void convert(ConstantExpr *OldC, const Type *NewTy) {
1082       Constant *New;
1083       switch (OldC->getOpcode()) {
1084       case Instruction::Cast:
1085         New = ConstantExpr::getCast(OldC->getOperand(0), NewTy);
1086         break;
1087       case Instruction::Select:
1088         New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1089                                         OldC->getOperand(1),
1090                                         OldC->getOperand(2));
1091         break;
1092       case Instruction::Shl:
1093       case Instruction::Shr:
1094         New = ConstantExpr::getShiftTy(NewTy, OldC->getOpcode(),
1095                                      OldC->getOperand(0), OldC->getOperand(1));
1096         break;
1097       default:
1098         assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1099                OldC->getOpcode() < Instruction::BinaryOpsEnd);
1100         New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1101                                   OldC->getOperand(1));
1102         break;
1103       case Instruction::GetElementPtr:
1104         // Make everyone now use a constant of the new type...
1105         std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1106         New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0), Idx);
1107         break;
1108       }
1109
1110       assert(New != OldC && "Didn't replace constant??");
1111       OldC->uncheckedReplaceAllUsesWith(New);
1112       OldC->destroyConstant();    // This constant is now dead, destroy it.
1113     }
1114   };
1115 } // end namespace llvm
1116
1117
1118 static ExprMapKeyType getValType(ConstantExpr *CE) {
1119   std::vector<Constant*> Operands;
1120   Operands.reserve(CE->getNumOperands());
1121   for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1122     Operands.push_back(cast<Constant>(CE->getOperand(i)));
1123   return ExprMapKeyType(CE->getOpcode(), Operands);
1124 }
1125
1126 static ValueMap<ExprMapKeyType, Type, ConstantExpr> ExprConstants;
1127
1128 Constant *ConstantExpr::getCast(Constant *C, const Type *Ty) {
1129   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1130
1131   if (Constant *FC = ConstantFoldCastInstruction(C, Ty))
1132     return FC;          // Fold a few common cases...
1133
1134   // Look up the constant in the table first to ensure uniqueness
1135   std::vector<Constant*> argVec(1, C);
1136   ExprMapKeyType Key = std::make_pair(Instruction::Cast, argVec);
1137   return ExprConstants.getOrCreate(Ty, Key);
1138 }
1139
1140 Constant *ConstantExpr::getSignExtend(Constant *C, const Type *Ty) {
1141   assert(C->getType()->isIntegral() && Ty->isIntegral() &&
1142          C->getType()->getPrimitiveSize() <= Ty->getPrimitiveSize() &&
1143          "This is an illegal sign extension!");
1144   if (C->getType() != Type::BoolTy) {
1145     C = ConstantExpr::getCast(C, C->getType()->getSignedVersion());
1146     return ConstantExpr::getCast(C, Ty);
1147   } else {
1148     if (C == ConstantBool::True)
1149       return ConstantIntegral::getAllOnesValue(Ty);
1150     else
1151       return ConstantIntegral::getNullValue(Ty);
1152   }
1153 }
1154
1155 Constant *ConstantExpr::getZeroExtend(Constant *C, const Type *Ty) {
1156   assert(C->getType()->isIntegral() && Ty->isIntegral() &&
1157          C->getType()->getPrimitiveSize() <= Ty->getPrimitiveSize() &&
1158          "This is an illegal zero extension!");
1159   if (C->getType() != Type::BoolTy)
1160     C = ConstantExpr::getCast(C, C->getType()->getUnsignedVersion());
1161   return ConstantExpr::getCast(C, Ty);
1162 }
1163
1164 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
1165   // sizeof is implemented as: (ulong) gep (Ty*)null, 1
1166   return getCast(
1167     getGetElementPtr(getNullValue(PointerType::get(Ty)),
1168                  std::vector<Constant*>(1, ConstantInt::get(Type::UIntTy, 1))),
1169     Type::ULongTy);
1170 }
1171
1172 Constant *ConstantExpr::getPtrPtrFromArrayPtr(Constant *C) {
1173   // pointer from array is implemented as: getelementptr arr ptr, 0, 0
1174   static std::vector<Constant*> Indices(2, ConstantUInt::get(Type::UIntTy, 0));
1175
1176   return ConstantExpr::getGetElementPtr(C, Indices);
1177 }
1178
1179 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1180                               Constant *C1, Constant *C2) {
1181   if (Opcode == Instruction::Shl || Opcode == Instruction::Shr)
1182     return getShiftTy(ReqTy, Opcode, C1, C2);
1183   // Check the operands for consistency first
1184   assert((Opcode >= Instruction::BinaryOpsBegin &&
1185           Opcode < Instruction::BinaryOpsEnd) &&
1186          "Invalid opcode in binary constant expression");
1187   assert(C1->getType() == C2->getType() &&
1188          "Operand types in binary constant expression should match");
1189
1190   if (ReqTy == C1->getType() || (Instruction::isRelational(Opcode) &&
1191                                  ReqTy == Type::BoolTy))
1192     if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1193       return FC;          // Fold a few common cases...
1194
1195   std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1196   ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1197   return ExprConstants.getOrCreate(ReqTy, Key);
1198 }
1199
1200 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1201 #ifndef NDEBUG
1202   switch (Opcode) {
1203   case Instruction::Add: case Instruction::Sub:
1204   case Instruction::Mul: case Instruction::Div:
1205   case Instruction::Rem:
1206     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1207     assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint()) &&
1208            "Tried to create an arithmetic operation on a non-arithmetic type!");
1209     break;
1210   case Instruction::And:
1211   case Instruction::Or:
1212   case Instruction::Xor:
1213     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1214     assert(C1->getType()->isIntegral() &&
1215            "Tried to create a logical operation on a non-integral type!");
1216     break;
1217   case Instruction::SetLT: case Instruction::SetGT: case Instruction::SetLE:
1218   case Instruction::SetGE: case Instruction::SetEQ: case Instruction::SetNE:
1219     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1220     break;
1221   case Instruction::Shl:
1222   case Instruction::Shr:
1223     assert(C2->getType() == Type::UByteTy && "Shift should be by ubyte!");
1224     assert(C1->getType()->isInteger() &&
1225            "Tried to create a shift operation on a non-integer type!");
1226     break;
1227   default:
1228     break;
1229   }
1230 #endif
1231
1232   if (Instruction::isRelational(Opcode))
1233     return getTy(Type::BoolTy, Opcode, C1, C2);
1234   else
1235     return getTy(C1->getType(), Opcode, C1, C2);
1236 }
1237
1238 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1239                                     Constant *V1, Constant *V2) {
1240   assert(C->getType() == Type::BoolTy && "Select condition must be bool!");
1241   assert(V1->getType() == V2->getType() && "Select value types must match!");
1242   assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1243
1244   if (ReqTy == V1->getType())
1245     if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1246       return SC;        // Fold common cases
1247
1248   std::vector<Constant*> argVec(3, C);
1249   argVec[1] = V1;
1250   argVec[2] = V2;
1251   ExprMapKeyType Key = std::make_pair(Instruction::Select, argVec);
1252   return ExprConstants.getOrCreate(ReqTy, Key);
1253 }
1254
1255 /// getShiftTy - Return a shift left or shift right constant expr
1256 Constant *ConstantExpr::getShiftTy(const Type *ReqTy, unsigned Opcode,
1257                                    Constant *C1, Constant *C2) {
1258   // Check the operands for consistency first
1259   assert((Opcode == Instruction::Shl ||
1260           Opcode == Instruction::Shr) &&
1261          "Invalid opcode in binary constant expression");
1262   assert(C1->getType()->isIntegral() && C2->getType() == Type::UByteTy &&
1263          "Invalid operand types for Shift constant expr!");
1264
1265   if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1266     return FC;          // Fold a few common cases...
1267
1268   // Look up the constant in the table first to ensure uniqueness
1269   std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1270   ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1271   return ExprConstants.getOrCreate(ReqTy, Key);
1272 }
1273
1274
1275 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1276                                            const std::vector<Value*> &IdxList) {
1277   assert(GetElementPtrInst::getIndexedType(C->getType(), IdxList, true) &&
1278          "GEP indices invalid!");
1279
1280   if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
1281     return FC;          // Fold a few common cases...
1282
1283   assert(isa<PointerType>(C->getType()) &&
1284          "Non-pointer type for constant GetElementPtr expression");
1285   // Look up the constant in the table first to ensure uniqueness
1286   std::vector<Constant*> ArgVec;
1287   ArgVec.reserve(IdxList.size()+1);
1288   ArgVec.push_back(C);
1289   for (unsigned i = 0, e = IdxList.size(); i != e; ++i)
1290     ArgVec.push_back(cast<Constant>(IdxList[i]));
1291   const ExprMapKeyType &Key = std::make_pair(Instruction::GetElementPtr,ArgVec);
1292   return ExprConstants.getOrCreate(ReqTy, Key);
1293 }
1294
1295 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1296                                          const std::vector<Constant*> &IdxList){
1297   // Get the result type of the getelementptr!
1298   std::vector<Value*> VIdxList(IdxList.begin(), IdxList.end());
1299
1300   const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), VIdxList,
1301                                                      true);
1302   assert(Ty && "GEP indices invalid!");
1303   return getGetElementPtrTy(PointerType::get(Ty), C, VIdxList);
1304 }
1305
1306 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1307                                          const std::vector<Value*> &IdxList) {
1308   // Get the result type of the getelementptr!
1309   const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
1310                                                      true);
1311   assert(Ty && "GEP indices invalid!");
1312   return getGetElementPtrTy(PointerType::get(Ty), C, IdxList);
1313 }
1314
1315
1316 // destroyConstant - Remove the constant from the constant table...
1317 //
1318 void ConstantExpr::destroyConstant() {
1319   ExprConstants.remove(this);
1320   destroyConstantImpl();
1321 }
1322
1323 const char *ConstantExpr::getOpcodeName() const {
1324   return Instruction::getOpcodeName(getOpcode());
1325 }
1326
1327 //===----------------------------------------------------------------------===//
1328 //                replaceUsesOfWithOnConstant implementations
1329
1330 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1331                                                 bool DisableChecking) {
1332   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1333   
1334   std::vector<Constant*> Values;
1335   Values.reserve(getNumOperands());  // Build replacement array...
1336   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1337     Constant *Val = getOperand(i);
1338     if (Val == From) Val = cast<Constant>(To);
1339     Values.push_back(Val);
1340   }
1341   
1342   Constant *Replacement = ConstantArray::get(getType(), Values);
1343   assert(Replacement != this && "I didn't contain From!");
1344   
1345   // Everyone using this now uses the replacement...
1346   if (DisableChecking)
1347     uncheckedReplaceAllUsesWith(Replacement);
1348   else
1349     replaceAllUsesWith(Replacement);
1350   
1351   // Delete the old constant!
1352   destroyConstant();
1353 }
1354
1355 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
1356                                                  bool DisableChecking) {
1357   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1358   
1359   std::vector<Constant*> Values;
1360   Values.reserve(getNumOperands());  // Build replacement array...
1361   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1362     Constant *Val = getOperand(i);
1363     if (Val == From) Val = cast<Constant>(To);
1364     Values.push_back(Val);
1365   }
1366   
1367   Constant *Replacement = ConstantStruct::get(getType(), Values);
1368   assert(Replacement != this && "I didn't contain From!");
1369   
1370   // Everyone using this now uses the replacement...
1371   if (DisableChecking)
1372     uncheckedReplaceAllUsesWith(Replacement);
1373   else
1374     replaceAllUsesWith(Replacement);
1375   
1376   // Delete the old constant!
1377   destroyConstant();
1378 }
1379
1380 void ConstantPacked::replaceUsesOfWithOnConstant(Value *From, Value *To,
1381                                                  bool DisableChecking) {
1382   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1383   
1384   std::vector<Constant*> Values;
1385   Values.reserve(getNumOperands());  // Build replacement array...
1386   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1387     Constant *Val = getOperand(i);
1388     if (Val == From) Val = cast<Constant>(To);
1389     Values.push_back(Val);
1390   }
1391   
1392   Constant *Replacement = ConstantPacked::get(getType(), Values);
1393   assert(Replacement != this && "I didn't contain From!");
1394   
1395   // Everyone using this now uses the replacement...
1396   if (DisableChecking)
1397     uncheckedReplaceAllUsesWith(Replacement);
1398   else
1399     replaceAllUsesWith(Replacement);
1400   
1401   // Delete the old constant!
1402   destroyConstant();
1403 }
1404
1405 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
1406                                                bool DisableChecking) {
1407   assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
1408   Constant *To = cast<Constant>(ToV);
1409   
1410   Constant *Replacement = 0;
1411   if (getOpcode() == Instruction::GetElementPtr) {
1412     std::vector<Constant*> Indices;
1413     Constant *Pointer = getOperand(0);
1414     Indices.reserve(getNumOperands()-1);
1415     if (Pointer == From) Pointer = To;
1416     
1417     for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1418       Constant *Val = getOperand(i);
1419       if (Val == From) Val = To;
1420       Indices.push_back(Val);
1421     }
1422     Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
1423   } else if (getOpcode() == Instruction::Cast) {
1424     assert(getOperand(0) == From && "Cast only has one use!");
1425     Replacement = ConstantExpr::getCast(To, getType());
1426   } else if (getOpcode() == Instruction::Select) {
1427     Constant *C1 = getOperand(0);
1428     Constant *C2 = getOperand(1);
1429     Constant *C3 = getOperand(2);
1430     if (C1 == From) C1 = To;
1431     if (C2 == From) C2 = To;
1432     if (C3 == From) C3 = To;
1433     Replacement = ConstantExpr::getSelect(C1, C2, C3);
1434   } else if (getNumOperands() == 2) {
1435     Constant *C1 = getOperand(0);
1436     Constant *C2 = getOperand(1);
1437     if (C1 == From) C1 = To;
1438     if (C2 == From) C2 = To;
1439     Replacement = ConstantExpr::get(getOpcode(), C1, C2);
1440   } else {
1441     assert(0 && "Unknown ConstantExpr type!");
1442     return;
1443   }
1444   
1445   assert(Replacement != this && "I didn't contain From!");
1446   
1447   // Everyone using this now uses the replacement...
1448   if (DisableChecking)
1449     uncheckedReplaceAllUsesWith(Replacement);
1450   else
1451     replaceAllUsesWith(Replacement);
1452   
1453   // Delete the old constant!
1454   destroyConstant();
1455 }
1456
1457
1458
1459 /// clearAllValueMaps - This method frees all internal memory used by the
1460 /// constant subsystem, which can be used in environments where this memory
1461 /// is otherwise reported as a leak.
1462 void Constant::clearAllValueMaps() {
1463   std::vector<Constant *> Constants;
1464
1465   DoubleConstants.clear(Constants);
1466   FloatConstants.clear(Constants);
1467   SIntConstants.clear(Constants);
1468   UIntConstants.clear(Constants);
1469   AggZeroConstants.clear(Constants);
1470   ArrayConstants.clear(Constants);
1471   StructConstants.clear(Constants);
1472   PackedConstants.clear(Constants);
1473   NullPtrConstants.clear(Constants);
1474   UndefValueConstants.clear(Constants);
1475   ExprConstants.clear(Constants);
1476
1477   for (std::vector<Constant *>::iterator I = Constants.begin(),
1478        E = Constants.end(); I != E; ++I)
1479     (*I)->dropAllReferences();
1480   for (std::vector<Constant *>::iterator I = Constants.begin(),
1481        E = Constants.end(); I != E; ++I)
1482     (*I)->destroyConstantImpl();
1483   Constants.clear();
1484 }