LLVM API Documentation

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 "llvm/Support/MathExtras.h"
00023 #include "llvm/Support/Visibility.h"
00024 #include <algorithm>
00025 #include <iostream>
00026 using namespace llvm;
00027 
00028 ConstantBool *ConstantBool::True  = new ConstantBool(true);
00029 ConstantBool *ConstantBool::False = new ConstantBool(false);
00030 
00031 
00032 //===----------------------------------------------------------------------===//
00033 //                              Constant Class
00034 //===----------------------------------------------------------------------===//
00035 
00036 void Constant::destroyConstantImpl() {
00037   // When a Constant is destroyed, there may be lingering
00038   // references to the constant by other constants in the constant pool.  These
00039   // constants are implicitly dependent on the module that is being deleted,
00040   // but they don't know that.  Because we only find out when the CPV is
00041   // deleted, we must now notify all of our users (that should only be
00042   // Constants) that they are, in fact, invalid now and should be deleted.
00043   //
00044   while (!use_empty()) {
00045     Value *V = use_back();
00046 #ifndef NDEBUG      // Only in -g mode...
00047     if (!isa<Constant>(V))
00048       std::cerr << "While deleting: " << *this
00049                 << "\n\nUse still stuck around after Def is destroyed: "
00050                 << *V << "\n\n";
00051 #endif
00052     assert(isa<Constant>(V) && "References remain to Constant being destroyed");
00053     Constant *CV = cast<Constant>(V);
00054     CV->destroyConstant();
00055 
00056     // The constant should remove itself from our use list...
00057     assert((use_empty() || use_back() != V) && "Constant not removed!");
00058   }
00059 
00060   // Value has no outstanding references it is safe to delete it now...
00061   delete this;
00062 }
00063 
00064 // Static constructor to create a '0' constant of arbitrary type...
00065 Constant *Constant::getNullValue(const Type *Ty) {
00066   switch (Ty->getTypeID()) {
00067   case Type::BoolTyID: {
00068     static Constant *NullBool = ConstantBool::get(false);
00069     return NullBool;
00070   }
00071   case Type::SByteTyID: {
00072     static Constant *NullSByte = ConstantSInt::get(Type::SByteTy, 0);
00073     return NullSByte;
00074   }
00075   case Type::UByteTyID: {
00076     static Constant *NullUByte = ConstantUInt::get(Type::UByteTy, 0);
00077     return NullUByte;
00078   }
00079   case Type::ShortTyID: {
00080     static Constant *NullShort = ConstantSInt::get(Type::ShortTy, 0);
00081     return NullShort;
00082   }
00083   case Type::UShortTyID: {
00084     static Constant *NullUShort = ConstantUInt::get(Type::UShortTy, 0);
00085     return NullUShort;
00086   }
00087   case Type::IntTyID: {
00088     static Constant *NullInt = ConstantSInt::get(Type::IntTy, 0);
00089     return NullInt;
00090   }
00091   case Type::UIntTyID: {
00092     static Constant *NullUInt = ConstantUInt::get(Type::UIntTy, 0);
00093     return NullUInt;
00094   }
00095   case Type::LongTyID: {
00096     static Constant *NullLong = ConstantSInt::get(Type::LongTy, 0);
00097     return NullLong;
00098   }
00099   case Type::ULongTyID: {
00100     static Constant *NullULong = ConstantUInt::get(Type::ULongTy, 0);
00101     return NullULong;
00102   }
00103 
00104   case Type::FloatTyID: {
00105     static Constant *NullFloat = ConstantFP::get(Type::FloatTy, 0);
00106     return NullFloat;
00107   }
00108   case Type::DoubleTyID: {
00109     static Constant *NullDouble = ConstantFP::get(Type::DoubleTy, 0);
00110     return NullDouble;
00111   }
00112 
00113   case Type::PointerTyID:
00114     return ConstantPointerNull::get(cast<PointerType>(Ty));
00115 
00116   case Type::StructTyID:
00117   case Type::ArrayTyID:
00118   case Type::PackedTyID:
00119     return ConstantAggregateZero::get(Ty);
00120   default:
00121     // Function, Label, or Opaque type?
00122     assert(!"Cannot create a null constant of that type!");
00123     return 0;
00124   }
00125 }
00126 
00127 // Static constructor to create the maximum constant of an integral type...
00128 ConstantIntegral *ConstantIntegral::getMaxValue(const Type *Ty) {
00129   switch (Ty->getTypeID()) {
00130   case Type::BoolTyID:   return ConstantBool::True;
00131   case Type::SByteTyID:
00132   case Type::ShortTyID:
00133   case Type::IntTyID:
00134   case Type::LongTyID: {
00135     // Calculate 011111111111111...
00136     unsigned TypeBits = Ty->getPrimitiveSize()*8;
00137     int64_t Val = INT64_MAX;             // All ones
00138     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
00139     return ConstantSInt::get(Ty, Val);
00140   }
00141 
00142   case Type::UByteTyID:
00143   case Type::UShortTyID:
00144   case Type::UIntTyID:
00145   case Type::ULongTyID:  return getAllOnesValue(Ty);
00146 
00147   default: return 0;
00148   }
00149 }
00150 
00151 // Static constructor to create the minimum constant for an integral type...
00152 ConstantIntegral *ConstantIntegral::getMinValue(const Type *Ty) {
00153   switch (Ty->getTypeID()) {
00154   case Type::BoolTyID:   return ConstantBool::False;
00155   case Type::SByteTyID:
00156   case Type::ShortTyID:
00157   case Type::IntTyID:
00158   case Type::LongTyID: {
00159      // Calculate 1111111111000000000000
00160      unsigned TypeBits = Ty->getPrimitiveSize()*8;
00161      int64_t Val = -1;                    // All ones
00162      Val <<= TypeBits-1;                  // Shift over to the right spot
00163      return ConstantSInt::get(Ty, Val);
00164   }
00165 
00166   case Type::UByteTyID:
00167   case Type::UShortTyID:
00168   case Type::UIntTyID:
00169   case Type::ULongTyID:  return ConstantUInt::get(Ty, 0);
00170 
00171   default: return 0;
00172   }
00173 }
00174 
00175 // Static constructor to create an integral constant with all bits set
00176 ConstantIntegral *ConstantIntegral::getAllOnesValue(const Type *Ty) {
00177   switch (Ty->getTypeID()) {
00178   case Type::BoolTyID:   return ConstantBool::True;
00179   case Type::SByteTyID:
00180   case Type::ShortTyID:
00181   case Type::IntTyID:
00182   case Type::LongTyID:   return ConstantSInt::get(Ty, -1);
00183 
00184   case Type::UByteTyID:
00185   case Type::UShortTyID:
00186   case Type::UIntTyID:
00187   case Type::ULongTyID: {
00188     // Calculate ~0 of the right type...
00189     unsigned TypeBits = Ty->getPrimitiveSize()*8;
00190     uint64_t Val = ~0ULL;                // All ones
00191     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
00192     return ConstantUInt::get(Ty, Val);
00193   }
00194   default: return 0;
00195   }
00196 }
00197 
00198 bool ConstantUInt::isAllOnesValue() const {
00199   unsigned TypeBits = getType()->getPrimitiveSize()*8;
00200   uint64_t Val = ~0ULL;                // All ones
00201   Val >>= 64-TypeBits;                 // Shift out inappropriate bits
00202   return getValue() == Val;
00203 }
00204 
00205 
00206 //===----------------------------------------------------------------------===//
00207 //                            ConstantXXX Classes
00208 //===----------------------------------------------------------------------===//
00209 
00210 //===----------------------------------------------------------------------===//
00211 //                             Normal Constructors
00212 
00213 ConstantIntegral::ConstantIntegral(const Type *Ty, ValueTy VT, uint64_t V)
00214   : Constant(Ty, VT, 0, 0) {
00215     Val.Unsigned = V;
00216 }
00217 
00218 ConstantBool::ConstantBool(bool V) 
00219   : ConstantIntegral(Type::BoolTy, ConstantBoolVal, V) {
00220 }
00221 
00222 ConstantInt::ConstantInt(const Type *Ty, ValueTy VT, uint64_t V)
00223   : ConstantIntegral(Ty, VT, V) {
00224 }
00225 
00226 ConstantSInt::ConstantSInt(const Type *Ty, int64_t V)
00227   : ConstantInt(Ty, ConstantSIntVal, V) {
00228   assert(Ty->isInteger() && Ty->isSigned() &&
00229          "Illegal type for signed integer constant!");
00230   assert(isValueValidForType(Ty, V) && "Value too large for type!");
00231 }
00232 
00233 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V)
00234   : ConstantInt(Ty, ConstantUIntVal, V) {
00235   assert(Ty->isInteger() && Ty->isUnsigned() &&
00236          "Illegal type for unsigned integer constant!");
00237   assert(isValueValidForType(Ty, V) && "Value too large for type!");
00238 }
00239 
00240 ConstantFP::ConstantFP(const Type *Ty, double V)
00241   : Constant(Ty, ConstantFPVal, 0, 0) {
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)
00248   : Constant(T, ConstantArrayVal, new Use[V.size()], V.size()) {
00249   assert(V.size() == T->getNumElements() &&
00250          "Invalid initializer vector for constant array");
00251   Use *OL = OperandList;
00252   for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
00253        I != E; ++I, ++OL) {
00254     Constant *C = *I;
00255     assert((C->getType() == T->getElementType() ||
00256             (T->isAbstract() &&
00257              C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
00258            "Initializer for array element doesn't match array element type!");
00259     OL->init(C, this);
00260   }
00261 }
00262 
00263 ConstantArray::~ConstantArray() {
00264   delete [] OperandList;
00265 }
00266 
00267 ConstantStruct::ConstantStruct(const StructType *T,
00268                                const std::vector<Constant*> &V)
00269   : Constant(T, ConstantStructVal, new Use[V.size()], V.size()) {
00270   assert(V.size() == T->getNumElements() &&
00271          "Invalid initializer vector for constant structure");
00272   Use *OL = OperandList;
00273   for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
00274        I != E; ++I, ++OL) {
00275     Constant *C = *I;
00276     assert((C->getType() == T->getElementType(I-V.begin()) ||
00277             ((T->getElementType(I-V.begin())->isAbstract() ||
00278               C->getType()->isAbstract()) &&
00279              T->getElementType(I-V.begin())->getTypeID() == 
00280                    C->getType()->getTypeID())) &&
00281            "Initializer for struct element doesn't match struct element type!");
00282     OL->init(C, this);
00283   }
00284 }
00285 
00286 ConstantStruct::~ConstantStruct() {
00287   delete [] OperandList;
00288 }
00289 
00290 
00291 ConstantPacked::ConstantPacked(const PackedType *T,
00292                                const std::vector<Constant*> &V)
00293   : Constant(T, ConstantPackedVal, new Use[V.size()], V.size()) {
00294   Use *OL = OperandList;
00295     for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
00296          I != E; ++I, ++OL) {
00297       Constant *C = *I;
00298       assert((C->getType() == T->getElementType() ||
00299             (T->isAbstract() &&
00300              C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
00301            "Initializer for packed element doesn't match packed element type!");
00302     OL->init(C, this);
00303   }
00304 }
00305 
00306 ConstantPacked::~ConstantPacked() {
00307   delete [] OperandList;
00308 }
00309 
00310 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
00311 /// behind the scenes to implement unary constant exprs.
00312 namespace {
00313 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
00314   Use Op;
00315 public:
00316   UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
00317     : ConstantExpr(Ty, Opcode, &Op, 1), Op(C, this) {}
00318 };
00319 }
00320 
00321 static bool isSetCC(unsigned Opcode) {
00322   return Opcode == Instruction::SetEQ || Opcode == Instruction::SetNE ||
00323          Opcode == Instruction::SetLT || Opcode == Instruction::SetGT ||
00324          Opcode == Instruction::SetLE || Opcode == Instruction::SetGE;
00325 }
00326 
00327 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
00328 /// behind the scenes to implement binary constant exprs.
00329 namespace {
00330 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
00331   Use Ops[2];
00332 public:
00333   BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
00334     : ConstantExpr(isSetCC(Opcode) ? Type::BoolTy : C1->getType(),
00335                    Opcode, Ops, 2) {
00336     Ops[0].init(C1, this);
00337     Ops[1].init(C2, this);
00338   }
00339 };
00340 }
00341 
00342 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
00343 /// behind the scenes to implement select constant exprs.
00344 namespace {
00345 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
00346   Use Ops[3];
00347 public:
00348   SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
00349     : ConstantExpr(C2->getType(), Instruction::Select, Ops, 3) {
00350     Ops[0].init(C1, this);
00351     Ops[1].init(C2, this);
00352     Ops[2].init(C3, this);
00353   }
00354 };
00355 }
00356 
00357 /// ExtractElementConstantExpr - This class is private to
00358 /// Constants.cpp, and is used behind the scenes to implement
00359 /// extractelement constant exprs.
00360 namespace {
00361 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
00362   Use Ops[2];
00363 public:
00364   ExtractElementConstantExpr(Constant *C1, Constant *C2)
00365     : ConstantExpr(cast<PackedType>(C1->getType())->getElementType(), 
00366                    Instruction::ExtractElement, Ops, 2) {
00367     Ops[0].init(C1, this);
00368     Ops[1].init(C2, this);
00369   }
00370 };
00371 }
00372 
00373 /// InsertElementConstantExpr - This class is private to
00374 /// Constants.cpp, and is used behind the scenes to implement
00375 /// insertelement constant exprs.
00376 namespace {
00377 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
00378   Use Ops[3];
00379 public:
00380   InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
00381     : ConstantExpr(C1->getType(), Instruction::InsertElement, 
00382                    Ops, 3) {
00383     Ops[0].init(C1, this);
00384     Ops[1].init(C2, this);
00385     Ops[2].init(C3, this);
00386   }
00387 };
00388 }
00389 
00390 /// ShuffleVectorConstantExpr - This class is private to
00391 /// Constants.cpp, and is used behind the scenes to implement
00392 /// shufflevector constant exprs.
00393 namespace {
00394 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
00395   Use Ops[3];
00396 public:
00397   ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
00398   : ConstantExpr(C1->getType(), Instruction::ShuffleVector, 
00399                  Ops, 3) {
00400     Ops[0].init(C1, this);
00401     Ops[1].init(C2, this);
00402     Ops[2].init(C3, this);
00403   }
00404 };
00405 }
00406 
00407 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
00408 /// used behind the scenes to implement getelementpr constant exprs.
00409 namespace {
00410 struct VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
00411   GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
00412                             const Type *DestTy)
00413     : ConstantExpr(DestTy, Instruction::GetElementPtr,
00414                    new Use[IdxList.size()+1], IdxList.size()+1) {
00415     OperandList[0].init(C, this);
00416     for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
00417       OperandList[i+1].init(IdxList[i], this);
00418   }
00419   ~GetElementPtrConstantExpr() {
00420     delete [] OperandList;
00421   }
00422 };
00423 }
00424 
00425 /// ConstantExpr::get* - Return some common constants without having to
00426 /// specify the full Instruction::OPCODE identifier.
00427 ///
00428 Constant *ConstantExpr::getNeg(Constant *C) {
00429   if (!C->getType()->isFloatingPoint())
00430     return get(Instruction::Sub, getNullValue(C->getType()), C);
00431   else
00432     return get(Instruction::Sub, ConstantFP::get(C->getType(), -0.0), C);
00433 }
00434 Constant *ConstantExpr::getNot(Constant *C) {
00435   assert(isa<ConstantIntegral>(C) && "Cannot NOT a nonintegral type!");
00436   return get(Instruction::Xor, C,
00437              ConstantIntegral::getAllOnesValue(C->getType()));
00438 }
00439 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
00440   return get(Instruction::Add, C1, C2);
00441 }
00442 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
00443   return get(Instruction::Sub, C1, C2);
00444 }
00445 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
00446   return get(Instruction::Mul, C1, C2);
00447 }
00448 Constant *ConstantExpr::getDiv(Constant *C1, Constant *C2) {
00449   return get(Instruction::Div, C1, C2);
00450 }
00451 Constant *ConstantExpr::getRem(Constant *C1, Constant *C2) {
00452   return get(Instruction::Rem, C1, C2);
00453 }
00454 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
00455   return get(Instruction::And, C1, C2);
00456 }
00457 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
00458   return get(Instruction::Or, C1, C2);
00459 }
00460 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
00461   return get(Instruction::Xor, C1, C2);
00462 }
00463 Constant *ConstantExpr::getSetEQ(Constant *C1, Constant *C2) {
00464   return get(Instruction::SetEQ, C1, C2);
00465 }
00466 Constant *ConstantExpr::getSetNE(Constant *C1, Constant *C2) {
00467   return get(Instruction::SetNE, C1, C2);
00468 }
00469 Constant *ConstantExpr::getSetLT(Constant *C1, Constant *C2) {
00470   return get(Instruction::SetLT, C1, C2);
00471 }
00472 Constant *ConstantExpr::getSetGT(Constant *C1, Constant *C2) {
00473   return get(Instruction::SetGT, C1, C2);
00474 }
00475 Constant *ConstantExpr::getSetLE(Constant *C1, Constant *C2) {
00476   return get(Instruction::SetLE, C1, C2);
00477 }
00478 Constant *ConstantExpr::getSetGE(Constant *C1, Constant *C2) {
00479   return get(Instruction::SetGE, C1, C2);
00480 }
00481 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
00482   return get(Instruction::Shl, C1, C2);
00483 }
00484 Constant *ConstantExpr::getShr(Constant *C1, Constant *C2) {
00485   return get(Instruction::Shr, C1, C2);
00486 }
00487 
00488 Constant *ConstantExpr::getUShr(Constant *C1, Constant *C2) {
00489   if (C1->getType()->isUnsigned()) return getShr(C1, C2);
00490   return getCast(getShr(getCast(C1,
00491                     C1->getType()->getUnsignedVersion()), C2), C1->getType());
00492 }
00493 
00494 Constant *ConstantExpr::getSShr(Constant *C1, Constant *C2) {
00495   if (C1->getType()->isSigned()) return getShr(C1, C2);
00496   return getCast(getShr(getCast(C1,
00497                         C1->getType()->getSignedVersion()), C2), C1->getType());
00498 }
00499 
00500 /// getWithOperandReplaced - Return a constant expression identical to this
00501 /// one, but with the specified operand set to the specified value.
00502 Constant *ConstantExpr::getWithOperandReplaced(unsigned OpNo,
00503                                                Constant *Op) const {
00504   assert(OpNo < getNumOperands() && "Operand num is out of range!");
00505   assert(Op->getType() == getOperand(OpNo)->getType() &&
00506          "Replacing operand with value of different type!");
00507   if (getOperand(OpNo) == Op)
00508     return const_cast<ConstantExpr*>(this);
00509   
00510   Constant *Op0, *Op1, *Op2;
00511   switch (getOpcode()) {
00512   case Instruction::Cast:
00513     return ConstantExpr::getCast(Op, getType());
00514   case Instruction::Select:
00515     Op0 = (OpNo == 0) ? Op : getOperand(0);
00516     Op1 = (OpNo == 1) ? Op : getOperand(1);
00517     Op2 = (OpNo == 2) ? Op : getOperand(2);
00518     return ConstantExpr::getSelect(Op0, Op1, Op2);
00519   case Instruction::InsertElement:
00520     Op0 = (OpNo == 0) ? Op : getOperand(0);
00521     Op1 = (OpNo == 1) ? Op : getOperand(1);
00522     Op2 = (OpNo == 2) ? Op : getOperand(2);
00523     return ConstantExpr::getInsertElement(Op0, Op1, Op2);
00524   case Instruction::ExtractElement:
00525     Op0 = (OpNo == 0) ? Op : getOperand(0);
00526     Op1 = (OpNo == 1) ? Op : getOperand(1);
00527     return ConstantExpr::getExtractElement(Op0, Op1);
00528   case Instruction::ShuffleVector:
00529     Op0 = (OpNo == 0) ? Op : getOperand(0);
00530     Op1 = (OpNo == 1) ? Op : getOperand(1);
00531     Op2 = (OpNo == 2) ? Op : getOperand(2);
00532     return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
00533   case Instruction::GetElementPtr: {
00534     std::vector<Constant*> Ops;
00535     for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
00536       Ops.push_back(getOperand(i));
00537     if (OpNo == 0)
00538       return ConstantExpr::getGetElementPtr(Op, Ops);
00539     Ops[OpNo-1] = Op;
00540     return ConstantExpr::getGetElementPtr(getOperand(0), Ops);
00541   }
00542   default:
00543     assert(getNumOperands() == 2 && "Must be binary operator?");
00544     Op0 = (OpNo == 0) ? Op : getOperand(0);
00545     Op1 = (OpNo == 1) ? Op : getOperand(1);
00546     return ConstantExpr::get(getOpcode(), Op0, Op1);
00547   }
00548 }
00549 
00550 /// getWithOperands - This returns the current constant expression with the
00551 /// operands replaced with the specified values.  The specified operands must
00552 /// match count and type with the existing ones.
00553 Constant *ConstantExpr::
00554 getWithOperands(const std::vector<Constant*> &Ops) const {
00555   assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
00556   bool AnyChange = false;
00557   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
00558     assert(Ops[i]->getType() == getOperand(i)->getType() &&
00559            "Operand type mismatch!");
00560     AnyChange |= Ops[i] != getOperand(i);
00561   }
00562   if (!AnyChange)  // No operands changed, return self.
00563     return const_cast<ConstantExpr*>(this);
00564 
00565   switch (getOpcode()) {
00566   case Instruction::Cast:
00567     return ConstantExpr::getCast(Ops[0], getType());
00568   case Instruction::Select:
00569     return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
00570   case Instruction::InsertElement:
00571     return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
00572   case Instruction::ExtractElement:
00573     return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
00574   case Instruction::ShuffleVector:
00575     return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
00576   case Instruction::GetElementPtr: {
00577     std::vector<Constant*> ActualOps(Ops.begin()+1, Ops.end());
00578     return ConstantExpr::getGetElementPtr(Ops[0], ActualOps);
00579   }
00580   default:
00581     assert(getNumOperands() == 2 && "Must be binary operator?");
00582     return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
00583   }
00584 }
00585 
00586 
00587 //===----------------------------------------------------------------------===//
00588 //                      isValueValidForType implementations
00589 
00590 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
00591   switch (Ty->getTypeID()) {
00592   default:
00593     return false;         // These can't be represented as integers!!!
00594     // Signed types...
00595   case Type::SByteTyID:
00596     return (Val <= INT8_MAX && Val >= INT8_MIN);
00597   case Type::ShortTyID:
00598     return (Val <= INT16_MAX && Val >= INT16_MIN);
00599   case Type::IntTyID:
00600     return (Val <= int(INT32_MAX) && Val >= int(INT32_MIN));
00601   case Type::LongTyID:
00602     return true;          // This is the largest type...
00603   }
00604 }
00605 
00606 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
00607   switch (Ty->getTypeID()) {
00608   default:
00609     return false;         // These can't be represented as integers!!!
00610 
00611     // Unsigned types...
00612   case Type::UByteTyID:
00613     return (Val <= UINT8_MAX);
00614   case Type::UShortTyID:
00615     return (Val <= UINT16_MAX);
00616   case Type::UIntTyID:
00617     return (Val <= UINT32_MAX);
00618   case Type::ULongTyID:
00619     return true;          // This is the largest type...
00620   }
00621 }
00622 
00623 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
00624   switch (Ty->getTypeID()) {
00625   default:
00626     return false;         // These can't be represented as floating point!
00627 
00628     // TODO: Figure out how to test if a double can be cast to a float!
00629   case Type::FloatTyID:
00630   case Type::DoubleTyID:
00631     return true;          // This is the largest type...
00632   }
00633 }
00634 
00635 //===----------------------------------------------------------------------===//
00636 //                      Factory Function Implementation
00637 
00638 // ConstantCreator - A class that is used to create constants by
00639 // ValueMap*.  This class should be partially specialized if there is
00640 // something strange that needs to be done to interface to the ctor for the
00641 // constant.
00642 //
00643 namespace llvm {
00644   template<class ConstantClass, class TypeClass, class ValType>
00645   struct VISIBILITY_HIDDEN ConstantCreator {
00646     static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
00647       return new ConstantClass(Ty, V);
00648     }
00649   };
00650 
00651   template<class ConstantClass, class TypeClass>
00652   struct VISIBILITY_HIDDEN ConvertConstantType {
00653     static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
00654       assert(0 && "This type cannot be converted!\n");
00655       abort();
00656     }
00657   };
00658 
00659   template<class ValType, class TypeClass, class ConstantClass,
00660            bool HasLargeKey = false  /*true for arrays and structs*/ >
00661   class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
00662   public:
00663     typedef std::pair<const Type*, ValType> MapKey;
00664     typedef std::map<MapKey, Constant *> MapTy;
00665     typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
00666     typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
00667   private:
00668     /// Map - This is the main map from the element descriptor to the Constants.
00669     /// This is the primary way we avoid creating two of the same shape
00670     /// constant.
00671     MapTy Map;
00672     
00673     /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
00674     /// from the constants to their element in Map.  This is important for
00675     /// removal of constants from the array, which would otherwise have to scan
00676     /// through the map with very large keys.
00677     InverseMapTy InverseMap;
00678 
00679     /// AbstractTypeMap - Map for abstract type constants.
00680     ///
00681     AbstractTypeMapTy AbstractTypeMap;
00682 
00683     friend void Constant::clearAllValueMaps();
00684   private:
00685     void clear(std::vector<Constant *> &Constants) {
00686       for(typename MapTy::iterator I = Map.begin(); I != Map.end(); ++I)
00687         Constants.push_back(I->second);
00688       Map.clear();
00689       AbstractTypeMap.clear();
00690       InverseMap.clear();
00691     }
00692 
00693   public:
00694     typename MapTy::iterator map_end() { return Map.end(); }
00695     
00696     /// InsertOrGetItem - Return an iterator for the specified element.
00697     /// If the element exists in the map, the returned iterator points to the
00698     /// entry and Exists=true.  If not, the iterator points to the newly
00699     /// inserted entry and returns Exists=false.  Newly inserted entries have
00700     /// I->second == 0, and should be filled in.
00701     typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
00702                                    &InsertVal,
00703                                    bool &Exists) {
00704       std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
00705       Exists = !IP.second;
00706       return IP.first;
00707     }
00708     
00709 private:
00710     typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
00711       if (HasLargeKey) {
00712         typename InverseMapTy::iterator IMI = InverseMap.find(CP);
00713         assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
00714                IMI->second->second == CP &&
00715                "InverseMap corrupt!");
00716         return IMI->second;
00717       }
00718       
00719       typename MapTy::iterator I =
00720         Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
00721       if (I == Map.end() || I->second != CP) {
00722         // FIXME: This should not use a linear scan.  If this gets to be a
00723         // performance problem, someone should look at this.
00724         for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
00725           /* empty */;
00726       }
00727       return I;
00728     }
00729 public:
00730     
00731     /// getOrCreate - Return the specified constant from the map, creating it if
00732     /// necessary.
00733     ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
00734       MapKey Lookup(Ty, V);
00735       typename MapTy::iterator I = Map.lower_bound(Lookup);
00736       if (I != Map.end() && I->first == Lookup)
00737         return static_cast<ConstantClass *>(I->second);  // Is it in the map?
00738 
00739       // If no preexisting value, create one now...
00740       ConstantClass *Result =
00741         ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
00742 
00743       /// FIXME: why does this assert fail when loading 176.gcc?
00744       //assert(Result->getType() == Ty && "Type specified is not correct!");
00745       I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
00746 
00747       if (HasLargeKey)  // Remember the reverse mapping if needed.
00748         InverseMap.insert(std::make_pair(Result, I));
00749       
00750       // If the type of the constant is abstract, make sure that an entry exists
00751       // for it in the AbstractTypeMap.
00752       if (Ty->isAbstract()) {
00753         typename AbstractTypeMapTy::iterator TI =
00754           AbstractTypeMap.lower_bound(Ty);
00755 
00756         if (TI == AbstractTypeMap.end() || TI->first != Ty) {
00757           // Add ourselves to the ATU list of the type.
00758           cast<DerivedType>(Ty)->addAbstractTypeUser(this);
00759 
00760           AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
00761         }
00762       }
00763       return Result;
00764     }
00765 
00766     void remove(ConstantClass *CP) {
00767       typename MapTy::iterator I = FindExistingElement(CP);
00768       assert(I != Map.end() && "Constant not found in constant table!");
00769       assert(I->second == CP && "Didn't find correct element?");
00770 
00771       if (HasLargeKey)  // Remember the reverse mapping if needed.
00772         InverseMap.erase(CP);
00773       
00774       // Now that we found the entry, make sure this isn't the entry that
00775       // the AbstractTypeMap points to.
00776       const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
00777       if (Ty->isAbstract()) {
00778         assert(AbstractTypeMap.count(Ty) &&
00779                "Abstract type not in AbstractTypeMap?");
00780         typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
00781         if (ATMEntryIt == I) {
00782           // Yes, we are removing the representative entry for this type.
00783           // See if there are any other entries of the same type.
00784           typename MapTy::iterator TmpIt = ATMEntryIt;
00785 
00786           // First check the entry before this one...
00787           if (TmpIt != Map.begin()) {
00788             --TmpIt;
00789             if (TmpIt->first.first != Ty) // Not the same type, move back...
00790               ++TmpIt;
00791           }
00792 
00793           // If we didn't find the same type, try to move forward...
00794           if (TmpIt == ATMEntryIt) {
00795             ++TmpIt;
00796             if (TmpIt == Map.end() || TmpIt->first.first != Ty)
00797               --TmpIt;   // No entry afterwards with the same type
00798           }
00799 
00800           // If there is another entry in the map of the same abstract type,
00801           // update the AbstractTypeMap entry now.
00802           if (TmpIt != ATMEntryIt) {
00803             ATMEntryIt = TmpIt;
00804           } else {
00805             // Otherwise, we are removing the last instance of this type
00806             // from the table.  Remove from the ATM, and from user list.
00807             cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
00808             AbstractTypeMap.erase(Ty);
00809           }
00810         }
00811       }
00812 
00813       Map.erase(I);
00814     }
00815 
00816     
00817     /// MoveConstantToNewSlot - If we are about to change C to be the element
00818     /// specified by I, update our internal data structures to reflect this
00819     /// fact.
00820     void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
00821       // First, remove the old location of the specified constant in the map.
00822       typename MapTy::iterator OldI = FindExistingElement(C);
00823       assert(OldI != Map.end() && "Constant not found in constant table!");
00824       assert(OldI->second == C && "Didn't find correct element?");
00825       
00826       // If this constant is the representative element for its abstract type,
00827       // update the AbstractTypeMap so that the representative element is I.
00828       if (C->getType()->isAbstract()) {
00829         typename AbstractTypeMapTy::iterator ATI =
00830             AbstractTypeMap.find(C->getType());
00831         assert(ATI != AbstractTypeMap.end() &&
00832                "Abstract type not in AbstractTypeMap?");
00833         if (ATI->second == OldI)
00834           ATI->second = I;
00835       }
00836       
00837       // Remove the old entry from the map.
00838       Map.erase(OldI);
00839       
00840       // Update the inverse map so that we know that this constant is now
00841       // located at descriptor I.
00842       if (HasLargeKey) {
00843         assert(I->second == C && "Bad inversemap entry!");
00844         InverseMap[C] = I;
00845       }
00846     }
00847     
00848     void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
00849       typename AbstractTypeMapTy::iterator I =
00850         AbstractTypeMap.find(cast<Type>(OldTy));
00851 
00852       assert(I != AbstractTypeMap.end() &&
00853              "Abstract type not in AbstractTypeMap?");
00854 
00855       // Convert a constant at a time until the last one is gone.  The last one
00856       // leaving will remove() itself, causing the AbstractTypeMapEntry to be
00857       // eliminated eventually.
00858       do {
00859         ConvertConstantType<ConstantClass,
00860                             TypeClass>::convert(
00861                                 static_cast<ConstantClass *>(I->second->second),
00862                                                 cast<TypeClass>(NewTy));
00863 
00864         I = AbstractTypeMap.find(cast<Type>(OldTy));
00865       } while (I != AbstractTypeMap.end());
00866     }
00867 
00868     // If the type became concrete without being refined to any other existing
00869     // type, we just remove ourselves from the ATU list.
00870     void typeBecameConcrete(const DerivedType *AbsTy) {
00871       AbsTy->removeAbstractTypeUser(this);
00872     }
00873 
00874     void dump() const {
00875       std::cerr << "Constant.cpp: ValueMap\n";
00876     }
00877   };
00878 }
00879 
00880 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
00881 //
00882 static ValueMap< int64_t, Type, ConstantSInt> SIntConstants;
00883 static ValueMap<uint64_t, Type, ConstantUInt> UIntConstants;
00884 
00885 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
00886   return SIntConstants.getOrCreate(Ty, V);
00887 }
00888 
00889 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
00890   return UIntConstants.getOrCreate(Ty, V);
00891 }
00892 
00893 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
00894   assert(V <= 127 && "Can only be used with very small positive constants!");
00895   if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
00896   return ConstantUInt::get(Ty, V);
00897 }
00898 
00899 //---- ConstantFP::get() implementation...
00900 //
00901 namespace llvm {
00902   template<>
00903   struct ConstantCreator<ConstantFP, Type, uint64_t> {
00904     static ConstantFP *create(const Type *Ty, uint64_t V) {
00905       assert(Ty == Type::DoubleTy);
00906       return new ConstantFP(Ty, BitsToDouble(V));
00907     }
00908   };
00909   template<>
00910   struct ConstantCreator<ConstantFP, Type, uint32_t> {
00911     static ConstantFP *create(const Type *Ty, uint32_t V) {
00912       assert(Ty == Type::FloatTy);
00913       return new ConstantFP(Ty, BitsToFloat(V));
00914     }
00915   };
00916 }
00917 
00918 static ValueMap<uint64_t, Type, ConstantFP> DoubleConstants;
00919 static ValueMap<uint32_t, Type, ConstantFP> FloatConstants;
00920 
00921 bool ConstantFP::isNullValue() const {
00922   return DoubleToBits(Val) == 0;
00923 }
00924 
00925 bool ConstantFP::isExactlyValue(double V) const {
00926   return DoubleToBits(V) == DoubleToBits(Val);
00927 }
00928 
00929 
00930 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
00931   if (Ty == Type::FloatTy) {
00932     // Force the value through memory to normalize it.
00933     return FloatConstants.getOrCreate(Ty, FloatToBits(V));
00934   } else {
00935     assert(Ty == Type::DoubleTy);
00936     return DoubleConstants.getOrCreate(Ty, DoubleToBits(V));
00937   }
00938 }
00939 
00940 //---- ConstantAggregateZero::get() implementation...
00941 //
00942 namespace llvm {
00943   // ConstantAggregateZero does not take extra "value" argument...
00944   template<class ValType>
00945   struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
00946     static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
00947       return new ConstantAggregateZero(Ty);
00948     }
00949   };
00950 
00951   template<>
00952   struct ConvertConstantType<ConstantAggregateZero, Type> {
00953     static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
00954       // Make everyone now use a constant of the new type...
00955       Constant *New = ConstantAggregateZero::get(NewTy);
00956       assert(New != OldC && "Didn't replace constant??");
00957       OldC->uncheckedReplaceAllUsesWith(New);
00958       OldC->destroyConstant();     // This constant is now dead, destroy it.
00959     }
00960   };
00961 }
00962 
00963 static ValueMap<char, Type, ConstantAggregateZero> AggZeroConstants;
00964 
00965 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
00966 
00967 Constant *ConstantAggregateZero::get(const Type *Ty) {
00968   assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<PackedType>(Ty)) &&
00969          "Cannot create an aggregate zero of non-aggregate type!");
00970   return AggZeroConstants.getOrCreate(Ty, 0);
00971 }
00972 
00973 // destroyConstant - Remove the constant from the constant table...
00974 //
00975 void ConstantAggregateZero::destroyConstant() {
00976   AggZeroConstants.remove(this);
00977   destroyConstantImpl();
00978 }
00979 
00980 //---- ConstantArray::get() implementation...
00981 //
00982 namespace llvm {
00983   template<>
00984   struct ConvertConstantType<ConstantArray, ArrayType> {
00985     static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
00986       // Make everyone now use a constant of the new type...
00987       std::vector<Constant*> C;
00988       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
00989         C.push_back(cast<Constant>(OldC->getOperand(i)));
00990       Constant *New = ConstantArray::get(NewTy, C);
00991       assert(New != OldC && "Didn't replace constant??");
00992       OldC->uncheckedReplaceAllUsesWith(New);
00993       OldC->destroyConstant();    // This constant is now dead, destroy it.
00994     }
00995   };
00996 }
00997 
00998 static std::vector<Constant*> getValType(ConstantArray *CA) {
00999   std::vector<Constant*> Elements;
01000   Elements.reserve(CA->getNumOperands());
01001   for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
01002     Elements.push_back(cast<Constant>(CA->getOperand(i)));
01003   return Elements;
01004 }
01005 
01006 typedef ValueMap<std::vector<Constant*>, ArrayType, 
01007                  ConstantArray, true /*largekey*/> ArrayConstantsTy;
01008 static ArrayConstantsTy ArrayConstants;
01009 
01010 Constant *ConstantArray::get(const ArrayType *Ty,
01011                              const std::vector<Constant*> &V) {
01012   // If this is an all-zero array, return a ConstantAggregateZero object
01013   if (!V.empty()) {
01014     Constant *C = V[0];
01015     if (!C->isNullValue())
01016       return ArrayConstants.getOrCreate(Ty, V);
01017     for (unsigned i = 1, e = V.size(); i != e; ++i)
01018       if (V[i] != C)
01019         return ArrayConstants.getOrCreate(Ty, V);
01020   }
01021   return ConstantAggregateZero::get(Ty);
01022 }
01023 
01024 // destroyConstant - Remove the constant from the constant table...
01025 //
01026 void ConstantArray::destroyConstant() {
01027   ArrayConstants.remove(this);
01028   destroyConstantImpl();
01029 }
01030 
01031 /// ConstantArray::get(const string&) - Return an array that is initialized to
01032 /// contain the specified string.  If length is zero then a null terminator is 
01033 /// added to the specified string so that it may be used in a natural way. 
01034 /// Otherwise, the length parameter specifies how much of the string to use 
01035 /// and it won't be null terminated.
01036 ///
01037 Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
01038   std::vector<Constant*> ElementVals;
01039   for (unsigned i = 0; i < Str.length(); ++i)
01040     ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
01041 
01042   // Add a null terminator to the string...
01043   if (AddNull) {
01044     ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
01045   }
01046 
01047   ArrayType *ATy = ArrayType::get(Type::SByteTy, ElementVals.size());
01048   return ConstantArray::get(ATy, ElementVals);
01049 }
01050 
01051 /// isString - This method returns true if the array is an array of sbyte or
01052 /// ubyte, and if the elements of the array are all ConstantInt's.
01053 bool ConstantArray::isString() const {
01054   // Check the element type for sbyte or ubyte...
01055   if (getType()->getElementType() != Type::UByteTy &&
01056       getType()->getElementType() != Type::SByteTy)
01057     return false;
01058   // Check the elements to make sure they are all integers, not constant
01059   // expressions.
01060   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
01061     if (!isa<ConstantInt>(getOperand(i)))
01062       return false;
01063   return true;
01064 }
01065 
01066 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
01067 // then this method converts the array to an std::string and returns it.
01068 // Otherwise, it asserts out.
01069 //
01070 std::string ConstantArray::getAsString() const {
01071   assert(isString() && "Not a string!");
01072   std::string Result;
01073   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
01074     Result += (char)cast<ConstantInt>(getOperand(i))->getRawValue();
01075   return Result;
01076 }
01077 
01078 
01079 //---- ConstantStruct::get() implementation...
01080 //
01081 
01082 namespace llvm {
01083   template<>
01084   struct ConvertConstantType<ConstantStruct, StructType> {
01085     static void convert(ConstantStruct *OldC, const StructType *NewTy) {
01086       // Make everyone now use a constant of the new type...
01087       std::vector<Constant*> C;
01088       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
01089         C.push_back(cast<Constant>(OldC->getOperand(i)));
01090       Constant *New = ConstantStruct::get(NewTy, C);
01091       assert(New != OldC && "Didn't replace constant??");
01092 
01093       OldC->uncheckedReplaceAllUsesWith(New);
01094       OldC->destroyConstant();    // This constant is now dead, destroy it.
01095     }
01096   };
01097 }
01098 
01099 typedef ValueMap<std::vector<Constant*>, StructType,
01100                  ConstantStruct, true /*largekey*/> StructConstantsTy;
01101 static StructConstantsTy StructConstants;
01102 
01103 static std::vector<Constant*> getValType(ConstantStruct *CS) {
01104   std::vector<Constant*> Elements;
01105   Elements.reserve(CS->getNumOperands());
01106   for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
01107     Elements.push_back(cast<Constant>(CS->getOperand(i)));
01108   return Elements;
01109 }
01110 
01111 Constant *ConstantStruct::get(const StructType *Ty,
01112                               const std::vector<Constant*> &V) {
01113   // Create a ConstantAggregateZero value if all elements are zeros...
01114   for (unsigned i = 0, e = V.size(); i != e; ++i)
01115     if (!V[i]->isNullValue())
01116       return StructConstants.getOrCreate(Ty, V);
01117 
01118   return ConstantAggregateZero::get(Ty);
01119 }
01120 
01121 Constant *ConstantStruct::get(const std::vector<Constant*> &V) {
01122   std::vector<const Type*> StructEls;
01123   StructEls.reserve(V.size());
01124   for (unsigned i = 0, e = V.size(); i != e; ++i)
01125     StructEls.push_back(V[i]->getType());
01126   return get(StructType::get(StructEls), V);
01127 }
01128 
01129 // destroyConstant - Remove the constant from the constant table...
01130 //
01131 void ConstantStruct::destroyConstant() {
01132   StructConstants.remove(this);
01133   destroyConstantImpl();
01134 }
01135 
01136 //---- ConstantPacked::get() implementation...
01137 //
01138 namespace llvm {
01139   template<>
01140   struct ConvertConstantType<ConstantPacked, PackedType> {
01141     static void convert(ConstantPacked *OldC, const PackedType *NewTy) {
01142       // Make everyone now use a constant of the new type...
01143       std::vector<Constant*> C;
01144       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
01145         C.push_back(cast<Constant>(OldC->getOperand(i)));
01146       Constant *New = ConstantPacked::get(NewTy, C);
01147       assert(New != OldC && "Didn't replace constant??");
01148       OldC->uncheckedReplaceAllUsesWith(New);
01149       OldC->destroyConstant();    // This constant is now dead, destroy it.
01150     }
01151   };
01152 }
01153 
01154 static std::vector<Constant*> getValType(ConstantPacked *CP) {
01155   std::vector<Constant*> Elements;
01156   Elements.reserve(CP->getNumOperands());
01157   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
01158     Elements.push_back(CP->getOperand(i));
01159   return Elements;
01160 }
01161 
01162 static ValueMap<std::vector<Constant*>, PackedType,
01163                 ConstantPacked> PackedConstants;
01164 
01165 Constant *ConstantPacked::get(const PackedType *Ty,
01166                               const std::vector<Constant*> &V) {
01167   // If this is an all-zero packed, return a ConstantAggregateZero object
01168   if (!V.empty()) {
01169     Constant *C = V[0];
01170     if (!C->isNullValue())
01171       return PackedConstants.getOrCreate(Ty, V);
01172     for (unsigned i = 1, e = V.size(); i != e; ++i)
01173       if (V[i] != C)
01174         return PackedConstants.getOrCreate(Ty, V);
01175   }
01176   return ConstantAggregateZero::get(Ty);
01177 }
01178 
01179 Constant *ConstantPacked::get(const std::vector<Constant*> &V) {
01180   assert(!V.empty() && "Cannot infer type if V is empty");
01181   return get(PackedType::get(V.front()->getType(),V.size()), V);
01182 }
01183 
01184 // destroyConstant - Remove the constant from the constant table...
01185 //
01186 void ConstantPacked::destroyConstant() {
01187   PackedConstants.remove(this);
01188   destroyConstantImpl();
01189 }
01190 
01191 //---- ConstantPointerNull::get() implementation...
01192 //
01193 
01194 namespace llvm {
01195   // ConstantPointerNull does not take extra "value" argument...
01196   template<class ValType>
01197   struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
01198     static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
01199       return new ConstantPointerNull(Ty);
01200     }
01201   };
01202 
01203   template<>
01204   struct ConvertConstantType<ConstantPointerNull, PointerType> {
01205     static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
01206       // Make everyone now use a constant of the new type...
01207       Constant *New = ConstantPointerNull::get(NewTy);
01208       assert(New != OldC && "Didn't replace constant??");
01209       OldC->uncheckedReplaceAllUsesWith(New);
01210       OldC->destroyConstant();     // This constant is now dead, destroy it.
01211     }
01212   };
01213 }
01214 
01215 static ValueMap<char, PointerType, ConstantPointerNull> NullPtrConstants;
01216 
01217 static char getValType(ConstantPointerNull *) {
01218   return 0;
01219 }
01220 
01221 
01222 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
01223   return NullPtrConstants.getOrCreate(Ty, 0);
01224 }
01225 
01226 // destroyConstant - Remove the constant from the constant table...
01227 //
01228 void ConstantPointerNull::destroyConstant() {
01229   NullPtrConstants.remove(this);
01230   destroyConstantImpl();
01231 }
01232 
01233 
01234 //---- UndefValue::get() implementation...
01235 //
01236 
01237 namespace llvm {
01238   // UndefValue does not take extra "value" argument...
01239   template<class ValType>
01240   struct ConstantCreator<UndefValue, Type, ValType> {
01241     static UndefValue *create(const Type *Ty, const ValType &V) {
01242       return new UndefValue(Ty);
01243     }
01244   };
01245 
01246   template<>
01247   struct ConvertConstantType<UndefValue, Type> {
01248     static void convert(UndefValue *OldC, const Type *NewTy) {
01249       // Make everyone now use a constant of the new type.
01250       Constant *New = UndefValue::get(NewTy);
01251       assert(New != OldC && "Didn't replace constant??");
01252       OldC->uncheckedReplaceAllUsesWith(New);
01253       OldC->destroyConstant();     // This constant is now dead, destroy it.
01254     }
01255   };
01256 }
01257 
01258 static ValueMap<char, Type, UndefValue> UndefValueConstants;
01259 
01260 static char getValType(UndefValue *) {
01261   return 0;
01262 }
01263 
01264 
01265 UndefValue *UndefValue::get(const Type *Ty) {
01266   return UndefValueConstants.getOrCreate(Ty, 0);
01267 }
01268 
01269 // destroyConstant - Remove the constant from the constant table.
01270 //
01271 void UndefValue::destroyConstant() {
01272   UndefValueConstants.remove(this);
01273   destroyConstantImpl();
01274 }
01275 
01276 
01277 
01278 
01279 //---- ConstantExpr::get() implementations...
01280 //
01281 typedef std::pair<unsigned, std::vector<Constant*> > ExprMapKeyType;
01282 
01283 namespace llvm {
01284   template<>
01285   struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
01286     static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V) {
01287       if (V.first == Instruction::Cast)
01288         return new UnaryConstantExpr(Instruction::Cast, V.second[0], Ty);
01289       if ((V.first >= Instruction::BinaryOpsBegin &&
01290            V.first < Instruction::BinaryOpsEnd) ||
01291           V.first == Instruction::Shl || V.first == Instruction::Shr)
01292         return new BinaryConstantExpr(V.first, V.second[0], V.second[1]);
01293       if (V.first == Instruction::Select)
01294         return new SelectConstantExpr(V.second[0], V.second[1], V.second[2]);
01295       if (V.first == Instruction::ExtractElement)
01296         return new ExtractElementConstantExpr(V.second[0], V.second[1]);
01297       if (V.first == Instruction::InsertElement)
01298         return new InsertElementConstantExpr(V.second[0], V.second[1],
01299                                              V.second[2]);
01300       if (V.first == Instruction::ShuffleVector)
01301         return new ShuffleVectorConstantExpr(V.second[0], V.second[1],
01302                                              V.second[2]);
01303       
01304       assert(V.first == Instruction::GetElementPtr && "Invalid ConstantExpr!");
01305 
01306       std::vector<Constant*> IdxList(V.second.begin()+1, V.second.end());
01307       return new GetElementPtrConstantExpr(V.second[0], IdxList, Ty);
01308     }
01309   };
01310 
01311   template<>
01312   struct ConvertConstantType<ConstantExpr, Type> {
01313     static void convert(ConstantExpr *OldC, const Type *NewTy) {
01314       Constant *New;
01315       switch (OldC->getOpcode()) {
01316       case Instruction::Cast:
01317         New = ConstantExpr::getCast(OldC->getOperand(0), NewTy);
01318         break;
01319       case Instruction::Select:
01320         New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
01321                                         OldC->getOperand(1),
01322                                         OldC->getOperand(2));
01323         break;
01324       case Instruction::Shl:
01325       case Instruction::Shr:
01326         New = ConstantExpr::getShiftTy(NewTy, OldC->getOpcode(),
01327                                      OldC->getOperand(0), OldC->getOperand(1));
01328         break;
01329       default:
01330         assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
01331                OldC->getOpcode() < Instruction::BinaryOpsEnd);
01332         New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
01333                                   OldC->getOperand(1));
01334         break;
01335       case Instruction::GetElementPtr:
01336         // Make everyone now use a constant of the new type...
01337         std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
01338         New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0), Idx);
01339         break;
01340       }
01341 
01342       assert(New != OldC && "Didn't replace constant??");
01343       OldC->uncheckedReplaceAllUsesWith(New);
01344       OldC->destroyConstant();    // This constant is now dead, destroy it.
01345     }
01346   };
01347 } // end namespace llvm
01348 
01349 
01350 static ExprMapKeyType getValType(ConstantExpr *CE) {
01351   std::vector<Constant*> Operands;
01352   Operands.reserve(CE->getNumOperands());
01353   for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
01354     Operands.push_back(cast<Constant>(CE->getOperand(i)));
01355   return ExprMapKeyType(CE->getOpcode(), Operands);
01356 }
01357 
01358 static ValueMap<ExprMapKeyType, Type, ConstantExpr> ExprConstants;
01359 
01360 Constant *ConstantExpr::getCast(Constant *C, const Type *Ty) {
01361   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
01362 
01363   if (Constant *FC = ConstantFoldCastInstruction(C, Ty))
01364     return FC;          // Fold a few common cases...
01365 
01366   // Look up the constant in the table first to ensure uniqueness
01367   std::vector<Constant*> argVec(1, C);
01368   ExprMapKeyType Key = std::make_pair(Instruction::Cast, argVec);
01369   return ExprConstants.getOrCreate(Ty, Key);
01370 }
01371 
01372 Constant *ConstantExpr::getSignExtend(Constant *C, const Type *Ty) {
01373   assert(C->getType()->isIntegral() && Ty->isIntegral() &&
01374          C->getType()->getPrimitiveSize() <= Ty->getPrimitiveSize() &&
01375          "This is an illegal sign extension!");
01376   if (C->getType() != Type::BoolTy) {
01377     C = ConstantExpr::getCast(C, C->getType()->getSignedVersion());
01378     return ConstantExpr::getCast(C, Ty);
01379   } else {
01380     if (C == ConstantBool::True)
01381       return ConstantIntegral::getAllOnesValue(Ty);
01382     else
01383       return ConstantIntegral::getNullValue(Ty);
01384   }
01385 }
01386 
01387 Constant *ConstantExpr::getZeroExtend(Constant *C, const Type *Ty) {
01388   assert(C->getType()->isIntegral() && Ty->isIntegral() &&
01389          C->getType()->getPrimitiveSize() <= Ty->getPrimitiveSize() &&
01390          "This is an illegal zero extension!");
01391   if (C->getType() != Type::BoolTy)
01392     C = ConstantExpr::getCast(C, C->getType()->getUnsignedVersion());
01393   return ConstantExpr::getCast(C, Ty);
01394 }
01395 
01396 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
01397   // sizeof is implemented as: (ulong) gep (Ty*)null, 1
01398   return getCast(
01399     getGetElementPtr(getNullValue(PointerType::get(Ty)),
01400                  std::vector<Constant*>(1, ConstantInt::get(Type::UIntTy, 1))),
01401     Type::ULongTy);
01402 }
01403 
01404 Constant *ConstantExpr::getPtrPtrFromArrayPtr(Constant *C) {
01405   // pointer from array is implemented as: getelementptr arr ptr, 0, 0
01406   static std::vector<Constant*> Indices(2, ConstantUInt::get(Type::UIntTy, 0));
01407 
01408   return ConstantExpr::getGetElementPtr(C, Indices);
01409 }
01410 
01411 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
01412                               Constant *C1, Constant *C2) {
01413   if (Opcode == Instruction::Shl || Opcode == Instruction::Shr)
01414     return getShiftTy(ReqTy, Opcode, C1, C2);
01415   // Check the operands for consistency first
01416   assert((Opcode >= Instruction::BinaryOpsBegin &&
01417           Opcode < Instruction::BinaryOpsEnd) &&
01418          "Invalid opcode in binary constant expression");
01419   assert(C1->getType() == C2->getType() &&
01420          "Operand types in binary constant expression should match");
01421 
01422   if (ReqTy == C1->getType() || (Instruction::isRelational(Opcode) &&
01423                                  ReqTy == Type::BoolTy))
01424     if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
01425       return FC;          // Fold a few common cases...
01426 
01427   std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
01428   ExprMapKeyType Key = std::make_pair(Opcode, argVec);
01429   return ExprConstants.getOrCreate(ReqTy, Key);
01430 }
01431 
01432 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
01433 #ifndef NDEBUG
01434   switch (Opcode) {
01435   case Instruction::Add: case Instruction::Sub:
01436   case Instruction::Mul: case Instruction::Div:
01437   case Instruction::Rem:
01438     assert(C1->getType() == C2->getType() && "Op types should be identical!");
01439     assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
01440             isa<PackedType>(C1->getType())) &&
01441            "Tried to create an arithmetic operation on a non-arithmetic type!");
01442     break;
01443   case Instruction::And:
01444   case Instruction::Or:
01445   case Instruction::Xor:
01446     assert(C1->getType() == C2->getType() && "Op types should be identical!");
01447     assert((C1->getType()->isIntegral() || isa<PackedType>(C1->getType())) &&
01448            "Tried to create a logical operation on a non-integral type!");
01449     break;
01450   case Instruction::SetLT: case Instruction::SetGT: case Instruction::SetLE:
01451   case Instruction::SetGE: case Instruction::SetEQ: case Instruction::SetNE:
01452     assert(C1->getType() == C2->getType() && "Op types should be identical!");
01453     break;
01454   case Instruction::Shl:
01455   case Instruction::Shr:
01456     assert(C2->getType() == Type::UByteTy && "Shift should be by ubyte!");
01457     assert((C1->getType()->isInteger() || isa<PackedType>(C1->getType())) &&
01458            "Tried to create a shift operation on a non-integer type!");
01459     break;
01460   default:
01461     break;
01462   }
01463 #endif
01464 
01465   if (Instruction::isRelational(Opcode))
01466     return getTy(Type::BoolTy, Opcode, C1, C2);
01467   else
01468     return getTy(C1->getType(), Opcode, C1, C2);
01469 }
01470 
01471 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
01472                                     Constant *V1, Constant *V2) {
01473   assert(C->getType() == Type::BoolTy && "Select condition must be bool!");
01474   assert(V1->getType() == V2->getType() && "Select value types must match!");
01475   assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
01476 
01477   if (ReqTy == V1->getType())
01478     if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
01479       return SC;        // Fold common cases
01480 
01481   std::vector<Constant*> argVec(3, C);
01482   argVec[1] = V1;
01483   argVec[2] = V2;
01484   ExprMapKeyType Key = std::make_pair(Instruction::Select, argVec);
01485   return ExprConstants.getOrCreate(ReqTy, Key);
01486 }
01487 
01488 /// getShiftTy - Return a shift left or shift right constant expr
01489 Constant *ConstantExpr::getShiftTy(const Type *ReqTy, unsigned Opcode,
01490                                    Constant *C1, Constant *C2) {
01491   // Check the operands for consistency first
01492   assert((Opcode == Instruction::Shl ||
01493           Opcode == Instruction::Shr) &&
01494          "Invalid opcode in binary constant expression");
01495   assert(C1->getType()->isIntegral() && C2->getType() == Type::UByteTy &&
01496          "Invalid operand types for Shift constant expr!");
01497 
01498   if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
01499     return FC;          // Fold a few common cases...
01500 
01501   // Look up the constant in the table first to ensure uniqueness
01502   std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
01503   ExprMapKeyType Key = std::make_pair(Opcode, argVec);
01504   return ExprConstants.getOrCreate(ReqTy, Key);
01505 }
01506 
01507 
01508 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
01509                                            const std::vector<Value*> &IdxList) {
01510   assert(GetElementPtrInst::getIndexedType(C->getType(), IdxList, true) &&
01511          "GEP indices invalid!");
01512 
01513   if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
01514     return FC;          // Fold a few common cases...
01515 
01516   assert(isa<PointerType>(C->getType()) &&
01517          "Non-pointer type for constant GetElementPtr expression");
01518   // Look up the constant in the table first to ensure uniqueness
01519   std::vector<Constant*> ArgVec;
01520   ArgVec.reserve(IdxList.size()+1);
01521   ArgVec.push_back(C);
01522   for (unsigned i = 0, e = IdxList.size(); i != e; ++i)
01523     ArgVec.push_back(cast<Constant>(IdxList[i]));
01524   const ExprMapKeyType &Key = std::make_pair(Instruction::GetElementPtr,ArgVec);
01525   return ExprConstants.getOrCreate(ReqTy, Key);
01526 }
01527 
01528 Constant *ConstantExpr::getGetElementPtr(Constant *C,
01529                                          const std::vector<Constant*> &IdxList){
01530   // Get the result type of the getelementptr!
01531   std::vector<Value*> VIdxList(IdxList.begin(), IdxList.end());
01532 
01533   const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), VIdxList,
01534                                                      true);
01535   assert(Ty && "GEP indices invalid!");
01536   return getGetElementPtrTy(PointerType::get(Ty), C, VIdxList);
01537 }
01538 
01539 Constant *ConstantExpr::getGetElementPtr(Constant *C,
01540                                          const std::vector<Value*> &IdxList) {
01541   // Get the result type of the getelementptr!
01542   const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
01543                                                      true);
01544   assert(Ty && "GEP indices invalid!");
01545   return getGetElementPtrTy(PointerType::get(Ty), C, IdxList);
01546 }
01547 
01548 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
01549                                             Constant *Idx) {
01550   if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
01551     return FC;          // Fold a few common cases...
01552   // Look up the constant in the table first to ensure uniqueness
01553   std::vector<Constant*> ArgVec(1, Val);
01554   ArgVec.push_back(Idx);
01555   const ExprMapKeyType &Key = std::make_pair(Instruction::ExtractElement,ArgVec);
01556   return ExprConstants.getOrCreate(ReqTy, Key);
01557 }
01558 
01559 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
01560   assert(isa<PackedType>(Val->getType()) &&
01561          "Tried to create extractelement operation on non-packed type!");
01562   assert(Idx->getType() == Type::UIntTy &&
01563          "Extractelement index must be uint type!");
01564   return getExtractElementTy(cast<PackedType>(Val->getType())->getElementType(),
01565                              Val, Idx);
01566 }
01567 
01568 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
01569                                            Constant *Elt, Constant *Idx) {
01570   if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
01571     return FC;          // Fold a few common cases...
01572   // Look up the constant in the table first to ensure uniqueness
01573   std::vector<Constant*> ArgVec(1, Val);
01574   ArgVec.push_back(Elt);
01575   ArgVec.push_back(Idx);
01576   const ExprMapKeyType &Key = std::make_pair(Instruction::InsertElement,ArgVec);
01577   return ExprConstants.getOrCreate(ReqTy, Key);
01578 }
01579 
01580 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt, 
01581                                          Constant *Idx) {
01582   assert(isa<PackedType>(Val->getType()) &&
01583          "Tried to create insertelement operation on non-packed type!");
01584   assert(Elt->getType() == cast<PackedType>(Val->getType())->getElementType()
01585          && "Insertelement types must match!");
01586   assert(Idx->getType() == Type::UIntTy &&
01587          "Insertelement index must be uint type!");
01588   return getInsertElementTy(cast<PackedType>(Val->getType())->getElementType(),
01589                             Val, Elt, Idx);
01590 }
01591 
01592 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
01593                                            Constant *V2, Constant *Mask) {
01594   if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
01595     return FC;          // Fold a few common cases...
01596   // Look up the constant in the table first to ensure uniqueness
01597   std::vector<Constant*> ArgVec(1, V1);
01598   ArgVec.push_back(V2);
01599   ArgVec.push_back(Mask);
01600   const ExprMapKeyType &Key = std::make_pair(Instruction::ShuffleVector,ArgVec);
01601   return ExprConstants.getOrCreate(ReqTy, Key);
01602 }
01603 
01604 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2, 
01605                                          Constant *Mask) {
01606   assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
01607          "Invalid shuffle vector constant expr operands!");
01608   return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
01609 }
01610 
01611 
01612 // destroyConstant - Remove the constant from the constant table...
01613 //
01614 void ConstantExpr::destroyConstant() {
01615   ExprConstants.remove(this);
01616   destroyConstantImpl();
01617 }
01618 
01619 const char *ConstantExpr::getOpcodeName() const {
01620   return Instruction::getOpcodeName(getOpcode());
01621 }
01622 
01623 //===----------------------------------------------------------------------===//
01624 //                replaceUsesOfWithOnConstant implementations
01625 
01626 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
01627                                                 Use *U) {
01628   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
01629   Constant *ToC = cast<Constant>(To);
01630 
01631   unsigned OperandToUpdate = U-OperandList;
01632   assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
01633 
01634   std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
01635   Lookup.first.first = getType();
01636   Lookup.second = this;
01637 
01638   std::vector<Constant*> &Values = Lookup.first.second;
01639   Values.reserve(getNumOperands());  // Build replacement array.
01640 
01641   // Fill values with the modified operands of the constant array.  Also, 
01642   // compute whether this turns into an all-zeros array.
01643   bool isAllZeros = false;
01644   if (!ToC->isNullValue()) {
01645     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
01646       Values.push_back(cast<Constant>(O->get()));
01647   } else {
01648     isAllZeros = true;
01649     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
01650       Constant *Val = cast<Constant>(O->get());
01651       Values.push_back(Val);
01652       if (isAllZeros) isAllZeros = Val->isNullValue();
01653     }
01654   }
01655   Values[OperandToUpdate] = ToC;
01656   
01657   Constant *Replacement = 0;
01658   if (isAllZeros) {
01659     Replacement = ConstantAggregateZero::get(getType());
01660   } else {
01661     // Check to see if we have this array type already.
01662     bool Exists;
01663     ArrayConstantsTy::MapTy::iterator I =
01664       ArrayConstants.InsertOrGetItem(Lookup, Exists);
01665     
01666     if (Exists) {
01667       Replacement = I->second;
01668     } else {
01669       // Okay, the new shape doesn't exist in the system yet.  Instead of
01670       // creating a new constant array, inserting it, replaceallusesof'ing the
01671       // old with the new, then deleting the old... just update the current one
01672       // in place!
01673       ArrayConstants.MoveConstantToNewSlot(this, I);
01674       
01675       // Update to the new value.
01676       setOperand(OperandToUpdate, ToC);
01677       return;
01678     }
01679   }
01680  
01681   // Otherwise, I do need to replace this with an existing value.
01682   assert(Replacement != this && "I didn't contain From!");
01683   
01684   // Everyone using this now uses the replacement.
01685   uncheckedReplaceAllUsesWith(Replacement);
01686   
01687   // Delete the old constant!
01688   destroyConstant();
01689 }
01690 
01691 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
01692                                                  Use *U) {
01693   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
01694   Constant *ToC = cast<Constant>(To);
01695 
01696   unsigned OperandToUpdate = U-OperandList;
01697   assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
01698 
01699   std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
01700   Lookup.first.first = getType();
01701   Lookup.second = this;
01702   std::vector<Constant*> &Values = Lookup.first.second;
01703   Values.reserve(getNumOperands());  // Build replacement struct.
01704   
01705   
01706   // Fill values with the modified operands of the constant struct.  Also, 
01707   // compute whether this turns into an all-zeros struct.
01708   bool isAllZeros = false;
01709   if (!ToC->isNullValue()) {
01710     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
01711       Values.push_back(cast<Constant>(O->get()));
01712   } else {
01713     isAllZeros = true;
01714     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
01715       Constant *Val = cast<Constant>(O->get());
01716       Values.push_back(Val);
01717       if (isAllZeros) isAllZeros = Val->isNullValue();
01718     }
01719   }
01720   Values[OperandToUpdate] = ToC;
01721   
01722   Constant *Replacement = 0;
01723   if (isAllZeros) {
01724     Replacement = ConstantAggregateZero::get(getType());
01725   } else {
01726     // Check to see if we have this array type already.
01727     bool Exists;
01728     StructConstantsTy::MapTy::iterator I =
01729       StructConstants.InsertOrGetItem(Lookup, Exists);
01730     
01731     if (Exists) {
01732       Replacement = I->second;
01733     } else {
01734       // Okay, the new shape doesn't exist in the system yet.  Instead of
01735       // creating a new constant struct, inserting it, replaceallusesof'ing the
01736       // old with the new, then deleting the old... just update the current one
01737       // in place!
01738       StructConstants.MoveConstantToNewSlot(this, I);
01739       
01740       // Update to the new value.
01741       setOperand(OperandToUpdate, ToC);
01742       return;
01743     }
01744   }
01745   
01746   assert(Replacement != this && "I didn't contain From!");
01747   
01748   // Everyone using this now uses the replacement.
01749   uncheckedReplaceAllUsesWith(Replacement);
01750   
01751   // Delete the old constant!
01752   destroyConstant();
01753 }
01754 
01755 void ConstantPacked::replaceUsesOfWithOnConstant(Value *From, Value *To,
01756                                                  Use *U) {
01757   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
01758   
01759   std::vector<Constant*> Values;
01760   Values.reserve(getNumOperands());  // Build replacement array...
01761   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
01762     Constant *Val = getOperand(i);
01763     if (Val == From) Val = cast<Constant>(To);
01764     Values.push_back(Val);
01765   }
01766   
01767   Constant *Replacement = ConstantPacked::get(getType(), Values);
01768   assert(Replacement != this && "I didn't contain From!");
01769   
01770   // Everyone using this now uses the replacement.
01771   uncheckedReplaceAllUsesWith(Replacement);
01772   
01773   // Delete the old constant!
01774   destroyConstant();
01775 }
01776 
01777 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
01778                                                Use *U) {
01779   assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
01780   Constant *To = cast<Constant>(ToV);
01781   
01782   Constant *Replacement = 0;
01783   if (getOpcode() == Instruction::GetElementPtr) {
01784     std::vector<Constant*> Indices;
01785     Constant *Pointer = getOperand(0);
01786     Indices.reserve(getNumOperands()-1);
01787     if (Pointer == From) Pointer = To;
01788     
01789     for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
01790       Constant *Val = getOperand(i);
01791       if (Val == From) Val = To;
01792       Indices.push_back(Val);
01793     }
01794     Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
01795   } else if (getOpcode() == Instruction::Cast) {
01796     assert(getOperand(0) == From && "Cast only has one use!");
01797     Replacement = ConstantExpr::getCast(To, getType());
01798   } else if (getOpcode() == Instruction::Select) {
01799     Constant *C1 = getOperand(0);
01800     Constant *C2 = getOperand(1);
01801     Constant *C3 = getOperand(2);
01802     if (C1 == From) C1 = To;
01803     if (C2 == From) C2 = To;
01804     if (C3 == From) C3 = To;
01805     Replacement = ConstantExpr::getSelect(C1, C2, C3);
01806   } else if (getOpcode() == Instruction::ExtractElement) {
01807     Constant *C1 = getOperand(0);
01808     Constant *C2 = getOperand(1);
01809     if (C1 == From) C1 = To;
01810     if (C2 == From) C2 = To;
01811     Replacement = ConstantExpr::getExtractElement(C1, C2);
01812   } else if (getOpcode() == Instruction::InsertElement) {
01813     Constant *C1 = getOperand(0);
01814     Constant *C2 = getOperand(1);
01815     Constant *C3 = getOperand(1);
01816     if (C1 == From) C1 = To;
01817     if (C2 == From) C2 = To;
01818     if (C3 == From) C3 = To;
01819     Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
01820   } else if (getOpcode() == Instruction::ShuffleVector) {
01821     Constant *C1 = getOperand(0);
01822     Constant *C2 = getOperand(1);
01823     Constant *C3 = getOperand(2);
01824     if (C1 == From) C1 = To;
01825     if (C2 == From) C2 = To;
01826     if (C3 == From) C3 = To;
01827     Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
01828   } else if (getNumOperands() == 2) {
01829     Constant *C1 = getOperand(0);
01830     Constant *C2 = getOperand(1);
01831     if (C1 == From) C1 = To;
01832     if (C2 == From) C2 = To;
01833     Replacement = ConstantExpr::get(getOpcode(), C1, C2);
01834   } else {
01835     assert(0 && "Unknown ConstantExpr type!");
01836     return;
01837   }
01838   
01839   assert(Replacement != this && "I didn't contain From!");
01840   
01841   // Everyone using this now uses the replacement.
01842   uncheckedReplaceAllUsesWith(Replacement);
01843   
01844   // Delete the old constant!
01845   destroyConstant();
01846 }
01847 
01848 
01849 
01850 /// clearAllValueMaps - This method frees all internal memory used by the
01851 /// constant subsystem, which can be used in environments where this memory
01852 /// is otherwise reported as a leak.
01853 void Constant::clearAllValueMaps() {
01854   std::vector<Constant *> Constants;
01855 
01856   DoubleConstants.clear(Constants);
01857   FloatConstants.clear(Constants);
01858   SIntConstants.clear(Constants);
01859   UIntConstants.clear(Constants);
01860   AggZeroConstants.clear(Constants);
01861   ArrayConstants.clear(Constants);
01862   StructConstants.clear(Constants);
01863   PackedConstants.clear(Constants);
01864   NullPtrConstants.clear(Constants);
01865   UndefValueConstants.clear(Constants);
01866   ExprConstants.clear(Constants);
01867 
01868   for (std::vector<Constant *>::iterator I = Constants.begin(),
01869        E = Constants.end(); I != E; ++I)
01870     (*I)->dropAllReferences();
01871   for (std::vector<Constant *>::iterator I = Constants.begin(),
01872        E = Constants.end(); I != E; ++I)
01873     (*I)->destroyConstantImpl();
01874   Constants.clear();
01875 }
01876 
01877 /// getStringValue - Turn an LLVM constant pointer that eventually points to a
01878 /// global into a string value.  Return an empty string if we can't do it.
01879 /// Parameter Chop determines if the result is chopped at the first null
01880 /// terminator.
01881 ///
01882 std::string Constant::getStringValue(bool Chop, unsigned Offset) {
01883   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
01884     if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
01885       ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
01886       if (Init->isString()) {
01887         std::string Result = Init->getAsString();
01888         if (Offset < Result.size()) {
01889           // If we are pointing INTO The string, erase the beginning...
01890           Result.erase(Result.begin(), Result.begin()+Offset);
01891 
01892           // Take off the null terminator, and any string fragments after it.
01893           if (Chop) {
01894             std::string::size_type NullPos = Result.find_first_of((char)0);
01895             if (NullPos != std::string::npos)
01896               Result.erase(Result.begin()+NullPos, Result.end());
01897           }
01898           return Result;
01899         }
01900       }
01901     }
01902   } else if (Constant *C = dyn_cast<Constant>(this)) {
01903     if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
01904       return GV->getStringValue(Chop, Offset);
01905     else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
01906       if (CE->getOpcode() == Instruction::GetElementPtr) {
01907         // Turn a gep into the specified offset.
01908         if (CE->getNumOperands() == 3 &&
01909             cast<Constant>(CE->getOperand(1))->isNullValue() &&
01910             isa<ConstantInt>(CE->getOperand(2))) {
01911           Offset += cast<ConstantInt>(CE->getOperand(2))->getRawValue();
01912           return CE->getOperand(0)->getStringValue(Chop, Offset);
01913         }
01914       }
01915     }
01916   }
01917   return "";
01918 }
01919