implement new helper method
[oota-llvm.git] / lib / VMCore / Constants.cpp
1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Constant* classes...
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Constants.h"
15 #include "ConstantFolding.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/iMemory.h"
18 #include "llvm/SymbolTable.h"
19 #include "llvm/Module.h"
20 #include "Support/StringExtras.h"
21 #include <algorithm>
22 #include <iostream>
23 using namespace llvm;
24
25 ConstantBool *ConstantBool::True  = new ConstantBool(true);
26 ConstantBool *ConstantBool::False = new ConstantBool(false);
27
28
29 //===----------------------------------------------------------------------===//
30 //                              Constant Class
31 //===----------------------------------------------------------------------===//
32
33 // Specialize setName to take care of symbol table majik
34 void Constant::setName(const std::string &Name, SymbolTable *ST) {
35   assert(ST && "Type::setName - Must provide symbol table argument!");
36
37   if (Name.size()) ST->insert(Name, this);
38 }
39
40 void Constant::destroyConstantImpl() {
41   // When a Constant is destroyed, there may be lingering
42   // references to the constant by other constants in the constant pool.  These
43   // constants are implicitly dependent on the module that is being deleted,
44   // but they don't know that.  Because we only find out when the CPV is
45   // deleted, we must now notify all of our users (that should only be
46   // Constants) that they are, in fact, invalid now and should be deleted.
47   //
48   while (!use_empty()) {
49     Value *V = use_back();
50 #ifndef NDEBUG      // Only in -g mode...
51     if (!isa<Constant>(V))
52       std::cerr << "While deleting: " << *this
53                 << "\n\nUse still stuck around after Def is destroyed: "
54                 << *V << "\n\n";
55 #endif
56     assert(isa<Constant>(V) && "References remain to Constant being destroyed");
57     Constant *CPV = cast<Constant>(V);
58     CPV->destroyConstant();
59
60     // The constant should remove itself from our use list...
61     assert((use_empty() || use_back() != V) && "Constant not removed!");
62   }
63
64   // Value has no outstanding references it is safe to delete it now...
65   delete this;
66 }
67
68 // Static constructor to create a '0' constant of arbitrary type...
69 Constant *Constant::getNullValue(const Type *Ty) {
70   switch (Ty->getTypeID()) {
71   case Type::BoolTyID: {
72     static Constant *NullBool = ConstantBool::get(false);
73     return NullBool;
74   }
75   case Type::SByteTyID: {
76     static Constant *NullSByte = ConstantSInt::get(Type::SByteTy, 0);
77     return NullSByte;
78   }
79   case Type::UByteTyID: {
80     static Constant *NullUByte = ConstantUInt::get(Type::UByteTy, 0);
81     return NullUByte;
82   }
83   case Type::ShortTyID: {
84     static Constant *NullShort = ConstantSInt::get(Type::ShortTy, 0);
85     return NullShort;
86   }
87   case Type::UShortTyID: {
88     static Constant *NullUShort = ConstantUInt::get(Type::UShortTy, 0);
89     return NullUShort;
90   }
91   case Type::IntTyID: {
92     static Constant *NullInt = ConstantSInt::get(Type::IntTy, 0);
93     return NullInt;
94   }
95   case Type::UIntTyID: {
96     static Constant *NullUInt = ConstantUInt::get(Type::UIntTy, 0);
97     return NullUInt;
98   }
99   case Type::LongTyID: {
100     static Constant *NullLong = ConstantSInt::get(Type::LongTy, 0);
101     return NullLong;
102   }
103   case Type::ULongTyID: {
104     static Constant *NullULong = ConstantUInt::get(Type::ULongTy, 0);
105     return NullULong;
106   }
107
108   case Type::FloatTyID: {
109     static Constant *NullFloat = ConstantFP::get(Type::FloatTy, 0);
110     return NullFloat;
111   }
112   case Type::DoubleTyID: {
113     static Constant *NullDouble = ConstantFP::get(Type::DoubleTy, 0);
114     return NullDouble;
115   }
116
117   case Type::PointerTyID: 
118     return ConstantPointerNull::get(cast<PointerType>(Ty));
119
120   case Type::StructTyID:
121   case Type::ArrayTyID:
122     return ConstantAggregateZero::get(Ty);
123   default:
124     // Function, Label, or Opaque type?
125     assert(!"Cannot create a null constant of that type!");
126     return 0;
127   }
128 }
129
130 // Static constructor to create the maximum constant of an integral type...
131 ConstantIntegral *ConstantIntegral::getMaxValue(const Type *Ty) {
132   switch (Ty->getTypeID()) {
133   case Type::BoolTyID:   return ConstantBool::True;
134   case Type::SByteTyID:
135   case Type::ShortTyID:
136   case Type::IntTyID:
137   case Type::LongTyID: {
138     // Calculate 011111111111111... 
139     unsigned TypeBits = Ty->getPrimitiveSize()*8;
140     int64_t Val = INT64_MAX;             // All ones
141     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
142     return ConstantSInt::get(Ty, Val);
143   }
144
145   case Type::UByteTyID:
146   case Type::UShortTyID:
147   case Type::UIntTyID:
148   case Type::ULongTyID:  return getAllOnesValue(Ty);
149
150   default: return 0;
151   }
152 }
153
154 // Static constructor to create the minimum constant for an integral type...
155 ConstantIntegral *ConstantIntegral::getMinValue(const Type *Ty) {
156   switch (Ty->getTypeID()) {
157   case Type::BoolTyID:   return ConstantBool::False;
158   case Type::SByteTyID:
159   case Type::ShortTyID:
160   case Type::IntTyID:
161   case Type::LongTyID: {
162      // Calculate 1111111111000000000000 
163      unsigned TypeBits = Ty->getPrimitiveSize()*8;
164      int64_t Val = -1;                    // All ones
165      Val <<= TypeBits-1;                  // Shift over to the right spot
166      return ConstantSInt::get(Ty, Val);
167   }
168
169   case Type::UByteTyID:
170   case Type::UShortTyID:
171   case Type::UIntTyID:
172   case Type::ULongTyID:  return ConstantUInt::get(Ty, 0);
173
174   default: return 0;
175   }
176 }
177
178 // Static constructor to create an integral constant with all bits set
179 ConstantIntegral *ConstantIntegral::getAllOnesValue(const Type *Ty) {
180   switch (Ty->getTypeID()) {
181   case Type::BoolTyID:   return ConstantBool::True;
182   case Type::SByteTyID:
183   case Type::ShortTyID:
184   case Type::IntTyID:
185   case Type::LongTyID:   return ConstantSInt::get(Ty, -1);
186
187   case Type::UByteTyID:
188   case Type::UShortTyID:
189   case Type::UIntTyID:
190   case Type::ULongTyID: {
191     // Calculate ~0 of the right type...
192     unsigned TypeBits = Ty->getPrimitiveSize()*8;
193     uint64_t Val = ~0ULL;                // All ones
194     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
195     return ConstantUInt::get(Ty, Val);
196   }
197   default: return 0;
198   }
199 }
200
201 bool ConstantUInt::isAllOnesValue() const {
202   unsigned TypeBits = getType()->getPrimitiveSize()*8;
203   uint64_t Val = ~0ULL;                // All ones
204   Val >>= 64-TypeBits;                 // Shift out inappropriate bits
205   return getValue() == Val;
206 }
207
208
209 //===----------------------------------------------------------------------===//
210 //                            ConstantXXX Classes
211 //===----------------------------------------------------------------------===//
212
213 //===----------------------------------------------------------------------===//
214 //                             Normal Constructors
215
216 ConstantIntegral::ConstantIntegral(const Type *Ty, uint64_t V)
217   : Constant(Ty) {
218     Val.Unsigned = V;
219 }
220
221 ConstantBool::ConstantBool(bool V) : ConstantIntegral(Type::BoolTy, V) {
222 }
223
224 ConstantInt::ConstantInt(const Type *Ty, uint64_t V) : ConstantIntegral(Ty, V) {
225 }
226
227 ConstantSInt::ConstantSInt(const Type *Ty, int64_t V) : ConstantInt(Ty, V) {
228   assert(Ty->isInteger() && Ty->isSigned() &&
229          "Illegal type for unsigned integer constant!");
230   assert(isValueValidForType(Ty, V) && "Value too large for type!");
231 }
232
233 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V) : ConstantInt(Ty, V) {
234   assert(Ty->isInteger() && Ty->isUnsigned() &&
235          "Illegal type for unsigned integer constant!");
236   assert(isValueValidForType(Ty, V) && "Value too large for type!");
237 }
238
239 ConstantFP::ConstantFP(const Type *Ty, double V) : Constant(Ty) {
240   assert(isValueValidForType(Ty, V) && "Value too large for type!");
241   Val = V;
242 }
243
244 ConstantArray::ConstantArray(const ArrayType *T,
245                              const std::vector<Constant*> &V) : Constant(T) {
246   Operands.reserve(V.size());
247   for (unsigned i = 0, e = V.size(); i != e; ++i) {
248     assert(V[i]->getType() == T->getElementType() ||
249            (T->isAbstract() &&
250             V[i]->getType()->getTypeID() == T->getElementType()->getTypeID()));
251     Operands.push_back(Use(V[i], this));
252   }
253 }
254
255 ConstantStruct::ConstantStruct(const StructType *T,
256                                const std::vector<Constant*> &V) : Constant(T) {
257   assert(V.size() == T->getNumElements() &&
258          "Invalid initializer vector for constant structure");
259   Operands.reserve(V.size());
260   for (unsigned i = 0, e = V.size(); i != e; ++i) {
261     assert((V[i]->getType() == T->getElementType(i) ||
262             ((T->getElementType(i)->isAbstract() ||
263               V[i]->getType()->isAbstract()) &&
264              T->getElementType(i)->getTypeID() == V[i]->getType()->getTypeID())) &&
265            "Initializer for struct element doesn't match struct element type!");
266     Operands.push_back(Use(V[i], this));
267   }
268 }
269
270 ConstantPointerRef::ConstantPointerRef(GlobalValue *GV)
271   : Constant(GV->getType()) {
272   Operands.reserve(1);
273   Operands.push_back(Use(GV, this));
274 }
275
276 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
277   : Constant(Ty), iType(Opcode) {
278   Operands.reserve(1);
279   Operands.push_back(Use(C, this));
280 }
281
282 // Select instruction creation ctor
283 ConstantExpr::ConstantExpr(Constant *C, Constant *V1, Constant *V2)
284   : Constant(V1->getType()), iType(Instruction::Select) {
285   Operands.reserve(3);
286   Operands.push_back(Use(C, this));
287   Operands.push_back(Use(V1, this));
288   Operands.push_back(Use(V2, this));
289 }
290
291
292 static bool isSetCC(unsigned Opcode) {
293   return Opcode == Instruction::SetEQ || Opcode == Instruction::SetNE ||
294          Opcode == Instruction::SetLT || Opcode == Instruction::SetGT ||
295          Opcode == Instruction::SetLE || Opcode == Instruction::SetGE;
296 }
297
298 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
299   : Constant(isSetCC(Opcode) ? Type::BoolTy : C1->getType()), iType(Opcode) {
300   Operands.reserve(2);
301   Operands.push_back(Use(C1, this));
302   Operands.push_back(Use(C2, this));
303 }
304
305 ConstantExpr::ConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
306                            const Type *DestTy)
307   : Constant(DestTy), iType(Instruction::GetElementPtr) {
308   Operands.reserve(1+IdxList.size());
309   Operands.push_back(Use(C, this));
310   for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
311     Operands.push_back(Use(IdxList[i], this));
312 }
313
314 /// ConstantExpr::get* - Return some common constants without having to
315 /// specify the full Instruction::OPCODE identifier.
316 ///
317 Constant *ConstantExpr::getNeg(Constant *C) {
318   if (!C->getType()->isFloatingPoint())
319     return get(Instruction::Sub, getNullValue(C->getType()), C);
320   else
321     return get(Instruction::Sub, ConstantFP::get(C->getType(), -0.0), C);
322 }
323 Constant *ConstantExpr::getNot(Constant *C) {
324   assert(isa<ConstantIntegral>(C) && "Cannot NOT a nonintegral type!");
325   return get(Instruction::Xor, C,
326              ConstantIntegral::getAllOnesValue(C->getType()));
327 }
328 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
329   return get(Instruction::Add, C1, C2);
330 }
331 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
332   return get(Instruction::Sub, C1, C2);
333 }
334 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
335   return get(Instruction::Mul, C1, C2);
336 }
337 Constant *ConstantExpr::getDiv(Constant *C1, Constant *C2) {
338   return get(Instruction::Div, C1, C2);
339 }
340 Constant *ConstantExpr::getRem(Constant *C1, Constant *C2) {
341   return get(Instruction::Rem, C1, C2);
342 }
343 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
344   return get(Instruction::And, C1, C2);
345 }
346 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
347   return get(Instruction::Or, C1, C2);
348 }
349 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
350   return get(Instruction::Xor, C1, C2);
351 }
352 Constant *ConstantExpr::getSetEQ(Constant *C1, Constant *C2) {
353   return get(Instruction::SetEQ, C1, C2);
354 }
355 Constant *ConstantExpr::getSetNE(Constant *C1, Constant *C2) {
356   return get(Instruction::SetNE, C1, C2);
357 }
358 Constant *ConstantExpr::getSetLT(Constant *C1, Constant *C2) {
359   return get(Instruction::SetLT, C1, C2);
360 }
361 Constant *ConstantExpr::getSetGT(Constant *C1, Constant *C2) {
362   return get(Instruction::SetGT, C1, C2);
363 }
364 Constant *ConstantExpr::getSetLE(Constant *C1, Constant *C2) {
365   return get(Instruction::SetLE, C1, C2);
366 }
367 Constant *ConstantExpr::getSetGE(Constant *C1, Constant *C2) {
368   return get(Instruction::SetGE, C1, C2);
369 }
370 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
371   return get(Instruction::Shl, C1, C2);
372 }
373 Constant *ConstantExpr::getShr(Constant *C1, Constant *C2) {
374   return get(Instruction::Shr, C1, C2);
375 }
376
377 Constant *ConstantExpr::getUShr(Constant *C1, Constant *C2) {
378   if (C1->getType()->isUnsigned()) return getShr(C1, C2);
379   return getCast(getShr(getCast(C1,
380                     C1->getType()->getUnsignedVersion()), C2), C1->getType());
381 }
382
383 Constant *ConstantExpr::getSShr(Constant *C1, Constant *C2) {
384   if (C1->getType()->isSigned()) return getShr(C1, C2);
385   return getCast(getShr(getCast(C1,
386                         C1->getType()->getSignedVersion()), C2), C1->getType());
387 }
388
389
390 //===----------------------------------------------------------------------===//
391 //                           classof implementations
392
393 bool ConstantIntegral::classof(const Constant *CPV) {
394   return CPV->getType()->isIntegral() && !isa<ConstantExpr>(CPV);
395 }
396
397 bool ConstantInt::classof(const Constant *CPV) {
398   return CPV->getType()->isInteger() && !isa<ConstantExpr>(CPV);
399 }
400 bool ConstantSInt::classof(const Constant *CPV) {
401   return CPV->getType()->isSigned() && !isa<ConstantExpr>(CPV);
402 }
403 bool ConstantUInt::classof(const Constant *CPV) {
404   return CPV->getType()->isUnsigned() && !isa<ConstantExpr>(CPV);
405 }
406 bool ConstantFP::classof(const Constant *CPV) {
407   const Type *Ty = CPV->getType();
408   return ((Ty == Type::FloatTy || Ty == Type::DoubleTy) &&
409           !isa<ConstantExpr>(CPV));
410 }
411 bool ConstantAggregateZero::classof(const Constant *CPV) {
412   return (isa<ArrayType>(CPV->getType()) || isa<StructType>(CPV->getType())) &&
413          CPV->isNullValue();
414 }
415 bool ConstantArray::classof(const Constant *CPV) {
416   return isa<ArrayType>(CPV->getType()) && !CPV->isNullValue();
417 }
418 bool ConstantStruct::classof(const Constant *CPV) {
419   return isa<StructType>(CPV->getType()) && !CPV->isNullValue();
420 }
421
422 bool ConstantPointerNull::classof(const Constant *CPV) {
423   return isa<PointerType>(CPV->getType()) && !isa<ConstantExpr>(CPV) &&
424          CPV->getNumOperands() == 0;
425 }
426
427 bool ConstantPointerRef::classof(const Constant *CPV) {
428   return isa<PointerType>(CPV->getType()) && !isa<ConstantExpr>(CPV) &&
429          CPV->getNumOperands() == 1;
430 }
431
432
433
434 //===----------------------------------------------------------------------===//
435 //                      isValueValidForType implementations
436
437 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
438   switch (Ty->getTypeID()) {
439   default:
440     return false;         // These can't be represented as integers!!!
441     // Signed types...
442   case Type::SByteTyID:
443     return (Val <= INT8_MAX && Val >= INT8_MIN);
444   case Type::ShortTyID:
445     return (Val <= INT16_MAX && Val >= INT16_MIN);
446   case Type::IntTyID:
447     return (Val <= int(INT32_MAX) && Val >= int(INT32_MIN));
448   case Type::LongTyID:
449     return true;          // This is the largest type...
450   }
451 }
452
453 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
454   switch (Ty->getTypeID()) {
455   default:
456     return false;         // These can't be represented as integers!!!
457
458     // Unsigned types...
459   case Type::UByteTyID:
460     return (Val <= UINT8_MAX);
461   case Type::UShortTyID:
462     return (Val <= UINT16_MAX);
463   case Type::UIntTyID:
464     return (Val <= UINT32_MAX);
465   case Type::ULongTyID:
466     return true;          // This is the largest type...
467   }
468 }
469
470 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
471   switch (Ty->getTypeID()) {
472   default:
473     return false;         // These can't be represented as floating point!
474
475     // TODO: Figure out how to test if a double can be cast to a float!
476   case Type::FloatTyID:
477   case Type::DoubleTyID:
478     return true;          // This is the largest type...
479   }
480 };
481
482 //===----------------------------------------------------------------------===//
483 //                replaceUsesOfWithOnConstant implementations
484
485 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
486                                                 bool DisableChecking) {
487   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
488
489   std::vector<Constant*> Values;
490   Values.reserve(getValues().size());  // Build replacement array...
491   for (unsigned i = 0, e = getValues().size(); i != e; ++i) {
492     Constant *Val = cast<Constant>(getValues()[i]);
493     if (Val == From) Val = cast<Constant>(To);
494     Values.push_back(Val);
495   }
496   
497   Constant *Replacement = ConstantArray::get(getType(), Values);
498   assert(Replacement != this && "I didn't contain From!");
499
500   // Everyone using this now uses the replacement...
501   if (DisableChecking)
502     uncheckedReplaceAllUsesWith(Replacement);
503   else
504     replaceAllUsesWith(Replacement);
505   
506   // Delete the old constant!
507   destroyConstant();  
508 }
509
510 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
511                                                  bool DisableChecking) {
512   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
513
514   std::vector<Constant*> Values;
515   Values.reserve(getValues().size());
516   for (unsigned i = 0, e = getValues().size(); i != e; ++i) {
517     Constant *Val = cast<Constant>(getValues()[i]);
518     if (Val == From) Val = cast<Constant>(To);
519     Values.push_back(Val);
520   }
521   
522   Constant *Replacement = ConstantStruct::get(getType(), Values);
523   assert(Replacement != this && "I didn't contain From!");
524
525   // Everyone using this now uses the replacement...
526   if (DisableChecking)
527     uncheckedReplaceAllUsesWith(Replacement);
528   else
529     replaceAllUsesWith(Replacement);
530   
531   // Delete the old constant!
532   destroyConstant();
533 }
534
535 void ConstantPointerRef::replaceUsesOfWithOnConstant(Value *From, Value *To,
536                                                      bool DisableChecking) {
537   if (isa<GlobalValue>(To)) {
538     assert(From == getOperand(0) && "Doesn't contain from!");
539     ConstantPointerRef *Replacement =
540       ConstantPointerRef::get(cast<GlobalValue>(To));
541     
542     // Everyone using this now uses the replacement...
543     if (DisableChecking)
544       uncheckedReplaceAllUsesWith(Replacement);
545     else
546       replaceAllUsesWith(Replacement);
547     
548   } else {
549     // Just replace ourselves with the To value specified.
550     if (DisableChecking)
551       uncheckedReplaceAllUsesWith(To);
552     else
553       replaceAllUsesWith(To);
554   }
555
556   // Delete the old constant!
557   destroyConstant();
558 }
559
560 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
561                                                bool DisableChecking) {
562   assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
563   Constant *To = cast<Constant>(ToV);
564
565   Constant *Replacement = 0;
566   if (getOpcode() == Instruction::GetElementPtr) {
567     std::vector<Constant*> Indices;
568     Constant *Pointer = getOperand(0);
569     Indices.reserve(getNumOperands()-1);
570     if (Pointer == From) Pointer = To;
571     
572     for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
573       Constant *Val = getOperand(i);
574       if (Val == From) Val = To;
575       Indices.push_back(Val);
576     }
577     Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
578   } else if (getOpcode() == Instruction::Cast) {
579     assert(getOperand(0) == From && "Cast only has one use!");
580     Replacement = ConstantExpr::getCast(To, getType());
581   } else if (getOpcode() == Instruction::Select) {
582     Constant *C1 = getOperand(0);
583     Constant *C2 = getOperand(1);
584     Constant *C3 = getOperand(2);
585     if (C1 == From) C1 = To;
586     if (C2 == From) C2 = To;
587     if (C3 == From) C3 = To;
588     Replacement = ConstantExpr::getSelect(C1, C2, C3);
589   } else if (getNumOperands() == 2) {
590     Constant *C1 = getOperand(0);
591     Constant *C2 = getOperand(1);
592     if (C1 == From) C1 = To;
593     if (C2 == From) C2 = To;
594     Replacement = ConstantExpr::get(getOpcode(), C1, C2);
595   } else {
596     assert(0 && "Unknown ConstantExpr type!");
597     return;
598   }
599   
600   assert(Replacement != this && "I didn't contain From!");
601
602   // Everyone using this now uses the replacement...
603   if (DisableChecking)
604     uncheckedReplaceAllUsesWith(Replacement);
605   else
606     replaceAllUsesWith(Replacement);
607   
608   // Delete the old constant!
609   destroyConstant();
610 }
611
612 //===----------------------------------------------------------------------===//
613 //                      Factory Function Implementation
614
615 // ConstantCreator - A class that is used to create constants by
616 // ValueMap*.  This class should be partially specialized if there is
617 // something strange that needs to be done to interface to the ctor for the
618 // constant.
619 //
620 namespace llvm {
621   template<class ConstantClass, class TypeClass, class ValType>
622   struct ConstantCreator {
623     static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
624       return new ConstantClass(Ty, V);
625     }
626   };
627   
628   template<class ConstantClass, class TypeClass>
629   struct ConvertConstantType {
630     static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
631       assert(0 && "This type cannot be converted!\n");
632       abort();
633     }
634   };
635 }
636
637 namespace {
638   template<class ValType, class TypeClass, class ConstantClass>
639   class ValueMap : public AbstractTypeUser {
640     typedef std::pair<const TypeClass*, ValType> MapKey;
641     typedef std::map<MapKey, ConstantClass *> MapTy;
642     typedef typename MapTy::iterator MapIterator;
643     MapTy Map;
644
645     typedef std::map<const TypeClass*, MapIterator> AbstractTypeMapTy;
646     AbstractTypeMapTy AbstractTypeMap;
647   public:
648     // getOrCreate - Return the specified constant from the map, creating it if
649     // necessary.
650     ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
651       MapKey Lookup(Ty, V);
652       MapIterator I = Map.lower_bound(Lookup);
653       if (I != Map.end() && I->first == Lookup)
654         return I->second;  // Is it in the map?
655
656       // If no preexisting value, create one now...
657       ConstantClass *Result =
658         ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
659
660
661       /// FIXME: why does this assert fail when loading 176.gcc?
662       //assert(Result->getType() == Ty && "Type specified is not correct!");
663       I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
664
665       // If the type of the constant is abstract, make sure that an entry exists
666       // for it in the AbstractTypeMap.
667       if (Ty->isAbstract()) {
668         typename AbstractTypeMapTy::iterator TI =
669           AbstractTypeMap.lower_bound(Ty);
670
671         if (TI == AbstractTypeMap.end() || TI->first != Ty) {
672           // Add ourselves to the ATU list of the type.
673           cast<DerivedType>(Ty)->addAbstractTypeUser(this);
674
675           AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
676         }
677       }
678       return Result;
679     }
680     
681     void remove(ConstantClass *CP) {
682       // FIXME: This should not use a linear scan.  If this gets to be a
683       // performance problem, someone should look at this.
684       MapIterator I = Map.begin();
685       for (MapIterator E = Map.end(); I != E && I->second != CP; ++I)
686         /* empty */;
687       
688       assert(I != Map.end() && "Constant not found in constant table!");
689
690       // Now that we found the entry, make sure this isn't the entry that
691       // the AbstractTypeMap points to.
692       const TypeClass *Ty = I->first.first;
693       if (Ty->isAbstract()) {
694         assert(AbstractTypeMap.count(Ty) &&
695                "Abstract type not in AbstractTypeMap?");
696         MapIterator &ATMEntryIt = AbstractTypeMap[Ty];
697         if (ATMEntryIt == I) {
698           // Yes, we are removing the representative entry for this type.
699           // See if there are any other entries of the same type.
700           MapIterator TmpIt = ATMEntryIt;
701           
702           // First check the entry before this one...
703           if (TmpIt != Map.begin()) {
704             --TmpIt;
705             if (TmpIt->first.first != Ty) // Not the same type, move back...
706               ++TmpIt;
707           }
708           
709           // If we didn't find the same type, try to move forward...
710           if (TmpIt == ATMEntryIt) {
711             ++TmpIt;
712             if (TmpIt == Map.end() || TmpIt->first.first != Ty)
713               --TmpIt;   // No entry afterwards with the same type
714           }
715
716           // If there is another entry in the map of the same abstract type,
717           // update the AbstractTypeMap entry now.
718           if (TmpIt != ATMEntryIt) {
719             ATMEntryIt = TmpIt;
720           } else {
721             // Otherwise, we are removing the last instance of this type
722             // from the table.  Remove from the ATM, and from user list.
723             cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
724             AbstractTypeMap.erase(Ty);
725           }
726         }
727       }
728       
729       Map.erase(I);
730     }
731
732     void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
733       typename AbstractTypeMapTy::iterator I = 
734         AbstractTypeMap.find(cast<TypeClass>(OldTy));
735
736       assert(I != AbstractTypeMap.end() &&
737              "Abstract type not in AbstractTypeMap?");
738
739       // Convert a constant at a time until the last one is gone.  The last one
740       // leaving will remove() itself, causing the AbstractTypeMapEntry to be
741       // eliminated eventually.
742       do {
743         ConvertConstantType<ConstantClass,
744                             TypeClass>::convert(I->second->second,
745                                                 cast<TypeClass>(NewTy));
746
747         I = AbstractTypeMap.find(cast<TypeClass>(OldTy));
748       } while (I != AbstractTypeMap.end());
749     }
750
751     // If the type became concrete without being refined to any other existing
752     // type, we just remove ourselves from the ATU list.
753     void typeBecameConcrete(const DerivedType *AbsTy) {
754       AbsTy->removeAbstractTypeUser(this);
755     }
756
757     void dump() const {
758       std::cerr << "Constant.cpp: ValueMap\n";
759     }
760   };
761 }
762
763
764
765 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
766 //
767 static ValueMap< int64_t, Type, ConstantSInt> SIntConstants;
768 static ValueMap<uint64_t, Type, ConstantUInt> UIntConstants;
769
770 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
771   return SIntConstants.getOrCreate(Ty, V);
772 }
773
774 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
775   return UIntConstants.getOrCreate(Ty, V);
776 }
777
778 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
779   assert(V <= 127 && "Can only be used with very small positive constants!");
780   if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
781   return ConstantUInt::get(Ty, V);
782 }
783
784 //---- ConstantFP::get() implementation...
785 //
786 namespace llvm {
787   template<>
788   struct ConstantCreator<ConstantFP, Type, uint64_t> {
789     static ConstantFP *create(const Type *Ty, uint64_t V) {
790       assert(Ty == Type::DoubleTy);
791       union {
792         double F;
793         uint64_t I;
794       } T;
795       T.I = V;
796       return new ConstantFP(Ty, T.F);
797     }
798   };
799   template<>
800   struct ConstantCreator<ConstantFP, Type, uint32_t> {
801     static ConstantFP *create(const Type *Ty, uint32_t V) {
802       assert(Ty == Type::FloatTy);
803       union {
804         float F;
805         uint32_t I;
806       } T;
807       T.I = V;
808       return new ConstantFP(Ty, T.F);
809     }
810   };
811 }
812
813 static ValueMap<uint64_t, Type, ConstantFP> DoubleConstants;
814 static ValueMap<uint32_t, Type, ConstantFP> FloatConstants;
815
816 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
817   if (Ty == Type::FloatTy) {
818     // Force the value through memory to normalize it.
819     union {
820       float F;
821       uint32_t I;
822     } T;
823     T.F = (float)V;
824     return FloatConstants.getOrCreate(Ty, T.I);
825   } else {
826     assert(Ty == Type::DoubleTy);
827     union {
828       double F;
829       uint64_t I;
830     } T;
831     T.F = V;
832     return DoubleConstants.getOrCreate(Ty, T.I);
833   }
834 }
835
836 //---- ConstantAggregateZero::get() implementation...
837 //
838 namespace llvm {
839   // ConstantAggregateZero does not take extra "value" argument...
840   template<class ValType>
841   struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
842     static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
843       return new ConstantAggregateZero(Ty);
844     }
845   };
846
847   template<>
848   struct ConvertConstantType<ConstantAggregateZero, Type> {
849     static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
850       // Make everyone now use a constant of the new type...
851       Constant *New = ConstantAggregateZero::get(NewTy);
852       assert(New != OldC && "Didn't replace constant??");
853       OldC->uncheckedReplaceAllUsesWith(New);
854       OldC->destroyConstant();     // This constant is now dead, destroy it.
855     }
856   };
857 }
858
859 static ValueMap<char, Type, ConstantAggregateZero> AggZeroConstants;
860
861 Constant *ConstantAggregateZero::get(const Type *Ty) {
862   return AggZeroConstants.getOrCreate(Ty, 0);
863 }
864
865 // destroyConstant - Remove the constant from the constant table...
866 //
867 void ConstantAggregateZero::destroyConstant() {
868   AggZeroConstants.remove(this);
869   destroyConstantImpl();
870 }
871
872 void ConstantAggregateZero::replaceUsesOfWithOnConstant(Value *From, Value *To,
873                                                         bool DisableChecking) {
874   assert(0 && "No uses!");
875   abort();
876 }
877
878
879
880 //---- ConstantArray::get() implementation...
881 //
882 namespace llvm {
883   template<>
884   struct ConvertConstantType<ConstantArray, ArrayType> {
885     static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
886       // Make everyone now use a constant of the new type...
887       std::vector<Constant*> C;
888       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
889         C.push_back(cast<Constant>(OldC->getOperand(i)));
890       Constant *New = ConstantArray::get(NewTy, C);
891       assert(New != OldC && "Didn't replace constant??");
892       OldC->uncheckedReplaceAllUsesWith(New);
893       OldC->destroyConstant();    // This constant is now dead, destroy it.
894     }
895   };
896 }
897
898 static ValueMap<std::vector<Constant*>, ArrayType,
899                 ConstantArray> ArrayConstants;
900
901 Constant *ConstantArray::get(const ArrayType *Ty,
902                              const std::vector<Constant*> &V) {
903   // If this is an all-zero array, return a ConstantAggregateZero object
904   if (!V.empty()) {
905     Constant *C = V[0];
906     if (!C->isNullValue())
907       return ArrayConstants.getOrCreate(Ty, V);
908     for (unsigned i = 1, e = V.size(); i != e; ++i)
909       if (V[i] != C)
910         return ArrayConstants.getOrCreate(Ty, V);
911   }
912   return ConstantAggregateZero::get(Ty);
913 }
914
915 // destroyConstant - Remove the constant from the constant table...
916 //
917 void ConstantArray::destroyConstant() {
918   ArrayConstants.remove(this);
919   destroyConstantImpl();
920 }
921
922 // ConstantArray::get(const string&) - Return an array that is initialized to
923 // contain the specified string.  A null terminator is added to the specified
924 // string so that it may be used in a natural way...
925 //
926 Constant *ConstantArray::get(const std::string &Str) {
927   std::vector<Constant*> ElementVals;
928
929   for (unsigned i = 0; i < Str.length(); ++i)
930     ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
931
932   // Add a null terminator to the string...
933   ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
934
935   ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
936   return ConstantArray::get(ATy, ElementVals);
937 }
938
939 /// isString - This method returns true if the array is an array of sbyte or
940 /// ubyte, and if the elements of the array are all ConstantInt's.
941 bool ConstantArray::isString() const {
942   // Check the element type for sbyte or ubyte...
943   if (getType()->getElementType() != Type::UByteTy &&
944       getType()->getElementType() != Type::SByteTy)
945     return false;
946   // Check the elements to make sure they are all integers, not constant
947   // expressions.
948   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
949     if (!isa<ConstantInt>(getOperand(i)))
950       return false;
951   return true;
952 }
953
954 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
955 // then this method converts the array to an std::string and returns it.
956 // Otherwise, it asserts out.
957 //
958 std::string ConstantArray::getAsString() const {
959   assert(isString() && "Not a string!");
960   std::string Result;
961   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
962     Result += (char)cast<ConstantInt>(getOperand(i))->getRawValue();
963   return Result;
964 }
965
966
967 //---- ConstantStruct::get() implementation...
968 //
969
970 namespace llvm {
971   template<>
972   struct ConvertConstantType<ConstantStruct, StructType> {
973     static void convert(ConstantStruct *OldC, const StructType *NewTy) {
974       // Make everyone now use a constant of the new type...
975       std::vector<Constant*> C;
976       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
977         C.push_back(cast<Constant>(OldC->getOperand(i)));
978       Constant *New = ConstantStruct::get(NewTy, C);
979       assert(New != OldC && "Didn't replace constant??");
980       
981       OldC->uncheckedReplaceAllUsesWith(New);
982       OldC->destroyConstant();    // This constant is now dead, destroy it.
983     }
984   };
985 }
986
987 static ValueMap<std::vector<Constant*>, StructType, 
988                 ConstantStruct> StructConstants;
989
990 Constant *ConstantStruct::get(const StructType *Ty,
991                               const std::vector<Constant*> &V) {
992   // Create a ConstantAggregateZero value if all elements are zeros...
993   for (unsigned i = 0, e = V.size(); i != e; ++i)
994     if (!V[i]->isNullValue())
995       return StructConstants.getOrCreate(Ty, V);
996
997   return ConstantAggregateZero::get(Ty);
998 }
999
1000 Constant *ConstantStruct::get(const std::vector<Constant*> &V) {
1001   std::vector<const Type*> StructEls;
1002   StructEls.reserve(V.size());
1003   for (unsigned i = 0, e = V.size(); i != e; ++i)
1004     StructEls.push_back(V[i]->getType());
1005   return get(StructType::get(StructEls), V);
1006 }
1007
1008 // destroyConstant - Remove the constant from the constant table...
1009 //
1010 void ConstantStruct::destroyConstant() {
1011   StructConstants.remove(this);
1012   destroyConstantImpl();
1013 }
1014
1015 //---- ConstantPointerNull::get() implementation...
1016 //
1017
1018 namespace llvm {
1019   // ConstantPointerNull does not take extra "value" argument...
1020   template<class ValType>
1021   struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1022     static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1023       return new ConstantPointerNull(Ty);
1024     }
1025   };
1026
1027   template<>
1028   struct ConvertConstantType<ConstantPointerNull, PointerType> {
1029     static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1030       // Make everyone now use a constant of the new type...
1031       Constant *New = ConstantPointerNull::get(NewTy);
1032       assert(New != OldC && "Didn't replace constant??");
1033       OldC->uncheckedReplaceAllUsesWith(New);
1034       OldC->destroyConstant();     // This constant is now dead, destroy it.
1035     }
1036   };
1037 }
1038
1039 static ValueMap<char, PointerType, ConstantPointerNull> NullPtrConstants;
1040
1041 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1042   return NullPtrConstants.getOrCreate(Ty, 0);
1043 }
1044
1045 // destroyConstant - Remove the constant from the constant table...
1046 //
1047 void ConstantPointerNull::destroyConstant() {
1048   NullPtrConstants.remove(this);
1049   destroyConstantImpl();
1050 }
1051
1052
1053 //---- ConstantPointerRef::get() implementation...
1054 //
1055 ConstantPointerRef *ConstantPointerRef::get(GlobalValue *GV) {
1056   assert(GV->getParent() && "Global Value must be attached to a module!");
1057   
1058   // The Module handles the pointer reference sharing...
1059   return GV->getParent()->getConstantPointerRef(GV);
1060 }
1061
1062 // destroyConstant - Remove the constant from the constant table...
1063 //
1064 void ConstantPointerRef::destroyConstant() {
1065   getValue()->getParent()->destroyConstantPointerRef(this);
1066   destroyConstantImpl();
1067 }
1068
1069
1070 //---- ConstantExpr::get() implementations...
1071 //
1072 typedef std::pair<unsigned, std::vector<Constant*> > ExprMapKeyType;
1073
1074 namespace llvm {
1075   template<>
1076   struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1077     static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V) {
1078       if (V.first == Instruction::Cast)
1079         return new ConstantExpr(Instruction::Cast, V.second[0], Ty);
1080       if ((V.first >= Instruction::BinaryOpsBegin &&
1081            V.first < Instruction::BinaryOpsEnd) ||
1082           V.first == Instruction::Shl || V.first == Instruction::Shr)
1083         return new ConstantExpr(V.first, V.second[0], V.second[1]);
1084       if (V.first == Instruction::Select)
1085         return new ConstantExpr(V.second[0], V.second[1], V.second[2]);
1086       
1087       assert(V.first == Instruction::GetElementPtr && "Invalid ConstantExpr!");
1088       
1089       std::vector<Constant*> IdxList(V.second.begin()+1, V.second.end());
1090       return new ConstantExpr(V.second[0], IdxList, Ty);
1091     }
1092   };
1093
1094   template<>
1095   struct ConvertConstantType<ConstantExpr, Type> {
1096     static void convert(ConstantExpr *OldC, const Type *NewTy) {
1097       Constant *New;
1098       switch (OldC->getOpcode()) {
1099       case Instruction::Cast:
1100         New = ConstantExpr::getCast(OldC->getOperand(0), NewTy);
1101         break;
1102       case Instruction::Select:
1103         New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1104                                         OldC->getOperand(1),
1105                                         OldC->getOperand(2));
1106         break;
1107       case Instruction::Shl:
1108       case Instruction::Shr:
1109         New = ConstantExpr::getShiftTy(NewTy, OldC->getOpcode(),
1110                                      OldC->getOperand(0), OldC->getOperand(1));
1111         break;
1112       default:
1113         assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1114                OldC->getOpcode() < Instruction::BinaryOpsEnd);
1115         New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1116                                   OldC->getOperand(1));
1117         break;
1118       case Instruction::GetElementPtr:
1119         // Make everyone now use a constant of the new type... 
1120         std::vector<Constant*> C;
1121         for (unsigned i = 1, e = OldC->getNumOperands(); i != e; ++i)
1122           C.push_back(cast<Constant>(OldC->getOperand(i)));
1123         New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0), C);
1124         break;
1125       }
1126       
1127       assert(New != OldC && "Didn't replace constant??");
1128       OldC->uncheckedReplaceAllUsesWith(New);
1129       OldC->destroyConstant();    // This constant is now dead, destroy it.
1130     }
1131   };
1132 } // end namespace llvm
1133
1134
1135 static ValueMap<ExprMapKeyType, Type, ConstantExpr> ExprConstants;
1136
1137 Constant *ConstantExpr::getCast(Constant *C, const Type *Ty) {
1138   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1139
1140   if (Constant *FC = ConstantFoldCastInstruction(C, Ty))
1141     return FC;          // Fold a few common cases...
1142
1143   // Look up the constant in the table first to ensure uniqueness
1144   std::vector<Constant*> argVec(1, C);
1145   ExprMapKeyType Key = std::make_pair(Instruction::Cast, argVec);
1146   return ExprConstants.getOrCreate(Ty, Key);
1147 }
1148
1149 Constant *ConstantExpr::getSignExtend(Constant *C, const Type *Ty) {
1150   assert(C->getType()->isInteger() && Ty->isInteger() &&
1151          C->getType()->getPrimitiveSize() <= Ty->getPrimitiveSize() &&
1152          "This is an illegal sign extension!");
1153   C = ConstantExpr::getCast(C, C->getType()->getSignedVersion());
1154   return ConstantExpr::getCast(C, Ty);
1155 }
1156
1157 Constant *ConstantExpr::getZeroExtend(Constant *C, const Type *Ty) {
1158   assert(C->getType()->isInteger() && Ty->isInteger() &&
1159          C->getType()->getPrimitiveSize() <= Ty->getPrimitiveSize() &&
1160          "This is an illegal zero extension!");
1161   C = ConstantExpr::getCast(C, C->getType()->getUnsignedVersion());
1162   return ConstantExpr::getCast(C, Ty);
1163 }
1164
1165 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1166                               Constant *C1, Constant *C2) {
1167   if (Opcode == Instruction::Shl || Opcode == Instruction::Shr)
1168     return getShiftTy(ReqTy, Opcode, C1, C2);
1169   // Check the operands for consistency first
1170   assert((Opcode >= Instruction::BinaryOpsBegin &&
1171           Opcode < Instruction::BinaryOpsEnd) &&
1172          "Invalid opcode in binary constant expression");
1173   assert(C1->getType() == C2->getType() &&
1174          "Operand types in binary constant expression should match");
1175
1176   if (ReqTy == C1->getType())
1177     if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1178       return FC;          // Fold a few common cases...
1179
1180   std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1181   ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1182   return ExprConstants.getOrCreate(ReqTy, Key);
1183 }
1184
1185 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1186                                     Constant *V1, Constant *V2) {
1187   assert(C->getType() == Type::BoolTy && "Select condition must be bool!");
1188   assert(V1->getType() == V2->getType() && "Select value types must match!");
1189   assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1190
1191   if (ReqTy == V1->getType())
1192     if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1193       return SC;        // Fold common cases
1194
1195   std::vector<Constant*> argVec(3, C);
1196   argVec[1] = V1;
1197   argVec[2] = V2;
1198   ExprMapKeyType Key = std::make_pair(Instruction::Select, argVec);
1199   return ExprConstants.getOrCreate(ReqTy, Key);
1200 }
1201
1202 /// getShiftTy - Return a shift left or shift right constant expr
1203 Constant *ConstantExpr::getShiftTy(const Type *ReqTy, unsigned Opcode,
1204                                    Constant *C1, Constant *C2) {
1205   // Check the operands for consistency first
1206   assert((Opcode == Instruction::Shl ||
1207           Opcode == Instruction::Shr) &&
1208          "Invalid opcode in binary constant expression");
1209   assert(C1->getType()->isIntegral() && C2->getType() == Type::UByteTy &&
1210          "Invalid operand types for Shift constant expr!");
1211
1212   if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1213     return FC;          // Fold a few common cases...
1214
1215   // Look up the constant in the table first to ensure uniqueness
1216   std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1217   ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1218   return ExprConstants.getOrCreate(ReqTy, Key);
1219 }
1220
1221
1222 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1223                                         const std::vector<Constant*> &IdxList) {
1224   assert(GetElementPtrInst::getIndexedType(C->getType(),
1225                    std::vector<Value*>(IdxList.begin(), IdxList.end()), true) &&
1226          "GEP indices invalid!");
1227
1228   if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
1229     return FC;          // Fold a few common cases...
1230
1231   assert(isa<PointerType>(C->getType()) &&
1232          "Non-pointer type for constant GetElementPtr expression");
1233   // Look up the constant in the table first to ensure uniqueness
1234   std::vector<Constant*> argVec(1, C);
1235   argVec.insert(argVec.end(), IdxList.begin(), IdxList.end());
1236   const ExprMapKeyType &Key = std::make_pair(Instruction::GetElementPtr,argVec);
1237   return ExprConstants.getOrCreate(ReqTy, Key);
1238 }
1239
1240 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1241                                          const std::vector<Constant*> &IdxList){
1242   // Get the result type of the getelementptr!
1243   std::vector<Value*> VIdxList(IdxList.begin(), IdxList.end());
1244
1245   const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), VIdxList,
1246                                                      true);
1247   assert(Ty && "GEP indices invalid!");
1248   return getGetElementPtrTy(PointerType::get(Ty), C, IdxList);
1249 }
1250
1251
1252 // destroyConstant - Remove the constant from the constant table...
1253 //
1254 void ConstantExpr::destroyConstant() {
1255   ExprConstants.remove(this);
1256   destroyConstantImpl();
1257 }
1258
1259 const char *ConstantExpr::getOpcodeName() const {
1260   return Instruction::getOpcodeName(getOpcode());
1261 }