LLVM API Documentation

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