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