- Dramatically simplify the Constant::mutateReferences implementation,
[oota-llvm.git] / lib / VMCore / Constants.cpp
1 //===-- Constants.cpp - Implement Constant nodes -----------------*- C++ -*--=//
2 //
3 // This file implements the Constant* classes...
4 //
5 //===----------------------------------------------------------------------===//
6
7 #include "llvm/Constants.h"
8 #include "llvm/DerivedTypes.h"
9 #include "llvm/iMemory.h"
10 #include "llvm/SymbolTable.h"
11 #include "llvm/Module.h"
12 #include "llvm/SlotCalculator.h"
13 #include "Support/StringExtras.h"
14 #include <algorithm>
15
16 using std::map;
17 using std::pair;
18 using std::make_pair;
19 using std::vector;
20
21 ConstantBool *ConstantBool::True  = new ConstantBool(true);
22 ConstantBool *ConstantBool::False = new ConstantBool(false);
23
24
25 //===----------------------------------------------------------------------===//
26 //                              Constant Class
27 //===----------------------------------------------------------------------===//
28
29 // Specialize setName to take care of symbol table majik
30 void Constant::setName(const std::string &Name, SymbolTable *ST) {
31   assert(ST && "Type::setName - Must provide symbol table argument!");
32
33   if (Name.size()) ST->insert(Name, this);
34 }
35
36 void Constant::destroyConstantImpl() {
37   // When a Constant is destroyed, there may be lingering
38   // references to the constant by other constants in the constant pool.  These
39   // constants are implicitly dependant on the module that is being deleted,
40   // but they don't know that.  Because we only find out when the CPV is
41   // deleted, we must now notify all of our users (that should only be
42   // Constants) that they are, in fact, invalid now and should be deleted.
43   //
44   while (!use_empty()) {
45     Value *V = use_back();
46 #ifndef NDEBUG      // Only in -g mode...
47     if (!isa<Constant>(V))
48       std::cerr << "While deleting: " << *this
49                 << "\n\nUse still stuck around after Def is destroyed: "
50                 << *V << "\n\n";
51 #endif
52     assert(isa<Constant>(V) && "References remain to Constant being destroyed");
53     Constant *CPV = cast<Constant>(V);
54     CPV->destroyConstant();
55
56     // The constant should remove itself from our use list...
57     assert((use_empty() || use_back() != V) && "Constant not removed!");
58   }
59
60   // Value has no outstanding references it is safe to delete it now...
61   delete this;
62 }
63
64 // Static constructor to create a '0' constant of arbitrary type...
65 Constant *Constant::getNullValue(const Type *Ty) {
66   switch (Ty->getPrimitiveID()) {
67   case Type::BoolTyID:   return ConstantBool::get(false);
68   case Type::SByteTyID:
69   case Type::ShortTyID:
70   case Type::IntTyID:
71   case Type::LongTyID:   return ConstantSInt::get(Ty, 0);
72
73   case Type::UByteTyID:
74   case Type::UShortTyID:
75   case Type::UIntTyID:
76   case Type::ULongTyID:  return ConstantUInt::get(Ty, 0);
77
78   case Type::FloatTyID:
79   case Type::DoubleTyID: return ConstantFP::get(Ty, 0);
80
81   case Type::PointerTyID: 
82     return ConstantPointerNull::get(cast<PointerType>(Ty));
83   default:
84     return 0;
85   }
86 }
87
88 // Static constructor to create the maximum constant of an integral type...
89 ConstantIntegral *ConstantIntegral::getMaxValue(const Type *Ty) {
90   switch (Ty->getPrimitiveID()) {
91   case Type::BoolTyID:   return ConstantBool::True;
92   case Type::SByteTyID:
93   case Type::ShortTyID:
94   case Type::IntTyID:
95   case Type::LongTyID: {
96     // Calculate 011111111111111... 
97     unsigned TypeBits = Ty->getPrimitiveSize()*8;
98     int64_t Val = INT64_MAX;             // All ones
99     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
100     return ConstantSInt::get(Ty, Val);
101   }
102
103   case Type::UByteTyID:
104   case Type::UShortTyID:
105   case Type::UIntTyID:
106   case Type::ULongTyID:  return getAllOnesValue(Ty);
107
108   default: return 0;
109   }
110 }
111
112 // Static constructor to create the minimum constant for an integral type...
113 ConstantIntegral *ConstantIntegral::getMinValue(const Type *Ty) {
114   switch (Ty->getPrimitiveID()) {
115   case Type::BoolTyID:   return ConstantBool::False;
116   case Type::SByteTyID:
117   case Type::ShortTyID:
118   case Type::IntTyID:
119   case Type::LongTyID: {
120      // Calculate 1111111111000000000000 
121      unsigned TypeBits = Ty->getPrimitiveSize()*8;
122      int64_t Val = -1;                    // All ones
123      Val <<= TypeBits-1;                  // Shift over to the right spot
124      return ConstantSInt::get(Ty, Val);
125   }
126
127   case Type::UByteTyID:
128   case Type::UShortTyID:
129   case Type::UIntTyID:
130   case Type::ULongTyID:  return ConstantUInt::get(Ty, 0);
131
132   default: return 0;
133   }
134 }
135
136 // Static constructor to create an integral constant with all bits set
137 ConstantIntegral *ConstantIntegral::getAllOnesValue(const Type *Ty) {
138   switch (Ty->getPrimitiveID()) {
139   case Type::BoolTyID:   return ConstantBool::True;
140   case Type::SByteTyID:
141   case Type::ShortTyID:
142   case Type::IntTyID:
143   case Type::LongTyID:   return ConstantSInt::get(Ty, -1);
144
145   case Type::UByteTyID:
146   case Type::UShortTyID:
147   case Type::UIntTyID:
148   case Type::ULongTyID: {
149     // Calculate ~0 of the right type...
150     unsigned TypeBits = Ty->getPrimitiveSize()*8;
151     uint64_t Val = ~0ULL;                // All ones
152     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
153     return ConstantUInt::get(Ty, Val);
154   }
155   default: return 0;
156   }
157 }
158
159
160 //===----------------------------------------------------------------------===//
161 //                            ConstantXXX Classes
162 //===----------------------------------------------------------------------===//
163
164 //===----------------------------------------------------------------------===//
165 //                             Normal Constructors
166
167 ConstantBool::ConstantBool(bool V) : ConstantIntegral(Type::BoolTy) {
168   Val = V;
169 }
170
171 ConstantInt::ConstantInt(const Type *Ty, uint64_t V) : ConstantIntegral(Ty) {
172   Val.Unsigned = V;
173 }
174
175 ConstantSInt::ConstantSInt(const Type *Ty, int64_t V) : ConstantInt(Ty, V) {
176   assert(Ty->isInteger() && Ty->isSigned() &&
177          "Illegal type for unsigned integer constant!");
178   assert(isValueValidForType(Ty, V) && "Value too large for type!");
179 }
180
181 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V) : ConstantInt(Ty, V) {
182   assert(Ty->isInteger() && Ty->isUnsigned() &&
183          "Illegal type for unsigned integer constant!");
184   assert(isValueValidForType(Ty, V) && "Value too large for type!");
185 }
186
187 ConstantFP::ConstantFP(const Type *Ty, double V) : Constant(Ty) {
188   assert(isValueValidForType(Ty, V) && "Value too large for type!");
189   Val = V;
190 }
191
192 ConstantArray::ConstantArray(const ArrayType *T,
193                              const std::vector<Constant*> &V) : Constant(T) {
194   Operands.reserve(V.size());
195   for (unsigned i = 0, e = V.size(); i != e; ++i) {
196     assert(V[i]->getType() == T->getElementType());
197     Operands.push_back(Use(V[i], this));
198   }
199 }
200
201 ConstantStruct::ConstantStruct(const StructType *T,
202                                const std::vector<Constant*> &V) : Constant(T) {
203   const StructType::ElementTypes &ETypes = T->getElementTypes();
204   assert(V.size() == ETypes.size() &&
205          "Invalid initializer vector for constant structure");
206   Operands.reserve(V.size());
207   for (unsigned i = 0, e = V.size(); i != e; ++i) {
208     assert(V[i]->getType() == ETypes[i]);
209     Operands.push_back(Use(V[i], this));
210   }
211 }
212
213 ConstantPointerRef::ConstantPointerRef(GlobalValue *GV)
214   : ConstantPointer(GV->getType()) {
215   Operands.push_back(Use(GV, this));
216 }
217
218 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
219   : Constant(Ty), iType(Opcode) {
220   Operands.push_back(Use(C, this));
221 }
222
223 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
224   : Constant(C1->getType()), iType(Opcode) {
225   Operands.push_back(Use(C1, this));
226   Operands.push_back(Use(C2, this));
227 }
228
229 ConstantExpr::ConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
230                            const Type *DestTy)
231   : Constant(DestTy), iType(Instruction::GetElementPtr) {
232   Operands.reserve(1+IdxList.size());
233   Operands.push_back(Use(C, this));
234   for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
235     Operands.push_back(Use(IdxList[i], this));
236 }
237
238
239
240 //===----------------------------------------------------------------------===//
241 //                           classof implementations
242
243 bool ConstantIntegral::classof(const Constant *CPV) {
244   return CPV->getType()->isIntegral() && !isa<ConstantExpr>(CPV);
245 }
246
247 bool ConstantInt::classof(const Constant *CPV) {
248   return CPV->getType()->isInteger() && !isa<ConstantExpr>(CPV);
249 }
250 bool ConstantSInt::classof(const Constant *CPV) {
251   return CPV->getType()->isSigned() && !isa<ConstantExpr>(CPV);
252 }
253 bool ConstantUInt::classof(const Constant *CPV) {
254   return CPV->getType()->isUnsigned() && !isa<ConstantExpr>(CPV);
255 }
256 bool ConstantFP::classof(const Constant *CPV) {
257   const Type *Ty = CPV->getType();
258   return ((Ty == Type::FloatTy || Ty == Type::DoubleTy) &&
259           !isa<ConstantExpr>(CPV));
260 }
261 bool ConstantArray::classof(const Constant *CPV) {
262   return isa<ArrayType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
263 }
264 bool ConstantStruct::classof(const Constant *CPV) {
265   return isa<StructType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
266 }
267 bool ConstantPointer::classof(const Constant *CPV) {
268   return (isa<PointerType>(CPV->getType()) && !isa<ConstantExpr>(CPV));
269 }
270
271
272
273 //===----------------------------------------------------------------------===//
274 //                      isValueValidForType implementations
275
276 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
277   switch (Ty->getPrimitiveID()) {
278   default:
279     return false;         // These can't be represented as integers!!!
280
281     // Signed types...
282   case Type::SByteTyID:
283     return (Val <= INT8_MAX && Val >= INT8_MIN);
284   case Type::ShortTyID:
285     return (Val <= INT16_MAX && Val >= INT16_MIN);
286   case Type::IntTyID:
287     return (Val <= INT32_MAX && Val >= INT32_MIN);
288   case Type::LongTyID:
289     return true;          // This is the largest type...
290   }
291   assert(0 && "WTF?");
292   return false;
293 }
294
295 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
296   switch (Ty->getPrimitiveID()) {
297   default:
298     return false;         // These can't be represented as integers!!!
299
300     // Unsigned types...
301   case Type::UByteTyID:
302     return (Val <= UINT8_MAX);
303   case Type::UShortTyID:
304     return (Val <= UINT16_MAX);
305   case Type::UIntTyID:
306     return (Val <= UINT32_MAX);
307   case Type::ULongTyID:
308     return true;          // This is the largest type...
309   }
310   assert(0 && "WTF?");
311   return false;
312 }
313
314 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
315   switch (Ty->getPrimitiveID()) {
316   default:
317     return false;         // These can't be represented as floating point!
318
319     // TODO: Figure out how to test if a double can be cast to a float!
320   case Type::FloatTyID:
321     /*
322     return (Val <= UINT8_MAX);
323     */
324   case Type::DoubleTyID:
325     return true;          // This is the largest type...
326   }
327 };
328
329 //===----------------------------------------------------------------------===//
330 //                replaceUsesOfWithOnConstant implementations
331
332 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To) {
333   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
334
335   std::vector<Constant*> Values;
336   Values.reserve(getValues().size());  // Build replacement array...
337   for (unsigned i = 0, e = getValues().size(); i != e; ++i) {
338     Constant *Val = cast<Constant>(getValues()[i]);
339     if (Val == From) Val = cast<Constant>(To);
340     Values.push_back(Val);
341   }
342   
343   ConstantArray *Replacement = ConstantArray::get(getType(), Values);
344   assert(Replacement != this && "I didn't contain From!");
345
346   // Everyone using this now uses the replacement...
347   replaceAllUsesWith(Replacement);
348   
349   // Delete the old constant!
350   destroyConstant();  
351 }
352
353 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To) {
354   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
355
356   std::vector<Constant*> Values;
357   Values.reserve(getValues().size());
358   for (unsigned i = 0, e = getValues().size(); i != e; ++i) {
359     Constant *Val = cast<Constant>(getValues()[i]);
360     if (Val == From) Val = cast<Constant>(To);
361     Values.push_back(Val);
362   }
363   
364   ConstantStruct *Replacement = ConstantStruct::get(getType(), Values);
365   assert(Replacement != this && "I didn't contain From!");
366
367   // Everyone using this now uses the replacement...
368   replaceAllUsesWith(Replacement);
369   
370   // Delete the old constant!
371   destroyConstant();
372 }
373
374 void ConstantPointerRef::replaceUsesOfWithOnConstant(Value *From, Value *To) {
375   if (isa<GlobalValue>(To)) {
376     assert(From == getOperand(0) && "Doesn't contain from!");
377     ConstantPointerRef *Replacement =
378       ConstantPointerRef::get(cast<GlobalValue>(To));
379     
380     // Everyone using this now uses the replacement...
381     replaceAllUsesWith(Replacement);
382     
383     // Delete the old constant!
384     destroyConstant();
385   } else {
386     // Just replace ourselves with the To value specified.
387     replaceAllUsesWith(To);
388   
389     // Delete the old constant!
390     destroyConstant();
391   }
392 }
393
394 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *To) {
395   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
396
397   ConstantExpr *Replacement = 0;
398   if (getOpcode() == Instruction::GetElementPtr) {
399     std::vector<Constant*> Indices;
400     Constant *Pointer = cast<Constant>(getOperand(0));
401     Indices.reserve(getNumOperands()-1);
402     if (Pointer == From) Pointer = cast<Constant>(To);
403     
404     for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
405       Constant *Val = cast<Constant>(getOperand(i));
406       if (Val == From) Val = cast<Constant>(To);
407       Indices.push_back(Val);
408     }
409     Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
410   } else if (getOpcode() == Instruction::Cast) {
411     assert(getOperand(0) == From && "Cast only has one use!");
412     Replacement = ConstantExpr::getCast(cast<Constant>(To), getType());
413   } else if (getNumOperands() == 2) {
414     Constant *C1 = cast<Constant>(getOperand(0));
415     Constant *C2 = cast<Constant>(getOperand(1));
416     if (C1 == From) C1 = cast<Constant>(To);
417     if (C2 == From) C2 = cast<Constant>(To);
418     Replacement = ConstantExpr::get(getOpcode(), C1, C2);
419   } else {
420     assert(0 && "Unknown ConstantExpr type!");
421     return;
422   }
423   
424   assert(Replacement != this && "I didn't contain From!");
425
426   // Everyone using this now uses the replacement...
427   replaceAllUsesWith(Replacement);
428   
429   // Delete the old constant!
430   destroyConstant();
431 }
432
433
434
435 //===----------------------------------------------------------------------===//
436 //                      Factory Function Implementation
437
438 template<class ValType, class ConstantClass>
439 struct ValueMap {
440   typedef pair<const Type*, ValType> ConstHashKey;
441   map<ConstHashKey, ConstantClass *> Map;
442
443   inline ConstantClass *get(const Type *Ty, ValType V) {
444     typename map<ConstHashKey,ConstantClass *>::iterator I =
445       Map.find(ConstHashKey(Ty, V));
446     return (I != Map.end()) ? I->second : 0;
447   }
448
449   inline void add(const Type *Ty, ValType V, ConstantClass *CP) {
450     Map.insert(make_pair(ConstHashKey(Ty, V), CP));
451   }
452
453   inline void remove(ConstantClass *CP) {
454     for (typename map<ConstHashKey,ConstantClass *>::iterator I = Map.begin(),
455                                                       E = Map.end(); I != E;++I)
456       if (I->second == CP) {
457         Map.erase(I);
458         return;
459       }
460   }
461 };
462
463 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
464 //
465 static ValueMap<uint64_t, ConstantInt> IntConstants;
466
467 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
468   ConstantSInt *Result = (ConstantSInt*)IntConstants.get(Ty, (uint64_t)V);
469   if (!Result)   // If no preexisting value, create one now...
470     IntConstants.add(Ty, V, Result = new ConstantSInt(Ty, V));
471   return Result;
472 }
473
474 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
475   ConstantUInt *Result = (ConstantUInt*)IntConstants.get(Ty, V);
476   if (!Result)   // If no preexisting value, create one now...
477     IntConstants.add(Ty, V, Result = new ConstantUInt(Ty, V));
478   return Result;
479 }
480
481 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
482   assert(V <= 127 && "Can only be used with very small positive constants!");
483   if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
484   return ConstantUInt::get(Ty, V);
485 }
486
487 //---- ConstantFP::get() implementation...
488 //
489 static ValueMap<double, ConstantFP> FPConstants;
490
491 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
492   ConstantFP *Result = FPConstants.get(Ty, V);
493   if (!Result)   // If no preexisting value, create one now...
494     FPConstants.add(Ty, V, Result = new ConstantFP(Ty, V));
495   return Result;
496 }
497
498 //---- ConstantArray::get() implementation...
499 //
500 static ValueMap<std::vector<Constant*>, ConstantArray> ArrayConstants;
501
502 ConstantArray *ConstantArray::get(const ArrayType *Ty,
503                                   const std::vector<Constant*> &V) {
504   ConstantArray *Result = ArrayConstants.get(Ty, V);
505   if (!Result)   // If no preexisting value, create one now...
506     ArrayConstants.add(Ty, V, Result = new ConstantArray(Ty, V));
507   return Result;
508 }
509
510 // ConstantArray::get(const string&) - Return an array that is initialized to
511 // contain the specified string.  A null terminator is added to the specified
512 // string so that it may be used in a natural way...
513 //
514 ConstantArray *ConstantArray::get(const std::string &Str) {
515   std::vector<Constant*> ElementVals;
516
517   for (unsigned i = 0; i < Str.length(); ++i)
518     ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
519
520   // Add a null terminator to the string...
521   ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
522
523   ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
524   return ConstantArray::get(ATy, ElementVals);
525 }
526
527
528 // destroyConstant - Remove the constant from the constant table...
529 //
530 void ConstantArray::destroyConstant() {
531   ArrayConstants.remove(this);
532   destroyConstantImpl();
533 }
534
535 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
536 // then this method converts the array to an std::string and returns it.
537 // Otherwise, it asserts out.
538 //
539 std::string ConstantArray::getAsString() const {
540   std::string Result;
541   if (getType()->getElementType() == Type::SByteTy)
542     for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
543       Result += (char)cast<ConstantSInt>(getOperand(i))->getValue();
544   else {
545     assert(getType()->getElementType() == Type::UByteTy && "Not a string!");
546     for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
547       Result += (char)cast<ConstantUInt>(getOperand(i))->getValue();
548   }
549   return Result;
550 }
551
552
553 //---- ConstantStruct::get() implementation...
554 //
555 static ValueMap<std::vector<Constant*>, ConstantStruct> StructConstants;
556
557 ConstantStruct *ConstantStruct::get(const StructType *Ty,
558                                     const std::vector<Constant*> &V) {
559   ConstantStruct *Result = StructConstants.get(Ty, V);
560   if (!Result)   // If no preexisting value, create one now...
561     StructConstants.add(Ty, V, Result = new ConstantStruct(Ty, V));
562   return Result;
563 }
564
565 // destroyConstant - Remove the constant from the constant table...
566 //
567 void ConstantStruct::destroyConstant() {
568   StructConstants.remove(this);
569   destroyConstantImpl();
570 }
571
572
573 //---- ConstantPointerNull::get() implementation...
574 //
575 static ValueMap<char, ConstantPointerNull> NullPtrConstants;
576
577 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
578   ConstantPointerNull *Result = NullPtrConstants.get(Ty, 0);
579   if (!Result)   // If no preexisting value, create one now...
580     NullPtrConstants.add(Ty, 0, Result = new ConstantPointerNull(Ty));
581   return Result;
582 }
583
584 // destroyConstant - Remove the constant from the constant table...
585 //
586 void ConstantPointerNull::destroyConstant() {
587   NullPtrConstants.remove(this);
588   destroyConstantImpl();
589 }
590
591
592 //---- ConstantPointerRef::get() implementation...
593 //
594 ConstantPointerRef *ConstantPointerRef::get(GlobalValue *GV) {
595   assert(GV->getParent() && "Global Value must be attached to a module!");
596   
597   // The Module handles the pointer reference sharing...
598   return GV->getParent()->getConstantPointerRef(GV);
599 }
600
601 // destroyConstant - Remove the constant from the constant table...
602 //
603 void ConstantPointerRef::destroyConstant() {
604   getValue()->getParent()->destroyConstantPointerRef(this);
605   destroyConstantImpl();
606 }
607
608
609 //---- ConstantExpr::get() implementations...
610 //
611 typedef pair<unsigned, vector<Constant*> > ExprMapKeyType;
612 static ValueMap<const ExprMapKeyType, ConstantExpr> ExprConstants;
613
614 ConstantExpr *ConstantExpr::getCast(Constant *C, const Type *Ty) {
615
616   // Look up the constant in the table first to ensure uniqueness
617   vector<Constant*> argVec(1, C);
618   const ExprMapKeyType &Key = make_pair(Instruction::Cast, argVec);
619   ConstantExpr *Result = ExprConstants.get(Ty, Key);
620   if (Result) return Result;
621   
622   // Its not in the table so create a new one and put it in the table.
623   Result = new ConstantExpr(Instruction::Cast, C, Ty);
624   ExprConstants.add(Ty, Key, Result);
625   return Result;
626 }
627
628 ConstantExpr *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
629   // Look up the constant in the table first to ensure uniqueness
630   vector<Constant*> argVec(1, C1); argVec.push_back(C2);
631   const ExprMapKeyType &Key = make_pair(Opcode, argVec);
632   ConstantExpr *Result = ExprConstants.get(C1->getType(), Key);
633   if (Result) return Result;
634   
635   // Its not in the table so create a new one and put it in the table.
636   // Check the operands for consistency first
637   assert((Opcode >= Instruction::BinaryOpsBegin &&
638           Opcode < Instruction::BinaryOpsEnd) &&
639          "Invalid opcode in binary constant expression");
640
641   assert(C1->getType() == C2->getType() &&
642          "Operand types in binary constant expression should match");
643   
644   Result = new ConstantExpr(Opcode, C1, C2);
645   ExprConstants.add(C1->getType(), Key, Result);
646   return Result;
647 }
648
649 ConstantExpr *ConstantExpr::getGetElementPtr(Constant *C,
650                                         const std::vector<Constant*> &IdxList) {
651   const Type *Ty = C->getType();
652
653   // Look up the constant in the table first to ensure uniqueness
654   vector<Constant*> argVec(1, C);
655   argVec.insert(argVec.end(), IdxList.begin(), IdxList.end());
656   
657   const ExprMapKeyType &Key = make_pair(Instruction::GetElementPtr, argVec);
658   ConstantExpr *Result = ExprConstants.get(Ty, 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   // 
664   assert(isa<PointerType>(Ty) &&
665          "Non-pointer type for constant GelElementPtr expression");
666
667   // Check that the indices list is valid...
668   std::vector<Value*> ValIdxList(IdxList.begin(), IdxList.end());
669   const Type *DestTy = GetElementPtrInst::getIndexedType(Ty, ValIdxList, true);
670   assert(DestTy && "Invalid index list for constant GelElementPtr expression");
671   
672   Result = new ConstantExpr(C, IdxList, PointerType::get(DestTy));
673   ExprConstants.add(Ty, Key, Result);
674   return Result;
675 }
676
677 // destroyConstant - Remove the constant from the constant table...
678 //
679 void ConstantExpr::destroyConstant() {
680   ExprConstants.remove(this);
681   destroyConstantImpl();
682 }
683
684 const char *ConstantExpr::getOpcodeName() const {
685   return Instruction::getOpcodeName(getOpcode());
686 }
687
688 unsigned Constant::mutateReferences(Value *OldV, Value *NewV) {
689   // Uses of constant pointer refs are global values, not constants!
690   if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(this)) {
691     GlobalValue *NewGV = cast<GlobalValue>(NewV);
692     GlobalValue *OldGV = CPR->getValue();
693
694     assert(OldGV == OldV && "Cannot mutate old value if I'm not using it!");
695
696     OldGV->getParent()->mutateConstantPointerRef(OldGV, NewGV);
697     Operands[0] = NewGV;
698     return 1;
699   } else {
700     Constant *NewC = cast<Constant>(NewV);
701     unsigned NumReplaced = 0;
702     for (unsigned i = 0, N = getNumOperands(); i != N; ++i)
703       if (Operands[i] == OldV) {
704         ++NumReplaced;
705         Operands[i] = NewC;
706       }
707     return NumReplaced;
708   }
709 }