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