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