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