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 is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the Constant* classes.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/IR/Constants.h"
00015 #include "ConstantFold.h"
00016 #include "LLVMContextImpl.h"
00017 #include "llvm/ADT/DenseMap.h"
00018 #include "llvm/ADT/FoldingSet.h"
00019 #include "llvm/ADT/STLExtras.h"
00020 #include "llvm/ADT/SmallVector.h"
00021 #include "llvm/ADT/StringExtras.h"
00022 #include "llvm/ADT/StringMap.h"
00023 #include "llvm/IR/DerivedTypes.h"
00024 #include "llvm/IR/GetElementPtrTypeIterator.h"
00025 #include "llvm/IR/GlobalValue.h"
00026 #include "llvm/IR/Instructions.h"
00027 #include "llvm/IR/Module.h"
00028 #include "llvm/IR/Operator.h"
00029 #include "llvm/Support/Compiler.h"
00030 #include "llvm/Support/Debug.h"
00031 #include "llvm/Support/ErrorHandling.h"
00032 #include "llvm/Support/ManagedStatic.h"
00033 #include "llvm/Support/MathExtras.h"
00034 #include "llvm/Support/raw_ostream.h"
00035 #include <algorithm>
00036 #include <cstdarg>
00037 using namespace llvm;
00038 
00039 //===----------------------------------------------------------------------===//
00040 //                              Constant Class
00041 //===----------------------------------------------------------------------===//
00042 
00043 void Constant::anchor() { }
00044 
00045 bool Constant::isNegativeZeroValue() const {
00046   // Floating point values have an explicit -0.0 value.
00047   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
00048     return CFP->isZero() && CFP->isNegative();
00049 
00050   // Equivalent for a vector of -0.0's.
00051   if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
00052     if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
00053       if (SplatCFP && SplatCFP->isZero() && SplatCFP->isNegative())
00054         return true;
00055 
00056   // We've already handled true FP case; any other FP vectors can't represent -0.0.
00057   if (getType()->isFPOrFPVectorTy())
00058     return false;
00059 
00060   // Otherwise, just use +0.0.
00061   return isNullValue();
00062 }
00063 
00064 // Return true iff this constant is positive zero (floating point), negative
00065 // zero (floating point), or a null value.
00066 bool Constant::isZeroValue() const {
00067   // Floating point values have an explicit -0.0 value.
00068   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
00069     return CFP->isZero();
00070 
00071   // Otherwise, just use +0.0.
00072   return isNullValue();
00073 }
00074 
00075 bool Constant::isNullValue() const {
00076   // 0 is null.
00077   if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
00078     return CI->isZero();
00079 
00080   // +0.0 is null.
00081   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
00082     return CFP->isZero() && !CFP->isNegative();
00083 
00084   // constant zero is zero for aggregates and cpnull is null for pointers.
00085   return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this);
00086 }
00087 
00088 bool Constant::isAllOnesValue() const {
00089   // Check for -1 integers
00090   if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
00091     return CI->isMinusOne();
00092 
00093   // Check for FP which are bitcasted from -1 integers
00094   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
00095     return CFP->getValueAPF().bitcastToAPInt().isAllOnesValue();
00096 
00097   // Check for constant vectors which are splats of -1 values.
00098   if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
00099     if (Constant *Splat = CV->getSplatValue())
00100       return Splat->isAllOnesValue();
00101 
00102   // Check for constant vectors which are splats of -1 values.
00103   if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
00104     if (Constant *Splat = CV->getSplatValue())
00105       return Splat->isAllOnesValue();
00106 
00107   return false;
00108 }
00109 
00110 bool Constant::isOneValue() const {
00111   // Check for 1 integers
00112   if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
00113     return CI->isOne();
00114 
00115   // Check for FP which are bitcasted from 1 integers
00116   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
00117     return CFP->getValueAPF().bitcastToAPInt() == 1;
00118 
00119   // Check for constant vectors which are splats of 1 values.
00120   if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
00121     if (Constant *Splat = CV->getSplatValue())
00122       return Splat->isOneValue();
00123 
00124   // Check for constant vectors which are splats of 1 values.
00125   if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
00126     if (Constant *Splat = CV->getSplatValue())
00127       return Splat->isOneValue();
00128 
00129   return false;
00130 }
00131 
00132 bool Constant::isMinSignedValue() const {
00133   // Check for INT_MIN integers
00134   if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
00135     return CI->isMinValue(/*isSigned=*/true);
00136 
00137   // Check for FP which are bitcasted from INT_MIN integers
00138   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
00139     return CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
00140 
00141   // Check for constant vectors which are splats of INT_MIN values.
00142   if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
00143     if (Constant *Splat = CV->getSplatValue())
00144       return Splat->isMinSignedValue();
00145 
00146   // Check for constant vectors which are splats of INT_MIN values.
00147   if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
00148     if (Constant *Splat = CV->getSplatValue())
00149       return Splat->isMinSignedValue();
00150 
00151   return false;
00152 }
00153 
00154 bool Constant::isNotMinSignedValue() const {
00155   // Check for INT_MIN integers
00156   if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
00157     return !CI->isMinValue(/*isSigned=*/true);
00158 
00159   // Check for FP which are bitcasted from INT_MIN integers
00160   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
00161     return !CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
00162 
00163   // Check for constant vectors which are splats of INT_MIN values.
00164   if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
00165     if (Constant *Splat = CV->getSplatValue())
00166       return Splat->isNotMinSignedValue();
00167 
00168   // Check for constant vectors which are splats of INT_MIN values.
00169   if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
00170     if (Constant *Splat = CV->getSplatValue())
00171       return Splat->isNotMinSignedValue();
00172 
00173   // It *may* contain INT_MIN, we can't tell.
00174   return false;
00175 }
00176 
00177 // Constructor to create a '0' constant of arbitrary type...
00178 Constant *Constant::getNullValue(Type *Ty) {
00179   switch (Ty->getTypeID()) {
00180   case Type::IntegerTyID:
00181     return ConstantInt::get(Ty, 0);
00182   case Type::HalfTyID:
00183     return ConstantFP::get(Ty->getContext(),
00184                            APFloat::getZero(APFloat::IEEEhalf));
00185   case Type::FloatTyID:
00186     return ConstantFP::get(Ty->getContext(),
00187                            APFloat::getZero(APFloat::IEEEsingle));
00188   case Type::DoubleTyID:
00189     return ConstantFP::get(Ty->getContext(),
00190                            APFloat::getZero(APFloat::IEEEdouble));
00191   case Type::X86_FP80TyID:
00192     return ConstantFP::get(Ty->getContext(),
00193                            APFloat::getZero(APFloat::x87DoubleExtended));
00194   case Type::FP128TyID:
00195     return ConstantFP::get(Ty->getContext(),
00196                            APFloat::getZero(APFloat::IEEEquad));
00197   case Type::PPC_FP128TyID:
00198     return ConstantFP::get(Ty->getContext(),
00199                            APFloat(APFloat::PPCDoubleDouble,
00200                                    APInt::getNullValue(128)));
00201   case Type::PointerTyID:
00202     return ConstantPointerNull::get(cast<PointerType>(Ty));
00203   case Type::StructTyID:
00204   case Type::ArrayTyID:
00205   case Type::VectorTyID:
00206     return ConstantAggregateZero::get(Ty);
00207   default:
00208     // Function, Label, or Opaque type?
00209     llvm_unreachable("Cannot create a null constant of that type!");
00210   }
00211 }
00212 
00213 Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) {
00214   Type *ScalarTy = Ty->getScalarType();
00215 
00216   // Create the base integer constant.
00217   Constant *C = ConstantInt::get(Ty->getContext(), V);
00218 
00219   // Convert an integer to a pointer, if necessary.
00220   if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
00221     C = ConstantExpr::getIntToPtr(C, PTy);
00222 
00223   // Broadcast a scalar to a vector, if necessary.
00224   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
00225     C = ConstantVector::getSplat(VTy->getNumElements(), C);
00226 
00227   return C;
00228 }
00229 
00230 Constant *Constant::getAllOnesValue(Type *Ty) {
00231   if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
00232     return ConstantInt::get(Ty->getContext(),
00233                             APInt::getAllOnesValue(ITy->getBitWidth()));
00234 
00235   if (Ty->isFloatingPointTy()) {
00236     APFloat FL = APFloat::getAllOnesValue(Ty->getPrimitiveSizeInBits(),
00237                                           !Ty->isPPC_FP128Ty());
00238     return ConstantFP::get(Ty->getContext(), FL);
00239   }
00240 
00241   VectorType *VTy = cast<VectorType>(Ty);
00242   return ConstantVector::getSplat(VTy->getNumElements(),
00243                                   getAllOnesValue(VTy->getElementType()));
00244 }
00245 
00246 /// getAggregateElement - For aggregates (struct/array/vector) return the
00247 /// constant that corresponds to the specified element if possible, or null if
00248 /// not.  This can return null if the element index is a ConstantExpr, or if
00249 /// 'this' is a constant expr.
00250 Constant *Constant::getAggregateElement(unsigned Elt) const {
00251   if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(this))
00252     return Elt < CS->getNumOperands() ? CS->getOperand(Elt) : nullptr;
00253 
00254   if (const ConstantArray *CA = dyn_cast<ConstantArray>(this))
00255     return Elt < CA->getNumOperands() ? CA->getOperand(Elt) : nullptr;
00256 
00257   if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
00258     return Elt < CV->getNumOperands() ? CV->getOperand(Elt) : nullptr;
00259 
00260   if (const ConstantAggregateZero *CAZ =dyn_cast<ConstantAggregateZero>(this))
00261     return CAZ->getElementValue(Elt);
00262 
00263   if (const UndefValue *UV = dyn_cast<UndefValue>(this))
00264     return UV->getElementValue(Elt);
00265 
00266   if (const ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(this))
00267     return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt)
00268                                        : nullptr;
00269   return nullptr;
00270 }
00271 
00272 Constant *Constant::getAggregateElement(Constant *Elt) const {
00273   assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
00274   if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt))
00275     return getAggregateElement(CI->getZExtValue());
00276   return nullptr;
00277 }
00278 
00279 
00280 void Constant::destroyConstantImpl() {
00281   // When a Constant is destroyed, there may be lingering
00282   // references to the constant by other constants in the constant pool.  These
00283   // constants are implicitly dependent on the module that is being deleted,
00284   // but they don't know that.  Because we only find out when the CPV is
00285   // deleted, we must now notify all of our users (that should only be
00286   // Constants) that they are, in fact, invalid now and should be deleted.
00287   //
00288   while (!use_empty()) {
00289     Value *V = user_back();
00290 #ifndef NDEBUG      // Only in -g mode...
00291     if (!isa<Constant>(V)) {
00292       dbgs() << "While deleting: " << *this
00293              << "\n\nUse still stuck around after Def is destroyed: "
00294              << *V << "\n\n";
00295     }
00296 #endif
00297     assert(isa<Constant>(V) && "References remain to Constant being destroyed");
00298     cast<Constant>(V)->destroyConstant();
00299 
00300     // The constant should remove itself from our use list...
00301     assert((use_empty() || user_back() != V) && "Constant not removed!");
00302   }
00303 
00304   // Value has no outstanding references it is safe to delete it now...
00305   delete this;
00306 }
00307 
00308 static bool canTrapImpl(const Constant *C,
00309                         SmallPtrSetImpl<const ConstantExpr *> &NonTrappingOps) {
00310   assert(C->getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
00311   // The only thing that could possibly trap are constant exprs.
00312   const ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
00313   if (!CE)
00314     return false;
00315 
00316   // ConstantExpr traps if any operands can trap.
00317   for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
00318     if (ConstantExpr *Op = dyn_cast<ConstantExpr>(CE->getOperand(i))) {
00319       if (NonTrappingOps.insert(Op) && canTrapImpl(Op, NonTrappingOps))
00320         return true;
00321     }
00322   }
00323 
00324   // Otherwise, only specific operations can trap.
00325   switch (CE->getOpcode()) {
00326   default:
00327     return false;
00328   case Instruction::UDiv:
00329   case Instruction::SDiv:
00330   case Instruction::FDiv:
00331   case Instruction::URem:
00332   case Instruction::SRem:
00333   case Instruction::FRem:
00334     // Div and rem can trap if the RHS is not known to be non-zero.
00335     if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
00336       return true;
00337     return false;
00338   }
00339 }
00340 
00341 /// canTrap - Return true if evaluation of this constant could trap.  This is
00342 /// true for things like constant expressions that could divide by zero.
00343 bool Constant::canTrap() const {
00344   SmallPtrSet<const ConstantExpr *, 4> NonTrappingOps;
00345   return canTrapImpl(this, NonTrappingOps);
00346 }
00347 
00348 /// Check if C contains a GlobalValue for which Predicate is true.
00349 static bool
00350 ConstHasGlobalValuePredicate(const Constant *C,
00351                              bool (*Predicate)(const GlobalValue *)) {
00352   SmallPtrSet<const Constant *, 8> Visited;
00353   SmallVector<const Constant *, 8> WorkList;
00354   WorkList.push_back(C);
00355   Visited.insert(C);
00356 
00357   while (!WorkList.empty()) {
00358     const Constant *WorkItem = WorkList.pop_back_val();
00359     if (const auto *GV = dyn_cast<GlobalValue>(WorkItem))
00360       if (Predicate(GV))
00361         return true;
00362     for (const Value *Op : WorkItem->operands()) {
00363       const Constant *ConstOp = dyn_cast<Constant>(Op);
00364       if (!ConstOp)
00365         continue;
00366       if (Visited.insert(ConstOp))
00367         WorkList.push_back(ConstOp);
00368     }
00369   }
00370   return false;
00371 }
00372 
00373 /// Return true if the value can vary between threads.
00374 bool Constant::isThreadDependent() const {
00375   auto DLLImportPredicate = [](const GlobalValue *GV) {
00376     return GV->isThreadLocal();
00377   };
00378   return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
00379 }
00380 
00381 bool Constant::isDLLImportDependent() const {
00382   auto DLLImportPredicate = [](const GlobalValue *GV) {
00383     return GV->hasDLLImportStorageClass();
00384   };
00385   return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
00386 }
00387 
00388 /// Return true if the constant has users other than constant exprs and other
00389 /// dangling things.
00390 bool Constant::isConstantUsed() const {
00391   for (const User *U : users()) {
00392     const Constant *UC = dyn_cast<Constant>(U);
00393     if (!UC || isa<GlobalValue>(UC))
00394       return true;
00395 
00396     if (UC->isConstantUsed())
00397       return true;
00398   }
00399   return false;
00400 }
00401 
00402 
00403 
00404 /// getRelocationInfo - This method classifies the entry according to
00405 /// whether or not it may generate a relocation entry.  This must be
00406 /// conservative, so if it might codegen to a relocatable entry, it should say
00407 /// so.  The return values are:
00408 /// 
00409 ///  NoRelocation: This constant pool entry is guaranteed to never have a
00410 ///     relocation applied to it (because it holds a simple constant like
00411 ///     '4').
00412 ///  LocalRelocation: This entry has relocations, but the entries are
00413 ///     guaranteed to be resolvable by the static linker, so the dynamic
00414 ///     linker will never see them.
00415 ///  GlobalRelocations: This entry may have arbitrary relocations.
00416 ///
00417 /// FIXME: This really should not be in IR.
00418 Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
00419   if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
00420     if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
00421       return LocalRelocation;  // Local to this file/library.
00422     return GlobalRelocations;    // Global reference.
00423   }
00424   
00425   if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
00426     return BA->getFunction()->getRelocationInfo();
00427   
00428   // While raw uses of blockaddress need to be relocated, differences between
00429   // two of them don't when they are for labels in the same function.  This is a
00430   // common idiom when creating a table for the indirect goto extension, so we
00431   // handle it efficiently here.
00432   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this))
00433     if (CE->getOpcode() == Instruction::Sub) {
00434       ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
00435       ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
00436       if (LHS && RHS &&
00437           LHS->getOpcode() == Instruction::PtrToInt &&
00438           RHS->getOpcode() == Instruction::PtrToInt &&
00439           isa<BlockAddress>(LHS->getOperand(0)) &&
00440           isa<BlockAddress>(RHS->getOperand(0)) &&
00441           cast<BlockAddress>(LHS->getOperand(0))->getFunction() ==
00442             cast<BlockAddress>(RHS->getOperand(0))->getFunction())
00443         return NoRelocation;
00444     }
00445 
00446   PossibleRelocationsTy Result = NoRelocation;
00447   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
00448     Result = std::max(Result,
00449                       cast<Constant>(getOperand(i))->getRelocationInfo());
00450 
00451   return Result;
00452 }
00453 
00454 /// removeDeadUsersOfConstant - If the specified constantexpr is dead, remove
00455 /// it.  This involves recursively eliminating any dead users of the
00456 /// constantexpr.
00457 static bool removeDeadUsersOfConstant(const Constant *C) {
00458   if (isa<GlobalValue>(C)) return false; // Cannot remove this
00459 
00460   while (!C->use_empty()) {
00461     const Constant *User = dyn_cast<Constant>(C->user_back());
00462     if (!User) return false; // Non-constant usage;
00463     if (!removeDeadUsersOfConstant(User))
00464       return false; // Constant wasn't dead
00465   }
00466 
00467   const_cast<Constant*>(C)->destroyConstant();
00468   return true;
00469 }
00470 
00471 
00472 /// removeDeadConstantUsers - If there are any dead constant users dangling
00473 /// off of this constant, remove them.  This method is useful for clients
00474 /// that want to check to see if a global is unused, but don't want to deal
00475 /// with potentially dead constants hanging off of the globals.
00476 void Constant::removeDeadConstantUsers() const {
00477   Value::const_user_iterator I = user_begin(), E = user_end();
00478   Value::const_user_iterator LastNonDeadUser = E;
00479   while (I != E) {
00480     const Constant *User = dyn_cast<Constant>(*I);
00481     if (!User) {
00482       LastNonDeadUser = I;
00483       ++I;
00484       continue;
00485     }
00486 
00487     if (!removeDeadUsersOfConstant(User)) {
00488       // If the constant wasn't dead, remember that this was the last live use
00489       // and move on to the next constant.
00490       LastNonDeadUser = I;
00491       ++I;
00492       continue;
00493     }
00494 
00495     // If the constant was dead, then the iterator is invalidated.
00496     if (LastNonDeadUser == E) {
00497       I = user_begin();
00498       if (I == E) break;
00499     } else {
00500       I = LastNonDeadUser;
00501       ++I;
00502     }
00503   }
00504 }
00505 
00506 
00507 
00508 //===----------------------------------------------------------------------===//
00509 //                                ConstantInt
00510 //===----------------------------------------------------------------------===//
00511 
00512 void ConstantInt::anchor() { }
00513 
00514 ConstantInt::ConstantInt(IntegerType *Ty, const APInt& V)
00515   : Constant(Ty, ConstantIntVal, nullptr, 0), Val(V) {
00516   assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
00517 }
00518 
00519 ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
00520   LLVMContextImpl *pImpl = Context.pImpl;
00521   if (!pImpl->TheTrueVal)
00522     pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
00523   return pImpl->TheTrueVal;
00524 }
00525 
00526 ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
00527   LLVMContextImpl *pImpl = Context.pImpl;
00528   if (!pImpl->TheFalseVal)
00529     pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
00530   return pImpl->TheFalseVal;
00531 }
00532 
00533 Constant *ConstantInt::getTrue(Type *Ty) {
00534   VectorType *VTy = dyn_cast<VectorType>(Ty);
00535   if (!VTy) {
00536     assert(Ty->isIntegerTy(1) && "True must be i1 or vector of i1.");
00537     return ConstantInt::getTrue(Ty->getContext());
00538   }
00539   assert(VTy->getElementType()->isIntegerTy(1) &&
00540          "True must be vector of i1 or i1.");
00541   return ConstantVector::getSplat(VTy->getNumElements(),
00542                                   ConstantInt::getTrue(Ty->getContext()));
00543 }
00544 
00545 Constant *ConstantInt::getFalse(Type *Ty) {
00546   VectorType *VTy = dyn_cast<VectorType>(Ty);
00547   if (!VTy) {
00548     assert(Ty->isIntegerTy(1) && "False must be i1 or vector of i1.");
00549     return ConstantInt::getFalse(Ty->getContext());
00550   }
00551   assert(VTy->getElementType()->isIntegerTy(1) &&
00552          "False must be vector of i1 or i1.");
00553   return ConstantVector::getSplat(VTy->getNumElements(),
00554                                   ConstantInt::getFalse(Ty->getContext()));
00555 }
00556 
00557 
00558 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap 
00559 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
00560 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
00561 // compare APInt's of different widths, which would violate an APInt class
00562 // invariant which generates an assertion.
00563 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
00564   // Get the corresponding integer type for the bit width of the value.
00565   IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
00566   // get an existing value or the insertion position
00567   LLVMContextImpl *pImpl = Context.pImpl;
00568   ConstantInt *&Slot = pImpl->IntConstants[DenseMapAPIntKeyInfo::KeyTy(V, ITy)];
00569   if (!Slot) Slot = new ConstantInt(ITy, V);
00570   return Slot;
00571 }
00572 
00573 Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
00574   Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
00575 
00576   // For vectors, broadcast the value.
00577   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
00578     return ConstantVector::getSplat(VTy->getNumElements(), C);
00579 
00580   return C;
00581 }
00582 
00583 ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V, 
00584                               bool isSigned) {
00585   return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
00586 }
00587 
00588 ConstantInt *ConstantInt::getSigned(IntegerType *Ty, int64_t V) {
00589   return get(Ty, V, true);
00590 }
00591 
00592 Constant *ConstantInt::getSigned(Type *Ty, int64_t V) {
00593   return get(Ty, V, true);
00594 }
00595 
00596 Constant *ConstantInt::get(Type *Ty, const APInt& V) {
00597   ConstantInt *C = get(Ty->getContext(), V);
00598   assert(C->getType() == Ty->getScalarType() &&
00599          "ConstantInt type doesn't match the type implied by its value!");
00600 
00601   // For vectors, broadcast the value.
00602   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
00603     return ConstantVector::getSplat(VTy->getNumElements(), C);
00604 
00605   return C;
00606 }
00607 
00608 ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str,
00609                               uint8_t radix) {
00610   return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
00611 }
00612 
00613 //===----------------------------------------------------------------------===//
00614 //                                ConstantFP
00615 //===----------------------------------------------------------------------===//
00616 
00617 static const fltSemantics *TypeToFloatSemantics(Type *Ty) {
00618   if (Ty->isHalfTy())
00619     return &APFloat::IEEEhalf;
00620   if (Ty->isFloatTy())
00621     return &APFloat::IEEEsingle;
00622   if (Ty->isDoubleTy())
00623     return &APFloat::IEEEdouble;
00624   if (Ty->isX86_FP80Ty())
00625     return &APFloat::x87DoubleExtended;
00626   else if (Ty->isFP128Ty())
00627     return &APFloat::IEEEquad;
00628 
00629   assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
00630   return &APFloat::PPCDoubleDouble;
00631 }
00632 
00633 void ConstantFP::anchor() { }
00634 
00635 /// get() - This returns a constant fp for the specified value in the
00636 /// specified type.  This should only be used for simple constant values like
00637 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
00638 Constant *ConstantFP::get(Type *Ty, double V) {
00639   LLVMContext &Context = Ty->getContext();
00640 
00641   APFloat FV(V);
00642   bool ignored;
00643   FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
00644              APFloat::rmNearestTiesToEven, &ignored);
00645   Constant *C = get(Context, FV);
00646 
00647   // For vectors, broadcast the value.
00648   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
00649     return ConstantVector::getSplat(VTy->getNumElements(), C);
00650 
00651   return C;
00652 }
00653 
00654 
00655 Constant *ConstantFP::get(Type *Ty, StringRef Str) {
00656   LLVMContext &Context = Ty->getContext();
00657 
00658   APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
00659   Constant *C = get(Context, FV);
00660 
00661   // For vectors, broadcast the value.
00662   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
00663     return ConstantVector::getSplat(VTy->getNumElements(), C);
00664 
00665   return C; 
00666 }
00667 
00668 Constant *ConstantFP::getNegativeZero(Type *Ty) {
00669   const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
00670   APFloat NegZero = APFloat::getZero(Semantics, /*Negative=*/true);
00671   Constant *C = get(Ty->getContext(), NegZero);
00672 
00673   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
00674     return ConstantVector::getSplat(VTy->getNumElements(), C);
00675 
00676   return C;
00677 }
00678 
00679 
00680 Constant *ConstantFP::getZeroValueForNegation(Type *Ty) {
00681   if (Ty->isFPOrFPVectorTy())
00682     return getNegativeZero(Ty);
00683 
00684   return Constant::getNullValue(Ty);
00685 }
00686 
00687 
00688 // ConstantFP accessors.
00689 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
00690   LLVMContextImpl* pImpl = Context.pImpl;
00691 
00692   ConstantFP *&Slot = pImpl->FPConstants[DenseMapAPFloatKeyInfo::KeyTy(V)];
00693 
00694   if (!Slot) {
00695     Type *Ty;
00696     if (&V.getSemantics() == &APFloat::IEEEhalf)
00697       Ty = Type::getHalfTy(Context);
00698     else if (&V.getSemantics() == &APFloat::IEEEsingle)
00699       Ty = Type::getFloatTy(Context);
00700     else if (&V.getSemantics() == &APFloat::IEEEdouble)
00701       Ty = Type::getDoubleTy(Context);
00702     else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
00703       Ty = Type::getX86_FP80Ty(Context);
00704     else if (&V.getSemantics() == &APFloat::IEEEquad)
00705       Ty = Type::getFP128Ty(Context);
00706     else {
00707       assert(&V.getSemantics() == &APFloat::PPCDoubleDouble && 
00708              "Unknown FP format");
00709       Ty = Type::getPPC_FP128Ty(Context);
00710     }
00711     Slot = new ConstantFP(Ty, V);
00712   }
00713 
00714   return Slot;
00715 }
00716 
00717 Constant *ConstantFP::getInfinity(Type *Ty, bool Negative) {
00718   const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
00719   Constant *C = get(Ty->getContext(), APFloat::getInf(Semantics, Negative));
00720 
00721   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
00722     return ConstantVector::getSplat(VTy->getNumElements(), C);
00723 
00724   return C;
00725 }
00726 
00727 ConstantFP::ConstantFP(Type *Ty, const APFloat& V)
00728   : Constant(Ty, ConstantFPVal, nullptr, 0), Val(V) {
00729   assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
00730          "FP type Mismatch");
00731 }
00732 
00733 bool ConstantFP::isExactlyValue(const APFloat &V) const {
00734   return Val.bitwiseIsEqual(V);
00735 }
00736 
00737 //===----------------------------------------------------------------------===//
00738 //                   ConstantAggregateZero Implementation
00739 //===----------------------------------------------------------------------===//
00740 
00741 /// getSequentialElement - If this CAZ has array or vector type, return a zero
00742 /// with the right element type.
00743 Constant *ConstantAggregateZero::getSequentialElement() const {
00744   return Constant::getNullValue(getType()->getSequentialElementType());
00745 }
00746 
00747 /// getStructElement - If this CAZ has struct type, return a zero with the
00748 /// right element type for the specified element.
00749 Constant *ConstantAggregateZero::getStructElement(unsigned Elt) const {
00750   return Constant::getNullValue(getType()->getStructElementType(Elt));
00751 }
00752 
00753 /// getElementValue - Return a zero of the right value for the specified GEP
00754 /// index if we can, otherwise return null (e.g. if C is a ConstantExpr).
00755 Constant *ConstantAggregateZero::getElementValue(Constant *C) const {
00756   if (isa<SequentialType>(getType()))
00757     return getSequentialElement();
00758   return getStructElement(cast<ConstantInt>(C)->getZExtValue());
00759 }
00760 
00761 /// getElementValue - Return a zero of the right value for the specified GEP
00762 /// index.
00763 Constant *ConstantAggregateZero::getElementValue(unsigned Idx) const {
00764   if (isa<SequentialType>(getType()))
00765     return getSequentialElement();
00766   return getStructElement(Idx);
00767 }
00768 
00769 
00770 //===----------------------------------------------------------------------===//
00771 //                         UndefValue Implementation
00772 //===----------------------------------------------------------------------===//
00773 
00774 /// getSequentialElement - If this undef has array or vector type, return an
00775 /// undef with the right element type.
00776 UndefValue *UndefValue::getSequentialElement() const {
00777   return UndefValue::get(getType()->getSequentialElementType());
00778 }
00779 
00780 /// getStructElement - If this undef has struct type, return a zero with the
00781 /// right element type for the specified element.
00782 UndefValue *UndefValue::getStructElement(unsigned Elt) const {
00783   return UndefValue::get(getType()->getStructElementType(Elt));
00784 }
00785 
00786 /// getElementValue - Return an undef of the right value for the specified GEP
00787 /// index if we can, otherwise return null (e.g. if C is a ConstantExpr).
00788 UndefValue *UndefValue::getElementValue(Constant *C) const {
00789   if (isa<SequentialType>(getType()))
00790     return getSequentialElement();
00791   return getStructElement(cast<ConstantInt>(C)->getZExtValue());
00792 }
00793 
00794 /// getElementValue - Return an undef of the right value for the specified GEP
00795 /// index.
00796 UndefValue *UndefValue::getElementValue(unsigned Idx) const {
00797   if (isa<SequentialType>(getType()))
00798     return getSequentialElement();
00799   return getStructElement(Idx);
00800 }
00801 
00802 
00803 
00804 //===----------------------------------------------------------------------===//
00805 //                            ConstantXXX Classes
00806 //===----------------------------------------------------------------------===//
00807 
00808 template <typename ItTy, typename EltTy>
00809 static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
00810   for (; Start != End; ++Start)
00811     if (*Start != Elt)
00812       return false;
00813   return true;
00814 }
00815 
00816 ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
00817   : Constant(T, ConstantArrayVal,
00818              OperandTraits<ConstantArray>::op_end(this) - V.size(),
00819              V.size()) {
00820   assert(V.size() == T->getNumElements() &&
00821          "Invalid initializer vector for constant array");
00822   for (unsigned i = 0, e = V.size(); i != e; ++i)
00823     assert(V[i]->getType() == T->getElementType() &&
00824            "Initializer for array element doesn't match array element type!");
00825   std::copy(V.begin(), V.end(), op_begin());
00826 }
00827 
00828 Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
00829   if (Constant *C = getImpl(Ty, V))
00830     return C;
00831   return Ty->getContext().pImpl->ArrayConstants.getOrCreate(Ty, V);
00832 }
00833 Constant *ConstantArray::getImpl(ArrayType *Ty, ArrayRef<Constant*> V) {
00834   // Empty arrays are canonicalized to ConstantAggregateZero.
00835   if (V.empty())
00836     return ConstantAggregateZero::get(Ty);
00837 
00838   for (unsigned i = 0, e = V.size(); i != e; ++i) {
00839     assert(V[i]->getType() == Ty->getElementType() &&
00840            "Wrong type in array element initializer");
00841   }
00842 
00843   // If this is an all-zero array, return a ConstantAggregateZero object.  If
00844   // all undef, return an UndefValue, if "all simple", then return a
00845   // ConstantDataArray.
00846   Constant *C = V[0];
00847   if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
00848     return UndefValue::get(Ty);
00849 
00850   if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
00851     return ConstantAggregateZero::get(Ty);
00852 
00853   // Check to see if all of the elements are ConstantFP or ConstantInt and if
00854   // the element type is compatible with ConstantDataVector.  If so, use it.
00855   if (ConstantDataSequential::isElementTypeCompatible(C->getType())) {
00856     // We speculatively build the elements here even if it turns out that there
00857     // is a constantexpr or something else weird in the array, since it is so
00858     // uncommon for that to happen.
00859     if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
00860       if (CI->getType()->isIntegerTy(8)) {
00861         SmallVector<uint8_t, 16> Elts;
00862         for (unsigned i = 0, e = V.size(); i != e; ++i)
00863           if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
00864             Elts.push_back(CI->getZExtValue());
00865           else
00866             break;
00867         if (Elts.size() == V.size())
00868           return ConstantDataArray::get(C->getContext(), Elts);
00869       } else if (CI->getType()->isIntegerTy(16)) {
00870         SmallVector<uint16_t, 16> Elts;
00871         for (unsigned i = 0, e = V.size(); i != e; ++i)
00872           if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
00873             Elts.push_back(CI->getZExtValue());
00874           else
00875             break;
00876         if (Elts.size() == V.size())
00877           return ConstantDataArray::get(C->getContext(), Elts);
00878       } else if (CI->getType()->isIntegerTy(32)) {
00879         SmallVector<uint32_t, 16> Elts;
00880         for (unsigned i = 0, e = V.size(); i != e; ++i)
00881           if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
00882             Elts.push_back(CI->getZExtValue());
00883           else
00884             break;
00885         if (Elts.size() == V.size())
00886           return ConstantDataArray::get(C->getContext(), Elts);
00887       } else if (CI->getType()->isIntegerTy(64)) {
00888         SmallVector<uint64_t, 16> Elts;
00889         for (unsigned i = 0, e = V.size(); i != e; ++i)
00890           if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
00891             Elts.push_back(CI->getZExtValue());
00892           else
00893             break;
00894         if (Elts.size() == V.size())
00895           return ConstantDataArray::get(C->getContext(), Elts);
00896       }
00897     }
00898 
00899     if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
00900       if (CFP->getType()->isFloatTy()) {
00901         SmallVector<float, 16> Elts;
00902         for (unsigned i = 0, e = V.size(); i != e; ++i)
00903           if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
00904             Elts.push_back(CFP->getValueAPF().convertToFloat());
00905           else
00906             break;
00907         if (Elts.size() == V.size())
00908           return ConstantDataArray::get(C->getContext(), Elts);
00909       } else if (CFP->getType()->isDoubleTy()) {
00910         SmallVector<double, 16> Elts;
00911         for (unsigned i = 0, e = V.size(); i != e; ++i)
00912           if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
00913             Elts.push_back(CFP->getValueAPF().convertToDouble());
00914           else
00915             break;
00916         if (Elts.size() == V.size())
00917           return ConstantDataArray::get(C->getContext(), Elts);
00918       }
00919     }
00920   }
00921 
00922   // Otherwise, we really do want to create a ConstantArray.
00923   return nullptr;
00924 }
00925 
00926 /// getTypeForElements - Return an anonymous struct type to use for a constant
00927 /// with the specified set of elements.  The list must not be empty.
00928 StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
00929                                                ArrayRef<Constant*> V,
00930                                                bool Packed) {
00931   unsigned VecSize = V.size();
00932   SmallVector<Type*, 16> EltTypes(VecSize);
00933   for (unsigned i = 0; i != VecSize; ++i)
00934     EltTypes[i] = V[i]->getType();
00935 
00936   return StructType::get(Context, EltTypes, Packed);
00937 }
00938 
00939 
00940 StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
00941                                                bool Packed) {
00942   assert(!V.empty() &&
00943          "ConstantStruct::getTypeForElements cannot be called on empty list");
00944   return getTypeForElements(V[0]->getContext(), V, Packed);
00945 }
00946 
00947 
00948 ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
00949   : Constant(T, ConstantStructVal,
00950              OperandTraits<ConstantStruct>::op_end(this) - V.size(),
00951              V.size()) {
00952   assert(V.size() == T->getNumElements() &&
00953          "Invalid initializer vector for constant structure");
00954   for (unsigned i = 0, e = V.size(); i != e; ++i)
00955     assert((T->isOpaque() || V[i]->getType() == T->getElementType(i)) &&
00956            "Initializer for struct element doesn't match struct element type!");
00957   std::copy(V.begin(), V.end(), op_begin());
00958 }
00959 
00960 // ConstantStruct accessors.
00961 Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
00962   assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
00963          "Incorrect # elements specified to ConstantStruct::get");
00964 
00965   // Create a ConstantAggregateZero value if all elements are zeros.
00966   bool isZero = true;
00967   bool isUndef = false;
00968   
00969   if (!V.empty()) {
00970     isUndef = isa<UndefValue>(V[0]);
00971     isZero = V[0]->isNullValue();
00972     if (isUndef || isZero) {
00973       for (unsigned i = 0, e = V.size(); i != e; ++i) {
00974         if (!V[i]->isNullValue())
00975           isZero = false;
00976         if (!isa<UndefValue>(V[i]))
00977           isUndef = false;
00978       }
00979     }
00980   }
00981   if (isZero)
00982     return ConstantAggregateZero::get(ST);
00983   if (isUndef)
00984     return UndefValue::get(ST);
00985 
00986   return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
00987 }
00988 
00989 Constant *ConstantStruct::get(StructType *T, ...) {
00990   va_list ap;
00991   SmallVector<Constant*, 8> Values;
00992   va_start(ap, T);
00993   while (Constant *Val = va_arg(ap, llvm::Constant*))
00994     Values.push_back(Val);
00995   va_end(ap);
00996   return get(T, Values);
00997 }
00998 
00999 ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
01000   : Constant(T, ConstantVectorVal,
01001              OperandTraits<ConstantVector>::op_end(this) - V.size(),
01002              V.size()) {
01003   for (size_t i = 0, e = V.size(); i != e; i++)
01004     assert(V[i]->getType() == T->getElementType() &&
01005            "Initializer for vector element doesn't match vector element type!");
01006   std::copy(V.begin(), V.end(), op_begin());
01007 }
01008 
01009 // ConstantVector accessors.
01010 Constant *ConstantVector::get(ArrayRef<Constant*> V) {
01011   if (Constant *C = getImpl(V))
01012     return C;
01013   VectorType *Ty = VectorType::get(V.front()->getType(), V.size());
01014   return Ty->getContext().pImpl->VectorConstants.getOrCreate(Ty, V);
01015 }
01016 Constant *ConstantVector::getImpl(ArrayRef<Constant*> V) {
01017   assert(!V.empty() && "Vectors can't be empty");
01018   VectorType *T = VectorType::get(V.front()->getType(), V.size());
01019 
01020   // If this is an all-undef or all-zero vector, return a
01021   // ConstantAggregateZero or UndefValue.
01022   Constant *C = V[0];
01023   bool isZero = C->isNullValue();
01024   bool isUndef = isa<UndefValue>(C);
01025 
01026   if (isZero || isUndef) {
01027     for (unsigned i = 1, e = V.size(); i != e; ++i)
01028       if (V[i] != C) {
01029         isZero = isUndef = false;
01030         break;
01031       }
01032   }
01033 
01034   if (isZero)
01035     return ConstantAggregateZero::get(T);
01036   if (isUndef)
01037     return UndefValue::get(T);
01038 
01039   // Check to see if all of the elements are ConstantFP or ConstantInt and if
01040   // the element type is compatible with ConstantDataVector.  If so, use it.
01041   if (ConstantDataSequential::isElementTypeCompatible(C->getType())) {
01042     // We speculatively build the elements here even if it turns out that there
01043     // is a constantexpr or something else weird in the array, since it is so
01044     // uncommon for that to happen.
01045     if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
01046       if (CI->getType()->isIntegerTy(8)) {
01047         SmallVector<uint8_t, 16> Elts;
01048         for (unsigned i = 0, e = V.size(); i != e; ++i)
01049           if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
01050             Elts.push_back(CI->getZExtValue());
01051           else
01052             break;
01053         if (Elts.size() == V.size())
01054           return ConstantDataVector::get(C->getContext(), Elts);
01055       } else if (CI->getType()->isIntegerTy(16)) {
01056         SmallVector<uint16_t, 16> Elts;
01057         for (unsigned i = 0, e = V.size(); i != e; ++i)
01058           if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
01059             Elts.push_back(CI->getZExtValue());
01060           else
01061             break;
01062         if (Elts.size() == V.size())
01063           return ConstantDataVector::get(C->getContext(), Elts);
01064       } else if (CI->getType()->isIntegerTy(32)) {
01065         SmallVector<uint32_t, 16> Elts;
01066         for (unsigned i = 0, e = V.size(); i != e; ++i)
01067           if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
01068             Elts.push_back(CI->getZExtValue());
01069           else
01070             break;
01071         if (Elts.size() == V.size())
01072           return ConstantDataVector::get(C->getContext(), Elts);
01073       } else if (CI->getType()->isIntegerTy(64)) {
01074         SmallVector<uint64_t, 16> Elts;
01075         for (unsigned i = 0, e = V.size(); i != e; ++i)
01076           if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
01077             Elts.push_back(CI->getZExtValue());
01078           else
01079             break;
01080         if (Elts.size() == V.size())
01081           return ConstantDataVector::get(C->getContext(), Elts);
01082       }
01083     }
01084 
01085     if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
01086       if (CFP->getType()->isFloatTy()) {
01087         SmallVector<float, 16> Elts;
01088         for (unsigned i = 0, e = V.size(); i != e; ++i)
01089           if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
01090             Elts.push_back(CFP->getValueAPF().convertToFloat());
01091           else
01092             break;
01093         if (Elts.size() == V.size())
01094           return ConstantDataVector::get(C->getContext(), Elts);
01095       } else if (CFP->getType()->isDoubleTy()) {
01096         SmallVector<double, 16> Elts;
01097         for (unsigned i = 0, e = V.size(); i != e; ++i)
01098           if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
01099             Elts.push_back(CFP->getValueAPF().convertToDouble());
01100           else
01101             break;
01102         if (Elts.size() == V.size())
01103           return ConstantDataVector::get(C->getContext(), Elts);
01104       }
01105     }
01106   }
01107 
01108   // Otherwise, the element type isn't compatible with ConstantDataVector, or
01109   // the operand list constants a ConstantExpr or something else strange.
01110   return nullptr;
01111 }
01112 
01113 Constant *ConstantVector::getSplat(unsigned NumElts, Constant *V) {
01114   // If this splat is compatible with ConstantDataVector, use it instead of
01115   // ConstantVector.
01116   if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&
01117       ConstantDataSequential::isElementTypeCompatible(V->getType()))
01118     return ConstantDataVector::getSplat(NumElts, V);
01119 
01120   SmallVector<Constant*, 32> Elts(NumElts, V);
01121   return get(Elts);
01122 }
01123 
01124 
01125 // Utility function for determining if a ConstantExpr is a CastOp or not. This
01126 // can't be inline because we don't want to #include Instruction.h into
01127 // Constant.h
01128 bool ConstantExpr::isCast() const {
01129   return Instruction::isCast(getOpcode());
01130 }
01131 
01132 bool ConstantExpr::isCompare() const {
01133   return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
01134 }
01135 
01136 bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
01137   if (getOpcode() != Instruction::GetElementPtr) return false;
01138 
01139   gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
01140   User::const_op_iterator OI = std::next(this->op_begin());
01141 
01142   // Skip the first index, as it has no static limit.
01143   ++GEPI;
01144   ++OI;
01145 
01146   // The remaining indices must be compile-time known integers within the
01147   // bounds of the corresponding notional static array types.
01148   for (; GEPI != E; ++GEPI, ++OI) {
01149     ConstantInt *CI = dyn_cast<ConstantInt>(*OI);
01150     if (!CI) return false;
01151     if (ArrayType *ATy = dyn_cast<ArrayType>(*GEPI))
01152       if (CI->getValue().getActiveBits() > 64 ||
01153           CI->getZExtValue() >= ATy->getNumElements())
01154         return false;
01155   }
01156 
01157   // All the indices checked out.
01158   return true;
01159 }
01160 
01161 bool ConstantExpr::hasIndices() const {
01162   return getOpcode() == Instruction::ExtractValue ||
01163          getOpcode() == Instruction::InsertValue;
01164 }
01165 
01166 ArrayRef<unsigned> ConstantExpr::getIndices() const {
01167   if (const ExtractValueConstantExpr *EVCE =
01168         dyn_cast<ExtractValueConstantExpr>(this))
01169     return EVCE->Indices;
01170 
01171   return cast<InsertValueConstantExpr>(this)->Indices;
01172 }
01173 
01174 unsigned ConstantExpr::getPredicate() const {
01175   assert(isCompare());
01176   return ((const CompareConstantExpr*)this)->predicate;
01177 }
01178 
01179 /// getWithOperandReplaced - Return a constant expression identical to this
01180 /// one, but with the specified operand set to the specified value.
01181 Constant *
01182 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
01183   assert(Op->getType() == getOperand(OpNo)->getType() &&
01184          "Replacing operand with value of different type!");
01185   if (getOperand(OpNo) == Op)
01186     return const_cast<ConstantExpr*>(this);
01187 
01188   SmallVector<Constant*, 8> NewOps;
01189   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
01190     NewOps.push_back(i == OpNo ? Op : getOperand(i));
01191 
01192   return getWithOperands(NewOps);
01193 }
01194 
01195 /// getWithOperands - This returns the current constant expression with the
01196 /// operands replaced with the specified values.  The specified array must
01197 /// have the same number of operands as our current one.
01198 Constant *ConstantExpr::getWithOperands(ArrayRef<Constant *> Ops, Type *Ty,
01199                                         bool OnlyIfReduced) const {
01200   assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
01201   bool AnyChange = Ty != getType();
01202   for (unsigned i = 0; i != Ops.size(); ++i)
01203     AnyChange |= Ops[i] != getOperand(i);
01204 
01205   if (!AnyChange)  // No operands changed, return self.
01206     return const_cast<ConstantExpr*>(this);
01207 
01208   Type *OnlyIfReducedTy = OnlyIfReduced ? Ty : nullptr;
01209   switch (getOpcode()) {
01210   case Instruction::Trunc:
01211   case Instruction::ZExt:
01212   case Instruction::SExt:
01213   case Instruction::FPTrunc:
01214   case Instruction::FPExt:
01215   case Instruction::UIToFP:
01216   case Instruction::SIToFP:
01217   case Instruction::FPToUI:
01218   case Instruction::FPToSI:
01219   case Instruction::PtrToInt:
01220   case Instruction::IntToPtr:
01221   case Instruction::BitCast:
01222   case Instruction::AddrSpaceCast:
01223     return ConstantExpr::getCast(getOpcode(), Ops[0], Ty, OnlyIfReduced);
01224   case Instruction::Select:
01225     return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2], OnlyIfReducedTy);
01226   case Instruction::InsertElement:
01227     return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2],
01228                                           OnlyIfReducedTy);
01229   case Instruction::ExtractElement:
01230     return ConstantExpr::getExtractElement(Ops[0], Ops[1], OnlyIfReducedTy);
01231   case Instruction::InsertValue:
01232     return ConstantExpr::getInsertValue(Ops[0], Ops[1], getIndices(),
01233                                         OnlyIfReducedTy);
01234   case Instruction::ExtractValue:
01235     return ConstantExpr::getExtractValue(Ops[0], getIndices(), OnlyIfReducedTy);
01236   case Instruction::ShuffleVector:
01237     return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2],
01238                                           OnlyIfReducedTy);
01239   case Instruction::GetElementPtr:
01240     return ConstantExpr::getGetElementPtr(Ops[0], Ops.slice(1),
01241                                           cast<GEPOperator>(this)->isInBounds(),
01242                                           OnlyIfReducedTy);
01243   case Instruction::ICmp:
01244   case Instruction::FCmp:
01245     return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1],
01246                                     OnlyIfReducedTy);
01247   default:
01248     assert(getNumOperands() == 2 && "Must be binary operator?");
01249     return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData,
01250                              OnlyIfReducedTy);
01251   }
01252 }
01253 
01254 
01255 //===----------------------------------------------------------------------===//
01256 //                      isValueValidForType implementations
01257 
01258 bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
01259   unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
01260   if (Ty->isIntegerTy(1))
01261     return Val == 0 || Val == 1;
01262   if (NumBits >= 64)
01263     return true; // always true, has to fit in largest type
01264   uint64_t Max = (1ll << NumBits) - 1;
01265   return Val <= Max;
01266 }
01267 
01268 bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
01269   unsigned NumBits = Ty->getIntegerBitWidth();
01270   if (Ty->isIntegerTy(1))
01271     return Val == 0 || Val == 1 || Val == -1;
01272   if (NumBits >= 64)
01273     return true; // always true, has to fit in largest type
01274   int64_t Min = -(1ll << (NumBits-1));
01275   int64_t Max = (1ll << (NumBits-1)) - 1;
01276   return (Val >= Min && Val <= Max);
01277 }
01278 
01279 bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {
01280   // convert modifies in place, so make a copy.
01281   APFloat Val2 = APFloat(Val);
01282   bool losesInfo;
01283   switch (Ty->getTypeID()) {
01284   default:
01285     return false;         // These can't be represented as floating point!
01286 
01287   // FIXME rounding mode needs to be more flexible
01288   case Type::HalfTyID: {
01289     if (&Val2.getSemantics() == &APFloat::IEEEhalf)
01290       return true;
01291     Val2.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &losesInfo);
01292     return !losesInfo;
01293   }
01294   case Type::FloatTyID: {
01295     if (&Val2.getSemantics() == &APFloat::IEEEsingle)
01296       return true;
01297     Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
01298     return !losesInfo;
01299   }
01300   case Type::DoubleTyID: {
01301     if (&Val2.getSemantics() == &APFloat::IEEEhalf ||
01302         &Val2.getSemantics() == &APFloat::IEEEsingle ||
01303         &Val2.getSemantics() == &APFloat::IEEEdouble)
01304       return true;
01305     Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
01306     return !losesInfo;
01307   }
01308   case Type::X86_FP80TyID:
01309     return &Val2.getSemantics() == &APFloat::IEEEhalf ||
01310            &Val2.getSemantics() == &APFloat::IEEEsingle || 
01311            &Val2.getSemantics() == &APFloat::IEEEdouble ||
01312            &Val2.getSemantics() == &APFloat::x87DoubleExtended;
01313   case Type::FP128TyID:
01314     return &Val2.getSemantics() == &APFloat::IEEEhalf ||
01315            &Val2.getSemantics() == &APFloat::IEEEsingle || 
01316            &Val2.getSemantics() == &APFloat::IEEEdouble ||
01317            &Val2.getSemantics() == &APFloat::IEEEquad;
01318   case Type::PPC_FP128TyID:
01319     return &Val2.getSemantics() == &APFloat::IEEEhalf ||
01320            &Val2.getSemantics() == &APFloat::IEEEsingle || 
01321            &Val2.getSemantics() == &APFloat::IEEEdouble ||
01322            &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
01323   }
01324 }
01325 
01326 
01327 //===----------------------------------------------------------------------===//
01328 //                      Factory Function Implementation
01329 
01330 ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
01331   assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
01332          "Cannot create an aggregate zero of non-aggregate type!");
01333   
01334   ConstantAggregateZero *&Entry = Ty->getContext().pImpl->CAZConstants[Ty];
01335   if (!Entry)
01336     Entry = new ConstantAggregateZero(Ty);
01337 
01338   return Entry;
01339 }
01340 
01341 /// destroyConstant - Remove the constant from the constant table.
01342 ///
01343 void ConstantAggregateZero::destroyConstant() {
01344   getContext().pImpl->CAZConstants.erase(getType());
01345   destroyConstantImpl();
01346 }
01347 
01348 /// destroyConstant - Remove the constant from the constant table...
01349 ///
01350 void ConstantArray::destroyConstant() {
01351   getType()->getContext().pImpl->ArrayConstants.remove(this);
01352   destroyConstantImpl();
01353 }
01354 
01355 
01356 //---- ConstantStruct::get() implementation...
01357 //
01358 
01359 // destroyConstant - Remove the constant from the constant table...
01360 //
01361 void ConstantStruct::destroyConstant() {
01362   getType()->getContext().pImpl->StructConstants.remove(this);
01363   destroyConstantImpl();
01364 }
01365 
01366 // destroyConstant - Remove the constant from the constant table...
01367 //
01368 void ConstantVector::destroyConstant() {
01369   getType()->getContext().pImpl->VectorConstants.remove(this);
01370   destroyConstantImpl();
01371 }
01372 
01373 /// getSplatValue - If this is a splat vector constant, meaning that all of
01374 /// the elements have the same value, return that value. Otherwise return 0.
01375 Constant *Constant::getSplatValue() const {
01376   assert(this->getType()->isVectorTy() && "Only valid for vectors!");
01377   if (isa<ConstantAggregateZero>(this))
01378     return getNullValue(this->getType()->getVectorElementType());
01379   if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
01380     return CV->getSplatValue();
01381   if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
01382     return CV->getSplatValue();
01383   return nullptr;
01384 }
01385 
01386 /// getSplatValue - If this is a splat constant, where all of the
01387 /// elements have the same value, return that value. Otherwise return null.
01388 Constant *ConstantVector::getSplatValue() const {
01389   // Check out first element.
01390   Constant *Elt = getOperand(0);
01391   // Then make sure all remaining elements point to the same value.
01392   for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
01393     if (getOperand(I) != Elt)
01394       return nullptr;
01395   return Elt;
01396 }
01397 
01398 /// If C is a constant integer then return its value, otherwise C must be a
01399 /// vector of constant integers, all equal, and the common value is returned.
01400 const APInt &Constant::getUniqueInteger() const {
01401   if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
01402     return CI->getValue();
01403   assert(this->getSplatValue() && "Doesn't contain a unique integer!");
01404   const Constant *C = this->getAggregateElement(0U);
01405   assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
01406   return cast<ConstantInt>(C)->getValue();
01407 }
01408 
01409 
01410 //---- ConstantPointerNull::get() implementation.
01411 //
01412 
01413 ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
01414   ConstantPointerNull *&Entry = Ty->getContext().pImpl->CPNConstants[Ty];
01415   if (!Entry)
01416     Entry = new ConstantPointerNull(Ty);
01417 
01418   return Entry;
01419 }
01420 
01421 // destroyConstant - Remove the constant from the constant table...
01422 //
01423 void ConstantPointerNull::destroyConstant() {
01424   getContext().pImpl->CPNConstants.erase(getType());
01425   // Free the constant and any dangling references to it.
01426   destroyConstantImpl();
01427 }
01428 
01429 
01430 //---- UndefValue::get() implementation.
01431 //
01432 
01433 UndefValue *UndefValue::get(Type *Ty) {
01434   UndefValue *&Entry = Ty->getContext().pImpl->UVConstants[Ty];
01435   if (!Entry)
01436     Entry = new UndefValue(Ty);
01437 
01438   return Entry;
01439 }
01440 
01441 // destroyConstant - Remove the constant from the constant table.
01442 //
01443 void UndefValue::destroyConstant() {
01444   // Free the constant and any dangling references to it.
01445   getContext().pImpl->UVConstants.erase(getType());
01446   destroyConstantImpl();
01447 }
01448 
01449 //---- BlockAddress::get() implementation.
01450 //
01451 
01452 BlockAddress *BlockAddress::get(BasicBlock *BB) {
01453   assert(BB->getParent() && "Block must have a parent");
01454   return get(BB->getParent(), BB);
01455 }
01456 
01457 BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
01458   BlockAddress *&BA =
01459     F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
01460   if (!BA)
01461     BA = new BlockAddress(F, BB);
01462 
01463   assert(BA->getFunction() == F && "Basic block moved between functions");
01464   return BA;
01465 }
01466 
01467 BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
01468 : Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
01469            &Op<0>(), 2) {
01470   setOperand(0, F);
01471   setOperand(1, BB);
01472   BB->AdjustBlockAddressRefCount(1);
01473 }
01474 
01475 BlockAddress *BlockAddress::lookup(const BasicBlock *BB) {
01476   if (!BB->hasAddressTaken())
01477     return nullptr;
01478 
01479   const Function *F = BB->getParent();
01480   assert(F && "Block must have a parent");
01481   BlockAddress *BA =
01482       F->getContext().pImpl->BlockAddresses.lookup(std::make_pair(F, BB));
01483   assert(BA && "Refcount and block address map disagree!");
01484   return BA;
01485 }
01486 
01487 // destroyConstant - Remove the constant from the constant table.
01488 //
01489 void BlockAddress::destroyConstant() {
01490   getFunction()->getType()->getContext().pImpl
01491     ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
01492   getBasicBlock()->AdjustBlockAddressRefCount(-1);
01493   destroyConstantImpl();
01494 }
01495 
01496 void BlockAddress::replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U) {
01497   // This could be replacing either the Basic Block or the Function.  In either
01498   // case, we have to remove the map entry.
01499   Function *NewF = getFunction();
01500   BasicBlock *NewBB = getBasicBlock();
01501 
01502   if (U == &Op<0>())
01503     NewF = cast<Function>(To->stripPointerCasts());
01504   else
01505     NewBB = cast<BasicBlock>(To);
01506 
01507   // See if the 'new' entry already exists, if not, just update this in place
01508   // and return early.
01509   BlockAddress *&NewBA =
01510     getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
01511   if (NewBA) {
01512     replaceUsesOfWithOnConstantImpl(NewBA);
01513     return;
01514   }
01515 
01516   getBasicBlock()->AdjustBlockAddressRefCount(-1);
01517 
01518   // Remove the old entry, this can't cause the map to rehash (just a
01519   // tombstone will get added).
01520   getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
01521                                                           getBasicBlock()));
01522   NewBA = this;
01523   setOperand(0, NewF);
01524   setOperand(1, NewBB);
01525   getBasicBlock()->AdjustBlockAddressRefCount(1);
01526 }
01527 
01528 //---- ConstantExpr::get() implementations.
01529 //
01530 
01531 /// This is a utility function to handle folding of casts and lookup of the
01532 /// cast in the ExprConstants map. It is used by the various get* methods below.
01533 static Constant *getFoldedCast(Instruction::CastOps opc, Constant *C, Type *Ty,
01534                                bool OnlyIfReduced = false) {
01535   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
01536   // Fold a few common cases
01537   if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
01538     return FC;
01539 
01540   if (OnlyIfReduced)
01541     return nullptr;
01542 
01543   LLVMContextImpl *pImpl = Ty->getContext().pImpl;
01544 
01545   // Look up the constant in the table first to ensure uniqueness.
01546   ConstantExprKeyType Key(opc, C);
01547 
01548   return pImpl->ExprConstants.getOrCreate(Ty, Key);
01549 }
01550 
01551 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty,
01552                                 bool OnlyIfReduced) {
01553   Instruction::CastOps opc = Instruction::CastOps(oc);
01554   assert(Instruction::isCast(opc) && "opcode out of range");
01555   assert(C && Ty && "Null arguments to getCast");
01556   assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
01557 
01558   switch (opc) {
01559   default:
01560     llvm_unreachable("Invalid cast opcode");
01561   case Instruction::Trunc:
01562     return getTrunc(C, Ty, OnlyIfReduced);
01563   case Instruction::ZExt:
01564     return getZExt(C, Ty, OnlyIfReduced);
01565   case Instruction::SExt:
01566     return getSExt(C, Ty, OnlyIfReduced);
01567   case Instruction::FPTrunc:
01568     return getFPTrunc(C, Ty, OnlyIfReduced);
01569   case Instruction::FPExt:
01570     return getFPExtend(C, Ty, OnlyIfReduced);
01571   case Instruction::UIToFP:
01572     return getUIToFP(C, Ty, OnlyIfReduced);
01573   case Instruction::SIToFP:
01574     return getSIToFP(C, Ty, OnlyIfReduced);
01575   case Instruction::FPToUI:
01576     return getFPToUI(C, Ty, OnlyIfReduced);
01577   case Instruction::FPToSI:
01578     return getFPToSI(C, Ty, OnlyIfReduced);
01579   case Instruction::PtrToInt:
01580     return getPtrToInt(C, Ty, OnlyIfReduced);
01581   case Instruction::IntToPtr:
01582     return getIntToPtr(C, Ty, OnlyIfReduced);
01583   case Instruction::BitCast:
01584     return getBitCast(C, Ty, OnlyIfReduced);
01585   case Instruction::AddrSpaceCast:
01586     return getAddrSpaceCast(C, Ty, OnlyIfReduced);
01587   }
01588 }
01589 
01590 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) {
01591   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
01592     return getBitCast(C, Ty);
01593   return getZExt(C, Ty);
01594 }
01595 
01596 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) {
01597   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
01598     return getBitCast(C, Ty);
01599   return getSExt(C, Ty);
01600 }
01601 
01602 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {
01603   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
01604     return getBitCast(C, Ty);
01605   return getTrunc(C, Ty);
01606 }
01607 
01608 Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {
01609   assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
01610   assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
01611           "Invalid cast");
01612 
01613   if (Ty->isIntOrIntVectorTy())
01614     return getPtrToInt(S, Ty);
01615 
01616   unsigned SrcAS = S->getType()->getPointerAddressSpace();
01617   if (Ty->isPtrOrPtrVectorTy() && SrcAS != Ty->getPointerAddressSpace())
01618     return getAddrSpaceCast(S, Ty);
01619 
01620   return getBitCast(S, Ty);
01621 }
01622 
01623 Constant *ConstantExpr::getPointerBitCastOrAddrSpaceCast(Constant *S,
01624                                                          Type *Ty) {
01625   assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
01626   assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
01627 
01628   if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
01629     return getAddrSpaceCast(S, Ty);
01630 
01631   return getBitCast(S, Ty);
01632 }
01633 
01634 Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty,
01635                                        bool isSigned) {
01636   assert(C->getType()->isIntOrIntVectorTy() &&
01637          Ty->isIntOrIntVectorTy() && "Invalid cast");
01638   unsigned SrcBits = C->getType()->getScalarSizeInBits();
01639   unsigned DstBits = Ty->getScalarSizeInBits();
01640   Instruction::CastOps opcode =
01641     (SrcBits == DstBits ? Instruction::BitCast :
01642      (SrcBits > DstBits ? Instruction::Trunc :
01643       (isSigned ? Instruction::SExt : Instruction::ZExt)));
01644   return getCast(opcode, C, Ty);
01645 }
01646 
01647 Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) {
01648   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
01649          "Invalid cast");
01650   unsigned SrcBits = C->getType()->getScalarSizeInBits();
01651   unsigned DstBits = Ty->getScalarSizeInBits();
01652   if (SrcBits == DstBits)
01653     return C; // Avoid a useless cast
01654   Instruction::CastOps opcode =
01655     (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
01656   return getCast(opcode, C, Ty);
01657 }
01658 
01659 Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
01660 #ifndef NDEBUG
01661   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
01662   bool toVec = Ty->getTypeID() == Type::VectorTyID;
01663 #endif
01664   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
01665   assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
01666   assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
01667   assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
01668          "SrcTy must be larger than DestTy for Trunc!");
01669 
01670   return getFoldedCast(Instruction::Trunc, C, Ty, OnlyIfReduced);
01671 }
01672 
01673 Constant *ConstantExpr::getSExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
01674 #ifndef NDEBUG
01675   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
01676   bool toVec = Ty->getTypeID() == Type::VectorTyID;
01677 #endif
01678   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
01679   assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
01680   assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
01681   assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
01682          "SrcTy must be smaller than DestTy for SExt!");
01683 
01684   return getFoldedCast(Instruction::SExt, C, Ty, OnlyIfReduced);
01685 }
01686 
01687 Constant *ConstantExpr::getZExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
01688 #ifndef NDEBUG
01689   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
01690   bool toVec = Ty->getTypeID() == Type::VectorTyID;
01691 #endif
01692   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
01693   assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
01694   assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
01695   assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
01696          "SrcTy must be smaller than DestTy for ZExt!");
01697 
01698   return getFoldedCast(Instruction::ZExt, C, Ty, OnlyIfReduced);
01699 }
01700 
01701 Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
01702 #ifndef NDEBUG
01703   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
01704   bool toVec = Ty->getTypeID() == Type::VectorTyID;
01705 #endif
01706   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
01707   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
01708          C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
01709          "This is an illegal floating point truncation!");
01710   return getFoldedCast(Instruction::FPTrunc, C, Ty, OnlyIfReduced);
01711 }
01712 
01713 Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty, bool OnlyIfReduced) {
01714 #ifndef NDEBUG
01715   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
01716   bool toVec = Ty->getTypeID() == Type::VectorTyID;
01717 #endif
01718   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
01719   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
01720          C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
01721          "This is an illegal floating point extension!");
01722   return getFoldedCast(Instruction::FPExt, C, Ty, OnlyIfReduced);
01723 }
01724 
01725 Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
01726 #ifndef NDEBUG
01727   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
01728   bool toVec = Ty->getTypeID() == Type::VectorTyID;
01729 #endif
01730   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
01731   assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
01732          "This is an illegal uint to floating point cast!");
01733   return getFoldedCast(Instruction::UIToFP, C, Ty, OnlyIfReduced);
01734 }
01735 
01736 Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
01737 #ifndef NDEBUG
01738   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
01739   bool toVec = Ty->getTypeID() == Type::VectorTyID;
01740 #endif
01741   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
01742   assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
01743          "This is an illegal sint to floating point cast!");
01744   return getFoldedCast(Instruction::SIToFP, C, Ty, OnlyIfReduced);
01745 }
01746 
01747 Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty, bool OnlyIfReduced) {
01748 #ifndef NDEBUG
01749   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
01750   bool toVec = Ty->getTypeID() == Type::VectorTyID;
01751 #endif
01752   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
01753   assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
01754          "This is an illegal floating point to uint cast!");
01755   return getFoldedCast(Instruction::FPToUI, C, Ty, OnlyIfReduced);
01756 }
01757 
01758 Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty, bool OnlyIfReduced) {
01759 #ifndef NDEBUG
01760   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
01761   bool toVec = Ty->getTypeID() == Type::VectorTyID;
01762 #endif
01763   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
01764   assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
01765          "This is an illegal floating point to sint cast!");
01766   return getFoldedCast(Instruction::FPToSI, C, Ty, OnlyIfReduced);
01767 }
01768 
01769 Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy,
01770                                     bool OnlyIfReduced) {
01771   assert(C->getType()->getScalarType()->isPointerTy() &&
01772          "PtrToInt source must be pointer or pointer vector");
01773   assert(DstTy->getScalarType()->isIntegerTy() && 
01774          "PtrToInt destination must be integer or integer vector");
01775   assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
01776   if (isa<VectorType>(C->getType()))
01777     assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
01778            "Invalid cast between a different number of vector elements");
01779   return getFoldedCast(Instruction::PtrToInt, C, DstTy, OnlyIfReduced);
01780 }
01781 
01782 Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy,
01783                                     bool OnlyIfReduced) {
01784   assert(C->getType()->getScalarType()->isIntegerTy() &&
01785          "IntToPtr source must be integer or integer vector");
01786   assert(DstTy->getScalarType()->isPointerTy() &&
01787          "IntToPtr destination must be a pointer or pointer vector");
01788   assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
01789   if (isa<VectorType>(C->getType()))
01790     assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
01791            "Invalid cast between a different number of vector elements");
01792   return getFoldedCast(Instruction::IntToPtr, C, DstTy, OnlyIfReduced);
01793 }
01794 
01795 Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy,
01796                                    bool OnlyIfReduced) {
01797   assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
01798          "Invalid constantexpr bitcast!");
01799 
01800   // It is common to ask for a bitcast of a value to its own type, handle this
01801   // speedily.
01802   if (C->getType() == DstTy) return C;
01803 
01804   return getFoldedCast(Instruction::BitCast, C, DstTy, OnlyIfReduced);
01805 }
01806 
01807 Constant *ConstantExpr::getAddrSpaceCast(Constant *C, Type *DstTy,
01808                                          bool OnlyIfReduced) {
01809   assert(CastInst::castIsValid(Instruction::AddrSpaceCast, C, DstTy) &&
01810          "Invalid constantexpr addrspacecast!");
01811 
01812   // Canonicalize addrspacecasts between different pointer types by first
01813   // bitcasting the pointer type and then converting the address space.
01814   PointerType *SrcScalarTy = cast<PointerType>(C->getType()->getScalarType());
01815   PointerType *DstScalarTy = cast<PointerType>(DstTy->getScalarType());
01816   Type *DstElemTy = DstScalarTy->getElementType();
01817   if (SrcScalarTy->getElementType() != DstElemTy) {
01818     Type *MidTy = PointerType::get(DstElemTy, SrcScalarTy->getAddressSpace());
01819     if (VectorType *VT = dyn_cast<VectorType>(DstTy)) {
01820       // Handle vectors of pointers.
01821       MidTy = VectorType::get(MidTy, VT->getNumElements());
01822     }
01823     C = getBitCast(C, MidTy);
01824   }
01825   return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced);
01826 }
01827 
01828 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
01829                             unsigned Flags, Type *OnlyIfReducedTy) {
01830   // Check the operands for consistency first.
01831   assert(Opcode >= Instruction::BinaryOpsBegin &&
01832          Opcode <  Instruction::BinaryOpsEnd   &&
01833          "Invalid opcode in binary constant expression");
01834   assert(C1->getType() == C2->getType() &&
01835          "Operand types in binary constant expression should match");
01836 
01837 #ifndef NDEBUG
01838   switch (Opcode) {
01839   case Instruction::Add:
01840   case Instruction::Sub:
01841   case Instruction::Mul:
01842     assert(C1->getType() == C2->getType() && "Op types should be identical!");
01843     assert(C1->getType()->isIntOrIntVectorTy() &&
01844            "Tried to create an integer operation on a non-integer type!");
01845     break;
01846   case Instruction::FAdd:
01847   case Instruction::FSub:
01848   case Instruction::FMul:
01849     assert(C1->getType() == C2->getType() && "Op types should be identical!");
01850     assert(C1->getType()->isFPOrFPVectorTy() &&
01851            "Tried to create a floating-point operation on a "
01852            "non-floating-point type!");
01853     break;
01854   case Instruction::UDiv: 
01855   case Instruction::SDiv: 
01856     assert(C1->getType() == C2->getType() && "Op types should be identical!");
01857     assert(C1->getType()->isIntOrIntVectorTy() &&
01858            "Tried to create an arithmetic operation on a non-arithmetic type!");
01859     break;
01860   case Instruction::FDiv:
01861     assert(C1->getType() == C2->getType() && "Op types should be identical!");
01862     assert(C1->getType()->isFPOrFPVectorTy() &&
01863            "Tried to create an arithmetic operation on a non-arithmetic type!");
01864     break;
01865   case Instruction::URem: 
01866   case Instruction::SRem: 
01867     assert(C1->getType() == C2->getType() && "Op types should be identical!");
01868     assert(C1->getType()->isIntOrIntVectorTy() &&
01869            "Tried to create an arithmetic operation on a non-arithmetic type!");
01870     break;
01871   case Instruction::FRem:
01872     assert(C1->getType() == C2->getType() && "Op types should be identical!");
01873     assert(C1->getType()->isFPOrFPVectorTy() &&
01874            "Tried to create an arithmetic operation on a non-arithmetic type!");
01875     break;
01876   case Instruction::And:
01877   case Instruction::Or:
01878   case Instruction::Xor:
01879     assert(C1->getType() == C2->getType() && "Op types should be identical!");
01880     assert(C1->getType()->isIntOrIntVectorTy() &&
01881            "Tried to create a logical operation on a non-integral type!");
01882     break;
01883   case Instruction::Shl:
01884   case Instruction::LShr:
01885   case Instruction::AShr:
01886     assert(C1->getType() == C2->getType() && "Op types should be identical!");
01887     assert(C1->getType()->isIntOrIntVectorTy() &&
01888            "Tried to create a shift operation on a non-integer type!");
01889     break;
01890   default:
01891     break;
01892   }
01893 #endif
01894 
01895   if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
01896     return FC;          // Fold a few common cases.
01897 
01898   if (OnlyIfReducedTy == C1->getType())
01899     return nullptr;
01900 
01901   Constant *ArgVec[] = { C1, C2 };
01902   ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
01903 
01904   LLVMContextImpl *pImpl = C1->getContext().pImpl;
01905   return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
01906 }
01907 
01908 Constant *ConstantExpr::getSizeOf(Type* Ty) {
01909   // sizeof is implemented as: (i64) gep (Ty*)null, 1
01910   // Note that a non-inbounds gep is used, as null isn't within any object.
01911   Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
01912   Constant *GEP = getGetElementPtr(
01913                  Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
01914   return getPtrToInt(GEP, 
01915                      Type::getInt64Ty(Ty->getContext()));
01916 }
01917 
01918 Constant *ConstantExpr::getAlignOf(Type* Ty) {
01919   // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
01920   // Note that a non-inbounds gep is used, as null isn't within any object.
01921   Type *AligningTy = 
01922     StructType::get(Type::getInt1Ty(Ty->getContext()), Ty, NULL);
01923   Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo(0));
01924   Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
01925   Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
01926   Constant *Indices[2] = { Zero, One };
01927   Constant *GEP = getGetElementPtr(NullPtr, Indices);
01928   return getPtrToInt(GEP,
01929                      Type::getInt64Ty(Ty->getContext()));
01930 }
01931 
01932 Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) {
01933   return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
01934                                            FieldNo));
01935 }
01936 
01937 Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) {
01938   // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
01939   // Note that a non-inbounds gep is used, as null isn't within any object.
01940   Constant *GEPIdx[] = {
01941     ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
01942     FieldNo
01943   };
01944   Constant *GEP = getGetElementPtr(
01945                 Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
01946   return getPtrToInt(GEP,
01947                      Type::getInt64Ty(Ty->getContext()));
01948 }
01949 
01950 Constant *ConstantExpr::getCompare(unsigned short Predicate, Constant *C1,
01951                                    Constant *C2, bool OnlyIfReduced) {
01952   assert(C1->getType() == C2->getType() && "Op types should be identical!");
01953 
01954   switch (Predicate) {
01955   default: llvm_unreachable("Invalid CmpInst predicate");
01956   case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
01957   case CmpInst::FCMP_OGE:   case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
01958   case CmpInst::FCMP_ONE:   case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
01959   case CmpInst::FCMP_UEQ:   case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
01960   case CmpInst::FCMP_ULT:   case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
01961   case CmpInst::FCMP_TRUE:
01962     return getFCmp(Predicate, C1, C2, OnlyIfReduced);
01963 
01964   case CmpInst::ICMP_EQ:  case CmpInst::ICMP_NE:  case CmpInst::ICMP_UGT:
01965   case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
01966   case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
01967   case CmpInst::ICMP_SLE:
01968     return getICmp(Predicate, C1, C2, OnlyIfReduced);
01969   }
01970 }
01971 
01972 Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2,
01973                                   Type *OnlyIfReducedTy) {
01974   assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
01975 
01976   if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
01977     return SC;        // Fold common cases
01978 
01979   if (OnlyIfReducedTy == V1->getType())
01980     return nullptr;
01981 
01982   Constant *ArgVec[] = { C, V1, V2 };
01983   ConstantExprKeyType Key(Instruction::Select, ArgVec);
01984 
01985   LLVMContextImpl *pImpl = C->getContext().pImpl;
01986   return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
01987 }
01988 
01989 Constant *ConstantExpr::getGetElementPtr(Constant *C, ArrayRef<Value *> Idxs,
01990                                          bool InBounds, Type *OnlyIfReducedTy) {
01991   assert(C->getType()->isPtrOrPtrVectorTy() &&
01992          "Non-pointer type for constant GetElementPtr expression");
01993 
01994   if (Constant *FC = ConstantFoldGetElementPtr(C, InBounds, Idxs))
01995     return FC;          // Fold a few common cases.
01996 
01997   // Get the result type of the getelementptr!
01998   Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), Idxs);
01999   assert(Ty && "GEP indices invalid!");
02000   unsigned AS = C->getType()->getPointerAddressSpace();
02001   Type *ReqTy = Ty->getPointerTo(AS);
02002   if (VectorType *VecTy = dyn_cast<VectorType>(C->getType()))
02003     ReqTy = VectorType::get(ReqTy, VecTy->getNumElements());
02004 
02005   if (OnlyIfReducedTy == ReqTy)
02006     return nullptr;
02007 
02008   // Look up the constant in the table first to ensure uniqueness
02009   std::vector<Constant*> ArgVec;
02010   ArgVec.reserve(1 + Idxs.size());
02011   ArgVec.push_back(C);
02012   for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
02013     assert(Idxs[i]->getType()->isVectorTy() == ReqTy->isVectorTy() &&
02014            "getelementptr index type missmatch");
02015     assert((!Idxs[i]->getType()->isVectorTy() ||
02016             ReqTy->getVectorNumElements() ==
02017             Idxs[i]->getType()->getVectorNumElements()) &&
02018            "getelementptr index type missmatch");
02019     ArgVec.push_back(cast<Constant>(Idxs[i]));
02020   }
02021   const ConstantExprKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
02022                                 InBounds ? GEPOperator::IsInBounds : 0);
02023 
02024   LLVMContextImpl *pImpl = C->getContext().pImpl;
02025   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
02026 }
02027 
02028 Constant *ConstantExpr::getICmp(unsigned short pred, Constant *LHS,
02029                                 Constant *RHS, bool OnlyIfReduced) {
02030   assert(LHS->getType() == RHS->getType());
02031   assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE && 
02032          pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
02033 
02034   if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
02035     return FC;          // Fold a few common cases...
02036 
02037   if (OnlyIfReduced)
02038     return nullptr;
02039 
02040   // Look up the constant in the table first to ensure uniqueness
02041   Constant *ArgVec[] = { LHS, RHS };
02042   // Get the key type with both the opcode and predicate
02043   const ConstantExprKeyType Key(Instruction::ICmp, ArgVec, pred);
02044 
02045   Type *ResultTy = Type::getInt1Ty(LHS->getContext());
02046   if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
02047     ResultTy = VectorType::get(ResultTy, VT->getNumElements());
02048 
02049   LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
02050   return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
02051 }
02052 
02053 Constant *ConstantExpr::getFCmp(unsigned short pred, Constant *LHS,
02054                                 Constant *RHS, bool OnlyIfReduced) {
02055   assert(LHS->getType() == RHS->getType());
02056   assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
02057 
02058   if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
02059     return FC;          // Fold a few common cases...
02060 
02061   if (OnlyIfReduced)
02062     return nullptr;
02063 
02064   // Look up the constant in the table first to ensure uniqueness
02065   Constant *ArgVec[] = { LHS, RHS };
02066   // Get the key type with both the opcode and predicate
02067   const ConstantExprKeyType Key(Instruction::FCmp, ArgVec, pred);
02068 
02069   Type *ResultTy = Type::getInt1Ty(LHS->getContext());
02070   if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
02071     ResultTy = VectorType::get(ResultTy, VT->getNumElements());
02072 
02073   LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
02074   return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
02075 }
02076 
02077 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx,
02078                                           Type *OnlyIfReducedTy) {
02079   assert(Val->getType()->isVectorTy() &&
02080          "Tried to create extractelement operation on non-vector type!");
02081   assert(Idx->getType()->isIntegerTy() &&
02082          "Extractelement index must be an integer type!");
02083 
02084   if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
02085     return FC;          // Fold a few common cases.
02086 
02087   Type *ReqTy = Val->getType()->getVectorElementType();
02088   if (OnlyIfReducedTy == ReqTy)
02089     return nullptr;
02090 
02091   // Look up the constant in the table first to ensure uniqueness
02092   Constant *ArgVec[] = { Val, Idx };
02093   const ConstantExprKeyType Key(Instruction::ExtractElement, ArgVec);
02094 
02095   LLVMContextImpl *pImpl = Val->getContext().pImpl;
02096   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
02097 }
02098 
02099 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
02100                                          Constant *Idx, Type *OnlyIfReducedTy) {
02101   assert(Val->getType()->isVectorTy() &&
02102          "Tried to create insertelement operation on non-vector type!");
02103   assert(Elt->getType() == Val->getType()->getVectorElementType() &&
02104          "Insertelement types must match!");
02105   assert(Idx->getType()->isIntegerTy() &&
02106          "Insertelement index must be i32 type!");
02107 
02108   if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
02109     return FC;          // Fold a few common cases.
02110 
02111   if (OnlyIfReducedTy == Val->getType())
02112     return nullptr;
02113 
02114   // Look up the constant in the table first to ensure uniqueness
02115   Constant *ArgVec[] = { Val, Elt, Idx };
02116   const ConstantExprKeyType Key(Instruction::InsertElement, ArgVec);
02117 
02118   LLVMContextImpl *pImpl = Val->getContext().pImpl;
02119   return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
02120 }
02121 
02122 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
02123                                          Constant *Mask, Type *OnlyIfReducedTy) {
02124   assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
02125          "Invalid shuffle vector constant expr operands!");
02126 
02127   if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
02128     return FC;          // Fold a few common cases.
02129 
02130   unsigned NElts = Mask->getType()->getVectorNumElements();
02131   Type *EltTy = V1->getType()->getVectorElementType();
02132   Type *ShufTy = VectorType::get(EltTy, NElts);
02133 
02134   if (OnlyIfReducedTy == ShufTy)
02135     return nullptr;
02136 
02137   // Look up the constant in the table first to ensure uniqueness
02138   Constant *ArgVec[] = { V1, V2, Mask };
02139   const ConstantExprKeyType Key(Instruction::ShuffleVector, ArgVec);
02140 
02141   LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
02142   return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
02143 }
02144 
02145 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
02146                                        ArrayRef<unsigned> Idxs,
02147                                        Type *OnlyIfReducedTy) {
02148   assert(Agg->getType()->isFirstClassType() &&
02149          "Non-first-class type for constant insertvalue expression");
02150 
02151   assert(ExtractValueInst::getIndexedType(Agg->getType(),
02152                                           Idxs) == Val->getType() &&
02153          "insertvalue indices invalid!");
02154   Type *ReqTy = Val->getType();
02155 
02156   if (Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs))
02157     return FC;
02158 
02159   if (OnlyIfReducedTy == ReqTy)
02160     return nullptr;
02161 
02162   Constant *ArgVec[] = { Agg, Val };
02163   const ConstantExprKeyType Key(Instruction::InsertValue, ArgVec, 0, 0, Idxs);
02164 
02165   LLVMContextImpl *pImpl = Agg->getContext().pImpl;
02166   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
02167 }
02168 
02169 Constant *ConstantExpr::getExtractValue(Constant *Agg, ArrayRef<unsigned> Idxs,
02170                                         Type *OnlyIfReducedTy) {
02171   assert(Agg->getType()->isFirstClassType() &&
02172          "Tried to create extractelement operation on non-first-class type!");
02173 
02174   Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs);
02175   (void)ReqTy;
02176   assert(ReqTy && "extractvalue indices invalid!");
02177 
02178   assert(Agg->getType()->isFirstClassType() &&
02179          "Non-first-class type for constant extractvalue expression");
02180   if (Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs))
02181     return FC;
02182 
02183   if (OnlyIfReducedTy == ReqTy)
02184     return nullptr;
02185 
02186   Constant *ArgVec[] = { Agg };
02187   const ConstantExprKeyType Key(Instruction::ExtractValue, ArgVec, 0, 0, Idxs);
02188 
02189   LLVMContextImpl *pImpl = Agg->getContext().pImpl;
02190   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
02191 }
02192 
02193 Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
02194   assert(C->getType()->isIntOrIntVectorTy() &&
02195          "Cannot NEG a nonintegral value!");
02196   return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
02197                 C, HasNUW, HasNSW);
02198 }
02199 
02200 Constant *ConstantExpr::getFNeg(Constant *C) {
02201   assert(C->getType()->isFPOrFPVectorTy() &&
02202          "Cannot FNEG a non-floating-point value!");
02203   return getFSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
02204 }
02205 
02206 Constant *ConstantExpr::getNot(Constant *C) {
02207   assert(C->getType()->isIntOrIntVectorTy() &&
02208          "Cannot NOT a nonintegral value!");
02209   return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
02210 }
02211 
02212 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
02213                                bool HasNUW, bool HasNSW) {
02214   unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
02215                    (HasNSW ? OverflowingBinaryOperator::NoSignedWrap   : 0);
02216   return get(Instruction::Add, C1, C2, Flags);
02217 }
02218 
02219 Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
02220   return get(Instruction::FAdd, C1, C2);
02221 }
02222 
02223 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
02224                                bool HasNUW, bool HasNSW) {
02225   unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
02226                    (HasNSW ? OverflowingBinaryOperator::NoSignedWrap   : 0);
02227   return get(Instruction::Sub, C1, C2, Flags);
02228 }
02229 
02230 Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
02231   return get(Instruction::FSub, C1, C2);
02232 }
02233 
02234 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
02235                                bool HasNUW, bool HasNSW) {
02236   unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
02237                    (HasNSW ? OverflowingBinaryOperator::NoSignedWrap   : 0);
02238   return get(Instruction::Mul, C1, C2, Flags);
02239 }
02240 
02241 Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
02242   return get(Instruction::FMul, C1, C2);
02243 }
02244 
02245 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
02246   return get(Instruction::UDiv, C1, C2,
02247              isExact ? PossiblyExactOperator::IsExact : 0);
02248 }
02249 
02250 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
02251   return get(Instruction::SDiv, C1, C2,
02252              isExact ? PossiblyExactOperator::IsExact : 0);
02253 }
02254 
02255 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
02256   return get(Instruction::FDiv, C1, C2);
02257 }
02258 
02259 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
02260   return get(Instruction::URem, C1, C2);
02261 }
02262 
02263 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
02264   return get(Instruction::SRem, C1, C2);
02265 }
02266 
02267 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
02268   return get(Instruction::FRem, C1, C2);
02269 }
02270 
02271 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
02272   return get(Instruction::And, C1, C2);
02273 }
02274 
02275 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
02276   return get(Instruction::Or, C1, C2);
02277 }
02278 
02279 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
02280   return get(Instruction::Xor, C1, C2);
02281 }
02282 
02283 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
02284                                bool HasNUW, bool HasNSW) {
02285   unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
02286                    (HasNSW ? OverflowingBinaryOperator::NoSignedWrap   : 0);
02287   return get(Instruction::Shl, C1, C2, Flags);
02288 }
02289 
02290 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
02291   return get(Instruction::LShr, C1, C2,
02292              isExact ? PossiblyExactOperator::IsExact : 0);
02293 }
02294 
02295 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
02296   return get(Instruction::AShr, C1, C2,
02297              isExact ? PossiblyExactOperator::IsExact : 0);
02298 }
02299 
02300 /// getBinOpIdentity - Return the identity for the given binary operation,
02301 /// i.e. a constant C such that X op C = X and C op X = X for every X.  It
02302 /// returns null if the operator doesn't have an identity.
02303 Constant *ConstantExpr::getBinOpIdentity(unsigned Opcode, Type *Ty) {
02304   switch (Opcode) {
02305   default:
02306     // Doesn't have an identity.
02307     return nullptr;
02308 
02309   case Instruction::Add:
02310   case Instruction::Or:
02311   case Instruction::Xor:
02312     return Constant::getNullValue(Ty);
02313 
02314   case Instruction::Mul:
02315     return ConstantInt::get(Ty, 1);
02316 
02317   case Instruction::And:
02318     return Constant::getAllOnesValue(Ty);
02319   }
02320 }
02321 
02322 /// getBinOpAbsorber - Return the absorbing element for the given binary
02323 /// operation, i.e. a constant C such that X op C = C and C op X = C for
02324 /// every X.  For example, this returns zero for integer multiplication.
02325 /// It returns null if the operator doesn't have an absorbing element.
02326 Constant *ConstantExpr::getBinOpAbsorber(unsigned Opcode, Type *Ty) {
02327   switch (Opcode) {
02328   default:
02329     // Doesn't have an absorber.
02330     return nullptr;
02331 
02332   case Instruction::Or:
02333     return Constant::getAllOnesValue(Ty);
02334 
02335   case Instruction::And:
02336   case Instruction::Mul:
02337     return Constant::getNullValue(Ty);
02338   }
02339 }
02340 
02341 // destroyConstant - Remove the constant from the constant table...
02342 //
02343 void ConstantExpr::destroyConstant() {
02344   getType()->getContext().pImpl->ExprConstants.remove(this);
02345   destroyConstantImpl();
02346 }
02347 
02348 const char *ConstantExpr::getOpcodeName() const {
02349   return Instruction::getOpcodeName(getOpcode());
02350 }
02351 
02352 
02353 
02354 GetElementPtrConstantExpr::
02355 GetElementPtrConstantExpr(Constant *C, ArrayRef<Constant*> IdxList,
02356                           Type *DestTy)
02357   : ConstantExpr(DestTy, Instruction::GetElementPtr,
02358                  OperandTraits<GetElementPtrConstantExpr>::op_end(this)
02359                  - (IdxList.size()+1), IdxList.size()+1) {
02360   OperandList[0] = C;
02361   for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
02362     OperandList[i+1] = IdxList[i];
02363 }
02364 
02365 //===----------------------------------------------------------------------===//
02366 //                       ConstantData* implementations
02367 
02368 void ConstantDataArray::anchor() {}
02369 void ConstantDataVector::anchor() {}
02370 
02371 /// getElementType - Return the element type of the array/vector.
02372 Type *ConstantDataSequential::getElementType() const {
02373   return getType()->getElementType();
02374 }
02375 
02376 StringRef ConstantDataSequential::getRawDataValues() const {
02377   return StringRef(DataElements, getNumElements()*getElementByteSize());
02378 }
02379 
02380 /// isElementTypeCompatible - Return true if a ConstantDataSequential can be
02381 /// formed with a vector or array of the specified element type.
02382 /// ConstantDataArray only works with normal float and int types that are
02383 /// stored densely in memory, not with things like i42 or x86_f80.
02384 bool ConstantDataSequential::isElementTypeCompatible(const Type *Ty) {
02385   if (Ty->isFloatTy() || Ty->isDoubleTy()) return true;
02386   if (const IntegerType *IT = dyn_cast<IntegerType>(Ty)) {
02387     switch (IT->getBitWidth()) {
02388     case 8:
02389     case 16:
02390     case 32:
02391     case 64:
02392       return true;
02393     default: break;
02394     }
02395   }
02396   return false;
02397 }
02398 
02399 /// getNumElements - Return the number of elements in the array or vector.
02400 unsigned ConstantDataSequential::getNumElements() const {
02401   if (ArrayType *AT = dyn_cast<ArrayType>(getType()))
02402     return AT->getNumElements();
02403   return getType()->getVectorNumElements();
02404 }
02405 
02406 
02407 /// getElementByteSize - Return the size in bytes of the elements in the data.
02408 uint64_t ConstantDataSequential::getElementByteSize() const {
02409   return getElementType()->getPrimitiveSizeInBits()/8;
02410 }
02411 
02412 /// getElementPointer - Return the start of the specified element.
02413 const char *ConstantDataSequential::getElementPointer(unsigned Elt) const {
02414   assert(Elt < getNumElements() && "Invalid Elt");
02415   return DataElements+Elt*getElementByteSize();
02416 }
02417 
02418 
02419 /// isAllZeros - return true if the array is empty or all zeros.
02420 static bool isAllZeros(StringRef Arr) {
02421   for (StringRef::iterator I = Arr.begin(), E = Arr.end(); I != E; ++I)
02422     if (*I != 0)
02423       return false;
02424   return true;
02425 }
02426 
02427 /// getImpl - This is the underlying implementation of all of the
02428 /// ConstantDataSequential::get methods.  They all thunk down to here, providing
02429 /// the correct element type.  We take the bytes in as a StringRef because
02430 /// we *want* an underlying "char*" to avoid TBAA type punning violations.
02431 Constant *ConstantDataSequential::getImpl(StringRef Elements, Type *Ty) {
02432   assert(isElementTypeCompatible(Ty->getSequentialElementType()));
02433   // If the elements are all zero or there are no elements, return a CAZ, which
02434   // is more dense and canonical.
02435   if (isAllZeros(Elements))
02436     return ConstantAggregateZero::get(Ty);
02437 
02438   // Do a lookup to see if we have already formed one of these.
02439   StringMap<ConstantDataSequential*>::MapEntryTy &Slot =
02440     Ty->getContext().pImpl->CDSConstants.GetOrCreateValue(Elements);
02441 
02442   // The bucket can point to a linked list of different CDS's that have the same
02443   // body but different types.  For example, 0,0,0,1 could be a 4 element array
02444   // of i8, or a 1-element array of i32.  They'll both end up in the same
02445   /// StringMap bucket, linked up by their Next pointers.  Walk the list.
02446   ConstantDataSequential **Entry = &Slot.getValue();
02447   for (ConstantDataSequential *Node = *Entry; Node;
02448        Entry = &Node->Next, Node = *Entry)
02449     if (Node->getType() == Ty)
02450       return Node;
02451 
02452   // Okay, we didn't get a hit.  Create a node of the right class, link it in,
02453   // and return it.
02454   if (isa<ArrayType>(Ty))
02455     return *Entry = new ConstantDataArray(Ty, Slot.getKeyData());
02456 
02457   assert(isa<VectorType>(Ty));
02458   return *Entry = new ConstantDataVector(Ty, Slot.getKeyData());
02459 }
02460 
02461 void ConstantDataSequential::destroyConstant() {
02462   // Remove the constant from the StringMap.
02463   StringMap<ConstantDataSequential*> &CDSConstants = 
02464     getType()->getContext().pImpl->CDSConstants;
02465 
02466   StringMap<ConstantDataSequential*>::iterator Slot =
02467     CDSConstants.find(getRawDataValues());
02468 
02469   assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
02470 
02471   ConstantDataSequential **Entry = &Slot->getValue();
02472 
02473   // Remove the entry from the hash table.
02474   if (!(*Entry)->Next) {
02475     // If there is only one value in the bucket (common case) it must be this
02476     // entry, and removing the entry should remove the bucket completely.
02477     assert((*Entry) == this && "Hash mismatch in ConstantDataSequential");
02478     getContext().pImpl->CDSConstants.erase(Slot);
02479   } else {
02480     // Otherwise, there are multiple entries linked off the bucket, unlink the 
02481     // node we care about but keep the bucket around.
02482     for (ConstantDataSequential *Node = *Entry; ;
02483          Entry = &Node->Next, Node = *Entry) {
02484       assert(Node && "Didn't find entry in its uniquing hash table!");
02485       // If we found our entry, unlink it from the list and we're done.
02486       if (Node == this) {
02487         *Entry = Node->Next;
02488         break;
02489       }
02490     }
02491   }
02492 
02493   // If we were part of a list, make sure that we don't delete the list that is
02494   // still owned by the uniquing map.
02495   Next = nullptr;
02496 
02497   // Finally, actually delete it.
02498   destroyConstantImpl();
02499 }
02500 
02501 /// get() constructors - Return a constant with array type with an element
02502 /// count and element type matching the ArrayRef passed in.  Note that this
02503 /// can return a ConstantAggregateZero object.
02504 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint8_t> Elts) {
02505   Type *Ty = ArrayType::get(Type::getInt8Ty(Context), Elts.size());
02506   const char *Data = reinterpret_cast<const char *>(Elts.data());
02507   return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*1), Ty);
02508 }
02509 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
02510   Type *Ty = ArrayType::get(Type::getInt16Ty(Context), Elts.size());
02511   const char *Data = reinterpret_cast<const char *>(Elts.data());
02512   return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*2), Ty);
02513 }
02514 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
02515   Type *Ty = ArrayType::get(Type::getInt32Ty(Context), Elts.size());
02516   const char *Data = reinterpret_cast<const char *>(Elts.data());
02517   return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
02518 }
02519 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
02520   Type *Ty = ArrayType::get(Type::getInt64Ty(Context), Elts.size());
02521   const char *Data = reinterpret_cast<const char *>(Elts.data());
02522   return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
02523 }
02524 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<float> Elts) {
02525   Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
02526   const char *Data = reinterpret_cast<const char *>(Elts.data());
02527   return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
02528 }
02529 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<double> Elts) {
02530   Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
02531   const char *Data = reinterpret_cast<const char *>(Elts.data());
02532   return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
02533 }
02534 
02535 /// getString - This method constructs a CDS and initializes it with a text
02536 /// string. The default behavior (AddNull==true) causes a null terminator to
02537 /// be placed at the end of the array (increasing the length of the string by
02538 /// one more than the StringRef would normally indicate.  Pass AddNull=false
02539 /// to disable this behavior.
02540 Constant *ConstantDataArray::getString(LLVMContext &Context,
02541                                        StringRef Str, bool AddNull) {
02542   if (!AddNull) {
02543     const uint8_t *Data = reinterpret_cast<const uint8_t *>(Str.data());
02544     return get(Context, makeArrayRef(const_cast<uint8_t *>(Data),
02545                Str.size()));
02546   }
02547 
02548   SmallVector<uint8_t, 64> ElementVals;
02549   ElementVals.append(Str.begin(), Str.end());
02550   ElementVals.push_back(0);
02551   return get(Context, ElementVals);
02552 }
02553 
02554 /// get() constructors - Return a constant with vector type with an element
02555 /// count and element type matching the ArrayRef passed in.  Note that this
02556 /// can return a ConstantAggregateZero object.
02557 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> Elts){
02558   Type *Ty = VectorType::get(Type::getInt8Ty(Context), Elts.size());
02559   const char *Data = reinterpret_cast<const char *>(Elts.data());
02560   return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*1), Ty);
02561 }
02562 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
02563   Type *Ty = VectorType::get(Type::getInt16Ty(Context), Elts.size());
02564   const char *Data = reinterpret_cast<const char *>(Elts.data());
02565   return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*2), Ty);
02566 }
02567 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
02568   Type *Ty = VectorType::get(Type::getInt32Ty(Context), Elts.size());
02569   const char *Data = reinterpret_cast<const char *>(Elts.data());
02570   return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
02571 }
02572 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
02573   Type *Ty = VectorType::get(Type::getInt64Ty(Context), Elts.size());
02574   const char *Data = reinterpret_cast<const char *>(Elts.data());
02575   return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
02576 }
02577 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> Elts) {
02578   Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
02579   const char *Data = reinterpret_cast<const char *>(Elts.data());
02580   return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
02581 }
02582 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<double> Elts) {
02583   Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
02584   const char *Data = reinterpret_cast<const char *>(Elts.data());
02585   return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
02586 }
02587 
02588 Constant *ConstantDataVector::getSplat(unsigned NumElts, Constant *V) {
02589   assert(isElementTypeCompatible(V->getType()) &&
02590          "Element type not compatible with ConstantData");
02591   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
02592     if (CI->getType()->isIntegerTy(8)) {
02593       SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
02594       return get(V->getContext(), Elts);
02595     }
02596     if (CI->getType()->isIntegerTy(16)) {
02597       SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
02598       return get(V->getContext(), Elts);
02599     }
02600     if (CI->getType()->isIntegerTy(32)) {
02601       SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
02602       return get(V->getContext(), Elts);
02603     }
02604     assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
02605     SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
02606     return get(V->getContext(), Elts);
02607   }
02608 
02609   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
02610     if (CFP->getType()->isFloatTy()) {
02611       SmallVector<float, 16> Elts(NumElts, CFP->getValueAPF().convertToFloat());
02612       return get(V->getContext(), Elts);
02613     }
02614     if (CFP->getType()->isDoubleTy()) {
02615       SmallVector<double, 16> Elts(NumElts,
02616                                    CFP->getValueAPF().convertToDouble());
02617       return get(V->getContext(), Elts);
02618     }
02619   }
02620   return ConstantVector::getSplat(NumElts, V);
02621 }
02622 
02623 
02624 /// getElementAsInteger - If this is a sequential container of integers (of
02625 /// any size), return the specified element in the low bits of a uint64_t.
02626 uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const {
02627   assert(isa<IntegerType>(getElementType()) &&
02628          "Accessor can only be used when element is an integer");
02629   const char *EltPtr = getElementPointer(Elt);
02630 
02631   // The data is stored in host byte order, make sure to cast back to the right
02632   // type to load with the right endianness.
02633   switch (getElementType()->getIntegerBitWidth()) {
02634   default: llvm_unreachable("Invalid bitwidth for CDS");
02635   case 8:
02636     return *const_cast<uint8_t *>(reinterpret_cast<const uint8_t *>(EltPtr));
02637   case 16:
02638     return *const_cast<uint16_t *>(reinterpret_cast<const uint16_t *>(EltPtr));
02639   case 32:
02640     return *const_cast<uint32_t *>(reinterpret_cast<const uint32_t *>(EltPtr));
02641   case 64:
02642     return *const_cast<uint64_t *>(reinterpret_cast<const uint64_t *>(EltPtr));
02643   }
02644 }
02645 
02646 /// getElementAsAPFloat - If this is a sequential container of floating point
02647 /// type, return the specified element as an APFloat.
02648 APFloat ConstantDataSequential::getElementAsAPFloat(unsigned Elt) const {
02649   const char *EltPtr = getElementPointer(Elt);
02650 
02651   switch (getElementType()->getTypeID()) {
02652   default:
02653     llvm_unreachable("Accessor can only be used when element is float/double!");
02654   case Type::FloatTyID: {
02655       const float *FloatPrt = reinterpret_cast<const float *>(EltPtr);
02656       return APFloat(*const_cast<float *>(FloatPrt));
02657     }
02658   case Type::DoubleTyID: {
02659       const double *DoublePtr = reinterpret_cast<const double *>(EltPtr);
02660       return APFloat(*const_cast<double *>(DoublePtr));
02661     }
02662   }
02663 }
02664 
02665 /// getElementAsFloat - If this is an sequential container of floats, return
02666 /// the specified element as a float.
02667 float ConstantDataSequential::getElementAsFloat(unsigned Elt) const {
02668   assert(getElementType()->isFloatTy() &&
02669          "Accessor can only be used when element is a 'float'");
02670   const float *EltPtr = reinterpret_cast<const float *>(getElementPointer(Elt));
02671   return *const_cast<float *>(EltPtr);
02672 }
02673 
02674 /// getElementAsDouble - If this is an sequential container of doubles, return
02675 /// the specified element as a float.
02676 double ConstantDataSequential::getElementAsDouble(unsigned Elt) const {
02677   assert(getElementType()->isDoubleTy() &&
02678          "Accessor can only be used when element is a 'float'");
02679   const double *EltPtr =
02680       reinterpret_cast<const double *>(getElementPointer(Elt));
02681   return *const_cast<double *>(EltPtr);
02682 }
02683 
02684 /// getElementAsConstant - Return a Constant for a specified index's element.
02685 /// Note that this has to compute a new constant to return, so it isn't as
02686 /// efficient as getElementAsInteger/Float/Double.
02687 Constant *ConstantDataSequential::getElementAsConstant(unsigned Elt) const {
02688   if (getElementType()->isFloatTy() || getElementType()->isDoubleTy())
02689     return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
02690 
02691   return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
02692 }
02693 
02694 /// isString - This method returns true if this is an array of i8.
02695 bool ConstantDataSequential::isString() const {
02696   return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(8);
02697 }
02698 
02699 /// isCString - This method returns true if the array "isString", ends with a
02700 /// nul byte, and does not contains any other nul bytes.
02701 bool ConstantDataSequential::isCString() const {
02702   if (!isString())
02703     return false;
02704 
02705   StringRef Str = getAsString();
02706 
02707   // The last value must be nul.
02708   if (Str.back() != 0) return false;
02709 
02710   // Other elements must be non-nul.
02711   return Str.drop_back().find(0) == StringRef::npos;
02712 }
02713 
02714 /// getSplatValue - If this is a splat constant, meaning that all of the
02715 /// elements have the same value, return that value. Otherwise return NULL.
02716 Constant *ConstantDataVector::getSplatValue() const {
02717   const char *Base = getRawDataValues().data();
02718 
02719   // Compare elements 1+ to the 0'th element.
02720   unsigned EltSize = getElementByteSize();
02721   for (unsigned i = 1, e = getNumElements(); i != e; ++i)
02722     if (memcmp(Base, Base+i*EltSize, EltSize))
02723       return nullptr;
02724 
02725   // If they're all the same, return the 0th one as a representative.
02726   return getElementAsConstant(0);
02727 }
02728 
02729 //===----------------------------------------------------------------------===//
02730 //                replaceUsesOfWithOnConstant implementations
02731 
02732 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
02733 /// 'From' to be uses of 'To'.  This must update the uniquing data structures
02734 /// etc.
02735 ///
02736 /// Note that we intentionally replace all uses of From with To here.  Consider
02737 /// a large array that uses 'From' 1000 times.  By handling this case all here,
02738 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
02739 /// single invocation handles all 1000 uses.  Handling them one at a time would
02740 /// work, but would be really slow because it would have to unique each updated
02741 /// array instance.
02742 ///
02743 void Constant::replaceUsesOfWithOnConstantImpl(Constant *Replacement) {
02744   // I do need to replace this with an existing value.
02745   assert(Replacement != this && "I didn't contain From!");
02746 
02747   // Everyone using this now uses the replacement.
02748   replaceAllUsesWith(Replacement);
02749 
02750   // Delete the old constant!
02751   destroyConstant();
02752 }
02753 
02754 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
02755                                                 Use *U) {
02756   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
02757   Constant *ToC = cast<Constant>(To);
02758 
02759   SmallVector<Constant*, 8> Values;
02760   Values.reserve(getNumOperands());  // Build replacement array.
02761 
02762   // Fill values with the modified operands of the constant array.  Also,
02763   // compute whether this turns into an all-zeros array.
02764   unsigned NumUpdated = 0;
02765 
02766   // Keep track of whether all the values in the array are "ToC".
02767   bool AllSame = true;
02768   for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
02769     Constant *Val = cast<Constant>(O->get());
02770     if (Val == From) {
02771       Val = ToC;
02772       ++NumUpdated;
02773     }
02774     Values.push_back(Val);
02775     AllSame &= Val == ToC;
02776   }
02777 
02778   if (AllSame && ToC->isNullValue()) {
02779     replaceUsesOfWithOnConstantImpl(ConstantAggregateZero::get(getType()));
02780     return;
02781   }
02782   if (AllSame && isa<UndefValue>(ToC)) {
02783     replaceUsesOfWithOnConstantImpl(UndefValue::get(getType()));
02784     return;
02785   }
02786 
02787   // Check for any other type of constant-folding.
02788   if (Constant *C = getImpl(getType(), Values)) {
02789     replaceUsesOfWithOnConstantImpl(C);
02790     return;
02791   }
02792 
02793   // Update to the new value.
02794   if (Constant *C = getContext().pImpl->ArrayConstants.replaceOperandsInPlace(
02795           Values, this, From, ToC, NumUpdated, U - OperandList))
02796     replaceUsesOfWithOnConstantImpl(C);
02797 }
02798 
02799 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
02800                                                  Use *U) {
02801   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
02802   Constant *ToC = cast<Constant>(To);
02803 
02804   unsigned OperandToUpdate = U-OperandList;
02805   assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
02806 
02807   SmallVector<Constant*, 8> Values;
02808   Values.reserve(getNumOperands());  // Build replacement struct.
02809 
02810   // Fill values with the modified operands of the constant struct.  Also,
02811   // compute whether this turns into an all-zeros struct.
02812   bool isAllZeros = false;
02813   bool isAllUndef = false;
02814   if (ToC->isNullValue()) {
02815     isAllZeros = true;
02816     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
02817       Constant *Val = cast<Constant>(O->get());
02818       Values.push_back(Val);
02819       if (isAllZeros) isAllZeros = Val->isNullValue();
02820     }
02821   } else if (isa<UndefValue>(ToC)) {
02822     isAllUndef = true;
02823     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
02824       Constant *Val = cast<Constant>(O->get());
02825       Values.push_back(Val);
02826       if (isAllUndef) isAllUndef = isa<UndefValue>(Val);
02827     }
02828   } else {
02829     for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
02830       Values.push_back(cast<Constant>(O->get()));
02831   }
02832   Values[OperandToUpdate] = ToC;
02833 
02834   if (isAllZeros) {
02835     replaceUsesOfWithOnConstantImpl(ConstantAggregateZero::get(getType()));
02836     return;
02837   }
02838   if (isAllUndef) {
02839     replaceUsesOfWithOnConstantImpl(UndefValue::get(getType()));
02840     return;
02841   }
02842 
02843   // Update to the new value.
02844   if (Constant *C = getContext().pImpl->StructConstants.replaceOperandsInPlace(
02845           Values, this, From, ToC))
02846     replaceUsesOfWithOnConstantImpl(C);
02847 }
02848 
02849 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
02850                                                  Use *U) {
02851   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
02852   Constant *ToC = cast<Constant>(To);
02853 
02854   SmallVector<Constant*, 8> Values;
02855   Values.reserve(getNumOperands());  // Build replacement array...
02856   unsigned NumUpdated = 0;
02857   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
02858     Constant *Val = getOperand(i);
02859     if (Val == From) {
02860       ++NumUpdated;
02861       Val = ToC;
02862     }
02863     Values.push_back(Val);
02864   }
02865 
02866   if (Constant *C = getImpl(Values)) {
02867     replaceUsesOfWithOnConstantImpl(C);
02868     return;
02869   }
02870 
02871   // Update to the new value.
02872   if (Constant *C = getContext().pImpl->VectorConstants.replaceOperandsInPlace(
02873           Values, this, From, ToC, NumUpdated, U - OperandList))
02874     replaceUsesOfWithOnConstantImpl(C);
02875 }
02876 
02877 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
02878                                                Use *U) {
02879   assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
02880   Constant *To = cast<Constant>(ToV);
02881 
02882   SmallVector<Constant*, 8> NewOps;
02883   unsigned NumUpdated = 0;
02884   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
02885     Constant *Op = getOperand(i);
02886     if (Op == From) {
02887       ++NumUpdated;
02888       Op = To;
02889     }
02890     NewOps.push_back(Op);
02891   }
02892   assert(NumUpdated && "I didn't contain From!");
02893 
02894   if (Constant *C = getWithOperands(NewOps, getType(), true)) {
02895     replaceUsesOfWithOnConstantImpl(C);
02896     return;
02897   }
02898 
02899   // Update to the new value.
02900   if (Constant *C = getContext().pImpl->ExprConstants.replaceOperandsInPlace(
02901           NewOps, this, From, To, NumUpdated, U - OperandList))
02902     replaceUsesOfWithOnConstantImpl(C);
02903 }
02904 
02905 Instruction *ConstantExpr::getAsInstruction() {
02906   SmallVector<Value*,4> ValueOperands;
02907   for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
02908     ValueOperands.push_back(cast<Value>(I));
02909 
02910   ArrayRef<Value*> Ops(ValueOperands);
02911 
02912   switch (getOpcode()) {
02913   case Instruction::Trunc:
02914   case Instruction::ZExt:
02915   case Instruction::SExt:
02916   case Instruction::FPTrunc:
02917   case Instruction::FPExt:
02918   case Instruction::UIToFP:
02919   case Instruction::SIToFP:
02920   case Instruction::FPToUI:
02921   case Instruction::FPToSI:
02922   case Instruction::PtrToInt:
02923   case Instruction::IntToPtr:
02924   case Instruction::BitCast:
02925   case Instruction::AddrSpaceCast:
02926     return CastInst::Create((Instruction::CastOps)getOpcode(),
02927                             Ops[0], getType());
02928   case Instruction::Select:
02929     return SelectInst::Create(Ops[0], Ops[1], Ops[2]);
02930   case Instruction::InsertElement:
02931     return InsertElementInst::Create(Ops[0], Ops[1], Ops[2]);
02932   case Instruction::ExtractElement:
02933     return ExtractElementInst::Create(Ops[0], Ops[1]);
02934   case Instruction::InsertValue:
02935     return InsertValueInst::Create(Ops[0], Ops[1], getIndices());
02936   case Instruction::ExtractValue:
02937     return ExtractValueInst::Create(Ops[0], getIndices());
02938   case Instruction::ShuffleVector:
02939     return new ShuffleVectorInst(Ops[0], Ops[1], Ops[2]);
02940 
02941   case Instruction::GetElementPtr:
02942     if (cast<GEPOperator>(this)->isInBounds())
02943       return GetElementPtrInst::CreateInBounds(Ops[0], Ops.slice(1));
02944     else
02945       return GetElementPtrInst::Create(Ops[0], Ops.slice(1));
02946 
02947   case Instruction::ICmp:
02948   case Instruction::FCmp:
02949     return CmpInst::Create((Instruction::OtherOps)getOpcode(),
02950                            getPredicate(), Ops[0], Ops[1]);
02951 
02952   default:
02953     assert(getNumOperands() == 2 && "Must be binary operator?");
02954     BinaryOperator *BO =
02955       BinaryOperator::Create((Instruction::BinaryOps)getOpcode(),
02956                              Ops[0], Ops[1]);
02957     if (isa<OverflowingBinaryOperator>(BO)) {
02958       BO->setHasNoUnsignedWrap(SubclassOptionalData &
02959                                OverflowingBinaryOperator::NoUnsignedWrap);
02960       BO->setHasNoSignedWrap(SubclassOptionalData &
02961                              OverflowingBinaryOperator::NoSignedWrap);
02962     }
02963     if (isa<PossiblyExactOperator>(BO))
02964       BO->setIsExact(SubclassOptionalData & PossiblyExactOperator::IsExact);
02965     return BO;
02966   }
02967 }