Added LLVM project notice to the top of every C++ source file.
[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 "llvm/ConstantHandling.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/iMemory.h"
18 #include "llvm/SymbolTable.h"
19 #include "llvm/Module.h"
20 #include "Support/StringExtras.h"
21 #include <algorithm>
22
23 ConstantBool *ConstantBool::True  = new ConstantBool(true);
24 ConstantBool *ConstantBool::False = new ConstantBool(false);
25
26
27 //===----------------------------------------------------------------------===//
28 //                              Constant Class
29 //===----------------------------------------------------------------------===//
30
31 // Specialize setName to take care of symbol table majik
32 void Constant::setName(const std::string &Name, SymbolTable *ST) {
33   assert(ST && "Type::setName - Must provide symbol table argument!");
34
35   if (Name.size()) ST->insert(Name, this);
36 }
37
38 void Constant::destroyConstantImpl() {
39   // When a Constant is destroyed, there may be lingering
40   // references to the constant by other constants in the constant pool.  These
41   // constants are implicitly dependent on the module that is being deleted,
42   // but they don't know that.  Because we only find out when the CPV is
43   // deleted, we must now notify all of our users (that should only be
44   // Constants) that they are, in fact, invalid now and should be deleted.
45   //
46   while (!use_empty()) {
47     Value *V = use_back();
48 #ifndef NDEBUG      // Only in -g mode...
49     if (!isa<Constant>(V))
50       std::cerr << "While deleting: " << *this
51                 << "\n\nUse still stuck around after Def is destroyed: "
52                 << *V << "\n\n";
53 #endif
54     assert(isa<Constant>(V) && "References remain to Constant being destroyed");
55     Constant *CPV = cast<Constant>(V);
56     CPV->destroyConstant();
57
58     // The constant should remove itself from our use list...
59     assert((use_empty() || use_back() != V) && "Constant not removed!");
60   }
61
62   // Value has no outstanding references it is safe to delete it now...
63   delete this;
64 }
65
66 // Static constructor to create a '0' constant of arbitrary type...
67 Constant *Constant::getNullValue(const Type *Ty) {
68   switch (Ty->getPrimitiveID()) {
69   case Type::BoolTyID: {
70     static Constant *NullBool = ConstantBool::get(false);
71     return NullBool;
72   }
73   case Type::SByteTyID: {
74     static Constant *NullSByte = ConstantSInt::get(Type::SByteTy, 0);
75     return NullSByte;
76   }
77   case Type::UByteTyID: {
78     static Constant *NullUByte = ConstantUInt::get(Type::UByteTy, 0);
79     return NullUByte;
80   }
81   case Type::ShortTyID: {
82     static Constant *NullShort = ConstantSInt::get(Type::ShortTy, 0);
83     return NullShort;
84   }
85   case Type::UShortTyID: {
86     static Constant *NullUShort = ConstantUInt::get(Type::UShortTy, 0);
87     return NullUShort;
88   }
89   case Type::IntTyID: {
90     static Constant *NullInt = ConstantSInt::get(Type::IntTy, 0);
91     return NullInt;
92   }
93   case Type::UIntTyID: {
94     static Constant *NullUInt = ConstantUInt::get(Type::UIntTy, 0);
95     return NullUInt;
96   }
97   case Type::LongTyID: {
98     static Constant *NullLong = ConstantSInt::get(Type::LongTy, 0);
99     return NullLong;
100   }
101   case Type::ULongTyID: {
102     static Constant *NullULong = ConstantUInt::get(Type::ULongTy, 0);
103     return NullULong;
104   }
105
106   case Type::FloatTyID: {
107     static Constant *NullFloat = ConstantFP::get(Type::FloatTy, 0);
108     return NullFloat;
109   }
110   case Type::DoubleTyID: {
111     static Constant *NullDouble = ConstantFP::get(Type::DoubleTy, 0);
112     return NullDouble;
113   }
114
115   case Type::PointerTyID: 
116     return ConstantPointerNull::get(cast<PointerType>(Ty));
117
118   case Type::StructTyID: {
119     const StructType *ST = cast<StructType>(Ty);
120     const StructType::ElementTypes &ETs = ST->getElementTypes();
121     std::vector<Constant*> Elements;
122     Elements.resize(ETs.size());
123     for (unsigned i = 0, e = ETs.size(); i != e; ++i)
124       Elements[i] = Constant::getNullValue(ETs[i]);
125     return ConstantStruct::get(ST, Elements);
126   }
127   case Type::ArrayTyID: {
128     const ArrayType *AT = cast<ArrayType>(Ty);
129     Constant *El = Constant::getNullValue(AT->getElementType());
130     unsigned NumElements = AT->getNumElements();
131     return ConstantArray::get(AT, std::vector<Constant*>(NumElements, El));
132   }
133   default:
134     // Function, Type, Label, or Opaque type?
135     assert(0 && "Cannot create a null constant of that type!");
136     return 0;
137   }
138 }
139
140 // Static constructor to create the maximum constant of an integral type...
141 ConstantIntegral *ConstantIntegral::getMaxValue(const Type *Ty) {
142   switch (Ty->getPrimitiveID()) {
143   case Type::BoolTyID:   return ConstantBool::True;
144   case Type::SByteTyID:
145   case Type::ShortTyID:
146   case Type::IntTyID:
147   case Type::LongTyID: {
148     // Calculate 011111111111111... 
149     unsigned TypeBits = Ty->getPrimitiveSize()*8;
150     int64_t Val = INT64_MAX;             // All ones
151     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
152     return ConstantSInt::get(Ty, Val);
153   }
154
155   case Type::UByteTyID:
156   case Type::UShortTyID:
157   case Type::UIntTyID:
158   case Type::ULongTyID:  return getAllOnesValue(Ty);
159
160   default: return 0;
161   }
162 }
163
164 // Static constructor to create the minimum constant for an integral type...
165 ConstantIntegral *ConstantIntegral::getMinValue(const Type *Ty) {
166   switch (Ty->getPrimitiveID()) {
167   case Type::BoolTyID:   return ConstantBool::False;
168   case Type::SByteTyID:
169   case Type::ShortTyID:
170   case Type::IntTyID:
171   case Type::LongTyID: {
172      // Calculate 1111111111000000000000 
173      unsigned TypeBits = Ty->getPrimitiveSize()*8;
174      int64_t Val = -1;                    // All ones
175      Val <<= TypeBits-1;                  // Shift over to the right spot
176      return ConstantSInt::get(Ty, Val);
177   }
178
179   case Type::UByteTyID:
180   case Type::UShortTyID:
181   case Type::UIntTyID:
182   case Type::ULongTyID:  return ConstantUInt::get(Ty, 0);
183
184   default: return 0;
185   }
186 }
187
188 // Static constructor to create an integral constant with all bits set
189 ConstantIntegral *ConstantIntegral::getAllOnesValue(const Type *Ty) {
190   switch (Ty->getPrimitiveID()) {
191   case Type::BoolTyID:   return ConstantBool::True;
192   case Type::SByteTyID:
193   case Type::ShortTyID:
194   case Type::IntTyID:
195   case Type::LongTyID:   return ConstantSInt::get(Ty, -1);
196
197   case Type::UByteTyID:
198   case Type::UShortTyID:
199   case Type::UIntTyID:
200   case Type::ULongTyID: {
201     // Calculate ~0 of the right type...
202     unsigned TypeBits = Ty->getPrimitiveSize()*8;
203     uint64_t Val = ~0ULL;                // All ones
204     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
205     return ConstantUInt::get(Ty, Val);
206   }
207   default: return 0;
208   }
209 }
210
211 bool ConstantUInt::isAllOnesValue() const {
212   unsigned TypeBits = getType()->getPrimitiveSize()*8;
213   uint64_t Val = ~0ULL;                // All ones
214   Val >>= 64-TypeBits;                 // Shift out inappropriate bits
215   return getValue() == Val;
216 }
217
218
219 //===----------------------------------------------------------------------===//
220 //                            ConstantXXX Classes
221 //===----------------------------------------------------------------------===//
222
223 //===----------------------------------------------------------------------===//
224 //                             Normal Constructors
225
226 ConstantBool::ConstantBool(bool V) : ConstantIntegral(Type::BoolTy) {
227   Val = V;
228 }
229
230 ConstantInt::ConstantInt(const Type *Ty, uint64_t V) : ConstantIntegral(Ty) {
231   Val.Unsigned = V;
232 }
233
234 ConstantSInt::ConstantSInt(const Type *Ty, int64_t V) : ConstantInt(Ty, V) {
235   assert(Ty->isInteger() && Ty->isSigned() &&
236          "Illegal type for unsigned integer constant!");
237   assert(isValueValidForType(Ty, V) && "Value too large for type!");
238 }
239
240 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V) : ConstantInt(Ty, V) {
241   assert(Ty->isInteger() && Ty->isUnsigned() &&
242          "Illegal type for unsigned integer constant!");
243   assert(isValueValidForType(Ty, V) && "Value too large for type!");
244 }
245
246 ConstantFP::ConstantFP(const Type *Ty, double V) : Constant(Ty) {
247   assert(isValueValidForType(Ty, V) && "Value too large for type!");
248   Val = V;
249 }
250
251 ConstantArray::ConstantArray(const ArrayType *T,
252                              const std::vector<Constant*> &V) : Constant(T) {
253   Operands.reserve(V.size());
254   for (unsigned i = 0, e = V.size(); i != e; ++i) {
255     assert(V[i]->getType() == T->getElementType() ||
256            (T->isAbstract() &&
257             V[i]->getType()->getPrimitiveID() ==
258             T->getElementType()->getPrimitiveID()));
259     Operands.push_back(Use(V[i], this));
260   }
261 }
262
263 ConstantStruct::ConstantStruct(const StructType *T,
264                                const std::vector<Constant*> &V) : Constant(T) {
265   const StructType::ElementTypes &ETypes = T->getElementTypes();
266   assert(V.size() == ETypes.size() &&
267          "Invalid initializer vector for constant structure");
268   Operands.reserve(V.size());
269   for (unsigned i = 0, e = V.size(); i != e; ++i) {
270     assert((V[i]->getType() == ETypes[i] ||
271             (ETypes[i]->isAbstract() &&
272              ETypes[i]->getPrimitiveID()==V[i]->getType()->getPrimitiveID())) &&
273            "Initializer for struct element doesn't match struct element type!");
274     Operands.push_back(Use(V[i], this));
275   }
276 }
277
278 ConstantPointerRef::ConstantPointerRef(GlobalValue *GV)
279   : ConstantPointer(GV->getType()) {
280   Operands.push_back(Use(GV, this));
281 }
282
283 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
284   : Constant(Ty), iType(Opcode) {
285   Operands.push_back(Use(C, this));
286 }
287
288 static bool isSetCC(unsigned Opcode) {
289   return Opcode == Instruction::SetEQ || Opcode == Instruction::SetNE ||
290          Opcode == Instruction::SetLT || Opcode == Instruction::SetGT ||
291          Opcode == Instruction::SetLE || Opcode == Instruction::SetGE;
292 }
293
294 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
295   : Constant(isSetCC(Opcode) ? Type::BoolTy : C1->getType()), iType(Opcode) {
296   Operands.push_back(Use(C1, this));
297   Operands.push_back(Use(C2, this));
298 }
299
300 ConstantExpr::ConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
301                            const Type *DestTy)
302   : Constant(DestTy), iType(Instruction::GetElementPtr) {
303   Operands.reserve(1+IdxList.size());
304   Operands.push_back(Use(C, this));
305   for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
306     Operands.push_back(Use(IdxList[i], this));
307 }
308
309
310
311 //===----------------------------------------------------------------------===//
312 //                           classof implementations
313
314 bool ConstantIntegral::classof(const Constant *CPV) {
315   return CPV->getType()->isIntegral() && !isa<ConstantExpr>(CPV);
316 }
317
318 bool ConstantInt::classof(const Constant *CPV) {
319   return CPV->getType()->isInteger() && !isa<ConstantExpr>(CPV);
320 }
321 bool ConstantSInt::classof(const Constant *CPV) {
322   return CPV->getType()->isSigned() && !isa<ConstantExpr>(CPV);
323 }
324 bool ConstantUInt::classof(const Constant *CPV) {
325   return CPV->getType()->isUnsigned() && !isa<ConstantExpr>(CPV);
326 }
327 bool ConstantFP::classof(const Constant *CPV) {
328   const Type *Ty = CPV->getType();
329   return ((Ty == Type::FloatTy || Ty == Type::DoubleTy) &&
330           !isa<ConstantExpr>(CPV));
331 }
332 bool ConstantArray::classof(const Constant *CPV) {
333   return isa<ArrayType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
334 }
335 bool ConstantStruct::classof(const Constant *CPV) {
336   return isa<StructType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
337 }
338 bool ConstantPointer::classof(const Constant *CPV) {
339   return (isa<PointerType>(CPV->getType()) && !isa<ConstantExpr>(CPV));
340 }
341
342
343
344 //===----------------------------------------------------------------------===//
345 //                      isValueValidForType implementations
346
347 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
348   switch (Ty->getPrimitiveID()) {
349   default:
350     return false;         // These can't be represented as integers!!!
351
352     // Signed types...
353   case Type::SByteTyID:
354     return (Val <= INT8_MAX && Val >= INT8_MIN);
355   case Type::ShortTyID:
356     return (Val <= INT16_MAX && Val >= INT16_MIN);
357   case Type::IntTyID:
358     return (Val <= INT32_MAX && Val >= INT32_MIN);
359   case Type::LongTyID:
360     return true;          // This is the largest type...
361   }
362   assert(0 && "WTF?");
363   return false;
364 }
365
366 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
367   switch (Ty->getPrimitiveID()) {
368   default:
369     return false;         // These can't be represented as integers!!!
370
371     // Unsigned types...
372   case Type::UByteTyID:
373     return (Val <= UINT8_MAX);
374   case Type::UShortTyID:
375     return (Val <= UINT16_MAX);
376   case Type::UIntTyID:
377     return (Val <= UINT32_MAX);
378   case Type::ULongTyID:
379     return true;          // This is the largest type...
380   }
381   assert(0 && "WTF?");
382   return false;
383 }
384
385 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
386   switch (Ty->getPrimitiveID()) {
387   default:
388     return false;         // These can't be represented as floating point!
389
390     // TODO: Figure out how to test if a double can be cast to a float!
391   case Type::FloatTyID:
392   case Type::DoubleTyID:
393     return true;          // This is the largest type...
394   }
395 };
396
397 //===----------------------------------------------------------------------===//
398 //                replaceUsesOfWithOnConstant implementations
399
400 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
401                                                 bool DisableChecking) {
402   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
403
404   std::vector<Constant*> Values;
405   Values.reserve(getValues().size());  // Build replacement array...
406   for (unsigned i = 0, e = getValues().size(); i != e; ++i) {
407     Constant *Val = cast<Constant>(getValues()[i]);
408     if (Val == From) Val = cast<Constant>(To);
409     Values.push_back(Val);
410   }
411   
412   ConstantArray *Replacement = ConstantArray::get(getType(), Values);
413   assert(Replacement != this && "I didn't contain From!");
414
415   // Everyone using this now uses the replacement...
416   if (DisableChecking)
417     uncheckedReplaceAllUsesWith(Replacement);
418   else
419     replaceAllUsesWith(Replacement);
420   
421   // Delete the old constant!
422   destroyConstant();  
423 }
424
425 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
426                                                  bool DisableChecking) {
427   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
428
429   std::vector<Constant*> Values;
430   Values.reserve(getValues().size());
431   for (unsigned i = 0, e = getValues().size(); i != e; ++i) {
432     Constant *Val = cast<Constant>(getValues()[i]);
433     if (Val == From) Val = cast<Constant>(To);
434     Values.push_back(Val);
435   }
436   
437   ConstantStruct *Replacement = ConstantStruct::get(getType(), Values);
438   assert(Replacement != this && "I didn't contain From!");
439
440   // Everyone using this now uses the replacement...
441   if (DisableChecking)
442     uncheckedReplaceAllUsesWith(Replacement);
443   else
444     replaceAllUsesWith(Replacement);
445   
446   // Delete the old constant!
447   destroyConstant();
448 }
449
450 void ConstantPointerRef::replaceUsesOfWithOnConstant(Value *From, Value *To,
451                                                      bool DisableChecking) {
452   if (isa<GlobalValue>(To)) {
453     assert(From == getOperand(0) && "Doesn't contain from!");
454     ConstantPointerRef *Replacement =
455       ConstantPointerRef::get(cast<GlobalValue>(To));
456     
457     // Everyone using this now uses the replacement...
458     if (DisableChecking)
459       uncheckedReplaceAllUsesWith(Replacement);
460     else
461       replaceAllUsesWith(Replacement);
462     
463   } else {
464     // Just replace ourselves with the To value specified.
465     if (DisableChecking)
466       uncheckedReplaceAllUsesWith(To);
467     else
468       replaceAllUsesWith(To);
469   }
470
471   // Delete the old constant!
472   destroyConstant();
473 }
474
475 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
476                                                bool DisableChecking) {
477   assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
478   Constant *To = cast<Constant>(ToV);
479
480   Constant *Replacement = 0;
481   if (getOpcode() == Instruction::GetElementPtr) {
482     std::vector<Constant*> Indices;
483     Constant *Pointer = getOperand(0);
484     Indices.reserve(getNumOperands()-1);
485     if (Pointer == From) Pointer = To;
486     
487     for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
488       Constant *Val = getOperand(i);
489       if (Val == From) Val = To;
490       Indices.push_back(Val);
491     }
492     Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
493   } else if (getOpcode() == Instruction::Cast) {
494     assert(getOperand(0) == From && "Cast only has one use!");
495     Replacement = ConstantExpr::getCast(To, getType());
496   } else if (getNumOperands() == 2) {
497     Constant *C1 = getOperand(0);
498     Constant *C2 = getOperand(1);
499     if (C1 == From) C1 = To;
500     if (C2 == From) C2 = To;
501     Replacement = ConstantExpr::get(getOpcode(), C1, C2);
502   } else {
503     assert(0 && "Unknown ConstantExpr type!");
504     return;
505   }
506   
507   assert(Replacement != this && "I didn't contain From!");
508
509   // Everyone using this now uses the replacement...
510   if (DisableChecking)
511     uncheckedReplaceAllUsesWith(Replacement);
512   else
513     replaceAllUsesWith(Replacement);
514   
515   // Delete the old constant!
516   destroyConstant();
517 }
518
519 //===----------------------------------------------------------------------===//
520 //                      Factory Function Implementation
521
522 // ConstantCreator - A class that is used to create constants by
523 // ValueMap*.  This class should be partially specialized if there is
524 // something strange that needs to be done to interface to the ctor for the
525 // constant.
526 //
527 template<class ConstantClass, class TypeClass, class ValType>
528 struct ConstantCreator {
529   static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
530     return new ConstantClass(Ty, V);
531   }
532 };
533
534 template<class ConstantClass, class TypeClass>
535 struct ConvertConstantType {
536   static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
537     assert(0 && "This type cannot be converted!\n");
538     abort();
539   }
540 };
541
542 namespace {
543   template<class ValType, class TypeClass, class ConstantClass>
544   class ValueMap : public AbstractTypeUser {
545     typedef std::pair<const TypeClass*, ValType> MapKey;
546     typedef std::map<MapKey, ConstantClass *> MapTy;
547     typedef typename MapTy::iterator MapIterator;
548     MapTy Map;
549
550     typedef std::map<const TypeClass*, MapIterator> AbstractTypeMapTy;
551     AbstractTypeMapTy AbstractTypeMap;
552   public:
553     // getOrCreate - Return the specified constant from the map, creating it if
554     // necessary.
555     ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
556       MapKey Lookup(Ty, V);
557       MapIterator I = Map.lower_bound(Lookup);
558       if (I != Map.end() && I->first == Lookup)
559         return I->second;  // Is it in the map?
560
561       // If no preexisting value, create one now...
562       ConstantClass *Result =
563         ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
564
565
566       /// FIXME: why does this assert fail when loading 176.gcc?
567       //assert(Result->getType() == Ty && "Type specified is not correct!");
568       I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
569
570       // If the type of the constant is abstract, make sure that an entry exists
571       // for it in the AbstractTypeMap.
572       if (Ty->isAbstract()) {
573         typename AbstractTypeMapTy::iterator TI =
574           AbstractTypeMap.lower_bound(Ty);
575
576         if (TI == AbstractTypeMap.end() || TI->first != Ty) {
577           // Add ourselves to the ATU list of the type.
578           cast<DerivedType>(Ty)->addAbstractTypeUser(this);
579
580           AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
581         }
582       }
583       return Result;
584     }
585     
586     void remove(ConstantClass *CP) {
587       // FIXME: This should not use a linear scan.  If this gets to be a
588       // performance problem, someone should look at this.
589       MapIterator I = Map.begin();
590       for (MapIterator E = Map.end(); I != E && I->second != CP; ++I)
591         /* empty */;
592       
593       assert(I != Map.end() && "Constant not found in constant table!");
594
595       // Now that we found the entry, make sure this isn't the entry that
596       // the AbstractTypeMap points to.
597       const TypeClass *Ty = I->first.first;
598       if (Ty->isAbstract()) {
599         assert(AbstractTypeMap.count(Ty) &&
600                "Abstract type not in AbstractTypeMap?");
601         MapIterator &ATMEntryIt = AbstractTypeMap[Ty];
602         if (ATMEntryIt == I) {
603           // Yes, we are removing the representative entry for this type.
604           // See if there are any other entries of the same type.
605           MapIterator TmpIt = ATMEntryIt;
606           
607           // First check the entry before this one...
608           if (TmpIt != Map.begin()) {
609             --TmpIt;
610             if (TmpIt->first.first != Ty) // Not the same type, move back...
611               ++TmpIt;
612           }
613           
614           // If we didn't find the same type, try to move forward...
615           if (TmpIt == ATMEntryIt) {
616             ++TmpIt;
617             if (TmpIt == Map.end() || TmpIt->first.first != Ty)
618               --TmpIt;   // No entry afterwards with the same type
619           }
620
621           // If there is another entry in the map of the same abstract type,
622           // update the AbstractTypeMap entry now.
623           if (TmpIt != ATMEntryIt) {
624             ATMEntryIt = TmpIt;
625           } else {
626             // Otherwise, we are removing the last instance of this type
627             // from the table.  Remove from the ATM, and from user list.
628             cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
629             AbstractTypeMap.erase(Ty);
630           }
631         }
632       }
633       
634       Map.erase(I);
635     }
636
637     void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
638       typename AbstractTypeMapTy::iterator I = 
639         AbstractTypeMap.find(cast<TypeClass>(OldTy));
640
641       assert(I != AbstractTypeMap.end() &&
642              "Abstract type not in AbstractTypeMap?");
643
644       // Convert a constant at a time until the last one is gone.  The last one
645       // leaving will remove() itself, causing the AbstractTypeMapEntry to be
646       // eliminated eventually.
647       do {
648         ConvertConstantType<ConstantClass,
649                             TypeClass>::convert(I->second->second,
650                                                 cast<TypeClass>(NewTy));
651
652         I = AbstractTypeMap.find(cast<TypeClass>(OldTy));
653       } while (I != AbstractTypeMap.end());
654     }
655
656     // If the type became concrete without being refined to any other existing
657     // type, we just remove ourselves from the ATU list.
658     void typeBecameConcrete(const DerivedType *AbsTy) {
659       AbsTy->removeAbstractTypeUser(this);
660     }
661
662     void dump() const {
663       std::cerr << "Constant.cpp: ValueMap\n";
664     }
665   };
666 }
667
668
669
670 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
671 //
672 static ValueMap< int64_t, Type, ConstantSInt> SIntConstants;
673 static ValueMap<uint64_t, Type, ConstantUInt> UIntConstants;
674
675 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
676   return SIntConstants.getOrCreate(Ty, V);
677 }
678
679 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
680   return UIntConstants.getOrCreate(Ty, V);
681 }
682
683 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
684   assert(V <= 127 && "Can only be used with very small positive constants!");
685   if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
686   return ConstantUInt::get(Ty, V);
687 }
688
689 //---- ConstantFP::get() implementation...
690 //
691 static ValueMap<double, Type, ConstantFP> FPConstants;
692
693 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
694   return FPConstants.getOrCreate(Ty, V);
695 }
696
697 //---- ConstantArray::get() implementation...
698 //
699
700 template<>
701 struct ConvertConstantType<ConstantArray, ArrayType> {
702   static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
703     // Make everyone now use a constant of the new type...
704     std::vector<Constant*> C;
705     for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
706       C.push_back(cast<Constant>(OldC->getOperand(i)));
707     Constant *New = ConstantArray::get(NewTy, C);
708     assert(New != OldC && "Didn't replace constant??");
709     OldC->uncheckedReplaceAllUsesWith(New);
710     OldC->destroyConstant();    // This constant is now dead, destroy it.
711   }
712 };
713
714
715 static ValueMap<std::vector<Constant*>, ArrayType,
716                 ConstantArray> ArrayConstants;
717
718 ConstantArray *ConstantArray::get(const ArrayType *Ty,
719                                   const std::vector<Constant*> &V) {
720   return ArrayConstants.getOrCreate(Ty, V);
721 }
722
723 // destroyConstant - Remove the constant from the constant table...
724 //
725 void ConstantArray::destroyConstant() {
726   ArrayConstants.remove(this);
727   destroyConstantImpl();
728 }
729
730 // ConstantArray::get(const string&) - Return an array that is initialized to
731 // contain the specified string.  A null terminator is added to the specified
732 // string so that it may be used in a natural way...
733 //
734 ConstantArray *ConstantArray::get(const std::string &Str) {
735   std::vector<Constant*> ElementVals;
736
737   for (unsigned i = 0; i < Str.length(); ++i)
738     ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
739
740   // Add a null terminator to the string...
741   ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
742
743   ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
744   return ConstantArray::get(ATy, ElementVals);
745 }
746
747 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
748 // then this method converts the array to an std::string and returns it.
749 // Otherwise, it asserts out.
750 //
751 std::string ConstantArray::getAsString() const {
752   assert((getType()->getElementType() == Type::UByteTy ||
753           getType()->getElementType() == Type::SByteTy) && "Not a string!");
754
755   std::string Result;
756   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
757     Result += (char)cast<ConstantInt>(getOperand(i))->getRawValue();
758   return Result;
759 }
760
761
762 //---- ConstantStruct::get() implementation...
763 //
764
765 template<>
766 struct ConvertConstantType<ConstantStruct, StructType> {
767   static void convert(ConstantStruct *OldC, const StructType *NewTy) {
768     // Make everyone now use a constant of the new type...
769     std::vector<Constant*> C;
770     for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
771       C.push_back(cast<Constant>(OldC->getOperand(i)));
772     Constant *New = ConstantStruct::get(NewTy, C);
773     assert(New != OldC && "Didn't replace constant??");
774
775     OldC->uncheckedReplaceAllUsesWith(New);
776     OldC->destroyConstant();    // This constant is now dead, destroy it.
777   }
778 };
779
780 static ValueMap<std::vector<Constant*>, StructType, 
781                 ConstantStruct> StructConstants;
782
783 ConstantStruct *ConstantStruct::get(const StructType *Ty,
784                                     const std::vector<Constant*> &V) {
785   return StructConstants.getOrCreate(Ty, V);
786 }
787
788 // destroyConstant - Remove the constant from the constant table...
789 //
790 void ConstantStruct::destroyConstant() {
791   StructConstants.remove(this);
792   destroyConstantImpl();
793 }
794
795 //---- ConstantPointerNull::get() implementation...
796 //
797
798 // ConstantPointerNull does not take extra "value" argument...
799 template<class ValType>
800 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
801   static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
802     return new ConstantPointerNull(Ty);
803   }
804 };
805
806 template<>
807 struct ConvertConstantType<ConstantPointerNull, PointerType> {
808   static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
809     // Make everyone now use a constant of the new type...
810     Constant *New = ConstantPointerNull::get(NewTy);
811     assert(New != OldC && "Didn't replace constant??");
812     OldC->uncheckedReplaceAllUsesWith(New);
813     OldC->destroyConstant();     // This constant is now dead, destroy it.
814   }
815 };
816
817 static ValueMap<char, PointerType, ConstantPointerNull> NullPtrConstants;
818
819 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
820   return NullPtrConstants.getOrCreate(Ty, 0);
821 }
822
823 // destroyConstant - Remove the constant from the constant table...
824 //
825 void ConstantPointerNull::destroyConstant() {
826   NullPtrConstants.remove(this);
827   destroyConstantImpl();
828 }
829
830
831 //---- ConstantPointerRef::get() implementation...
832 //
833 ConstantPointerRef *ConstantPointerRef::get(GlobalValue *GV) {
834   assert(GV->getParent() && "Global Value must be attached to a module!");
835   
836   // The Module handles the pointer reference sharing...
837   return GV->getParent()->getConstantPointerRef(GV);
838 }
839
840 // destroyConstant - Remove the constant from the constant table...
841 //
842 void ConstantPointerRef::destroyConstant() {
843   getValue()->getParent()->destroyConstantPointerRef(this);
844   destroyConstantImpl();
845 }
846
847
848 //---- ConstantExpr::get() implementations...
849 //
850 typedef std::pair<unsigned, std::vector<Constant*> > ExprMapKeyType;
851
852 template<>
853 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
854   static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V) {
855     if (V.first == Instruction::Cast)
856       return new ConstantExpr(Instruction::Cast, V.second[0], Ty);
857     if ((V.first >= Instruction::BinaryOpsBegin &&
858          V.first < Instruction::BinaryOpsEnd) ||
859         V.first == Instruction::Shl || V.first == Instruction::Shr)
860       return new ConstantExpr(V.first, V.second[0], V.second[1]);
861     
862     assert(V.first == Instruction::GetElementPtr && "Invalid ConstantExpr!");
863     
864     std::vector<Constant*> IdxList(V.second.begin()+1, V.second.end());
865     return new ConstantExpr(V.second[0], IdxList, Ty);
866   }
867 };
868
869 template<>
870 struct ConvertConstantType<ConstantExpr, Type> {
871   static void convert(ConstantExpr *OldC, const Type *NewTy) {
872     Constant *New;
873     switch (OldC->getOpcode()) {
874     case Instruction::Cast:
875       New = ConstantExpr::getCast(OldC->getOperand(0), NewTy);
876       break;
877     case Instruction::Shl:
878     case Instruction::Shr:
879       New = ConstantExpr::getShiftTy(NewTy, OldC->getOpcode(),
880                                      OldC->getOperand(0), OldC->getOperand(1));
881       break;
882     default:
883       assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
884              OldC->getOpcode() < Instruction::BinaryOpsEnd);
885       New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
886                                 OldC->getOperand(1));
887       break;
888     case Instruction::GetElementPtr:
889       // Make everyone now use a constant of the new type... 
890       std::vector<Constant*> C;
891       for (unsigned i = 1, e = OldC->getNumOperands(); i != e; ++i)
892         C.push_back(cast<Constant>(OldC->getOperand(i)));
893       New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0), C);
894       break;
895     }
896
897     assert(New != OldC && "Didn't replace constant??");
898     OldC->uncheckedReplaceAllUsesWith(New);
899     OldC->destroyConstant();    // This constant is now dead, destroy it.
900   }
901 };
902
903
904 static ValueMap<ExprMapKeyType, Type, ConstantExpr> ExprConstants;
905
906 Constant *ConstantExpr::getCast(Constant *C, const Type *Ty) {
907   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
908
909   if (Constant *FC = ConstantFoldCastInstruction(C, Ty))
910     return FC;          // Fold a few common cases...
911
912   // Look up the constant in the table first to ensure uniqueness
913   std::vector<Constant*> argVec(1, C);
914   ExprMapKeyType Key = std::make_pair(Instruction::Cast, argVec);
915   return ExprConstants.getOrCreate(Ty, Key);
916 }
917
918 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
919                               Constant *C1, Constant *C2) {
920   // Check the operands for consistency first
921   assert((Opcode >= Instruction::BinaryOpsBegin &&
922           Opcode < Instruction::BinaryOpsEnd) &&
923          "Invalid opcode in binary constant expression");
924   assert(C1->getType() == C2->getType() &&
925          "Operand types in binary constant expression should match");
926
927   if (ReqTy == C1->getType())
928     if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
929       return FC;          // Fold a few common cases...
930
931   std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
932   ExprMapKeyType Key = std::make_pair(Opcode, argVec);
933   return ExprConstants.getOrCreate(ReqTy, Key);
934 }
935
936 /// getShift - Return a shift left or shift right constant expr
937 Constant *ConstantExpr::getShiftTy(const Type *ReqTy, unsigned Opcode,
938                                    Constant *C1, Constant *C2) {
939   // Check the operands for consistency first
940   assert((Opcode == Instruction::Shl ||
941           Opcode == Instruction::Shr) &&
942          "Invalid opcode in binary constant expression");
943   assert(C1->getType()->isIntegral() && C2->getType() == Type::UByteTy &&
944          "Invalid operand types for Shift constant expr!");
945
946   if (Constant *FC = ConstantFoldShiftInstruction(Opcode, C1, C2))
947     return FC;          // Fold a few common cases...
948
949   // Look up the constant in the table first to ensure uniqueness
950   std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
951   ExprMapKeyType Key = std::make_pair(Opcode, argVec);
952   return ExprConstants.getOrCreate(ReqTy, Key);
953 }
954
955
956 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
957                                         const std::vector<Constant*> &IdxList) {
958   if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
959     return FC;          // Fold a few common cases...
960   assert(isa<PointerType>(C->getType()) &&
961          "Non-pointer type for constant GetElementPtr expression");
962
963   // Look up the constant in the table first to ensure uniqueness
964   std::vector<Constant*> argVec(1, C);
965   argVec.insert(argVec.end(), IdxList.begin(), IdxList.end());
966   const ExprMapKeyType &Key = std::make_pair(Instruction::GetElementPtr,argVec);
967   return ExprConstants.getOrCreate(ReqTy, Key);
968 }
969
970 Constant *ConstantExpr::getGetElementPtr(Constant *C,
971                                          const std::vector<Constant*> &IdxList){
972   // Get the result type of the getelementptr!
973   std::vector<Value*> VIdxList(IdxList.begin(), IdxList.end());
974
975   const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), VIdxList,
976                                                      true);
977   assert(Ty && "GEP indices invalid!");
978   return getGetElementPtrTy(PointerType::get(Ty), C, IdxList);
979 }
980
981
982 // destroyConstant - Remove the constant from the constant table...
983 //
984 void ConstantExpr::destroyConstant() {
985   ExprConstants.remove(this);
986   destroyConstantImpl();
987 }
988
989 const char *ConstantExpr::getOpcodeName() const {
990   return Instruction::getOpcodeName(getOpcode());
991 }
992
993 unsigned Constant::mutateReferences(Value *OldV, Value *NewV) {
994   // Uses of constant pointer refs are global values, not constants!
995   if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(this)) {
996     GlobalValue *NewGV = cast<GlobalValue>(NewV);
997     GlobalValue *OldGV = CPR->getValue();
998
999     assert(OldGV == OldV && "Cannot mutate old value if I'm not using it!");
1000     Operands[0] = NewGV;
1001     OldGV->getParent()->mutateConstantPointerRef(OldGV, NewGV);
1002     return 1;
1003   } else {
1004     Constant *NewC = cast<Constant>(NewV);
1005     unsigned NumReplaced = 0;
1006     for (unsigned i = 0, N = getNumOperands(); i != N; ++i)
1007       if (Operands[i] == OldV) {
1008         ++NumReplaced;
1009         Operands[i] = NewC;
1010       }
1011     return NumReplaced;
1012   }
1013 }