499452c4251551cfb2f8062320ada03187f0c439
[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     Operands.push_back(Use(V[i], this));
230   }
231 }
232
233 ConstantPointerRef::ConstantPointerRef(GlobalValue *GV)
234   : ConstantPointer(GV->getType()) {
235   Operands.push_back(Use(GV, this));
236 }
237
238 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
239   : Constant(Ty), iType(Opcode) {
240   Operands.push_back(Use(C, this));
241 }
242
243 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
244   : Constant(C1->getType()), iType(Opcode) {
245   Operands.push_back(Use(C1, this));
246   Operands.push_back(Use(C2, this));
247 }
248
249 ConstantExpr::ConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
250                            const Type *DestTy)
251   : Constant(DestTy), iType(Instruction::GetElementPtr) {
252   Operands.reserve(1+IdxList.size());
253   Operands.push_back(Use(C, this));
254   for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
255     Operands.push_back(Use(IdxList[i], this));
256 }
257
258
259
260 //===----------------------------------------------------------------------===//
261 //                           classof implementations
262
263 bool ConstantIntegral::classof(const Constant *CPV) {
264   return CPV->getType()->isIntegral() && !isa<ConstantExpr>(CPV);
265 }
266
267 bool ConstantInt::classof(const Constant *CPV) {
268   return CPV->getType()->isInteger() && !isa<ConstantExpr>(CPV);
269 }
270 bool ConstantSInt::classof(const Constant *CPV) {
271   return CPV->getType()->isSigned() && !isa<ConstantExpr>(CPV);
272 }
273 bool ConstantUInt::classof(const Constant *CPV) {
274   return CPV->getType()->isUnsigned() && !isa<ConstantExpr>(CPV);
275 }
276 bool ConstantFP::classof(const Constant *CPV) {
277   const Type *Ty = CPV->getType();
278   return ((Ty == Type::FloatTy || Ty == Type::DoubleTy) &&
279           !isa<ConstantExpr>(CPV));
280 }
281 bool ConstantArray::classof(const Constant *CPV) {
282   return isa<ArrayType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
283 }
284 bool ConstantStruct::classof(const Constant *CPV) {
285   return isa<StructType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
286 }
287 bool ConstantPointer::classof(const Constant *CPV) {
288   return (isa<PointerType>(CPV->getType()) && !isa<ConstantExpr>(CPV));
289 }
290
291
292
293 //===----------------------------------------------------------------------===//
294 //                      isValueValidForType implementations
295
296 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
297   switch (Ty->getPrimitiveID()) {
298   default:
299     return false;         // These can't be represented as integers!!!
300
301     // Signed types...
302   case Type::SByteTyID:
303     return (Val <= INT8_MAX && Val >= INT8_MIN);
304   case Type::ShortTyID:
305     return (Val <= INT16_MAX && Val >= INT16_MIN);
306   case Type::IntTyID:
307     return (Val <= INT32_MAX && Val >= INT32_MIN);
308   case Type::LongTyID:
309     return true;          // This is the largest type...
310   }
311   assert(0 && "WTF?");
312   return false;
313 }
314
315 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
316   switch (Ty->getPrimitiveID()) {
317   default:
318     return false;         // These can't be represented as integers!!!
319
320     // Unsigned types...
321   case Type::UByteTyID:
322     return (Val <= UINT8_MAX);
323   case Type::UShortTyID:
324     return (Val <= UINT16_MAX);
325   case Type::UIntTyID:
326     return (Val <= UINT32_MAX);
327   case Type::ULongTyID:
328     return true;          // This is the largest type...
329   }
330   assert(0 && "WTF?");
331   return false;
332 }
333
334 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
335   switch (Ty->getPrimitiveID()) {
336   default:
337     return false;         // These can't be represented as floating point!
338
339     // TODO: Figure out how to test if a double can be cast to a float!
340   case Type::FloatTyID:
341     /*
342     return (Val <= UINT8_MAX);
343     */
344   case Type::DoubleTyID:
345     return true;          // This is the largest type...
346   }
347 };
348
349 //===----------------------------------------------------------------------===//
350 //                replaceUsesOfWithOnConstant implementations
351
352 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To) {
353   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
354
355   std::vector<Constant*> Values;
356   Values.reserve(getValues().size());  // Build replacement array...
357   for (unsigned i = 0, e = getValues().size(); i != e; ++i) {
358     Constant *Val = cast<Constant>(getValues()[i]);
359     if (Val == From) Val = cast<Constant>(To);
360     Values.push_back(Val);
361   }
362   
363   ConstantArray *Replacement = ConstantArray::get(getType(), Values);
364   assert(Replacement != this && "I didn't contain From!");
365
366   // Everyone using this now uses the replacement...
367   replaceAllUsesWith(Replacement);
368   
369   // Delete the old constant!
370   destroyConstant();  
371 }
372
373 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To) {
374   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
375
376   std::vector<Constant*> Values;
377   Values.reserve(getValues().size());
378   for (unsigned i = 0, e = getValues().size(); i != e; ++i) {
379     Constant *Val = cast<Constant>(getValues()[i]);
380     if (Val == From) Val = cast<Constant>(To);
381     Values.push_back(Val);
382   }
383   
384   ConstantStruct *Replacement = ConstantStruct::get(getType(), Values);
385   assert(Replacement != this && "I didn't contain From!");
386
387   // Everyone using this now uses the replacement...
388   replaceAllUsesWith(Replacement);
389   
390   // Delete the old constant!
391   destroyConstant();
392 }
393
394 void ConstantPointerRef::replaceUsesOfWithOnConstant(Value *From, Value *To) {
395   if (isa<GlobalValue>(To)) {
396     assert(From == getOperand(0) && "Doesn't contain from!");
397     ConstantPointerRef *Replacement =
398       ConstantPointerRef::get(cast<GlobalValue>(To));
399     
400     // Everyone using this now uses the replacement...
401     replaceAllUsesWith(Replacement);
402     
403     // Delete the old constant!
404     destroyConstant();
405   } else {
406     // Just replace ourselves with the To value specified.
407     replaceAllUsesWith(To);
408   
409     // Delete the old constant!
410     destroyConstant();
411   }
412 }
413
414 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *To) {
415   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
416
417   Constant *Replacement = 0;
418   if (getOpcode() == Instruction::GetElementPtr) {
419     std::vector<Constant*> Indices;
420     Constant *Pointer = cast<Constant>(getOperand(0));
421     Indices.reserve(getNumOperands()-1);
422     if (Pointer == From) Pointer = cast<Constant>(To);
423     
424     for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
425       Constant *Val = cast<Constant>(getOperand(i));
426       if (Val == From) Val = cast<Constant>(To);
427       Indices.push_back(Val);
428     }
429     Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
430   } else if (getOpcode() == Instruction::Cast) {
431     assert(getOperand(0) == From && "Cast only has one use!");
432     Replacement = ConstantExpr::getCast(cast<Constant>(To), getType());
433   } else if (getNumOperands() == 2) {
434     Constant *C1 = cast<Constant>(getOperand(0));
435     Constant *C2 = cast<Constant>(getOperand(1));
436     if (C1 == From) C1 = cast<Constant>(To);
437     if (C2 == From) C2 = cast<Constant>(To);
438     Replacement = ConstantExpr::get(getOpcode(), C1, C2);
439   } else {
440     assert(0 && "Unknown ConstantExpr type!");
441     return;
442   }
443   
444   assert(Replacement != this && "I didn't contain From!");
445
446   // Everyone using this now uses the replacement...
447   replaceAllUsesWith(Replacement);
448   
449   // Delete the old constant!
450   destroyConstant();
451 }
452
453
454
455 //===----------------------------------------------------------------------===//
456 //                      Factory Function Implementation
457
458 template<class ValType, class ConstantClass>
459 struct ValueMap {
460   typedef std::pair<const Type*, ValType> ConstHashKey;
461   std::map<ConstHashKey, ConstantClass *> Map;
462
463   inline ConstantClass *get(const Type *Ty, ValType V) {
464     typename std::map<ConstHashKey,ConstantClass *>::iterator I =
465       Map.find(ConstHashKey(Ty, V));
466     return (I != Map.end()) ? I->second : 0;
467   }
468
469   inline void add(const Type *Ty, ValType V, ConstantClass *CP) {
470     Map.insert(std::make_pair(ConstHashKey(Ty, V), CP));
471   }
472
473   inline void remove(ConstantClass *CP) {
474     for (typename std::map<ConstHashKey, ConstantClass*>::iterator
475            I = Map.begin(), E = Map.end(); I != E; ++I)
476       if (I->second == CP) {
477         Map.erase(I);
478         return;
479       }
480   }
481 };
482
483 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
484 //
485 static ValueMap<uint64_t, ConstantInt> IntConstants;
486
487 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
488   ConstantSInt *Result = (ConstantSInt*)IntConstants.get(Ty, (uint64_t)V);
489   if (!Result)   // If no preexisting value, create one now...
490     IntConstants.add(Ty, V, Result = new ConstantSInt(Ty, V));
491   return Result;
492 }
493
494 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
495   ConstantUInt *Result = (ConstantUInt*)IntConstants.get(Ty, V);
496   if (!Result)   // If no preexisting value, create one now...
497     IntConstants.add(Ty, V, Result = new ConstantUInt(Ty, V));
498   return Result;
499 }
500
501 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
502   assert(V <= 127 && "Can only be used with very small positive constants!");
503   if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
504   return ConstantUInt::get(Ty, V);
505 }
506
507 //---- ConstantFP::get() implementation...
508 //
509 static ValueMap<double, ConstantFP> FPConstants;
510
511 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
512   ConstantFP *Result = FPConstants.get(Ty, V);
513   if (!Result)   // If no preexisting value, create one now...
514     FPConstants.add(Ty, V, Result = new ConstantFP(Ty, V));
515   return Result;
516 }
517
518 //---- ConstantArray::get() implementation...
519 //
520 static ValueMap<std::vector<Constant*>, ConstantArray> ArrayConstants;
521
522 ConstantArray *ConstantArray::get(const ArrayType *Ty,
523                                   const std::vector<Constant*> &V) {
524   ConstantArray *Result = ArrayConstants.get(Ty, V);
525   if (!Result)   // If no preexisting value, create one now...
526     ArrayConstants.add(Ty, V, Result = new ConstantArray(Ty, V));
527   return Result;
528 }
529
530 // ConstantArray::get(const string&) - Return an array that is initialized to
531 // contain the specified string.  A null terminator is added to the specified
532 // string so that it may be used in a natural way...
533 //
534 ConstantArray *ConstantArray::get(const std::string &Str) {
535   std::vector<Constant*> ElementVals;
536
537   for (unsigned i = 0; i < Str.length(); ++i)
538     ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
539
540   // Add a null terminator to the string...
541   ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
542
543   ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
544   return ConstantArray::get(ATy, ElementVals);
545 }
546
547
548 // destroyConstant - Remove the constant from the constant table...
549 //
550 void ConstantArray::destroyConstant() {
551   ArrayConstants.remove(this);
552   destroyConstantImpl();
553 }
554
555 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
556 // then this method converts the array to an std::string and returns it.
557 // Otherwise, it asserts out.
558 //
559 std::string ConstantArray::getAsString() const {
560   std::string Result;
561   if (getType()->getElementType() == Type::SByteTy)
562     for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
563       Result += (char)cast<ConstantSInt>(getOperand(i))->getValue();
564   else {
565     assert(getType()->getElementType() == Type::UByteTy && "Not a string!");
566     for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
567       Result += (char)cast<ConstantUInt>(getOperand(i))->getValue();
568   }
569   return Result;
570 }
571
572
573 //---- ConstantStruct::get() implementation...
574 //
575 static ValueMap<std::vector<Constant*>, ConstantStruct> StructConstants;
576
577 ConstantStruct *ConstantStruct::get(const StructType *Ty,
578                                     const std::vector<Constant*> &V) {
579   ConstantStruct *Result = StructConstants.get(Ty, V);
580   if (!Result)   // If no preexisting value, create one now...
581     StructConstants.add(Ty, V, Result = new ConstantStruct(Ty, V));
582   return Result;
583 }
584
585 // destroyConstant - Remove the constant from the constant table...
586 //
587 void ConstantStruct::destroyConstant() {
588   StructConstants.remove(this);
589   destroyConstantImpl();
590 }
591
592
593 //---- ConstantPointerNull::get() implementation...
594 //
595 static ValueMap<char, ConstantPointerNull> NullPtrConstants;
596
597 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
598   ConstantPointerNull *Result = NullPtrConstants.get(Ty, 0);
599   if (!Result)   // If no preexisting value, create one now...
600     NullPtrConstants.add(Ty, 0, Result = new ConstantPointerNull(Ty));
601   return Result;
602 }
603
604 // destroyConstant - Remove the constant from the constant table...
605 //
606 void ConstantPointerNull::destroyConstant() {
607   NullPtrConstants.remove(this);
608   destroyConstantImpl();
609 }
610
611
612 //---- ConstantPointerRef::get() implementation...
613 //
614 ConstantPointerRef *ConstantPointerRef::get(GlobalValue *GV) {
615   assert(GV->getParent() && "Global Value must be attached to a module!");
616   
617   // The Module handles the pointer reference sharing...
618   return GV->getParent()->getConstantPointerRef(GV);
619 }
620
621 // destroyConstant - Remove the constant from the constant table...
622 //
623 void ConstantPointerRef::destroyConstant() {
624   getValue()->getParent()->destroyConstantPointerRef(this);
625   destroyConstantImpl();
626 }
627
628
629 //---- ConstantExpr::get() implementations...
630 //
631 typedef std::pair<unsigned, std::vector<Constant*> > ExprMapKeyType;
632 static ValueMap<const ExprMapKeyType, ConstantExpr> ExprConstants;
633
634 Constant *ConstantExpr::getCast(Constant *C, const Type *Ty) {
635   if (Constant *FC = ConstantFoldCastInstruction(C, Ty))
636     return FC;          // Fold a few common cases...
637
638   // Look up the constant in the table first to ensure uniqueness
639   std::vector<Constant*> argVec(1, C);
640   const ExprMapKeyType &Key = std::make_pair(Instruction::Cast, argVec);
641   ConstantExpr *Result = ExprConstants.get(Ty, Key);
642   if (Result) return Result;
643   
644   // Its not in the table so create a new one and put it in the table.
645   Result = new ConstantExpr(Instruction::Cast, C, Ty);
646   ExprConstants.add(Ty, Key, Result);
647   return Result;
648 }
649
650 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
651   
652   if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
653     return FC;          // Fold a few common cases...
654
655   // Look up the constant in the table first to ensure uniqueness
656   std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
657   const ExprMapKeyType &Key = std::make_pair(Opcode, argVec);
658   ConstantExpr *Result = ExprConstants.get(C1->getType(), Key);
659   if (Result) return Result;
660   
661   // Its not in the table so create a new one and put it in the table.
662   // Check the operands for consistency first
663   assert((Opcode >= Instruction::BinaryOpsBegin &&
664           Opcode < Instruction::BinaryOpsEnd) &&
665          "Invalid opcode in binary constant expression");
666
667   assert(C1->getType() == C2->getType() &&
668          "Operand types in binary constant expression should match");
669   
670   Result = new ConstantExpr(Opcode, C1, C2);
671   ExprConstants.add(C1->getType(), Key, Result);
672   return Result;
673 }
674
675 Constant *ConstantExpr::getGetElementPtr(Constant *C,
676                                          const std::vector<Constant*> &IdxList){
677   if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
678     return FC;          // Fold a few common cases...
679   const Type *Ty = C->getType();
680
681   // Look up the constant in the table first to ensure uniqueness
682   std::vector<Constant*> argVec(1, C);
683   argVec.insert(argVec.end(), IdxList.begin(), IdxList.end());
684   
685   const ExprMapKeyType &Key = std::make_pair(Instruction::GetElementPtr,argVec);
686   ConstantExpr *Result = ExprConstants.get(Ty, Key);
687   if (Result) return Result;
688
689   // Its not in the table so create a new one and put it in the table.
690   // Check the operands for consistency first
691   // 
692   assert(isa<PointerType>(Ty) &&
693          "Non-pointer type for constant GelElementPtr expression");
694
695   // Check that the indices list is valid...
696   std::vector<Value*> ValIdxList(IdxList.begin(), IdxList.end());
697   const Type *DestTy = GetElementPtrInst::getIndexedType(Ty, ValIdxList, true);
698   assert(DestTy && "Invalid index list for constant GelElementPtr expression");
699   
700   Result = new ConstantExpr(C, IdxList, PointerType::get(DestTy));
701   ExprConstants.add(Ty, Key, Result);
702   return Result;
703 }
704
705 // destroyConstant - Remove the constant from the constant table...
706 //
707 void ConstantExpr::destroyConstant() {
708   ExprConstants.remove(this);
709   destroyConstantImpl();
710 }
711
712 const char *ConstantExpr::getOpcodeName() const {
713   return Instruction::getOpcodeName(getOpcode());
714 }
715
716 unsigned Constant::mutateReferences(Value *OldV, Value *NewV) {
717   // Uses of constant pointer refs are global values, not constants!
718   if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(this)) {
719     GlobalValue *NewGV = cast<GlobalValue>(NewV);
720     GlobalValue *OldGV = CPR->getValue();
721
722     assert(OldGV == OldV && "Cannot mutate old value if I'm not using it!");
723
724     OldGV->getParent()->mutateConstantPointerRef(OldGV, NewGV);
725     Operands[0] = NewGV;
726     return 1;
727   } else {
728     Constant *NewC = cast<Constant>(NewV);
729     unsigned NumReplaced = 0;
730     for (unsigned i = 0, N = getNumOperands(); i != N; ++i)
731       if (Operands[i] == OldV) {
732         ++NumReplaced;
733         Operands[i] = NewC;
734       }
735     return NumReplaced;
736   }
737 }