There is nothing special about noops anymore
[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     Operands.push_back(Use(V[i], this));
218   }
219 }
220
221 ConstantStruct::ConstantStruct(const StructType *T,
222                                const std::vector<Constant*> &V) : Constant(T) {
223   const StructType::ElementTypes &ETypes = T->getElementTypes();
224   assert(V.size() == ETypes.size() &&
225          "Invalid initializer vector for constant structure");
226   Operands.reserve(V.size());
227   for (unsigned i = 0, e = V.size(); i != e; ++i) {
228     assert((V[i]->getType() == ETypes[i] ||
229             (ETypes[i]->isAbstract() &&
230              ETypes[i]->getPrimitiveID()==V[i]->getType()->getPrimitiveID())) &&
231            "Initializer for struct element doesn't match struct element type!");
232     Operands.push_back(Use(V[i], this));
233   }
234 }
235
236 ConstantPointerRef::ConstantPointerRef(GlobalValue *GV)
237   : ConstantPointer(GV->getType()) {
238   Operands.push_back(Use(GV, this));
239 }
240
241 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
242   : Constant(Ty), iType(Opcode) {
243   Operands.push_back(Use(C, this));
244 }
245
246 static bool isSetCC(unsigned Opcode) {
247   return Opcode == Instruction::SetEQ || Opcode == Instruction::SetNE ||
248          Opcode == Instruction::SetLT || Opcode == Instruction::SetGT ||
249          Opcode == Instruction::SetLE || Opcode == Instruction::SetGE;
250 }
251
252 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
253   : Constant(isSetCC(Opcode) ? Type::BoolTy : C1->getType()), iType(Opcode) {
254   Operands.push_back(Use(C1, this));
255   Operands.push_back(Use(C2, this));
256 }
257
258 ConstantExpr::ConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
259                            const Type *DestTy)
260   : Constant(DestTy), iType(Instruction::GetElementPtr) {
261   Operands.reserve(1+IdxList.size());
262   Operands.push_back(Use(C, this));
263   for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
264     Operands.push_back(Use(IdxList[i], this));
265 }
266
267
268
269 //===----------------------------------------------------------------------===//
270 //                           classof implementations
271
272 bool ConstantIntegral::classof(const Constant *CPV) {
273   return CPV->getType()->isIntegral() && !isa<ConstantExpr>(CPV);
274 }
275
276 bool ConstantInt::classof(const Constant *CPV) {
277   return CPV->getType()->isInteger() && !isa<ConstantExpr>(CPV);
278 }
279 bool ConstantSInt::classof(const Constant *CPV) {
280   return CPV->getType()->isSigned() && !isa<ConstantExpr>(CPV);
281 }
282 bool ConstantUInt::classof(const Constant *CPV) {
283   return CPV->getType()->isUnsigned() && !isa<ConstantExpr>(CPV);
284 }
285 bool ConstantFP::classof(const Constant *CPV) {
286   const Type *Ty = CPV->getType();
287   return ((Ty == Type::FloatTy || Ty == Type::DoubleTy) &&
288           !isa<ConstantExpr>(CPV));
289 }
290 bool ConstantArray::classof(const Constant *CPV) {
291   return isa<ArrayType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
292 }
293 bool ConstantStruct::classof(const Constant *CPV) {
294   return isa<StructType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
295 }
296 bool ConstantPointer::classof(const Constant *CPV) {
297   return (isa<PointerType>(CPV->getType()) && !isa<ConstantExpr>(CPV));
298 }
299
300
301
302 //===----------------------------------------------------------------------===//
303 //                      isValueValidForType implementations
304
305 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
306   switch (Ty->getPrimitiveID()) {
307   default:
308     return false;         // These can't be represented as integers!!!
309
310     // Signed types...
311   case Type::SByteTyID:
312     return (Val <= INT8_MAX && Val >= INT8_MIN);
313   case Type::ShortTyID:
314     return (Val <= INT16_MAX && Val >= INT16_MIN);
315   case Type::IntTyID:
316     return (Val <= INT32_MAX && Val >= INT32_MIN);
317   case Type::LongTyID:
318     return true;          // This is the largest type...
319   }
320   assert(0 && "WTF?");
321   return false;
322 }
323
324 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
325   switch (Ty->getPrimitiveID()) {
326   default:
327     return false;         // These can't be represented as integers!!!
328
329     // Unsigned types...
330   case Type::UByteTyID:
331     return (Val <= UINT8_MAX);
332   case Type::UShortTyID:
333     return (Val <= UINT16_MAX);
334   case Type::UIntTyID:
335     return (Val <= UINT32_MAX);
336   case Type::ULongTyID:
337     return true;          // This is the largest type...
338   }
339   assert(0 && "WTF?");
340   return false;
341 }
342
343 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
344   switch (Ty->getPrimitiveID()) {
345   default:
346     return false;         // These can't be represented as floating point!
347
348     // TODO: Figure out how to test if a double can be cast to a float!
349   case Type::FloatTyID:
350     /*
351     return (Val <= UINT8_MAX);
352     */
353   case Type::DoubleTyID:
354     return true;          // This is the largest type...
355   }
356 };
357
358 //===----------------------------------------------------------------------===//
359 //                replaceUsesOfWithOnConstant implementations
360
361 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To) {
362   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
363
364   std::vector<Constant*> Values;
365   Values.reserve(getValues().size());  // Build replacement array...
366   for (unsigned i = 0, e = getValues().size(); i != e; ++i) {
367     Constant *Val = cast<Constant>(getValues()[i]);
368     if (Val == From) Val = cast<Constant>(To);
369     Values.push_back(Val);
370   }
371   
372   ConstantArray *Replacement = ConstantArray::get(getType(), Values);
373   assert(Replacement != this && "I didn't contain From!");
374
375   // Everyone using this now uses the replacement...
376   replaceAllUsesWith(Replacement);
377   
378   // Delete the old constant!
379   destroyConstant();  
380 }
381
382 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To) {
383   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
384
385   std::vector<Constant*> Values;
386   Values.reserve(getValues().size());
387   for (unsigned i = 0, e = getValues().size(); i != e; ++i) {
388     Constant *Val = cast<Constant>(getValues()[i]);
389     if (Val == From) Val = cast<Constant>(To);
390     Values.push_back(Val);
391   }
392   
393   ConstantStruct *Replacement = ConstantStruct::get(getType(), Values);
394   assert(Replacement != this && "I didn't contain From!");
395
396   // Everyone using this now uses the replacement...
397   replaceAllUsesWith(Replacement);
398   
399   // Delete the old constant!
400   destroyConstant();
401 }
402
403 void ConstantPointerRef::replaceUsesOfWithOnConstant(Value *From, Value *To) {
404   if (isa<GlobalValue>(To)) {
405     assert(From == getOperand(0) && "Doesn't contain from!");
406     ConstantPointerRef *Replacement =
407       ConstantPointerRef::get(cast<GlobalValue>(To));
408     
409     // Everyone using this now uses the replacement...
410     replaceAllUsesWith(Replacement);
411     
412     // Delete the old constant!
413     destroyConstant();
414   } else {
415     // Just replace ourselves with the To value specified.
416     replaceAllUsesWith(To);
417   
418     // Delete the old constant!
419     destroyConstant();
420   }
421 }
422
423 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV) {
424   assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
425   Constant *To = cast<Constant>(ToV);
426
427   Constant *Replacement = 0;
428   if (getOpcode() == Instruction::GetElementPtr) {
429     std::vector<Constant*> Indices;
430     Constant *Pointer = getOperand(0);
431     Indices.reserve(getNumOperands()-1);
432     if (Pointer == From) Pointer = To;
433     
434     for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
435       Constant *Val = getOperand(i);
436       if (Val == From) Val = To;
437       Indices.push_back(Val);
438     }
439     Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
440   } else if (getOpcode() == Instruction::Cast) {
441     assert(getOperand(0) == From && "Cast only has one use!");
442     Replacement = ConstantExpr::getCast(To, getType());
443   } else if (getNumOperands() == 2) {
444     Constant *C1 = getOperand(0);
445     Constant *C2 = getOperand(1);
446     if (C1 == From) C1 = To;
447     if (C2 == From) C2 = To;
448     Replacement = ConstantExpr::get(getOpcode(), C1, C2);
449   } else {
450     assert(0 && "Unknown ConstantExpr type!");
451     return;
452   }
453   
454   assert(Replacement != this && "I didn't contain From!");
455
456   // Everyone using this now uses the replacement...
457   replaceAllUsesWith(Replacement);
458   
459   // Delete the old constant!
460   destroyConstant();
461 }
462
463 //===----------------------------------------------------------------------===//
464 //                      Factory Function Implementation
465
466 // ReplaceUsesOfWith - This is exactly the same as Value::replaceAllUsesWith,
467 // except that it doesn't have all of the asserts.  The asserts fail because we
468 // are half-way done resolving types, which causes some types to exist as two
469 // different Type*'s at the same time.  This is a sledgehammer to work around
470 // this problem.
471 //
472 static void ReplaceUsesOfWith(Value *Old, Value *New) {
473   while (!Old->use_empty()) {
474     User *Use = Old->use_back();
475     // Must handle Constants specially, we cannot call replaceUsesOfWith on a
476     // constant!
477     if (Constant *C = dyn_cast<Constant>(Use)) {
478       C->replaceUsesOfWithOnConstant(Old, New);
479     } else {
480       Use->replaceUsesOfWith(Old, New);
481     }
482   }
483 }
484
485
486 // ConstantCreator - A class that is used to create constants by
487 // ValueMap*.  This class should be partially specialized if there is
488 // something strange that needs to be done to interface to the ctor for the
489 // constant.
490 //
491 template<class ConstantClass, class TypeClass, class ValType>
492 struct ConstantCreator {
493   static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
494     return new ConstantClass(Ty, V);
495   }
496 };
497
498 namespace {
499   template<class ValType, class TypeClass, class ConstantClass>
500   class ValueMap {
501   protected:
502     typedef std::pair<const TypeClass*, ValType> ConstHashKey;
503     std::map<ConstHashKey, ConstantClass *> Map;
504   public:
505     // getOrCreate - Return the specified constant from the map, creating it if
506     // necessary.
507     ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
508       ConstHashKey Lookup(Ty, V);
509       typename std::map<ConstHashKey,ConstantClass *>::iterator I =
510         Map.lower_bound(Lookup);
511       if (I != Map.end() && I->first == Lookup)
512         return I->second;  // Is it in the map?
513
514       // If no preexisting value, create one now...
515       ConstantClass *Result =
516         ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
517
518       Map.insert(I, std::make_pair(ConstHashKey(Ty, V), Result));
519       return Result;
520     }
521     
522     void remove(ConstantClass *CP) {
523       // FIXME: This could be sped up a LOT.  If this gets to be a performance
524       // problem, someone should look at this.
525       for (typename std::map<ConstHashKey, ConstantClass*>::iterator
526              I = Map.begin(), E = Map.end(); I != E; ++I)
527         if (I->second == CP) {
528           Map.erase(I);
529           return;
530         }
531       assert(0 && "Constant not found in constant table!");
532     }
533   };
534 }
535
536
537
538 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
539 //
540 static ValueMap< int64_t, Type, ConstantSInt> SIntConstants;
541 static ValueMap<uint64_t, Type, ConstantUInt> UIntConstants;
542
543 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
544   return SIntConstants.getOrCreate(Ty, V);
545 }
546
547 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
548   return UIntConstants.getOrCreate(Ty, V);
549 }
550
551 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
552   assert(V <= 127 && "Can only be used with very small positive constants!");
553   if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
554   return ConstantUInt::get(Ty, V);
555 }
556
557 //---- ConstantFP::get() implementation...
558 //
559 static ValueMap<double, Type, ConstantFP> FPConstants;
560
561 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
562   return FPConstants.getOrCreate(Ty, V);
563 }
564
565 //---- ConstantArray::get() implementation...
566 //
567 static ValueMap<std::vector<Constant*>, ArrayType,
568                 ConstantArray> ArrayConstants;
569
570 ConstantArray *ConstantArray::get(const ArrayType *Ty,
571                                   const std::vector<Constant*> &V) {
572   return ArrayConstants.getOrCreate(Ty, V);
573 }
574
575 // destroyConstant - Remove the constant from the constant table...
576 //
577 void ConstantArray::destroyConstant() {
578   ArrayConstants.remove(this);
579   destroyConstantImpl();
580 }
581
582 /// refineAbstractType - If this callback is invoked, then this constant is of a
583 /// derived type, change all users to use a concrete constant of the new type.
584 ///
585 void ConstantArray::refineAbstractType(const DerivedType *OldTy,
586                                        const Type *NewTy) {
587   Value::refineAbstractType(OldTy, NewTy);
588   if (OldTy == NewTy) return;
589
590   // Make everyone now use a constant of the new type...
591   std::vector<Constant*> C;
592   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
593     C.push_back(cast<Constant>(getOperand(i)));
594   Constant *New = ConstantArray::get(cast<ArrayType>(NewTy), C);
595   if (New != this) {
596     ReplaceUsesOfWith(this, New);
597     destroyConstant();    // This constant is now dead, destroy it.
598   }
599 }
600
601
602 // ConstantArray::get(const string&) - Return an array that is initialized to
603 // contain the specified string.  A null terminator is added to the specified
604 // string so that it may be used in a natural way...
605 //
606 ConstantArray *ConstantArray::get(const std::string &Str) {
607   std::vector<Constant*> ElementVals;
608
609   for (unsigned i = 0; i < Str.length(); ++i)
610     ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
611
612   // Add a null terminator to the string...
613   ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
614
615   ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
616   return ConstantArray::get(ATy, ElementVals);
617 }
618
619 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
620 // then this method converts the array to an std::string and returns it.
621 // Otherwise, it asserts out.
622 //
623 std::string ConstantArray::getAsString() const {
624   assert((getType()->getElementType() == Type::UByteTy ||
625           getType()->getElementType() == Type::SByteTy) && "Not a string!");
626
627   std::string Result;
628   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
629     Result += (char)cast<ConstantInt>(getOperand(i))->getRawValue();
630   return Result;
631 }
632
633
634 //---- ConstantStruct::get() implementation...
635 //
636 static ValueMap<std::vector<Constant*>, StructType, 
637                 ConstantStruct> StructConstants;
638
639 ConstantStruct *ConstantStruct::get(const StructType *Ty,
640                                     const std::vector<Constant*> &V) {
641   return StructConstants.getOrCreate(Ty, V);
642 }
643
644 // destroyConstant - Remove the constant from the constant table...
645 //
646 void ConstantStruct::destroyConstant() {
647   StructConstants.remove(this);
648   destroyConstantImpl();
649 }
650
651 /// refineAbstractType - If this callback is invoked, then this constant is of a
652 /// derived type, change all users to use a concrete constant of the new type.
653 ///
654 void ConstantStruct::refineAbstractType(const DerivedType *OldTy,
655                                         const Type *NewTy) {
656   Value::refineAbstractType(OldTy, NewTy);
657   if (OldTy == NewTy) return;
658
659   // Make everyone now use a constant of the new type...
660   std::vector<Constant*> C;
661   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
662     C.push_back(cast<Constant>(getOperand(i)));
663   Constant *New = ConstantStruct::get(cast<StructType>(NewTy), C);
664   if (New != this) {
665     ReplaceUsesOfWith(this, New);
666     destroyConstant();    // This constant is now dead, destroy it.
667   }
668 }
669
670
671 //---- ConstantPointerNull::get() implementation...
672 //
673
674 // ConstantPointerNull does not take extra "value" argument...
675 template<class ValType>
676 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
677   static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
678     return new ConstantPointerNull(Ty);
679   }
680 };
681
682 static ValueMap<char, PointerType, ConstantPointerNull> NullPtrConstants;
683
684 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
685   return NullPtrConstants.getOrCreate(Ty, 0);
686 }
687
688 // destroyConstant - Remove the constant from the constant table...
689 //
690 void ConstantPointerNull::destroyConstant() {
691   NullPtrConstants.remove(this);
692   destroyConstantImpl();
693 }
694
695 /// refineAbstractType - If this callback is invoked, then this constant is of a
696 /// derived type, change all users to use a concrete constant of the new type.
697 ///
698 void ConstantPointerNull::refineAbstractType(const DerivedType *OldTy,
699                                              const Type *NewTy) {
700   Value::refineAbstractType(OldTy, NewTy);
701   if (OldTy == NewTy) return;
702
703   // Make everyone now use a constant of the new type...
704   Constant *New = ConstantPointerNull::get(cast<PointerType>(NewTy));
705   if (New != this) {
706     ReplaceUsesOfWith(this, New);
707     
708     // This constant is now dead, destroy it.
709     destroyConstant();
710   }
711 }
712
713
714
715 //---- ConstantPointerRef::get() implementation...
716 //
717 ConstantPointerRef *ConstantPointerRef::get(GlobalValue *GV) {
718   assert(GV->getParent() && "Global Value must be attached to a module!");
719   
720   // The Module handles the pointer reference sharing...
721   return GV->getParent()->getConstantPointerRef(GV);
722 }
723
724 // destroyConstant - Remove the constant from the constant table...
725 //
726 void ConstantPointerRef::destroyConstant() {
727   getValue()->getParent()->destroyConstantPointerRef(this);
728   destroyConstantImpl();
729 }
730
731
732 //---- ConstantExpr::get() implementations...
733 //
734 typedef std::pair<unsigned, std::vector<Constant*> > ExprMapKeyType;
735
736 template<>
737 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
738   static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V) {
739     if (V.first == Instruction::Cast)
740       return new ConstantExpr(Instruction::Cast, V.second[0], Ty);
741     if ((V.first >= Instruction::BinaryOpsBegin &&
742          V.first < Instruction::BinaryOpsEnd) ||
743         V.first == Instruction::Shl || V.first == Instruction::Shr)
744       return new ConstantExpr(V.first, V.second[0], V.second[1]);
745     
746     assert(V.first == Instruction::GetElementPtr && "Invalid ConstantExpr!");
747     
748     // Check that the indices list is valid...
749     std::vector<Value*> ValIdxList(V.second.begin()+1, V.second.end());
750     const Type *DestTy = GetElementPtrInst::getIndexedType(Ty, ValIdxList,
751                                                            true);
752     assert(DestTy && "Invalid index list for GetElementPtr expression");
753     
754     std::vector<Constant*> IdxList(V.second.begin()+1, V.second.end());
755     return new ConstantExpr(V.second[0], IdxList, PointerType::get(DestTy));
756   }
757 };
758
759 static ValueMap<ExprMapKeyType, Type, ConstantExpr> ExprConstants;
760
761 Constant *ConstantExpr::getCast(Constant *C, const Type *Ty) {
762   if (Constant *FC = ConstantFoldCastInstruction(C, Ty))
763     return FC;          // Fold a few common cases...
764
765   // Look up the constant in the table first to ensure uniqueness
766   std::vector<Constant*> argVec(1, C);
767   ExprMapKeyType Key = std::make_pair(Instruction::Cast, argVec);
768   return ExprConstants.getOrCreate(Ty, Key);
769 }
770
771 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
772   // Check the operands for consistency first
773   assert((Opcode >= Instruction::BinaryOpsBegin &&
774           Opcode < Instruction::BinaryOpsEnd) &&
775          "Invalid opcode in binary constant expression");
776   assert(C1->getType() == C2->getType() &&
777          "Operand types in binary constant expression should match");
778   
779   if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
780     return FC;          // Fold a few common cases...
781
782   std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
783   ExprMapKeyType Key = std::make_pair(Opcode, argVec);
784   return ExprConstants.getOrCreate(C1->getType(), Key);
785 }
786
787 /// getShift - Return a shift left or shift right constant expr
788 Constant *ConstantExpr::getShift(unsigned Opcode, Constant *C1, Constant *C2) {
789   // Check the operands for consistency first
790   assert((Opcode == Instruction::Shl ||
791           Opcode == Instruction::Shr) &&
792          "Invalid opcode in binary constant expression");
793   assert(C1->getType()->isIntegral() && C2->getType() == Type::UByteTy &&
794          "Invalid operand types for Shift constant expr!");
795
796   if (Constant *FC = ConstantFoldShiftInstruction(Opcode, C1, C2))
797     return FC;          // Fold a few common cases...
798
799   // Look up the constant in the table first to ensure uniqueness
800   std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
801   ExprMapKeyType Key = std::make_pair(Opcode, argVec);
802   return ExprConstants.getOrCreate(C1->getType(), Key);
803 }
804
805
806 Constant *ConstantExpr::getGetElementPtr(Constant *C,
807                                          const std::vector<Constant*> &IdxList){
808   if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
809     return FC;          // Fold a few common cases...
810   const Type *Ty = C->getType();
811   assert(isa<PointerType>(Ty) &&
812          "Non-pointer type for constant GetElementPtr expression");
813
814   // Look up the constant in the table first to ensure uniqueness
815   std::vector<Constant*> argVec(1, C);
816   argVec.insert(argVec.end(), IdxList.begin(), IdxList.end());
817   
818   const ExprMapKeyType &Key = std::make_pair(Instruction::GetElementPtr,argVec);
819   return ExprConstants.getOrCreate(Ty, Key);
820 }
821
822 // destroyConstant - Remove the constant from the constant table...
823 //
824 void ConstantExpr::destroyConstant() {
825   ExprConstants.remove(this);
826   destroyConstantImpl();
827 }
828
829 /// refineAbstractType - If this callback is invoked, then this constant is of a
830 /// derived type, change all users to use a concrete constant of the new type.
831 ///
832 void ConstantExpr::refineAbstractType(const DerivedType *OldTy,
833                                       const Type *NewTy) {
834   Value::refineAbstractType(OldTy, NewTy);
835   if (OldTy == NewTy) return;
836
837   // FIXME: These need to use a lower-level implementation method, because the
838   // ::get methods intuit the type of the result based on the types of the
839   // operands.  The operand types may not have had their types resolved yet.
840   //
841   Constant *New;
842   if (getOpcode() == Instruction::Cast) {
843     New = getCast(getOperand(0), NewTy);
844   } else if (getOpcode() >= Instruction::BinaryOpsBegin &&
845              getOpcode() < Instruction::BinaryOpsEnd) {
846     New = get(getOpcode(), getOperand(0), getOperand(0));
847   } else if (getOpcode() == Instruction::Shl || getOpcode() ==Instruction::Shr){
848     New = getShift(getOpcode(), getOperand(0), getOperand(0));
849   } else {
850     assert(getOpcode() == Instruction::GetElementPtr);
851
852     // Make everyone now use a constant of the new type...
853     std::vector<Constant*> C;
854     for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
855       C.push_back(cast<Constant>(getOperand(i)));
856     New = ConstantExpr::getGetElementPtr(getOperand(0), C);
857   }
858   if (New != this) {
859     ReplaceUsesOfWith(this, New);
860     destroyConstant();    // This constant is now dead, destroy it.
861   }
862 }
863
864
865
866
867 const char *ConstantExpr::getOpcodeName() const {
868   return Instruction::getOpcodeName(getOpcode());
869 }
870
871 unsigned Constant::mutateReferences(Value *OldV, Value *NewV) {
872   // Uses of constant pointer refs are global values, not constants!
873   if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(this)) {
874     GlobalValue *NewGV = cast<GlobalValue>(NewV);
875     GlobalValue *OldGV = CPR->getValue();
876
877     assert(OldGV == OldV && "Cannot mutate old value if I'm not using it!");
878     Operands[0] = NewGV;
879     OldGV->getParent()->mutateConstantPointerRef(OldGV, NewGV);
880     return 1;
881   } else {
882     Constant *NewC = cast<Constant>(NewV);
883     unsigned NumReplaced = 0;
884     for (unsigned i = 0, N = getNumOperands(); i != N; ++i)
885       if (Operands[i] == OldV) {
886         ++NumReplaced;
887         Operands[i] = NewC;
888       }
889     return NumReplaced;
890   }
891 }