LLVM API Documentation

Main Page | Namespace List | Class Hierarchy | Alphabetical List | Class List | Directories | File List | Namespace Members | Class Members | File Members | Related Pages

Constants.cpp

Go to the documentation of this file.
00001 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
00002 // 
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file was developed by the LLVM research group and is distributed under
00006 // the University of Illinois Open Source License. See LICENSE.TXT for details.
00007 // 
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the Constant* classes...
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/Constants.h"
00015 #include "ConstantFolding.h"
00016 #include "llvm/DerivedTypes.h"
00017 #include "llvm/GlobalValue.h"
00018 #include "llvm/Instructions.h"
00019 #include "llvm/SymbolTable.h"
00020 #include "llvm/Module.h"
00021 #include "llvm/ADT/StringExtras.h"
00022 #include <algorithm>
00023 #include <iostream>
00024 using namespace llvm;
00025 
00026 ConstantBool *ConstantBool::True  = new ConstantBool(true);
00027 ConstantBool *ConstantBool::False = new ConstantBool(false);
00028 
00029 
00030 //===----------------------------------------------------------------------===//
00031 //                              Constant Class
00032 //===----------------------------------------------------------------------===//
00033 
00034 // Specialize setName to take care of symbol table majik
00035 void Constant::setName(const std::string &Name, SymbolTable *ST) {
00036   assert(ST && "Type::setName - Must provide symbol table argument!");
00037 
00038   if (Name.size()) ST->insert(Name, this);
00039 }
00040 
00041 void Constant::destroyConstantImpl() {
00042   // When a Constant is destroyed, there may be lingering
00043   // references to the constant by other constants in the constant pool.  These
00044   // constants are implicitly dependent on the module that is being deleted,
00045   // but they don't know that.  Because we only find out when the CPV is
00046   // deleted, we must now notify all of our users (that should only be
00047   // Constants) that they are, in fact, invalid now and should be deleted.
00048   //
00049   while (!use_empty()) {
00050     Value *V = use_back();
00051 #ifndef NDEBUG      // Only in -g mode...
00052     if (!isa<Constant>(V))
00053       std::cerr << "While deleting: " << *this
00054                 << "\n\nUse still stuck around after Def is destroyed: "
00055                 << *V << "\n\n";
00056 #endif
00057     assert(isa<Constant>(V) && "References remain to Constant being destroyed");
00058     Constant *CV = cast<Constant>(V);
00059     CV->destroyConstant();
00060 
00061     // The constant should remove itself from our use list...
00062     assert((use_empty() || use_back() != V) && "Constant not removed!");
00063   }
00064 
00065   // Value has no outstanding references it is safe to delete it now...
00066   delete this;
00067 }
00068 
00069 // Static constructor to create a '0' constant of arbitrary type...
00070 Constant *Constant::getNullValue(const Type *Ty) {
00071   switch (Ty->getTypeID()) {
00072   case Type::BoolTyID: {
00073     static Constant *NullBool = ConstantBool::get(false);
00074     return NullBool;
00075   }
00076   case Type::SByteTyID: {
00077     static Constant *NullSByte = ConstantSInt::get(Type::SByteTy, 0);
00078     return NullSByte;
00079   }
00080   case Type::UByteTyID: {
00081     static Constant *NullUByte = ConstantUInt::get(Type::UByteTy, 0);
00082     return NullUByte;
00083   }
00084   case Type::ShortTyID: {
00085     static Constant *NullShort = ConstantSInt::get(Type::ShortTy, 0);
00086     return NullShort;
00087   }
00088   case Type::UShortTyID: {
00089     static Constant *NullUShort = ConstantUInt::get(Type::UShortTy, 0);
00090     return NullUShort;
00091   }
00092   case Type::IntTyID: {
00093     static Constant *NullInt = ConstantSInt::get(Type::IntTy, 0);
00094     return NullInt;
00095   }
00096   case Type::UIntTyID: {
00097     static Constant *NullUInt = ConstantUInt::get(Type::UIntTy, 0);
00098     return NullUInt;
00099   }
00100   case Type::LongTyID: {
00101     static Constant *NullLong = ConstantSInt::get(Type::LongTy, 0);
00102     return NullLong;
00103   }
00104   case Type::ULongTyID: {
00105     static Constant *NullULong = ConstantUInt::get(Type::ULongTy, 0);
00106     return NullULong;
00107   }
00108 
00109   case Type::FloatTyID: {
00110     static Constant *NullFloat = ConstantFP::get(Type::FloatTy, 0);
00111     return NullFloat;
00112   }
00113   case Type::DoubleTyID: {
00114     static Constant *NullDouble = ConstantFP::get(Type::DoubleTy, 0);
00115     return NullDouble;
00116   }
00117 
00118   case Type::PointerTyID: 
00119     return ConstantPointerNull::get(cast<PointerType>(Ty));
00120 
00121   case Type::StructTyID:
00122   case Type::ArrayTyID:
00123   case Type::PackedTyID:
00124     return ConstantAggregateZero::get(Ty);
00125   default:
00126     // Function, Label, or Opaque type?
00127     assert(!"Cannot create a null constant of that type!");
00128     return 0;
00129   }
00130 }
00131 
00132 // Static constructor to create the maximum constant of an integral type...
00133 ConstantIntegral *ConstantIntegral::getMaxValue(const Type *Ty) {
00134   switch (Ty->getTypeID()) {
00135   case Type::BoolTyID:   return ConstantBool::True;
00136   case Type::SByteTyID:
00137   case Type::ShortTyID:
00138   case Type::IntTyID:
00139   case Type::LongTyID: {
00140     // Calculate 011111111111111... 
00141     unsigned TypeBits = Ty->getPrimitiveSize()*8;
00142     int64_t Val = INT64_MAX;             // All ones
00143     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
00144     return ConstantSInt::get(Ty, Val);
00145   }
00146 
00147   case Type::UByteTyID:
00148   case Type::UShortTyID:
00149   case Type::UIntTyID:
00150   case Type::ULongTyID:  return getAllOnesValue(Ty);
00151 
00152   default: return 0;
00153   }
00154 }
00155 
00156 // Static constructor to create the minimum constant for an integral type...
00157 ConstantIntegral *ConstantIntegral::getMinValue(const Type *Ty) {
00158   switch (Ty->getTypeID()) {
00159   case Type::BoolTyID:   return ConstantBool::False;
00160   case Type::SByteTyID:
00161   case Type::ShortTyID:
00162   case Type::IntTyID:
00163   case Type::LongTyID: {
00164      // Calculate 1111111111000000000000 
00165      unsigned TypeBits = Ty->getPrimitiveSize()*8;
00166      int64_t Val = -1;                    // All ones
00167      Val <<= TypeBits-1;                  // Shift over to the right spot
00168      return ConstantSInt::get(Ty, Val);
00169   }
00170 
00171   case Type::UByteTyID:
00172   case Type::UShortTyID:
00173   case Type::UIntTyID:
00174   case Type::ULongTyID:  return ConstantUInt::get(Ty, 0);
00175 
00176   default: return 0;
00177   }
00178 }
00179 
00180 // Static constructor to create an integral constant with all bits set
00181 ConstantIntegral *ConstantIntegral::getAllOnesValue(const Type *Ty) {
00182   switch (Ty->getTypeID()) {
00183   case Type::BoolTyID:   return ConstantBool::True;
00184   case Type::SByteTyID:
00185   case Type::ShortTyID:
00186   case Type::IntTyID:
00187   case Type::LongTyID:   return ConstantSInt::get(Ty, -1);
00188 
00189   case Type::UByteTyID:
00190   case Type::UShortTyID:
00191   case Type::UIntTyID:
00192   case Type::ULongTyID: {
00193     // Calculate ~0 of the right type...
00194     unsigned TypeBits = Ty->getPrimitiveSize()*8;
00195     uint64_t Val = ~0ULL;                // All ones
00196     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
00197     return ConstantUInt::get(Ty, Val);
00198   }
00199   default: return 0;
00200   }
00201 }
00202 
00203 bool ConstantUInt::isAllOnesValue() const {
00204   unsigned TypeBits = getType()->getPrimitiveSize()*8;
00205   uint64_t Val = ~0ULL;                // All ones
00206   Val >>= 64-TypeBits;                 // Shift out inappropriate bits
00207   return getValue() == Val;
00208 }
00209 
00210 
00211 //===----------------------------------------------------------------------===//
00212 //                            ConstantXXX Classes
00213 //===----------------------------------------------------------------------===//
00214 
00215 //===----------------------------------------------------------------------===//
00216 //                             Normal Constructors
00217 
00218 ConstantIntegral::ConstantIntegral(const Type *Ty, uint64_t V)
00219   : Constant(Ty) {
00220     Val.Unsigned = V;
00221 }
00222 
00223 ConstantBool::ConstantBool(bool V) : ConstantIntegral(Type::BoolTy, V) {
00224 }
00225 
00226 ConstantInt::ConstantInt(const Type *Ty, uint64_t V) : ConstantIntegral(Ty, V) {
00227 }
00228 
00229 ConstantSInt::ConstantSInt(const Type *Ty, int64_t V) : ConstantInt(Ty, V) {
00230   assert(Ty->isInteger() && Ty->isSigned() &&
00231          "Illegal type for unsigned integer constant!");
00232   assert(isValueValidForType(Ty, V) && "Value too large for type!");
00233 }
00234 
00235 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V) : ConstantInt(Ty, V) {
00236   assert(Ty->isInteger() && Ty->isUnsigned() &&
00237          "Illegal type for unsigned integer constant!");
00238   assert(isValueValidForType(Ty, V) && "Value too large for type!");
00239 }
00240 
00241 ConstantFP::ConstantFP(const Type *Ty, double V) : Constant(Ty) {
00242   assert(isValueValidForType(Ty, V) && "Value too large for type!");
00243   Val = V;
00244 }
00245 
00246 ConstantArray::ConstantArray(const ArrayType *T,
00247                              const std::vector<Constant*> &V) : Constant(T) {
00248   assert(V.size() == T->getNumElements() &&
00249          "Invalid initializer vector for constant array");
00250   Operands.reserve(V.size());
00251   for (unsigned i = 0, e = V.size(); i != e; ++i) {
00252     assert((V[i]->getType() == T->getElementType() ||
00253             (T->isAbstract() &&
00254              V[i]->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
00255            "Initializer for array element doesn't match array element type!");
00256     Operands.push_back(Use(V[i], this));
00257   }
00258 }
00259 
00260 ConstantStruct::ConstantStruct(const StructType *T,
00261                                const std::vector<Constant*> &V) : Constant(T) {
00262   assert(V.size() == T->getNumElements() &&
00263          "Invalid initializer vector for constant structure");
00264   Operands.reserve(V.size());
00265   for (unsigned i = 0, e = V.size(); i != e; ++i) {
00266     assert((V[i]->getType() == T->getElementType(i) ||
00267             ((T->getElementType(i)->isAbstract() ||
00268               V[i]->getType()->isAbstract()) &&
00269              T->getElementType(i)->getTypeID() == V[i]->getType()->getTypeID())) &&
00270            "Initializer for struct element doesn't match struct element type!");
00271     Operands.push_back(Use(V[i], this));
00272   }
00273 }
00274 
00275 ConstantPacked::ConstantPacked(const PackedType *T,
00276                                const std::vector<Constant*> &V) : Constant(T) {
00277   Operands.reserve(V.size());
00278   for (unsigned i = 0, e = V.size(); i != e; ++i) {
00279     assert((V[i]->getType() == T->getElementType() ||
00280             (T->isAbstract() &&
00281              V[i]->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
00282            "Initializer for packed element doesn't match packed element type!");
00283     Operands.push_back(Use(V[i], this));
00284   }
00285 }
00286 
00287 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
00288   : Constant(Ty, ConstantExprVal), iType(Opcode) {
00289   Operands.reserve(1);
00290   Operands.push_back(Use(C, this));
00291 }
00292 
00293 // Select instruction creation ctor
00294 ConstantExpr::ConstantExpr(Constant *C, Constant *V1, Constant *V2)
00295   : Constant(V1->getType(), ConstantExprVal), iType(Instruction::Select) {
00296   Operands.reserve(3);
00297   Operands.push_back(Use(C, this));
00298   Operands.push_back(Use(V1, this));
00299   Operands.push_back(Use(V2, this));
00300 }
00301 
00302 
00303 static bool isSetCC(unsigned Opcode) {
00304   return Opcode == Instruction::SetEQ || Opcode == Instruction::SetNE ||
00305          Opcode == Instruction::SetLT || Opcode == Instruction::SetGT ||
00306          Opcode == Instruction::SetLE || Opcode == Instruction::SetGE;
00307 }
00308 
00309 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
00310   : Constant(isSetCC(Opcode) ? Type::BoolTy : C1->getType(), ConstantExprVal),
00311     iType(Opcode) {
00312   Operands.reserve(2);
00313   Operands.push_back(Use(C1, this));
00314   Operands.push_back(Use(C2, this));
00315 }
00316 
00317 ConstantExpr::ConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
00318                            const Type *DestTy)
00319   : Constant(DestTy, ConstantExprVal), iType(Instruction::GetElementPtr) {
00320   Operands.reserve(1+IdxList.size());
00321   Operands.push_back(Use(C, this));
00322   for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
00323     Operands.push_back(Use(IdxList[i], this));
00324 }
00325 
00326 /// ConstantExpr::get* - Return some common constants without having to
00327 /// specify the full Instruction::OPCODE identifier.
00328 ///
00329 Constant *ConstantExpr::getNeg(Constant *C) {
00330   if (!C->getType()->isFloatingPoint())
00331     return get(Instruction::Sub, getNullValue(C->getType()), C);
00332   else
00333     return get(Instruction::Sub, ConstantFP::get(C->getType(), -0.0), C);
00334 }
00335 Constant *ConstantExpr::getNot(Constant *C) {
00336   assert(isa<ConstantIntegral>(C) && "Cannot NOT a nonintegral type!");
00337   return get(Instruction::Xor, C,
00338              ConstantIntegral::getAllOnesValue(C->getType()));
00339 }
00340 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
00341   return get(Instruction::Add, C1, C2);
00342 }
00343 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
00344   return get(Instruction::Sub, C1, C2);
00345 }
00346 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
00347   return get(Instruction::Mul, C1, C2);
00348 }
00349 Constant *ConstantExpr::getDiv(Constant *C1, Constant *C2) {
00350   return get(Instruction::Div, C1, C2);
00351 }
00352 Constant *ConstantExpr::getRem(Constant *C1, Constant *C2) {
00353   return get(Instruction::Rem, C1, C2);
00354 }
00355 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
00356   return get(Instruction::And, C1, C2);
00357 }
00358 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
00359   return get(Instruction::Or, C1, C2);
00360 }
00361 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
00362   return get(Instruction::Xor, C1, C2);
00363 }
00364 Constant *ConstantExpr::getSetEQ(Constant *C1, Constant *C2) {
00365   return get(Instruction::SetEQ, C1, C2);
00366 }
00367 Constant *ConstantExpr::getSetNE(Constant *C1, Constant *C2) {
00368   return get(Instruction::SetNE, C1, C2);
00369 }
00370 Constant *ConstantExpr::getSetLT(Constant *C1, Constant *C2) {
00371   return get(Instruction::SetLT, C1, C2);
00372 }
00373 Constant *ConstantExpr::getSetGT(Constant *C1, Constant *C2) {
00374   return get(Instruction::SetGT, C1, C2);
00375 }
00376 Constant *ConstantExpr::getSetLE(Constant *C1, Constant *C2) {
00377   return get(Instruction::SetLE, C1, C2);
00378 }
00379 Constant *ConstantExpr::getSetGE(Constant *C1, Constant *C2) {
00380   return get(Instruction::SetGE, C1, C2);
00381 }
00382 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
00383   return get(Instruction::Shl, C1, C2);
00384 }
00385 Constant *ConstantExpr::getShr(Constant *C1, Constant *C2) {
00386   return get(Instruction::Shr, C1, C2);
00387 }
00388 
00389 Constant *ConstantExpr::getUShr(Constant *C1, Constant *C2) {
00390   if (C1->getType()->isUnsigned()) return getShr(C1, C2);
00391   return getCast(getShr(getCast(C1,
00392                     C1->getType()->getUnsignedVersion()), C2), C1->getType());
00393 }
00394 
00395 Constant *ConstantExpr::getSShr(Constant *C1, Constant *C2) {
00396   if (C1->getType()->isSigned()) return getShr(C1, C2);
00397   return getCast(getShr(getCast(C1,
00398                         C1->getType()->getSignedVersion()), C2), C1->getType());
00399 }
00400 
00401 
00402 //===----------------------------------------------------------------------===//
00403 //                      isValueValidForType implementations
00404 
00405 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
00406   switch (Ty->getTypeID()) {
00407   default:
00408     return false;         // These can't be represented as integers!!!
00409     // Signed types...
00410   case Type::SByteTyID:
00411     return (Val <= INT8_MAX && Val >= INT8_MIN);
00412   case Type::ShortTyID:
00413     return (Val <= INT16_MAX && Val >= INT16_MIN);
00414   case Type::IntTyID:
00415     return (Val <= int(INT32_MAX) && Val >= int(INT32_MIN));
00416   case Type::LongTyID:
00417     return true;          // This is the largest type...
00418   }
00419 }
00420 
00421 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
00422   switch (Ty->getTypeID()) {
00423   default:
00424     return false;         // These can't be represented as integers!!!
00425 
00426     // Unsigned types...
00427   case Type::UByteTyID:
00428     return (Val <= UINT8_MAX);
00429   case Type::UShortTyID:
00430     return (Val <= UINT16_MAX);
00431   case Type::UIntTyID:
00432     return (Val <= UINT32_MAX);
00433   case Type::ULongTyID:
00434     return true;          // This is the largest type...
00435   }
00436 }
00437 
00438 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
00439   switch (Ty->getTypeID()) {
00440   default:
00441     return false;         // These can't be represented as floating point!
00442 
00443     // TODO: Figure out how to test if a double can be cast to a float!
00444   case Type::FloatTyID:
00445   case Type::DoubleTyID:
00446     return true;          // This is the largest type...
00447   }
00448 };
00449 
00450 //===----------------------------------------------------------------------===//
00451 //                replaceUsesOfWithOnConstant implementations
00452 
00453 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
00454                                                 bool DisableChecking) {
00455   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
00456 
00457   std::vector<Constant*> Values;
00458   Values.reserve(getNumOperands());  // Build replacement array...
00459   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
00460     Constant *Val = getOperand(i);
00461     if (Val == From) Val = cast<Constant>(To);
00462     Values.push_back(Val);
00463   }
00464   
00465   Constant *Replacement = ConstantArray::get(getType(), Values);
00466   assert(Replacement != this && "I didn't contain From!");
00467 
00468   // Everyone using this now uses the replacement...
00469   if (DisableChecking)
00470     uncheckedReplaceAllUsesWith(Replacement);
00471   else
00472     replaceAllUsesWith(Replacement);
00473   
00474   // Delete the old constant!
00475   destroyConstant();  
00476 }
00477 
00478 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
00479                                                  bool DisableChecking) {
00480   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
00481 
00482   std::vector<Constant*> Values;
00483   Values.reserve(getNumOperands());  // Build replacement array...
00484   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
00485     Constant *Val = getOperand(i);
00486     if (Val == From) Val = cast<Constant>(To);
00487     Values.push_back(Val);
00488   }
00489   
00490   Constant *Replacement = ConstantStruct::get(getType(), Values);
00491   assert(Replacement != this && "I didn't contain From!");
00492 
00493   // Everyone using this now uses the replacement...
00494   if (DisableChecking)
00495     uncheckedReplaceAllUsesWith(Replacement);
00496   else
00497     replaceAllUsesWith(Replacement);
00498   
00499   // Delete the old constant!
00500   destroyConstant();
00501 }
00502 
00503 void ConstantPacked::replaceUsesOfWithOnConstant(Value *From, Value *To,
00504                                                  bool DisableChecking) {
00505   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
00506 
00507   std::vector<Constant*> Values;
00508   Values.reserve(getNumOperands());  // Build replacement array...
00509   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
00510     Constant *Val = getOperand(i);
00511     if (Val == From) Val = cast<Constant>(To);
00512     Values.push_back(Val);
00513   }
00514   
00515   Constant *Replacement = ConstantPacked::get(getType(), Values);
00516   assert(Replacement != this && "I didn't contain From!");
00517 
00518   // Everyone using this now uses the replacement...
00519   if (DisableChecking)
00520     uncheckedReplaceAllUsesWith(Replacement);
00521   else
00522     replaceAllUsesWith(Replacement);
00523   
00524   // Delete the old constant!
00525   destroyConstant();  
00526 }
00527 
00528 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
00529                                                bool DisableChecking) {
00530   assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
00531   Constant *To = cast<Constant>(ToV);
00532 
00533   Constant *Replacement = 0;
00534   if (getOpcode() == Instruction::GetElementPtr) {
00535     std::vector<Constant*> Indices;
00536     Constant *Pointer = getOperand(0);
00537     Indices.reserve(getNumOperands()-1);
00538     if (Pointer == From) Pointer = To;
00539     
00540     for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
00541       Constant *Val = getOperand(i);
00542       if (Val == From) Val = To;
00543       Indices.push_back(Val);
00544     }
00545     Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
00546   } else if (getOpcode() == Instruction::Cast) {
00547     assert(getOperand(0) == From && "Cast only has one use!");
00548     Replacement = ConstantExpr::getCast(To, getType());
00549   } else if (getOpcode() == Instruction::Select) {
00550     Constant *C1 = getOperand(0);
00551     Constant *C2 = getOperand(1);
00552     Constant *C3 = getOperand(2);
00553     if (C1 == From) C1 = To;
00554     if (C2 == From) C2 = To;
00555     if (C3 == From) C3 = To;
00556     Replacement = ConstantExpr::getSelect(C1, C2, C3);
00557   } else if (getNumOperands() == 2) {
00558     Constant *C1 = getOperand(0);
00559     Constant *C2 = getOperand(1);
00560     if (C1 == From) C1 = To;
00561     if (C2 == From) C2 = To;
00562     Replacement = ConstantExpr::get(getOpcode(), C1, C2);
00563   } else {
00564     assert(0 && "Unknown ConstantExpr type!");
00565     return;
00566   }
00567   
00568   assert(Replacement != this && "I didn't contain From!");
00569 
00570   // Everyone using this now uses the replacement...
00571   if (DisableChecking)
00572     uncheckedReplaceAllUsesWith(Replacement);
00573   else
00574     replaceAllUsesWith(Replacement);
00575   
00576   // Delete the old constant!
00577   destroyConstant();
00578 }
00579 
00580 //===----------------------------------------------------------------------===//
00581 //                      Factory Function Implementation
00582 
00583 // ConstantCreator - A class that is used to create constants by
00584 // ValueMap*.  This class should be partially specialized if there is
00585 // something strange that needs to be done to interface to the ctor for the
00586 // constant.
00587 //
00588 namespace llvm {
00589   template<class ConstantClass, class TypeClass, class ValType>
00590   struct ConstantCreator {
00591     static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
00592       return new ConstantClass(Ty, V);
00593     }
00594   };
00595   
00596   template<class ConstantClass, class TypeClass>
00597   struct ConvertConstantType {
00598     static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
00599       assert(0 && "This type cannot be converted!\n");
00600       abort();
00601     }
00602   };
00603 }
00604 
00605 namespace {
00606   template<class ValType, class TypeClass, class ConstantClass>
00607   class ValueMap : public AbstractTypeUser {
00608     typedef std::pair<const TypeClass*, ValType> MapKey;
00609     typedef std::map<MapKey, ConstantClass *> MapTy;
00610     typedef typename MapTy::iterator MapIterator;
00611     MapTy Map;
00612 
00613     typedef std::map<const TypeClass*, MapIterator> AbstractTypeMapTy;
00614     AbstractTypeMapTy AbstractTypeMap;
00615 
00616     friend void Constant::clearAllValueMaps();
00617   private:
00618     void clear(std::vector<Constant *> &Constants) {
00619       for(MapIterator I = Map.begin(); I != Map.end(); ++I)
00620         Constants.push_back(I->second);
00621       Map.clear();
00622       AbstractTypeMap.clear();
00623     }
00624 
00625   public:
00626     // getOrCreate - Return the specified constant from the map, creating it if
00627     // necessary.
00628     ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
00629       MapKey Lookup(Ty, V);
00630       MapIterator I = Map.lower_bound(Lookup);
00631       if (I != Map.end() && I->first == Lookup)
00632         return I->second;  // Is it in the map?
00633 
00634       // If no preexisting value, create one now...
00635       ConstantClass *Result =
00636         ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
00637 
00638 
00639       /// FIXME: why does this assert fail when loading 176.gcc?
00640       //assert(Result->getType() == Ty && "Type specified is not correct!");
00641       I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
00642 
00643       // If the type of the constant is abstract, make sure that an entry exists
00644       // for it in the AbstractTypeMap.
00645       if (Ty->isAbstract()) {
00646         typename AbstractTypeMapTy::iterator TI =
00647           AbstractTypeMap.lower_bound(Ty);
00648 
00649         if (TI == AbstractTypeMap.end() || TI->first != Ty) {
00650           // Add ourselves to the ATU list of the type.
00651           cast<DerivedType>(Ty)->addAbstractTypeUser(this);
00652 
00653           AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
00654         }
00655       }
00656       return Result;
00657     }
00658     
00659     void remove(ConstantClass *CP) {
00660       MapIterator I = Map.find(MapKey((TypeClass*)CP->getRawType(),
00661                                       getValType(CP)));
00662       if (I == Map.end() || I->second != CP) {
00663         // FIXME: This should not use a linear scan.  If this gets to be a
00664         // performance problem, someone should look at this.
00665         for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
00666           /* empty */;
00667       }
00668 
00669       assert(I != Map.end() && "Constant not found in constant table!");
00670       assert(I->second == CP && "Didn't find correct element?");
00671 
00672       // Now that we found the entry, make sure this isn't the entry that
00673       // the AbstractTypeMap points to.
00674       const TypeClass *Ty = I->first.first;
00675       if (Ty->isAbstract()) {
00676         assert(AbstractTypeMap.count(Ty) &&
00677                "Abstract type not in AbstractTypeMap?");
00678         MapIterator &ATMEntryIt = AbstractTypeMap[Ty];
00679         if (ATMEntryIt == I) {
00680           // Yes, we are removing the representative entry for this type.
00681           // See if there are any other entries of the same type.
00682           MapIterator TmpIt = ATMEntryIt;
00683           
00684           // First check the entry before this one...
00685           if (TmpIt != Map.begin()) {
00686             --TmpIt;
00687             if (TmpIt->first.first != Ty) // Not the same type, move back...
00688               ++TmpIt;
00689           }
00690           
00691           // If we didn't find the same type, try to move forward...
00692           if (TmpIt == ATMEntryIt) {
00693             ++TmpIt;
00694             if (TmpIt == Map.end() || TmpIt->first.first != Ty)
00695               --TmpIt;   // No entry afterwards with the same type
00696           }
00697 
00698           // If there is another entry in the map of the same abstract type,
00699           // update the AbstractTypeMap entry now.
00700           if (TmpIt != ATMEntryIt) {
00701             ATMEntryIt = TmpIt;
00702           } else {
00703             // Otherwise, we are removing the last instance of this type
00704             // from the table.  Remove from the ATM, and from user list.
00705             cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
00706             AbstractTypeMap.erase(Ty);
00707           }
00708         }
00709       }
00710       
00711       Map.erase(I);
00712     }
00713 
00714     void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
00715       typename AbstractTypeMapTy::iterator I = 
00716         AbstractTypeMap.find(cast<TypeClass>(OldTy));
00717 
00718       assert(I != AbstractTypeMap.end() &&
00719              "Abstract type not in AbstractTypeMap?");
00720 
00721       // Convert a constant at a time until the last one is gone.  The last one
00722       // leaving will remove() itself, causing the AbstractTypeMapEntry to be
00723       // eliminated eventually.
00724       do {
00725         ConvertConstantType<ConstantClass,
00726                             TypeClass>::convert(I->second->second,
00727                                                 cast<TypeClass>(NewTy));
00728 
00729         I = AbstractTypeMap.find(cast<TypeClass>(OldTy));
00730       } while (I != AbstractTypeMap.end());
00731     }
00732 
00733     // If the type became concrete without being refined to any other existing
00734     // type, we just remove ourselves from the ATU list.
00735     void typeBecameConcrete(const DerivedType *AbsTy) {
00736       AbsTy->removeAbstractTypeUser(this);
00737     }
00738 
00739     void dump() const {
00740       std::cerr << "Constant.cpp: ValueMap\n";
00741     }
00742   };
00743 }
00744 
00745 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
00746 //
00747 static ValueMap< int64_t, Type, ConstantSInt> SIntConstants;
00748 static ValueMap<uint64_t, Type, ConstantUInt> UIntConstants;
00749 
00750 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
00751   return SIntConstants.getOrCreate(Ty, V);
00752 }
00753 
00754 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
00755   return UIntConstants.getOrCreate(Ty, V);
00756 }
00757 
00758 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
00759   assert(V <= 127 && "Can only be used with very small positive constants!");
00760   if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
00761   return ConstantUInt::get(Ty, V);
00762 }
00763 
00764 //---- ConstantFP::get() implementation...
00765 //
00766 namespace llvm {
00767   template<>
00768   struct ConstantCreator<ConstantFP, Type, uint64_t> {
00769     static ConstantFP *create(const Type *Ty, uint64_t V) {
00770       assert(Ty == Type::DoubleTy);
00771       union {
00772         double F;
00773         uint64_t I;
00774       } T;
00775       T.I = V;
00776       return new ConstantFP(Ty, T.F);
00777     }
00778   };
00779   template<>
00780   struct ConstantCreator<ConstantFP, Type, uint32_t> {
00781     static ConstantFP *create(const Type *Ty, uint32_t V) {
00782       assert(Ty == Type::FloatTy);
00783       union {
00784         float F;
00785         uint32_t I;
00786       } T;
00787       T.I = V;
00788       return new ConstantFP(Ty, T.F);
00789     }
00790   };
00791 }
00792 
00793 static ValueMap<uint64_t, Type, ConstantFP> DoubleConstants;
00794 static ValueMap<uint32_t, Type, ConstantFP> FloatConstants;
00795 
00796 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
00797   if (Ty == Type::FloatTy) {
00798     // Force the value through memory to normalize it.
00799     union {
00800       float F;
00801       uint32_t I;
00802     } T;
00803     T.F = (float)V;
00804     return FloatConstants.getOrCreate(Ty, T.I);
00805   } else {
00806     assert(Ty == Type::DoubleTy);
00807     union {
00808       double F;
00809       uint64_t I;
00810     } T;
00811     T.F = V;
00812     return DoubleConstants.getOrCreate(Ty, T.I);
00813   }
00814 }
00815 
00816 //---- ConstantAggregateZero::get() implementation...
00817 //
00818 namespace llvm {
00819   // ConstantAggregateZero does not take extra "value" argument...
00820   template<class ValType>
00821   struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
00822     static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
00823       return new ConstantAggregateZero(Ty);
00824     }
00825   };
00826 
00827   template<>
00828   struct ConvertConstantType<ConstantAggregateZero, Type> {
00829     static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
00830       // Make everyone now use a constant of the new type...
00831       Constant *New = ConstantAggregateZero::get(NewTy);
00832       assert(New != OldC && "Didn't replace constant??");
00833       OldC->uncheckedReplaceAllUsesWith(New);
00834       OldC->destroyConstant();     // This constant is now dead, destroy it.
00835     }
00836   };
00837 }
00838 
00839 static ValueMap<char, Type, ConstantAggregateZero> AggZeroConstants;
00840 
00841 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
00842 
00843 Constant *ConstantAggregateZero::get(const Type *Ty) {
00844   return AggZeroConstants.getOrCreate(Ty, 0);
00845 }
00846 
00847 // destroyConstant - Remove the constant from the constant table...
00848 //
00849 void ConstantAggregateZero::destroyConstant() {
00850   AggZeroConstants.remove(this);
00851   destroyConstantImpl();
00852 }
00853 
00854 void ConstantAggregateZero::replaceUsesOfWithOnConstant(Value *From, Value *To,
00855                                                         bool DisableChecking) {
00856   assert(0 && "No uses!");
00857   abort();
00858 }
00859 
00860 
00861 
00862 //---- ConstantArray::get() implementation...
00863 //
00864 namespace llvm {
00865   template<>
00866   struct ConvertConstantType<ConstantArray, ArrayType> {
00867     static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
00868       // Make everyone now use a constant of the new type...
00869       std::vector<Constant*> C;
00870       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
00871         C.push_back(cast<Constant>(OldC->getOperand(i)));
00872       Constant *New = ConstantArray::get(NewTy, C);
00873       assert(New != OldC && "Didn't replace constant??");
00874       OldC->uncheckedReplaceAllUsesWith(New);
00875       OldC->destroyConstant();    // This constant is now dead, destroy it.
00876     }
00877   };
00878 }
00879 
00880 static std::vector<Constant*> getValType(ConstantArray *CA) {
00881   std::vector<Constant*> Elements;
00882   Elements.reserve(CA->getNumOperands());
00883   for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
00884     Elements.push_back(cast<Constant>(CA->getOperand(i)));
00885   return Elements;
00886 }
00887 
00888 static ValueMap<std::vector<Constant*>, ArrayType,
00889                 ConstantArray> ArrayConstants;
00890 
00891 Constant *ConstantArray::get(const ArrayType *Ty,
00892                              const std::vector<Constant*> &V) {
00893   // If this is an all-zero array, return a ConstantAggregateZero object
00894   if (!V.empty()) {
00895     Constant *C = V[0];
00896     if (!C->isNullValue())
00897       return ArrayConstants.getOrCreate(Ty, V);
00898     for (unsigned i = 1, e = V.size(); i != e; ++i)
00899       if (V[i] != C)
00900         return ArrayConstants.getOrCreate(Ty, V);
00901   }
00902   return ConstantAggregateZero::get(Ty);
00903 }
00904 
00905 // destroyConstant - Remove the constant from the constant table...
00906 //
00907 void ConstantArray::destroyConstant() {
00908   ArrayConstants.remove(this);
00909   destroyConstantImpl();
00910 }
00911 
00912 // ConstantArray::get(const string&) - Return an array that is initialized to
00913 // contain the specified string.  A null terminator is added to the specified
00914 // string so that it may be used in a natural way...
00915 //
00916 Constant *ConstantArray::get(const std::string &Str) {
00917   std::vector<Constant*> ElementVals;
00918 
00919   for (unsigned i = 0; i < Str.length(); ++i)
00920     ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
00921 
00922   // Add a null terminator to the string...
00923   ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
00924 
00925   ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
00926   return ConstantArray::get(ATy, ElementVals);
00927 }
00928 
00929 /// isString - This method returns true if the array is an array of sbyte or
00930 /// ubyte, and if the elements of the array are all ConstantInt's.
00931 bool ConstantArray::isString() const {
00932   // Check the element type for sbyte or ubyte...
00933   if (getType()->getElementType() != Type::UByteTy &&
00934       getType()->getElementType() != Type::SByteTy)
00935     return false;
00936   // Check the elements to make sure they are all integers, not constant
00937   // expressions.
00938   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
00939     if (!isa<ConstantInt>(getOperand(i)))
00940       return false;
00941   return true;
00942 }
00943 
00944 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
00945 // then this method converts the array to an std::string and returns it.
00946 // Otherwise, it asserts out.
00947 //
00948 std::string ConstantArray::getAsString() const {
00949   assert(isString() && "Not a string!");
00950   std::string Result;
00951   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
00952     Result += (char)cast<ConstantInt>(getOperand(i))->getRawValue();
00953   return Result;
00954 }
00955 
00956 
00957 //---- ConstantStruct::get() implementation...
00958 //
00959 
00960 namespace llvm {
00961   template<>
00962   struct ConvertConstantType<ConstantStruct, StructType> {
00963     static void convert(ConstantStruct *OldC, const StructType *NewTy) {
00964       // Make everyone now use a constant of the new type...
00965       std::vector<Constant*> C;
00966       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
00967         C.push_back(cast<Constant>(OldC->getOperand(i)));
00968       Constant *New = ConstantStruct::get(NewTy, C);
00969       assert(New != OldC && "Didn't replace constant??");
00970       
00971       OldC->uncheckedReplaceAllUsesWith(New);
00972       OldC->destroyConstant();    // This constant is now dead, destroy it.
00973     }
00974   };
00975 }
00976 
00977 static ValueMap<std::vector<Constant*>, StructType, 
00978                 ConstantStruct> StructConstants;
00979 
00980 static std::vector<Constant*> getValType(ConstantStruct *CS) {
00981   std::vector<Constant*> Elements;
00982   Elements.reserve(CS->getNumOperands());
00983   for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
00984     Elements.push_back(cast<Constant>(CS->getOperand(i)));
00985   return Elements;
00986 }
00987 
00988 Constant *ConstantStruct::get(const StructType *Ty,
00989                               const std::vector<Constant*> &V) {
00990   // Create a ConstantAggregateZero value if all elements are zeros...
00991   for (unsigned i = 0, e = V.size(); i != e; ++i)
00992     if (!V[i]->isNullValue())
00993       return StructConstants.getOrCreate(Ty, V);
00994 
00995   return ConstantAggregateZero::get(Ty);
00996 }
00997 
00998 Constant *ConstantStruct::get(const std::vector<Constant*> &V) {
00999   std::vector<const Type*> StructEls;
01000   StructEls.reserve(V.size());
01001   for (unsigned i = 0, e = V.size(); i != e; ++i)
01002     StructEls.push_back(V[i]->getType());
01003   return get(StructType::get(StructEls), V);
01004 }
01005 
01006 // destroyConstant - Remove the constant from the constant table...
01007 //
01008 void ConstantStruct::destroyConstant() {
01009   StructConstants.remove(this);
01010   destroyConstantImpl();
01011 }
01012 
01013 //---- ConstantPacked::get() implementation...
01014 //
01015 namespace llvm {
01016   template<>
01017   struct ConvertConstantType<ConstantPacked, PackedType> {
01018     static void convert(ConstantPacked *OldC, const PackedType *NewTy) {
01019       // Make everyone now use a constant of the new type...
01020       std::vector<Constant*> C;
01021       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
01022         C.push_back(cast<Constant>(OldC->getOperand(i)));
01023       Constant *New = ConstantPacked::get(NewTy, C);
01024       assert(New != OldC && "Didn't replace constant??");
01025       OldC->uncheckedReplaceAllUsesWith(New);
01026       OldC->destroyConstant();    // This constant is now dead, destroy it.
01027     }
01028   };
01029 }
01030 
01031 static std::vector<Constant*> getValType(ConstantPacked *CP) {
01032   std::vector<Constant*> Elements;
01033   Elements.reserve(CP->getNumOperands());
01034   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
01035     Elements.push_back(CP->getOperand(i));
01036   return Elements;
01037 }
01038 
01039 static ValueMap<std::vector<Constant*>, PackedType,
01040                 ConstantPacked> PackedConstants;
01041 
01042 Constant *ConstantPacked::get(const PackedType *Ty,
01043                               const std::vector<Constant*> &V) {
01044   // If this is an all-zero packed, return a ConstantAggregateZero object
01045   if (!V.empty()) {
01046     Constant *C = V[0];
01047     if (!C->isNullValue())
01048       return PackedConstants.getOrCreate(Ty, V);
01049     for (unsigned i = 1, e = V.size(); i != e; ++i)
01050       if (V[i] != C)
01051         return PackedConstants.getOrCreate(Ty, V);
01052   }
01053   return ConstantAggregateZero::get(Ty);
01054 }
01055 
01056 Constant *ConstantPacked::get(const std::vector<Constant*> &V) {
01057   assert(!V.empty() && "Cannot infer type if V is empty");
01058   return get(PackedType::get(V.front()->getType(),V.size()), V);
01059 }
01060 
01061 // destroyConstant - Remove the constant from the constant table...
01062 //
01063 void ConstantPacked::destroyConstant() {
01064   PackedConstants.remove(this);
01065   destroyConstantImpl();
01066 }
01067 
01068 //---- ConstantPointerNull::get() implementation...
01069 //
01070 
01071 namespace llvm {
01072   // ConstantPointerNull does not take extra "value" argument...
01073   template<class ValType>
01074   struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
01075     static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
01076       return new ConstantPointerNull(Ty);
01077     }
01078   };
01079 
01080   template<>
01081   struct ConvertConstantType<ConstantPointerNull, PointerType> {
01082     static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
01083       // Make everyone now use a constant of the new type...
01084       Constant *New = ConstantPointerNull::get(NewTy);
01085       assert(New != OldC && "Didn't replace constant??");
01086       OldC->uncheckedReplaceAllUsesWith(New);
01087       OldC->destroyConstant();     // This constant is now dead, destroy it.
01088     }
01089   };
01090 }
01091 
01092 static ValueMap<char, PointerType, ConstantPointerNull> NullPtrConstants;
01093 
01094 static char getValType(ConstantPointerNull *) {
01095   return 0;
01096 }
01097 
01098 
01099 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
01100   return NullPtrConstants.getOrCreate(Ty, 0);
01101 }
01102 
01103 // destroyConstant - Remove the constant from the constant table...
01104 //
01105 void ConstantPointerNull::destroyConstant() {
01106   NullPtrConstants.remove(this);
01107   destroyConstantImpl();
01108 }
01109 
01110 
01111 //---- UndefValue::get() implementation...
01112 //
01113 
01114 namespace llvm {
01115   // UndefValue does not take extra "value" argument...
01116   template<class ValType>
01117   struct ConstantCreator<UndefValue, Type, ValType> {
01118     static UndefValue *create(const Type *Ty, const ValType &V) {
01119       return new UndefValue(Ty);
01120     }
01121   };
01122 
01123   template<>
01124   struct ConvertConstantType<UndefValue, Type> {
01125     static void convert(UndefValue *OldC, const Type *NewTy) {
01126       // Make everyone now use a constant of the new type.
01127       Constant *New = UndefValue::get(NewTy);
01128       assert(New != OldC && "Didn't replace constant??");
01129       OldC->uncheckedReplaceAllUsesWith(New);
01130       OldC->destroyConstant();     // This constant is now dead, destroy it.
01131     }
01132   };
01133 }
01134 
01135 static ValueMap<char, Type, UndefValue> UndefValueConstants;
01136 
01137 static char getValType(UndefValue *) {
01138   return 0;
01139 }
01140 
01141 
01142 UndefValue *UndefValue::get(const Type *Ty) {
01143   return UndefValueConstants.getOrCreate(Ty, 0);
01144 }
01145 
01146 // destroyConstant - Remove the constant from the constant table.
01147 //
01148 void UndefValue::destroyConstant() {
01149   UndefValueConstants.remove(this);
01150   destroyConstantImpl();
01151 }
01152 
01153 
01154 
01155 
01156 //---- ConstantExpr::get() implementations...
01157 //
01158 typedef std::pair<unsigned, std::vector<Constant*> > ExprMapKeyType;
01159 
01160 namespace llvm {
01161   template<>
01162   struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
01163     static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V) {
01164       if (V.first == Instruction::Cast)
01165         return new ConstantExpr(Instruction::Cast, V.second[0], Ty);
01166       if ((V.first >= Instruction::BinaryOpsBegin &&
01167            V.first < Instruction::BinaryOpsEnd) ||
01168           V.first == Instruction::Shl || V.first == Instruction::Shr)
01169         return new ConstantExpr(V.first, V.second[0], V.second[1]);
01170       if (V.first == Instruction::Select)
01171         return new ConstantExpr(V.second[0], V.second[1], V.second[2]);
01172       
01173       assert(V.first == Instruction::GetElementPtr && "Invalid ConstantExpr!");
01174       
01175       std::vector<Constant*> IdxList(V.second.begin()+1, V.second.end());
01176       return new ConstantExpr(V.second[0], IdxList, Ty);
01177     }
01178   };
01179 
01180   template<>
01181   struct ConvertConstantType<ConstantExpr, Type> {
01182     static void convert(ConstantExpr *OldC, const Type *NewTy) {
01183       Constant *New;
01184       switch (OldC->getOpcode()) {
01185       case Instruction::Cast:
01186         New = ConstantExpr::getCast(OldC->getOperand(0), NewTy);
01187         break;
01188       case Instruction::Select:
01189         New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
01190                                         OldC->getOperand(1),
01191                                         OldC->getOperand(2));
01192         break;
01193       case Instruction::Shl:
01194       case Instruction::Shr:
01195         New = ConstantExpr::getShiftTy(NewTy, OldC->getOpcode(),
01196                                      OldC->getOperand(0), OldC->getOperand(1));
01197         break;
01198       default:
01199         assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
01200                OldC->getOpcode() < Instruction::BinaryOpsEnd);
01201         New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
01202                                   OldC->getOperand(1));
01203         break;
01204       case Instruction::GetElementPtr:
01205         // Make everyone now use a constant of the new type... 
01206         std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
01207         New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0), Idx);
01208         break;
01209       }
01210       
01211       assert(New != OldC && "Didn't replace constant??");
01212       OldC->uncheckedReplaceAllUsesWith(New);
01213       OldC->destroyConstant();    // This constant is now dead, destroy it.
01214     }
01215   };
01216 } // end namespace llvm
01217 
01218 
01219 static ExprMapKeyType getValType(ConstantExpr *CE) {
01220   std::vector<Constant*> Operands;
01221   Operands.reserve(CE->getNumOperands());
01222   for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
01223     Operands.push_back(cast<Constant>(CE->getOperand(i)));
01224   return ExprMapKeyType(CE->getOpcode(), Operands);
01225 }
01226 
01227 static ValueMap<ExprMapKeyType, Type, ConstantExpr> ExprConstants;
01228 
01229 Constant *ConstantExpr::getCast(Constant *C, const Type *Ty) {
01230   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
01231 
01232   if (Constant *FC = ConstantFoldCastInstruction(C, Ty))
01233     return FC;          // Fold a few common cases...
01234 
01235   // Look up the constant in the table first to ensure uniqueness
01236   std::vector<Constant*> argVec(1, C);
01237   ExprMapKeyType Key = std::make_pair(Instruction::Cast, argVec);
01238   return ExprConstants.getOrCreate(Ty, Key);
01239 }
01240 
01241 Constant *ConstantExpr::getSignExtend(Constant *C, const Type *Ty) {
01242   assert(C->getType()->isInteger() && Ty->isInteger() &&
01243          C->getType()->getPrimitiveSize() <= Ty->getPrimitiveSize() &&
01244          "This is an illegal sign extension!");
01245   C = ConstantExpr::getCast(C, C->getType()->getSignedVersion());
01246   return ConstantExpr::getCast(C, Ty);
01247 }
01248 
01249 Constant *ConstantExpr::getZeroExtend(Constant *C, const Type *Ty) {
01250   assert(C->getType()->isInteger() && Ty->isInteger() &&
01251          C->getType()->getPrimitiveSize() <= Ty->getPrimitiveSize() &&
01252          "This is an illegal zero extension!");
01253   C = ConstantExpr::getCast(C, C->getType()->getUnsignedVersion());
01254   return ConstantExpr::getCast(C, Ty);
01255 }
01256 
01257 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
01258   // sizeof is implemented as: (unsigned) gep (Ty*)null, 1
01259   return getCast(
01260     getGetElementPtr(
01261       getNullValue(PointerType::get(Ty)),
01262       std::vector<Constant*>(1, ConstantInt::get(Type::UIntTy, 1))),
01263     Type::UIntTy);
01264 }
01265 
01266 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
01267                               Constant *C1, Constant *C2) {
01268   if (Opcode == Instruction::Shl || Opcode == Instruction::Shr)
01269     return getShiftTy(ReqTy, Opcode, C1, C2);
01270   // Check the operands for consistency first
01271   assert((Opcode >= Instruction::BinaryOpsBegin &&
01272           Opcode < Instruction::BinaryOpsEnd) &&
01273          "Invalid opcode in binary constant expression");
01274   assert(C1->getType() == C2->getType() &&
01275          "Operand types in binary constant expression should match");
01276 
01277   if (ReqTy == C1->getType() || (Instruction::isRelational(Opcode) &&
01278                                  ReqTy == Type::BoolTy))
01279     if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
01280       return FC;          // Fold a few common cases...
01281 
01282   std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
01283   ExprMapKeyType Key = std::make_pair(Opcode, argVec);
01284   return ExprConstants.getOrCreate(ReqTy, Key);
01285 }
01286 
01287 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
01288 #ifndef NDEBUG
01289   switch (Opcode) {
01290   case Instruction::Add: case Instruction::Sub:
01291   case Instruction::Mul: case Instruction::Div:
01292   case Instruction::Rem:
01293     assert(C1->getType() == C2->getType() && "Op types should be identical!");
01294     assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint()) && 
01295            "Tried to create an arithmetic operation on a non-arithmetic type!");
01296     break;
01297   case Instruction::And:
01298   case Instruction::Or:
01299   case Instruction::Xor:
01300     assert(C1->getType() == C2->getType() && "Op types should be identical!");
01301     assert(C1->getType()->isIntegral() &&
01302            "Tried to create an logical operation on a non-integral type!");
01303     break;
01304   case Instruction::SetLT: case Instruction::SetGT: case Instruction::SetLE:
01305   case Instruction::SetGE: case Instruction::SetEQ: case Instruction::SetNE:
01306     assert(C1->getType() == C2->getType() && "Op types should be identical!");
01307     break;
01308   case Instruction::Shl:
01309   case Instruction::Shr:
01310     assert(C2->getType() == Type::UByteTy && "Shift should be by ubyte!");
01311     assert(C1->getType()->isInteger() &&
01312            "Tried to create a shift operation on a non-integer type!");
01313     break;
01314   default:
01315     break;
01316   }
01317 #endif
01318 
01319   if (Instruction::isRelational(Opcode))
01320     return getTy(Type::BoolTy, Opcode, C1, C2);
01321   else
01322     return getTy(C1->getType(), Opcode, C1, C2);
01323 }
01324 
01325 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
01326                                     Constant *V1, Constant *V2) {
01327   assert(C->getType() == Type::BoolTy && "Select condition must be bool!");
01328   assert(V1->getType() == V2->getType() && "Select value types must match!");
01329   assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
01330 
01331   if (ReqTy == V1->getType())
01332     if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
01333       return SC;        // Fold common cases
01334 
01335   std::vector<Constant*> argVec(3, C);
01336   argVec[1] = V1;
01337   argVec[2] = V2;
01338   ExprMapKeyType Key = std::make_pair(Instruction::Select, argVec);
01339   return ExprConstants.getOrCreate(ReqTy, Key);
01340 }
01341 
01342 /// getShiftTy - Return a shift left or shift right constant expr
01343 Constant *ConstantExpr::getShiftTy(const Type *ReqTy, unsigned Opcode,
01344                                    Constant *C1, Constant *C2) {
01345   // Check the operands for consistency first
01346   assert((Opcode == Instruction::Shl ||
01347           Opcode == Instruction::Shr) &&
01348          "Invalid opcode in binary constant expression");
01349   assert(C1->getType()->isIntegral() && C2->getType() == Type::UByteTy &&
01350          "Invalid operand types for Shift constant expr!");
01351 
01352   if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
01353     return FC;          // Fold a few common cases...
01354 
01355   // Look up the constant in the table first to ensure uniqueness
01356   std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
01357   ExprMapKeyType Key = std::make_pair(Opcode, argVec);
01358   return ExprConstants.getOrCreate(ReqTy, Key);
01359 }
01360 
01361 
01362 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
01363                                            const std::vector<Value*> &IdxList) {
01364   assert(GetElementPtrInst::getIndexedType(C->getType(), IdxList, true) &&
01365          "GEP indices invalid!");
01366 
01367   if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
01368     return FC;          // Fold a few common cases...
01369 
01370   assert(isa<PointerType>(C->getType()) &&
01371          "Non-pointer type for constant GetElementPtr expression");
01372   // Look up the constant in the table first to ensure uniqueness
01373   std::vector<Constant*> ArgVec;
01374   ArgVec.reserve(IdxList.size()+1);
01375   ArgVec.push_back(C);
01376   for (unsigned i = 0, e = IdxList.size(); i != e; ++i)
01377     ArgVec.push_back(cast<Constant>(IdxList[i]));
01378   const ExprMapKeyType &Key = std::make_pair(Instruction::GetElementPtr,ArgVec);
01379   return ExprConstants.getOrCreate(ReqTy, Key);
01380 }
01381 
01382 Constant *ConstantExpr::getGetElementPtr(Constant *C,
01383                                          const std::vector<Constant*> &IdxList){
01384   // Get the result type of the getelementptr!
01385   std::vector<Value*> VIdxList(IdxList.begin(), IdxList.end());
01386 
01387   const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), VIdxList,
01388                                                      true);
01389   assert(Ty && "GEP indices invalid!");
01390   return getGetElementPtrTy(PointerType::get(Ty), C, VIdxList);
01391 }
01392 
01393 Constant *ConstantExpr::getGetElementPtr(Constant *C,
01394                                          const std::vector<Value*> &IdxList) {
01395   // Get the result type of the getelementptr!
01396   const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
01397                                                      true);
01398   assert(Ty && "GEP indices invalid!");
01399   return getGetElementPtrTy(PointerType::get(Ty), C, IdxList);
01400 }
01401 
01402 
01403 // destroyConstant - Remove the constant from the constant table...
01404 //
01405 void ConstantExpr::destroyConstant() {
01406   ExprConstants.remove(this);
01407   destroyConstantImpl();
01408 }
01409 
01410 const char *ConstantExpr::getOpcodeName() const {
01411   return Instruction::getOpcodeName(getOpcode());
01412 }
01413 
01414 /// clearAllValueMaps - This method frees all internal memory used by the
01415 /// constant subsystem, which can be used in environments where this memory
01416 /// is otherwise reported as a leak.
01417 void Constant::clearAllValueMaps() {
01418   std::vector<Constant *> Constants;
01419 
01420   DoubleConstants.clear(Constants);
01421   FloatConstants.clear(Constants);
01422   SIntConstants.clear(Constants);
01423   UIntConstants.clear(Constants);
01424   AggZeroConstants.clear(Constants);
01425   ArrayConstants.clear(Constants);
01426   StructConstants.clear(Constants);
01427   PackedConstants.clear(Constants);
01428   NullPtrConstants.clear(Constants);
01429   UndefValueConstants.clear(Constants);
01430   ExprConstants.clear(Constants);
01431 
01432   for (std::vector<Constant *>::iterator I = Constants.begin(), 
01433        E = Constants.end(); I != E; ++I)
01434     (*I)->dropAllReferences();
01435   for (std::vector<Constant *>::iterator I = Constants.begin(),
01436        E = Constants.end(); I != E; ++I)
01437     (*I)->destroyConstantImpl();
01438   Constants.clear();
01439 }