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