Path: blob/main/contrib/llvm-project/llvm/lib/IR/Constants.cpp
35234 views
//===-- Constants.cpp - Implement Constant nodes --------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements the Constant* classes.9//10//===----------------------------------------------------------------------===//1112#include "llvm/IR/Constants.h"13#include "LLVMContextImpl.h"14#include "llvm/ADT/STLExtras.h"15#include "llvm/ADT/SmallVector.h"16#include "llvm/ADT/StringMap.h"17#include "llvm/IR/BasicBlock.h"18#include "llvm/IR/ConstantFold.h"19#include "llvm/IR/DerivedTypes.h"20#include "llvm/IR/Function.h"21#include "llvm/IR/GetElementPtrTypeIterator.h"22#include "llvm/IR/GlobalAlias.h"23#include "llvm/IR/GlobalIFunc.h"24#include "llvm/IR/GlobalValue.h"25#include "llvm/IR/GlobalVariable.h"26#include "llvm/IR/Instructions.h"27#include "llvm/IR/Operator.h"28#include "llvm/IR/PatternMatch.h"29#include "llvm/Support/ErrorHandling.h"30#include "llvm/Support/MathExtras.h"31#include "llvm/Support/raw_ostream.h"32#include <algorithm>3334using namespace llvm;35using namespace PatternMatch;3637// As set of temporary options to help migrate how splats are represented.38static cl::opt<bool> UseConstantIntForFixedLengthSplat(39"use-constant-int-for-fixed-length-splat", cl::init(false), cl::Hidden,40cl::desc("Use ConstantInt's native fixed-length vector splat support."));41static cl::opt<bool> UseConstantFPForFixedLengthSplat(42"use-constant-fp-for-fixed-length-splat", cl::init(false), cl::Hidden,43cl::desc("Use ConstantFP's native fixed-length vector splat support."));44static cl::opt<bool> UseConstantIntForScalableSplat(45"use-constant-int-for-scalable-splat", cl::init(false), cl::Hidden,46cl::desc("Use ConstantInt's native scalable vector splat support."));47static cl::opt<bool> UseConstantFPForScalableSplat(48"use-constant-fp-for-scalable-splat", cl::init(false), cl::Hidden,49cl::desc("Use ConstantFP's native scalable vector splat support."));5051//===----------------------------------------------------------------------===//52// Constant Class53//===----------------------------------------------------------------------===//5455bool Constant::isNegativeZeroValue() const {56// Floating point values have an explicit -0.0 value.57if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))58return CFP->isZero() && CFP->isNegative();5960// Equivalent for a vector of -0.0's.61if (getType()->isVectorTy())62if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))63return SplatCFP->isNegativeZeroValue();6465// We've already handled true FP case; any other FP vectors can't represent -0.0.66if (getType()->isFPOrFPVectorTy())67return false;6869// Otherwise, just use +0.0.70return isNullValue();71}7273// Return true iff this constant is positive zero (floating point), negative74// zero (floating point), or a null value.75bool Constant::isZeroValue() const {76// Floating point values have an explicit -0.0 value.77if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))78return CFP->isZero();7980// Check for constant splat vectors of 1 values.81if (getType()->isVectorTy())82if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))83return SplatCFP->isZero();8485// Otherwise, just use +0.0.86return isNullValue();87}8889bool Constant::isNullValue() const {90// 0 is null.91if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))92return CI->isZero();9394// +0.0 is null.95if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))96// ppc_fp128 determine isZero using high order double only97// Should check the bitwise value to make sure all bits are zero.98return CFP->isExactlyValue(+0.0);99100// constant zero is zero for aggregates, cpnull is null for pointers, none for101// tokens.102return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this) ||103isa<ConstantTokenNone>(this) || isa<ConstantTargetNone>(this);104}105106bool Constant::isAllOnesValue() const {107// Check for -1 integers108if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))109return CI->isMinusOne();110111// Check for FP which are bitcasted from -1 integers112if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))113return CFP->getValueAPF().bitcastToAPInt().isAllOnes();114115// Check for constant splat vectors of 1 values.116if (getType()->isVectorTy())117if (const auto *SplatVal = getSplatValue())118return SplatVal->isAllOnesValue();119120return false;121}122123bool Constant::isOneValue() const {124// Check for 1 integers125if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))126return CI->isOne();127128// Check for FP which are bitcasted from 1 integers129if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))130return CFP->getValueAPF().bitcastToAPInt().isOne();131132// Check for constant splat vectors of 1 values.133if (getType()->isVectorTy())134if (const auto *SplatVal = getSplatValue())135return SplatVal->isOneValue();136137return false;138}139140bool Constant::isNotOneValue() const {141// Check for 1 integers142if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))143return !CI->isOneValue();144145// Check for FP which are bitcasted from 1 integers146if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))147return !CFP->getValueAPF().bitcastToAPInt().isOne();148149// Check that vectors don't contain 1150if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {151for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {152Constant *Elt = getAggregateElement(I);153if (!Elt || !Elt->isNotOneValue())154return false;155}156return true;157}158159// Check for splats that don't contain 1160if (getType()->isVectorTy())161if (const auto *SplatVal = getSplatValue())162return SplatVal->isNotOneValue();163164// It *may* contain 1, we can't tell.165return false;166}167168bool Constant::isMinSignedValue() const {169// Check for INT_MIN integers170if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))171return CI->isMinValue(/*isSigned=*/true);172173// Check for FP which are bitcasted from INT_MIN integers174if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))175return CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();176177// Check for splats of INT_MIN values.178if (getType()->isVectorTy())179if (const auto *SplatVal = getSplatValue())180return SplatVal->isMinSignedValue();181182return false;183}184185bool Constant::isNotMinSignedValue() const {186// Check for INT_MIN integers187if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))188return !CI->isMinValue(/*isSigned=*/true);189190// Check for FP which are bitcasted from INT_MIN integers191if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))192return !CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();193194// Check that vectors don't contain INT_MIN195if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {196for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {197Constant *Elt = getAggregateElement(I);198if (!Elt || !Elt->isNotMinSignedValue())199return false;200}201return true;202}203204// Check for splats that aren't INT_MIN205if (getType()->isVectorTy())206if (const auto *SplatVal = getSplatValue())207return SplatVal->isNotMinSignedValue();208209// It *may* contain INT_MIN, we can't tell.210return false;211}212213bool Constant::isFiniteNonZeroFP() const {214if (auto *CFP = dyn_cast<ConstantFP>(this))215return CFP->getValueAPF().isFiniteNonZero();216217if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {218for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {219auto *CFP = dyn_cast_or_null<ConstantFP>(getAggregateElement(I));220if (!CFP || !CFP->getValueAPF().isFiniteNonZero())221return false;222}223return true;224}225226if (getType()->isVectorTy())227if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))228return SplatCFP->isFiniteNonZeroFP();229230// It *may* contain finite non-zero, we can't tell.231return false;232}233234bool Constant::isNormalFP() const {235if (auto *CFP = dyn_cast<ConstantFP>(this))236return CFP->getValueAPF().isNormal();237238if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {239for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {240auto *CFP = dyn_cast_or_null<ConstantFP>(getAggregateElement(I));241if (!CFP || !CFP->getValueAPF().isNormal())242return false;243}244return true;245}246247if (getType()->isVectorTy())248if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))249return SplatCFP->isNormalFP();250251// It *may* contain a normal fp value, we can't tell.252return false;253}254255bool Constant::hasExactInverseFP() const {256if (auto *CFP = dyn_cast<ConstantFP>(this))257return CFP->getValueAPF().getExactInverse(nullptr);258259if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {260for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {261auto *CFP = dyn_cast_or_null<ConstantFP>(getAggregateElement(I));262if (!CFP || !CFP->getValueAPF().getExactInverse(nullptr))263return false;264}265return true;266}267268if (getType()->isVectorTy())269if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))270return SplatCFP->hasExactInverseFP();271272// It *may* have an exact inverse fp value, we can't tell.273return false;274}275276bool Constant::isNaN() const {277if (auto *CFP = dyn_cast<ConstantFP>(this))278return CFP->isNaN();279280if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {281for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {282auto *CFP = dyn_cast_or_null<ConstantFP>(getAggregateElement(I));283if (!CFP || !CFP->isNaN())284return false;285}286return true;287}288289if (getType()->isVectorTy())290if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))291return SplatCFP->isNaN();292293// It *may* be NaN, we can't tell.294return false;295}296297bool Constant::isElementWiseEqual(Value *Y) const {298// Are they fully identical?299if (this == Y)300return true;301302// The input value must be a vector constant with the same type.303auto *VTy = dyn_cast<VectorType>(getType());304if (!isa<Constant>(Y) || !VTy || VTy != Y->getType())305return false;306307// TODO: Compare pointer constants?308if (!(VTy->getElementType()->isIntegerTy() ||309VTy->getElementType()->isFloatingPointTy()))310return false;311312// They may still be identical element-wise (if they have `undef`s).313// Bitcast to integer to allow exact bitwise comparison for all types.314Type *IntTy = VectorType::getInteger(VTy);315Constant *C0 = ConstantExpr::getBitCast(const_cast<Constant *>(this), IntTy);316Constant *C1 = ConstantExpr::getBitCast(cast<Constant>(Y), IntTy);317Constant *CmpEq = ConstantFoldCompareInstruction(ICmpInst::ICMP_EQ, C0, C1);318return CmpEq && (isa<PoisonValue>(CmpEq) || match(CmpEq, m_One()));319}320321static bool322containsUndefinedElement(const Constant *C,323function_ref<bool(const Constant *)> HasFn) {324if (auto *VTy = dyn_cast<VectorType>(C->getType())) {325if (HasFn(C))326return true;327if (isa<ConstantAggregateZero>(C))328return false;329if (isa<ScalableVectorType>(C->getType()))330return false;331332for (unsigned i = 0, e = cast<FixedVectorType>(VTy)->getNumElements();333i != e; ++i) {334if (Constant *Elem = C->getAggregateElement(i))335if (HasFn(Elem))336return true;337}338}339340return false;341}342343bool Constant::containsUndefOrPoisonElement() const {344return containsUndefinedElement(345this, [&](const auto *C) { return isa<UndefValue>(C); });346}347348bool Constant::containsPoisonElement() const {349return containsUndefinedElement(350this, [&](const auto *C) { return isa<PoisonValue>(C); });351}352353bool Constant::containsUndefElement() const {354return containsUndefinedElement(this, [&](const auto *C) {355return isa<UndefValue>(C) && !isa<PoisonValue>(C);356});357}358359bool Constant::containsConstantExpression() const {360if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {361for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i)362if (isa<ConstantExpr>(getAggregateElement(i)))363return true;364}365return false;366}367368/// Constructor to create a '0' constant of arbitrary type.369Constant *Constant::getNullValue(Type *Ty) {370switch (Ty->getTypeID()) {371case Type::IntegerTyID:372return ConstantInt::get(Ty, 0);373case Type::HalfTyID:374case Type::BFloatTyID:375case Type::FloatTyID:376case Type::DoubleTyID:377case Type::X86_FP80TyID:378case Type::FP128TyID:379case Type::PPC_FP128TyID:380return ConstantFP::get(Ty->getContext(),381APFloat::getZero(Ty->getFltSemantics()));382case Type::PointerTyID:383return ConstantPointerNull::get(cast<PointerType>(Ty));384case Type::StructTyID:385case Type::ArrayTyID:386case Type::FixedVectorTyID:387case Type::ScalableVectorTyID:388return ConstantAggregateZero::get(Ty);389case Type::TokenTyID:390return ConstantTokenNone::get(Ty->getContext());391case Type::TargetExtTyID:392return ConstantTargetNone::get(cast<TargetExtType>(Ty));393default:394// Function, Label, or Opaque type?395llvm_unreachable("Cannot create a null constant of that type!");396}397}398399Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) {400Type *ScalarTy = Ty->getScalarType();401402// Create the base integer constant.403Constant *C = ConstantInt::get(Ty->getContext(), V);404405// Convert an integer to a pointer, if necessary.406if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))407C = ConstantExpr::getIntToPtr(C, PTy);408409// Broadcast a scalar to a vector, if necessary.410if (VectorType *VTy = dyn_cast<VectorType>(Ty))411C = ConstantVector::getSplat(VTy->getElementCount(), C);412413return C;414}415416Constant *Constant::getAllOnesValue(Type *Ty) {417if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))418return ConstantInt::get(Ty->getContext(),419APInt::getAllOnes(ITy->getBitWidth()));420421if (Ty->isFloatingPointTy()) {422APFloat FL = APFloat::getAllOnesValue(Ty->getFltSemantics());423return ConstantFP::get(Ty->getContext(), FL);424}425426VectorType *VTy = cast<VectorType>(Ty);427return ConstantVector::getSplat(VTy->getElementCount(),428getAllOnesValue(VTy->getElementType()));429}430431Constant *Constant::getAggregateElement(unsigned Elt) const {432assert((getType()->isAggregateType() || getType()->isVectorTy()) &&433"Must be an aggregate/vector constant");434435if (const auto *CC = dyn_cast<ConstantAggregate>(this))436return Elt < CC->getNumOperands() ? CC->getOperand(Elt) : nullptr;437438if (const auto *CAZ = dyn_cast<ConstantAggregateZero>(this))439return Elt < CAZ->getElementCount().getKnownMinValue()440? CAZ->getElementValue(Elt)441: nullptr;442443// FIXME: getNumElements() will fail for non-fixed vector types.444if (isa<ScalableVectorType>(getType()))445return nullptr;446447if (const auto *PV = dyn_cast<PoisonValue>(this))448return Elt < PV->getNumElements() ? PV->getElementValue(Elt) : nullptr;449450if (const auto *UV = dyn_cast<UndefValue>(this))451return Elt < UV->getNumElements() ? UV->getElementValue(Elt) : nullptr;452453if (const auto *CDS = dyn_cast<ConstantDataSequential>(this))454return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt)455: nullptr;456457return nullptr;458}459460Constant *Constant::getAggregateElement(Constant *Elt) const {461assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");462if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt)) {463// Check if the constant fits into an uint64_t.464if (CI->getValue().getActiveBits() > 64)465return nullptr;466return getAggregateElement(CI->getZExtValue());467}468return nullptr;469}470471void Constant::destroyConstant() {472/// First call destroyConstantImpl on the subclass. This gives the subclass473/// a chance to remove the constant from any maps/pools it's contained in.474switch (getValueID()) {475default:476llvm_unreachable("Not a constant!");477#define HANDLE_CONSTANT(Name) \478case Value::Name##Val: \479cast<Name>(this)->destroyConstantImpl(); \480break;481#include "llvm/IR/Value.def"482}483484// When a Constant is destroyed, there may be lingering485// references to the constant by other constants in the constant pool. These486// constants are implicitly dependent on the module that is being deleted,487// but they don't know that. Because we only find out when the CPV is488// deleted, we must now notify all of our users (that should only be489// Constants) that they are, in fact, invalid now and should be deleted.490//491while (!use_empty()) {492Value *V = user_back();493#ifndef NDEBUG // Only in -g mode...494if (!isa<Constant>(V)) {495dbgs() << "While deleting: " << *this496<< "\n\nUse still stuck around after Def is destroyed: " << *V497<< "\n\n";498}499#endif500assert(isa<Constant>(V) && "References remain to Constant being destroyed");501cast<Constant>(V)->destroyConstant();502503// The constant should remove itself from our use list...504assert((use_empty() || user_back() != V) && "Constant not removed!");505}506507// Value has no outstanding references it is safe to delete it now...508deleteConstant(this);509}510511void llvm::deleteConstant(Constant *C) {512switch (C->getValueID()) {513case Constant::ConstantIntVal:514delete static_cast<ConstantInt *>(C);515break;516case Constant::ConstantFPVal:517delete static_cast<ConstantFP *>(C);518break;519case Constant::ConstantAggregateZeroVal:520delete static_cast<ConstantAggregateZero *>(C);521break;522case Constant::ConstantArrayVal:523delete static_cast<ConstantArray *>(C);524break;525case Constant::ConstantStructVal:526delete static_cast<ConstantStruct *>(C);527break;528case Constant::ConstantVectorVal:529delete static_cast<ConstantVector *>(C);530break;531case Constant::ConstantPointerNullVal:532delete static_cast<ConstantPointerNull *>(C);533break;534case Constant::ConstantDataArrayVal:535delete static_cast<ConstantDataArray *>(C);536break;537case Constant::ConstantDataVectorVal:538delete static_cast<ConstantDataVector *>(C);539break;540case Constant::ConstantTokenNoneVal:541delete static_cast<ConstantTokenNone *>(C);542break;543case Constant::BlockAddressVal:544delete static_cast<BlockAddress *>(C);545break;546case Constant::DSOLocalEquivalentVal:547delete static_cast<DSOLocalEquivalent *>(C);548break;549case Constant::NoCFIValueVal:550delete static_cast<NoCFIValue *>(C);551break;552case Constant::ConstantPtrAuthVal:553delete static_cast<ConstantPtrAuth *>(C);554break;555case Constant::UndefValueVal:556delete static_cast<UndefValue *>(C);557break;558case Constant::PoisonValueVal:559delete static_cast<PoisonValue *>(C);560break;561case Constant::ConstantExprVal:562if (isa<CastConstantExpr>(C))563delete static_cast<CastConstantExpr *>(C);564else if (isa<BinaryConstantExpr>(C))565delete static_cast<BinaryConstantExpr *>(C);566else if (isa<ExtractElementConstantExpr>(C))567delete static_cast<ExtractElementConstantExpr *>(C);568else if (isa<InsertElementConstantExpr>(C))569delete static_cast<InsertElementConstantExpr *>(C);570else if (isa<ShuffleVectorConstantExpr>(C))571delete static_cast<ShuffleVectorConstantExpr *>(C);572else if (isa<GetElementPtrConstantExpr>(C))573delete static_cast<GetElementPtrConstantExpr *>(C);574else575llvm_unreachable("Unexpected constant expr");576break;577default:578llvm_unreachable("Unexpected constant");579}580}581582/// Check if C contains a GlobalValue for which Predicate is true.583static bool584ConstHasGlobalValuePredicate(const Constant *C,585bool (*Predicate)(const GlobalValue *)) {586SmallPtrSet<const Constant *, 8> Visited;587SmallVector<const Constant *, 8> WorkList;588WorkList.push_back(C);589Visited.insert(C);590591while (!WorkList.empty()) {592const Constant *WorkItem = WorkList.pop_back_val();593if (const auto *GV = dyn_cast<GlobalValue>(WorkItem))594if (Predicate(GV))595return true;596for (const Value *Op : WorkItem->operands()) {597const Constant *ConstOp = dyn_cast<Constant>(Op);598if (!ConstOp)599continue;600if (Visited.insert(ConstOp).second)601WorkList.push_back(ConstOp);602}603}604return false;605}606607bool Constant::isThreadDependent() const {608auto DLLImportPredicate = [](const GlobalValue *GV) {609return GV->isThreadLocal();610};611return ConstHasGlobalValuePredicate(this, DLLImportPredicate);612}613614bool Constant::isDLLImportDependent() const {615auto DLLImportPredicate = [](const GlobalValue *GV) {616return GV->hasDLLImportStorageClass();617};618return ConstHasGlobalValuePredicate(this, DLLImportPredicate);619}620621bool Constant::isConstantUsed() const {622for (const User *U : users()) {623const Constant *UC = dyn_cast<Constant>(U);624if (!UC || isa<GlobalValue>(UC))625return true;626627if (UC->isConstantUsed())628return true;629}630return false;631}632633bool Constant::needsDynamicRelocation() const {634return getRelocationInfo() == GlobalRelocation;635}636637bool Constant::needsRelocation() const {638return getRelocationInfo() != NoRelocation;639}640641Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {642if (isa<GlobalValue>(this))643return GlobalRelocation; // Global reference.644645if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))646return BA->getFunction()->getRelocationInfo();647648if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this)) {649if (CE->getOpcode() == Instruction::Sub) {650ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));651ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));652if (LHS && RHS && LHS->getOpcode() == Instruction::PtrToInt &&653RHS->getOpcode() == Instruction::PtrToInt) {654Constant *LHSOp0 = LHS->getOperand(0);655Constant *RHSOp0 = RHS->getOperand(0);656657// While raw uses of blockaddress need to be relocated, differences658// between two of them don't when they are for labels in the same659// function. This is a common idiom when creating a table for the660// indirect goto extension, so we handle it efficiently here.661if (isa<BlockAddress>(LHSOp0) && isa<BlockAddress>(RHSOp0) &&662cast<BlockAddress>(LHSOp0)->getFunction() ==663cast<BlockAddress>(RHSOp0)->getFunction())664return NoRelocation;665666// Relative pointers do not need to be dynamically relocated.667if (auto *RHSGV =668dyn_cast<GlobalValue>(RHSOp0->stripInBoundsConstantOffsets())) {669auto *LHS = LHSOp0->stripInBoundsConstantOffsets();670if (auto *LHSGV = dyn_cast<GlobalValue>(LHS)) {671if (LHSGV->isDSOLocal() && RHSGV->isDSOLocal())672return LocalRelocation;673} else if (isa<DSOLocalEquivalent>(LHS)) {674if (RHSGV->isDSOLocal())675return LocalRelocation;676}677}678}679}680}681682PossibleRelocationsTy Result = NoRelocation;683for (unsigned i = 0, e = getNumOperands(); i != e; ++i)684Result =685std::max(cast<Constant>(getOperand(i))->getRelocationInfo(), Result);686687return Result;688}689690/// Return true if the specified constantexpr is dead. This involves691/// recursively traversing users of the constantexpr.692/// If RemoveDeadUsers is true, also remove dead users at the same time.693static bool constantIsDead(const Constant *C, bool RemoveDeadUsers) {694if (isa<GlobalValue>(C)) return false; // Cannot remove this695696Value::const_user_iterator I = C->user_begin(), E = C->user_end();697while (I != E) {698const Constant *User = dyn_cast<Constant>(*I);699if (!User) return false; // Non-constant usage;700if (!constantIsDead(User, RemoveDeadUsers))701return false; // Constant wasn't dead702703// Just removed User, so the iterator was invalidated.704// Since we return immediately upon finding a live user, we can always705// restart from user_begin().706if (RemoveDeadUsers)707I = C->user_begin();708else709++I;710}711712if (RemoveDeadUsers) {713// If C is only used by metadata, it should not be preserved but should714// have its uses replaced.715ReplaceableMetadataImpl::SalvageDebugInfo(*C);716const_cast<Constant *>(C)->destroyConstant();717}718719return true;720}721722void Constant::removeDeadConstantUsers() const {723Value::const_user_iterator I = user_begin(), E = user_end();724Value::const_user_iterator LastNonDeadUser = E;725while (I != E) {726const Constant *User = dyn_cast<Constant>(*I);727if (!User) {728LastNonDeadUser = I;729++I;730continue;731}732733if (!constantIsDead(User, /* RemoveDeadUsers= */ true)) {734// If the constant wasn't dead, remember that this was the last live use735// and move on to the next constant.736LastNonDeadUser = I;737++I;738continue;739}740741// If the constant was dead, then the iterator is invalidated.742if (LastNonDeadUser == E)743I = user_begin();744else745I = std::next(LastNonDeadUser);746}747}748749bool Constant::hasOneLiveUse() const { return hasNLiveUses(1); }750751bool Constant::hasZeroLiveUses() const { return hasNLiveUses(0); }752753bool Constant::hasNLiveUses(unsigned N) const {754unsigned NumUses = 0;755for (const Use &U : uses()) {756const Constant *User = dyn_cast<Constant>(U.getUser());757if (!User || !constantIsDead(User, /* RemoveDeadUsers= */ false)) {758++NumUses;759760if (NumUses > N)761return false;762}763}764return NumUses == N;765}766767Constant *Constant::replaceUndefsWith(Constant *C, Constant *Replacement) {768assert(C && Replacement && "Expected non-nullptr constant arguments");769Type *Ty = C->getType();770if (match(C, m_Undef())) {771assert(Ty == Replacement->getType() && "Expected matching types");772return Replacement;773}774775// Don't know how to deal with this constant.776auto *VTy = dyn_cast<FixedVectorType>(Ty);777if (!VTy)778return C;779780unsigned NumElts = VTy->getNumElements();781SmallVector<Constant *, 32> NewC(NumElts);782for (unsigned i = 0; i != NumElts; ++i) {783Constant *EltC = C->getAggregateElement(i);784assert((!EltC || EltC->getType() == Replacement->getType()) &&785"Expected matching types");786NewC[i] = EltC && match(EltC, m_Undef()) ? Replacement : EltC;787}788return ConstantVector::get(NewC);789}790791Constant *Constant::mergeUndefsWith(Constant *C, Constant *Other) {792assert(C && Other && "Expected non-nullptr constant arguments");793if (match(C, m_Undef()))794return C;795796Type *Ty = C->getType();797if (match(Other, m_Undef()))798return UndefValue::get(Ty);799800auto *VTy = dyn_cast<FixedVectorType>(Ty);801if (!VTy)802return C;803804Type *EltTy = VTy->getElementType();805unsigned NumElts = VTy->getNumElements();806assert(isa<FixedVectorType>(Other->getType()) &&807cast<FixedVectorType>(Other->getType())->getNumElements() == NumElts &&808"Type mismatch");809810bool FoundExtraUndef = false;811SmallVector<Constant *, 32> NewC(NumElts);812for (unsigned I = 0; I != NumElts; ++I) {813NewC[I] = C->getAggregateElement(I);814Constant *OtherEltC = Other->getAggregateElement(I);815assert(NewC[I] && OtherEltC && "Unknown vector element");816if (!match(NewC[I], m_Undef()) && match(OtherEltC, m_Undef())) {817NewC[I] = UndefValue::get(EltTy);818FoundExtraUndef = true;819}820}821if (FoundExtraUndef)822return ConstantVector::get(NewC);823return C;824}825826bool Constant::isManifestConstant() const {827if (isa<ConstantData>(this))828return true;829if (isa<ConstantAggregate>(this) || isa<ConstantExpr>(this)) {830for (const Value *Op : operand_values())831if (!cast<Constant>(Op)->isManifestConstant())832return false;833return true;834}835return false;836}837838//===----------------------------------------------------------------------===//839// ConstantInt840//===----------------------------------------------------------------------===//841842ConstantInt::ConstantInt(Type *Ty, const APInt &V)843: ConstantData(Ty, ConstantIntVal), Val(V) {844assert(V.getBitWidth() ==845cast<IntegerType>(Ty->getScalarType())->getBitWidth() &&846"Invalid constant for type");847}848849ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {850LLVMContextImpl *pImpl = Context.pImpl;851if (!pImpl->TheTrueVal)852pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);853return pImpl->TheTrueVal;854}855856ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {857LLVMContextImpl *pImpl = Context.pImpl;858if (!pImpl->TheFalseVal)859pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);860return pImpl->TheFalseVal;861}862863ConstantInt *ConstantInt::getBool(LLVMContext &Context, bool V) {864return V ? getTrue(Context) : getFalse(Context);865}866867Constant *ConstantInt::getTrue(Type *Ty) {868assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");869ConstantInt *TrueC = ConstantInt::getTrue(Ty->getContext());870if (auto *VTy = dyn_cast<VectorType>(Ty))871return ConstantVector::getSplat(VTy->getElementCount(), TrueC);872return TrueC;873}874875Constant *ConstantInt::getFalse(Type *Ty) {876assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");877ConstantInt *FalseC = ConstantInt::getFalse(Ty->getContext());878if (auto *VTy = dyn_cast<VectorType>(Ty))879return ConstantVector::getSplat(VTy->getElementCount(), FalseC);880return FalseC;881}882883Constant *ConstantInt::getBool(Type *Ty, bool V) {884return V ? getTrue(Ty) : getFalse(Ty);885}886887// Get a ConstantInt from an APInt.888ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {889// get an existing value or the insertion position890LLVMContextImpl *pImpl = Context.pImpl;891std::unique_ptr<ConstantInt> &Slot =892V.isZero() ? pImpl->IntZeroConstants[V.getBitWidth()]893: V.isOne() ? pImpl->IntOneConstants[V.getBitWidth()]894: pImpl->IntConstants[V];895if (!Slot) {896// Get the corresponding integer type for the bit width of the value.897IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());898Slot.reset(new ConstantInt(ITy, V));899}900assert(Slot->getType() == IntegerType::get(Context, V.getBitWidth()));901return Slot.get();902}903904// Get a ConstantInt vector with each lane set to the same APInt.905ConstantInt *ConstantInt::get(LLVMContext &Context, ElementCount EC,906const APInt &V) {907// Get an existing value or the insertion position.908std::unique_ptr<ConstantInt> &Slot =909Context.pImpl->IntSplatConstants[std::make_pair(EC, V)];910if (!Slot) {911IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());912VectorType *VTy = VectorType::get(ITy, EC);913Slot.reset(new ConstantInt(VTy, V));914}915916#ifndef NDEBUG917IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());918VectorType *VTy = VectorType::get(ITy, EC);919assert(Slot->getType() == VTy);920#endif921return Slot.get();922}923924Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {925Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);926927// For vectors, broadcast the value.928if (VectorType *VTy = dyn_cast<VectorType>(Ty))929return ConstantVector::getSplat(VTy->getElementCount(), C);930931return C;932}933934ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V, bool isSigned) {935return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));936}937938Constant *ConstantInt::get(Type *Ty, const APInt& V) {939ConstantInt *C = get(Ty->getContext(), V);940assert(C->getType() == Ty->getScalarType() &&941"ConstantInt type doesn't match the type implied by its value!");942943// For vectors, broadcast the value.944if (VectorType *VTy = dyn_cast<VectorType>(Ty))945return ConstantVector::getSplat(VTy->getElementCount(), C);946947return C;948}949950ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str, uint8_t radix) {951return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));952}953954/// Remove the constant from the constant table.955void ConstantInt::destroyConstantImpl() {956llvm_unreachable("You can't ConstantInt->destroyConstantImpl()!");957}958959//===----------------------------------------------------------------------===//960// ConstantFP961//===----------------------------------------------------------------------===//962963Constant *ConstantFP::get(Type *Ty, double V) {964LLVMContext &Context = Ty->getContext();965966APFloat FV(V);967bool ignored;968FV.convert(Ty->getScalarType()->getFltSemantics(),969APFloat::rmNearestTiesToEven, &ignored);970Constant *C = get(Context, FV);971972// For vectors, broadcast the value.973if (VectorType *VTy = dyn_cast<VectorType>(Ty))974return ConstantVector::getSplat(VTy->getElementCount(), C);975976return C;977}978979Constant *ConstantFP::get(Type *Ty, const APFloat &V) {980ConstantFP *C = get(Ty->getContext(), V);981assert(C->getType() == Ty->getScalarType() &&982"ConstantFP type doesn't match the type implied by its value!");983984// For vectors, broadcast the value.985if (auto *VTy = dyn_cast<VectorType>(Ty))986return ConstantVector::getSplat(VTy->getElementCount(), C);987988return C;989}990991Constant *ConstantFP::get(Type *Ty, StringRef Str) {992LLVMContext &Context = Ty->getContext();993994APFloat FV(Ty->getScalarType()->getFltSemantics(), Str);995Constant *C = get(Context, FV);996997// For vectors, broadcast the value.998if (VectorType *VTy = dyn_cast<VectorType>(Ty))999return ConstantVector::getSplat(VTy->getElementCount(), C);10001001return C;1002}10031004Constant *ConstantFP::getNaN(Type *Ty, bool Negative, uint64_t Payload) {1005const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();1006APFloat NaN = APFloat::getNaN(Semantics, Negative, Payload);1007Constant *C = get(Ty->getContext(), NaN);10081009if (VectorType *VTy = dyn_cast<VectorType>(Ty))1010return ConstantVector::getSplat(VTy->getElementCount(), C);10111012return C;1013}10141015Constant *ConstantFP::getQNaN(Type *Ty, bool Negative, APInt *Payload) {1016const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();1017APFloat NaN = APFloat::getQNaN(Semantics, Negative, Payload);1018Constant *C = get(Ty->getContext(), NaN);10191020if (VectorType *VTy = dyn_cast<VectorType>(Ty))1021return ConstantVector::getSplat(VTy->getElementCount(), C);10221023return C;1024}10251026Constant *ConstantFP::getSNaN(Type *Ty, bool Negative, APInt *Payload) {1027const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();1028APFloat NaN = APFloat::getSNaN(Semantics, Negative, Payload);1029Constant *C = get(Ty->getContext(), NaN);10301031if (VectorType *VTy = dyn_cast<VectorType>(Ty))1032return ConstantVector::getSplat(VTy->getElementCount(), C);10331034return C;1035}10361037Constant *ConstantFP::getZero(Type *Ty, bool Negative) {1038const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();1039APFloat NegZero = APFloat::getZero(Semantics, Negative);1040Constant *C = get(Ty->getContext(), NegZero);10411042if (VectorType *VTy = dyn_cast<VectorType>(Ty))1043return ConstantVector::getSplat(VTy->getElementCount(), C);10441045return C;1046}104710481049// ConstantFP accessors.1050ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {1051LLVMContextImpl* pImpl = Context.pImpl;10521053std::unique_ptr<ConstantFP> &Slot = pImpl->FPConstants[V];10541055if (!Slot) {1056Type *Ty = Type::getFloatingPointTy(Context, V.getSemantics());1057Slot.reset(new ConstantFP(Ty, V));1058}10591060return Slot.get();1061}10621063// Get a ConstantFP vector with each lane set to the same APFloat.1064ConstantFP *ConstantFP::get(LLVMContext &Context, ElementCount EC,1065const APFloat &V) {1066// Get an existing value or the insertion position.1067std::unique_ptr<ConstantFP> &Slot =1068Context.pImpl->FPSplatConstants[std::make_pair(EC, V)];1069if (!Slot) {1070Type *EltTy = Type::getFloatingPointTy(Context, V.getSemantics());1071VectorType *VTy = VectorType::get(EltTy, EC);1072Slot.reset(new ConstantFP(VTy, V));1073}10741075#ifndef NDEBUG1076Type *EltTy = Type::getFloatingPointTy(Context, V.getSemantics());1077VectorType *VTy = VectorType::get(EltTy, EC);1078assert(Slot->getType() == VTy);1079#endif1080return Slot.get();1081}10821083Constant *ConstantFP::getInfinity(Type *Ty, bool Negative) {1084const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();1085Constant *C = get(Ty->getContext(), APFloat::getInf(Semantics, Negative));10861087if (VectorType *VTy = dyn_cast<VectorType>(Ty))1088return ConstantVector::getSplat(VTy->getElementCount(), C);10891090return C;1091}10921093ConstantFP::ConstantFP(Type *Ty, const APFloat &V)1094: ConstantData(Ty, ConstantFPVal), Val(V) {1095assert(&V.getSemantics() == &Ty->getScalarType()->getFltSemantics() &&1096"FP type Mismatch");1097}10981099bool ConstantFP::isExactlyValue(const APFloat &V) const {1100return Val.bitwiseIsEqual(V);1101}11021103/// Remove the constant from the constant table.1104void ConstantFP::destroyConstantImpl() {1105llvm_unreachable("You can't ConstantFP->destroyConstantImpl()!");1106}11071108//===----------------------------------------------------------------------===//1109// ConstantAggregateZero Implementation1110//===----------------------------------------------------------------------===//11111112Constant *ConstantAggregateZero::getSequentialElement() const {1113if (auto *AT = dyn_cast<ArrayType>(getType()))1114return Constant::getNullValue(AT->getElementType());1115return Constant::getNullValue(cast<VectorType>(getType())->getElementType());1116}11171118Constant *ConstantAggregateZero::getStructElement(unsigned Elt) const {1119return Constant::getNullValue(getType()->getStructElementType(Elt));1120}11211122Constant *ConstantAggregateZero::getElementValue(Constant *C) const {1123if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))1124return getSequentialElement();1125return getStructElement(cast<ConstantInt>(C)->getZExtValue());1126}11271128Constant *ConstantAggregateZero::getElementValue(unsigned Idx) const {1129if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))1130return getSequentialElement();1131return getStructElement(Idx);1132}11331134ElementCount ConstantAggregateZero::getElementCount() const {1135Type *Ty = getType();1136if (auto *AT = dyn_cast<ArrayType>(Ty))1137return ElementCount::getFixed(AT->getNumElements());1138if (auto *VT = dyn_cast<VectorType>(Ty))1139return VT->getElementCount();1140return ElementCount::getFixed(Ty->getStructNumElements());1141}11421143//===----------------------------------------------------------------------===//1144// UndefValue Implementation1145//===----------------------------------------------------------------------===//11461147UndefValue *UndefValue::getSequentialElement() const {1148if (ArrayType *ATy = dyn_cast<ArrayType>(getType()))1149return UndefValue::get(ATy->getElementType());1150return UndefValue::get(cast<VectorType>(getType())->getElementType());1151}11521153UndefValue *UndefValue::getStructElement(unsigned Elt) const {1154return UndefValue::get(getType()->getStructElementType(Elt));1155}11561157UndefValue *UndefValue::getElementValue(Constant *C) const {1158if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))1159return getSequentialElement();1160return getStructElement(cast<ConstantInt>(C)->getZExtValue());1161}11621163UndefValue *UndefValue::getElementValue(unsigned Idx) const {1164if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))1165return getSequentialElement();1166return getStructElement(Idx);1167}11681169unsigned UndefValue::getNumElements() const {1170Type *Ty = getType();1171if (auto *AT = dyn_cast<ArrayType>(Ty))1172return AT->getNumElements();1173if (auto *VT = dyn_cast<VectorType>(Ty))1174return cast<FixedVectorType>(VT)->getNumElements();1175return Ty->getStructNumElements();1176}11771178//===----------------------------------------------------------------------===//1179// PoisonValue Implementation1180//===----------------------------------------------------------------------===//11811182PoisonValue *PoisonValue::getSequentialElement() const {1183if (ArrayType *ATy = dyn_cast<ArrayType>(getType()))1184return PoisonValue::get(ATy->getElementType());1185return PoisonValue::get(cast<VectorType>(getType())->getElementType());1186}11871188PoisonValue *PoisonValue::getStructElement(unsigned Elt) const {1189return PoisonValue::get(getType()->getStructElementType(Elt));1190}11911192PoisonValue *PoisonValue::getElementValue(Constant *C) const {1193if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))1194return getSequentialElement();1195return getStructElement(cast<ConstantInt>(C)->getZExtValue());1196}11971198PoisonValue *PoisonValue::getElementValue(unsigned Idx) const {1199if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))1200return getSequentialElement();1201return getStructElement(Idx);1202}12031204//===----------------------------------------------------------------------===//1205// ConstantXXX Classes1206//===----------------------------------------------------------------------===//12071208template <typename ItTy, typename EltTy>1209static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {1210for (; Start != End; ++Start)1211if (*Start != Elt)1212return false;1213return true;1214}12151216template <typename SequentialTy, typename ElementTy>1217static Constant *getIntSequenceIfElementsMatch(ArrayRef<Constant *> V) {1218assert(!V.empty() && "Cannot get empty int sequence.");12191220SmallVector<ElementTy, 16> Elts;1221for (Constant *C : V)1222if (auto *CI = dyn_cast<ConstantInt>(C))1223Elts.push_back(CI->getZExtValue());1224else1225return nullptr;1226return SequentialTy::get(V[0]->getContext(), Elts);1227}12281229template <typename SequentialTy, typename ElementTy>1230static Constant *getFPSequenceIfElementsMatch(ArrayRef<Constant *> V) {1231assert(!V.empty() && "Cannot get empty FP sequence.");12321233SmallVector<ElementTy, 16> Elts;1234for (Constant *C : V)1235if (auto *CFP = dyn_cast<ConstantFP>(C))1236Elts.push_back(CFP->getValueAPF().bitcastToAPInt().getLimitedValue());1237else1238return nullptr;1239return SequentialTy::getFP(V[0]->getType(), Elts);1240}12411242template <typename SequenceTy>1243static Constant *getSequenceIfElementsMatch(Constant *C,1244ArrayRef<Constant *> V) {1245// We speculatively build the elements here even if it turns out that there is1246// a constantexpr or something else weird, since it is so uncommon for that to1247// happen.1248if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {1249if (CI->getType()->isIntegerTy(8))1250return getIntSequenceIfElementsMatch<SequenceTy, uint8_t>(V);1251else if (CI->getType()->isIntegerTy(16))1252return getIntSequenceIfElementsMatch<SequenceTy, uint16_t>(V);1253else if (CI->getType()->isIntegerTy(32))1254return getIntSequenceIfElementsMatch<SequenceTy, uint32_t>(V);1255else if (CI->getType()->isIntegerTy(64))1256return getIntSequenceIfElementsMatch<SequenceTy, uint64_t>(V);1257} else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {1258if (CFP->getType()->isHalfTy() || CFP->getType()->isBFloatTy())1259return getFPSequenceIfElementsMatch<SequenceTy, uint16_t>(V);1260else if (CFP->getType()->isFloatTy())1261return getFPSequenceIfElementsMatch<SequenceTy, uint32_t>(V);1262else if (CFP->getType()->isDoubleTy())1263return getFPSequenceIfElementsMatch<SequenceTy, uint64_t>(V);1264}12651266return nullptr;1267}12681269ConstantAggregate::ConstantAggregate(Type *T, ValueTy VT,1270ArrayRef<Constant *> V)1271: Constant(T, VT, OperandTraits<ConstantAggregate>::op_end(this) - V.size(),1272V.size()) {1273llvm::copy(V, op_begin());12741275// Check that types match, unless this is an opaque struct.1276if (auto *ST = dyn_cast<StructType>(T)) {1277if (ST->isOpaque())1278return;1279for (unsigned I = 0, E = V.size(); I != E; ++I)1280assert(V[I]->getType() == ST->getTypeAtIndex(I) &&1281"Initializer for struct element doesn't match!");1282}1283}12841285ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)1286: ConstantAggregate(T, ConstantArrayVal, V) {1287assert(V.size() == T->getNumElements() &&1288"Invalid initializer for constant array");1289}12901291Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {1292if (Constant *C = getImpl(Ty, V))1293return C;1294return Ty->getContext().pImpl->ArrayConstants.getOrCreate(Ty, V);1295}12961297Constant *ConstantArray::getImpl(ArrayType *Ty, ArrayRef<Constant*> V) {1298// Empty arrays are canonicalized to ConstantAggregateZero.1299if (V.empty())1300return ConstantAggregateZero::get(Ty);13011302for (Constant *C : V) {1303assert(C->getType() == Ty->getElementType() &&1304"Wrong type in array element initializer");1305(void)C;1306}13071308// If this is an all-zero array, return a ConstantAggregateZero object. If1309// all undef, return an UndefValue, if "all simple", then return a1310// ConstantDataArray.1311Constant *C = V[0];1312if (isa<PoisonValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))1313return PoisonValue::get(Ty);13141315if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))1316return UndefValue::get(Ty);13171318if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))1319return ConstantAggregateZero::get(Ty);13201321// Check to see if all of the elements are ConstantFP or ConstantInt and if1322// the element type is compatible with ConstantDataVector. If so, use it.1323if (ConstantDataSequential::isElementTypeCompatible(C->getType()))1324return getSequenceIfElementsMatch<ConstantDataArray>(C, V);13251326// Otherwise, we really do want to create a ConstantArray.1327return nullptr;1328}13291330StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,1331ArrayRef<Constant*> V,1332bool Packed) {1333unsigned VecSize = V.size();1334SmallVector<Type*, 16> EltTypes(VecSize);1335for (unsigned i = 0; i != VecSize; ++i)1336EltTypes[i] = V[i]->getType();13371338return StructType::get(Context, EltTypes, Packed);1339}134013411342StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,1343bool Packed) {1344assert(!V.empty() &&1345"ConstantStruct::getTypeForElements cannot be called on empty list");1346return getTypeForElements(V[0]->getContext(), V, Packed);1347}13481349ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)1350: ConstantAggregate(T, ConstantStructVal, V) {1351assert((T->isOpaque() || V.size() == T->getNumElements()) &&1352"Invalid initializer for constant struct");1353}13541355// ConstantStruct accessors.1356Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {1357assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&1358"Incorrect # elements specified to ConstantStruct::get");13591360// Create a ConstantAggregateZero value if all elements are zeros.1361bool isZero = true;1362bool isUndef = false;1363bool isPoison = false;13641365if (!V.empty()) {1366isUndef = isa<UndefValue>(V[0]);1367isPoison = isa<PoisonValue>(V[0]);1368isZero = V[0]->isNullValue();1369// PoisonValue inherits UndefValue, so its check is not necessary.1370if (isUndef || isZero) {1371for (Constant *C : V) {1372if (!C->isNullValue())1373isZero = false;1374if (!isa<PoisonValue>(C))1375isPoison = false;1376if (isa<PoisonValue>(C) || !isa<UndefValue>(C))1377isUndef = false;1378}1379}1380}1381if (isZero)1382return ConstantAggregateZero::get(ST);1383if (isPoison)1384return PoisonValue::get(ST);1385if (isUndef)1386return UndefValue::get(ST);13871388return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);1389}13901391ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)1392: ConstantAggregate(T, ConstantVectorVal, V) {1393assert(V.size() == cast<FixedVectorType>(T)->getNumElements() &&1394"Invalid initializer for constant vector");1395}13961397// ConstantVector accessors.1398Constant *ConstantVector::get(ArrayRef<Constant*> V) {1399if (Constant *C = getImpl(V))1400return C;1401auto *Ty = FixedVectorType::get(V.front()->getType(), V.size());1402return Ty->getContext().pImpl->VectorConstants.getOrCreate(Ty, V);1403}14041405Constant *ConstantVector::getImpl(ArrayRef<Constant*> V) {1406assert(!V.empty() && "Vectors can't be empty");1407auto *T = FixedVectorType::get(V.front()->getType(), V.size());14081409// If this is an all-undef or all-zero vector, return a1410// ConstantAggregateZero or UndefValue.1411Constant *C = V[0];1412bool isZero = C->isNullValue();1413bool isUndef = isa<UndefValue>(C);1414bool isPoison = isa<PoisonValue>(C);1415bool isSplatFP = UseConstantFPForFixedLengthSplat && isa<ConstantFP>(C);1416bool isSplatInt = UseConstantIntForFixedLengthSplat && isa<ConstantInt>(C);14171418if (isZero || isUndef || isSplatFP || isSplatInt) {1419for (unsigned i = 1, e = V.size(); i != e; ++i)1420if (V[i] != C) {1421isZero = isUndef = isPoison = isSplatFP = isSplatInt = false;1422break;1423}1424}14251426if (isZero)1427return ConstantAggregateZero::get(T);1428if (isPoison)1429return PoisonValue::get(T);1430if (isUndef)1431return UndefValue::get(T);1432if (isSplatFP)1433return ConstantFP::get(C->getContext(), T->getElementCount(),1434cast<ConstantFP>(C)->getValue());1435if (isSplatInt)1436return ConstantInt::get(C->getContext(), T->getElementCount(),1437cast<ConstantInt>(C)->getValue());14381439// Check to see if all of the elements are ConstantFP or ConstantInt and if1440// the element type is compatible with ConstantDataVector. If so, use it.1441if (ConstantDataSequential::isElementTypeCompatible(C->getType()))1442return getSequenceIfElementsMatch<ConstantDataVector>(C, V);14431444// Otherwise, the element type isn't compatible with ConstantDataVector, or1445// the operand list contains a ConstantExpr or something else strange.1446return nullptr;1447}14481449Constant *ConstantVector::getSplat(ElementCount EC, Constant *V) {1450if (!EC.isScalable()) {1451// Maintain special handling of zero.1452if (!V->isNullValue()) {1453if (UseConstantIntForFixedLengthSplat && isa<ConstantInt>(V))1454return ConstantInt::get(V->getContext(), EC,1455cast<ConstantInt>(V)->getValue());1456if (UseConstantFPForFixedLengthSplat && isa<ConstantFP>(V))1457return ConstantFP::get(V->getContext(), EC,1458cast<ConstantFP>(V)->getValue());1459}14601461// If this splat is compatible with ConstantDataVector, use it instead of1462// ConstantVector.1463if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&1464ConstantDataSequential::isElementTypeCompatible(V->getType()))1465return ConstantDataVector::getSplat(EC.getKnownMinValue(), V);14661467SmallVector<Constant *, 32> Elts(EC.getKnownMinValue(), V);1468return get(Elts);1469}14701471// Maintain special handling of zero.1472if (!V->isNullValue()) {1473if (UseConstantIntForScalableSplat && isa<ConstantInt>(V))1474return ConstantInt::get(V->getContext(), EC,1475cast<ConstantInt>(V)->getValue());1476if (UseConstantFPForScalableSplat && isa<ConstantFP>(V))1477return ConstantFP::get(V->getContext(), EC,1478cast<ConstantFP>(V)->getValue());1479}14801481Type *VTy = VectorType::get(V->getType(), EC);14821483if (V->isNullValue())1484return ConstantAggregateZero::get(VTy);1485else if (isa<UndefValue>(V))1486return UndefValue::get(VTy);14871488Type *IdxTy = Type::getInt64Ty(VTy->getContext());14891490// Move scalar into vector.1491Constant *PoisonV = PoisonValue::get(VTy);1492V = ConstantExpr::getInsertElement(PoisonV, V, ConstantInt::get(IdxTy, 0));1493// Build shuffle mask to perform the splat.1494SmallVector<int, 8> Zeros(EC.getKnownMinValue(), 0);1495// Splat.1496return ConstantExpr::getShuffleVector(V, PoisonV, Zeros);1497}14981499ConstantTokenNone *ConstantTokenNone::get(LLVMContext &Context) {1500LLVMContextImpl *pImpl = Context.pImpl;1501if (!pImpl->TheNoneToken)1502pImpl->TheNoneToken.reset(new ConstantTokenNone(Context));1503return pImpl->TheNoneToken.get();1504}15051506/// Remove the constant from the constant table.1507void ConstantTokenNone::destroyConstantImpl() {1508llvm_unreachable("You can't ConstantTokenNone->destroyConstantImpl()!");1509}15101511// Utility function for determining if a ConstantExpr is a CastOp or not. This1512// can't be inline because we don't want to #include Instruction.h into1513// Constant.h1514bool ConstantExpr::isCast() const { return Instruction::isCast(getOpcode()); }15151516ArrayRef<int> ConstantExpr::getShuffleMask() const {1517return cast<ShuffleVectorConstantExpr>(this)->ShuffleMask;1518}15191520Constant *ConstantExpr::getShuffleMaskForBitcode() const {1521return cast<ShuffleVectorConstantExpr>(this)->ShuffleMaskForBitcode;1522}15231524Constant *ConstantExpr::getWithOperands(ArrayRef<Constant *> Ops, Type *Ty,1525bool OnlyIfReduced, Type *SrcTy) const {1526assert(Ops.size() == getNumOperands() && "Operand count mismatch!");15271528// If no operands changed return self.1529if (Ty == getType() && std::equal(Ops.begin(), Ops.end(), op_begin()))1530return const_cast<ConstantExpr*>(this);15311532Type *OnlyIfReducedTy = OnlyIfReduced ? Ty : nullptr;1533switch (getOpcode()) {1534case Instruction::Trunc:1535case Instruction::ZExt:1536case Instruction::SExt:1537case Instruction::FPTrunc:1538case Instruction::FPExt:1539case Instruction::UIToFP:1540case Instruction::SIToFP:1541case Instruction::FPToUI:1542case Instruction::FPToSI:1543case Instruction::PtrToInt:1544case Instruction::IntToPtr:1545case Instruction::BitCast:1546case Instruction::AddrSpaceCast:1547return ConstantExpr::getCast(getOpcode(), Ops[0], Ty, OnlyIfReduced);1548case Instruction::InsertElement:1549return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2],1550OnlyIfReducedTy);1551case Instruction::ExtractElement:1552return ConstantExpr::getExtractElement(Ops[0], Ops[1], OnlyIfReducedTy);1553case Instruction::ShuffleVector:1554return ConstantExpr::getShuffleVector(Ops[0], Ops[1], getShuffleMask(),1555OnlyIfReducedTy);1556case Instruction::GetElementPtr: {1557auto *GEPO = cast<GEPOperator>(this);1558assert(SrcTy || (Ops[0]->getType() == getOperand(0)->getType()));1559return ConstantExpr::getGetElementPtr(1560SrcTy ? SrcTy : GEPO->getSourceElementType(), Ops[0], Ops.slice(1),1561GEPO->getNoWrapFlags(), GEPO->getInRange(), OnlyIfReducedTy);1562}1563default:1564assert(getNumOperands() == 2 && "Must be binary operator?");1565return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData,1566OnlyIfReducedTy);1567}1568}156915701571//===----------------------------------------------------------------------===//1572// isValueValidForType implementations15731574bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {1575unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay1576if (Ty->isIntegerTy(1))1577return Val == 0 || Val == 1;1578return isUIntN(NumBits, Val);1579}15801581bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {1582unsigned NumBits = Ty->getIntegerBitWidth();1583if (Ty->isIntegerTy(1))1584return Val == 0 || Val == 1 || Val == -1;1585return isIntN(NumBits, Val);1586}15871588bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {1589// convert modifies in place, so make a copy.1590APFloat Val2 = APFloat(Val);1591bool losesInfo;1592switch (Ty->getTypeID()) {1593default:1594return false; // These can't be represented as floating point!15951596// FIXME rounding mode needs to be more flexible1597case Type::HalfTyID: {1598if (&Val2.getSemantics() == &APFloat::IEEEhalf())1599return true;1600Val2.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &losesInfo);1601return !losesInfo;1602}1603case Type::BFloatTyID: {1604if (&Val2.getSemantics() == &APFloat::BFloat())1605return true;1606Val2.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven, &losesInfo);1607return !losesInfo;1608}1609case Type::FloatTyID: {1610if (&Val2.getSemantics() == &APFloat::IEEEsingle())1611return true;1612Val2.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &losesInfo);1613return !losesInfo;1614}1615case Type::DoubleTyID: {1616if (&Val2.getSemantics() == &APFloat::IEEEhalf() ||1617&Val2.getSemantics() == &APFloat::BFloat() ||1618&Val2.getSemantics() == &APFloat::IEEEsingle() ||1619&Val2.getSemantics() == &APFloat::IEEEdouble())1620return true;1621Val2.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &losesInfo);1622return !losesInfo;1623}1624case Type::X86_FP80TyID:1625return &Val2.getSemantics() == &APFloat::IEEEhalf() ||1626&Val2.getSemantics() == &APFloat::BFloat() ||1627&Val2.getSemantics() == &APFloat::IEEEsingle() ||1628&Val2.getSemantics() == &APFloat::IEEEdouble() ||1629&Val2.getSemantics() == &APFloat::x87DoubleExtended();1630case Type::FP128TyID:1631return &Val2.getSemantics() == &APFloat::IEEEhalf() ||1632&Val2.getSemantics() == &APFloat::BFloat() ||1633&Val2.getSemantics() == &APFloat::IEEEsingle() ||1634&Val2.getSemantics() == &APFloat::IEEEdouble() ||1635&Val2.getSemantics() == &APFloat::IEEEquad();1636case Type::PPC_FP128TyID:1637return &Val2.getSemantics() == &APFloat::IEEEhalf() ||1638&Val2.getSemantics() == &APFloat::BFloat() ||1639&Val2.getSemantics() == &APFloat::IEEEsingle() ||1640&Val2.getSemantics() == &APFloat::IEEEdouble() ||1641&Val2.getSemantics() == &APFloat::PPCDoubleDouble();1642}1643}164416451646//===----------------------------------------------------------------------===//1647// Factory Function Implementation16481649ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {1650assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&1651"Cannot create an aggregate zero of non-aggregate type!");16521653std::unique_ptr<ConstantAggregateZero> &Entry =1654Ty->getContext().pImpl->CAZConstants[Ty];1655if (!Entry)1656Entry.reset(new ConstantAggregateZero(Ty));16571658return Entry.get();1659}16601661/// Remove the constant from the constant table.1662void ConstantAggregateZero::destroyConstantImpl() {1663getContext().pImpl->CAZConstants.erase(getType());1664}16651666/// Remove the constant from the constant table.1667void ConstantArray::destroyConstantImpl() {1668getType()->getContext().pImpl->ArrayConstants.remove(this);1669}167016711672//---- ConstantStruct::get() implementation...1673//16741675/// Remove the constant from the constant table.1676void ConstantStruct::destroyConstantImpl() {1677getType()->getContext().pImpl->StructConstants.remove(this);1678}16791680/// Remove the constant from the constant table.1681void ConstantVector::destroyConstantImpl() {1682getType()->getContext().pImpl->VectorConstants.remove(this);1683}16841685Constant *Constant::getSplatValue(bool AllowPoison) const {1686assert(this->getType()->isVectorTy() && "Only valid for vectors!");1687if (isa<ConstantAggregateZero>(this))1688return getNullValue(cast<VectorType>(getType())->getElementType());1689if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))1690return CV->getSplatValue();1691if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))1692return CV->getSplatValue(AllowPoison);16931694// Check if this is a constant expression splat of the form returned by1695// ConstantVector::getSplat()1696const auto *Shuf = dyn_cast<ConstantExpr>(this);1697if (Shuf && Shuf->getOpcode() == Instruction::ShuffleVector &&1698isa<UndefValue>(Shuf->getOperand(1))) {16991700const auto *IElt = dyn_cast<ConstantExpr>(Shuf->getOperand(0));1701if (IElt && IElt->getOpcode() == Instruction::InsertElement &&1702isa<UndefValue>(IElt->getOperand(0))) {17031704ArrayRef<int> Mask = Shuf->getShuffleMask();1705Constant *SplatVal = IElt->getOperand(1);1706ConstantInt *Index = dyn_cast<ConstantInt>(IElt->getOperand(2));17071708if (Index && Index->getValue() == 0 &&1709llvm::all_of(Mask, [](int I) { return I == 0; }))1710return SplatVal;1711}1712}17131714return nullptr;1715}17161717Constant *ConstantVector::getSplatValue(bool AllowPoison) const {1718// Check out first element.1719Constant *Elt = getOperand(0);1720// Then make sure all remaining elements point to the same value.1721for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {1722Constant *OpC = getOperand(I);1723if (OpC == Elt)1724continue;17251726// Strict mode: any mismatch is not a splat.1727if (!AllowPoison)1728return nullptr;17291730// Allow poison mode: ignore poison elements.1731if (isa<PoisonValue>(OpC))1732continue;17331734// If we do not have a defined element yet, use the current operand.1735if (isa<PoisonValue>(Elt))1736Elt = OpC;17371738if (OpC != Elt)1739return nullptr;1740}1741return Elt;1742}17431744const APInt &Constant::getUniqueInteger() const {1745if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))1746return CI->getValue();1747// Scalable vectors can use a ConstantExpr to build a splat.1748if (isa<ConstantExpr>(this))1749return cast<ConstantInt>(this->getSplatValue())->getValue();1750// For non-ConstantExpr we use getAggregateElement as a fast path to avoid1751// calling getSplatValue in release builds.1752assert(this->getSplatValue() && "Doesn't contain a unique integer!");1753const Constant *C = this->getAggregateElement(0U);1754assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");1755return cast<ConstantInt>(C)->getValue();1756}17571758ConstantRange Constant::toConstantRange() const {1759if (auto *CI = dyn_cast<ConstantInt>(this))1760return ConstantRange(CI->getValue());17611762unsigned BitWidth = getType()->getScalarSizeInBits();1763if (!getType()->isVectorTy())1764return ConstantRange::getFull(BitWidth);17651766if (auto *CI = dyn_cast_or_null<ConstantInt>(1767getSplatValue(/*AllowPoison=*/true)))1768return ConstantRange(CI->getValue());17691770if (auto *CDV = dyn_cast<ConstantDataVector>(this)) {1771ConstantRange CR = ConstantRange::getEmpty(BitWidth);1772for (unsigned I = 0, E = CDV->getNumElements(); I < E; ++I)1773CR = CR.unionWith(CDV->getElementAsAPInt(I));1774return CR;1775}17761777if (auto *CV = dyn_cast<ConstantVector>(this)) {1778ConstantRange CR = ConstantRange::getEmpty(BitWidth);1779for (unsigned I = 0, E = CV->getNumOperands(); I < E; ++I) {1780Constant *Elem = CV->getOperand(I);1781if (!Elem)1782return ConstantRange::getFull(BitWidth);1783if (isa<PoisonValue>(Elem))1784continue;1785auto *CI = dyn_cast<ConstantInt>(Elem);1786if (!CI)1787return ConstantRange::getFull(BitWidth);1788CR = CR.unionWith(CI->getValue());1789}1790return CR;1791}17921793return ConstantRange::getFull(BitWidth);1794}17951796//---- ConstantPointerNull::get() implementation.1797//17981799ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {1800std::unique_ptr<ConstantPointerNull> &Entry =1801Ty->getContext().pImpl->CPNConstants[Ty];1802if (!Entry)1803Entry.reset(new ConstantPointerNull(Ty));18041805return Entry.get();1806}18071808/// Remove the constant from the constant table.1809void ConstantPointerNull::destroyConstantImpl() {1810getContext().pImpl->CPNConstants.erase(getType());1811}18121813//---- ConstantTargetNone::get() implementation.1814//18151816ConstantTargetNone *ConstantTargetNone::get(TargetExtType *Ty) {1817assert(Ty->hasProperty(TargetExtType::HasZeroInit) &&1818"Target extension type not allowed to have a zeroinitializer");1819std::unique_ptr<ConstantTargetNone> &Entry =1820Ty->getContext().pImpl->CTNConstants[Ty];1821if (!Entry)1822Entry.reset(new ConstantTargetNone(Ty));18231824return Entry.get();1825}18261827/// Remove the constant from the constant table.1828void ConstantTargetNone::destroyConstantImpl() {1829getContext().pImpl->CTNConstants.erase(getType());1830}18311832UndefValue *UndefValue::get(Type *Ty) {1833std::unique_ptr<UndefValue> &Entry = Ty->getContext().pImpl->UVConstants[Ty];1834if (!Entry)1835Entry.reset(new UndefValue(Ty));18361837return Entry.get();1838}18391840/// Remove the constant from the constant table.1841void UndefValue::destroyConstantImpl() {1842// Free the constant and any dangling references to it.1843if (getValueID() == UndefValueVal) {1844getContext().pImpl->UVConstants.erase(getType());1845} else if (getValueID() == PoisonValueVal) {1846getContext().pImpl->PVConstants.erase(getType());1847}1848llvm_unreachable("Not a undef or a poison!");1849}18501851PoisonValue *PoisonValue::get(Type *Ty) {1852std::unique_ptr<PoisonValue> &Entry = Ty->getContext().pImpl->PVConstants[Ty];1853if (!Entry)1854Entry.reset(new PoisonValue(Ty));18551856return Entry.get();1857}18581859/// Remove the constant from the constant table.1860void PoisonValue::destroyConstantImpl() {1861// Free the constant and any dangling references to it.1862getContext().pImpl->PVConstants.erase(getType());1863}18641865BlockAddress *BlockAddress::get(BasicBlock *BB) {1866assert(BB->getParent() && "Block must have a parent");1867return get(BB->getParent(), BB);1868}18691870BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {1871BlockAddress *&BA =1872F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];1873if (!BA)1874BA = new BlockAddress(F, BB);18751876assert(BA->getFunction() == F && "Basic block moved between functions");1877return BA;1878}18791880BlockAddress::BlockAddress(Function *F, BasicBlock *BB)1881: Constant(PointerType::get(F->getContext(), F->getAddressSpace()),1882Value::BlockAddressVal, &Op<0>(), 2) {1883setOperand(0, F);1884setOperand(1, BB);1885BB->AdjustBlockAddressRefCount(1);1886}18871888BlockAddress *BlockAddress::lookup(const BasicBlock *BB) {1889if (!BB->hasAddressTaken())1890return nullptr;18911892const Function *F = BB->getParent();1893assert(F && "Block must have a parent");1894BlockAddress *BA =1895F->getContext().pImpl->BlockAddresses.lookup(std::make_pair(F, BB));1896assert(BA && "Refcount and block address map disagree!");1897return BA;1898}18991900/// Remove the constant from the constant table.1901void BlockAddress::destroyConstantImpl() {1902getFunction()->getType()->getContext().pImpl1903->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));1904getBasicBlock()->AdjustBlockAddressRefCount(-1);1905}19061907Value *BlockAddress::handleOperandChangeImpl(Value *From, Value *To) {1908// This could be replacing either the Basic Block or the Function. In either1909// case, we have to remove the map entry.1910Function *NewF = getFunction();1911BasicBlock *NewBB = getBasicBlock();19121913if (From == NewF)1914NewF = cast<Function>(To->stripPointerCasts());1915else {1916assert(From == NewBB && "From does not match any operand");1917NewBB = cast<BasicBlock>(To);1918}19191920// See if the 'new' entry already exists, if not, just update this in place1921// and return early.1922BlockAddress *&NewBA =1923getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];1924if (NewBA)1925return NewBA;19261927getBasicBlock()->AdjustBlockAddressRefCount(-1);19281929// Remove the old entry, this can't cause the map to rehash (just a1930// tombstone will get added).1931getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),1932getBasicBlock()));1933NewBA = this;1934setOperand(0, NewF);1935setOperand(1, NewBB);1936getBasicBlock()->AdjustBlockAddressRefCount(1);19371938// If we just want to keep the existing value, then return null.1939// Callers know that this means we shouldn't delete this value.1940return nullptr;1941}19421943DSOLocalEquivalent *DSOLocalEquivalent::get(GlobalValue *GV) {1944DSOLocalEquivalent *&Equiv = GV->getContext().pImpl->DSOLocalEquivalents[GV];1945if (!Equiv)1946Equiv = new DSOLocalEquivalent(GV);19471948assert(Equiv->getGlobalValue() == GV &&1949"DSOLocalFunction does not match the expected global value");1950return Equiv;1951}19521953DSOLocalEquivalent::DSOLocalEquivalent(GlobalValue *GV)1954: Constant(GV->getType(), Value::DSOLocalEquivalentVal, &Op<0>(), 1) {1955setOperand(0, GV);1956}19571958/// Remove the constant from the constant table.1959void DSOLocalEquivalent::destroyConstantImpl() {1960const GlobalValue *GV = getGlobalValue();1961GV->getContext().pImpl->DSOLocalEquivalents.erase(GV);1962}19631964Value *DSOLocalEquivalent::handleOperandChangeImpl(Value *From, Value *To) {1965assert(From == getGlobalValue() && "Changing value does not match operand.");1966assert(isa<Constant>(To) && "Can only replace the operands with a constant");19671968// The replacement is with another global value.1969if (const auto *ToObj = dyn_cast<GlobalValue>(To)) {1970DSOLocalEquivalent *&NewEquiv =1971getContext().pImpl->DSOLocalEquivalents[ToObj];1972if (NewEquiv)1973return llvm::ConstantExpr::getBitCast(NewEquiv, getType());1974}19751976// If the argument is replaced with a null value, just replace this constant1977// with a null value.1978if (cast<Constant>(To)->isNullValue())1979return To;19801981// The replacement could be a bitcast or an alias to another function. We can1982// replace it with a bitcast to the dso_local_equivalent of that function.1983auto *Func = cast<Function>(To->stripPointerCastsAndAliases());1984DSOLocalEquivalent *&NewEquiv = getContext().pImpl->DSOLocalEquivalents[Func];1985if (NewEquiv)1986return llvm::ConstantExpr::getBitCast(NewEquiv, getType());19871988// Replace this with the new one.1989getContext().pImpl->DSOLocalEquivalents.erase(getGlobalValue());1990NewEquiv = this;1991setOperand(0, Func);19921993if (Func->getType() != getType()) {1994// It is ok to mutate the type here because this constant should always1995// reflect the type of the function it's holding.1996mutateType(Func->getType());1997}1998return nullptr;1999}20002001NoCFIValue *NoCFIValue::get(GlobalValue *GV) {2002NoCFIValue *&NC = GV->getContext().pImpl->NoCFIValues[GV];2003if (!NC)2004NC = new NoCFIValue(GV);20052006assert(NC->getGlobalValue() == GV &&2007"NoCFIValue does not match the expected global value");2008return NC;2009}20102011NoCFIValue::NoCFIValue(GlobalValue *GV)2012: Constant(GV->getType(), Value::NoCFIValueVal, &Op<0>(), 1) {2013setOperand(0, GV);2014}20152016/// Remove the constant from the constant table.2017void NoCFIValue::destroyConstantImpl() {2018const GlobalValue *GV = getGlobalValue();2019GV->getContext().pImpl->NoCFIValues.erase(GV);2020}20212022Value *NoCFIValue::handleOperandChangeImpl(Value *From, Value *To) {2023assert(From == getGlobalValue() && "Changing value does not match operand.");20242025GlobalValue *GV = dyn_cast<GlobalValue>(To->stripPointerCasts());2026assert(GV && "Can only replace the operands with a global value");20272028NoCFIValue *&NewNC = getContext().pImpl->NoCFIValues[GV];2029if (NewNC)2030return llvm::ConstantExpr::getBitCast(NewNC, getType());20312032getContext().pImpl->NoCFIValues.erase(getGlobalValue());2033NewNC = this;2034setOperand(0, GV);20352036if (GV->getType() != getType())2037mutateType(GV->getType());20382039return nullptr;2040}20412042//---- ConstantPtrAuth::get() implementations.2043//20442045ConstantPtrAuth *ConstantPtrAuth::get(Constant *Ptr, ConstantInt *Key,2046ConstantInt *Disc, Constant *AddrDisc) {2047Constant *ArgVec[] = {Ptr, Key, Disc, AddrDisc};2048ConstantPtrAuthKeyType MapKey(ArgVec);2049LLVMContextImpl *pImpl = Ptr->getContext().pImpl;2050return pImpl->ConstantPtrAuths.getOrCreate(Ptr->getType(), MapKey);2051}20522053ConstantPtrAuth *ConstantPtrAuth::getWithSameSchema(Constant *Pointer) const {2054return get(Pointer, getKey(), getDiscriminator(), getAddrDiscriminator());2055}20562057ConstantPtrAuth::ConstantPtrAuth(Constant *Ptr, ConstantInt *Key,2058ConstantInt *Disc, Constant *AddrDisc)2059: Constant(Ptr->getType(), Value::ConstantPtrAuthVal, &Op<0>(), 4) {2060assert(Ptr->getType()->isPointerTy());2061assert(Key->getBitWidth() == 32);2062assert(Disc->getBitWidth() == 64);2063assert(AddrDisc->getType()->isPointerTy());2064setOperand(0, Ptr);2065setOperand(1, Key);2066setOperand(2, Disc);2067setOperand(3, AddrDisc);2068}20692070/// Remove the constant from the constant table.2071void ConstantPtrAuth::destroyConstantImpl() {2072getType()->getContext().pImpl->ConstantPtrAuths.remove(this);2073}20742075Value *ConstantPtrAuth::handleOperandChangeImpl(Value *From, Value *ToV) {2076assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");2077Constant *To = cast<Constant>(ToV);20782079SmallVector<Constant *, 4> Values;2080Values.reserve(getNumOperands());20812082unsigned NumUpdated = 0;20832084Use *OperandList = getOperandList();2085unsigned OperandNo = 0;2086for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) {2087Constant *Val = cast<Constant>(O->get());2088if (Val == From) {2089OperandNo = (O - OperandList);2090Val = To;2091++NumUpdated;2092}2093Values.push_back(Val);2094}20952096return getContext().pImpl->ConstantPtrAuths.replaceOperandsInPlace(2097Values, this, From, To, NumUpdated, OperandNo);2098}20992100bool ConstantPtrAuth::isKnownCompatibleWith(const Value *Key,2101const Value *Discriminator,2102const DataLayout &DL) const {2103// If the keys are different, there's no chance for this to be compatible.2104if (getKey() != Key)2105return false;21062107// We can have 3 kinds of discriminators:2108// - simple, integer-only: `i64 x, ptr null` vs. `i64 x`2109// - address-only: `i64 0, ptr p` vs. `ptr p`2110// - blended address/integer: `i64 x, ptr p` vs. `@llvm.ptrauth.blend(p, x)`21112112// If this constant has a simple discriminator (integer, no address), easy:2113// it's compatible iff the provided full discriminator is also a simple2114// discriminator, identical to our integer discriminator.2115if (!hasAddressDiscriminator())2116return getDiscriminator() == Discriminator;21172118// Otherwise, we can isolate address and integer discriminator components.2119const Value *AddrDiscriminator = nullptr;21202121// This constant may or may not have an integer discriminator (instead of 0).2122if (!getDiscriminator()->isNullValue()) {2123// If it does, there's an implicit blend. We need to have a matching blend2124// intrinsic in the provided full discriminator.2125if (!match(Discriminator,2126m_Intrinsic<Intrinsic::ptrauth_blend>(2127m_Value(AddrDiscriminator), m_Specific(getDiscriminator()))))2128return false;2129} else {2130// Otherwise, interpret the provided full discriminator as address-only.2131AddrDiscriminator = Discriminator;2132}21332134// Either way, we can now focus on comparing the address discriminators.21352136// Discriminators are i64, so the provided addr disc may be a ptrtoint.2137if (auto *Cast = dyn_cast<PtrToIntOperator>(AddrDiscriminator))2138AddrDiscriminator = Cast->getPointerOperand();21392140// Beyond that, we're only interested in compatible pointers.2141if (getAddrDiscriminator()->getType() != AddrDiscriminator->getType())2142return false;21432144// These are often the same constant GEP, making them trivially equivalent.2145if (getAddrDiscriminator() == AddrDiscriminator)2146return true;21472148// Finally, they may be equivalent base+offset expressions.2149APInt Off1(DL.getIndexTypeSizeInBits(getAddrDiscriminator()->getType()), 0);2150auto *Base1 = getAddrDiscriminator()->stripAndAccumulateConstantOffsets(2151DL, Off1, /*AllowNonInbounds=*/true);21522153APInt Off2(DL.getIndexTypeSizeInBits(AddrDiscriminator->getType()), 0);2154auto *Base2 = AddrDiscriminator->stripAndAccumulateConstantOffsets(2155DL, Off2, /*AllowNonInbounds=*/true);21562157return Base1 == Base2 && Off1 == Off2;2158}21592160//---- ConstantExpr::get() implementations.2161//21622163/// This is a utility function to handle folding of casts and lookup of the2164/// cast in the ExprConstants map. It is used by the various get* methods below.2165static Constant *getFoldedCast(Instruction::CastOps opc, Constant *C, Type *Ty,2166bool OnlyIfReduced = false) {2167assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");2168// Fold a few common cases2169if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))2170return FC;21712172if (OnlyIfReduced)2173return nullptr;21742175LLVMContextImpl *pImpl = Ty->getContext().pImpl;21762177// Look up the constant in the table first to ensure uniqueness.2178ConstantExprKeyType Key(opc, C);21792180return pImpl->ExprConstants.getOrCreate(Ty, Key);2181}21822183Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty,2184bool OnlyIfReduced) {2185Instruction::CastOps opc = Instruction::CastOps(oc);2186assert(Instruction::isCast(opc) && "opcode out of range");2187assert(isSupportedCastOp(opc) &&2188"Cast opcode not supported as constant expression");2189assert(C && Ty && "Null arguments to getCast");2190assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");21912192switch (opc) {2193default:2194llvm_unreachable("Invalid cast opcode");2195case Instruction::Trunc:2196return getTrunc(C, Ty, OnlyIfReduced);2197case Instruction::PtrToInt:2198return getPtrToInt(C, Ty, OnlyIfReduced);2199case Instruction::IntToPtr:2200return getIntToPtr(C, Ty, OnlyIfReduced);2201case Instruction::BitCast:2202return getBitCast(C, Ty, OnlyIfReduced);2203case Instruction::AddrSpaceCast:2204return getAddrSpaceCast(C, Ty, OnlyIfReduced);2205}2206}22072208Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {2209if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())2210return getBitCast(C, Ty);2211return getTrunc(C, Ty);2212}22132214Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {2215assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");2216assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&2217"Invalid cast");22182219if (Ty->isIntOrIntVectorTy())2220return getPtrToInt(S, Ty);22212222unsigned SrcAS = S->getType()->getPointerAddressSpace();2223if (Ty->isPtrOrPtrVectorTy() && SrcAS != Ty->getPointerAddressSpace())2224return getAddrSpaceCast(S, Ty);22252226return getBitCast(S, Ty);2227}22282229Constant *ConstantExpr::getPointerBitCastOrAddrSpaceCast(Constant *S,2230Type *Ty) {2231assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");2232assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");22332234if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())2235return getAddrSpaceCast(S, Ty);22362237return getBitCast(S, Ty);2238}22392240Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {2241#ifndef NDEBUG2242bool fromVec = isa<VectorType>(C->getType());2243bool toVec = isa<VectorType>(Ty);2244#endif2245assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");2246assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");2247assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");2248assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&2249"SrcTy must be larger than DestTy for Trunc!");22502251return getFoldedCast(Instruction::Trunc, C, Ty, OnlyIfReduced);2252}22532254Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy,2255bool OnlyIfReduced) {2256assert(C->getType()->isPtrOrPtrVectorTy() &&2257"PtrToInt source must be pointer or pointer vector");2258assert(DstTy->isIntOrIntVectorTy() &&2259"PtrToInt destination must be integer or integer vector");2260assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));2261if (isa<VectorType>(C->getType()))2262assert(cast<VectorType>(C->getType())->getElementCount() ==2263cast<VectorType>(DstTy)->getElementCount() &&2264"Invalid cast between a different number of vector elements");2265return getFoldedCast(Instruction::PtrToInt, C, DstTy, OnlyIfReduced);2266}22672268Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy,2269bool OnlyIfReduced) {2270assert(C->getType()->isIntOrIntVectorTy() &&2271"IntToPtr source must be integer or integer vector");2272assert(DstTy->isPtrOrPtrVectorTy() &&2273"IntToPtr destination must be a pointer or pointer vector");2274assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));2275if (isa<VectorType>(C->getType()))2276assert(cast<VectorType>(C->getType())->getElementCount() ==2277cast<VectorType>(DstTy)->getElementCount() &&2278"Invalid cast between a different number of vector elements");2279return getFoldedCast(Instruction::IntToPtr, C, DstTy, OnlyIfReduced);2280}22812282Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy,2283bool OnlyIfReduced) {2284assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&2285"Invalid constantexpr bitcast!");22862287// It is common to ask for a bitcast of a value to its own type, handle this2288// speedily.2289if (C->getType() == DstTy) return C;22902291return getFoldedCast(Instruction::BitCast, C, DstTy, OnlyIfReduced);2292}22932294Constant *ConstantExpr::getAddrSpaceCast(Constant *C, Type *DstTy,2295bool OnlyIfReduced) {2296assert(CastInst::castIsValid(Instruction::AddrSpaceCast, C, DstTy) &&2297"Invalid constantexpr addrspacecast!");2298return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced);2299}23002301Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,2302unsigned Flags, Type *OnlyIfReducedTy) {2303// Check the operands for consistency first.2304assert(Instruction::isBinaryOp(Opcode) &&2305"Invalid opcode in binary constant expression");2306assert(isSupportedBinOp(Opcode) &&2307"Binop not supported as constant expression");2308assert(C1->getType() == C2->getType() &&2309"Operand types in binary constant expression should match");23102311#ifndef NDEBUG2312switch (Opcode) {2313case Instruction::Add:2314case Instruction::Sub:2315case Instruction::Mul:2316assert(C1->getType()->isIntOrIntVectorTy() &&2317"Tried to create an integer operation on a non-integer type!");2318break;2319case Instruction::And:2320case Instruction::Or:2321case Instruction::Xor:2322assert(C1->getType()->isIntOrIntVectorTy() &&2323"Tried to create a logical operation on a non-integral type!");2324break;2325default:2326break;2327}2328#endif23292330if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))2331return FC;23322333if (OnlyIfReducedTy == C1->getType())2334return nullptr;23352336Constant *ArgVec[] = {C1, C2};2337ConstantExprKeyType Key(Opcode, ArgVec, Flags);23382339LLVMContextImpl *pImpl = C1->getContext().pImpl;2340return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);2341}23422343bool ConstantExpr::isDesirableBinOp(unsigned Opcode) {2344switch (Opcode) {2345case Instruction::UDiv:2346case Instruction::SDiv:2347case Instruction::URem:2348case Instruction::SRem:2349case Instruction::FAdd:2350case Instruction::FSub:2351case Instruction::FMul:2352case Instruction::FDiv:2353case Instruction::FRem:2354case Instruction::And:2355case Instruction::Or:2356case Instruction::LShr:2357case Instruction::AShr:2358case Instruction::Shl:2359return false;2360case Instruction::Add:2361case Instruction::Sub:2362case Instruction::Mul:2363case Instruction::Xor:2364return true;2365default:2366llvm_unreachable("Argument must be binop opcode");2367}2368}23692370bool ConstantExpr::isSupportedBinOp(unsigned Opcode) {2371switch (Opcode) {2372case Instruction::UDiv:2373case Instruction::SDiv:2374case Instruction::URem:2375case Instruction::SRem:2376case Instruction::FAdd:2377case Instruction::FSub:2378case Instruction::FMul:2379case Instruction::FDiv:2380case Instruction::FRem:2381case Instruction::And:2382case Instruction::Or:2383case Instruction::LShr:2384case Instruction::AShr:2385case Instruction::Shl:2386return false;2387case Instruction::Add:2388case Instruction::Sub:2389case Instruction::Mul:2390case Instruction::Xor:2391return true;2392default:2393llvm_unreachable("Argument must be binop opcode");2394}2395}23962397bool ConstantExpr::isDesirableCastOp(unsigned Opcode) {2398switch (Opcode) {2399case Instruction::ZExt:2400case Instruction::SExt:2401case Instruction::FPTrunc:2402case Instruction::FPExt:2403case Instruction::UIToFP:2404case Instruction::SIToFP:2405case Instruction::FPToUI:2406case Instruction::FPToSI:2407return false;2408case Instruction::Trunc:2409case Instruction::PtrToInt:2410case Instruction::IntToPtr:2411case Instruction::BitCast:2412case Instruction::AddrSpaceCast:2413return true;2414default:2415llvm_unreachable("Argument must be cast opcode");2416}2417}24182419bool ConstantExpr::isSupportedCastOp(unsigned Opcode) {2420switch (Opcode) {2421case Instruction::ZExt:2422case Instruction::SExt:2423case Instruction::FPTrunc:2424case Instruction::FPExt:2425case Instruction::UIToFP:2426case Instruction::SIToFP:2427case Instruction::FPToUI:2428case Instruction::FPToSI:2429return false;2430case Instruction::Trunc:2431case Instruction::PtrToInt:2432case Instruction::IntToPtr:2433case Instruction::BitCast:2434case Instruction::AddrSpaceCast:2435return true;2436default:2437llvm_unreachable("Argument must be cast opcode");2438}2439}24402441Constant *ConstantExpr::getSizeOf(Type* Ty) {2442// sizeof is implemented as: (i64) gep (Ty*)null, 12443// Note that a non-inbounds gep is used, as null isn't within any object.2444Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);2445Constant *GEP = getGetElementPtr(2446Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);2447return getPtrToInt(GEP,2448Type::getInt64Ty(Ty->getContext()));2449}24502451Constant *ConstantExpr::getAlignOf(Type* Ty) {2452// alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 12453// Note that a non-inbounds gep is used, as null isn't within any object.2454Type *AligningTy = StructType::get(Type::getInt1Ty(Ty->getContext()), Ty);2455Constant *NullPtr =2456Constant::getNullValue(PointerType::getUnqual(AligningTy->getContext()));2457Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);2458Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);2459Constant *Indices[2] = {Zero, One};2460Constant *GEP = getGetElementPtr(AligningTy, NullPtr, Indices);2461return getPtrToInt(GEP, Type::getInt64Ty(Ty->getContext()));2462}24632464Constant *ConstantExpr::getGetElementPtr(Type *Ty, Constant *C,2465ArrayRef<Value *> Idxs,2466GEPNoWrapFlags NW,2467std::optional<ConstantRange> InRange,2468Type *OnlyIfReducedTy) {2469assert(Ty && "Must specify element type");2470assert(isSupportedGetElementPtr(Ty) && "Element type is unsupported!");24712472if (Constant *FC = ConstantFoldGetElementPtr(Ty, C, InRange, Idxs))2473return FC; // Fold a few common cases.24742475assert(GetElementPtrInst::getIndexedType(Ty, Idxs) && "GEP indices invalid!");2476;24772478// Get the result type of the getelementptr!2479Type *ReqTy = GetElementPtrInst::getGEPReturnType(C, Idxs);2480if (OnlyIfReducedTy == ReqTy)2481return nullptr;24822483auto EltCount = ElementCount::getFixed(0);2484if (VectorType *VecTy = dyn_cast<VectorType>(ReqTy))2485EltCount = VecTy->getElementCount();24862487// Look up the constant in the table first to ensure uniqueness2488std::vector<Constant*> ArgVec;2489ArgVec.reserve(1 + Idxs.size());2490ArgVec.push_back(C);2491auto GTI = gep_type_begin(Ty, Idxs), GTE = gep_type_end(Ty, Idxs);2492for (; GTI != GTE; ++GTI) {2493auto *Idx = cast<Constant>(GTI.getOperand());2494assert(2495(!isa<VectorType>(Idx->getType()) ||2496cast<VectorType>(Idx->getType())->getElementCount() == EltCount) &&2497"getelementptr index type missmatch");24982499if (GTI.isStruct() && Idx->getType()->isVectorTy()) {2500Idx = Idx->getSplatValue();2501} else if (GTI.isSequential() && EltCount.isNonZero() &&2502!Idx->getType()->isVectorTy()) {2503Idx = ConstantVector::getSplat(EltCount, Idx);2504}2505ArgVec.push_back(Idx);2506}25072508const ConstantExprKeyType Key(Instruction::GetElementPtr, ArgVec, NW.getRaw(),2509std::nullopt, Ty, InRange);25102511LLVMContextImpl *pImpl = C->getContext().pImpl;2512return pImpl->ExprConstants.getOrCreate(ReqTy, Key);2513}25142515Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx,2516Type *OnlyIfReducedTy) {2517assert(Val->getType()->isVectorTy() &&2518"Tried to create extractelement operation on non-vector type!");2519assert(Idx->getType()->isIntegerTy() &&2520"Extractelement index must be an integer type!");25212522if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))2523return FC; // Fold a few common cases.25242525Type *ReqTy = cast<VectorType>(Val->getType())->getElementType();2526if (OnlyIfReducedTy == ReqTy)2527return nullptr;25282529// Look up the constant in the table first to ensure uniqueness2530Constant *ArgVec[] = { Val, Idx };2531const ConstantExprKeyType Key(Instruction::ExtractElement, ArgVec);25322533LLVMContextImpl *pImpl = Val->getContext().pImpl;2534return pImpl->ExprConstants.getOrCreate(ReqTy, Key);2535}25362537Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,2538Constant *Idx, Type *OnlyIfReducedTy) {2539assert(Val->getType()->isVectorTy() &&2540"Tried to create insertelement operation on non-vector type!");2541assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType() &&2542"Insertelement types must match!");2543assert(Idx->getType()->isIntegerTy() &&2544"Insertelement index must be i32 type!");25452546if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))2547return FC; // Fold a few common cases.25482549if (OnlyIfReducedTy == Val->getType())2550return nullptr;25512552// Look up the constant in the table first to ensure uniqueness2553Constant *ArgVec[] = { Val, Elt, Idx };2554const ConstantExprKeyType Key(Instruction::InsertElement, ArgVec);25552556LLVMContextImpl *pImpl = Val->getContext().pImpl;2557return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);2558}25592560Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,2561ArrayRef<int> Mask,2562Type *OnlyIfReducedTy) {2563assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&2564"Invalid shuffle vector constant expr operands!");25652566if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))2567return FC; // Fold a few common cases.25682569unsigned NElts = Mask.size();2570auto V1VTy = cast<VectorType>(V1->getType());2571Type *EltTy = V1VTy->getElementType();2572bool TypeIsScalable = isa<ScalableVectorType>(V1VTy);2573Type *ShufTy = VectorType::get(EltTy, NElts, TypeIsScalable);25742575if (OnlyIfReducedTy == ShufTy)2576return nullptr;25772578// Look up the constant in the table first to ensure uniqueness2579Constant *ArgVec[] = {V1, V2};2580ConstantExprKeyType Key(Instruction::ShuffleVector, ArgVec, 0, Mask);25812582LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;2583return pImpl->ExprConstants.getOrCreate(ShufTy, Key);2584}25852586Constant *ConstantExpr::getNeg(Constant *C, bool HasNSW) {2587assert(C->getType()->isIntOrIntVectorTy() &&2588"Cannot NEG a nonintegral value!");2589return getSub(ConstantInt::get(C->getType(), 0), C, /*HasNUW=*/false, HasNSW);2590}25912592Constant *ConstantExpr::getNot(Constant *C) {2593assert(C->getType()->isIntOrIntVectorTy() &&2594"Cannot NOT a nonintegral value!");2595return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));2596}25972598Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,2599bool HasNUW, bool HasNSW) {2600unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |2601(HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);2602return get(Instruction::Add, C1, C2, Flags);2603}26042605Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,2606bool HasNUW, bool HasNSW) {2607unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |2608(HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);2609return get(Instruction::Sub, C1, C2, Flags);2610}26112612Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,2613bool HasNUW, bool HasNSW) {2614unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |2615(HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);2616return get(Instruction::Mul, C1, C2, Flags);2617}26182619Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {2620return get(Instruction::Xor, C1, C2);2621}26222623Constant *ConstantExpr::getExactLogBase2(Constant *C) {2624Type *Ty = C->getType();2625const APInt *IVal;2626if (match(C, m_APInt(IVal)) && IVal->isPowerOf2())2627return ConstantInt::get(Ty, IVal->logBase2());26282629// FIXME: We can extract pow of 2 of splat constant for scalable vectors.2630auto *VecTy = dyn_cast<FixedVectorType>(Ty);2631if (!VecTy)2632return nullptr;26332634SmallVector<Constant *, 4> Elts;2635for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {2636Constant *Elt = C->getAggregateElement(I);2637if (!Elt)2638return nullptr;2639// Note that log2(iN undef) is *NOT* iN undef, because log2(iN undef) u< N.2640if (isa<UndefValue>(Elt)) {2641Elts.push_back(Constant::getNullValue(Ty->getScalarType()));2642continue;2643}2644if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())2645return nullptr;2646Elts.push_back(ConstantInt::get(Ty->getScalarType(), IVal->logBase2()));2647}26482649return ConstantVector::get(Elts);2650}26512652Constant *ConstantExpr::getBinOpIdentity(unsigned Opcode, Type *Ty,2653bool AllowRHSConstant, bool NSZ) {2654assert(Instruction::isBinaryOp(Opcode) && "Only binops allowed");26552656// Commutative opcodes: it does not matter if AllowRHSConstant is set.2657if (Instruction::isCommutative(Opcode)) {2658switch (Opcode) {2659case Instruction::Add: // X + 0 = X2660case Instruction::Or: // X | 0 = X2661case Instruction::Xor: // X ^ 0 = X2662return Constant::getNullValue(Ty);2663case Instruction::Mul: // X * 1 = X2664return ConstantInt::get(Ty, 1);2665case Instruction::And: // X & -1 = X2666return Constant::getAllOnesValue(Ty);2667case Instruction::FAdd: // X + -0.0 = X2668return ConstantFP::getZero(Ty, !NSZ);2669case Instruction::FMul: // X * 1.0 = X2670return ConstantFP::get(Ty, 1.0);2671default:2672llvm_unreachable("Every commutative binop has an identity constant");2673}2674}26752676// Non-commutative opcodes: AllowRHSConstant must be set.2677if (!AllowRHSConstant)2678return nullptr;26792680switch (Opcode) {2681case Instruction::Sub: // X - 0 = X2682case Instruction::Shl: // X << 0 = X2683case Instruction::LShr: // X >>u 0 = X2684case Instruction::AShr: // X >> 0 = X2685case Instruction::FSub: // X - 0.0 = X2686return Constant::getNullValue(Ty);2687case Instruction::SDiv: // X / 1 = X2688case Instruction::UDiv: // X /u 1 = X2689return ConstantInt::get(Ty, 1);2690case Instruction::FDiv: // X / 1.0 = X2691return ConstantFP::get(Ty, 1.0);2692default:2693return nullptr;2694}2695}26962697Constant *ConstantExpr::getIntrinsicIdentity(Intrinsic::ID ID, Type *Ty) {2698switch (ID) {2699case Intrinsic::umax:2700return Constant::getNullValue(Ty);2701case Intrinsic::umin:2702return Constant::getAllOnesValue(Ty);2703case Intrinsic::smax:2704return Constant::getIntegerValue(2705Ty, APInt::getSignedMinValue(Ty->getIntegerBitWidth()));2706case Intrinsic::smin:2707return Constant::getIntegerValue(2708Ty, APInt::getSignedMaxValue(Ty->getIntegerBitWidth()));2709default:2710return nullptr;2711}2712}27132714Constant *ConstantExpr::getIdentity(Instruction *I, Type *Ty,2715bool AllowRHSConstant, bool NSZ) {2716if (I->isBinaryOp())2717return getBinOpIdentity(I->getOpcode(), Ty, AllowRHSConstant, NSZ);2718if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))2719return getIntrinsicIdentity(II->getIntrinsicID(), Ty);2720return nullptr;2721}27222723Constant *ConstantExpr::getBinOpAbsorber(unsigned Opcode, Type *Ty) {2724switch (Opcode) {2725default:2726// Doesn't have an absorber.2727return nullptr;27282729case Instruction::Or:2730return Constant::getAllOnesValue(Ty);27312732case Instruction::And:2733case Instruction::Mul:2734return Constant::getNullValue(Ty);2735}2736}27372738/// Remove the constant from the constant table.2739void ConstantExpr::destroyConstantImpl() {2740getType()->getContext().pImpl->ExprConstants.remove(this);2741}27422743const char *ConstantExpr::getOpcodeName() const {2744return Instruction::getOpcodeName(getOpcode());2745}27462747GetElementPtrConstantExpr::GetElementPtrConstantExpr(2748Type *SrcElementTy, Constant *C, ArrayRef<Constant *> IdxList, Type *DestTy,2749std::optional<ConstantRange> InRange)2750: ConstantExpr(DestTy, Instruction::GetElementPtr,2751OperandTraits<GetElementPtrConstantExpr>::op_end(this) -2752(IdxList.size() + 1),2753IdxList.size() + 1),2754SrcElementTy(SrcElementTy),2755ResElementTy(GetElementPtrInst::getIndexedType(SrcElementTy, IdxList)),2756InRange(std::move(InRange)) {2757Op<0>() = C;2758Use *OperandList = getOperandList();2759for (unsigned i = 0, E = IdxList.size(); i != E; ++i)2760OperandList[i+1] = IdxList[i];2761}27622763Type *GetElementPtrConstantExpr::getSourceElementType() const {2764return SrcElementTy;2765}27662767Type *GetElementPtrConstantExpr::getResultElementType() const {2768return ResElementTy;2769}27702771std::optional<ConstantRange> GetElementPtrConstantExpr::getInRange() const {2772return InRange;2773}27742775//===----------------------------------------------------------------------===//2776// ConstantData* implementations27772778Type *ConstantDataSequential::getElementType() const {2779if (ArrayType *ATy = dyn_cast<ArrayType>(getType()))2780return ATy->getElementType();2781return cast<VectorType>(getType())->getElementType();2782}27832784StringRef ConstantDataSequential::getRawDataValues() const {2785return StringRef(DataElements, getNumElements()*getElementByteSize());2786}27872788bool ConstantDataSequential::isElementTypeCompatible(Type *Ty) {2789if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() || Ty->isDoubleTy())2790return true;2791if (auto *IT = dyn_cast<IntegerType>(Ty)) {2792switch (IT->getBitWidth()) {2793case 8:2794case 16:2795case 32:2796case 64:2797return true;2798default: break;2799}2800}2801return false;2802}28032804unsigned ConstantDataSequential::getNumElements() const {2805if (ArrayType *AT = dyn_cast<ArrayType>(getType()))2806return AT->getNumElements();2807return cast<FixedVectorType>(getType())->getNumElements();2808}280928102811uint64_t ConstantDataSequential::getElementByteSize() const {2812return getElementType()->getPrimitiveSizeInBits()/8;2813}28142815/// Return the start of the specified element.2816const char *ConstantDataSequential::getElementPointer(unsigned Elt) const {2817assert(Elt < getNumElements() && "Invalid Elt");2818return DataElements+Elt*getElementByteSize();2819}282028212822/// Return true if the array is empty or all zeros.2823static bool isAllZeros(StringRef Arr) {2824for (char I : Arr)2825if (I != 0)2826return false;2827return true;2828}28292830/// This is the underlying implementation of all of the2831/// ConstantDataSequential::get methods. They all thunk down to here, providing2832/// the correct element type. We take the bytes in as a StringRef because2833/// we *want* an underlying "char*" to avoid TBAA type punning violations.2834Constant *ConstantDataSequential::getImpl(StringRef Elements, Type *Ty) {2835#ifndef NDEBUG2836if (ArrayType *ATy = dyn_cast<ArrayType>(Ty))2837assert(isElementTypeCompatible(ATy->getElementType()));2838else2839assert(isElementTypeCompatible(cast<VectorType>(Ty)->getElementType()));2840#endif2841// If the elements are all zero or there are no elements, return a CAZ, which2842// is more dense and canonical.2843if (isAllZeros(Elements))2844return ConstantAggregateZero::get(Ty);28452846// Do a lookup to see if we have already formed one of these.2847auto &Slot =2848*Ty->getContext()2849.pImpl->CDSConstants.insert(std::make_pair(Elements, nullptr))2850.first;28512852// The bucket can point to a linked list of different CDS's that have the same2853// body but different types. For example, 0,0,0,1 could be a 4 element array2854// of i8, or a 1-element array of i32. They'll both end up in the same2855/// StringMap bucket, linked up by their Next pointers. Walk the list.2856std::unique_ptr<ConstantDataSequential> *Entry = &Slot.second;2857for (; *Entry; Entry = &(*Entry)->Next)2858if ((*Entry)->getType() == Ty)2859return Entry->get();28602861// Okay, we didn't get a hit. Create a node of the right class, link it in,2862// and return it.2863if (isa<ArrayType>(Ty)) {2864// Use reset because std::make_unique can't access the constructor.2865Entry->reset(new ConstantDataArray(Ty, Slot.first().data()));2866return Entry->get();2867}28682869assert(isa<VectorType>(Ty));2870// Use reset because std::make_unique can't access the constructor.2871Entry->reset(new ConstantDataVector(Ty, Slot.first().data()));2872return Entry->get();2873}28742875void ConstantDataSequential::destroyConstantImpl() {2876// Remove the constant from the StringMap.2877StringMap<std::unique_ptr<ConstantDataSequential>> &CDSConstants =2878getType()->getContext().pImpl->CDSConstants;28792880auto Slot = CDSConstants.find(getRawDataValues());28812882assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");28832884std::unique_ptr<ConstantDataSequential> *Entry = &Slot->getValue();28852886// Remove the entry from the hash table.2887if (!(*Entry)->Next) {2888// If there is only one value in the bucket (common case) it must be this2889// entry, and removing the entry should remove the bucket completely.2890assert(Entry->get() == this && "Hash mismatch in ConstantDataSequential");2891getContext().pImpl->CDSConstants.erase(Slot);2892return;2893}28942895// Otherwise, there are multiple entries linked off the bucket, unlink the2896// node we care about but keep the bucket around.2897while (true) {2898std::unique_ptr<ConstantDataSequential> &Node = *Entry;2899assert(Node && "Didn't find entry in its uniquing hash table!");2900// If we found our entry, unlink it from the list and we're done.2901if (Node.get() == this) {2902Node = std::move(Node->Next);2903return;2904}29052906Entry = &Node->Next;2907}2908}29092910/// getFP() constructors - Return a constant of array type with a float2911/// element type taken from argument `ElementType', and count taken from2912/// argument `Elts'. The amount of bits of the contained type must match the2913/// number of bits of the type contained in the passed in ArrayRef.2914/// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note2915/// that this can return a ConstantAggregateZero object.2916Constant *ConstantDataArray::getFP(Type *ElementType, ArrayRef<uint16_t> Elts) {2917assert((ElementType->isHalfTy() || ElementType->isBFloatTy()) &&2918"Element type is not a 16-bit float type");2919Type *Ty = ArrayType::get(ElementType, Elts.size());2920const char *Data = reinterpret_cast<const char *>(Elts.data());2921return getImpl(StringRef(Data, Elts.size() * 2), Ty);2922}2923Constant *ConstantDataArray::getFP(Type *ElementType, ArrayRef<uint32_t> Elts) {2924assert(ElementType->isFloatTy() && "Element type is not a 32-bit float type");2925Type *Ty = ArrayType::get(ElementType, Elts.size());2926const char *Data = reinterpret_cast<const char *>(Elts.data());2927return getImpl(StringRef(Data, Elts.size() * 4), Ty);2928}2929Constant *ConstantDataArray::getFP(Type *ElementType, ArrayRef<uint64_t> Elts) {2930assert(ElementType->isDoubleTy() &&2931"Element type is not a 64-bit float type");2932Type *Ty = ArrayType::get(ElementType, Elts.size());2933const char *Data = reinterpret_cast<const char *>(Elts.data());2934return getImpl(StringRef(Data, Elts.size() * 8), Ty);2935}29362937Constant *ConstantDataArray::getString(LLVMContext &Context,2938StringRef Str, bool AddNull) {2939if (!AddNull) {2940const uint8_t *Data = Str.bytes_begin();2941return get(Context, ArrayRef(Data, Str.size()));2942}29432944SmallVector<uint8_t, 64> ElementVals;2945ElementVals.append(Str.begin(), Str.end());2946ElementVals.push_back(0);2947return get(Context, ElementVals);2948}29492950/// get() constructors - Return a constant with vector type with an element2951/// count and element type matching the ArrayRef passed in. Note that this2952/// can return a ConstantAggregateZero object.2953Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> Elts){2954auto *Ty = FixedVectorType::get(Type::getInt8Ty(Context), Elts.size());2955const char *Data = reinterpret_cast<const char *>(Elts.data());2956return getImpl(StringRef(Data, Elts.size() * 1), Ty);2957}2958Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){2959auto *Ty = FixedVectorType::get(Type::getInt16Ty(Context), Elts.size());2960const char *Data = reinterpret_cast<const char *>(Elts.data());2961return getImpl(StringRef(Data, Elts.size() * 2), Ty);2962}2963Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){2964auto *Ty = FixedVectorType::get(Type::getInt32Ty(Context), Elts.size());2965const char *Data = reinterpret_cast<const char *>(Elts.data());2966return getImpl(StringRef(Data, Elts.size() * 4), Ty);2967}2968Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){2969auto *Ty = FixedVectorType::get(Type::getInt64Ty(Context), Elts.size());2970const char *Data = reinterpret_cast<const char *>(Elts.data());2971return getImpl(StringRef(Data, Elts.size() * 8), Ty);2972}2973Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> Elts) {2974auto *Ty = FixedVectorType::get(Type::getFloatTy(Context), Elts.size());2975const char *Data = reinterpret_cast<const char *>(Elts.data());2976return getImpl(StringRef(Data, Elts.size() * 4), Ty);2977}2978Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<double> Elts) {2979auto *Ty = FixedVectorType::get(Type::getDoubleTy(Context), Elts.size());2980const char *Data = reinterpret_cast<const char *>(Elts.data());2981return getImpl(StringRef(Data, Elts.size() * 8), Ty);2982}29832984/// getFP() constructors - Return a constant of vector type with a float2985/// element type taken from argument `ElementType', and count taken from2986/// argument `Elts'. The amount of bits of the contained type must match the2987/// number of bits of the type contained in the passed in ArrayRef.2988/// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note2989/// that this can return a ConstantAggregateZero object.2990Constant *ConstantDataVector::getFP(Type *ElementType,2991ArrayRef<uint16_t> Elts) {2992assert((ElementType->isHalfTy() || ElementType->isBFloatTy()) &&2993"Element type is not a 16-bit float type");2994auto *Ty = FixedVectorType::get(ElementType, Elts.size());2995const char *Data = reinterpret_cast<const char *>(Elts.data());2996return getImpl(StringRef(Data, Elts.size() * 2), Ty);2997}2998Constant *ConstantDataVector::getFP(Type *ElementType,2999ArrayRef<uint32_t> Elts) {3000assert(ElementType->isFloatTy() && "Element type is not a 32-bit float type");3001auto *Ty = FixedVectorType::get(ElementType, Elts.size());3002const char *Data = reinterpret_cast<const char *>(Elts.data());3003return getImpl(StringRef(Data, Elts.size() * 4), Ty);3004}3005Constant *ConstantDataVector::getFP(Type *ElementType,3006ArrayRef<uint64_t> Elts) {3007assert(ElementType->isDoubleTy() &&3008"Element type is not a 64-bit float type");3009auto *Ty = FixedVectorType::get(ElementType, Elts.size());3010const char *Data = reinterpret_cast<const char *>(Elts.data());3011return getImpl(StringRef(Data, Elts.size() * 8), Ty);3012}30133014Constant *ConstantDataVector::getSplat(unsigned NumElts, Constant *V) {3015assert(isElementTypeCompatible(V->getType()) &&3016"Element type not compatible with ConstantData");3017if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {3018if (CI->getType()->isIntegerTy(8)) {3019SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());3020return get(V->getContext(), Elts);3021}3022if (CI->getType()->isIntegerTy(16)) {3023SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());3024return get(V->getContext(), Elts);3025}3026if (CI->getType()->isIntegerTy(32)) {3027SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());3028return get(V->getContext(), Elts);3029}3030assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");3031SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());3032return get(V->getContext(), Elts);3033}30343035if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {3036if (CFP->getType()->isHalfTy()) {3037SmallVector<uint16_t, 16> Elts(3038NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());3039return getFP(V->getType(), Elts);3040}3041if (CFP->getType()->isBFloatTy()) {3042SmallVector<uint16_t, 16> Elts(3043NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());3044return getFP(V->getType(), Elts);3045}3046if (CFP->getType()->isFloatTy()) {3047SmallVector<uint32_t, 16> Elts(3048NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());3049return getFP(V->getType(), Elts);3050}3051if (CFP->getType()->isDoubleTy()) {3052SmallVector<uint64_t, 16> Elts(3053NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());3054return getFP(V->getType(), Elts);3055}3056}3057return ConstantVector::getSplat(ElementCount::getFixed(NumElts), V);3058}305930603061uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const {3062assert(isa<IntegerType>(getElementType()) &&3063"Accessor can only be used when element is an integer");3064const char *EltPtr = getElementPointer(Elt);30653066// The data is stored in host byte order, make sure to cast back to the right3067// type to load with the right endianness.3068switch (getElementType()->getIntegerBitWidth()) {3069default: llvm_unreachable("Invalid bitwidth for CDS");3070case 8:3071return *reinterpret_cast<const uint8_t *>(EltPtr);3072case 16:3073return *reinterpret_cast<const uint16_t *>(EltPtr);3074case 32:3075return *reinterpret_cast<const uint32_t *>(EltPtr);3076case 64:3077return *reinterpret_cast<const uint64_t *>(EltPtr);3078}3079}30803081APInt ConstantDataSequential::getElementAsAPInt(unsigned Elt) const {3082assert(isa<IntegerType>(getElementType()) &&3083"Accessor can only be used when element is an integer");3084const char *EltPtr = getElementPointer(Elt);30853086// The data is stored in host byte order, make sure to cast back to the right3087// type to load with the right endianness.3088switch (getElementType()->getIntegerBitWidth()) {3089default: llvm_unreachable("Invalid bitwidth for CDS");3090case 8: {3091auto EltVal = *reinterpret_cast<const uint8_t *>(EltPtr);3092return APInt(8, EltVal);3093}3094case 16: {3095auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);3096return APInt(16, EltVal);3097}3098case 32: {3099auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);3100return APInt(32, EltVal);3101}3102case 64: {3103auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);3104return APInt(64, EltVal);3105}3106}3107}31083109APFloat ConstantDataSequential::getElementAsAPFloat(unsigned Elt) const {3110const char *EltPtr = getElementPointer(Elt);31113112switch (getElementType()->getTypeID()) {3113default:3114llvm_unreachable("Accessor can only be used when element is float/double!");3115case Type::HalfTyID: {3116auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);3117return APFloat(APFloat::IEEEhalf(), APInt(16, EltVal));3118}3119case Type::BFloatTyID: {3120auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);3121return APFloat(APFloat::BFloat(), APInt(16, EltVal));3122}3123case Type::FloatTyID: {3124auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);3125return APFloat(APFloat::IEEEsingle(), APInt(32, EltVal));3126}3127case Type::DoubleTyID: {3128auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);3129return APFloat(APFloat::IEEEdouble(), APInt(64, EltVal));3130}3131}3132}31333134float ConstantDataSequential::getElementAsFloat(unsigned Elt) const {3135assert(getElementType()->isFloatTy() &&3136"Accessor can only be used when element is a 'float'");3137return *reinterpret_cast<const float *>(getElementPointer(Elt));3138}31393140double ConstantDataSequential::getElementAsDouble(unsigned Elt) const {3141assert(getElementType()->isDoubleTy() &&3142"Accessor can only be used when element is a 'float'");3143return *reinterpret_cast<const double *>(getElementPointer(Elt));3144}31453146Constant *ConstantDataSequential::getElementAsConstant(unsigned Elt) const {3147if (getElementType()->isHalfTy() || getElementType()->isBFloatTy() ||3148getElementType()->isFloatTy() || getElementType()->isDoubleTy())3149return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));31503151return ConstantInt::get(getElementType(), getElementAsInteger(Elt));3152}31533154bool ConstantDataSequential::isString(unsigned CharSize) const {3155return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(CharSize);3156}31573158bool ConstantDataSequential::isCString() const {3159if (!isString())3160return false;31613162StringRef Str = getAsString();31633164// The last value must be nul.3165if (Str.back() != 0) return false;31663167// Other elements must be non-nul.3168return !Str.drop_back().contains(0);3169}31703171bool ConstantDataVector::isSplatData() const {3172const char *Base = getRawDataValues().data();31733174// Compare elements 1+ to the 0'th element.3175unsigned EltSize = getElementByteSize();3176for (unsigned i = 1, e = getNumElements(); i != e; ++i)3177if (memcmp(Base, Base+i*EltSize, EltSize))3178return false;31793180return true;3181}31823183bool ConstantDataVector::isSplat() const {3184if (!IsSplatSet) {3185IsSplatSet = true;3186IsSplat = isSplatData();3187}3188return IsSplat;3189}31903191Constant *ConstantDataVector::getSplatValue() const {3192// If they're all the same, return the 0th one as a representative.3193return isSplat() ? getElementAsConstant(0) : nullptr;3194}31953196//===----------------------------------------------------------------------===//3197// handleOperandChange implementations31983199/// Update this constant array to change uses of3200/// 'From' to be uses of 'To'. This must update the uniquing data structures3201/// etc.3202///3203/// Note that we intentionally replace all uses of From with To here. Consider3204/// a large array that uses 'From' 1000 times. By handling this case all here,3205/// ConstantArray::handleOperandChange is only invoked once, and that3206/// single invocation handles all 1000 uses. Handling them one at a time would3207/// work, but would be really slow because it would have to unique each updated3208/// array instance.3209///3210void Constant::handleOperandChange(Value *From, Value *To) {3211Value *Replacement = nullptr;3212switch (getValueID()) {3213default:3214llvm_unreachable("Not a constant!");3215#define HANDLE_CONSTANT(Name) \3216case Value::Name##Val: \3217Replacement = cast<Name>(this)->handleOperandChangeImpl(From, To); \3218break;3219#include "llvm/IR/Value.def"3220}32213222// If handleOperandChangeImpl returned nullptr, then it handled3223// replacing itself and we don't want to delete or replace anything else here.3224if (!Replacement)3225return;32263227// I do need to replace this with an existing value.3228assert(Replacement != this && "I didn't contain From!");32293230// Everyone using this now uses the replacement.3231replaceAllUsesWith(Replacement);32323233// Delete the old constant!3234destroyConstant();3235}32363237Value *ConstantArray::handleOperandChangeImpl(Value *From, Value *To) {3238assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");3239Constant *ToC = cast<Constant>(To);32403241SmallVector<Constant*, 8> Values;3242Values.reserve(getNumOperands()); // Build replacement array.32433244// Fill values with the modified operands of the constant array. Also,3245// compute whether this turns into an all-zeros array.3246unsigned NumUpdated = 0;32473248// Keep track of whether all the values in the array are "ToC".3249bool AllSame = true;3250Use *OperandList = getOperandList();3251unsigned OperandNo = 0;3252for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {3253Constant *Val = cast<Constant>(O->get());3254if (Val == From) {3255OperandNo = (O - OperandList);3256Val = ToC;3257++NumUpdated;3258}3259Values.push_back(Val);3260AllSame &= Val == ToC;3261}32623263if (AllSame && ToC->isNullValue())3264return ConstantAggregateZero::get(getType());32653266if (AllSame && isa<UndefValue>(ToC))3267return UndefValue::get(getType());32683269// Check for any other type of constant-folding.3270if (Constant *C = getImpl(getType(), Values))3271return C;32723273// Update to the new value.3274return getContext().pImpl->ArrayConstants.replaceOperandsInPlace(3275Values, this, From, ToC, NumUpdated, OperandNo);3276}32773278Value *ConstantStruct::handleOperandChangeImpl(Value *From, Value *To) {3279assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");3280Constant *ToC = cast<Constant>(To);32813282Use *OperandList = getOperandList();32833284SmallVector<Constant*, 8> Values;3285Values.reserve(getNumOperands()); // Build replacement struct.32863287// Fill values with the modified operands of the constant struct. Also,3288// compute whether this turns into an all-zeros struct.3289unsigned NumUpdated = 0;3290bool AllSame = true;3291unsigned OperandNo = 0;3292for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) {3293Constant *Val = cast<Constant>(O->get());3294if (Val == From) {3295OperandNo = (O - OperandList);3296Val = ToC;3297++NumUpdated;3298}3299Values.push_back(Val);3300AllSame &= Val == ToC;3301}33023303if (AllSame && ToC->isNullValue())3304return ConstantAggregateZero::get(getType());33053306if (AllSame && isa<UndefValue>(ToC))3307return UndefValue::get(getType());33083309// Update to the new value.3310return getContext().pImpl->StructConstants.replaceOperandsInPlace(3311Values, this, From, ToC, NumUpdated, OperandNo);3312}33133314Value *ConstantVector::handleOperandChangeImpl(Value *From, Value *To) {3315assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");3316Constant *ToC = cast<Constant>(To);33173318SmallVector<Constant*, 8> Values;3319Values.reserve(getNumOperands()); // Build replacement array...3320unsigned NumUpdated = 0;3321unsigned OperandNo = 0;3322for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {3323Constant *Val = getOperand(i);3324if (Val == From) {3325OperandNo = i;3326++NumUpdated;3327Val = ToC;3328}3329Values.push_back(Val);3330}33313332if (Constant *C = getImpl(Values))3333return C;33343335// Update to the new value.3336return getContext().pImpl->VectorConstants.replaceOperandsInPlace(3337Values, this, From, ToC, NumUpdated, OperandNo);3338}33393340Value *ConstantExpr::handleOperandChangeImpl(Value *From, Value *ToV) {3341assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");3342Constant *To = cast<Constant>(ToV);33433344SmallVector<Constant*, 8> NewOps;3345unsigned NumUpdated = 0;3346unsigned OperandNo = 0;3347for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {3348Constant *Op = getOperand(i);3349if (Op == From) {3350OperandNo = i;3351++NumUpdated;3352Op = To;3353}3354NewOps.push_back(Op);3355}3356assert(NumUpdated && "I didn't contain From!");33573358if (Constant *C = getWithOperands(NewOps, getType(), true))3359return C;33603361// Update to the new value.3362return getContext().pImpl->ExprConstants.replaceOperandsInPlace(3363NewOps, this, From, To, NumUpdated, OperandNo);3364}33653366Instruction *ConstantExpr::getAsInstruction() const {3367SmallVector<Value *, 4> ValueOperands(operands());3368ArrayRef<Value*> Ops(ValueOperands);33693370switch (getOpcode()) {3371case Instruction::Trunc:3372case Instruction::PtrToInt:3373case Instruction::IntToPtr:3374case Instruction::BitCast:3375case Instruction::AddrSpaceCast:3376return CastInst::Create((Instruction::CastOps)getOpcode(), Ops[0],3377getType(), "");3378case Instruction::InsertElement:3379return InsertElementInst::Create(Ops[0], Ops[1], Ops[2], "");3380case Instruction::ExtractElement:3381return ExtractElementInst::Create(Ops[0], Ops[1], "");3382case Instruction::ShuffleVector:3383return new ShuffleVectorInst(Ops[0], Ops[1], getShuffleMask(), "");33843385case Instruction::GetElementPtr: {3386const auto *GO = cast<GEPOperator>(this);3387return GetElementPtrInst::Create(GO->getSourceElementType(), Ops[0],3388Ops.slice(1), GO->getNoWrapFlags(), "");3389}3390default:3391assert(getNumOperands() == 2 && "Must be binary operator?");3392BinaryOperator *BO = BinaryOperator::Create(3393(Instruction::BinaryOps)getOpcode(), Ops[0], Ops[1], "");3394if (isa<OverflowingBinaryOperator>(BO)) {3395BO->setHasNoUnsignedWrap(SubclassOptionalData &3396OverflowingBinaryOperator::NoUnsignedWrap);3397BO->setHasNoSignedWrap(SubclassOptionalData &3398OverflowingBinaryOperator::NoSignedWrap);3399}3400if (isa<PossiblyExactOperator>(BO))3401BO->setIsExact(SubclassOptionalData & PossiblyExactOperator::IsExact);3402return BO;3403}3404}340534063407