There is no reason for Value to be an AbstractTypeUser. This just makes things
[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 dependent 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   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                                                 bool DisableChecking) {
363   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
364
365   std::vector<Constant*> Values;
366   Values.reserve(getValues().size());  // Build replacement array...
367   for (unsigned i = 0, e = getValues().size(); i != e; ++i) {
368     Constant *Val = cast<Constant>(getValues()[i]);
369     if (Val == From) Val = cast<Constant>(To);
370     Values.push_back(Val);
371   }
372   
373   ConstantArray *Replacement = ConstantArray::get(getType(), Values);
374   assert(Replacement != this && "I didn't contain From!");
375
376   // Everyone using this now uses the replacement...
377   if (DisableChecking)
378     uncheckedReplaceAllUsesWith(Replacement);
379   else
380     replaceAllUsesWith(Replacement);
381   
382   // Delete the old constant!
383   destroyConstant();  
384 }
385
386 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
387                                                  bool DisableChecking) {
388   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
389
390   std::vector<Constant*> Values;
391   Values.reserve(getValues().size());
392   for (unsigned i = 0, e = getValues().size(); i != e; ++i) {
393     Constant *Val = cast<Constant>(getValues()[i]);
394     if (Val == From) Val = cast<Constant>(To);
395     Values.push_back(Val);
396   }
397   
398   ConstantStruct *Replacement = ConstantStruct::get(getType(), Values);
399   assert(Replacement != this && "I didn't contain From!");
400
401   // Everyone using this now uses the replacement...
402   if (DisableChecking)
403     uncheckedReplaceAllUsesWith(Replacement);
404   else
405     replaceAllUsesWith(Replacement);
406   
407   // Delete the old constant!
408   destroyConstant();
409 }
410
411 void ConstantPointerRef::replaceUsesOfWithOnConstant(Value *From, Value *To,
412                                                      bool DisableChecking) {
413   if (isa<GlobalValue>(To)) {
414     assert(From == getOperand(0) && "Doesn't contain from!");
415     ConstantPointerRef *Replacement =
416       ConstantPointerRef::get(cast<GlobalValue>(To));
417     
418     // Everyone using this now uses the replacement...
419     if (DisableChecking)
420       uncheckedReplaceAllUsesWith(Replacement);
421     else
422       replaceAllUsesWith(Replacement);
423     
424   } else {
425     // Just replace ourselves with the To value specified.
426     if (DisableChecking)
427       uncheckedReplaceAllUsesWith(To);
428     else
429       replaceAllUsesWith(To);
430   }
431
432   // Delete the old constant!
433   destroyConstant();
434 }
435
436 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
437                                                bool DisableChecking) {
438   assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
439   Constant *To = cast<Constant>(ToV);
440
441   Constant *Replacement = 0;
442   if (getOpcode() == Instruction::GetElementPtr) {
443     std::vector<Constant*> Indices;
444     Constant *Pointer = getOperand(0);
445     Indices.reserve(getNumOperands()-1);
446     if (Pointer == From) Pointer = To;
447     
448     for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
449       Constant *Val = getOperand(i);
450       if (Val == From) Val = To;
451       Indices.push_back(Val);
452     }
453     Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
454   } else if (getOpcode() == Instruction::Cast) {
455     assert(getOperand(0) == From && "Cast only has one use!");
456     Replacement = ConstantExpr::getCast(To, getType());
457   } else if (getNumOperands() == 2) {
458     Constant *C1 = getOperand(0);
459     Constant *C2 = getOperand(1);
460     if (C1 == From) C1 = To;
461     if (C2 == From) C2 = To;
462     Replacement = ConstantExpr::get(getOpcode(), C1, C2);
463   } else {
464     assert(0 && "Unknown ConstantExpr type!");
465     return;
466   }
467   
468   assert(Replacement != this && "I didn't contain From!");
469
470   // Everyone using this now uses the replacement...
471   if (DisableChecking)
472     uncheckedReplaceAllUsesWith(Replacement);
473   else
474     replaceAllUsesWith(Replacement);
475   
476   // Delete the old constant!
477   destroyConstant();
478 }
479
480 //===----------------------------------------------------------------------===//
481 //                      Factory Function Implementation
482
483 // ConstantCreator - A class that is used to create constants by
484 // ValueMap*.  This class should be partially specialized if there is
485 // something strange that needs to be done to interface to the ctor for the
486 // constant.
487 //
488 template<class ConstantClass, class TypeClass, class ValType>
489 struct ConstantCreator {
490   static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
491     return new ConstantClass(Ty, V);
492   }
493 };
494
495 namespace {
496   template<class ValType, class TypeClass, class ConstantClass>
497   class ValueMap {
498   protected:
499     typedef std::pair<const TypeClass*, ValType> ConstHashKey;
500     std::map<ConstHashKey, ConstantClass *> Map;
501   public:
502     // getOrCreate - Return the specified constant from the map, creating it if
503     // necessary.
504     ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
505       ConstHashKey Lookup(Ty, V);
506       typename std::map<ConstHashKey,ConstantClass *>::iterator I =
507         Map.lower_bound(Lookup);
508       if (I != Map.end() && I->first == Lookup)
509         return I->second;  // Is it in the map?
510
511       // If no preexisting value, create one now...
512       ConstantClass *Result =
513         ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
514
515       Map.insert(I, std::make_pair(ConstHashKey(Ty, V), Result));
516       return Result;
517     }
518     
519     void remove(ConstantClass *CP) {
520       // FIXME: This could be sped up a LOT.  If this gets to be a performance
521       // problem, someone should look at this.
522       for (typename std::map<ConstHashKey, ConstantClass*>::iterator
523              I = Map.begin(), E = Map.end(); I != E; ++I)
524         if (I->second == CP) {
525           Map.erase(I);
526           return;
527         }
528       assert(0 && "Constant not found in constant table!");
529     }
530   };
531 }
532
533
534
535 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
536 //
537 static ValueMap< int64_t, Type, ConstantSInt> SIntConstants;
538 static ValueMap<uint64_t, Type, ConstantUInt> UIntConstants;
539
540 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
541   return SIntConstants.getOrCreate(Ty, V);
542 }
543
544 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
545   return UIntConstants.getOrCreate(Ty, V);
546 }
547
548 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
549   assert(V <= 127 && "Can only be used with very small positive constants!");
550   if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
551   return ConstantUInt::get(Ty, V);
552 }
553
554 //---- ConstantFP::get() implementation...
555 //
556 static ValueMap<double, Type, ConstantFP> FPConstants;
557
558 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
559   return FPConstants.getOrCreate(Ty, V);
560 }
561
562 //---- ConstantArray::get() implementation...
563 //
564 static ValueMap<std::vector<Constant*>, ArrayType,
565                 ConstantArray> ArrayConstants;
566
567 ConstantArray *ConstantArray::get(const ArrayType *Ty,
568                                   const std::vector<Constant*> &V) {
569   return ArrayConstants.getOrCreate(Ty, V);
570 }
571
572 // destroyConstant - Remove the constant from the constant table...
573 //
574 void ConstantArray::destroyConstant() {
575   ArrayConstants.remove(this);
576   destroyConstantImpl();
577 }
578
579 /// refineAbstractType - If this callback is invoked, then this constant is of a
580 /// derived type, change all users to use a concrete constant of the new type.
581 ///
582 void ConstantArray::refineAbstractType(const DerivedType *OldTy,
583                                        const Type *NewTy) {
584   if (OldTy == NewTy) return;
585
586   // Make everyone now use a constant of the new type...
587   std::vector<Constant*> C;
588   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
589     C.push_back(cast<Constant>(getOperand(i)));
590   Constant *New = ConstantArray::get(cast<ArrayType>(NewTy), C);
591   if (New != this) {
592     uncheckedReplaceAllUsesWith(New);
593     destroyConstant();    // This constant is now dead, destroy it.
594   }
595 }
596
597
598 // ConstantArray::get(const string&) - Return an array that is initialized to
599 // contain the specified string.  A null terminator is added to the specified
600 // string so that it may be used in a natural way...
601 //
602 ConstantArray *ConstantArray::get(const std::string &Str) {
603   std::vector<Constant*> ElementVals;
604
605   for (unsigned i = 0; i < Str.length(); ++i)
606     ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
607
608   // Add a null terminator to the string...
609   ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
610
611   ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
612   return ConstantArray::get(ATy, ElementVals);
613 }
614
615 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
616 // then this method converts the array to an std::string and returns it.
617 // Otherwise, it asserts out.
618 //
619 std::string ConstantArray::getAsString() const {
620   assert((getType()->getElementType() == Type::UByteTy ||
621           getType()->getElementType() == Type::SByteTy) && "Not a string!");
622
623   std::string Result;
624   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
625     Result += (char)cast<ConstantInt>(getOperand(i))->getRawValue();
626   return Result;
627 }
628
629
630 //---- ConstantStruct::get() implementation...
631 //
632 static ValueMap<std::vector<Constant*>, StructType, 
633                 ConstantStruct> StructConstants;
634
635 ConstantStruct *ConstantStruct::get(const StructType *Ty,
636                                     const std::vector<Constant*> &V) {
637   return StructConstants.getOrCreate(Ty, V);
638 }
639
640 // destroyConstant - Remove the constant from the constant table...
641 //
642 void ConstantStruct::destroyConstant() {
643   StructConstants.remove(this);
644   destroyConstantImpl();
645 }
646
647 /// refineAbstractType - If this callback is invoked, then this constant is of a
648 /// derived type, change all users to use a concrete constant of the new type.
649 ///
650 void ConstantStruct::refineAbstractType(const DerivedType *OldTy,
651                                         const Type *NewTy) {
652   if (OldTy == NewTy) return;
653
654   // Make everyone now use a constant of the new type...
655   std::vector<Constant*> C;
656   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
657     C.push_back(cast<Constant>(getOperand(i)));
658   Constant *New = ConstantStruct::get(cast<StructType>(NewTy), C);
659   if (New != this) {
660     uncheckedReplaceAllUsesWith(New);
661     destroyConstant();    // This constant is now dead, destroy it.
662   }
663 }
664
665
666 //---- ConstantPointerNull::get() implementation...
667 //
668
669 // ConstantPointerNull does not take extra "value" argument...
670 template<class ValType>
671 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
672   static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
673     return new ConstantPointerNull(Ty);
674   }
675 };
676
677 static ValueMap<char, PointerType, ConstantPointerNull> NullPtrConstants;
678
679 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
680   return NullPtrConstants.getOrCreate(Ty, 0);
681 }
682
683 // destroyConstant - Remove the constant from the constant table...
684 //
685 void ConstantPointerNull::destroyConstant() {
686   NullPtrConstants.remove(this);
687   destroyConstantImpl();
688 }
689
690 /// refineAbstractType - If this callback is invoked, then this constant is of a
691 /// derived type, change all users to use a concrete constant of the new type.
692 ///
693 void ConstantPointerNull::refineAbstractType(const DerivedType *OldTy,
694                                              const Type *NewTy) {
695   if (OldTy == NewTy) return;
696
697   // Make everyone now use a constant of the new type...
698   Constant *New = ConstantPointerNull::get(cast<PointerType>(NewTy));
699   if (New != this) {
700     uncheckedReplaceAllUsesWith(New);
701     
702     // This constant is now dead, destroy it.
703     destroyConstant();
704   }
705 }
706
707
708
709 //---- ConstantPointerRef::get() implementation...
710 //
711 ConstantPointerRef *ConstantPointerRef::get(GlobalValue *GV) {
712   assert(GV->getParent() && "Global Value must be attached to a module!");
713   
714   // The Module handles the pointer reference sharing...
715   return GV->getParent()->getConstantPointerRef(GV);
716 }
717
718 // destroyConstant - Remove the constant from the constant table...
719 //
720 void ConstantPointerRef::destroyConstant() {
721   getValue()->getParent()->destroyConstantPointerRef(this);
722   destroyConstantImpl();
723 }
724
725
726 //---- ConstantExpr::get() implementations...
727 //
728 typedef std::pair<unsigned, std::vector<Constant*> > ExprMapKeyType;
729
730 template<>
731 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
732   static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V) {
733     if (V.first == Instruction::Cast)
734       return new ConstantExpr(Instruction::Cast, V.second[0], Ty);
735     if ((V.first >= Instruction::BinaryOpsBegin &&
736          V.first < Instruction::BinaryOpsEnd) ||
737         V.first == Instruction::Shl || V.first == Instruction::Shr)
738       return new ConstantExpr(V.first, V.second[0], V.second[1]);
739     
740     assert(V.first == Instruction::GetElementPtr && "Invalid ConstantExpr!");
741     
742     // Check that the indices list is valid...
743     std::vector<Value*> ValIdxList(V.second.begin()+1, V.second.end());
744     const Type *DestTy = GetElementPtrInst::getIndexedType(Ty, ValIdxList,
745                                                            true);
746     assert(DestTy && "Invalid index list for GetElementPtr expression");
747     
748     std::vector<Constant*> IdxList(V.second.begin()+1, V.second.end());
749     return new ConstantExpr(V.second[0], IdxList, PointerType::get(DestTy));
750   }
751 };
752
753 static ValueMap<ExprMapKeyType, Type, ConstantExpr> ExprConstants;
754
755 Constant *ConstantExpr::getCast(Constant *C, const Type *Ty) {
756   if (Constant *FC = ConstantFoldCastInstruction(C, Ty))
757     return FC;          // Fold a few common cases...
758
759   // Look up the constant in the table first to ensure uniqueness
760   std::vector<Constant*> argVec(1, C);
761   ExprMapKeyType Key = std::make_pair(Instruction::Cast, argVec);
762   return ExprConstants.getOrCreate(Ty, Key);
763 }
764
765 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
766   // Check the operands for consistency first
767   assert((Opcode >= Instruction::BinaryOpsBegin &&
768           Opcode < Instruction::BinaryOpsEnd) &&
769          "Invalid opcode in binary constant expression");
770   assert(C1->getType() == C2->getType() &&
771          "Operand types in binary constant expression should match");
772   
773   if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
774     return FC;          // Fold a few common cases...
775
776   std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
777   ExprMapKeyType Key = std::make_pair(Opcode, argVec);
778   return ExprConstants.getOrCreate(C1->getType(), Key);
779 }
780
781 /// getShift - Return a shift left or shift right constant expr
782 Constant *ConstantExpr::getShift(unsigned Opcode, Constant *C1, Constant *C2) {
783   // Check the operands for consistency first
784   assert((Opcode == Instruction::Shl ||
785           Opcode == Instruction::Shr) &&
786          "Invalid opcode in binary constant expression");
787   assert(C1->getType()->isIntegral() && C2->getType() == Type::UByteTy &&
788          "Invalid operand types for Shift constant expr!");
789
790   if (Constant *FC = ConstantFoldShiftInstruction(Opcode, C1, C2))
791     return FC;          // Fold a few common cases...
792
793   // Look up the constant in the table first to ensure uniqueness
794   std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
795   ExprMapKeyType Key = std::make_pair(Opcode, argVec);
796   return ExprConstants.getOrCreate(C1->getType(), Key);
797 }
798
799
800 Constant *ConstantExpr::getGetElementPtr(Constant *C,
801                                          const std::vector<Constant*> &IdxList){
802   if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
803     return FC;          // Fold a few common cases...
804   const Type *Ty = C->getType();
805   assert(isa<PointerType>(Ty) &&
806          "Non-pointer type for constant GetElementPtr expression");
807
808   // Look up the constant in the table first to ensure uniqueness
809   std::vector<Constant*> argVec(1, C);
810   argVec.insert(argVec.end(), IdxList.begin(), IdxList.end());
811   
812   const ExprMapKeyType &Key = std::make_pair(Instruction::GetElementPtr,argVec);
813   return ExprConstants.getOrCreate(Ty, Key);
814 }
815
816 // destroyConstant - Remove the constant from the constant table...
817 //
818 void ConstantExpr::destroyConstant() {
819   ExprConstants.remove(this);
820   destroyConstantImpl();
821 }
822
823 /// refineAbstractType - If this callback is invoked, then this constant is of a
824 /// derived type, change all users to use a concrete constant of the new type.
825 ///
826 void ConstantExpr::refineAbstractType(const DerivedType *OldTy,
827                                       const Type *NewTy) {
828   if (OldTy == NewTy) return;
829
830   // FIXME: These need to use a lower-level implementation method, because the
831   // ::get methods intuit the type of the result based on the types of the
832   // operands.  The operand types may not have had their types resolved yet.
833   //
834   Constant *New;
835   if (getOpcode() == Instruction::Cast) {
836     New = getCast(getOperand(0), NewTy);
837   } else if (getOpcode() >= Instruction::BinaryOpsBegin &&
838              getOpcode() < Instruction::BinaryOpsEnd) {
839     New = get(getOpcode(), getOperand(0), getOperand(0));
840   } else if (getOpcode() == Instruction::Shl || getOpcode() ==Instruction::Shr){
841     New = getShift(getOpcode(), getOperand(0), getOperand(0));
842   } else {
843     assert(getOpcode() == Instruction::GetElementPtr);
844
845     // Make everyone now use a constant of the new type...
846     std::vector<Constant*> C;
847     for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
848       C.push_back(cast<Constant>(getOperand(i)));
849     New = ConstantExpr::getGetElementPtr(getOperand(0), C);
850   }
851   if (New != this) {
852     uncheckedReplaceAllUsesWith(New);
853     destroyConstant();    // This constant is now dead, destroy it.
854   }
855 }
856
857
858
859
860 const char *ConstantExpr::getOpcodeName() const {
861   return Instruction::getOpcodeName(getOpcode());
862 }
863
864 unsigned Constant::mutateReferences(Value *OldV, Value *NewV) {
865   // Uses of constant pointer refs are global values, not constants!
866   if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(this)) {
867     GlobalValue *NewGV = cast<GlobalValue>(NewV);
868     GlobalValue *OldGV = CPR->getValue();
869
870     assert(OldGV == OldV && "Cannot mutate old value if I'm not using it!");
871     Operands[0] = NewGV;
872     OldGV->getParent()->mutateConstantPointerRef(OldGV, NewGV);
873     return 1;
874   } else {
875     Constant *NewC = cast<Constant>(NewV);
876     unsigned NumReplaced = 0;
877     for (unsigned i = 0, N = getNumOperands(); i != N; ++i)
878       if (Operands[i] == OldV) {
879         ++NumReplaced;
880         Operands[i] = NewC;
881       }
882     return NumReplaced;
883   }
884 }