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