Constants never get names.
[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/GlobalValue.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/SymbolTable.h"
20 #include "llvm/Module.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include <algorithm>
23 #include <iostream>
24 using namespace llvm;
25
26 ConstantBool *ConstantBool::True  = new ConstantBool(true);
27 ConstantBool *ConstantBool::False = new ConstantBool(false);
28
29
30 //===----------------------------------------------------------------------===//
31 //                              Constant Class
32 //===----------------------------------------------------------------------===//
33
34 void Constant::setName(const std::string &Name) {
35   // Constants can't take names.
36 }
37
38 void Constant::destroyConstantImpl() {
39   // When a Constant is destroyed, there may be lingering
40   // references to the constant by other constants in the constant pool.  These
41   // constants are implicitly dependent on the module that is being deleted,
42   // but they don't know that.  Because we only find out when the CPV is
43   // deleted, we must now notify all of our users (that should only be
44   // Constants) that they are, in fact, invalid now and should be deleted.
45   //
46   while (!use_empty()) {
47     Value *V = use_back();
48 #ifndef NDEBUG      // Only in -g mode...
49     if (!isa<Constant>(V))
50       std::cerr << "While deleting: " << *this
51                 << "\n\nUse still stuck around after Def is destroyed: "
52                 << *V << "\n\n";
53 #endif
54     assert(isa<Constant>(V) && "References remain to Constant being destroyed");
55     Constant *CV = cast<Constant>(V);
56     CV->destroyConstant();
57
58     // The constant should remove itself from our use list...
59     assert((use_empty() || use_back() != V) && "Constant not removed!");
60   }
61
62   // Value has no outstanding references it is safe to delete it now...
63   delete this;
64 }
65
66 // Static constructor to create a '0' constant of arbitrary type...
67 Constant *Constant::getNullValue(const Type *Ty) {
68   switch (Ty->getTypeID()) {
69   case Type::BoolTyID: {
70     static Constant *NullBool = ConstantBool::get(false);
71     return NullBool;
72   }
73   case Type::SByteTyID: {
74     static Constant *NullSByte = ConstantSInt::get(Type::SByteTy, 0);
75     return NullSByte;
76   }
77   case Type::UByteTyID: {
78     static Constant *NullUByte = ConstantUInt::get(Type::UByteTy, 0);
79     return NullUByte;
80   }
81   case Type::ShortTyID: {
82     static Constant *NullShort = ConstantSInt::get(Type::ShortTy, 0);
83     return NullShort;
84   }
85   case Type::UShortTyID: {
86     static Constant *NullUShort = ConstantUInt::get(Type::UShortTy, 0);
87     return NullUShort;
88   }
89   case Type::IntTyID: {
90     static Constant *NullInt = ConstantSInt::get(Type::IntTy, 0);
91     return NullInt;
92   }
93   case Type::UIntTyID: {
94     static Constant *NullUInt = ConstantUInt::get(Type::UIntTy, 0);
95     return NullUInt;
96   }
97   case Type::LongTyID: {
98     static Constant *NullLong = ConstantSInt::get(Type::LongTy, 0);
99     return NullLong;
100   }
101   case Type::ULongTyID: {
102     static Constant *NullULong = ConstantUInt::get(Type::ULongTy, 0);
103     return NullULong;
104   }
105
106   case Type::FloatTyID: {
107     static Constant *NullFloat = ConstantFP::get(Type::FloatTy, 0);
108     return NullFloat;
109   }
110   case Type::DoubleTyID: {
111     static Constant *NullDouble = ConstantFP::get(Type::DoubleTy, 0);
112     return NullDouble;
113   }
114
115   case Type::PointerTyID: 
116     return ConstantPointerNull::get(cast<PointerType>(Ty));
117
118   case Type::StructTyID:
119   case Type::ArrayTyID:
120   case Type::PackedTyID:
121     return ConstantAggregateZero::get(Ty);
122   default:
123     // Function, Label, or Opaque type?
124     assert(!"Cannot create a null constant of that type!");
125     return 0;
126   }
127 }
128
129 // Static constructor to create the maximum constant of an integral type...
130 ConstantIntegral *ConstantIntegral::getMaxValue(const Type *Ty) {
131   switch (Ty->getTypeID()) {
132   case Type::BoolTyID:   return ConstantBool::True;
133   case Type::SByteTyID:
134   case Type::ShortTyID:
135   case Type::IntTyID:
136   case Type::LongTyID: {
137     // Calculate 011111111111111... 
138     unsigned TypeBits = Ty->getPrimitiveSize()*8;
139     int64_t Val = INT64_MAX;             // All ones
140     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
141     return ConstantSInt::get(Ty, Val);
142   }
143
144   case Type::UByteTyID:
145   case Type::UShortTyID:
146   case Type::UIntTyID:
147   case Type::ULongTyID:  return getAllOnesValue(Ty);
148
149   default: return 0;
150   }
151 }
152
153 // Static constructor to create the minimum constant for an integral type...
154 ConstantIntegral *ConstantIntegral::getMinValue(const Type *Ty) {
155   switch (Ty->getTypeID()) {
156   case Type::BoolTyID:   return ConstantBool::False;
157   case Type::SByteTyID:
158   case Type::ShortTyID:
159   case Type::IntTyID:
160   case Type::LongTyID: {
161      // Calculate 1111111111000000000000 
162      unsigned TypeBits = Ty->getPrimitiveSize()*8;
163      int64_t Val = -1;                    // All ones
164      Val <<= TypeBits-1;                  // Shift over to the right spot
165      return ConstantSInt::get(Ty, Val);
166   }
167
168   case Type::UByteTyID:
169   case Type::UShortTyID:
170   case Type::UIntTyID:
171   case Type::ULongTyID:  return ConstantUInt::get(Ty, 0);
172
173   default: return 0;
174   }
175 }
176
177 // Static constructor to create an integral constant with all bits set
178 ConstantIntegral *ConstantIntegral::getAllOnesValue(const Type *Ty) {
179   switch (Ty->getTypeID()) {
180   case Type::BoolTyID:   return ConstantBool::True;
181   case Type::SByteTyID:
182   case Type::ShortTyID:
183   case Type::IntTyID:
184   case Type::LongTyID:   return ConstantSInt::get(Ty, -1);
185
186   case Type::UByteTyID:
187   case Type::UShortTyID:
188   case Type::UIntTyID:
189   case Type::ULongTyID: {
190     // Calculate ~0 of the right type...
191     unsigned TypeBits = Ty->getPrimitiveSize()*8;
192     uint64_t Val = ~0ULL;                // All ones
193     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
194     return ConstantUInt::get(Ty, Val);
195   }
196   default: return 0;
197   }
198 }
199
200 bool ConstantUInt::isAllOnesValue() const {
201   unsigned TypeBits = getType()->getPrimitiveSize()*8;
202   uint64_t Val = ~0ULL;                // All ones
203   Val >>= 64-TypeBits;                 // Shift out inappropriate bits
204   return getValue() == Val;
205 }
206
207
208 //===----------------------------------------------------------------------===//
209 //                            ConstantXXX Classes
210 //===----------------------------------------------------------------------===//
211
212 //===----------------------------------------------------------------------===//
213 //                             Normal Constructors
214
215 ConstantIntegral::ConstantIntegral(const Type *Ty, uint64_t V)
216   : Constant(Ty, SimpleConstantVal, 0, 0) {
217     Val.Unsigned = V;
218 }
219
220 ConstantBool::ConstantBool(bool V) : ConstantIntegral(Type::BoolTy, V) {
221 }
222
223 ConstantInt::ConstantInt(const Type *Ty, uint64_t V) : ConstantIntegral(Ty, V) {
224 }
225
226 ConstantSInt::ConstantSInt(const Type *Ty, int64_t V) : ConstantInt(Ty, V) {
227   assert(Ty->isInteger() && Ty->isSigned() &&
228          "Illegal type for unsigned integer constant!");
229   assert(isValueValidForType(Ty, V) && "Value too large for type!");
230 }
231
232 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V) : ConstantInt(Ty, V) {
233   assert(Ty->isInteger() && Ty->isUnsigned() &&
234          "Illegal type for unsigned integer constant!");
235   assert(isValueValidForType(Ty, V) && "Value too large for type!");
236 }
237
238 ConstantFP::ConstantFP(const Type *Ty, double V)
239   : Constant(Ty, SimpleConstantVal, 0, 0) {
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)
246   : Constant(T, SimpleConstantVal, new Use[V.size()], V.size()) {
247   assert(V.size() == T->getNumElements() &&
248          "Invalid initializer vector for constant array");
249   Use *OL = OperandList;
250   for (unsigned i = 0, e = V.size(); i != e; ++i) {
251     assert((V[i]->getType() == T->getElementType() ||
252             (T->isAbstract() &&
253              V[i]->getType()->getTypeID()==T->getElementType()->getTypeID())) &&
254            "Initializer for array element doesn't match array element type!");
255     OL[i].init(V[i], this);
256   }
257 }
258
259 ConstantArray::~ConstantArray() {
260   delete [] OperandList;
261 }
262
263 ConstantStruct::ConstantStruct(const StructType *T,
264                                const std::vector<Constant*> &V)
265   : Constant(T, SimpleConstantVal, new Use[V.size()], V.size()) {
266   assert(V.size() == T->getNumElements() &&
267          "Invalid initializer vector for constant structure");
268   Use *OL = OperandList;
269   for (unsigned i = 0, e = V.size(); i != e; ++i) {
270     assert((V[i]->getType() == T->getElementType(i) ||
271             ((T->getElementType(i)->isAbstract() ||
272               V[i]->getType()->isAbstract()) &&
273              T->getElementType(i)->getTypeID()==V[i]->getType()->getTypeID()))&&
274            "Initializer for struct element doesn't match struct element type!");
275     OL[i].init(V[i], this);
276   }
277 }
278
279 ConstantStruct::~ConstantStruct() {
280   delete [] OperandList;
281 }
282
283
284 ConstantPacked::ConstantPacked(const PackedType *T,
285                                const std::vector<Constant*> &V)
286   : Constant(T, SimpleConstantVal, new Use[V.size()], V.size()) {
287   Use *OL = OperandList;
288   for (unsigned i = 0, e = V.size(); i != e; ++i) {
289     assert((V[i]->getType() == T->getElementType() ||
290             (T->isAbstract() &&
291              V[i]->getType()->getTypeID()==T->getElementType()->getTypeID())) &&
292            "Initializer for packed element doesn't match packed element type!");
293     OL[i].init(V[i], this);
294   }
295 }
296
297 ConstantPacked::~ConstantPacked() {
298   delete [] OperandList;
299 }
300
301 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
302 /// behind the scenes to implement unary constant exprs.
303 class UnaryConstantExpr : public ConstantExpr {
304   Use Op;
305 public:
306   UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
307     : ConstantExpr(Ty, Opcode, &Op, 1), Op(C, this) {}
308 };
309
310 static bool isSetCC(unsigned Opcode) {
311   return Opcode == Instruction::SetEQ || Opcode == Instruction::SetNE ||
312          Opcode == Instruction::SetLT || Opcode == Instruction::SetGT ||
313          Opcode == Instruction::SetLE || Opcode == Instruction::SetGE;
314 }
315
316 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
317 /// behind the scenes to implement binary constant exprs.
318 class BinaryConstantExpr : public ConstantExpr {
319   Use Ops[2];
320 public:
321   BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
322     : ConstantExpr(isSetCC(Opcode) ? Type::BoolTy : C1->getType(),
323                    Opcode, Ops, 2) {
324     Ops[0].init(C1, this);
325     Ops[1].init(C2, this);
326   }
327 };
328
329 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
330 /// behind the scenes to implement select constant exprs.
331 class SelectConstantExpr : public ConstantExpr {
332   Use Ops[3];
333 public:
334   SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
335     : ConstantExpr(C2->getType(), Instruction::Select, Ops, 3) {
336     Ops[0].init(C1, this);
337     Ops[1].init(C2, this);
338     Ops[2].init(C3, this);
339   }
340 };
341
342 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
343 /// used behind the scenes to implement getelementpr constant exprs.
344 struct GetElementPtrConstantExpr : public ConstantExpr {
345   GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
346                             const Type *DestTy)
347     : ConstantExpr(DestTy, Instruction::GetElementPtr,
348                    new Use[IdxList.size()+1], IdxList.size()+1) {
349     OperandList[0].init(C, this);
350     for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
351       OperandList[i+1].init(IdxList[i], this);
352   }
353   ~GetElementPtrConstantExpr() {
354     delete [] OperandList;    
355   }
356 };
357
358 /// ConstantExpr::get* - Return some common constants without having to
359 /// specify the full Instruction::OPCODE identifier.
360 ///
361 Constant *ConstantExpr::getNeg(Constant *C) {
362   if (!C->getType()->isFloatingPoint())
363     return get(Instruction::Sub, getNullValue(C->getType()), C);
364   else
365     return get(Instruction::Sub, ConstantFP::get(C->getType(), -0.0), C);
366 }
367 Constant *ConstantExpr::getNot(Constant *C) {
368   assert(isa<ConstantIntegral>(C) && "Cannot NOT a nonintegral type!");
369   return get(Instruction::Xor, C,
370              ConstantIntegral::getAllOnesValue(C->getType()));
371 }
372 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
373   return get(Instruction::Add, C1, C2);
374 }
375 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
376   return get(Instruction::Sub, C1, C2);
377 }
378 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
379   return get(Instruction::Mul, C1, C2);
380 }
381 Constant *ConstantExpr::getDiv(Constant *C1, Constant *C2) {
382   return get(Instruction::Div, C1, C2);
383 }
384 Constant *ConstantExpr::getRem(Constant *C1, Constant *C2) {
385   return get(Instruction::Rem, C1, C2);
386 }
387 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
388   return get(Instruction::And, C1, C2);
389 }
390 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
391   return get(Instruction::Or, C1, C2);
392 }
393 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
394   return get(Instruction::Xor, C1, C2);
395 }
396 Constant *ConstantExpr::getSetEQ(Constant *C1, Constant *C2) {
397   return get(Instruction::SetEQ, C1, C2);
398 }
399 Constant *ConstantExpr::getSetNE(Constant *C1, Constant *C2) {
400   return get(Instruction::SetNE, C1, C2);
401 }
402 Constant *ConstantExpr::getSetLT(Constant *C1, Constant *C2) {
403   return get(Instruction::SetLT, C1, C2);
404 }
405 Constant *ConstantExpr::getSetGT(Constant *C1, Constant *C2) {
406   return get(Instruction::SetGT, C1, C2);
407 }
408 Constant *ConstantExpr::getSetLE(Constant *C1, Constant *C2) {
409   return get(Instruction::SetLE, C1, C2);
410 }
411 Constant *ConstantExpr::getSetGE(Constant *C1, Constant *C2) {
412   return get(Instruction::SetGE, C1, C2);
413 }
414 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
415   return get(Instruction::Shl, C1, C2);
416 }
417 Constant *ConstantExpr::getShr(Constant *C1, Constant *C2) {
418   return get(Instruction::Shr, C1, C2);
419 }
420
421 Constant *ConstantExpr::getUShr(Constant *C1, Constant *C2) {
422   if (C1->getType()->isUnsigned()) return getShr(C1, C2);
423   return getCast(getShr(getCast(C1,
424                     C1->getType()->getUnsignedVersion()), C2), C1->getType());
425 }
426
427 Constant *ConstantExpr::getSShr(Constant *C1, Constant *C2) {
428   if (C1->getType()->isSigned()) return getShr(C1, C2);
429   return getCast(getShr(getCast(C1,
430                         C1->getType()->getSignedVersion()), C2), C1->getType());
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(getNumOperands());  // Build replacement array...
491   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
492     Constant *Val = getOperand(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(getNumOperands());  // Build replacement array...
516   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
517     Constant *Val = getOperand(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 ConstantPacked::replaceUsesOfWithOnConstant(Value *From, Value *To,
536                                                  bool DisableChecking) {
537   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
538
539   std::vector<Constant*> Values;
540   Values.reserve(getNumOperands());  // Build replacement array...
541   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
542     Constant *Val = getOperand(i);
543     if (Val == From) Val = cast<Constant>(To);
544     Values.push_back(Val);
545   }
546   
547   Constant *Replacement = ConstantPacked::get(getType(), Values);
548   assert(Replacement != this && "I didn't contain From!");
549
550   // Everyone using this now uses the replacement...
551   if (DisableChecking)
552     uncheckedReplaceAllUsesWith(Replacement);
553   else
554     replaceAllUsesWith(Replacement);
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
648     friend void Constant::clearAllValueMaps();
649   private:
650     void clear(std::vector<Constant *> &Constants) {
651       for(MapIterator I = Map.begin(); I != Map.end(); ++I)
652         Constants.push_back(I->second);
653       Map.clear();
654       AbstractTypeMap.clear();
655     }
656
657   public:
658     // getOrCreate - Return the specified constant from the map, creating it if
659     // necessary.
660     ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
661       MapKey Lookup(Ty, V);
662       MapIterator I = Map.lower_bound(Lookup);
663       if (I != Map.end() && I->first == Lookup)
664         return I->second;  // Is it in the map?
665
666       // If no preexisting value, create one now...
667       ConstantClass *Result =
668         ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
669
670
671       /// FIXME: why does this assert fail when loading 176.gcc?
672       //assert(Result->getType() == Ty && "Type specified is not correct!");
673       I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
674
675       // If the type of the constant is abstract, make sure that an entry exists
676       // for it in the AbstractTypeMap.
677       if (Ty->isAbstract()) {
678         typename AbstractTypeMapTy::iterator TI =
679           AbstractTypeMap.lower_bound(Ty);
680
681         if (TI == AbstractTypeMap.end() || TI->first != Ty) {
682           // Add ourselves to the ATU list of the type.
683           cast<DerivedType>(Ty)->addAbstractTypeUser(this);
684
685           AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
686         }
687       }
688       return Result;
689     }
690     
691     void remove(ConstantClass *CP) {
692       MapIterator I = Map.find(MapKey((TypeClass*)CP->getRawType(),
693                                       getValType(CP)));
694       if (I == Map.end() || I->second != CP) {
695         // FIXME: This should not use a linear scan.  If this gets to be a
696         // performance problem, someone should look at this.
697         for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
698           /* empty */;
699       }
700
701       assert(I != Map.end() && "Constant not found in constant table!");
702       assert(I->second == CP && "Didn't find correct element?");
703
704       // Now that we found the entry, make sure this isn't the entry that
705       // the AbstractTypeMap points to.
706       const TypeClass *Ty = I->first.first;
707       if (Ty->isAbstract()) {
708         assert(AbstractTypeMap.count(Ty) &&
709                "Abstract type not in AbstractTypeMap?");
710         MapIterator &ATMEntryIt = AbstractTypeMap[Ty];
711         if (ATMEntryIt == I) {
712           // Yes, we are removing the representative entry for this type.
713           // See if there are any other entries of the same type.
714           MapIterator TmpIt = ATMEntryIt;
715           
716           // First check the entry before this one...
717           if (TmpIt != Map.begin()) {
718             --TmpIt;
719             if (TmpIt->first.first != Ty) // Not the same type, move back...
720               ++TmpIt;
721           }
722           
723           // If we didn't find the same type, try to move forward...
724           if (TmpIt == ATMEntryIt) {
725             ++TmpIt;
726             if (TmpIt == Map.end() || TmpIt->first.first != Ty)
727               --TmpIt;   // No entry afterwards with the same type
728           }
729
730           // If there is another entry in the map of the same abstract type,
731           // update the AbstractTypeMap entry now.
732           if (TmpIt != ATMEntryIt) {
733             ATMEntryIt = TmpIt;
734           } else {
735             // Otherwise, we are removing the last instance of this type
736             // from the table.  Remove from the ATM, and from user list.
737             cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
738             AbstractTypeMap.erase(Ty);
739           }
740         }
741       }
742       
743       Map.erase(I);
744     }
745
746     void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
747       typename AbstractTypeMapTy::iterator I = 
748         AbstractTypeMap.find(cast<TypeClass>(OldTy));
749
750       assert(I != AbstractTypeMap.end() &&
751              "Abstract type not in AbstractTypeMap?");
752
753       // Convert a constant at a time until the last one is gone.  The last one
754       // leaving will remove() itself, causing the AbstractTypeMapEntry to be
755       // eliminated eventually.
756       do {
757         ConvertConstantType<ConstantClass,
758                             TypeClass>::convert(I->second->second,
759                                                 cast<TypeClass>(NewTy));
760
761         I = AbstractTypeMap.find(cast<TypeClass>(OldTy));
762       } while (I != AbstractTypeMap.end());
763     }
764
765     // If the type became concrete without being refined to any other existing
766     // type, we just remove ourselves from the ATU list.
767     void typeBecameConcrete(const DerivedType *AbsTy) {
768       AbsTy->removeAbstractTypeUser(this);
769     }
770
771     void dump() const {
772       std::cerr << "Constant.cpp: ValueMap\n";
773     }
774   };
775 }
776
777 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
778 //
779 static ValueMap< int64_t, Type, ConstantSInt> SIntConstants;
780 static ValueMap<uint64_t, Type, ConstantUInt> UIntConstants;
781
782 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
783   return SIntConstants.getOrCreate(Ty, V);
784 }
785
786 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
787   return UIntConstants.getOrCreate(Ty, V);
788 }
789
790 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
791   assert(V <= 127 && "Can only be used with very small positive constants!");
792   if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
793   return ConstantUInt::get(Ty, V);
794 }
795
796 //---- ConstantFP::get() implementation...
797 //
798 namespace llvm {
799   template<>
800   struct ConstantCreator<ConstantFP, Type, uint64_t> {
801     static ConstantFP *create(const Type *Ty, uint64_t V) {
802       assert(Ty == Type::DoubleTy);
803       union {
804         double F;
805         uint64_t I;
806       } T;
807       T.I = V;
808       return new ConstantFP(Ty, T.F);
809     }
810   };
811   template<>
812   struct ConstantCreator<ConstantFP, Type, uint32_t> {
813     static ConstantFP *create(const Type *Ty, uint32_t V) {
814       assert(Ty == Type::FloatTy);
815       union {
816         float F;
817         uint32_t I;
818       } T;
819       T.I = V;
820       return new ConstantFP(Ty, T.F);
821     }
822   };
823 }
824
825 static ValueMap<uint64_t, Type, ConstantFP> DoubleConstants;
826 static ValueMap<uint32_t, Type, ConstantFP> FloatConstants;
827
828 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
829   if (Ty == Type::FloatTy) {
830     // Force the value through memory to normalize it.
831     union {
832       float F;
833       uint32_t I;
834     } T;
835     T.F = (float)V;
836     return FloatConstants.getOrCreate(Ty, T.I);
837   } else {
838     assert(Ty == Type::DoubleTy);
839     union {
840       double F;
841       uint64_t I;
842     } T;
843     T.F = V;
844     return DoubleConstants.getOrCreate(Ty, T.I);
845   }
846 }
847
848 //---- ConstantAggregateZero::get() implementation...
849 //
850 namespace llvm {
851   // ConstantAggregateZero does not take extra "value" argument...
852   template<class ValType>
853   struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
854     static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
855       return new ConstantAggregateZero(Ty);
856     }
857   };
858
859   template<>
860   struct ConvertConstantType<ConstantAggregateZero, Type> {
861     static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
862       // Make everyone now use a constant of the new type...
863       Constant *New = ConstantAggregateZero::get(NewTy);
864       assert(New != OldC && "Didn't replace constant??");
865       OldC->uncheckedReplaceAllUsesWith(New);
866       OldC->destroyConstant();     // This constant is now dead, destroy it.
867     }
868   };
869 }
870
871 static ValueMap<char, Type, ConstantAggregateZero> AggZeroConstants;
872
873 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
874
875 Constant *ConstantAggregateZero::get(const Type *Ty) {
876   return AggZeroConstants.getOrCreate(Ty, 0);
877 }
878
879 // destroyConstant - Remove the constant from the constant table...
880 //
881 void ConstantAggregateZero::destroyConstant() {
882   AggZeroConstants.remove(this);
883   destroyConstantImpl();
884 }
885
886 void ConstantAggregateZero::replaceUsesOfWithOnConstant(Value *From, Value *To,
887                                                         bool DisableChecking) {
888   assert(0 && "No uses!");
889   abort();
890 }
891
892
893
894 //---- ConstantArray::get() implementation...
895 //
896 namespace llvm {
897   template<>
898   struct ConvertConstantType<ConstantArray, ArrayType> {
899     static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
900       // Make everyone now use a constant of the new type...
901       std::vector<Constant*> C;
902       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
903         C.push_back(cast<Constant>(OldC->getOperand(i)));
904       Constant *New = ConstantArray::get(NewTy, C);
905       assert(New != OldC && "Didn't replace constant??");
906       OldC->uncheckedReplaceAllUsesWith(New);
907       OldC->destroyConstant();    // This constant is now dead, destroy it.
908     }
909   };
910 }
911
912 static std::vector<Constant*> getValType(ConstantArray *CA) {
913   std::vector<Constant*> Elements;
914   Elements.reserve(CA->getNumOperands());
915   for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
916     Elements.push_back(cast<Constant>(CA->getOperand(i)));
917   return Elements;
918 }
919
920 static ValueMap<std::vector<Constant*>, ArrayType,
921                 ConstantArray> ArrayConstants;
922
923 Constant *ConstantArray::get(const ArrayType *Ty,
924                              const std::vector<Constant*> &V) {
925   // If this is an all-zero array, return a ConstantAggregateZero object
926   if (!V.empty()) {
927     Constant *C = V[0];
928     if (!C->isNullValue())
929       return ArrayConstants.getOrCreate(Ty, V);
930     for (unsigned i = 1, e = V.size(); i != e; ++i)
931       if (V[i] != C)
932         return ArrayConstants.getOrCreate(Ty, V);
933   }
934   return ConstantAggregateZero::get(Ty);
935 }
936
937 // destroyConstant - Remove the constant from the constant table...
938 //
939 void ConstantArray::destroyConstant() {
940   ArrayConstants.remove(this);
941   destroyConstantImpl();
942 }
943
944 // ConstantArray::get(const string&) - Return an array that is initialized to
945 // contain the specified string.  A null terminator is added to the specified
946 // string so that it may be used in a natural way...
947 //
948 Constant *ConstantArray::get(const std::string &Str) {
949   std::vector<Constant*> ElementVals;
950
951   for (unsigned i = 0; i < Str.length(); ++i)
952     ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
953
954   // Add a null terminator to the string...
955   ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
956
957   ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
958   return ConstantArray::get(ATy, ElementVals);
959 }
960
961 /// isString - This method returns true if the array is an array of sbyte or
962 /// ubyte, and if the elements of the array are all ConstantInt's.
963 bool ConstantArray::isString() const {
964   // Check the element type for sbyte or ubyte...
965   if (getType()->getElementType() != Type::UByteTy &&
966       getType()->getElementType() != Type::SByteTy)
967     return false;
968   // Check the elements to make sure they are all integers, not constant
969   // expressions.
970   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
971     if (!isa<ConstantInt>(getOperand(i)))
972       return false;
973   return true;
974 }
975
976 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
977 // then this method converts the array to an std::string and returns it.
978 // Otherwise, it asserts out.
979 //
980 std::string ConstantArray::getAsString() const {
981   assert(isString() && "Not a string!");
982   std::string Result;
983   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
984     Result += (char)cast<ConstantInt>(getOperand(i))->getRawValue();
985   return Result;
986 }
987
988
989 //---- ConstantStruct::get() implementation...
990 //
991
992 namespace llvm {
993   template<>
994   struct ConvertConstantType<ConstantStruct, StructType> {
995     static void convert(ConstantStruct *OldC, const StructType *NewTy) {
996       // Make everyone now use a constant of the new type...
997       std::vector<Constant*> C;
998       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
999         C.push_back(cast<Constant>(OldC->getOperand(i)));
1000       Constant *New = ConstantStruct::get(NewTy, C);
1001       assert(New != OldC && "Didn't replace constant??");
1002       
1003       OldC->uncheckedReplaceAllUsesWith(New);
1004       OldC->destroyConstant();    // This constant is now dead, destroy it.
1005     }
1006   };
1007 }
1008
1009 static ValueMap<std::vector<Constant*>, StructType, 
1010                 ConstantStruct> StructConstants;
1011
1012 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1013   std::vector<Constant*> Elements;
1014   Elements.reserve(CS->getNumOperands());
1015   for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1016     Elements.push_back(cast<Constant>(CS->getOperand(i)));
1017   return Elements;
1018 }
1019
1020 Constant *ConstantStruct::get(const StructType *Ty,
1021                               const std::vector<Constant*> &V) {
1022   // Create a ConstantAggregateZero value if all elements are zeros...
1023   for (unsigned i = 0, e = V.size(); i != e; ++i)
1024     if (!V[i]->isNullValue())
1025       return StructConstants.getOrCreate(Ty, V);
1026
1027   return ConstantAggregateZero::get(Ty);
1028 }
1029
1030 Constant *ConstantStruct::get(const std::vector<Constant*> &V) {
1031   std::vector<const Type*> StructEls;
1032   StructEls.reserve(V.size());
1033   for (unsigned i = 0, e = V.size(); i != e; ++i)
1034     StructEls.push_back(V[i]->getType());
1035   return get(StructType::get(StructEls), V);
1036 }
1037
1038 // destroyConstant - Remove the constant from the constant table...
1039 //
1040 void ConstantStruct::destroyConstant() {
1041   StructConstants.remove(this);
1042   destroyConstantImpl();
1043 }
1044
1045 //---- ConstantPacked::get() implementation...
1046 //
1047 namespace llvm {
1048   template<>
1049   struct ConvertConstantType<ConstantPacked, PackedType> {
1050     static void convert(ConstantPacked *OldC, const PackedType *NewTy) {
1051       // Make everyone now use a constant of the new type...
1052       std::vector<Constant*> C;
1053       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1054         C.push_back(cast<Constant>(OldC->getOperand(i)));
1055       Constant *New = ConstantPacked::get(NewTy, C);
1056       assert(New != OldC && "Didn't replace constant??");
1057       OldC->uncheckedReplaceAllUsesWith(New);
1058       OldC->destroyConstant();    // This constant is now dead, destroy it.
1059     }
1060   };
1061 }
1062
1063 static std::vector<Constant*> getValType(ConstantPacked *CP) {
1064   std::vector<Constant*> Elements;
1065   Elements.reserve(CP->getNumOperands());
1066   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1067     Elements.push_back(CP->getOperand(i));
1068   return Elements;
1069 }
1070
1071 static ValueMap<std::vector<Constant*>, PackedType,
1072                 ConstantPacked> PackedConstants;
1073
1074 Constant *ConstantPacked::get(const PackedType *Ty,
1075                               const std::vector<Constant*> &V) {
1076   // If this is an all-zero packed, return a ConstantAggregateZero object
1077   if (!V.empty()) {
1078     Constant *C = V[0];
1079     if (!C->isNullValue())
1080       return PackedConstants.getOrCreate(Ty, V);
1081     for (unsigned i = 1, e = V.size(); i != e; ++i)
1082       if (V[i] != C)
1083         return PackedConstants.getOrCreate(Ty, V);
1084   }
1085   return ConstantAggregateZero::get(Ty);
1086 }
1087
1088 Constant *ConstantPacked::get(const std::vector<Constant*> &V) {
1089   assert(!V.empty() && "Cannot infer type if V is empty");
1090   return get(PackedType::get(V.front()->getType(),V.size()), V);
1091 }
1092
1093 // destroyConstant - Remove the constant from the constant table...
1094 //
1095 void ConstantPacked::destroyConstant() {
1096   PackedConstants.remove(this);
1097   destroyConstantImpl();
1098 }
1099
1100 //---- ConstantPointerNull::get() implementation...
1101 //
1102
1103 namespace llvm {
1104   // ConstantPointerNull does not take extra "value" argument...
1105   template<class ValType>
1106   struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1107     static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1108       return new ConstantPointerNull(Ty);
1109     }
1110   };
1111
1112   template<>
1113   struct ConvertConstantType<ConstantPointerNull, PointerType> {
1114     static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1115       // Make everyone now use a constant of the new type...
1116       Constant *New = ConstantPointerNull::get(NewTy);
1117       assert(New != OldC && "Didn't replace constant??");
1118       OldC->uncheckedReplaceAllUsesWith(New);
1119       OldC->destroyConstant();     // This constant is now dead, destroy it.
1120     }
1121   };
1122 }
1123
1124 static ValueMap<char, PointerType, ConstantPointerNull> NullPtrConstants;
1125
1126 static char getValType(ConstantPointerNull *) {
1127   return 0;
1128 }
1129
1130
1131 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1132   return NullPtrConstants.getOrCreate(Ty, 0);
1133 }
1134
1135 // destroyConstant - Remove the constant from the constant table...
1136 //
1137 void ConstantPointerNull::destroyConstant() {
1138   NullPtrConstants.remove(this);
1139   destroyConstantImpl();
1140 }
1141
1142
1143 //---- UndefValue::get() implementation...
1144 //
1145
1146 namespace llvm {
1147   // UndefValue does not take extra "value" argument...
1148   template<class ValType>
1149   struct ConstantCreator<UndefValue, Type, ValType> {
1150     static UndefValue *create(const Type *Ty, const ValType &V) {
1151       return new UndefValue(Ty);
1152     }
1153   };
1154
1155   template<>
1156   struct ConvertConstantType<UndefValue, Type> {
1157     static void convert(UndefValue *OldC, const Type *NewTy) {
1158       // Make everyone now use a constant of the new type.
1159       Constant *New = UndefValue::get(NewTy);
1160       assert(New != OldC && "Didn't replace constant??");
1161       OldC->uncheckedReplaceAllUsesWith(New);
1162       OldC->destroyConstant();     // This constant is now dead, destroy it.
1163     }
1164   };
1165 }
1166
1167 static ValueMap<char, Type, UndefValue> UndefValueConstants;
1168
1169 static char getValType(UndefValue *) {
1170   return 0;
1171 }
1172
1173
1174 UndefValue *UndefValue::get(const Type *Ty) {
1175   return UndefValueConstants.getOrCreate(Ty, 0);
1176 }
1177
1178 // destroyConstant - Remove the constant from the constant table.
1179 //
1180 void UndefValue::destroyConstant() {
1181   UndefValueConstants.remove(this);
1182   destroyConstantImpl();
1183 }
1184
1185
1186
1187
1188 //---- ConstantExpr::get() implementations...
1189 //
1190 typedef std::pair<unsigned, std::vector<Constant*> > ExprMapKeyType;
1191
1192 namespace llvm {
1193   template<>
1194   struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1195     static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V) {
1196       if (V.first == Instruction::Cast)
1197         return new UnaryConstantExpr(Instruction::Cast, V.second[0], Ty);
1198       if ((V.first >= Instruction::BinaryOpsBegin &&
1199            V.first < Instruction::BinaryOpsEnd) ||
1200           V.first == Instruction::Shl || V.first == Instruction::Shr)
1201         return new BinaryConstantExpr(V.first, V.second[0], V.second[1]);
1202       if (V.first == Instruction::Select)
1203         return new SelectConstantExpr(V.second[0], V.second[1], V.second[2]);
1204       
1205       assert(V.first == Instruction::GetElementPtr && "Invalid ConstantExpr!");
1206       
1207       std::vector<Constant*> IdxList(V.second.begin()+1, V.second.end());
1208       return new GetElementPtrConstantExpr(V.second[0], IdxList, Ty);
1209     }
1210   };
1211
1212   template<>
1213   struct ConvertConstantType<ConstantExpr, Type> {
1214     static void convert(ConstantExpr *OldC, const Type *NewTy) {
1215       Constant *New;
1216       switch (OldC->getOpcode()) {
1217       case Instruction::Cast:
1218         New = ConstantExpr::getCast(OldC->getOperand(0), NewTy);
1219         break;
1220       case Instruction::Select:
1221         New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1222                                         OldC->getOperand(1),
1223                                         OldC->getOperand(2));
1224         break;
1225       case Instruction::Shl:
1226       case Instruction::Shr:
1227         New = ConstantExpr::getShiftTy(NewTy, OldC->getOpcode(),
1228                                      OldC->getOperand(0), OldC->getOperand(1));
1229         break;
1230       default:
1231         assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1232                OldC->getOpcode() < Instruction::BinaryOpsEnd);
1233         New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1234                                   OldC->getOperand(1));
1235         break;
1236       case Instruction::GetElementPtr:
1237         // Make everyone now use a constant of the new type... 
1238         std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1239         New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0), Idx);
1240         break;
1241       }
1242       
1243       assert(New != OldC && "Didn't replace constant??");
1244       OldC->uncheckedReplaceAllUsesWith(New);
1245       OldC->destroyConstant();    // This constant is now dead, destroy it.
1246     }
1247   };
1248 } // end namespace llvm
1249
1250
1251 static ExprMapKeyType getValType(ConstantExpr *CE) {
1252   std::vector<Constant*> Operands;
1253   Operands.reserve(CE->getNumOperands());
1254   for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1255     Operands.push_back(cast<Constant>(CE->getOperand(i)));
1256   return ExprMapKeyType(CE->getOpcode(), Operands);
1257 }
1258
1259 static ValueMap<ExprMapKeyType, Type, ConstantExpr> ExprConstants;
1260
1261 Constant *ConstantExpr::getCast(Constant *C, const Type *Ty) {
1262   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1263
1264   if (Constant *FC = ConstantFoldCastInstruction(C, Ty))
1265     return FC;          // Fold a few common cases...
1266
1267   // Look up the constant in the table first to ensure uniqueness
1268   std::vector<Constant*> argVec(1, C);
1269   ExprMapKeyType Key = std::make_pair(Instruction::Cast, argVec);
1270   return ExprConstants.getOrCreate(Ty, Key);
1271 }
1272
1273 Constant *ConstantExpr::getSignExtend(Constant *C, const Type *Ty) {
1274   assert(C->getType()->isIntegral() && Ty->isIntegral() &&
1275          C->getType()->getPrimitiveSize() <= Ty->getPrimitiveSize() &&
1276          "This is an illegal sign extension!");
1277   if (C->getType() != Type::BoolTy) {
1278     C = ConstantExpr::getCast(C, C->getType()->getSignedVersion());
1279     return ConstantExpr::getCast(C, Ty);
1280   } else {
1281     if (C == ConstantBool::True)
1282       return ConstantIntegral::getAllOnesValue(Ty);
1283     else
1284       return ConstantIntegral::getNullValue(Ty);
1285   }
1286 }
1287
1288 Constant *ConstantExpr::getZeroExtend(Constant *C, const Type *Ty) {
1289   assert(C->getType()->isIntegral() && Ty->isIntegral() &&
1290          C->getType()->getPrimitiveSize() <= Ty->getPrimitiveSize() &&
1291          "This is an illegal zero extension!");
1292   if (C->getType() != Type::BoolTy)
1293     C = ConstantExpr::getCast(C, C->getType()->getUnsignedVersion());
1294   return ConstantExpr::getCast(C, Ty);
1295 }
1296
1297 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
1298   // sizeof is implemented as: (ulong) gep (Ty*)null, 1
1299   return getCast(
1300     getGetElementPtr(getNullValue(PointerType::get(Ty)),
1301                  std::vector<Constant*>(1, ConstantInt::get(Type::UIntTy, 1))),
1302     Type::ULongTy);
1303 }
1304
1305 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1306                               Constant *C1, Constant *C2) {
1307   if (Opcode == Instruction::Shl || Opcode == Instruction::Shr)
1308     return getShiftTy(ReqTy, Opcode, C1, C2);
1309   // Check the operands for consistency first
1310   assert((Opcode >= Instruction::BinaryOpsBegin &&
1311           Opcode < Instruction::BinaryOpsEnd) &&
1312          "Invalid opcode in binary constant expression");
1313   assert(C1->getType() == C2->getType() &&
1314          "Operand types in binary constant expression should match");
1315
1316   if (ReqTy == C1->getType() || (Instruction::isRelational(Opcode) &&
1317                                  ReqTy == Type::BoolTy))
1318     if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1319       return FC;          // Fold a few common cases...
1320
1321   std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1322   ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1323   return ExprConstants.getOrCreate(ReqTy, Key);
1324 }
1325
1326 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1327 #ifndef NDEBUG
1328   switch (Opcode) {
1329   case Instruction::Add: case Instruction::Sub:
1330   case Instruction::Mul: case Instruction::Div:
1331   case Instruction::Rem:
1332     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1333     assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint()) && 
1334            "Tried to create an arithmetic operation on a non-arithmetic type!");
1335     break;
1336   case Instruction::And:
1337   case Instruction::Or:
1338   case Instruction::Xor:
1339     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1340     assert(C1->getType()->isIntegral() &&
1341            "Tried to create a logical operation on a non-integral type!");
1342     break;
1343   case Instruction::SetLT: case Instruction::SetGT: case Instruction::SetLE:
1344   case Instruction::SetGE: case Instruction::SetEQ: case Instruction::SetNE:
1345     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1346     break;
1347   case Instruction::Shl:
1348   case Instruction::Shr:
1349     assert(C2->getType() == Type::UByteTy && "Shift should be by ubyte!");
1350     assert(C1->getType()->isInteger() &&
1351            "Tried to create a shift operation on a non-integer type!");
1352     break;
1353   default:
1354     break;
1355   }
1356 #endif
1357
1358   if (Instruction::isRelational(Opcode))
1359     return getTy(Type::BoolTy, Opcode, C1, C2);
1360   else
1361     return getTy(C1->getType(), Opcode, C1, C2);
1362 }
1363
1364 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1365                                     Constant *V1, Constant *V2) {
1366   assert(C->getType() == Type::BoolTy && "Select condition must be bool!");
1367   assert(V1->getType() == V2->getType() && "Select value types must match!");
1368   assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1369
1370   if (ReqTy == V1->getType())
1371     if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1372       return SC;        // Fold common cases
1373
1374   std::vector<Constant*> argVec(3, C);
1375   argVec[1] = V1;
1376   argVec[2] = V2;
1377   ExprMapKeyType Key = std::make_pair(Instruction::Select, argVec);
1378   return ExprConstants.getOrCreate(ReqTy, Key);
1379 }
1380
1381 /// getShiftTy - Return a shift left or shift right constant expr
1382 Constant *ConstantExpr::getShiftTy(const Type *ReqTy, unsigned Opcode,
1383                                    Constant *C1, Constant *C2) {
1384   // Check the operands for consistency first
1385   assert((Opcode == Instruction::Shl ||
1386           Opcode == Instruction::Shr) &&
1387          "Invalid opcode in binary constant expression");
1388   assert(C1->getType()->isIntegral() && C2->getType() == Type::UByteTy &&
1389          "Invalid operand types for Shift constant expr!");
1390
1391   if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1392     return FC;          // Fold a few common cases...
1393
1394   // Look up the constant in the table first to ensure uniqueness
1395   std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1396   ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1397   return ExprConstants.getOrCreate(ReqTy, Key);
1398 }
1399
1400
1401 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1402                                            const std::vector<Value*> &IdxList) {
1403   assert(GetElementPtrInst::getIndexedType(C->getType(), IdxList, true) &&
1404          "GEP indices invalid!");
1405
1406   if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
1407     return FC;          // Fold a few common cases...
1408
1409   assert(isa<PointerType>(C->getType()) &&
1410          "Non-pointer type for constant GetElementPtr expression");
1411   // Look up the constant in the table first to ensure uniqueness
1412   std::vector<Constant*> ArgVec;
1413   ArgVec.reserve(IdxList.size()+1);
1414   ArgVec.push_back(C);
1415   for (unsigned i = 0, e = IdxList.size(); i != e; ++i)
1416     ArgVec.push_back(cast<Constant>(IdxList[i]));
1417   const ExprMapKeyType &Key = std::make_pair(Instruction::GetElementPtr,ArgVec);
1418   return ExprConstants.getOrCreate(ReqTy, Key);
1419 }
1420
1421 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1422                                          const std::vector<Constant*> &IdxList){
1423   // Get the result type of the getelementptr!
1424   std::vector<Value*> VIdxList(IdxList.begin(), IdxList.end());
1425
1426   const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), VIdxList,
1427                                                      true);
1428   assert(Ty && "GEP indices invalid!");
1429   return getGetElementPtrTy(PointerType::get(Ty), C, VIdxList);
1430 }
1431
1432 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1433                                          const std::vector<Value*> &IdxList) {
1434   // Get the result type of the getelementptr!
1435   const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
1436                                                      true);
1437   assert(Ty && "GEP indices invalid!");
1438   return getGetElementPtrTy(PointerType::get(Ty), C, IdxList);
1439 }
1440
1441
1442 // destroyConstant - Remove the constant from the constant table...
1443 //
1444 void ConstantExpr::destroyConstant() {
1445   ExprConstants.remove(this);
1446   destroyConstantImpl();
1447 }
1448
1449 const char *ConstantExpr::getOpcodeName() const {
1450   return Instruction::getOpcodeName(getOpcode());
1451 }
1452
1453 /// clearAllValueMaps - This method frees all internal memory used by the
1454 /// constant subsystem, which can be used in environments where this memory
1455 /// is otherwise reported as a leak.
1456 void Constant::clearAllValueMaps() {
1457   std::vector<Constant *> Constants;
1458
1459   DoubleConstants.clear(Constants);
1460   FloatConstants.clear(Constants);
1461   SIntConstants.clear(Constants);
1462   UIntConstants.clear(Constants);
1463   AggZeroConstants.clear(Constants);
1464   ArrayConstants.clear(Constants);
1465   StructConstants.clear(Constants);
1466   PackedConstants.clear(Constants);
1467   NullPtrConstants.clear(Constants);
1468   UndefValueConstants.clear(Constants);
1469   ExprConstants.clear(Constants);
1470
1471   for (std::vector<Constant *>::iterator I = Constants.begin(), 
1472        E = Constants.end(); I != E; ++I)
1473     (*I)->dropAllReferences();
1474   for (std::vector<Constant *>::iterator I = Constants.begin(),
1475        E = Constants.end(); I != E; ++I)
1476     (*I)->destroyConstantImpl();
1477   Constants.clear();
1478 }