Change the signature of replaceUsesOfWithOnConstant. The bool was always
[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            bool HasLargeKey = false  /*true for arrays and structs*/ >
518   class ValueMap : public AbstractTypeUser {
519   public:
520     typedef std::pair<const TypeClass*, ValType> MapKey;
521     typedef std::map<MapKey, ConstantClass *> MapTy;
522     typedef typename MapTy::iterator MapIterator;
523   private:
524     /// Map - This is the main map from the element descriptor to the Constants.
525     /// This is the primary way we avoid creating two of the same shape
526     /// constant.
527     MapTy Map;
528     
529     /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
530     /// from the constants to their element in Map.  This is important for
531     /// removal of constants from the array, which would otherwise have to scan
532     /// through the map with very large keys.
533     std::map<ConstantClass*, MapIterator> InverseMap;
534
535     typedef std::map<const TypeClass*, MapIterator> AbstractTypeMapTy;
536     AbstractTypeMapTy AbstractTypeMap;
537
538     friend void Constant::clearAllValueMaps();
539   private:
540     void clear(std::vector<Constant *> &Constants) {
541       for(MapIterator I = Map.begin(); I != Map.end(); ++I)
542         Constants.push_back(I->second);
543       Map.clear();
544       AbstractTypeMap.clear();
545       InverseMap.clear();
546     }
547
548   public:
549     MapIterator map_end() { return Map.end(); }
550     
551     void UpdateInverseMap(ConstantClass *C, MapIterator I) {
552       if (HasLargeKey) {
553         assert(I->second == C && "Bad inversemap entry!");
554         InverseMap[C] = I;
555       }
556     }
557     
558     /// InsertOrGetItem - Return an iterator for the specified element.
559     /// If the element exists in the map, the returned iterator points to the
560     /// entry and Exists=true.  If not, the iterator points to the newly
561     /// inserted entry and returns Exists=false.  Newly inserted entries have
562     /// I->second == 0, and should be filled in.
563     MapIterator InsertOrGetItem(std::pair<MapKey, ConstantClass *> &InsertVal,
564                                    bool &Exists) {
565       std::pair<MapIterator, bool> IP = Map.insert(InsertVal);
566       Exists = !IP.second;
567       return IP.first;
568     }
569     
570 private:
571     MapIterator FindExistingElement(ConstantClass *CP) {
572       if (HasLargeKey) {
573         typename std::map<ConstantClass*, MapIterator>::iterator
574             IMI = InverseMap.find(CP);
575         assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
576                IMI->second->second == CP &&
577                "InverseMap corrupt!");
578         return IMI->second;
579       }
580       
581       MapIterator I =
582         Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
583       if (I == Map.end() || I->second != CP) {
584         // FIXME: This should not use a linear scan.  If this gets to be a
585         // performance problem, someone should look at this.
586         for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
587           /* empty */;
588       }
589       return I;
590     }
591 public:
592     
593     /// SimpleRemove - This method removes the specified constant from the map,
594     /// without updating type information.  This should only be used when we're
595     /// changing an element in the map, making this the second half of a 'move'
596     /// operation.
597     void SimpleRemove(ConstantClass *CP) {
598       MapIterator I = FindExistingElement(CP);
599       assert(I != Map.end() && "Constant not found in constant table!");
600       assert(I->second == CP && "Didn't find correct element?");
601       Map.erase(I);
602     }
603       
604     /// getOrCreate - Return the specified constant from the map, creating it if
605     /// necessary.
606     ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
607       MapKey Lookup(Ty, V);
608       MapIterator I = Map.lower_bound(Lookup);
609       if (I != Map.end() && I->first == Lookup)
610         return I->second;  // Is it in the map?
611
612       // If no preexisting value, create one now...
613       ConstantClass *Result =
614         ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
615
616       /// FIXME: why does this assert fail when loading 176.gcc?
617       //assert(Result->getType() == Ty && "Type specified is not correct!");
618       I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
619
620       if (HasLargeKey)  // Remember the reverse mapping if needed.
621         InverseMap.insert(std::make_pair(Result, I));
622       
623       // If the type of the constant is abstract, make sure that an entry exists
624       // for it in the AbstractTypeMap.
625       if (Ty->isAbstract()) {
626         typename AbstractTypeMapTy::iterator TI =
627           AbstractTypeMap.lower_bound(Ty);
628
629         if (TI == AbstractTypeMap.end() || TI->first != Ty) {
630           // Add ourselves to the ATU list of the type.
631           cast<DerivedType>(Ty)->addAbstractTypeUser(this);
632
633           AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
634         }
635       }
636       return Result;
637     }
638
639     void remove(ConstantClass *CP) {
640       MapIterator I = FindExistingElement(CP);
641       assert(I != Map.end() && "Constant not found in constant table!");
642       assert(I->second == CP && "Didn't find correct element?");
643
644       if (HasLargeKey)  // Remember the reverse mapping if needed.
645         InverseMap.erase(CP);
646       
647       // Now that we found the entry, make sure this isn't the entry that
648       // the AbstractTypeMap points to.
649       const TypeClass *Ty = I->first.first;
650       if (Ty->isAbstract()) {
651         assert(AbstractTypeMap.count(Ty) &&
652                "Abstract type not in AbstractTypeMap?");
653         MapIterator &ATMEntryIt = AbstractTypeMap[Ty];
654         if (ATMEntryIt == I) {
655           // Yes, we are removing the representative entry for this type.
656           // See if there are any other entries of the same type.
657           MapIterator TmpIt = ATMEntryIt;
658
659           // First check the entry before this one...
660           if (TmpIt != Map.begin()) {
661             --TmpIt;
662             if (TmpIt->first.first != Ty) // Not the same type, move back...
663               ++TmpIt;
664           }
665
666           // If we didn't find the same type, try to move forward...
667           if (TmpIt == ATMEntryIt) {
668             ++TmpIt;
669             if (TmpIt == Map.end() || TmpIt->first.first != Ty)
670               --TmpIt;   // No entry afterwards with the same type
671           }
672
673           // If there is another entry in the map of the same abstract type,
674           // update the AbstractTypeMap entry now.
675           if (TmpIt != ATMEntryIt) {
676             ATMEntryIt = TmpIt;
677           } else {
678             // Otherwise, we are removing the last instance of this type
679             // from the table.  Remove from the ATM, and from user list.
680             cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
681             AbstractTypeMap.erase(Ty);
682           }
683         }
684       }
685
686       Map.erase(I);
687     }
688
689     void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
690       typename AbstractTypeMapTy::iterator I =
691         AbstractTypeMap.find(cast<TypeClass>(OldTy));
692
693       assert(I != AbstractTypeMap.end() &&
694              "Abstract type not in AbstractTypeMap?");
695
696       // Convert a constant at a time until the last one is gone.  The last one
697       // leaving will remove() itself, causing the AbstractTypeMapEntry to be
698       // eliminated eventually.
699       do {
700         ConvertConstantType<ConstantClass,
701                             TypeClass>::convert(I->second->second,
702                                                 cast<TypeClass>(NewTy));
703
704         I = AbstractTypeMap.find(cast<TypeClass>(OldTy));
705       } while (I != AbstractTypeMap.end());
706     }
707
708     // If the type became concrete without being refined to any other existing
709     // type, we just remove ourselves from the ATU list.
710     void typeBecameConcrete(const DerivedType *AbsTy) {
711       AbsTy->removeAbstractTypeUser(this);
712     }
713
714     void dump() const {
715       std::cerr << "Constant.cpp: ValueMap\n";
716     }
717   };
718 }
719
720 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
721 //
722 static ValueMap< int64_t, Type, ConstantSInt> SIntConstants;
723 static ValueMap<uint64_t, Type, ConstantUInt> UIntConstants;
724
725 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
726   return SIntConstants.getOrCreate(Ty, V);
727 }
728
729 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
730   return UIntConstants.getOrCreate(Ty, V);
731 }
732
733 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
734   assert(V <= 127 && "Can only be used with very small positive constants!");
735   if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
736   return ConstantUInt::get(Ty, V);
737 }
738
739 //---- ConstantFP::get() implementation...
740 //
741 namespace llvm {
742   template<>
743   struct ConstantCreator<ConstantFP, Type, uint64_t> {
744     static ConstantFP *create(const Type *Ty, uint64_t V) {
745       assert(Ty == Type::DoubleTy);
746       return new ConstantFP(Ty, BitsToDouble(V));
747     }
748   };
749   template<>
750   struct ConstantCreator<ConstantFP, Type, uint32_t> {
751     static ConstantFP *create(const Type *Ty, uint32_t V) {
752       assert(Ty == Type::FloatTy);
753       return new ConstantFP(Ty, BitsToFloat(V));
754     }
755   };
756 }
757
758 static ValueMap<uint64_t, Type, ConstantFP> DoubleConstants;
759 static ValueMap<uint32_t, Type, ConstantFP> FloatConstants;
760
761 bool ConstantFP::isNullValue() const {
762   return DoubleToBits(Val) == 0;
763 }
764
765 bool ConstantFP::isExactlyValue(double V) const {
766   return DoubleToBits(V) == DoubleToBits(Val);
767 }
768
769
770 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
771   if (Ty == Type::FloatTy) {
772     // Force the value through memory to normalize it.
773     return FloatConstants.getOrCreate(Ty, FloatToBits(V));
774   } else {
775     assert(Ty == Type::DoubleTy);
776     return DoubleConstants.getOrCreate(Ty, DoubleToBits(V));
777   }
778 }
779
780 //---- ConstantAggregateZero::get() implementation...
781 //
782 namespace llvm {
783   // ConstantAggregateZero does not take extra "value" argument...
784   template<class ValType>
785   struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
786     static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
787       return new ConstantAggregateZero(Ty);
788     }
789   };
790
791   template<>
792   struct ConvertConstantType<ConstantAggregateZero, Type> {
793     static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
794       // Make everyone now use a constant of the new type...
795       Constant *New = ConstantAggregateZero::get(NewTy);
796       assert(New != OldC && "Didn't replace constant??");
797       OldC->uncheckedReplaceAllUsesWith(New);
798       OldC->destroyConstant();     // This constant is now dead, destroy it.
799     }
800   };
801 }
802
803 static ValueMap<char, Type, ConstantAggregateZero> AggZeroConstants;
804
805 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
806
807 Constant *ConstantAggregateZero::get(const Type *Ty) {
808   return AggZeroConstants.getOrCreate(Ty, 0);
809 }
810
811 // destroyConstant - Remove the constant from the constant table...
812 //
813 void ConstantAggregateZero::destroyConstant() {
814   AggZeroConstants.remove(this);
815   destroyConstantImpl();
816 }
817
818 //---- ConstantArray::get() implementation...
819 //
820 namespace llvm {
821   template<>
822   struct ConvertConstantType<ConstantArray, ArrayType> {
823     static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
824       // Make everyone now use a constant of the new type...
825       std::vector<Constant*> C;
826       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
827         C.push_back(cast<Constant>(OldC->getOperand(i)));
828       Constant *New = ConstantArray::get(NewTy, C);
829       assert(New != OldC && "Didn't replace constant??");
830       OldC->uncheckedReplaceAllUsesWith(New);
831       OldC->destroyConstant();    // This constant is now dead, destroy it.
832     }
833   };
834 }
835
836 static std::vector<Constant*> getValType(ConstantArray *CA) {
837   std::vector<Constant*> Elements;
838   Elements.reserve(CA->getNumOperands());
839   for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
840     Elements.push_back(cast<Constant>(CA->getOperand(i)));
841   return Elements;
842 }
843
844 typedef ValueMap<std::vector<Constant*>, ArrayType, 
845                  ConstantArray, true /*largekey*/> ArrayConstantsTy;
846 static ArrayConstantsTy ArrayConstants;
847
848 Constant *ConstantArray::get(const ArrayType *Ty,
849                              const std::vector<Constant*> &V) {
850   // If this is an all-zero array, return a ConstantAggregateZero object
851   if (!V.empty()) {
852     Constant *C = V[0];
853     if (!C->isNullValue())
854       return ArrayConstants.getOrCreate(Ty, V);
855     for (unsigned i = 1, e = V.size(); i != e; ++i)
856       if (V[i] != C)
857         return ArrayConstants.getOrCreate(Ty, V);
858   }
859   return ConstantAggregateZero::get(Ty);
860 }
861
862 // destroyConstant - Remove the constant from the constant table...
863 //
864 void ConstantArray::destroyConstant() {
865   ArrayConstants.remove(this);
866   destroyConstantImpl();
867 }
868
869 // ConstantArray::get(const string&) - Return an array that is initialized to
870 // contain the specified string.  A null terminator is added to the specified
871 // string so that it may be used in a natural way...
872 //
873 Constant *ConstantArray::get(const std::string &Str) {
874   std::vector<Constant*> ElementVals;
875
876   for (unsigned i = 0; i < Str.length(); ++i)
877     ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
878
879   // Add a null terminator to the string...
880   ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
881
882   ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
883   return ConstantArray::get(ATy, ElementVals);
884 }
885
886 /// isString - This method returns true if the array is an array of sbyte or
887 /// ubyte, and if the elements of the array are all ConstantInt's.
888 bool ConstantArray::isString() const {
889   // Check the element type for sbyte or ubyte...
890   if (getType()->getElementType() != Type::UByteTy &&
891       getType()->getElementType() != Type::SByteTy)
892     return false;
893   // Check the elements to make sure they are all integers, not constant
894   // expressions.
895   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
896     if (!isa<ConstantInt>(getOperand(i)))
897       return false;
898   return true;
899 }
900
901 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
902 // then this method converts the array to an std::string and returns it.
903 // Otherwise, it asserts out.
904 //
905 std::string ConstantArray::getAsString() const {
906   assert(isString() && "Not a string!");
907   std::string Result;
908   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
909     Result += (char)cast<ConstantInt>(getOperand(i))->getRawValue();
910   return Result;
911 }
912
913
914 //---- ConstantStruct::get() implementation...
915 //
916
917 namespace llvm {
918   template<>
919   struct ConvertConstantType<ConstantStruct, StructType> {
920     static void convert(ConstantStruct *OldC, const StructType *NewTy) {
921       // Make everyone now use a constant of the new type...
922       std::vector<Constant*> C;
923       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
924         C.push_back(cast<Constant>(OldC->getOperand(i)));
925       Constant *New = ConstantStruct::get(NewTy, C);
926       assert(New != OldC && "Didn't replace constant??");
927
928       OldC->uncheckedReplaceAllUsesWith(New);
929       OldC->destroyConstant();    // This constant is now dead, destroy it.
930     }
931   };
932 }
933
934 typedef ValueMap<std::vector<Constant*>, StructType,
935                  ConstantStruct, true /*largekey*/> StructConstantsTy;
936 static StructConstantsTy StructConstants;
937
938 static std::vector<Constant*> getValType(ConstantStruct *CS) {
939   std::vector<Constant*> Elements;
940   Elements.reserve(CS->getNumOperands());
941   for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
942     Elements.push_back(cast<Constant>(CS->getOperand(i)));
943   return Elements;
944 }
945
946 Constant *ConstantStruct::get(const StructType *Ty,
947                               const std::vector<Constant*> &V) {
948   // Create a ConstantAggregateZero value if all elements are zeros...
949   for (unsigned i = 0, e = V.size(); i != e; ++i)
950     if (!V[i]->isNullValue())
951       return StructConstants.getOrCreate(Ty, V);
952
953   return ConstantAggregateZero::get(Ty);
954 }
955
956 Constant *ConstantStruct::get(const std::vector<Constant*> &V) {
957   std::vector<const Type*> StructEls;
958   StructEls.reserve(V.size());
959   for (unsigned i = 0, e = V.size(); i != e; ++i)
960     StructEls.push_back(V[i]->getType());
961   return get(StructType::get(StructEls), V);
962 }
963
964 // destroyConstant - Remove the constant from the constant table...
965 //
966 void ConstantStruct::destroyConstant() {
967   StructConstants.remove(this);
968   destroyConstantImpl();
969 }
970
971 //---- ConstantPacked::get() implementation...
972 //
973 namespace llvm {
974   template<>
975   struct ConvertConstantType<ConstantPacked, PackedType> {
976     static void convert(ConstantPacked *OldC, const PackedType *NewTy) {
977       // Make everyone now use a constant of the new type...
978       std::vector<Constant*> C;
979       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
980         C.push_back(cast<Constant>(OldC->getOperand(i)));
981       Constant *New = ConstantPacked::get(NewTy, C);
982       assert(New != OldC && "Didn't replace constant??");
983       OldC->uncheckedReplaceAllUsesWith(New);
984       OldC->destroyConstant();    // This constant is now dead, destroy it.
985     }
986   };
987 }
988
989 static std::vector<Constant*> getValType(ConstantPacked *CP) {
990   std::vector<Constant*> Elements;
991   Elements.reserve(CP->getNumOperands());
992   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
993     Elements.push_back(CP->getOperand(i));
994   return Elements;
995 }
996
997 static ValueMap<std::vector<Constant*>, PackedType,
998                 ConstantPacked> PackedConstants;
999
1000 Constant *ConstantPacked::get(const PackedType *Ty,
1001                               const std::vector<Constant*> &V) {
1002   // If this is an all-zero packed, return a ConstantAggregateZero object
1003   if (!V.empty()) {
1004     Constant *C = V[0];
1005     if (!C->isNullValue())
1006       return PackedConstants.getOrCreate(Ty, V);
1007     for (unsigned i = 1, e = V.size(); i != e; ++i)
1008       if (V[i] != C)
1009         return PackedConstants.getOrCreate(Ty, V);
1010   }
1011   return ConstantAggregateZero::get(Ty);
1012 }
1013
1014 Constant *ConstantPacked::get(const std::vector<Constant*> &V) {
1015   assert(!V.empty() && "Cannot infer type if V is empty");
1016   return get(PackedType::get(V.front()->getType(),V.size()), V);
1017 }
1018
1019 // destroyConstant - Remove the constant from the constant table...
1020 //
1021 void ConstantPacked::destroyConstant() {
1022   PackedConstants.remove(this);
1023   destroyConstantImpl();
1024 }
1025
1026 //---- ConstantPointerNull::get() implementation...
1027 //
1028
1029 namespace llvm {
1030   // ConstantPointerNull does not take extra "value" argument...
1031   template<class ValType>
1032   struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1033     static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1034       return new ConstantPointerNull(Ty);
1035     }
1036   };
1037
1038   template<>
1039   struct ConvertConstantType<ConstantPointerNull, PointerType> {
1040     static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1041       // Make everyone now use a constant of the new type...
1042       Constant *New = ConstantPointerNull::get(NewTy);
1043       assert(New != OldC && "Didn't replace constant??");
1044       OldC->uncheckedReplaceAllUsesWith(New);
1045       OldC->destroyConstant();     // This constant is now dead, destroy it.
1046     }
1047   };
1048 }
1049
1050 static ValueMap<char, PointerType, ConstantPointerNull> NullPtrConstants;
1051
1052 static char getValType(ConstantPointerNull *) {
1053   return 0;
1054 }
1055
1056
1057 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1058   return NullPtrConstants.getOrCreate(Ty, 0);
1059 }
1060
1061 // destroyConstant - Remove the constant from the constant table...
1062 //
1063 void ConstantPointerNull::destroyConstant() {
1064   NullPtrConstants.remove(this);
1065   destroyConstantImpl();
1066 }
1067
1068
1069 //---- UndefValue::get() implementation...
1070 //
1071
1072 namespace llvm {
1073   // UndefValue does not take extra "value" argument...
1074   template<class ValType>
1075   struct ConstantCreator<UndefValue, Type, ValType> {
1076     static UndefValue *create(const Type *Ty, const ValType &V) {
1077       return new UndefValue(Ty);
1078     }
1079   };
1080
1081   template<>
1082   struct ConvertConstantType<UndefValue, Type> {
1083     static void convert(UndefValue *OldC, const Type *NewTy) {
1084       // Make everyone now use a constant of the new type.
1085       Constant *New = UndefValue::get(NewTy);
1086       assert(New != OldC && "Didn't replace constant??");
1087       OldC->uncheckedReplaceAllUsesWith(New);
1088       OldC->destroyConstant();     // This constant is now dead, destroy it.
1089     }
1090   };
1091 }
1092
1093 static ValueMap<char, Type, UndefValue> UndefValueConstants;
1094
1095 static char getValType(UndefValue *) {
1096   return 0;
1097 }
1098
1099
1100 UndefValue *UndefValue::get(const Type *Ty) {
1101   return UndefValueConstants.getOrCreate(Ty, 0);
1102 }
1103
1104 // destroyConstant - Remove the constant from the constant table.
1105 //
1106 void UndefValue::destroyConstant() {
1107   UndefValueConstants.remove(this);
1108   destroyConstantImpl();
1109 }
1110
1111
1112
1113
1114 //---- ConstantExpr::get() implementations...
1115 //
1116 typedef std::pair<unsigned, std::vector<Constant*> > ExprMapKeyType;
1117
1118 namespace llvm {
1119   template<>
1120   struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1121     static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V) {
1122       if (V.first == Instruction::Cast)
1123         return new UnaryConstantExpr(Instruction::Cast, V.second[0], Ty);
1124       if ((V.first >= Instruction::BinaryOpsBegin &&
1125            V.first < Instruction::BinaryOpsEnd) ||
1126           V.first == Instruction::Shl || V.first == Instruction::Shr)
1127         return new BinaryConstantExpr(V.first, V.second[0], V.second[1]);
1128       if (V.first == Instruction::Select)
1129         return new SelectConstantExpr(V.second[0], V.second[1], V.second[2]);
1130
1131       assert(V.first == Instruction::GetElementPtr && "Invalid ConstantExpr!");
1132
1133       std::vector<Constant*> IdxList(V.second.begin()+1, V.second.end());
1134       return new GetElementPtrConstantExpr(V.second[0], IdxList, Ty);
1135     }
1136   };
1137
1138   template<>
1139   struct ConvertConstantType<ConstantExpr, Type> {
1140     static void convert(ConstantExpr *OldC, const Type *NewTy) {
1141       Constant *New;
1142       switch (OldC->getOpcode()) {
1143       case Instruction::Cast:
1144         New = ConstantExpr::getCast(OldC->getOperand(0), NewTy);
1145         break;
1146       case Instruction::Select:
1147         New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1148                                         OldC->getOperand(1),
1149                                         OldC->getOperand(2));
1150         break;
1151       case Instruction::Shl:
1152       case Instruction::Shr:
1153         New = ConstantExpr::getShiftTy(NewTy, OldC->getOpcode(),
1154                                      OldC->getOperand(0), OldC->getOperand(1));
1155         break;
1156       default:
1157         assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1158                OldC->getOpcode() < Instruction::BinaryOpsEnd);
1159         New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1160                                   OldC->getOperand(1));
1161         break;
1162       case Instruction::GetElementPtr:
1163         // Make everyone now use a constant of the new type...
1164         std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1165         New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0), Idx);
1166         break;
1167       }
1168
1169       assert(New != OldC && "Didn't replace constant??");
1170       OldC->uncheckedReplaceAllUsesWith(New);
1171       OldC->destroyConstant();    // This constant is now dead, destroy it.
1172     }
1173   };
1174 } // end namespace llvm
1175
1176
1177 static ExprMapKeyType getValType(ConstantExpr *CE) {
1178   std::vector<Constant*> Operands;
1179   Operands.reserve(CE->getNumOperands());
1180   for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1181     Operands.push_back(cast<Constant>(CE->getOperand(i)));
1182   return ExprMapKeyType(CE->getOpcode(), Operands);
1183 }
1184
1185 static ValueMap<ExprMapKeyType, Type, ConstantExpr> ExprConstants;
1186
1187 Constant *ConstantExpr::getCast(Constant *C, const Type *Ty) {
1188   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1189
1190   if (Constant *FC = ConstantFoldCastInstruction(C, Ty))
1191     return FC;          // Fold a few common cases...
1192
1193   // Look up the constant in the table first to ensure uniqueness
1194   std::vector<Constant*> argVec(1, C);
1195   ExprMapKeyType Key = std::make_pair(Instruction::Cast, argVec);
1196   return ExprConstants.getOrCreate(Ty, Key);
1197 }
1198
1199 Constant *ConstantExpr::getSignExtend(Constant *C, const Type *Ty) {
1200   assert(C->getType()->isIntegral() && Ty->isIntegral() &&
1201          C->getType()->getPrimitiveSize() <= Ty->getPrimitiveSize() &&
1202          "This is an illegal sign extension!");
1203   if (C->getType() != Type::BoolTy) {
1204     C = ConstantExpr::getCast(C, C->getType()->getSignedVersion());
1205     return ConstantExpr::getCast(C, Ty);
1206   } else {
1207     if (C == ConstantBool::True)
1208       return ConstantIntegral::getAllOnesValue(Ty);
1209     else
1210       return ConstantIntegral::getNullValue(Ty);
1211   }
1212 }
1213
1214 Constant *ConstantExpr::getZeroExtend(Constant *C, const Type *Ty) {
1215   assert(C->getType()->isIntegral() && Ty->isIntegral() &&
1216          C->getType()->getPrimitiveSize() <= Ty->getPrimitiveSize() &&
1217          "This is an illegal zero extension!");
1218   if (C->getType() != Type::BoolTy)
1219     C = ConstantExpr::getCast(C, C->getType()->getUnsignedVersion());
1220   return ConstantExpr::getCast(C, Ty);
1221 }
1222
1223 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
1224   // sizeof is implemented as: (ulong) gep (Ty*)null, 1
1225   return getCast(
1226     getGetElementPtr(getNullValue(PointerType::get(Ty)),
1227                  std::vector<Constant*>(1, ConstantInt::get(Type::UIntTy, 1))),
1228     Type::ULongTy);
1229 }
1230
1231 Constant *ConstantExpr::getPtrPtrFromArrayPtr(Constant *C) {
1232   // pointer from array is implemented as: getelementptr arr ptr, 0, 0
1233   static std::vector<Constant*> Indices(2, ConstantUInt::get(Type::UIntTy, 0));
1234
1235   return ConstantExpr::getGetElementPtr(C, Indices);
1236 }
1237
1238 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1239                               Constant *C1, Constant *C2) {
1240   if (Opcode == Instruction::Shl || Opcode == Instruction::Shr)
1241     return getShiftTy(ReqTy, Opcode, C1, C2);
1242   // Check the operands for consistency first
1243   assert((Opcode >= Instruction::BinaryOpsBegin &&
1244           Opcode < Instruction::BinaryOpsEnd) &&
1245          "Invalid opcode in binary constant expression");
1246   assert(C1->getType() == C2->getType() &&
1247          "Operand types in binary constant expression should match");
1248
1249   if (ReqTy == C1->getType() || (Instruction::isRelational(Opcode) &&
1250                                  ReqTy == Type::BoolTy))
1251     if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1252       return FC;          // Fold a few common cases...
1253
1254   std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1255   ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1256   return ExprConstants.getOrCreate(ReqTy, Key);
1257 }
1258
1259 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1260 #ifndef NDEBUG
1261   switch (Opcode) {
1262   case Instruction::Add: case Instruction::Sub:
1263   case Instruction::Mul: case Instruction::Div:
1264   case Instruction::Rem:
1265     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1266     assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint()) &&
1267            "Tried to create an arithmetic operation on a non-arithmetic type!");
1268     break;
1269   case Instruction::And:
1270   case Instruction::Or:
1271   case Instruction::Xor:
1272     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1273     assert(C1->getType()->isIntegral() &&
1274            "Tried to create a logical operation on a non-integral type!");
1275     break;
1276   case Instruction::SetLT: case Instruction::SetGT: case Instruction::SetLE:
1277   case Instruction::SetGE: case Instruction::SetEQ: case Instruction::SetNE:
1278     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1279     break;
1280   case Instruction::Shl:
1281   case Instruction::Shr:
1282     assert(C2->getType() == Type::UByteTy && "Shift should be by ubyte!");
1283     assert(C1->getType()->isInteger() &&
1284            "Tried to create a shift operation on a non-integer type!");
1285     break;
1286   default:
1287     break;
1288   }
1289 #endif
1290
1291   if (Instruction::isRelational(Opcode))
1292     return getTy(Type::BoolTy, Opcode, C1, C2);
1293   else
1294     return getTy(C1->getType(), Opcode, C1, C2);
1295 }
1296
1297 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1298                                     Constant *V1, Constant *V2) {
1299   assert(C->getType() == Type::BoolTy && "Select condition must be bool!");
1300   assert(V1->getType() == V2->getType() && "Select value types must match!");
1301   assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1302
1303   if (ReqTy == V1->getType())
1304     if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1305       return SC;        // Fold common cases
1306
1307   std::vector<Constant*> argVec(3, C);
1308   argVec[1] = V1;
1309   argVec[2] = V2;
1310   ExprMapKeyType Key = std::make_pair(Instruction::Select, argVec);
1311   return ExprConstants.getOrCreate(ReqTy, Key);
1312 }
1313
1314 /// getShiftTy - Return a shift left or shift right constant expr
1315 Constant *ConstantExpr::getShiftTy(const Type *ReqTy, unsigned Opcode,
1316                                    Constant *C1, Constant *C2) {
1317   // Check the operands for consistency first
1318   assert((Opcode == Instruction::Shl ||
1319           Opcode == Instruction::Shr) &&
1320          "Invalid opcode in binary constant expression");
1321   assert(C1->getType()->isIntegral() && C2->getType() == Type::UByteTy &&
1322          "Invalid operand types for Shift constant expr!");
1323
1324   if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1325     return FC;          // Fold a few common cases...
1326
1327   // Look up the constant in the table first to ensure uniqueness
1328   std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1329   ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1330   return ExprConstants.getOrCreate(ReqTy, Key);
1331 }
1332
1333
1334 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1335                                            const std::vector<Value*> &IdxList) {
1336   assert(GetElementPtrInst::getIndexedType(C->getType(), IdxList, true) &&
1337          "GEP indices invalid!");
1338
1339   if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
1340     return FC;          // Fold a few common cases...
1341
1342   assert(isa<PointerType>(C->getType()) &&
1343          "Non-pointer type for constant GetElementPtr expression");
1344   // Look up the constant in the table first to ensure uniqueness
1345   std::vector<Constant*> ArgVec;
1346   ArgVec.reserve(IdxList.size()+1);
1347   ArgVec.push_back(C);
1348   for (unsigned i = 0, e = IdxList.size(); i != e; ++i)
1349     ArgVec.push_back(cast<Constant>(IdxList[i]));
1350   const ExprMapKeyType &Key = std::make_pair(Instruction::GetElementPtr,ArgVec);
1351   return ExprConstants.getOrCreate(ReqTy, Key);
1352 }
1353
1354 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1355                                          const std::vector<Constant*> &IdxList){
1356   // Get the result type of the getelementptr!
1357   std::vector<Value*> VIdxList(IdxList.begin(), IdxList.end());
1358
1359   const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), VIdxList,
1360                                                      true);
1361   assert(Ty && "GEP indices invalid!");
1362   return getGetElementPtrTy(PointerType::get(Ty), C, VIdxList);
1363 }
1364
1365 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1366                                          const std::vector<Value*> &IdxList) {
1367   // Get the result type of the getelementptr!
1368   const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
1369                                                      true);
1370   assert(Ty && "GEP indices invalid!");
1371   return getGetElementPtrTy(PointerType::get(Ty), C, IdxList);
1372 }
1373
1374
1375 // destroyConstant - Remove the constant from the constant table...
1376 //
1377 void ConstantExpr::destroyConstant() {
1378   ExprConstants.remove(this);
1379   destroyConstantImpl();
1380 }
1381
1382 const char *ConstantExpr::getOpcodeName() const {
1383   return Instruction::getOpcodeName(getOpcode());
1384 }
1385
1386 //===----------------------------------------------------------------------===//
1387 //                replaceUsesOfWithOnConstant implementations
1388
1389 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1390                                                 Use *U) {
1391   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1392   Constant *ToC = cast<Constant>(To);
1393   
1394   std::pair<ArrayConstantsTy::MapKey, ConstantArray*> Lookup;
1395   Lookup.first.first = getType();
1396   Lookup.second = this;
1397   std::vector<Constant*> &Values = Lookup.first.second;
1398   Values.reserve(getNumOperands());  // Build replacement array.
1399   
1400   // Fill values with the modified operands of the constant array.  Also, 
1401   // compute whether this turns into an all-zeros array.
1402   bool isAllZeros = ToC->isNullValue();
1403   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1404     Constant *Val = getOperand(i);
1405     if (Val == From) Val = ToC;
1406     Values.push_back(Val);
1407     if (isAllZeros) isAllZeros = Val->isNullValue();
1408   }
1409   
1410   Constant *Replacement = 0;
1411   if (isAllZeros) {
1412     Replacement = ConstantAggregateZero::get(getType());
1413   } else {
1414     // Check to see if we have this array type already.
1415     bool Exists;
1416     ArrayConstantsTy::MapIterator I =
1417       ArrayConstants.InsertOrGetItem(Lookup, Exists);
1418     
1419     if (Exists) {
1420       Replacement = I->second;
1421     } else {
1422       // Okay, the new shape doesn't exist in the system yet.  Instead of
1423       // creating a new constant array, inserting it, replaceallusesof'ing the
1424       // old with the new, then deleting the old... just update the current one
1425       // in place!
1426       ArrayConstants.SimpleRemove(this);   // Remove old shape from the map.
1427
1428       // Update the inverse map so that we know that this constant is now
1429       // located at descriptor I.
1430       ArrayConstants.UpdateInverseMap(this, I);
1431       
1432       // Update to the new values.
1433       for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1434         if (getOperand(i) == From)
1435           setOperand(i, ToC);
1436       return;
1437     }
1438   }
1439  
1440   // Otherwise, I do need to replace this with an existing value.
1441   assert(Replacement != this && "I didn't contain From!");
1442   
1443   // Everyone using this now uses the replacement.
1444   uncheckedReplaceAllUsesWith(Replacement);
1445   
1446   // Delete the old constant!
1447   destroyConstant();
1448 }
1449
1450 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
1451                                                  Use *U) {
1452   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1453   Constant *ToC = cast<Constant>(To);
1454
1455   std::pair<StructConstantsTy::MapKey, ConstantStruct*> Lookup;
1456   Lookup.first.first = getType();
1457   Lookup.second = this;
1458   std::vector<Constant*> &Values = Lookup.first.second;
1459   Values.reserve(getNumOperands());  // Build replacement struct.
1460   
1461   // Fill values with the modified operands of the constant struct.  Also, 
1462   // compute whether this turns into an all-zeros struct.
1463   bool isAllZeros = ToC->isNullValue();
1464   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1465     Constant *Val = getOperand(i);
1466     if (Val == From) Val = ToC;
1467     Values.push_back(Val);
1468     if (isAllZeros) isAllZeros = Val->isNullValue();
1469   }
1470     
1471   Constant *Replacement = 0;
1472   if (isAllZeros) {
1473     Replacement = ConstantAggregateZero::get(getType());
1474   } else {
1475     // Check to see if we have this array type already.
1476     bool Exists;
1477     StructConstantsTy::MapIterator I =
1478     StructConstants.InsertOrGetItem(Lookup, Exists);
1479     
1480     if (Exists) {
1481       Replacement = I->second;
1482     } else {
1483       // Okay, the new shape doesn't exist in the system yet.  Instead of
1484       // creating a new constant struct, inserting it, replaceallusesof'ing the
1485       // old with the new, then deleting the old... just update the current one
1486       // in place!
1487       StructConstants.SimpleRemove(this);   // Remove old shape from the map.
1488
1489       // Update the inverse map so that we know that this constant is now
1490       // located at descriptor I.
1491       StructConstants.UpdateInverseMap(this, I);
1492       
1493       // Update to the new values.
1494       for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1495         if (getOperand(i) == From)
1496           setOperand(i, ToC);
1497       return;
1498     }
1499   }
1500   
1501   assert(Replacement != this && "I didn't contain From!");
1502   
1503   // Everyone using this now uses the replacement.
1504   uncheckedReplaceAllUsesWith(Replacement);
1505   
1506   // Delete the old constant!
1507   destroyConstant();
1508 }
1509
1510 void ConstantPacked::replaceUsesOfWithOnConstant(Value *From, Value *To,
1511                                                  Use *U) {
1512   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1513   
1514   std::vector<Constant*> Values;
1515   Values.reserve(getNumOperands());  // Build replacement array...
1516   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1517     Constant *Val = getOperand(i);
1518     if (Val == From) Val = cast<Constant>(To);
1519     Values.push_back(Val);
1520   }
1521   
1522   Constant *Replacement = ConstantPacked::get(getType(), Values);
1523   assert(Replacement != this && "I didn't contain From!");
1524   
1525   // Everyone using this now uses the replacement.
1526   uncheckedReplaceAllUsesWith(Replacement);
1527   
1528   // Delete the old constant!
1529   destroyConstant();
1530 }
1531
1532 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
1533                                                Use *U) {
1534   assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
1535   Constant *To = cast<Constant>(ToV);
1536   
1537   Constant *Replacement = 0;
1538   if (getOpcode() == Instruction::GetElementPtr) {
1539     std::vector<Constant*> Indices;
1540     Constant *Pointer = getOperand(0);
1541     Indices.reserve(getNumOperands()-1);
1542     if (Pointer == From) Pointer = To;
1543     
1544     for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1545       Constant *Val = getOperand(i);
1546       if (Val == From) Val = To;
1547       Indices.push_back(Val);
1548     }
1549     Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
1550   } else if (getOpcode() == Instruction::Cast) {
1551     assert(getOperand(0) == From && "Cast only has one use!");
1552     Replacement = ConstantExpr::getCast(To, getType());
1553   } else if (getOpcode() == Instruction::Select) {
1554     Constant *C1 = getOperand(0);
1555     Constant *C2 = getOperand(1);
1556     Constant *C3 = getOperand(2);
1557     if (C1 == From) C1 = To;
1558     if (C2 == From) C2 = To;
1559     if (C3 == From) C3 = To;
1560     Replacement = ConstantExpr::getSelect(C1, C2, C3);
1561   } else if (getNumOperands() == 2) {
1562     Constant *C1 = getOperand(0);
1563     Constant *C2 = getOperand(1);
1564     if (C1 == From) C1 = To;
1565     if (C2 == From) C2 = To;
1566     Replacement = ConstantExpr::get(getOpcode(), C1, C2);
1567   } else {
1568     assert(0 && "Unknown ConstantExpr type!");
1569     return;
1570   }
1571   
1572   assert(Replacement != this && "I didn't contain From!");
1573   
1574   // Everyone using this now uses the replacement.
1575   uncheckedReplaceAllUsesWith(Replacement);
1576   
1577   // Delete the old constant!
1578   destroyConstant();
1579 }
1580
1581
1582
1583 /// clearAllValueMaps - This method frees all internal memory used by the
1584 /// constant subsystem, which can be used in environments where this memory
1585 /// is otherwise reported as a leak.
1586 void Constant::clearAllValueMaps() {
1587   std::vector<Constant *> Constants;
1588
1589   DoubleConstants.clear(Constants);
1590   FloatConstants.clear(Constants);
1591   SIntConstants.clear(Constants);
1592   UIntConstants.clear(Constants);
1593   AggZeroConstants.clear(Constants);
1594   ArrayConstants.clear(Constants);
1595   StructConstants.clear(Constants);
1596   PackedConstants.clear(Constants);
1597   NullPtrConstants.clear(Constants);
1598   UndefValueConstants.clear(Constants);
1599   ExprConstants.clear(Constants);
1600
1601   for (std::vector<Constant *>::iterator I = Constants.begin(),
1602        E = Constants.end(); I != E; ++I)
1603     (*I)->dropAllReferences();
1604   for (std::vector<Constant *>::iterator I = Constants.begin(),
1605        E = Constants.end(); I != E; ++I)
1606     (*I)->destroyConstantImpl();
1607   Constants.clear();
1608 }