xref: /openbsd/gnu/llvm/llvm/lib/IR/Constants.cpp (revision d415bd75)
109467b48Spatrick //===-- Constants.cpp - Implement Constant nodes --------------------------===//
209467b48Spatrick //
309467b48Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
409467b48Spatrick // See https://llvm.org/LICENSE.txt for license information.
509467b48Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
609467b48Spatrick //
709467b48Spatrick //===----------------------------------------------------------------------===//
809467b48Spatrick //
909467b48Spatrick // This file implements the Constant* classes.
1009467b48Spatrick //
1109467b48Spatrick //===----------------------------------------------------------------------===//
1209467b48Spatrick 
1309467b48Spatrick #include "llvm/IR/Constants.h"
1409467b48Spatrick #include "LLVMContextImpl.h"
1509467b48Spatrick #include "llvm/ADT/STLExtras.h"
1609467b48Spatrick #include "llvm/ADT/SmallVector.h"
1709467b48Spatrick #include "llvm/ADT/StringMap.h"
18*d415bd75Srobert #include "llvm/IR/BasicBlock.h"
19*d415bd75Srobert #include "llvm/IR/ConstantFold.h"
2009467b48Spatrick #include "llvm/IR/DerivedTypes.h"
21*d415bd75Srobert #include "llvm/IR/Function.h"
2209467b48Spatrick #include "llvm/IR/GetElementPtrTypeIterator.h"
23*d415bd75Srobert #include "llvm/IR/GlobalAlias.h"
24*d415bd75Srobert #include "llvm/IR/GlobalIFunc.h"
2509467b48Spatrick #include "llvm/IR/GlobalValue.h"
26*d415bd75Srobert #include "llvm/IR/GlobalVariable.h"
2709467b48Spatrick #include "llvm/IR/Instructions.h"
2809467b48Spatrick #include "llvm/IR/Operator.h"
2909467b48Spatrick #include "llvm/IR/PatternMatch.h"
3009467b48Spatrick #include "llvm/Support/ErrorHandling.h"
3109467b48Spatrick #include "llvm/Support/MathExtras.h"
3209467b48Spatrick #include "llvm/Support/raw_ostream.h"
3309467b48Spatrick #include <algorithm>
3409467b48Spatrick 
3509467b48Spatrick using namespace llvm;
3609467b48Spatrick using namespace PatternMatch;
3709467b48Spatrick 
3809467b48Spatrick //===----------------------------------------------------------------------===//
3909467b48Spatrick //                              Constant Class
4009467b48Spatrick //===----------------------------------------------------------------------===//
4109467b48Spatrick 
isNegativeZeroValue() const4209467b48Spatrick bool Constant::isNegativeZeroValue() const {
4309467b48Spatrick   // Floating point values have an explicit -0.0 value.
4409467b48Spatrick   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
4509467b48Spatrick     return CFP->isZero() && CFP->isNegative();
4609467b48Spatrick 
4709467b48Spatrick   // Equivalent for a vector of -0.0's.
4873471bf0Spatrick   if (getType()->isVectorTy())
4973471bf0Spatrick     if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
5073471bf0Spatrick       return SplatCFP->isNegativeZeroValue();
5109467b48Spatrick 
5209467b48Spatrick   // We've already handled true FP case; any other FP vectors can't represent -0.0.
5309467b48Spatrick   if (getType()->isFPOrFPVectorTy())
5409467b48Spatrick     return false;
5509467b48Spatrick 
5609467b48Spatrick   // Otherwise, just use +0.0.
5709467b48Spatrick   return isNullValue();
5809467b48Spatrick }
5909467b48Spatrick 
6009467b48Spatrick // Return true iff this constant is positive zero (floating point), negative
6109467b48Spatrick // zero (floating point), or a null value.
isZeroValue() const6209467b48Spatrick bool Constant::isZeroValue() const {
6309467b48Spatrick   // Floating point values have an explicit -0.0 value.
6409467b48Spatrick   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
6509467b48Spatrick     return CFP->isZero();
6609467b48Spatrick 
6773471bf0Spatrick   // Check for constant splat vectors of 1 values.
6873471bf0Spatrick   if (getType()->isVectorTy())
6973471bf0Spatrick     if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
7073471bf0Spatrick       return SplatCFP->isZero();
7109467b48Spatrick 
7209467b48Spatrick   // Otherwise, just use +0.0.
7309467b48Spatrick   return isNullValue();
7409467b48Spatrick }
7509467b48Spatrick 
isNullValue() const7609467b48Spatrick bool Constant::isNullValue() const {
7709467b48Spatrick   // 0 is null.
7809467b48Spatrick   if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
7909467b48Spatrick     return CI->isZero();
8009467b48Spatrick 
8109467b48Spatrick   // +0.0 is null.
8209467b48Spatrick   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
8373471bf0Spatrick     // ppc_fp128 determine isZero using high order double only
8473471bf0Spatrick     // Should check the bitwise value to make sure all bits are zero.
8573471bf0Spatrick     return CFP->isExactlyValue(+0.0);
8609467b48Spatrick 
8709467b48Spatrick   // constant zero is zero for aggregates, cpnull is null for pointers, none for
8809467b48Spatrick   // tokens.
8909467b48Spatrick   return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this) ||
90*d415bd75Srobert          isa<ConstantTokenNone>(this) || isa<ConstantTargetNone>(this);
9109467b48Spatrick }
9209467b48Spatrick 
isAllOnesValue() const9309467b48Spatrick bool Constant::isAllOnesValue() const {
9409467b48Spatrick   // Check for -1 integers
9509467b48Spatrick   if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
9609467b48Spatrick     return CI->isMinusOne();
9709467b48Spatrick 
9809467b48Spatrick   // Check for FP which are bitcasted from -1 integers
9909467b48Spatrick   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
100*d415bd75Srobert     return CFP->getValueAPF().bitcastToAPInt().isAllOnes();
10109467b48Spatrick 
10273471bf0Spatrick   // Check for constant splat vectors of 1 values.
10373471bf0Spatrick   if (getType()->isVectorTy())
10473471bf0Spatrick     if (const auto *SplatVal = getSplatValue())
10573471bf0Spatrick       return SplatVal->isAllOnesValue();
10609467b48Spatrick 
10709467b48Spatrick   return false;
10809467b48Spatrick }
10909467b48Spatrick 
isOneValue() const11009467b48Spatrick bool Constant::isOneValue() const {
11109467b48Spatrick   // Check for 1 integers
11209467b48Spatrick   if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
11309467b48Spatrick     return CI->isOne();
11409467b48Spatrick 
11509467b48Spatrick   // Check for FP which are bitcasted from 1 integers
11609467b48Spatrick   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
117*d415bd75Srobert     return CFP->getValueAPF().bitcastToAPInt().isOne();
11809467b48Spatrick 
11973471bf0Spatrick   // Check for constant splat vectors of 1 values.
12073471bf0Spatrick   if (getType()->isVectorTy())
12173471bf0Spatrick     if (const auto *SplatVal = getSplatValue())
12273471bf0Spatrick       return SplatVal->isOneValue();
12309467b48Spatrick 
12409467b48Spatrick   return false;
12509467b48Spatrick }
12609467b48Spatrick 
isNotOneValue() const12709467b48Spatrick bool Constant::isNotOneValue() const {
12809467b48Spatrick   // Check for 1 integers
12909467b48Spatrick   if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
13009467b48Spatrick     return !CI->isOneValue();
13109467b48Spatrick 
13209467b48Spatrick   // Check for FP which are bitcasted from 1 integers
13309467b48Spatrick   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
134*d415bd75Srobert     return !CFP->getValueAPF().bitcastToAPInt().isOne();
13509467b48Spatrick 
13609467b48Spatrick   // Check that vectors don't contain 1
13773471bf0Spatrick   if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
13873471bf0Spatrick     for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
13973471bf0Spatrick       Constant *Elt = getAggregateElement(I);
14009467b48Spatrick       if (!Elt || !Elt->isNotOneValue())
14109467b48Spatrick         return false;
14209467b48Spatrick     }
14309467b48Spatrick     return true;
14409467b48Spatrick   }
14509467b48Spatrick 
14673471bf0Spatrick   // Check for splats that don't contain 1
14773471bf0Spatrick   if (getType()->isVectorTy())
14873471bf0Spatrick     if (const auto *SplatVal = getSplatValue())
14973471bf0Spatrick       return SplatVal->isNotOneValue();
15073471bf0Spatrick 
15109467b48Spatrick   // It *may* contain 1, we can't tell.
15209467b48Spatrick   return false;
15309467b48Spatrick }
15409467b48Spatrick 
isMinSignedValue() const15509467b48Spatrick bool Constant::isMinSignedValue() const {
15609467b48Spatrick   // Check for INT_MIN integers
15709467b48Spatrick   if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
15809467b48Spatrick     return CI->isMinValue(/*isSigned=*/true);
15909467b48Spatrick 
16009467b48Spatrick   // Check for FP which are bitcasted from INT_MIN integers
16109467b48Spatrick   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
16209467b48Spatrick     return CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
16309467b48Spatrick 
16473471bf0Spatrick   // Check for splats of INT_MIN values.
16573471bf0Spatrick   if (getType()->isVectorTy())
16673471bf0Spatrick     if (const auto *SplatVal = getSplatValue())
16773471bf0Spatrick       return SplatVal->isMinSignedValue();
16809467b48Spatrick 
16909467b48Spatrick   return false;
17009467b48Spatrick }
17109467b48Spatrick 
isNotMinSignedValue() const17209467b48Spatrick bool Constant::isNotMinSignedValue() const {
17309467b48Spatrick   // Check for INT_MIN integers
17409467b48Spatrick   if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
17509467b48Spatrick     return !CI->isMinValue(/*isSigned=*/true);
17609467b48Spatrick 
17709467b48Spatrick   // Check for FP which are bitcasted from INT_MIN integers
17809467b48Spatrick   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
17909467b48Spatrick     return !CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
18009467b48Spatrick 
18109467b48Spatrick   // Check that vectors don't contain INT_MIN
18273471bf0Spatrick   if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
18373471bf0Spatrick     for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
18473471bf0Spatrick       Constant *Elt = getAggregateElement(I);
18509467b48Spatrick       if (!Elt || !Elt->isNotMinSignedValue())
18609467b48Spatrick         return false;
18709467b48Spatrick     }
18809467b48Spatrick     return true;
18909467b48Spatrick   }
19009467b48Spatrick 
19173471bf0Spatrick   // Check for splats that aren't INT_MIN
19273471bf0Spatrick   if (getType()->isVectorTy())
19373471bf0Spatrick     if (const auto *SplatVal = getSplatValue())
19473471bf0Spatrick       return SplatVal->isNotMinSignedValue();
19573471bf0Spatrick 
19609467b48Spatrick   // It *may* contain INT_MIN, we can't tell.
19709467b48Spatrick   return false;
19809467b48Spatrick }
19909467b48Spatrick 
isFiniteNonZeroFP() const20009467b48Spatrick bool Constant::isFiniteNonZeroFP() const {
20109467b48Spatrick   if (auto *CFP = dyn_cast<ConstantFP>(this))
20209467b48Spatrick     return CFP->getValueAPF().isFiniteNonZero();
20373471bf0Spatrick 
20473471bf0Spatrick   if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
20573471bf0Spatrick     for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
20673471bf0Spatrick       auto *CFP = dyn_cast_or_null<ConstantFP>(getAggregateElement(I));
20709467b48Spatrick       if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
20809467b48Spatrick         return false;
20909467b48Spatrick     }
21009467b48Spatrick     return true;
21109467b48Spatrick   }
21209467b48Spatrick 
21373471bf0Spatrick   if (getType()->isVectorTy())
21473471bf0Spatrick     if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
21573471bf0Spatrick       return SplatCFP->isFiniteNonZeroFP();
21673471bf0Spatrick 
21773471bf0Spatrick   // It *may* contain finite non-zero, we can't tell.
21873471bf0Spatrick   return false;
21973471bf0Spatrick }
22073471bf0Spatrick 
isNormalFP() const22109467b48Spatrick bool Constant::isNormalFP() const {
22209467b48Spatrick   if (auto *CFP = dyn_cast<ConstantFP>(this))
22309467b48Spatrick     return CFP->getValueAPF().isNormal();
22473471bf0Spatrick 
22573471bf0Spatrick   if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
22673471bf0Spatrick     for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
22773471bf0Spatrick       auto *CFP = dyn_cast_or_null<ConstantFP>(getAggregateElement(I));
22809467b48Spatrick       if (!CFP || !CFP->getValueAPF().isNormal())
22909467b48Spatrick         return false;
23009467b48Spatrick     }
23109467b48Spatrick     return true;
23209467b48Spatrick   }
23309467b48Spatrick 
23473471bf0Spatrick   if (getType()->isVectorTy())
23573471bf0Spatrick     if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
23673471bf0Spatrick       return SplatCFP->isNormalFP();
23773471bf0Spatrick 
23873471bf0Spatrick   // It *may* contain a normal fp value, we can't tell.
23973471bf0Spatrick   return false;
24073471bf0Spatrick }
24173471bf0Spatrick 
hasExactInverseFP() const24209467b48Spatrick bool Constant::hasExactInverseFP() const {
24309467b48Spatrick   if (auto *CFP = dyn_cast<ConstantFP>(this))
24409467b48Spatrick     return CFP->getValueAPF().getExactInverse(nullptr);
24573471bf0Spatrick 
24673471bf0Spatrick   if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
24773471bf0Spatrick     for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
24873471bf0Spatrick       auto *CFP = dyn_cast_or_null<ConstantFP>(getAggregateElement(I));
24909467b48Spatrick       if (!CFP || !CFP->getValueAPF().getExactInverse(nullptr))
25009467b48Spatrick         return false;
25109467b48Spatrick     }
25209467b48Spatrick     return true;
25309467b48Spatrick   }
25409467b48Spatrick 
25573471bf0Spatrick   if (getType()->isVectorTy())
25673471bf0Spatrick     if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
25773471bf0Spatrick       return SplatCFP->hasExactInverseFP();
25873471bf0Spatrick 
25973471bf0Spatrick   // It *may* have an exact inverse fp value, we can't tell.
26073471bf0Spatrick   return false;
26173471bf0Spatrick }
26273471bf0Spatrick 
isNaN() const26309467b48Spatrick bool Constant::isNaN() const {
26409467b48Spatrick   if (auto *CFP = dyn_cast<ConstantFP>(this))
26509467b48Spatrick     return CFP->isNaN();
26673471bf0Spatrick 
26773471bf0Spatrick   if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
26873471bf0Spatrick     for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
26973471bf0Spatrick       auto *CFP = dyn_cast_or_null<ConstantFP>(getAggregateElement(I));
27009467b48Spatrick       if (!CFP || !CFP->isNaN())
27109467b48Spatrick         return false;
27209467b48Spatrick     }
27309467b48Spatrick     return true;
27409467b48Spatrick   }
27509467b48Spatrick 
27673471bf0Spatrick   if (getType()->isVectorTy())
27773471bf0Spatrick     if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
27873471bf0Spatrick       return SplatCFP->isNaN();
27973471bf0Spatrick 
28073471bf0Spatrick   // It *may* be NaN, we can't tell.
28173471bf0Spatrick   return false;
28273471bf0Spatrick }
28373471bf0Spatrick 
isElementWiseEqual(Value * Y) const28409467b48Spatrick bool Constant::isElementWiseEqual(Value *Y) const {
28509467b48Spatrick   // Are they fully identical?
28609467b48Spatrick   if (this == Y)
28709467b48Spatrick     return true;
28809467b48Spatrick 
28909467b48Spatrick   // The input value must be a vector constant with the same type.
290097a140dSpatrick   auto *VTy = dyn_cast<VectorType>(getType());
291097a140dSpatrick   if (!isa<Constant>(Y) || !VTy || VTy != Y->getType())
292097a140dSpatrick     return false;
293097a140dSpatrick 
294097a140dSpatrick   // TODO: Compare pointer constants?
295097a140dSpatrick   if (!(VTy->getElementType()->isIntegerTy() ||
296097a140dSpatrick         VTy->getElementType()->isFloatingPointTy()))
29709467b48Spatrick     return false;
29809467b48Spatrick 
29909467b48Spatrick   // They may still be identical element-wise (if they have `undef`s).
300097a140dSpatrick   // Bitcast to integer to allow exact bitwise comparison for all types.
301097a140dSpatrick   Type *IntTy = VectorType::getInteger(VTy);
302097a140dSpatrick   Constant *C0 = ConstantExpr::getBitCast(const_cast<Constant *>(this), IntTy);
303097a140dSpatrick   Constant *C1 = ConstantExpr::getBitCast(cast<Constant>(Y), IntTy);
304097a140dSpatrick   Constant *CmpEq = ConstantExpr::getICmp(ICmpInst::ICMP_EQ, C0, C1);
305097a140dSpatrick   return isa<UndefValue>(CmpEq) || match(CmpEq, m_One());
30609467b48Spatrick }
30709467b48Spatrick 
30873471bf0Spatrick static bool
containsUndefinedElement(const Constant * C,function_ref<bool (const Constant *)> HasFn)30973471bf0Spatrick containsUndefinedElement(const Constant *C,
31073471bf0Spatrick                          function_ref<bool(const Constant *)> HasFn) {
31173471bf0Spatrick   if (auto *VTy = dyn_cast<VectorType>(C->getType())) {
31273471bf0Spatrick     if (HasFn(C))
31309467b48Spatrick       return true;
31473471bf0Spatrick     if (isa<ConstantAggregateZero>(C))
31573471bf0Spatrick       return false;
31673471bf0Spatrick     if (isa<ScalableVectorType>(C->getType()))
31773471bf0Spatrick       return false;
31873471bf0Spatrick 
31973471bf0Spatrick     for (unsigned i = 0, e = cast<FixedVectorType>(VTy)->getNumElements();
32073471bf0Spatrick          i != e; ++i) {
32173471bf0Spatrick       if (Constant *Elem = C->getAggregateElement(i))
32273471bf0Spatrick         if (HasFn(Elem))
32373471bf0Spatrick           return true;
32473471bf0Spatrick     }
325097a140dSpatrick   }
32609467b48Spatrick 
32709467b48Spatrick   return false;
32809467b48Spatrick }
32909467b48Spatrick 
containsUndefOrPoisonElement() const33073471bf0Spatrick bool Constant::containsUndefOrPoisonElement() const {
33173471bf0Spatrick   return containsUndefinedElement(
33273471bf0Spatrick       this, [&](const auto *C) { return isa<UndefValue>(C); });
33373471bf0Spatrick }
33473471bf0Spatrick 
containsPoisonElement() const33573471bf0Spatrick bool Constant::containsPoisonElement() const {
33673471bf0Spatrick   return containsUndefinedElement(
33773471bf0Spatrick       this, [&](const auto *C) { return isa<PoisonValue>(C); });
33873471bf0Spatrick }
33973471bf0Spatrick 
containsUndefElement() const340*d415bd75Srobert bool Constant::containsUndefElement() const {
341*d415bd75Srobert   return containsUndefinedElement(this, [&](const auto *C) {
342*d415bd75Srobert     return isa<UndefValue>(C) && !isa<PoisonValue>(C);
343*d415bd75Srobert   });
344*d415bd75Srobert }
345*d415bd75Srobert 
containsConstantExpression() const34609467b48Spatrick bool Constant::containsConstantExpression() const {
34773471bf0Spatrick   if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
348097a140dSpatrick     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i)
34909467b48Spatrick       if (isa<ConstantExpr>(getAggregateElement(i)))
35009467b48Spatrick         return true;
351097a140dSpatrick   }
35209467b48Spatrick   return false;
35309467b48Spatrick }
35409467b48Spatrick 
35509467b48Spatrick /// Constructor to create a '0' constant of arbitrary type.
getNullValue(Type * Ty)35609467b48Spatrick Constant *Constant::getNullValue(Type *Ty) {
35709467b48Spatrick   switch (Ty->getTypeID()) {
35809467b48Spatrick   case Type::IntegerTyID:
35909467b48Spatrick     return ConstantInt::get(Ty, 0);
36009467b48Spatrick   case Type::HalfTyID:
361097a140dSpatrick   case Type::BFloatTyID:
36209467b48Spatrick   case Type::FloatTyID:
36309467b48Spatrick   case Type::DoubleTyID:
36409467b48Spatrick   case Type::X86_FP80TyID:
36509467b48Spatrick   case Type::FP128TyID:
36609467b48Spatrick   case Type::PPC_FP128TyID:
36709467b48Spatrick     return ConstantFP::get(Ty->getContext(),
368*d415bd75Srobert                            APFloat::getZero(Ty->getFltSemantics()));
36909467b48Spatrick   case Type::PointerTyID:
37009467b48Spatrick     return ConstantPointerNull::get(cast<PointerType>(Ty));
37109467b48Spatrick   case Type::StructTyID:
37209467b48Spatrick   case Type::ArrayTyID:
373097a140dSpatrick   case Type::FixedVectorTyID:
374097a140dSpatrick   case Type::ScalableVectorTyID:
37509467b48Spatrick     return ConstantAggregateZero::get(Ty);
37609467b48Spatrick   case Type::TokenTyID:
37709467b48Spatrick     return ConstantTokenNone::get(Ty->getContext());
378*d415bd75Srobert   case Type::TargetExtTyID:
379*d415bd75Srobert     return ConstantTargetNone::get(cast<TargetExtType>(Ty));
38009467b48Spatrick   default:
38109467b48Spatrick     // Function, Label, or Opaque type?
38209467b48Spatrick     llvm_unreachable("Cannot create a null constant of that type!");
38309467b48Spatrick   }
38409467b48Spatrick }
38509467b48Spatrick 
getIntegerValue(Type * Ty,const APInt & V)38609467b48Spatrick Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) {
38709467b48Spatrick   Type *ScalarTy = Ty->getScalarType();
38809467b48Spatrick 
38909467b48Spatrick   // Create the base integer constant.
39009467b48Spatrick   Constant *C = ConstantInt::get(Ty->getContext(), V);
39109467b48Spatrick 
39209467b48Spatrick   // Convert an integer to a pointer, if necessary.
39309467b48Spatrick   if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
39409467b48Spatrick     C = ConstantExpr::getIntToPtr(C, PTy);
39509467b48Spatrick 
39609467b48Spatrick   // Broadcast a scalar to a vector, if necessary.
39709467b48Spatrick   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
398097a140dSpatrick     C = ConstantVector::getSplat(VTy->getElementCount(), C);
39909467b48Spatrick 
40009467b48Spatrick   return C;
40109467b48Spatrick }
40209467b48Spatrick 
getAllOnesValue(Type * Ty)40309467b48Spatrick Constant *Constant::getAllOnesValue(Type *Ty) {
40409467b48Spatrick   if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
40509467b48Spatrick     return ConstantInt::get(Ty->getContext(),
406*d415bd75Srobert                             APInt::getAllOnes(ITy->getBitWidth()));
40709467b48Spatrick 
40809467b48Spatrick   if (Ty->isFloatingPointTy()) {
409*d415bd75Srobert     APFloat FL = APFloat::getAllOnesValue(Ty->getFltSemantics());
41009467b48Spatrick     return ConstantFP::get(Ty->getContext(), FL);
41109467b48Spatrick   }
41209467b48Spatrick 
41309467b48Spatrick   VectorType *VTy = cast<VectorType>(Ty);
414097a140dSpatrick   return ConstantVector::getSplat(VTy->getElementCount(),
41509467b48Spatrick                                   getAllOnesValue(VTy->getElementType()));
41609467b48Spatrick }
41709467b48Spatrick 
getAggregateElement(unsigned Elt) const41809467b48Spatrick Constant *Constant::getAggregateElement(unsigned Elt) const {
41973471bf0Spatrick   assert((getType()->isAggregateType() || getType()->isVectorTy()) &&
42073471bf0Spatrick          "Must be an aggregate/vector constant");
42173471bf0Spatrick 
42273471bf0Spatrick   if (const auto *CC = dyn_cast<ConstantAggregate>(this))
42309467b48Spatrick     return Elt < CC->getNumOperands() ? CC->getOperand(Elt) : nullptr;
42409467b48Spatrick 
42573471bf0Spatrick   if (const auto *CAZ = dyn_cast<ConstantAggregateZero>(this))
42673471bf0Spatrick     return Elt < CAZ->getElementCount().getKnownMinValue()
42773471bf0Spatrick                ? CAZ->getElementValue(Elt)
42873471bf0Spatrick                : nullptr;
42909467b48Spatrick 
43073471bf0Spatrick   // FIXME: getNumElements() will fail for non-fixed vector types.
43173471bf0Spatrick   if (isa<ScalableVectorType>(getType()))
43273471bf0Spatrick     return nullptr;
43373471bf0Spatrick 
43473471bf0Spatrick   if (const auto *PV = dyn_cast<PoisonValue>(this))
43573471bf0Spatrick     return Elt < PV->getNumElements() ? PV->getElementValue(Elt) : nullptr;
43673471bf0Spatrick 
43773471bf0Spatrick   if (const auto *UV = dyn_cast<UndefValue>(this))
43809467b48Spatrick     return Elt < UV->getNumElements() ? UV->getElementValue(Elt) : nullptr;
43909467b48Spatrick 
44073471bf0Spatrick   if (const auto *CDS = dyn_cast<ConstantDataSequential>(this))
44109467b48Spatrick     return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt)
44209467b48Spatrick                                        : nullptr;
44373471bf0Spatrick 
44409467b48Spatrick   return nullptr;
44509467b48Spatrick }
44609467b48Spatrick 
getAggregateElement(Constant * Elt) const44709467b48Spatrick Constant *Constant::getAggregateElement(Constant *Elt) const {
44809467b48Spatrick   assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
44909467b48Spatrick   if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt)) {
45009467b48Spatrick     // Check if the constant fits into an uint64_t.
45109467b48Spatrick     if (CI->getValue().getActiveBits() > 64)
45209467b48Spatrick       return nullptr;
45309467b48Spatrick     return getAggregateElement(CI->getZExtValue());
45409467b48Spatrick   }
45509467b48Spatrick   return nullptr;
45609467b48Spatrick }
45709467b48Spatrick 
destroyConstant()45809467b48Spatrick void Constant::destroyConstant() {
45909467b48Spatrick   /// First call destroyConstantImpl on the subclass.  This gives the subclass
46009467b48Spatrick   /// a chance to remove the constant from any maps/pools it's contained in.
46109467b48Spatrick   switch (getValueID()) {
46209467b48Spatrick   default:
46309467b48Spatrick     llvm_unreachable("Not a constant!");
46409467b48Spatrick #define HANDLE_CONSTANT(Name)                                                  \
46509467b48Spatrick   case Value::Name##Val:                                                       \
46609467b48Spatrick     cast<Name>(this)->destroyConstantImpl();                                   \
46709467b48Spatrick     break;
46809467b48Spatrick #include "llvm/IR/Value.def"
46909467b48Spatrick   }
47009467b48Spatrick 
47109467b48Spatrick   // When a Constant is destroyed, there may be lingering
47209467b48Spatrick   // references to the constant by other constants in the constant pool.  These
47309467b48Spatrick   // constants are implicitly dependent on the module that is being deleted,
47409467b48Spatrick   // but they don't know that.  Because we only find out when the CPV is
47509467b48Spatrick   // deleted, we must now notify all of our users (that should only be
47609467b48Spatrick   // Constants) that they are, in fact, invalid now and should be deleted.
47709467b48Spatrick   //
47809467b48Spatrick   while (!use_empty()) {
47909467b48Spatrick     Value *V = user_back();
48009467b48Spatrick #ifndef NDEBUG // Only in -g mode...
48109467b48Spatrick     if (!isa<Constant>(V)) {
48209467b48Spatrick       dbgs() << "While deleting: " << *this
48309467b48Spatrick              << "\n\nUse still stuck around after Def is destroyed: " << *V
48409467b48Spatrick              << "\n\n";
48509467b48Spatrick     }
48609467b48Spatrick #endif
48709467b48Spatrick     assert(isa<Constant>(V) && "References remain to Constant being destroyed");
48809467b48Spatrick     cast<Constant>(V)->destroyConstant();
48909467b48Spatrick 
49009467b48Spatrick     // The constant should remove itself from our use list...
49109467b48Spatrick     assert((use_empty() || user_back() != V) && "Constant not removed!");
49209467b48Spatrick   }
49309467b48Spatrick 
49409467b48Spatrick   // Value has no outstanding references it is safe to delete it now...
495097a140dSpatrick   deleteConstant(this);
496097a140dSpatrick }
497097a140dSpatrick 
deleteConstant(Constant * C)498097a140dSpatrick void llvm::deleteConstant(Constant *C) {
499097a140dSpatrick   switch (C->getValueID()) {
500097a140dSpatrick   case Constant::ConstantIntVal:
501097a140dSpatrick     delete static_cast<ConstantInt *>(C);
502097a140dSpatrick     break;
503097a140dSpatrick   case Constant::ConstantFPVal:
504097a140dSpatrick     delete static_cast<ConstantFP *>(C);
505097a140dSpatrick     break;
506097a140dSpatrick   case Constant::ConstantAggregateZeroVal:
507097a140dSpatrick     delete static_cast<ConstantAggregateZero *>(C);
508097a140dSpatrick     break;
509097a140dSpatrick   case Constant::ConstantArrayVal:
510097a140dSpatrick     delete static_cast<ConstantArray *>(C);
511097a140dSpatrick     break;
512097a140dSpatrick   case Constant::ConstantStructVal:
513097a140dSpatrick     delete static_cast<ConstantStruct *>(C);
514097a140dSpatrick     break;
515097a140dSpatrick   case Constant::ConstantVectorVal:
516097a140dSpatrick     delete static_cast<ConstantVector *>(C);
517097a140dSpatrick     break;
518097a140dSpatrick   case Constant::ConstantPointerNullVal:
519097a140dSpatrick     delete static_cast<ConstantPointerNull *>(C);
520097a140dSpatrick     break;
521097a140dSpatrick   case Constant::ConstantDataArrayVal:
522097a140dSpatrick     delete static_cast<ConstantDataArray *>(C);
523097a140dSpatrick     break;
524097a140dSpatrick   case Constant::ConstantDataVectorVal:
525097a140dSpatrick     delete static_cast<ConstantDataVector *>(C);
526097a140dSpatrick     break;
527097a140dSpatrick   case Constant::ConstantTokenNoneVal:
528097a140dSpatrick     delete static_cast<ConstantTokenNone *>(C);
529097a140dSpatrick     break;
530097a140dSpatrick   case Constant::BlockAddressVal:
531097a140dSpatrick     delete static_cast<BlockAddress *>(C);
532097a140dSpatrick     break;
53373471bf0Spatrick   case Constant::DSOLocalEquivalentVal:
53473471bf0Spatrick     delete static_cast<DSOLocalEquivalent *>(C);
53573471bf0Spatrick     break;
536*d415bd75Srobert   case Constant::NoCFIValueVal:
537*d415bd75Srobert     delete static_cast<NoCFIValue *>(C);
538*d415bd75Srobert     break;
539097a140dSpatrick   case Constant::UndefValueVal:
540097a140dSpatrick     delete static_cast<UndefValue *>(C);
541097a140dSpatrick     break;
54273471bf0Spatrick   case Constant::PoisonValueVal:
54373471bf0Spatrick     delete static_cast<PoisonValue *>(C);
54473471bf0Spatrick     break;
545097a140dSpatrick   case Constant::ConstantExprVal:
546*d415bd75Srobert     if (isa<CastConstantExpr>(C))
547*d415bd75Srobert       delete static_cast<CastConstantExpr *>(C);
548097a140dSpatrick     else if (isa<BinaryConstantExpr>(C))
549097a140dSpatrick       delete static_cast<BinaryConstantExpr *>(C);
550097a140dSpatrick     else if (isa<SelectConstantExpr>(C))
551097a140dSpatrick       delete static_cast<SelectConstantExpr *>(C);
552097a140dSpatrick     else if (isa<ExtractElementConstantExpr>(C))
553097a140dSpatrick       delete static_cast<ExtractElementConstantExpr *>(C);
554097a140dSpatrick     else if (isa<InsertElementConstantExpr>(C))
555097a140dSpatrick       delete static_cast<InsertElementConstantExpr *>(C);
556097a140dSpatrick     else if (isa<ShuffleVectorConstantExpr>(C))
557097a140dSpatrick       delete static_cast<ShuffleVectorConstantExpr *>(C);
558097a140dSpatrick     else if (isa<GetElementPtrConstantExpr>(C))
559097a140dSpatrick       delete static_cast<GetElementPtrConstantExpr *>(C);
560097a140dSpatrick     else if (isa<CompareConstantExpr>(C))
561097a140dSpatrick       delete static_cast<CompareConstantExpr *>(C);
562097a140dSpatrick     else
563097a140dSpatrick       llvm_unreachable("Unexpected constant expr");
564097a140dSpatrick     break;
565097a140dSpatrick   default:
566097a140dSpatrick     llvm_unreachable("Unexpected constant");
567097a140dSpatrick   }
56809467b48Spatrick }
56909467b48Spatrick 
57009467b48Spatrick /// Check if C contains a GlobalValue for which Predicate is true.
57109467b48Spatrick static bool
ConstHasGlobalValuePredicate(const Constant * C,bool (* Predicate)(const GlobalValue *))57209467b48Spatrick ConstHasGlobalValuePredicate(const Constant *C,
57309467b48Spatrick                              bool (*Predicate)(const GlobalValue *)) {
57409467b48Spatrick   SmallPtrSet<const Constant *, 8> Visited;
57509467b48Spatrick   SmallVector<const Constant *, 8> WorkList;
57609467b48Spatrick   WorkList.push_back(C);
57709467b48Spatrick   Visited.insert(C);
57809467b48Spatrick 
57909467b48Spatrick   while (!WorkList.empty()) {
58009467b48Spatrick     const Constant *WorkItem = WorkList.pop_back_val();
58109467b48Spatrick     if (const auto *GV = dyn_cast<GlobalValue>(WorkItem))
58209467b48Spatrick       if (Predicate(GV))
58309467b48Spatrick         return true;
58409467b48Spatrick     for (const Value *Op : WorkItem->operands()) {
58509467b48Spatrick       const Constant *ConstOp = dyn_cast<Constant>(Op);
58609467b48Spatrick       if (!ConstOp)
58709467b48Spatrick         continue;
58809467b48Spatrick       if (Visited.insert(ConstOp).second)
58909467b48Spatrick         WorkList.push_back(ConstOp);
59009467b48Spatrick     }
59109467b48Spatrick   }
59209467b48Spatrick   return false;
59309467b48Spatrick }
59409467b48Spatrick 
isThreadDependent() const59509467b48Spatrick bool Constant::isThreadDependent() const {
59609467b48Spatrick   auto DLLImportPredicate = [](const GlobalValue *GV) {
59709467b48Spatrick     return GV->isThreadLocal();
59809467b48Spatrick   };
59909467b48Spatrick   return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
60009467b48Spatrick }
60109467b48Spatrick 
isDLLImportDependent() const60209467b48Spatrick bool Constant::isDLLImportDependent() const {
60309467b48Spatrick   auto DLLImportPredicate = [](const GlobalValue *GV) {
60409467b48Spatrick     return GV->hasDLLImportStorageClass();
60509467b48Spatrick   };
60609467b48Spatrick   return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
60709467b48Spatrick }
60809467b48Spatrick 
isConstantUsed() const60909467b48Spatrick bool Constant::isConstantUsed() const {
61009467b48Spatrick   for (const User *U : users()) {
61109467b48Spatrick     const Constant *UC = dyn_cast<Constant>(U);
61209467b48Spatrick     if (!UC || isa<GlobalValue>(UC))
61309467b48Spatrick       return true;
61409467b48Spatrick 
61509467b48Spatrick     if (UC->isConstantUsed())
61609467b48Spatrick       return true;
61709467b48Spatrick   }
61809467b48Spatrick   return false;
61909467b48Spatrick }
62009467b48Spatrick 
needsDynamicRelocation() const62173471bf0Spatrick bool Constant::needsDynamicRelocation() const {
62273471bf0Spatrick   return getRelocationInfo() == GlobalRelocation;
62373471bf0Spatrick }
62473471bf0Spatrick 
needsRelocation() const62509467b48Spatrick bool Constant::needsRelocation() const {
62673471bf0Spatrick   return getRelocationInfo() != NoRelocation;
62773471bf0Spatrick }
62873471bf0Spatrick 
getRelocationInfo() const62973471bf0Spatrick Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
63009467b48Spatrick   if (isa<GlobalValue>(this))
63173471bf0Spatrick     return GlobalRelocation; // Global reference.
63209467b48Spatrick 
63309467b48Spatrick   if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
63473471bf0Spatrick     return BA->getFunction()->getRelocationInfo();
63509467b48Spatrick 
63609467b48Spatrick   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this)) {
63709467b48Spatrick     if (CE->getOpcode() == Instruction::Sub) {
63809467b48Spatrick       ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
63909467b48Spatrick       ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
64009467b48Spatrick       if (LHS && RHS && LHS->getOpcode() == Instruction::PtrToInt &&
64109467b48Spatrick           RHS->getOpcode() == Instruction::PtrToInt) {
64209467b48Spatrick         Constant *LHSOp0 = LHS->getOperand(0);
64309467b48Spatrick         Constant *RHSOp0 = RHS->getOperand(0);
64409467b48Spatrick 
64509467b48Spatrick         // While raw uses of blockaddress need to be relocated, differences
64609467b48Spatrick         // between two of them don't when they are for labels in the same
64709467b48Spatrick         // function.  This is a common idiom when creating a table for the
64809467b48Spatrick         // indirect goto extension, so we handle it efficiently here.
64909467b48Spatrick         if (isa<BlockAddress>(LHSOp0) && isa<BlockAddress>(RHSOp0) &&
65009467b48Spatrick             cast<BlockAddress>(LHSOp0)->getFunction() ==
65109467b48Spatrick                 cast<BlockAddress>(RHSOp0)->getFunction())
65273471bf0Spatrick           return NoRelocation;
65309467b48Spatrick 
65409467b48Spatrick         // Relative pointers do not need to be dynamically relocated.
65573471bf0Spatrick         if (auto *RHSGV =
65673471bf0Spatrick                 dyn_cast<GlobalValue>(RHSOp0->stripInBoundsConstantOffsets())) {
65773471bf0Spatrick           auto *LHS = LHSOp0->stripInBoundsConstantOffsets();
65873471bf0Spatrick           if (auto *LHSGV = dyn_cast<GlobalValue>(LHS)) {
65909467b48Spatrick             if (LHSGV->isDSOLocal() && RHSGV->isDSOLocal())
66073471bf0Spatrick               return LocalRelocation;
66173471bf0Spatrick           } else if (isa<DSOLocalEquivalent>(LHS)) {
66273471bf0Spatrick             if (RHSGV->isDSOLocal())
66373471bf0Spatrick               return LocalRelocation;
66473471bf0Spatrick           }
66573471bf0Spatrick         }
66609467b48Spatrick       }
66709467b48Spatrick     }
66809467b48Spatrick   }
66909467b48Spatrick 
67073471bf0Spatrick   PossibleRelocationsTy Result = NoRelocation;
67109467b48Spatrick   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
67273471bf0Spatrick     Result =
67373471bf0Spatrick         std::max(cast<Constant>(getOperand(i))->getRelocationInfo(), Result);
67409467b48Spatrick 
67509467b48Spatrick   return Result;
67609467b48Spatrick }
67709467b48Spatrick 
678*d415bd75Srobert /// Return true if the specified constantexpr is dead. This involves
679*d415bd75Srobert /// recursively traversing users of the constantexpr.
680*d415bd75Srobert /// If RemoveDeadUsers is true, also remove dead users at the same time.
constantIsDead(const Constant * C,bool RemoveDeadUsers)681*d415bd75Srobert static bool constantIsDead(const Constant *C, bool RemoveDeadUsers) {
68209467b48Spatrick   if (isa<GlobalValue>(C)) return false; // Cannot remove this
68309467b48Spatrick 
684*d415bd75Srobert   Value::const_user_iterator I = C->user_begin(), E = C->user_end();
685*d415bd75Srobert   while (I != E) {
686*d415bd75Srobert     const Constant *User = dyn_cast<Constant>(*I);
68709467b48Spatrick     if (!User) return false; // Non-constant usage;
688*d415bd75Srobert     if (!constantIsDead(User, RemoveDeadUsers))
68909467b48Spatrick       return false; // Constant wasn't dead
690*d415bd75Srobert 
691*d415bd75Srobert     // Just removed User, so the iterator was invalidated.
692*d415bd75Srobert     // Since we return immediately upon finding a live user, we can always
693*d415bd75Srobert     // restart from user_begin().
694*d415bd75Srobert     if (RemoveDeadUsers)
695*d415bd75Srobert       I = C->user_begin();
696*d415bd75Srobert     else
697*d415bd75Srobert       ++I;
69809467b48Spatrick   }
69909467b48Spatrick 
700*d415bd75Srobert   if (RemoveDeadUsers) {
701*d415bd75Srobert     // If C is only used by metadata, it should not be preserved but should
702*d415bd75Srobert     // have its uses replaced.
703*d415bd75Srobert     ReplaceableMetadataImpl::SalvageDebugInfo(*C);
70409467b48Spatrick     const_cast<Constant *>(C)->destroyConstant();
705*d415bd75Srobert   }
706*d415bd75Srobert 
70709467b48Spatrick   return true;
70809467b48Spatrick }
70909467b48Spatrick 
removeDeadConstantUsers() const71009467b48Spatrick void Constant::removeDeadConstantUsers() const {
71109467b48Spatrick   Value::const_user_iterator I = user_begin(), E = user_end();
71209467b48Spatrick   Value::const_user_iterator LastNonDeadUser = E;
71309467b48Spatrick   while (I != E) {
71409467b48Spatrick     const Constant *User = dyn_cast<Constant>(*I);
71509467b48Spatrick     if (!User) {
71609467b48Spatrick       LastNonDeadUser = I;
71709467b48Spatrick       ++I;
71809467b48Spatrick       continue;
71909467b48Spatrick     }
72009467b48Spatrick 
721*d415bd75Srobert     if (!constantIsDead(User, /* RemoveDeadUsers= */ true)) {
72209467b48Spatrick       // If the constant wasn't dead, remember that this was the last live use
72309467b48Spatrick       // and move on to the next constant.
72409467b48Spatrick       LastNonDeadUser = I;
72509467b48Spatrick       ++I;
72609467b48Spatrick       continue;
72709467b48Spatrick     }
72809467b48Spatrick 
72909467b48Spatrick     // If the constant was dead, then the iterator is invalidated.
73009467b48Spatrick     if (LastNonDeadUser == E)
73109467b48Spatrick       I = user_begin();
73209467b48Spatrick     else
73309467b48Spatrick       I = std::next(LastNonDeadUser);
73409467b48Spatrick   }
73509467b48Spatrick }
73609467b48Spatrick 
hasOneLiveUse() const737*d415bd75Srobert bool Constant::hasOneLiveUse() const { return hasNLiveUses(1); }
738*d415bd75Srobert 
hasZeroLiveUses() const739*d415bd75Srobert bool Constant::hasZeroLiveUses() const { return hasNLiveUses(0); }
740*d415bd75Srobert 
hasNLiveUses(unsigned N) const741*d415bd75Srobert bool Constant::hasNLiveUses(unsigned N) const {
742*d415bd75Srobert   unsigned NumUses = 0;
743*d415bd75Srobert   for (const Use &U : uses()) {
744*d415bd75Srobert     const Constant *User = dyn_cast<Constant>(U.getUser());
745*d415bd75Srobert     if (!User || !constantIsDead(User, /* RemoveDeadUsers= */ false)) {
746*d415bd75Srobert       ++NumUses;
747*d415bd75Srobert 
748*d415bd75Srobert       if (NumUses > N)
749*d415bd75Srobert         return false;
750*d415bd75Srobert     }
751*d415bd75Srobert   }
752*d415bd75Srobert   return NumUses == N;
753*d415bd75Srobert }
754*d415bd75Srobert 
replaceUndefsWith(Constant * C,Constant * Replacement)75509467b48Spatrick Constant *Constant::replaceUndefsWith(Constant *C, Constant *Replacement) {
75609467b48Spatrick   assert(C && Replacement && "Expected non-nullptr constant arguments");
75709467b48Spatrick   Type *Ty = C->getType();
75809467b48Spatrick   if (match(C, m_Undef())) {
75909467b48Spatrick     assert(Ty == Replacement->getType() && "Expected matching types");
76009467b48Spatrick     return Replacement;
76109467b48Spatrick   }
76209467b48Spatrick 
76309467b48Spatrick   // Don't know how to deal with this constant.
764097a140dSpatrick   auto *VTy = dyn_cast<FixedVectorType>(Ty);
765097a140dSpatrick   if (!VTy)
76609467b48Spatrick     return C;
76709467b48Spatrick 
768097a140dSpatrick   unsigned NumElts = VTy->getNumElements();
76909467b48Spatrick   SmallVector<Constant *, 32> NewC(NumElts);
77009467b48Spatrick   for (unsigned i = 0; i != NumElts; ++i) {
77109467b48Spatrick     Constant *EltC = C->getAggregateElement(i);
77209467b48Spatrick     assert((!EltC || EltC->getType() == Replacement->getType()) &&
77309467b48Spatrick            "Expected matching types");
77409467b48Spatrick     NewC[i] = EltC && match(EltC, m_Undef()) ? Replacement : EltC;
77509467b48Spatrick   }
77609467b48Spatrick   return ConstantVector::get(NewC);
77709467b48Spatrick }
77809467b48Spatrick 
mergeUndefsWith(Constant * C,Constant * Other)77973471bf0Spatrick Constant *Constant::mergeUndefsWith(Constant *C, Constant *Other) {
78073471bf0Spatrick   assert(C && Other && "Expected non-nullptr constant arguments");
78173471bf0Spatrick   if (match(C, m_Undef()))
78273471bf0Spatrick     return C;
78373471bf0Spatrick 
78473471bf0Spatrick   Type *Ty = C->getType();
78573471bf0Spatrick   if (match(Other, m_Undef()))
78673471bf0Spatrick     return UndefValue::get(Ty);
78773471bf0Spatrick 
78873471bf0Spatrick   auto *VTy = dyn_cast<FixedVectorType>(Ty);
78973471bf0Spatrick   if (!VTy)
79073471bf0Spatrick     return C;
79173471bf0Spatrick 
79273471bf0Spatrick   Type *EltTy = VTy->getElementType();
79373471bf0Spatrick   unsigned NumElts = VTy->getNumElements();
79473471bf0Spatrick   assert(isa<FixedVectorType>(Other->getType()) &&
79573471bf0Spatrick          cast<FixedVectorType>(Other->getType())->getNumElements() == NumElts &&
79673471bf0Spatrick          "Type mismatch");
79773471bf0Spatrick 
79873471bf0Spatrick   bool FoundExtraUndef = false;
79973471bf0Spatrick   SmallVector<Constant *, 32> NewC(NumElts);
80073471bf0Spatrick   for (unsigned I = 0; I != NumElts; ++I) {
80173471bf0Spatrick     NewC[I] = C->getAggregateElement(I);
80273471bf0Spatrick     Constant *OtherEltC = Other->getAggregateElement(I);
80373471bf0Spatrick     assert(NewC[I] && OtherEltC && "Unknown vector element");
80473471bf0Spatrick     if (!match(NewC[I], m_Undef()) && match(OtherEltC, m_Undef())) {
80573471bf0Spatrick       NewC[I] = UndefValue::get(EltTy);
80673471bf0Spatrick       FoundExtraUndef = true;
80773471bf0Spatrick     }
80873471bf0Spatrick   }
80973471bf0Spatrick   if (FoundExtraUndef)
81073471bf0Spatrick     return ConstantVector::get(NewC);
81173471bf0Spatrick   return C;
81273471bf0Spatrick }
81373471bf0Spatrick 
isManifestConstant() const81473471bf0Spatrick bool Constant::isManifestConstant() const {
81573471bf0Spatrick   if (isa<ConstantData>(this))
81673471bf0Spatrick     return true;
81773471bf0Spatrick   if (isa<ConstantAggregate>(this) || isa<ConstantExpr>(this)) {
81873471bf0Spatrick     for (const Value *Op : operand_values())
81973471bf0Spatrick       if (!cast<Constant>(Op)->isManifestConstant())
82073471bf0Spatrick         return false;
82173471bf0Spatrick     return true;
82273471bf0Spatrick   }
82373471bf0Spatrick   return false;
82473471bf0Spatrick }
82509467b48Spatrick 
82609467b48Spatrick //===----------------------------------------------------------------------===//
82709467b48Spatrick //                                ConstantInt
82809467b48Spatrick //===----------------------------------------------------------------------===//
82909467b48Spatrick 
ConstantInt(IntegerType * Ty,const APInt & V)83009467b48Spatrick ConstantInt::ConstantInt(IntegerType *Ty, const APInt &V)
83109467b48Spatrick     : ConstantData(Ty, ConstantIntVal), Val(V) {
83209467b48Spatrick   assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
83309467b48Spatrick }
83409467b48Spatrick 
getTrue(LLVMContext & Context)83509467b48Spatrick ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
83609467b48Spatrick   LLVMContextImpl *pImpl = Context.pImpl;
83709467b48Spatrick   if (!pImpl->TheTrueVal)
83809467b48Spatrick     pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
83909467b48Spatrick   return pImpl->TheTrueVal;
84009467b48Spatrick }
84109467b48Spatrick 
getFalse(LLVMContext & Context)84209467b48Spatrick ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
84309467b48Spatrick   LLVMContextImpl *pImpl = Context.pImpl;
84409467b48Spatrick   if (!pImpl->TheFalseVal)
84509467b48Spatrick     pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
84609467b48Spatrick   return pImpl->TheFalseVal;
84709467b48Spatrick }
84809467b48Spatrick 
getBool(LLVMContext & Context,bool V)84973471bf0Spatrick ConstantInt *ConstantInt::getBool(LLVMContext &Context, bool V) {
85073471bf0Spatrick   return V ? getTrue(Context) : getFalse(Context);
85173471bf0Spatrick }
85273471bf0Spatrick 
getTrue(Type * Ty)85309467b48Spatrick Constant *ConstantInt::getTrue(Type *Ty) {
85409467b48Spatrick   assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
85509467b48Spatrick   ConstantInt *TrueC = ConstantInt::getTrue(Ty->getContext());
85609467b48Spatrick   if (auto *VTy = dyn_cast<VectorType>(Ty))
857097a140dSpatrick     return ConstantVector::getSplat(VTy->getElementCount(), TrueC);
85809467b48Spatrick   return TrueC;
85909467b48Spatrick }
86009467b48Spatrick 
getFalse(Type * Ty)86109467b48Spatrick Constant *ConstantInt::getFalse(Type *Ty) {
86209467b48Spatrick   assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
86309467b48Spatrick   ConstantInt *FalseC = ConstantInt::getFalse(Ty->getContext());
86409467b48Spatrick   if (auto *VTy = dyn_cast<VectorType>(Ty))
865097a140dSpatrick     return ConstantVector::getSplat(VTy->getElementCount(), FalseC);
86609467b48Spatrick   return FalseC;
86709467b48Spatrick }
86809467b48Spatrick 
getBool(Type * Ty,bool V)86973471bf0Spatrick Constant *ConstantInt::getBool(Type *Ty, bool V) {
87073471bf0Spatrick   return V ? getTrue(Ty) : getFalse(Ty);
87173471bf0Spatrick }
87273471bf0Spatrick 
87309467b48Spatrick // Get a ConstantInt from an APInt.
get(LLVMContext & Context,const APInt & V)87409467b48Spatrick ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
87509467b48Spatrick   // get an existing value or the insertion position
87609467b48Spatrick   LLVMContextImpl *pImpl = Context.pImpl;
87709467b48Spatrick   std::unique_ptr<ConstantInt> &Slot = pImpl->IntConstants[V];
87809467b48Spatrick   if (!Slot) {
87909467b48Spatrick     // Get the corresponding integer type for the bit width of the value.
88009467b48Spatrick     IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
88109467b48Spatrick     Slot.reset(new ConstantInt(ITy, V));
88209467b48Spatrick   }
88309467b48Spatrick   assert(Slot->getType() == IntegerType::get(Context, V.getBitWidth()));
88409467b48Spatrick   return Slot.get();
88509467b48Spatrick }
88609467b48Spatrick 
get(Type * Ty,uint64_t V,bool isSigned)88709467b48Spatrick Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
88809467b48Spatrick   Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
88909467b48Spatrick 
89009467b48Spatrick   // For vectors, broadcast the value.
89109467b48Spatrick   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
892097a140dSpatrick     return ConstantVector::getSplat(VTy->getElementCount(), C);
89309467b48Spatrick 
89409467b48Spatrick   return C;
89509467b48Spatrick }
89609467b48Spatrick 
get(IntegerType * Ty,uint64_t V,bool isSigned)89709467b48Spatrick ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V, bool isSigned) {
89809467b48Spatrick   return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
89909467b48Spatrick }
90009467b48Spatrick 
getSigned(IntegerType * Ty,int64_t V)90109467b48Spatrick ConstantInt *ConstantInt::getSigned(IntegerType *Ty, int64_t V) {
90209467b48Spatrick   return get(Ty, V, true);
90309467b48Spatrick }
90409467b48Spatrick 
getSigned(Type * Ty,int64_t V)90509467b48Spatrick Constant *ConstantInt::getSigned(Type *Ty, int64_t V) {
90609467b48Spatrick   return get(Ty, V, true);
90709467b48Spatrick }
90809467b48Spatrick 
get(Type * Ty,const APInt & V)90909467b48Spatrick Constant *ConstantInt::get(Type *Ty, const APInt& V) {
91009467b48Spatrick   ConstantInt *C = get(Ty->getContext(), V);
91109467b48Spatrick   assert(C->getType() == Ty->getScalarType() &&
91209467b48Spatrick          "ConstantInt type doesn't match the type implied by its value!");
91309467b48Spatrick 
91409467b48Spatrick   // For vectors, broadcast the value.
91509467b48Spatrick   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
916097a140dSpatrick     return ConstantVector::getSplat(VTy->getElementCount(), C);
91709467b48Spatrick 
91809467b48Spatrick   return C;
91909467b48Spatrick }
92009467b48Spatrick 
get(IntegerType * Ty,StringRef Str,uint8_t radix)92109467b48Spatrick ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str, uint8_t radix) {
92209467b48Spatrick   return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
92309467b48Spatrick }
92409467b48Spatrick 
92509467b48Spatrick /// Remove the constant from the constant table.
destroyConstantImpl()92609467b48Spatrick void ConstantInt::destroyConstantImpl() {
92709467b48Spatrick   llvm_unreachable("You can't ConstantInt->destroyConstantImpl()!");
92809467b48Spatrick }
92909467b48Spatrick 
93009467b48Spatrick //===----------------------------------------------------------------------===//
93109467b48Spatrick //                                ConstantFP
93209467b48Spatrick //===----------------------------------------------------------------------===//
93309467b48Spatrick 
get(Type * Ty,double V)93409467b48Spatrick Constant *ConstantFP::get(Type *Ty, double V) {
93509467b48Spatrick   LLVMContext &Context = Ty->getContext();
93609467b48Spatrick 
93709467b48Spatrick   APFloat FV(V);
93809467b48Spatrick   bool ignored;
93973471bf0Spatrick   FV.convert(Ty->getScalarType()->getFltSemantics(),
94009467b48Spatrick              APFloat::rmNearestTiesToEven, &ignored);
94109467b48Spatrick   Constant *C = get(Context, FV);
94209467b48Spatrick 
94309467b48Spatrick   // For vectors, broadcast the value.
94409467b48Spatrick   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
945097a140dSpatrick     return ConstantVector::getSplat(VTy->getElementCount(), C);
94609467b48Spatrick 
94709467b48Spatrick   return C;
94809467b48Spatrick }
94909467b48Spatrick 
get(Type * Ty,const APFloat & V)95009467b48Spatrick Constant *ConstantFP::get(Type *Ty, const APFloat &V) {
95109467b48Spatrick   ConstantFP *C = get(Ty->getContext(), V);
95209467b48Spatrick   assert(C->getType() == Ty->getScalarType() &&
95309467b48Spatrick          "ConstantFP type doesn't match the type implied by its value!");
95409467b48Spatrick 
95509467b48Spatrick   // For vectors, broadcast the value.
95609467b48Spatrick   if (auto *VTy = dyn_cast<VectorType>(Ty))
957097a140dSpatrick     return ConstantVector::getSplat(VTy->getElementCount(), C);
95809467b48Spatrick 
95909467b48Spatrick   return C;
96009467b48Spatrick }
96109467b48Spatrick 
get(Type * Ty,StringRef Str)96209467b48Spatrick Constant *ConstantFP::get(Type *Ty, StringRef Str) {
96309467b48Spatrick   LLVMContext &Context = Ty->getContext();
96409467b48Spatrick 
96573471bf0Spatrick   APFloat FV(Ty->getScalarType()->getFltSemantics(), Str);
96609467b48Spatrick   Constant *C = get(Context, FV);
96709467b48Spatrick 
96809467b48Spatrick   // For vectors, broadcast the value.
96909467b48Spatrick   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
970097a140dSpatrick     return ConstantVector::getSplat(VTy->getElementCount(), C);
97109467b48Spatrick 
97209467b48Spatrick   return C;
97309467b48Spatrick }
97409467b48Spatrick 
getNaN(Type * Ty,bool Negative,uint64_t Payload)97509467b48Spatrick Constant *ConstantFP::getNaN(Type *Ty, bool Negative, uint64_t Payload) {
97673471bf0Spatrick   const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
97709467b48Spatrick   APFloat NaN = APFloat::getNaN(Semantics, Negative, Payload);
97809467b48Spatrick   Constant *C = get(Ty->getContext(), NaN);
97909467b48Spatrick 
98009467b48Spatrick   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
981097a140dSpatrick     return ConstantVector::getSplat(VTy->getElementCount(), C);
98209467b48Spatrick 
98309467b48Spatrick   return C;
98409467b48Spatrick }
98509467b48Spatrick 
getQNaN(Type * Ty,bool Negative,APInt * Payload)98609467b48Spatrick Constant *ConstantFP::getQNaN(Type *Ty, bool Negative, APInt *Payload) {
98773471bf0Spatrick   const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
98809467b48Spatrick   APFloat NaN = APFloat::getQNaN(Semantics, Negative, Payload);
98909467b48Spatrick   Constant *C = get(Ty->getContext(), NaN);
99009467b48Spatrick 
99109467b48Spatrick   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
992097a140dSpatrick     return ConstantVector::getSplat(VTy->getElementCount(), C);
99309467b48Spatrick 
99409467b48Spatrick   return C;
99509467b48Spatrick }
99609467b48Spatrick 
getSNaN(Type * Ty,bool Negative,APInt * Payload)99709467b48Spatrick Constant *ConstantFP::getSNaN(Type *Ty, bool Negative, APInt *Payload) {
99873471bf0Spatrick   const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
99909467b48Spatrick   APFloat NaN = APFloat::getSNaN(Semantics, Negative, Payload);
100009467b48Spatrick   Constant *C = get(Ty->getContext(), NaN);
100109467b48Spatrick 
100209467b48Spatrick   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1003097a140dSpatrick     return ConstantVector::getSplat(VTy->getElementCount(), C);
100409467b48Spatrick 
100509467b48Spatrick   return C;
100609467b48Spatrick }
100709467b48Spatrick 
getZero(Type * Ty,bool Negative)1008*d415bd75Srobert Constant *ConstantFP::getZero(Type *Ty, bool Negative) {
100973471bf0Spatrick   const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1010*d415bd75Srobert   APFloat NegZero = APFloat::getZero(Semantics, Negative);
101109467b48Spatrick   Constant *C = get(Ty->getContext(), NegZero);
101209467b48Spatrick 
101309467b48Spatrick   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1014097a140dSpatrick     return ConstantVector::getSplat(VTy->getElementCount(), C);
101509467b48Spatrick 
101609467b48Spatrick   return C;
101709467b48Spatrick }
101809467b48Spatrick 
getZeroValueForNegation(Type * Ty)101909467b48Spatrick Constant *ConstantFP::getZeroValueForNegation(Type *Ty) {
102009467b48Spatrick   if (Ty->isFPOrFPVectorTy())
102109467b48Spatrick     return getNegativeZero(Ty);
102209467b48Spatrick 
102309467b48Spatrick   return Constant::getNullValue(Ty);
102409467b48Spatrick }
102509467b48Spatrick 
102609467b48Spatrick 
102709467b48Spatrick // ConstantFP accessors.
get(LLVMContext & Context,const APFloat & V)102809467b48Spatrick ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
102909467b48Spatrick   LLVMContextImpl* pImpl = Context.pImpl;
103009467b48Spatrick 
103109467b48Spatrick   std::unique_ptr<ConstantFP> &Slot = pImpl->FPConstants[V];
103209467b48Spatrick 
103309467b48Spatrick   if (!Slot) {
103473471bf0Spatrick     Type *Ty = Type::getFloatingPointTy(Context, V.getSemantics());
103509467b48Spatrick     Slot.reset(new ConstantFP(Ty, V));
103609467b48Spatrick   }
103709467b48Spatrick 
103809467b48Spatrick   return Slot.get();
103909467b48Spatrick }
104009467b48Spatrick 
getInfinity(Type * Ty,bool Negative)104109467b48Spatrick Constant *ConstantFP::getInfinity(Type *Ty, bool Negative) {
104273471bf0Spatrick   const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
104309467b48Spatrick   Constant *C = get(Ty->getContext(), APFloat::getInf(Semantics, Negative));
104409467b48Spatrick 
104509467b48Spatrick   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1046097a140dSpatrick     return ConstantVector::getSplat(VTy->getElementCount(), C);
104709467b48Spatrick 
104809467b48Spatrick   return C;
104909467b48Spatrick }
105009467b48Spatrick 
ConstantFP(Type * Ty,const APFloat & V)105109467b48Spatrick ConstantFP::ConstantFP(Type *Ty, const APFloat &V)
105209467b48Spatrick     : ConstantData(Ty, ConstantFPVal), Val(V) {
105373471bf0Spatrick   assert(&V.getSemantics() == &Ty->getFltSemantics() &&
105409467b48Spatrick          "FP type Mismatch");
105509467b48Spatrick }
105609467b48Spatrick 
isExactlyValue(const APFloat & V) const105709467b48Spatrick bool ConstantFP::isExactlyValue(const APFloat &V) const {
105809467b48Spatrick   return Val.bitwiseIsEqual(V);
105909467b48Spatrick }
106009467b48Spatrick 
106109467b48Spatrick /// Remove the constant from the constant table.
destroyConstantImpl()106209467b48Spatrick void ConstantFP::destroyConstantImpl() {
106309467b48Spatrick   llvm_unreachable("You can't ConstantFP->destroyConstantImpl()!");
106409467b48Spatrick }
106509467b48Spatrick 
106609467b48Spatrick //===----------------------------------------------------------------------===//
106709467b48Spatrick //                   ConstantAggregateZero Implementation
106809467b48Spatrick //===----------------------------------------------------------------------===//
106909467b48Spatrick 
getSequentialElement() const107009467b48Spatrick Constant *ConstantAggregateZero::getSequentialElement() const {
1071097a140dSpatrick   if (auto *AT = dyn_cast<ArrayType>(getType()))
1072097a140dSpatrick     return Constant::getNullValue(AT->getElementType());
1073097a140dSpatrick   return Constant::getNullValue(cast<VectorType>(getType())->getElementType());
107409467b48Spatrick }
107509467b48Spatrick 
getStructElement(unsigned Elt) const107609467b48Spatrick Constant *ConstantAggregateZero::getStructElement(unsigned Elt) const {
107709467b48Spatrick   return Constant::getNullValue(getType()->getStructElementType(Elt));
107809467b48Spatrick }
107909467b48Spatrick 
getElementValue(Constant * C) const108009467b48Spatrick Constant *ConstantAggregateZero::getElementValue(Constant *C) const {
1081097a140dSpatrick   if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
108209467b48Spatrick     return getSequentialElement();
108309467b48Spatrick   return getStructElement(cast<ConstantInt>(C)->getZExtValue());
108409467b48Spatrick }
108509467b48Spatrick 
getElementValue(unsigned Idx) const108609467b48Spatrick Constant *ConstantAggregateZero::getElementValue(unsigned Idx) const {
1087097a140dSpatrick   if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
108809467b48Spatrick     return getSequentialElement();
108909467b48Spatrick   return getStructElement(Idx);
109009467b48Spatrick }
109109467b48Spatrick 
getElementCount() const109273471bf0Spatrick ElementCount ConstantAggregateZero::getElementCount() const {
109309467b48Spatrick   Type *Ty = getType();
109409467b48Spatrick   if (auto *AT = dyn_cast<ArrayType>(Ty))
109573471bf0Spatrick     return ElementCount::getFixed(AT->getNumElements());
109609467b48Spatrick   if (auto *VT = dyn_cast<VectorType>(Ty))
109773471bf0Spatrick     return VT->getElementCount();
109873471bf0Spatrick   return ElementCount::getFixed(Ty->getStructNumElements());
109909467b48Spatrick }
110009467b48Spatrick 
110109467b48Spatrick //===----------------------------------------------------------------------===//
110209467b48Spatrick //                         UndefValue Implementation
110309467b48Spatrick //===----------------------------------------------------------------------===//
110409467b48Spatrick 
getSequentialElement() const110509467b48Spatrick UndefValue *UndefValue::getSequentialElement() const {
1106097a140dSpatrick   if (ArrayType *ATy = dyn_cast<ArrayType>(getType()))
1107097a140dSpatrick     return UndefValue::get(ATy->getElementType());
1108097a140dSpatrick   return UndefValue::get(cast<VectorType>(getType())->getElementType());
110909467b48Spatrick }
111009467b48Spatrick 
getStructElement(unsigned Elt) const111109467b48Spatrick UndefValue *UndefValue::getStructElement(unsigned Elt) const {
111209467b48Spatrick   return UndefValue::get(getType()->getStructElementType(Elt));
111309467b48Spatrick }
111409467b48Spatrick 
getElementValue(Constant * C) const111509467b48Spatrick UndefValue *UndefValue::getElementValue(Constant *C) const {
1116097a140dSpatrick   if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
111709467b48Spatrick     return getSequentialElement();
111809467b48Spatrick   return getStructElement(cast<ConstantInt>(C)->getZExtValue());
111909467b48Spatrick }
112009467b48Spatrick 
getElementValue(unsigned Idx) const112109467b48Spatrick UndefValue *UndefValue::getElementValue(unsigned Idx) const {
1122097a140dSpatrick   if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
112309467b48Spatrick     return getSequentialElement();
112409467b48Spatrick   return getStructElement(Idx);
112509467b48Spatrick }
112609467b48Spatrick 
getNumElements() const112709467b48Spatrick unsigned UndefValue::getNumElements() const {
112809467b48Spatrick   Type *Ty = getType();
1129097a140dSpatrick   if (auto *AT = dyn_cast<ArrayType>(Ty))
1130097a140dSpatrick     return AT->getNumElements();
1131097a140dSpatrick   if (auto *VT = dyn_cast<VectorType>(Ty))
113273471bf0Spatrick     return cast<FixedVectorType>(VT)->getNumElements();
113309467b48Spatrick   return Ty->getStructNumElements();
113409467b48Spatrick }
113509467b48Spatrick 
113609467b48Spatrick //===----------------------------------------------------------------------===//
113773471bf0Spatrick //                         PoisonValue Implementation
113873471bf0Spatrick //===----------------------------------------------------------------------===//
113973471bf0Spatrick 
getSequentialElement() const114073471bf0Spatrick PoisonValue *PoisonValue::getSequentialElement() const {
114173471bf0Spatrick   if (ArrayType *ATy = dyn_cast<ArrayType>(getType()))
114273471bf0Spatrick     return PoisonValue::get(ATy->getElementType());
114373471bf0Spatrick   return PoisonValue::get(cast<VectorType>(getType())->getElementType());
114473471bf0Spatrick }
114573471bf0Spatrick 
getStructElement(unsigned Elt) const114673471bf0Spatrick PoisonValue *PoisonValue::getStructElement(unsigned Elt) const {
114773471bf0Spatrick   return PoisonValue::get(getType()->getStructElementType(Elt));
114873471bf0Spatrick }
114973471bf0Spatrick 
getElementValue(Constant * C) const115073471bf0Spatrick PoisonValue *PoisonValue::getElementValue(Constant *C) const {
115173471bf0Spatrick   if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
115273471bf0Spatrick     return getSequentialElement();
115373471bf0Spatrick   return getStructElement(cast<ConstantInt>(C)->getZExtValue());
115473471bf0Spatrick }
115573471bf0Spatrick 
getElementValue(unsigned Idx) const115673471bf0Spatrick PoisonValue *PoisonValue::getElementValue(unsigned Idx) const {
115773471bf0Spatrick   if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
115873471bf0Spatrick     return getSequentialElement();
115973471bf0Spatrick   return getStructElement(Idx);
116073471bf0Spatrick }
116173471bf0Spatrick 
116273471bf0Spatrick //===----------------------------------------------------------------------===//
116309467b48Spatrick //                            ConstantXXX Classes
116409467b48Spatrick //===----------------------------------------------------------------------===//
116509467b48Spatrick 
116609467b48Spatrick template <typename ItTy, typename EltTy>
rangeOnlyContains(ItTy Start,ItTy End,EltTy Elt)116709467b48Spatrick static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
116809467b48Spatrick   for (; Start != End; ++Start)
116909467b48Spatrick     if (*Start != Elt)
117009467b48Spatrick       return false;
117109467b48Spatrick   return true;
117209467b48Spatrick }
117309467b48Spatrick 
117409467b48Spatrick template <typename SequentialTy, typename ElementTy>
getIntSequenceIfElementsMatch(ArrayRef<Constant * > V)117509467b48Spatrick static Constant *getIntSequenceIfElementsMatch(ArrayRef<Constant *> V) {
117609467b48Spatrick   assert(!V.empty() && "Cannot get empty int sequence.");
117709467b48Spatrick 
117809467b48Spatrick   SmallVector<ElementTy, 16> Elts;
117909467b48Spatrick   for (Constant *C : V)
118009467b48Spatrick     if (auto *CI = dyn_cast<ConstantInt>(C))
118109467b48Spatrick       Elts.push_back(CI->getZExtValue());
118209467b48Spatrick     else
118309467b48Spatrick       return nullptr;
118409467b48Spatrick   return SequentialTy::get(V[0]->getContext(), Elts);
118509467b48Spatrick }
118609467b48Spatrick 
118709467b48Spatrick template <typename SequentialTy, typename ElementTy>
getFPSequenceIfElementsMatch(ArrayRef<Constant * > V)118809467b48Spatrick static Constant *getFPSequenceIfElementsMatch(ArrayRef<Constant *> V) {
118909467b48Spatrick   assert(!V.empty() && "Cannot get empty FP sequence.");
119009467b48Spatrick 
119109467b48Spatrick   SmallVector<ElementTy, 16> Elts;
119209467b48Spatrick   for (Constant *C : V)
119309467b48Spatrick     if (auto *CFP = dyn_cast<ConstantFP>(C))
119409467b48Spatrick       Elts.push_back(CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
119509467b48Spatrick     else
119609467b48Spatrick       return nullptr;
1197097a140dSpatrick   return SequentialTy::getFP(V[0]->getType(), Elts);
119809467b48Spatrick }
119909467b48Spatrick 
120009467b48Spatrick template <typename SequenceTy>
getSequenceIfElementsMatch(Constant * C,ArrayRef<Constant * > V)120109467b48Spatrick static Constant *getSequenceIfElementsMatch(Constant *C,
120209467b48Spatrick                                             ArrayRef<Constant *> V) {
120309467b48Spatrick   // We speculatively build the elements here even if it turns out that there is
120409467b48Spatrick   // a constantexpr or something else weird, since it is so uncommon for that to
120509467b48Spatrick   // happen.
120609467b48Spatrick   if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
120709467b48Spatrick     if (CI->getType()->isIntegerTy(8))
120809467b48Spatrick       return getIntSequenceIfElementsMatch<SequenceTy, uint8_t>(V);
120909467b48Spatrick     else if (CI->getType()->isIntegerTy(16))
121009467b48Spatrick       return getIntSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
121109467b48Spatrick     else if (CI->getType()->isIntegerTy(32))
121209467b48Spatrick       return getIntSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
121309467b48Spatrick     else if (CI->getType()->isIntegerTy(64))
121409467b48Spatrick       return getIntSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
121509467b48Spatrick   } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
1216097a140dSpatrick     if (CFP->getType()->isHalfTy() || CFP->getType()->isBFloatTy())
121709467b48Spatrick       return getFPSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
121809467b48Spatrick     else if (CFP->getType()->isFloatTy())
121909467b48Spatrick       return getFPSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
122009467b48Spatrick     else if (CFP->getType()->isDoubleTy())
122109467b48Spatrick       return getFPSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
122209467b48Spatrick   }
122309467b48Spatrick 
122409467b48Spatrick   return nullptr;
122509467b48Spatrick }
122609467b48Spatrick 
ConstantAggregate(Type * T,ValueTy VT,ArrayRef<Constant * > V)1227097a140dSpatrick ConstantAggregate::ConstantAggregate(Type *T, ValueTy VT,
122809467b48Spatrick                                      ArrayRef<Constant *> V)
122909467b48Spatrick     : Constant(T, VT, OperandTraits<ConstantAggregate>::op_end(this) - V.size(),
123009467b48Spatrick                V.size()) {
123109467b48Spatrick   llvm::copy(V, op_begin());
123209467b48Spatrick 
123309467b48Spatrick   // Check that types match, unless this is an opaque struct.
1234097a140dSpatrick   if (auto *ST = dyn_cast<StructType>(T)) {
123509467b48Spatrick     if (ST->isOpaque())
123609467b48Spatrick       return;
123709467b48Spatrick     for (unsigned I = 0, E = V.size(); I != E; ++I)
1238097a140dSpatrick       assert(V[I]->getType() == ST->getTypeAtIndex(I) &&
1239097a140dSpatrick              "Initializer for struct element doesn't match!");
1240097a140dSpatrick   }
124109467b48Spatrick }
124209467b48Spatrick 
ConstantArray(ArrayType * T,ArrayRef<Constant * > V)124309467b48Spatrick ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
124409467b48Spatrick     : ConstantAggregate(T, ConstantArrayVal, V) {
124509467b48Spatrick   assert(V.size() == T->getNumElements() &&
124609467b48Spatrick          "Invalid initializer for constant array");
124709467b48Spatrick }
124809467b48Spatrick 
get(ArrayType * Ty,ArrayRef<Constant * > V)124909467b48Spatrick Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
125009467b48Spatrick   if (Constant *C = getImpl(Ty, V))
125109467b48Spatrick     return C;
125209467b48Spatrick   return Ty->getContext().pImpl->ArrayConstants.getOrCreate(Ty, V);
125309467b48Spatrick }
125409467b48Spatrick 
getImpl(ArrayType * Ty,ArrayRef<Constant * > V)125509467b48Spatrick Constant *ConstantArray::getImpl(ArrayType *Ty, ArrayRef<Constant*> V) {
125609467b48Spatrick   // Empty arrays are canonicalized to ConstantAggregateZero.
125709467b48Spatrick   if (V.empty())
125809467b48Spatrick     return ConstantAggregateZero::get(Ty);
125909467b48Spatrick 
1260*d415bd75Srobert   for (Constant *C : V) {
1261*d415bd75Srobert     assert(C->getType() == Ty->getElementType() &&
126209467b48Spatrick            "Wrong type in array element initializer");
1263*d415bd75Srobert     (void)C;
126409467b48Spatrick   }
126509467b48Spatrick 
126609467b48Spatrick   // If this is an all-zero array, return a ConstantAggregateZero object.  If
126709467b48Spatrick   // all undef, return an UndefValue, if "all simple", then return a
126809467b48Spatrick   // ConstantDataArray.
126909467b48Spatrick   Constant *C = V[0];
127073471bf0Spatrick   if (isa<PoisonValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
127173471bf0Spatrick     return PoisonValue::get(Ty);
127273471bf0Spatrick 
127309467b48Spatrick   if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
127409467b48Spatrick     return UndefValue::get(Ty);
127509467b48Spatrick 
127609467b48Spatrick   if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
127709467b48Spatrick     return ConstantAggregateZero::get(Ty);
127809467b48Spatrick 
127909467b48Spatrick   // Check to see if all of the elements are ConstantFP or ConstantInt and if
128009467b48Spatrick   // the element type is compatible with ConstantDataVector.  If so, use it.
128109467b48Spatrick   if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
128209467b48Spatrick     return getSequenceIfElementsMatch<ConstantDataArray>(C, V);
128309467b48Spatrick 
128409467b48Spatrick   // Otherwise, we really do want to create a ConstantArray.
128509467b48Spatrick   return nullptr;
128609467b48Spatrick }
128709467b48Spatrick 
getTypeForElements(LLVMContext & Context,ArrayRef<Constant * > V,bool Packed)128809467b48Spatrick StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
128909467b48Spatrick                                                ArrayRef<Constant*> V,
129009467b48Spatrick                                                bool Packed) {
129109467b48Spatrick   unsigned VecSize = V.size();
129209467b48Spatrick   SmallVector<Type*, 16> EltTypes(VecSize);
129309467b48Spatrick   for (unsigned i = 0; i != VecSize; ++i)
129409467b48Spatrick     EltTypes[i] = V[i]->getType();
129509467b48Spatrick 
129609467b48Spatrick   return StructType::get(Context, EltTypes, Packed);
129709467b48Spatrick }
129809467b48Spatrick 
129909467b48Spatrick 
getTypeForElements(ArrayRef<Constant * > V,bool Packed)130009467b48Spatrick StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
130109467b48Spatrick                                                bool Packed) {
130209467b48Spatrick   assert(!V.empty() &&
130309467b48Spatrick          "ConstantStruct::getTypeForElements cannot be called on empty list");
130409467b48Spatrick   return getTypeForElements(V[0]->getContext(), V, Packed);
130509467b48Spatrick }
130609467b48Spatrick 
ConstantStruct(StructType * T,ArrayRef<Constant * > V)130709467b48Spatrick ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
130809467b48Spatrick     : ConstantAggregate(T, ConstantStructVal, V) {
130909467b48Spatrick   assert((T->isOpaque() || V.size() == T->getNumElements()) &&
131009467b48Spatrick          "Invalid initializer for constant struct");
131109467b48Spatrick }
131209467b48Spatrick 
131309467b48Spatrick // ConstantStruct accessors.
get(StructType * ST,ArrayRef<Constant * > V)131409467b48Spatrick Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
131509467b48Spatrick   assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
131609467b48Spatrick          "Incorrect # elements specified to ConstantStruct::get");
131709467b48Spatrick 
131809467b48Spatrick   // Create a ConstantAggregateZero value if all elements are zeros.
131909467b48Spatrick   bool isZero = true;
132009467b48Spatrick   bool isUndef = false;
132173471bf0Spatrick   bool isPoison = false;
132209467b48Spatrick 
132309467b48Spatrick   if (!V.empty()) {
132409467b48Spatrick     isUndef = isa<UndefValue>(V[0]);
132573471bf0Spatrick     isPoison = isa<PoisonValue>(V[0]);
132609467b48Spatrick     isZero = V[0]->isNullValue();
132773471bf0Spatrick     // PoisonValue inherits UndefValue, so its check is not necessary.
132809467b48Spatrick     if (isUndef || isZero) {
1329*d415bd75Srobert       for (Constant *C : V) {
1330*d415bd75Srobert         if (!C->isNullValue())
133109467b48Spatrick           isZero = false;
1332*d415bd75Srobert         if (!isa<PoisonValue>(C))
133373471bf0Spatrick           isPoison = false;
1334*d415bd75Srobert         if (isa<PoisonValue>(C) || !isa<UndefValue>(C))
133509467b48Spatrick           isUndef = false;
133609467b48Spatrick       }
133709467b48Spatrick     }
133809467b48Spatrick   }
133909467b48Spatrick   if (isZero)
134009467b48Spatrick     return ConstantAggregateZero::get(ST);
134173471bf0Spatrick   if (isPoison)
134273471bf0Spatrick     return PoisonValue::get(ST);
134309467b48Spatrick   if (isUndef)
134409467b48Spatrick     return UndefValue::get(ST);
134509467b48Spatrick 
134609467b48Spatrick   return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
134709467b48Spatrick }
134809467b48Spatrick 
ConstantVector(VectorType * T,ArrayRef<Constant * > V)134909467b48Spatrick ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
135009467b48Spatrick     : ConstantAggregate(T, ConstantVectorVal, V) {
135173471bf0Spatrick   assert(V.size() == cast<FixedVectorType>(T)->getNumElements() &&
135209467b48Spatrick          "Invalid initializer for constant vector");
135309467b48Spatrick }
135409467b48Spatrick 
135509467b48Spatrick // ConstantVector accessors.
get(ArrayRef<Constant * > V)135609467b48Spatrick Constant *ConstantVector::get(ArrayRef<Constant*> V) {
135709467b48Spatrick   if (Constant *C = getImpl(V))
135809467b48Spatrick     return C;
1359097a140dSpatrick   auto *Ty = FixedVectorType::get(V.front()->getType(), V.size());
136009467b48Spatrick   return Ty->getContext().pImpl->VectorConstants.getOrCreate(Ty, V);
136109467b48Spatrick }
136209467b48Spatrick 
getImpl(ArrayRef<Constant * > V)136309467b48Spatrick Constant *ConstantVector::getImpl(ArrayRef<Constant*> V) {
136409467b48Spatrick   assert(!V.empty() && "Vectors can't be empty");
1365097a140dSpatrick   auto *T = FixedVectorType::get(V.front()->getType(), V.size());
136609467b48Spatrick 
136709467b48Spatrick   // If this is an all-undef or all-zero vector, return a
136809467b48Spatrick   // ConstantAggregateZero or UndefValue.
136909467b48Spatrick   Constant *C = V[0];
137009467b48Spatrick   bool isZero = C->isNullValue();
137109467b48Spatrick   bool isUndef = isa<UndefValue>(C);
137273471bf0Spatrick   bool isPoison = isa<PoisonValue>(C);
137309467b48Spatrick 
137409467b48Spatrick   if (isZero || isUndef) {
137509467b48Spatrick     for (unsigned i = 1, e = V.size(); i != e; ++i)
137609467b48Spatrick       if (V[i] != C) {
137773471bf0Spatrick         isZero = isUndef = isPoison = false;
137809467b48Spatrick         break;
137909467b48Spatrick       }
138009467b48Spatrick   }
138109467b48Spatrick 
138209467b48Spatrick   if (isZero)
138309467b48Spatrick     return ConstantAggregateZero::get(T);
138473471bf0Spatrick   if (isPoison)
138573471bf0Spatrick     return PoisonValue::get(T);
138609467b48Spatrick   if (isUndef)
138709467b48Spatrick     return UndefValue::get(T);
138809467b48Spatrick 
138909467b48Spatrick   // Check to see if all of the elements are ConstantFP or ConstantInt and if
139009467b48Spatrick   // the element type is compatible with ConstantDataVector.  If so, use it.
139109467b48Spatrick   if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
139209467b48Spatrick     return getSequenceIfElementsMatch<ConstantDataVector>(C, V);
139309467b48Spatrick 
139409467b48Spatrick   // Otherwise, the element type isn't compatible with ConstantDataVector, or
139509467b48Spatrick   // the operand list contains a ConstantExpr or something else strange.
139609467b48Spatrick   return nullptr;
139709467b48Spatrick }
139809467b48Spatrick 
getSplat(ElementCount EC,Constant * V)1399097a140dSpatrick Constant *ConstantVector::getSplat(ElementCount EC, Constant *V) {
140073471bf0Spatrick   if (!EC.isScalable()) {
140109467b48Spatrick     // If this splat is compatible with ConstantDataVector, use it instead of
140209467b48Spatrick     // ConstantVector.
140309467b48Spatrick     if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&
140409467b48Spatrick         ConstantDataSequential::isElementTypeCompatible(V->getType()))
140573471bf0Spatrick       return ConstantDataVector::getSplat(EC.getKnownMinValue(), V);
140609467b48Spatrick 
140773471bf0Spatrick     SmallVector<Constant *, 32> Elts(EC.getKnownMinValue(), V);
140809467b48Spatrick     return get(Elts);
140909467b48Spatrick   }
141009467b48Spatrick 
1411097a140dSpatrick   Type *VTy = VectorType::get(V->getType(), EC);
1412097a140dSpatrick 
1413097a140dSpatrick   if (V->isNullValue())
1414097a140dSpatrick     return ConstantAggregateZero::get(VTy);
1415097a140dSpatrick   else if (isa<UndefValue>(V))
1416097a140dSpatrick     return UndefValue::get(VTy);
1417097a140dSpatrick 
1418*d415bd75Srobert   Type *IdxTy = Type::getInt64Ty(VTy->getContext());
1419097a140dSpatrick 
1420097a140dSpatrick   // Move scalar into vector.
1421*d415bd75Srobert   Constant *PoisonV = PoisonValue::get(VTy);
1422*d415bd75Srobert   V = ConstantExpr::getInsertElement(PoisonV, V, ConstantInt::get(IdxTy, 0));
1423097a140dSpatrick   // Build shuffle mask to perform the splat.
142473471bf0Spatrick   SmallVector<int, 8> Zeros(EC.getKnownMinValue(), 0);
1425097a140dSpatrick   // Splat.
1426*d415bd75Srobert   return ConstantExpr::getShuffleVector(V, PoisonV, Zeros);
1427097a140dSpatrick }
1428097a140dSpatrick 
get(LLVMContext & Context)142909467b48Spatrick ConstantTokenNone *ConstantTokenNone::get(LLVMContext &Context) {
143009467b48Spatrick   LLVMContextImpl *pImpl = Context.pImpl;
143109467b48Spatrick   if (!pImpl->TheNoneToken)
143209467b48Spatrick     pImpl->TheNoneToken.reset(new ConstantTokenNone(Context));
143309467b48Spatrick   return pImpl->TheNoneToken.get();
143409467b48Spatrick }
143509467b48Spatrick 
143609467b48Spatrick /// Remove the constant from the constant table.
destroyConstantImpl()143709467b48Spatrick void ConstantTokenNone::destroyConstantImpl() {
143809467b48Spatrick   llvm_unreachable("You can't ConstantTokenNone->destroyConstantImpl()!");
143909467b48Spatrick }
144009467b48Spatrick 
144109467b48Spatrick // Utility function for determining if a ConstantExpr is a CastOp or not. This
144209467b48Spatrick // can't be inline because we don't want to #include Instruction.h into
144309467b48Spatrick // Constant.h
isCast() const144409467b48Spatrick bool ConstantExpr::isCast() const {
144509467b48Spatrick   return Instruction::isCast(getOpcode());
144609467b48Spatrick }
144709467b48Spatrick 
isCompare() const144809467b48Spatrick bool ConstantExpr::isCompare() const {
144909467b48Spatrick   return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
145009467b48Spatrick }
145109467b48Spatrick 
getPredicate() const145209467b48Spatrick unsigned ConstantExpr::getPredicate() const {
145309467b48Spatrick   return cast<CompareConstantExpr>(this)->predicate;
145409467b48Spatrick }
145509467b48Spatrick 
getShuffleMask() const1456097a140dSpatrick ArrayRef<int> ConstantExpr::getShuffleMask() const {
1457097a140dSpatrick   return cast<ShuffleVectorConstantExpr>(this)->ShuffleMask;
1458097a140dSpatrick }
1459097a140dSpatrick 
getShuffleMaskForBitcode() const1460097a140dSpatrick Constant *ConstantExpr::getShuffleMaskForBitcode() const {
1461097a140dSpatrick   return cast<ShuffleVectorConstantExpr>(this)->ShuffleMaskForBitcode;
1462097a140dSpatrick }
1463097a140dSpatrick 
getWithOperands(ArrayRef<Constant * > Ops,Type * Ty,bool OnlyIfReduced,Type * SrcTy) const146409467b48Spatrick Constant *ConstantExpr::getWithOperands(ArrayRef<Constant *> Ops, Type *Ty,
146509467b48Spatrick                                         bool OnlyIfReduced, Type *SrcTy) const {
146609467b48Spatrick   assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
146709467b48Spatrick 
146809467b48Spatrick   // If no operands changed return self.
146909467b48Spatrick   if (Ty == getType() && std::equal(Ops.begin(), Ops.end(), op_begin()))
147009467b48Spatrick     return const_cast<ConstantExpr*>(this);
147109467b48Spatrick 
147209467b48Spatrick   Type *OnlyIfReducedTy = OnlyIfReduced ? Ty : nullptr;
147309467b48Spatrick   switch (getOpcode()) {
147409467b48Spatrick   case Instruction::Trunc:
147509467b48Spatrick   case Instruction::ZExt:
147609467b48Spatrick   case Instruction::SExt:
147709467b48Spatrick   case Instruction::FPTrunc:
147809467b48Spatrick   case Instruction::FPExt:
147909467b48Spatrick   case Instruction::UIToFP:
148009467b48Spatrick   case Instruction::SIToFP:
148109467b48Spatrick   case Instruction::FPToUI:
148209467b48Spatrick   case Instruction::FPToSI:
148309467b48Spatrick   case Instruction::PtrToInt:
148409467b48Spatrick   case Instruction::IntToPtr:
148509467b48Spatrick   case Instruction::BitCast:
148609467b48Spatrick   case Instruction::AddrSpaceCast:
148709467b48Spatrick     return ConstantExpr::getCast(getOpcode(), Ops[0], Ty, OnlyIfReduced);
148809467b48Spatrick   case Instruction::Select:
148909467b48Spatrick     return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2], OnlyIfReducedTy);
149009467b48Spatrick   case Instruction::InsertElement:
149109467b48Spatrick     return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2],
149209467b48Spatrick                                           OnlyIfReducedTy);
149309467b48Spatrick   case Instruction::ExtractElement:
149409467b48Spatrick     return ConstantExpr::getExtractElement(Ops[0], Ops[1], OnlyIfReducedTy);
149509467b48Spatrick   case Instruction::ShuffleVector:
1496097a140dSpatrick     return ConstantExpr::getShuffleVector(Ops[0], Ops[1], getShuffleMask(),
149709467b48Spatrick                                           OnlyIfReducedTy);
149809467b48Spatrick   case Instruction::GetElementPtr: {
149909467b48Spatrick     auto *GEPO = cast<GEPOperator>(this);
150009467b48Spatrick     assert(SrcTy || (Ops[0]->getType() == getOperand(0)->getType()));
150109467b48Spatrick     return ConstantExpr::getGetElementPtr(
150209467b48Spatrick         SrcTy ? SrcTy : GEPO->getSourceElementType(), Ops[0], Ops.slice(1),
150309467b48Spatrick         GEPO->isInBounds(), GEPO->getInRangeIndex(), OnlyIfReducedTy);
150409467b48Spatrick   }
150509467b48Spatrick   case Instruction::ICmp:
150609467b48Spatrick   case Instruction::FCmp:
150709467b48Spatrick     return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1],
150809467b48Spatrick                                     OnlyIfReducedTy);
150909467b48Spatrick   default:
151009467b48Spatrick     assert(getNumOperands() == 2 && "Must be binary operator?");
151109467b48Spatrick     return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData,
151209467b48Spatrick                              OnlyIfReducedTy);
151309467b48Spatrick   }
151409467b48Spatrick }
151509467b48Spatrick 
151609467b48Spatrick 
151709467b48Spatrick //===----------------------------------------------------------------------===//
151809467b48Spatrick //                      isValueValidForType implementations
151909467b48Spatrick 
isValueValidForType(Type * Ty,uint64_t Val)152009467b48Spatrick bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
152109467b48Spatrick   unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
152209467b48Spatrick   if (Ty->isIntegerTy(1))
152309467b48Spatrick     return Val == 0 || Val == 1;
152409467b48Spatrick   return isUIntN(NumBits, Val);
152509467b48Spatrick }
152609467b48Spatrick 
isValueValidForType(Type * Ty,int64_t Val)152709467b48Spatrick bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
152809467b48Spatrick   unsigned NumBits = Ty->getIntegerBitWidth();
152909467b48Spatrick   if (Ty->isIntegerTy(1))
153009467b48Spatrick     return Val == 0 || Val == 1 || Val == -1;
153109467b48Spatrick   return isIntN(NumBits, Val);
153209467b48Spatrick }
153309467b48Spatrick 
isValueValidForType(Type * Ty,const APFloat & Val)153409467b48Spatrick bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {
153509467b48Spatrick   // convert modifies in place, so make a copy.
153609467b48Spatrick   APFloat Val2 = APFloat(Val);
153709467b48Spatrick   bool losesInfo;
153809467b48Spatrick   switch (Ty->getTypeID()) {
153909467b48Spatrick   default:
154009467b48Spatrick     return false;         // These can't be represented as floating point!
154109467b48Spatrick 
154209467b48Spatrick   // FIXME rounding mode needs to be more flexible
154309467b48Spatrick   case Type::HalfTyID: {
154409467b48Spatrick     if (&Val2.getSemantics() == &APFloat::IEEEhalf())
154509467b48Spatrick       return true;
154609467b48Spatrick     Val2.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &losesInfo);
154709467b48Spatrick     return !losesInfo;
154809467b48Spatrick   }
1549097a140dSpatrick   case Type::BFloatTyID: {
1550097a140dSpatrick     if (&Val2.getSemantics() == &APFloat::BFloat())
1551097a140dSpatrick       return true;
1552097a140dSpatrick     Val2.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven, &losesInfo);
1553097a140dSpatrick     return !losesInfo;
1554097a140dSpatrick   }
155509467b48Spatrick   case Type::FloatTyID: {
155609467b48Spatrick     if (&Val2.getSemantics() == &APFloat::IEEEsingle())
155709467b48Spatrick       return true;
155809467b48Spatrick     Val2.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &losesInfo);
155909467b48Spatrick     return !losesInfo;
156009467b48Spatrick   }
156109467b48Spatrick   case Type::DoubleTyID: {
156209467b48Spatrick     if (&Val2.getSemantics() == &APFloat::IEEEhalf() ||
1563097a140dSpatrick         &Val2.getSemantics() == &APFloat::BFloat() ||
156409467b48Spatrick         &Val2.getSemantics() == &APFloat::IEEEsingle() ||
156509467b48Spatrick         &Val2.getSemantics() == &APFloat::IEEEdouble())
156609467b48Spatrick       return true;
156709467b48Spatrick     Val2.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &losesInfo);
156809467b48Spatrick     return !losesInfo;
156909467b48Spatrick   }
157009467b48Spatrick   case Type::X86_FP80TyID:
157109467b48Spatrick     return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1572097a140dSpatrick            &Val2.getSemantics() == &APFloat::BFloat() ||
157309467b48Spatrick            &Val2.getSemantics() == &APFloat::IEEEsingle() ||
157409467b48Spatrick            &Val2.getSemantics() == &APFloat::IEEEdouble() ||
157509467b48Spatrick            &Val2.getSemantics() == &APFloat::x87DoubleExtended();
157609467b48Spatrick   case Type::FP128TyID:
157709467b48Spatrick     return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1578097a140dSpatrick            &Val2.getSemantics() == &APFloat::BFloat() ||
157909467b48Spatrick            &Val2.getSemantics() == &APFloat::IEEEsingle() ||
158009467b48Spatrick            &Val2.getSemantics() == &APFloat::IEEEdouble() ||
158109467b48Spatrick            &Val2.getSemantics() == &APFloat::IEEEquad();
158209467b48Spatrick   case Type::PPC_FP128TyID:
158309467b48Spatrick     return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1584097a140dSpatrick            &Val2.getSemantics() == &APFloat::BFloat() ||
158509467b48Spatrick            &Val2.getSemantics() == &APFloat::IEEEsingle() ||
158609467b48Spatrick            &Val2.getSemantics() == &APFloat::IEEEdouble() ||
158709467b48Spatrick            &Val2.getSemantics() == &APFloat::PPCDoubleDouble();
158809467b48Spatrick   }
158909467b48Spatrick }
159009467b48Spatrick 
159109467b48Spatrick 
159209467b48Spatrick //===----------------------------------------------------------------------===//
159309467b48Spatrick //                      Factory Function Implementation
159409467b48Spatrick 
get(Type * Ty)159509467b48Spatrick ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
159609467b48Spatrick   assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
159709467b48Spatrick          "Cannot create an aggregate zero of non-aggregate type!");
159809467b48Spatrick 
159909467b48Spatrick   std::unique_ptr<ConstantAggregateZero> &Entry =
160009467b48Spatrick       Ty->getContext().pImpl->CAZConstants[Ty];
160109467b48Spatrick   if (!Entry)
160209467b48Spatrick     Entry.reset(new ConstantAggregateZero(Ty));
160309467b48Spatrick 
160409467b48Spatrick   return Entry.get();
160509467b48Spatrick }
160609467b48Spatrick 
160709467b48Spatrick /// Remove the constant from the constant table.
destroyConstantImpl()160809467b48Spatrick void ConstantAggregateZero::destroyConstantImpl() {
160909467b48Spatrick   getContext().pImpl->CAZConstants.erase(getType());
161009467b48Spatrick }
161109467b48Spatrick 
161209467b48Spatrick /// Remove the constant from the constant table.
destroyConstantImpl()161309467b48Spatrick void ConstantArray::destroyConstantImpl() {
161409467b48Spatrick   getType()->getContext().pImpl->ArrayConstants.remove(this);
161509467b48Spatrick }
161609467b48Spatrick 
161709467b48Spatrick 
161809467b48Spatrick //---- ConstantStruct::get() implementation...
161909467b48Spatrick //
162009467b48Spatrick 
162109467b48Spatrick /// Remove the constant from the constant table.
destroyConstantImpl()162209467b48Spatrick void ConstantStruct::destroyConstantImpl() {
162309467b48Spatrick   getType()->getContext().pImpl->StructConstants.remove(this);
162409467b48Spatrick }
162509467b48Spatrick 
162609467b48Spatrick /// Remove the constant from the constant table.
destroyConstantImpl()162709467b48Spatrick void ConstantVector::destroyConstantImpl() {
162809467b48Spatrick   getType()->getContext().pImpl->VectorConstants.remove(this);
162909467b48Spatrick }
163009467b48Spatrick 
getSplatValue(bool AllowUndefs) const163109467b48Spatrick Constant *Constant::getSplatValue(bool AllowUndefs) const {
163209467b48Spatrick   assert(this->getType()->isVectorTy() && "Only valid for vectors!");
163309467b48Spatrick   if (isa<ConstantAggregateZero>(this))
1634097a140dSpatrick     return getNullValue(cast<VectorType>(getType())->getElementType());
163509467b48Spatrick   if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
163609467b48Spatrick     return CV->getSplatValue();
163709467b48Spatrick   if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
163809467b48Spatrick     return CV->getSplatValue(AllowUndefs);
1639097a140dSpatrick 
1640097a140dSpatrick   // Check if this is a constant expression splat of the form returned by
1641097a140dSpatrick   // ConstantVector::getSplat()
1642097a140dSpatrick   const auto *Shuf = dyn_cast<ConstantExpr>(this);
1643097a140dSpatrick   if (Shuf && Shuf->getOpcode() == Instruction::ShuffleVector &&
1644097a140dSpatrick       isa<UndefValue>(Shuf->getOperand(1))) {
1645097a140dSpatrick 
1646097a140dSpatrick     const auto *IElt = dyn_cast<ConstantExpr>(Shuf->getOperand(0));
1647097a140dSpatrick     if (IElt && IElt->getOpcode() == Instruction::InsertElement &&
1648097a140dSpatrick         isa<UndefValue>(IElt->getOperand(0))) {
1649097a140dSpatrick 
1650097a140dSpatrick       ArrayRef<int> Mask = Shuf->getShuffleMask();
1651097a140dSpatrick       Constant *SplatVal = IElt->getOperand(1);
1652097a140dSpatrick       ConstantInt *Index = dyn_cast<ConstantInt>(IElt->getOperand(2));
1653097a140dSpatrick 
1654097a140dSpatrick       if (Index && Index->getValue() == 0 &&
165573471bf0Spatrick           llvm::all_of(Mask, [](int I) { return I == 0; }))
1656097a140dSpatrick         return SplatVal;
1657097a140dSpatrick     }
1658097a140dSpatrick   }
1659097a140dSpatrick 
166009467b48Spatrick   return nullptr;
166109467b48Spatrick }
166209467b48Spatrick 
getSplatValue(bool AllowUndefs) const166309467b48Spatrick Constant *ConstantVector::getSplatValue(bool AllowUndefs) const {
166409467b48Spatrick   // Check out first element.
166509467b48Spatrick   Constant *Elt = getOperand(0);
166609467b48Spatrick   // Then make sure all remaining elements point to the same value.
166709467b48Spatrick   for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
166809467b48Spatrick     Constant *OpC = getOperand(I);
166909467b48Spatrick     if (OpC == Elt)
167009467b48Spatrick       continue;
167109467b48Spatrick 
167209467b48Spatrick     // Strict mode: any mismatch is not a splat.
167309467b48Spatrick     if (!AllowUndefs)
167409467b48Spatrick       return nullptr;
167509467b48Spatrick 
167609467b48Spatrick     // Allow undefs mode: ignore undefined elements.
167709467b48Spatrick     if (isa<UndefValue>(OpC))
167809467b48Spatrick       continue;
167909467b48Spatrick 
168009467b48Spatrick     // If we do not have a defined element yet, use the current operand.
168109467b48Spatrick     if (isa<UndefValue>(Elt))
168209467b48Spatrick       Elt = OpC;
168309467b48Spatrick 
168409467b48Spatrick     if (OpC != Elt)
168509467b48Spatrick       return nullptr;
168609467b48Spatrick   }
168709467b48Spatrick   return Elt;
168809467b48Spatrick }
168909467b48Spatrick 
getUniqueInteger() const169009467b48Spatrick const APInt &Constant::getUniqueInteger() const {
169109467b48Spatrick   if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
169209467b48Spatrick     return CI->getValue();
1693*d415bd75Srobert   // Scalable vectors can use a ConstantExpr to build a splat.
1694*d415bd75Srobert   if (isa<ConstantExpr>(this))
1695*d415bd75Srobert     return cast<ConstantInt>(this->getSplatValue())->getValue();
1696*d415bd75Srobert   // For non-ConstantExpr we use getAggregateElement as a fast path to avoid
1697*d415bd75Srobert   // calling getSplatValue in release builds.
169809467b48Spatrick   assert(this->getSplatValue() && "Doesn't contain a unique integer!");
169909467b48Spatrick   const Constant *C = this->getAggregateElement(0U);
170009467b48Spatrick   assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
170109467b48Spatrick   return cast<ConstantInt>(C)->getValue();
170209467b48Spatrick }
170309467b48Spatrick 
170409467b48Spatrick //---- ConstantPointerNull::get() implementation.
170509467b48Spatrick //
170609467b48Spatrick 
get(PointerType * Ty)170709467b48Spatrick ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
170809467b48Spatrick   std::unique_ptr<ConstantPointerNull> &Entry =
170909467b48Spatrick       Ty->getContext().pImpl->CPNConstants[Ty];
171009467b48Spatrick   if (!Entry)
171109467b48Spatrick     Entry.reset(new ConstantPointerNull(Ty));
171209467b48Spatrick 
171309467b48Spatrick   return Entry.get();
171409467b48Spatrick }
171509467b48Spatrick 
171609467b48Spatrick /// Remove the constant from the constant table.
destroyConstantImpl()171709467b48Spatrick void ConstantPointerNull::destroyConstantImpl() {
171809467b48Spatrick   getContext().pImpl->CPNConstants.erase(getType());
171909467b48Spatrick }
172009467b48Spatrick 
1721*d415bd75Srobert //---- ConstantTargetNone::get() implementation.
1722*d415bd75Srobert //
1723*d415bd75Srobert 
get(TargetExtType * Ty)1724*d415bd75Srobert ConstantTargetNone *ConstantTargetNone::get(TargetExtType *Ty) {
1725*d415bd75Srobert   assert(Ty->hasProperty(TargetExtType::HasZeroInit) &&
1726*d415bd75Srobert          "Target extension type not allowed to have a zeroinitializer");
1727*d415bd75Srobert   std::unique_ptr<ConstantTargetNone> &Entry =
1728*d415bd75Srobert       Ty->getContext().pImpl->CTNConstants[Ty];
1729*d415bd75Srobert   if (!Entry)
1730*d415bd75Srobert     Entry.reset(new ConstantTargetNone(Ty));
1731*d415bd75Srobert 
1732*d415bd75Srobert   return Entry.get();
1733*d415bd75Srobert }
1734*d415bd75Srobert 
1735*d415bd75Srobert /// Remove the constant from the constant table.
destroyConstantImpl()1736*d415bd75Srobert void ConstantTargetNone::destroyConstantImpl() {
1737*d415bd75Srobert   getContext().pImpl->CTNConstants.erase(getType());
1738*d415bd75Srobert }
1739*d415bd75Srobert 
get(Type * Ty)174009467b48Spatrick UndefValue *UndefValue::get(Type *Ty) {
174109467b48Spatrick   std::unique_ptr<UndefValue> &Entry = Ty->getContext().pImpl->UVConstants[Ty];
174209467b48Spatrick   if (!Entry)
174309467b48Spatrick     Entry.reset(new UndefValue(Ty));
174409467b48Spatrick 
174509467b48Spatrick   return Entry.get();
174609467b48Spatrick }
174709467b48Spatrick 
174809467b48Spatrick /// Remove the constant from the constant table.
destroyConstantImpl()174909467b48Spatrick void UndefValue::destroyConstantImpl() {
175009467b48Spatrick   // Free the constant and any dangling references to it.
175173471bf0Spatrick   if (getValueID() == UndefValueVal) {
175209467b48Spatrick     getContext().pImpl->UVConstants.erase(getType());
175373471bf0Spatrick   } else if (getValueID() == PoisonValueVal) {
175473471bf0Spatrick     getContext().pImpl->PVConstants.erase(getType());
175573471bf0Spatrick   }
175673471bf0Spatrick   llvm_unreachable("Not a undef or a poison!");
175773471bf0Spatrick }
175873471bf0Spatrick 
get(Type * Ty)175973471bf0Spatrick PoisonValue *PoisonValue::get(Type *Ty) {
176073471bf0Spatrick   std::unique_ptr<PoisonValue> &Entry = Ty->getContext().pImpl->PVConstants[Ty];
176173471bf0Spatrick   if (!Entry)
176273471bf0Spatrick     Entry.reset(new PoisonValue(Ty));
176373471bf0Spatrick 
176473471bf0Spatrick   return Entry.get();
176573471bf0Spatrick }
176673471bf0Spatrick 
176773471bf0Spatrick /// Remove the constant from the constant table.
destroyConstantImpl()176873471bf0Spatrick void PoisonValue::destroyConstantImpl() {
176973471bf0Spatrick   // Free the constant and any dangling references to it.
177073471bf0Spatrick   getContext().pImpl->PVConstants.erase(getType());
177109467b48Spatrick }
177209467b48Spatrick 
get(BasicBlock * BB)177309467b48Spatrick BlockAddress *BlockAddress::get(BasicBlock *BB) {
177409467b48Spatrick   assert(BB->getParent() && "Block must have a parent");
177509467b48Spatrick   return get(BB->getParent(), BB);
177609467b48Spatrick }
177709467b48Spatrick 
get(Function * F,BasicBlock * BB)177809467b48Spatrick BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
177909467b48Spatrick   BlockAddress *&BA =
178009467b48Spatrick     F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
178109467b48Spatrick   if (!BA)
178209467b48Spatrick     BA = new BlockAddress(F, BB);
178309467b48Spatrick 
178409467b48Spatrick   assert(BA->getFunction() == F && "Basic block moved between functions");
178509467b48Spatrick   return BA;
178609467b48Spatrick }
178709467b48Spatrick 
BlockAddress(Function * F,BasicBlock * BB)178809467b48Spatrick BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
178973471bf0Spatrick     : Constant(Type::getInt8PtrTy(F->getContext(), F->getAddressSpace()),
179073471bf0Spatrick                Value::BlockAddressVal, &Op<0>(), 2) {
179109467b48Spatrick   setOperand(0, F);
179209467b48Spatrick   setOperand(1, BB);
179309467b48Spatrick   BB->AdjustBlockAddressRefCount(1);
179409467b48Spatrick }
179509467b48Spatrick 
lookup(const BasicBlock * BB)179609467b48Spatrick BlockAddress *BlockAddress::lookup(const BasicBlock *BB) {
179709467b48Spatrick   if (!BB->hasAddressTaken())
179809467b48Spatrick     return nullptr;
179909467b48Spatrick 
180009467b48Spatrick   const Function *F = BB->getParent();
180109467b48Spatrick   assert(F && "Block must have a parent");
180209467b48Spatrick   BlockAddress *BA =
180309467b48Spatrick       F->getContext().pImpl->BlockAddresses.lookup(std::make_pair(F, BB));
180409467b48Spatrick   assert(BA && "Refcount and block address map disagree!");
180509467b48Spatrick   return BA;
180609467b48Spatrick }
180709467b48Spatrick 
180809467b48Spatrick /// Remove the constant from the constant table.
destroyConstantImpl()180909467b48Spatrick void BlockAddress::destroyConstantImpl() {
181009467b48Spatrick   getFunction()->getType()->getContext().pImpl
181109467b48Spatrick     ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
181209467b48Spatrick   getBasicBlock()->AdjustBlockAddressRefCount(-1);
181309467b48Spatrick }
181409467b48Spatrick 
handleOperandChangeImpl(Value * From,Value * To)181509467b48Spatrick Value *BlockAddress::handleOperandChangeImpl(Value *From, Value *To) {
181609467b48Spatrick   // This could be replacing either the Basic Block or the Function.  In either
181709467b48Spatrick   // case, we have to remove the map entry.
181809467b48Spatrick   Function *NewF = getFunction();
181909467b48Spatrick   BasicBlock *NewBB = getBasicBlock();
182009467b48Spatrick 
182109467b48Spatrick   if (From == NewF)
182209467b48Spatrick     NewF = cast<Function>(To->stripPointerCasts());
182309467b48Spatrick   else {
182409467b48Spatrick     assert(From == NewBB && "From does not match any operand");
182509467b48Spatrick     NewBB = cast<BasicBlock>(To);
182609467b48Spatrick   }
182709467b48Spatrick 
182809467b48Spatrick   // See if the 'new' entry already exists, if not, just update this in place
182909467b48Spatrick   // and return early.
183009467b48Spatrick   BlockAddress *&NewBA =
183109467b48Spatrick     getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
183209467b48Spatrick   if (NewBA)
183309467b48Spatrick     return NewBA;
183409467b48Spatrick 
183509467b48Spatrick   getBasicBlock()->AdjustBlockAddressRefCount(-1);
183609467b48Spatrick 
183709467b48Spatrick   // Remove the old entry, this can't cause the map to rehash (just a
183809467b48Spatrick   // tombstone will get added).
183909467b48Spatrick   getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
184009467b48Spatrick                                                           getBasicBlock()));
184109467b48Spatrick   NewBA = this;
184209467b48Spatrick   setOperand(0, NewF);
184309467b48Spatrick   setOperand(1, NewBB);
184409467b48Spatrick   getBasicBlock()->AdjustBlockAddressRefCount(1);
184509467b48Spatrick 
184609467b48Spatrick   // If we just want to keep the existing value, then return null.
184709467b48Spatrick   // Callers know that this means we shouldn't delete this value.
184809467b48Spatrick   return nullptr;
184909467b48Spatrick }
185009467b48Spatrick 
get(GlobalValue * GV)185173471bf0Spatrick DSOLocalEquivalent *DSOLocalEquivalent::get(GlobalValue *GV) {
185273471bf0Spatrick   DSOLocalEquivalent *&Equiv = GV->getContext().pImpl->DSOLocalEquivalents[GV];
185373471bf0Spatrick   if (!Equiv)
185473471bf0Spatrick     Equiv = new DSOLocalEquivalent(GV);
185573471bf0Spatrick 
185673471bf0Spatrick   assert(Equiv->getGlobalValue() == GV &&
185773471bf0Spatrick          "DSOLocalFunction does not match the expected global value");
185873471bf0Spatrick   return Equiv;
185973471bf0Spatrick }
186073471bf0Spatrick 
DSOLocalEquivalent(GlobalValue * GV)186173471bf0Spatrick DSOLocalEquivalent::DSOLocalEquivalent(GlobalValue *GV)
186273471bf0Spatrick     : Constant(GV->getType(), Value::DSOLocalEquivalentVal, &Op<0>(), 1) {
186373471bf0Spatrick   setOperand(0, GV);
186473471bf0Spatrick }
186573471bf0Spatrick 
186673471bf0Spatrick /// Remove the constant from the constant table.
destroyConstantImpl()186773471bf0Spatrick void DSOLocalEquivalent::destroyConstantImpl() {
186873471bf0Spatrick   const GlobalValue *GV = getGlobalValue();
186973471bf0Spatrick   GV->getContext().pImpl->DSOLocalEquivalents.erase(GV);
187073471bf0Spatrick }
187173471bf0Spatrick 
handleOperandChangeImpl(Value * From,Value * To)187273471bf0Spatrick Value *DSOLocalEquivalent::handleOperandChangeImpl(Value *From, Value *To) {
187373471bf0Spatrick   assert(From == getGlobalValue() && "Changing value does not match operand.");
187473471bf0Spatrick   assert(isa<Constant>(To) && "Can only replace the operands with a constant");
187573471bf0Spatrick 
187673471bf0Spatrick   // The replacement is with another global value.
187773471bf0Spatrick   if (const auto *ToObj = dyn_cast<GlobalValue>(To)) {
187873471bf0Spatrick     DSOLocalEquivalent *&NewEquiv =
187973471bf0Spatrick         getContext().pImpl->DSOLocalEquivalents[ToObj];
188073471bf0Spatrick     if (NewEquiv)
188173471bf0Spatrick       return llvm::ConstantExpr::getBitCast(NewEquiv, getType());
188273471bf0Spatrick   }
188373471bf0Spatrick 
188473471bf0Spatrick   // If the argument is replaced with a null value, just replace this constant
188573471bf0Spatrick   // with a null value.
188673471bf0Spatrick   if (cast<Constant>(To)->isNullValue())
188773471bf0Spatrick     return To;
188873471bf0Spatrick 
188973471bf0Spatrick   // The replacement could be a bitcast or an alias to another function. We can
189073471bf0Spatrick   // replace it with a bitcast to the dso_local_equivalent of that function.
189173471bf0Spatrick   auto *Func = cast<Function>(To->stripPointerCastsAndAliases());
189273471bf0Spatrick   DSOLocalEquivalent *&NewEquiv = getContext().pImpl->DSOLocalEquivalents[Func];
189373471bf0Spatrick   if (NewEquiv)
189473471bf0Spatrick     return llvm::ConstantExpr::getBitCast(NewEquiv, getType());
189573471bf0Spatrick 
189673471bf0Spatrick   // Replace this with the new one.
189773471bf0Spatrick   getContext().pImpl->DSOLocalEquivalents.erase(getGlobalValue());
189873471bf0Spatrick   NewEquiv = this;
189973471bf0Spatrick   setOperand(0, Func);
190073471bf0Spatrick 
190173471bf0Spatrick   if (Func->getType() != getType()) {
190273471bf0Spatrick     // It is ok to mutate the type here because this constant should always
190373471bf0Spatrick     // reflect the type of the function it's holding.
190473471bf0Spatrick     mutateType(Func->getType());
190573471bf0Spatrick   }
190673471bf0Spatrick   return nullptr;
190773471bf0Spatrick }
190873471bf0Spatrick 
get(GlobalValue * GV)1909*d415bd75Srobert NoCFIValue *NoCFIValue::get(GlobalValue *GV) {
1910*d415bd75Srobert   NoCFIValue *&NC = GV->getContext().pImpl->NoCFIValues[GV];
1911*d415bd75Srobert   if (!NC)
1912*d415bd75Srobert     NC = new NoCFIValue(GV);
1913*d415bd75Srobert 
1914*d415bd75Srobert   assert(NC->getGlobalValue() == GV &&
1915*d415bd75Srobert          "NoCFIValue does not match the expected global value");
1916*d415bd75Srobert   return NC;
1917*d415bd75Srobert }
1918*d415bd75Srobert 
NoCFIValue(GlobalValue * GV)1919*d415bd75Srobert NoCFIValue::NoCFIValue(GlobalValue *GV)
1920*d415bd75Srobert     : Constant(GV->getType(), Value::NoCFIValueVal, &Op<0>(), 1) {
1921*d415bd75Srobert   setOperand(0, GV);
1922*d415bd75Srobert }
1923*d415bd75Srobert 
1924*d415bd75Srobert /// Remove the constant from the constant table.
destroyConstantImpl()1925*d415bd75Srobert void NoCFIValue::destroyConstantImpl() {
1926*d415bd75Srobert   const GlobalValue *GV = getGlobalValue();
1927*d415bd75Srobert   GV->getContext().pImpl->NoCFIValues.erase(GV);
1928*d415bd75Srobert }
1929*d415bd75Srobert 
handleOperandChangeImpl(Value * From,Value * To)1930*d415bd75Srobert Value *NoCFIValue::handleOperandChangeImpl(Value *From, Value *To) {
1931*d415bd75Srobert   assert(From == getGlobalValue() && "Changing value does not match operand.");
1932*d415bd75Srobert 
1933*d415bd75Srobert   GlobalValue *GV = dyn_cast<GlobalValue>(To->stripPointerCasts());
1934*d415bd75Srobert   assert(GV && "Can only replace the operands with a global value");
1935*d415bd75Srobert 
1936*d415bd75Srobert   NoCFIValue *&NewNC = getContext().pImpl->NoCFIValues[GV];
1937*d415bd75Srobert   if (NewNC)
1938*d415bd75Srobert     return llvm::ConstantExpr::getBitCast(NewNC, getType());
1939*d415bd75Srobert 
1940*d415bd75Srobert   getContext().pImpl->NoCFIValues.erase(getGlobalValue());
1941*d415bd75Srobert   NewNC = this;
1942*d415bd75Srobert   setOperand(0, GV);
1943*d415bd75Srobert 
1944*d415bd75Srobert   if (GV->getType() != getType())
1945*d415bd75Srobert     mutateType(GV->getType());
1946*d415bd75Srobert 
1947*d415bd75Srobert   return nullptr;
1948*d415bd75Srobert }
1949*d415bd75Srobert 
195009467b48Spatrick //---- ConstantExpr::get() implementations.
195109467b48Spatrick //
195209467b48Spatrick 
195309467b48Spatrick /// This is a utility function to handle folding of casts and lookup of the
195409467b48Spatrick /// cast in the ExprConstants map. It is used by the various get* methods below.
getFoldedCast(Instruction::CastOps opc,Constant * C,Type * Ty,bool OnlyIfReduced=false)195509467b48Spatrick static Constant *getFoldedCast(Instruction::CastOps opc, Constant *C, Type *Ty,
195609467b48Spatrick                                bool OnlyIfReduced = false) {
195709467b48Spatrick   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
195809467b48Spatrick   // Fold a few common cases
195909467b48Spatrick   if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
196009467b48Spatrick     return FC;
196109467b48Spatrick 
196209467b48Spatrick   if (OnlyIfReduced)
196309467b48Spatrick     return nullptr;
196409467b48Spatrick 
196509467b48Spatrick   LLVMContextImpl *pImpl = Ty->getContext().pImpl;
196609467b48Spatrick 
196709467b48Spatrick   // Look up the constant in the table first to ensure uniqueness.
196809467b48Spatrick   ConstantExprKeyType Key(opc, C);
196909467b48Spatrick 
197009467b48Spatrick   return pImpl->ExprConstants.getOrCreate(Ty, Key);
197109467b48Spatrick }
197209467b48Spatrick 
getCast(unsigned oc,Constant * C,Type * Ty,bool OnlyIfReduced)197309467b48Spatrick Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty,
197409467b48Spatrick                                 bool OnlyIfReduced) {
197509467b48Spatrick   Instruction::CastOps opc = Instruction::CastOps(oc);
197609467b48Spatrick   assert(Instruction::isCast(opc) && "opcode out of range");
197709467b48Spatrick   assert(C && Ty && "Null arguments to getCast");
197809467b48Spatrick   assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
197909467b48Spatrick 
198009467b48Spatrick   switch (opc) {
198109467b48Spatrick   default:
198209467b48Spatrick     llvm_unreachable("Invalid cast opcode");
198309467b48Spatrick   case Instruction::Trunc:
198409467b48Spatrick     return getTrunc(C, Ty, OnlyIfReduced);
198509467b48Spatrick   case Instruction::ZExt:
198609467b48Spatrick     return getZExt(C, Ty, OnlyIfReduced);
198709467b48Spatrick   case Instruction::SExt:
198809467b48Spatrick     return getSExt(C, Ty, OnlyIfReduced);
198909467b48Spatrick   case Instruction::FPTrunc:
199009467b48Spatrick     return getFPTrunc(C, Ty, OnlyIfReduced);
199109467b48Spatrick   case Instruction::FPExt:
199209467b48Spatrick     return getFPExtend(C, Ty, OnlyIfReduced);
199309467b48Spatrick   case Instruction::UIToFP:
199409467b48Spatrick     return getUIToFP(C, Ty, OnlyIfReduced);
199509467b48Spatrick   case Instruction::SIToFP:
199609467b48Spatrick     return getSIToFP(C, Ty, OnlyIfReduced);
199709467b48Spatrick   case Instruction::FPToUI:
199809467b48Spatrick     return getFPToUI(C, Ty, OnlyIfReduced);
199909467b48Spatrick   case Instruction::FPToSI:
200009467b48Spatrick     return getFPToSI(C, Ty, OnlyIfReduced);
200109467b48Spatrick   case Instruction::PtrToInt:
200209467b48Spatrick     return getPtrToInt(C, Ty, OnlyIfReduced);
200309467b48Spatrick   case Instruction::IntToPtr:
200409467b48Spatrick     return getIntToPtr(C, Ty, OnlyIfReduced);
200509467b48Spatrick   case Instruction::BitCast:
200609467b48Spatrick     return getBitCast(C, Ty, OnlyIfReduced);
200709467b48Spatrick   case Instruction::AddrSpaceCast:
200809467b48Spatrick     return getAddrSpaceCast(C, Ty, OnlyIfReduced);
200909467b48Spatrick   }
201009467b48Spatrick }
201109467b48Spatrick 
getZExtOrBitCast(Constant * C,Type * Ty)201209467b48Spatrick Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) {
201309467b48Spatrick   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
201409467b48Spatrick     return getBitCast(C, Ty);
201509467b48Spatrick   return getZExt(C, Ty);
201609467b48Spatrick }
201709467b48Spatrick 
getSExtOrBitCast(Constant * C,Type * Ty)201809467b48Spatrick Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) {
201909467b48Spatrick   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
202009467b48Spatrick     return getBitCast(C, Ty);
202109467b48Spatrick   return getSExt(C, Ty);
202209467b48Spatrick }
202309467b48Spatrick 
getTruncOrBitCast(Constant * C,Type * Ty)202409467b48Spatrick Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {
202509467b48Spatrick   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
202609467b48Spatrick     return getBitCast(C, Ty);
202709467b48Spatrick   return getTrunc(C, Ty);
202809467b48Spatrick }
202909467b48Spatrick 
getSExtOrTrunc(Constant * C,Type * Ty)2030*d415bd75Srobert Constant *ConstantExpr::getSExtOrTrunc(Constant *C, Type *Ty) {
2031*d415bd75Srobert   assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2032*d415bd75Srobert          "Can only sign extend/truncate integers!");
2033*d415bd75Srobert   Type *CTy = C->getType();
2034*d415bd75Srobert   if (CTy->getScalarSizeInBits() < Ty->getScalarSizeInBits())
2035*d415bd75Srobert     return getSExt(C, Ty);
2036*d415bd75Srobert   if (CTy->getScalarSizeInBits() > Ty->getScalarSizeInBits())
2037*d415bd75Srobert     return getTrunc(C, Ty);
2038*d415bd75Srobert   return C;
2039*d415bd75Srobert }
2040*d415bd75Srobert 
getPointerCast(Constant * S,Type * Ty)204109467b48Spatrick Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {
204209467b48Spatrick   assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
204309467b48Spatrick   assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
204409467b48Spatrick           "Invalid cast");
204509467b48Spatrick 
204609467b48Spatrick   if (Ty->isIntOrIntVectorTy())
204709467b48Spatrick     return getPtrToInt(S, Ty);
204809467b48Spatrick 
204909467b48Spatrick   unsigned SrcAS = S->getType()->getPointerAddressSpace();
205009467b48Spatrick   if (Ty->isPtrOrPtrVectorTy() && SrcAS != Ty->getPointerAddressSpace())
205109467b48Spatrick     return getAddrSpaceCast(S, Ty);
205209467b48Spatrick 
205309467b48Spatrick   return getBitCast(S, Ty);
205409467b48Spatrick }
205509467b48Spatrick 
getPointerBitCastOrAddrSpaceCast(Constant * S,Type * Ty)205609467b48Spatrick Constant *ConstantExpr::getPointerBitCastOrAddrSpaceCast(Constant *S,
205709467b48Spatrick                                                          Type *Ty) {
205809467b48Spatrick   assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
205909467b48Spatrick   assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
206009467b48Spatrick 
206109467b48Spatrick   if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
206209467b48Spatrick     return getAddrSpaceCast(S, Ty);
206309467b48Spatrick 
206409467b48Spatrick   return getBitCast(S, Ty);
206509467b48Spatrick }
206609467b48Spatrick 
getIntegerCast(Constant * C,Type * Ty,bool isSigned)206709467b48Spatrick Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty, bool isSigned) {
206809467b48Spatrick   assert(C->getType()->isIntOrIntVectorTy() &&
206909467b48Spatrick          Ty->isIntOrIntVectorTy() && "Invalid cast");
207009467b48Spatrick   unsigned SrcBits = C->getType()->getScalarSizeInBits();
207109467b48Spatrick   unsigned DstBits = Ty->getScalarSizeInBits();
207209467b48Spatrick   Instruction::CastOps opcode =
207309467b48Spatrick     (SrcBits == DstBits ? Instruction::BitCast :
207409467b48Spatrick      (SrcBits > DstBits ? Instruction::Trunc :
207509467b48Spatrick       (isSigned ? Instruction::SExt : Instruction::ZExt)));
207609467b48Spatrick   return getCast(opcode, C, Ty);
207709467b48Spatrick }
207809467b48Spatrick 
getFPCast(Constant * C,Type * Ty)207909467b48Spatrick Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) {
208009467b48Spatrick   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
208109467b48Spatrick          "Invalid cast");
208209467b48Spatrick   unsigned SrcBits = C->getType()->getScalarSizeInBits();
208309467b48Spatrick   unsigned DstBits = Ty->getScalarSizeInBits();
208409467b48Spatrick   if (SrcBits == DstBits)
208509467b48Spatrick     return C; // Avoid a useless cast
208609467b48Spatrick   Instruction::CastOps opcode =
208709467b48Spatrick     (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
208809467b48Spatrick   return getCast(opcode, C, Ty);
208909467b48Spatrick }
209009467b48Spatrick 
getTrunc(Constant * C,Type * Ty,bool OnlyIfReduced)209109467b48Spatrick Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
209209467b48Spatrick #ifndef NDEBUG
2093097a140dSpatrick   bool fromVec = isa<VectorType>(C->getType());
2094097a140dSpatrick   bool toVec = isa<VectorType>(Ty);
209509467b48Spatrick #endif
209609467b48Spatrick   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
209709467b48Spatrick   assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
209809467b48Spatrick   assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
209909467b48Spatrick   assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
210009467b48Spatrick          "SrcTy must be larger than DestTy for Trunc!");
210109467b48Spatrick 
210209467b48Spatrick   return getFoldedCast(Instruction::Trunc, C, Ty, OnlyIfReduced);
210309467b48Spatrick }
210409467b48Spatrick 
getSExt(Constant * C,Type * Ty,bool OnlyIfReduced)210509467b48Spatrick Constant *ConstantExpr::getSExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
210609467b48Spatrick #ifndef NDEBUG
2107097a140dSpatrick   bool fromVec = isa<VectorType>(C->getType());
2108097a140dSpatrick   bool toVec = isa<VectorType>(Ty);
210909467b48Spatrick #endif
211009467b48Spatrick   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
211109467b48Spatrick   assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
211209467b48Spatrick   assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
211309467b48Spatrick   assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
211409467b48Spatrick          "SrcTy must be smaller than DestTy for SExt!");
211509467b48Spatrick 
211609467b48Spatrick   return getFoldedCast(Instruction::SExt, C, Ty, OnlyIfReduced);
211709467b48Spatrick }
211809467b48Spatrick 
getZExt(Constant * C,Type * Ty,bool OnlyIfReduced)211909467b48Spatrick Constant *ConstantExpr::getZExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
212009467b48Spatrick #ifndef NDEBUG
2121097a140dSpatrick   bool fromVec = isa<VectorType>(C->getType());
2122097a140dSpatrick   bool toVec = isa<VectorType>(Ty);
212309467b48Spatrick #endif
212409467b48Spatrick   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
212509467b48Spatrick   assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
212609467b48Spatrick   assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
212709467b48Spatrick   assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
212809467b48Spatrick          "SrcTy must be smaller than DestTy for ZExt!");
212909467b48Spatrick 
213009467b48Spatrick   return getFoldedCast(Instruction::ZExt, C, Ty, OnlyIfReduced);
213109467b48Spatrick }
213209467b48Spatrick 
getFPTrunc(Constant * C,Type * Ty,bool OnlyIfReduced)213309467b48Spatrick Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
213409467b48Spatrick #ifndef NDEBUG
2135097a140dSpatrick   bool fromVec = isa<VectorType>(C->getType());
2136097a140dSpatrick   bool toVec = isa<VectorType>(Ty);
213709467b48Spatrick #endif
213809467b48Spatrick   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
213909467b48Spatrick   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
214009467b48Spatrick          C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
214109467b48Spatrick          "This is an illegal floating point truncation!");
214209467b48Spatrick   return getFoldedCast(Instruction::FPTrunc, C, Ty, OnlyIfReduced);
214309467b48Spatrick }
214409467b48Spatrick 
getFPExtend(Constant * C,Type * Ty,bool OnlyIfReduced)214509467b48Spatrick Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty, bool OnlyIfReduced) {
214609467b48Spatrick #ifndef NDEBUG
2147097a140dSpatrick   bool fromVec = isa<VectorType>(C->getType());
2148097a140dSpatrick   bool toVec = isa<VectorType>(Ty);
214909467b48Spatrick #endif
215009467b48Spatrick   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
215109467b48Spatrick   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
215209467b48Spatrick          C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
215309467b48Spatrick          "This is an illegal floating point extension!");
215409467b48Spatrick   return getFoldedCast(Instruction::FPExt, C, Ty, OnlyIfReduced);
215509467b48Spatrick }
215609467b48Spatrick 
getUIToFP(Constant * C,Type * Ty,bool OnlyIfReduced)215709467b48Spatrick Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
215809467b48Spatrick #ifndef NDEBUG
2159097a140dSpatrick   bool fromVec = isa<VectorType>(C->getType());
2160097a140dSpatrick   bool toVec = isa<VectorType>(Ty);
216109467b48Spatrick #endif
216209467b48Spatrick   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
216309467b48Spatrick   assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
216409467b48Spatrick          "This is an illegal uint to floating point cast!");
216509467b48Spatrick   return getFoldedCast(Instruction::UIToFP, C, Ty, OnlyIfReduced);
216609467b48Spatrick }
216709467b48Spatrick 
getSIToFP(Constant * C,Type * Ty,bool OnlyIfReduced)216809467b48Spatrick Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
216909467b48Spatrick #ifndef NDEBUG
2170097a140dSpatrick   bool fromVec = isa<VectorType>(C->getType());
2171097a140dSpatrick   bool toVec = isa<VectorType>(Ty);
217209467b48Spatrick #endif
217309467b48Spatrick   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
217409467b48Spatrick   assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
217509467b48Spatrick          "This is an illegal sint to floating point cast!");
217609467b48Spatrick   return getFoldedCast(Instruction::SIToFP, C, Ty, OnlyIfReduced);
217709467b48Spatrick }
217809467b48Spatrick 
getFPToUI(Constant * C,Type * Ty,bool OnlyIfReduced)217909467b48Spatrick Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty, bool OnlyIfReduced) {
218009467b48Spatrick #ifndef NDEBUG
2181097a140dSpatrick   bool fromVec = isa<VectorType>(C->getType());
2182097a140dSpatrick   bool toVec = isa<VectorType>(Ty);
218309467b48Spatrick #endif
218409467b48Spatrick   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
218509467b48Spatrick   assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
218609467b48Spatrick          "This is an illegal floating point to uint cast!");
218709467b48Spatrick   return getFoldedCast(Instruction::FPToUI, C, Ty, OnlyIfReduced);
218809467b48Spatrick }
218909467b48Spatrick 
getFPToSI(Constant * C,Type * Ty,bool OnlyIfReduced)219009467b48Spatrick Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty, bool OnlyIfReduced) {
219109467b48Spatrick #ifndef NDEBUG
2192097a140dSpatrick   bool fromVec = isa<VectorType>(C->getType());
2193097a140dSpatrick   bool toVec = isa<VectorType>(Ty);
219409467b48Spatrick #endif
219509467b48Spatrick   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
219609467b48Spatrick   assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
219709467b48Spatrick          "This is an illegal floating point to sint cast!");
219809467b48Spatrick   return getFoldedCast(Instruction::FPToSI, C, Ty, OnlyIfReduced);
219909467b48Spatrick }
220009467b48Spatrick 
getPtrToInt(Constant * C,Type * DstTy,bool OnlyIfReduced)220109467b48Spatrick Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy,
220209467b48Spatrick                                     bool OnlyIfReduced) {
220309467b48Spatrick   assert(C->getType()->isPtrOrPtrVectorTy() &&
220409467b48Spatrick          "PtrToInt source must be pointer or pointer vector");
220509467b48Spatrick   assert(DstTy->isIntOrIntVectorTy() &&
220609467b48Spatrick          "PtrToInt destination must be integer or integer vector");
220709467b48Spatrick   assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
220809467b48Spatrick   if (isa<VectorType>(C->getType()))
2209*d415bd75Srobert     assert(cast<VectorType>(C->getType())->getElementCount() ==
2210*d415bd75Srobert                cast<VectorType>(DstTy)->getElementCount() &&
221109467b48Spatrick            "Invalid cast between a different number of vector elements");
221209467b48Spatrick   return getFoldedCast(Instruction::PtrToInt, C, DstTy, OnlyIfReduced);
221309467b48Spatrick }
221409467b48Spatrick 
getIntToPtr(Constant * C,Type * DstTy,bool OnlyIfReduced)221509467b48Spatrick Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy,
221609467b48Spatrick                                     bool OnlyIfReduced) {
221709467b48Spatrick   assert(C->getType()->isIntOrIntVectorTy() &&
221809467b48Spatrick          "IntToPtr source must be integer or integer vector");
221909467b48Spatrick   assert(DstTy->isPtrOrPtrVectorTy() &&
222009467b48Spatrick          "IntToPtr destination must be a pointer or pointer vector");
222109467b48Spatrick   assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
222209467b48Spatrick   if (isa<VectorType>(C->getType()))
222373471bf0Spatrick     assert(cast<VectorType>(C->getType())->getElementCount() ==
222473471bf0Spatrick                cast<VectorType>(DstTy)->getElementCount() &&
222509467b48Spatrick            "Invalid cast between a different number of vector elements");
222609467b48Spatrick   return getFoldedCast(Instruction::IntToPtr, C, DstTy, OnlyIfReduced);
222709467b48Spatrick }
222809467b48Spatrick 
getBitCast(Constant * C,Type * DstTy,bool OnlyIfReduced)222909467b48Spatrick Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy,
223009467b48Spatrick                                    bool OnlyIfReduced) {
223109467b48Spatrick   assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
223209467b48Spatrick          "Invalid constantexpr bitcast!");
223309467b48Spatrick 
223409467b48Spatrick   // It is common to ask for a bitcast of a value to its own type, handle this
223509467b48Spatrick   // speedily.
223609467b48Spatrick   if (C->getType() == DstTy) return C;
223709467b48Spatrick 
223809467b48Spatrick   return getFoldedCast(Instruction::BitCast, C, DstTy, OnlyIfReduced);
223909467b48Spatrick }
224009467b48Spatrick 
getAddrSpaceCast(Constant * C,Type * DstTy,bool OnlyIfReduced)224109467b48Spatrick Constant *ConstantExpr::getAddrSpaceCast(Constant *C, Type *DstTy,
224209467b48Spatrick                                          bool OnlyIfReduced) {
224309467b48Spatrick   assert(CastInst::castIsValid(Instruction::AddrSpaceCast, C, DstTy) &&
224409467b48Spatrick          "Invalid constantexpr addrspacecast!");
224509467b48Spatrick 
224609467b48Spatrick   // Canonicalize addrspacecasts between different pointer types by first
224709467b48Spatrick   // bitcasting the pointer type and then converting the address space.
224809467b48Spatrick   PointerType *SrcScalarTy = cast<PointerType>(C->getType()->getScalarType());
224909467b48Spatrick   PointerType *DstScalarTy = cast<PointerType>(DstTy->getScalarType());
225073471bf0Spatrick   if (!SrcScalarTy->hasSameElementTypeAs(DstScalarTy)) {
225173471bf0Spatrick     Type *MidTy = PointerType::getWithSamePointeeType(
225273471bf0Spatrick         DstScalarTy, SrcScalarTy->getAddressSpace());
225309467b48Spatrick     if (VectorType *VT = dyn_cast<VectorType>(DstTy)) {
225409467b48Spatrick       // Handle vectors of pointers.
225573471bf0Spatrick       MidTy = FixedVectorType::get(MidTy,
225673471bf0Spatrick                                    cast<FixedVectorType>(VT)->getNumElements());
225709467b48Spatrick     }
225809467b48Spatrick     C = getBitCast(C, MidTy);
225909467b48Spatrick   }
226009467b48Spatrick   return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced);
226109467b48Spatrick }
226209467b48Spatrick 
get(unsigned Opcode,Constant * C1,Constant * C2,unsigned Flags,Type * OnlyIfReducedTy)226309467b48Spatrick Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
226409467b48Spatrick                             unsigned Flags, Type *OnlyIfReducedTy) {
226509467b48Spatrick   // Check the operands for consistency first.
226609467b48Spatrick   assert(Instruction::isBinaryOp(Opcode) &&
226709467b48Spatrick          "Invalid opcode in binary constant expression");
2268*d415bd75Srobert   assert(isSupportedBinOp(Opcode) &&
2269*d415bd75Srobert          "Binop not supported as constant expression");
227009467b48Spatrick   assert(C1->getType() == C2->getType() &&
227109467b48Spatrick          "Operand types in binary constant expression should match");
227209467b48Spatrick 
227309467b48Spatrick #ifndef NDEBUG
227409467b48Spatrick   switch (Opcode) {
227509467b48Spatrick   case Instruction::Add:
227609467b48Spatrick   case Instruction::Sub:
227709467b48Spatrick   case Instruction::Mul:
227809467b48Spatrick   case Instruction::UDiv:
227909467b48Spatrick   case Instruction::SDiv:
228009467b48Spatrick   case Instruction::URem:
228109467b48Spatrick   case Instruction::SRem:
228209467b48Spatrick     assert(C1->getType()->isIntOrIntVectorTy() &&
228309467b48Spatrick            "Tried to create an integer operation on a non-integer type!");
228409467b48Spatrick     break;
228509467b48Spatrick   case Instruction::FAdd:
228609467b48Spatrick   case Instruction::FSub:
228709467b48Spatrick   case Instruction::FMul:
228809467b48Spatrick   case Instruction::FDiv:
228909467b48Spatrick   case Instruction::FRem:
229009467b48Spatrick     assert(C1->getType()->isFPOrFPVectorTy() &&
229109467b48Spatrick            "Tried to create a floating-point operation on a "
229209467b48Spatrick            "non-floating-point type!");
229309467b48Spatrick     break;
229409467b48Spatrick   case Instruction::And:
229509467b48Spatrick   case Instruction::Or:
229609467b48Spatrick   case Instruction::Xor:
229709467b48Spatrick     assert(C1->getType()->isIntOrIntVectorTy() &&
229809467b48Spatrick            "Tried to create a logical operation on a non-integral type!");
229909467b48Spatrick     break;
230009467b48Spatrick   case Instruction::Shl:
230109467b48Spatrick   case Instruction::LShr:
230209467b48Spatrick   case Instruction::AShr:
230309467b48Spatrick     assert(C1->getType()->isIntOrIntVectorTy() &&
230409467b48Spatrick            "Tried to create a shift operation on a non-integer type!");
230509467b48Spatrick     break;
230609467b48Spatrick   default:
230709467b48Spatrick     break;
230809467b48Spatrick   }
230909467b48Spatrick #endif
231009467b48Spatrick 
231109467b48Spatrick   if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
231209467b48Spatrick     return FC;
231309467b48Spatrick 
231409467b48Spatrick   if (OnlyIfReducedTy == C1->getType())
231509467b48Spatrick     return nullptr;
231609467b48Spatrick 
231709467b48Spatrick   Constant *ArgVec[] = { C1, C2 };
231809467b48Spatrick   ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
231909467b48Spatrick 
232009467b48Spatrick   LLVMContextImpl *pImpl = C1->getContext().pImpl;
232109467b48Spatrick   return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
232209467b48Spatrick }
232309467b48Spatrick 
isDesirableBinOp(unsigned Opcode)2324*d415bd75Srobert bool ConstantExpr::isDesirableBinOp(unsigned Opcode) {
2325*d415bd75Srobert   switch (Opcode) {
2326*d415bd75Srobert   case Instruction::UDiv:
2327*d415bd75Srobert   case Instruction::SDiv:
2328*d415bd75Srobert   case Instruction::URem:
2329*d415bd75Srobert   case Instruction::SRem:
2330*d415bd75Srobert   case Instruction::FAdd:
2331*d415bd75Srobert   case Instruction::FSub:
2332*d415bd75Srobert   case Instruction::FMul:
2333*d415bd75Srobert   case Instruction::FDiv:
2334*d415bd75Srobert   case Instruction::FRem:
2335*d415bd75Srobert     return false;
2336*d415bd75Srobert   case Instruction::Add:
2337*d415bd75Srobert   case Instruction::Sub:
2338*d415bd75Srobert   case Instruction::Mul:
2339*d415bd75Srobert   case Instruction::Shl:
2340*d415bd75Srobert   case Instruction::LShr:
2341*d415bd75Srobert   case Instruction::AShr:
2342*d415bd75Srobert   case Instruction::And:
2343*d415bd75Srobert   case Instruction::Or:
2344*d415bd75Srobert   case Instruction::Xor:
2345*d415bd75Srobert     return true;
2346*d415bd75Srobert   default:
2347*d415bd75Srobert     llvm_unreachable("Argument must be binop opcode");
2348*d415bd75Srobert   }
2349*d415bd75Srobert }
2350*d415bd75Srobert 
isSupportedBinOp(unsigned Opcode)2351*d415bd75Srobert bool ConstantExpr::isSupportedBinOp(unsigned Opcode) {
2352*d415bd75Srobert   switch (Opcode) {
2353*d415bd75Srobert   case Instruction::UDiv:
2354*d415bd75Srobert   case Instruction::SDiv:
2355*d415bd75Srobert   case Instruction::URem:
2356*d415bd75Srobert   case Instruction::SRem:
2357*d415bd75Srobert   case Instruction::FAdd:
2358*d415bd75Srobert   case Instruction::FSub:
2359*d415bd75Srobert   case Instruction::FMul:
2360*d415bd75Srobert   case Instruction::FDiv:
2361*d415bd75Srobert   case Instruction::FRem:
2362*d415bd75Srobert     return false;
2363*d415bd75Srobert   case Instruction::Add:
2364*d415bd75Srobert   case Instruction::Sub:
2365*d415bd75Srobert   case Instruction::Mul:
2366*d415bd75Srobert   case Instruction::Shl:
2367*d415bd75Srobert   case Instruction::LShr:
2368*d415bd75Srobert   case Instruction::AShr:
2369*d415bd75Srobert   case Instruction::And:
2370*d415bd75Srobert   case Instruction::Or:
2371*d415bd75Srobert   case Instruction::Xor:
2372*d415bd75Srobert     return true;
2373*d415bd75Srobert   default:
2374*d415bd75Srobert     llvm_unreachable("Argument must be binop opcode");
2375*d415bd75Srobert   }
2376*d415bd75Srobert }
2377*d415bd75Srobert 
getSizeOf(Type * Ty)237809467b48Spatrick Constant *ConstantExpr::getSizeOf(Type* Ty) {
237909467b48Spatrick   // sizeof is implemented as: (i64) gep (Ty*)null, 1
238009467b48Spatrick   // Note that a non-inbounds gep is used, as null isn't within any object.
238109467b48Spatrick   Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
238209467b48Spatrick   Constant *GEP = getGetElementPtr(
238309467b48Spatrick       Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
238409467b48Spatrick   return getPtrToInt(GEP,
238509467b48Spatrick                      Type::getInt64Ty(Ty->getContext()));
238609467b48Spatrick }
238709467b48Spatrick 
getAlignOf(Type * Ty)238809467b48Spatrick Constant *ConstantExpr::getAlignOf(Type* Ty) {
238909467b48Spatrick   // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
239009467b48Spatrick   // Note that a non-inbounds gep is used, as null isn't within any object.
239109467b48Spatrick   Type *AligningTy = StructType::get(Type::getInt1Ty(Ty->getContext()), Ty);
239209467b48Spatrick   Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo(0));
239309467b48Spatrick   Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
239409467b48Spatrick   Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
239509467b48Spatrick   Constant *Indices[2] = { Zero, One };
239609467b48Spatrick   Constant *GEP = getGetElementPtr(AligningTy, NullPtr, Indices);
239709467b48Spatrick   return getPtrToInt(GEP,
239809467b48Spatrick                      Type::getInt64Ty(Ty->getContext()));
239909467b48Spatrick }
240009467b48Spatrick 
getOffsetOf(StructType * STy,unsigned FieldNo)240109467b48Spatrick Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) {
240209467b48Spatrick   return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
240309467b48Spatrick                                            FieldNo));
240409467b48Spatrick }
240509467b48Spatrick 
getOffsetOf(Type * Ty,Constant * FieldNo)240609467b48Spatrick Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) {
240709467b48Spatrick   // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
240809467b48Spatrick   // Note that a non-inbounds gep is used, as null isn't within any object.
240909467b48Spatrick   Constant *GEPIdx[] = {
241009467b48Spatrick     ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
241109467b48Spatrick     FieldNo
241209467b48Spatrick   };
241309467b48Spatrick   Constant *GEP = getGetElementPtr(
241409467b48Spatrick       Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
241509467b48Spatrick   return getPtrToInt(GEP,
241609467b48Spatrick                      Type::getInt64Ty(Ty->getContext()));
241709467b48Spatrick }
241809467b48Spatrick 
getCompare(unsigned short Predicate,Constant * C1,Constant * C2,bool OnlyIfReduced)241909467b48Spatrick Constant *ConstantExpr::getCompare(unsigned short Predicate, Constant *C1,
242009467b48Spatrick                                    Constant *C2, bool OnlyIfReduced) {
242109467b48Spatrick   assert(C1->getType() == C2->getType() && "Op types should be identical!");
242209467b48Spatrick 
242309467b48Spatrick   switch (Predicate) {
242409467b48Spatrick   default: llvm_unreachable("Invalid CmpInst predicate");
242509467b48Spatrick   case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
242609467b48Spatrick   case CmpInst::FCMP_OGE:   case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
242709467b48Spatrick   case CmpInst::FCMP_ONE:   case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
242809467b48Spatrick   case CmpInst::FCMP_UEQ:   case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
242909467b48Spatrick   case CmpInst::FCMP_ULT:   case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
243009467b48Spatrick   case CmpInst::FCMP_TRUE:
243109467b48Spatrick     return getFCmp(Predicate, C1, C2, OnlyIfReduced);
243209467b48Spatrick 
243309467b48Spatrick   case CmpInst::ICMP_EQ:  case CmpInst::ICMP_NE:  case CmpInst::ICMP_UGT:
243409467b48Spatrick   case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
243509467b48Spatrick   case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
243609467b48Spatrick   case CmpInst::ICMP_SLE:
243709467b48Spatrick     return getICmp(Predicate, C1, C2, OnlyIfReduced);
243809467b48Spatrick   }
243909467b48Spatrick }
244009467b48Spatrick 
getSelect(Constant * C,Constant * V1,Constant * V2,Type * OnlyIfReducedTy)244109467b48Spatrick Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2,
244209467b48Spatrick                                   Type *OnlyIfReducedTy) {
244309467b48Spatrick   assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
244409467b48Spatrick 
244509467b48Spatrick   if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
244609467b48Spatrick     return SC;        // Fold common cases
244709467b48Spatrick 
244809467b48Spatrick   if (OnlyIfReducedTy == V1->getType())
244909467b48Spatrick     return nullptr;
245009467b48Spatrick 
245109467b48Spatrick   Constant *ArgVec[] = { C, V1, V2 };
245209467b48Spatrick   ConstantExprKeyType Key(Instruction::Select, ArgVec);
245309467b48Spatrick 
245409467b48Spatrick   LLVMContextImpl *pImpl = C->getContext().pImpl;
245509467b48Spatrick   return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
245609467b48Spatrick }
245709467b48Spatrick 
getGetElementPtr(Type * Ty,Constant * C,ArrayRef<Value * > Idxs,bool InBounds,std::optional<unsigned> InRangeIndex,Type * OnlyIfReducedTy)245809467b48Spatrick Constant *ConstantExpr::getGetElementPtr(Type *Ty, Constant *C,
245909467b48Spatrick                                          ArrayRef<Value *> Idxs, bool InBounds,
2460*d415bd75Srobert                                          std::optional<unsigned> InRangeIndex,
246109467b48Spatrick                                          Type *OnlyIfReducedTy) {
246273471bf0Spatrick   PointerType *OrigPtrTy = cast<PointerType>(C->getType()->getScalarType());
246373471bf0Spatrick   assert(Ty && "Must specify element type");
246473471bf0Spatrick   assert(OrigPtrTy->isOpaqueOrPointeeTypeMatches(Ty));
246509467b48Spatrick 
246609467b48Spatrick   if (Constant *FC =
246709467b48Spatrick           ConstantFoldGetElementPtr(Ty, C, InBounds, InRangeIndex, Idxs))
246809467b48Spatrick     return FC;          // Fold a few common cases.
246909467b48Spatrick 
247009467b48Spatrick   // Get the result type of the getelementptr!
247109467b48Spatrick   Type *DestTy = GetElementPtrInst::getIndexedType(Ty, Idxs);
247209467b48Spatrick   assert(DestTy && "GEP indices invalid!");
247373471bf0Spatrick   unsigned AS = OrigPtrTy->getAddressSpace();
247473471bf0Spatrick   Type *ReqTy = OrigPtrTy->isOpaque()
247573471bf0Spatrick       ? PointerType::get(OrigPtrTy->getContext(), AS)
247673471bf0Spatrick       : DestTy->getPointerTo(AS);
247709467b48Spatrick 
247873471bf0Spatrick   auto EltCount = ElementCount::getFixed(0);
2479097a140dSpatrick   if (VectorType *VecTy = dyn_cast<VectorType>(C->getType()))
2480097a140dSpatrick     EltCount = VecTy->getElementCount();
2481097a140dSpatrick   else
2482*d415bd75Srobert     for (auto *Idx : Idxs)
2483097a140dSpatrick       if (VectorType *VecTy = dyn_cast<VectorType>(Idx->getType()))
2484097a140dSpatrick         EltCount = VecTy->getElementCount();
248509467b48Spatrick 
248673471bf0Spatrick   if (EltCount.isNonZero())
2487097a140dSpatrick     ReqTy = VectorType::get(ReqTy, EltCount);
248809467b48Spatrick 
248909467b48Spatrick   if (OnlyIfReducedTy == ReqTy)
249009467b48Spatrick     return nullptr;
249109467b48Spatrick 
249209467b48Spatrick   // Look up the constant in the table first to ensure uniqueness
249309467b48Spatrick   std::vector<Constant*> ArgVec;
249409467b48Spatrick   ArgVec.reserve(1 + Idxs.size());
249509467b48Spatrick   ArgVec.push_back(C);
2496097a140dSpatrick   auto GTI = gep_type_begin(Ty, Idxs), GTE = gep_type_end(Ty, Idxs);
2497097a140dSpatrick   for (; GTI != GTE; ++GTI) {
2498097a140dSpatrick     auto *Idx = cast<Constant>(GTI.getOperand());
2499097a140dSpatrick     assert(
2500097a140dSpatrick         (!isa<VectorType>(Idx->getType()) ||
2501097a140dSpatrick          cast<VectorType>(Idx->getType())->getElementCount() == EltCount) &&
250209467b48Spatrick         "getelementptr index type missmatch");
250309467b48Spatrick 
2504097a140dSpatrick     if (GTI.isStruct() && Idx->getType()->isVectorTy()) {
2505097a140dSpatrick       Idx = Idx->getSplatValue();
250673471bf0Spatrick     } else if (GTI.isSequential() && EltCount.isNonZero() &&
2507097a140dSpatrick                !Idx->getType()->isVectorTy()) {
2508097a140dSpatrick       Idx = ConstantVector::getSplat(EltCount, Idx);
2509097a140dSpatrick     }
251009467b48Spatrick     ArgVec.push_back(Idx);
251109467b48Spatrick   }
251209467b48Spatrick 
251309467b48Spatrick   unsigned SubClassOptionalData = InBounds ? GEPOperator::IsInBounds : 0;
251409467b48Spatrick   if (InRangeIndex && *InRangeIndex < 63)
251509467b48Spatrick     SubClassOptionalData |= (*InRangeIndex + 1) << 1;
251609467b48Spatrick   const ConstantExprKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
2517*d415bd75Srobert                                 SubClassOptionalData, std::nullopt, Ty);
251809467b48Spatrick 
251909467b48Spatrick   LLVMContextImpl *pImpl = C->getContext().pImpl;
252009467b48Spatrick   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
252109467b48Spatrick }
252209467b48Spatrick 
getICmp(unsigned short pred,Constant * LHS,Constant * RHS,bool OnlyIfReduced)252309467b48Spatrick Constant *ConstantExpr::getICmp(unsigned short pred, Constant *LHS,
252409467b48Spatrick                                 Constant *RHS, bool OnlyIfReduced) {
2525*d415bd75Srobert   auto Predicate = static_cast<CmpInst::Predicate>(pred);
252609467b48Spatrick   assert(LHS->getType() == RHS->getType());
2527*d415bd75Srobert   assert(CmpInst::isIntPredicate(Predicate) && "Invalid ICmp Predicate");
252809467b48Spatrick 
2529*d415bd75Srobert   if (Constant *FC = ConstantFoldCompareInstruction(Predicate, LHS, RHS))
253009467b48Spatrick     return FC;          // Fold a few common cases...
253109467b48Spatrick 
253209467b48Spatrick   if (OnlyIfReduced)
253309467b48Spatrick     return nullptr;
253409467b48Spatrick 
253509467b48Spatrick   // Look up the constant in the table first to ensure uniqueness
253609467b48Spatrick   Constant *ArgVec[] = { LHS, RHS };
253709467b48Spatrick   // Get the key type with both the opcode and predicate
2538*d415bd75Srobert   const ConstantExprKeyType Key(Instruction::ICmp, ArgVec, Predicate);
253909467b48Spatrick 
254009467b48Spatrick   Type *ResultTy = Type::getInt1Ty(LHS->getContext());
254109467b48Spatrick   if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
2542097a140dSpatrick     ResultTy = VectorType::get(ResultTy, VT->getElementCount());
254309467b48Spatrick 
254409467b48Spatrick   LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
254509467b48Spatrick   return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
254609467b48Spatrick }
254709467b48Spatrick 
getFCmp(unsigned short pred,Constant * LHS,Constant * RHS,bool OnlyIfReduced)254809467b48Spatrick Constant *ConstantExpr::getFCmp(unsigned short pred, Constant *LHS,
254909467b48Spatrick                                 Constant *RHS, bool OnlyIfReduced) {
2550*d415bd75Srobert   auto Predicate = static_cast<CmpInst::Predicate>(pred);
255109467b48Spatrick   assert(LHS->getType() == RHS->getType());
2552*d415bd75Srobert   assert(CmpInst::isFPPredicate(Predicate) && "Invalid FCmp Predicate");
255309467b48Spatrick 
2554*d415bd75Srobert   if (Constant *FC = ConstantFoldCompareInstruction(Predicate, LHS, RHS))
255509467b48Spatrick     return FC;          // Fold a few common cases...
255609467b48Spatrick 
255709467b48Spatrick   if (OnlyIfReduced)
255809467b48Spatrick     return nullptr;
255909467b48Spatrick 
256009467b48Spatrick   // Look up the constant in the table first to ensure uniqueness
256109467b48Spatrick   Constant *ArgVec[] = { LHS, RHS };
256209467b48Spatrick   // Get the key type with both the opcode and predicate
2563*d415bd75Srobert   const ConstantExprKeyType Key(Instruction::FCmp, ArgVec, Predicate);
256409467b48Spatrick 
256509467b48Spatrick   Type *ResultTy = Type::getInt1Ty(LHS->getContext());
256609467b48Spatrick   if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
2567097a140dSpatrick     ResultTy = VectorType::get(ResultTy, VT->getElementCount());
256809467b48Spatrick 
256909467b48Spatrick   LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
257009467b48Spatrick   return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
257109467b48Spatrick }
257209467b48Spatrick 
getExtractElement(Constant * Val,Constant * Idx,Type * OnlyIfReducedTy)257309467b48Spatrick Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx,
257409467b48Spatrick                                           Type *OnlyIfReducedTy) {
257509467b48Spatrick   assert(Val->getType()->isVectorTy() &&
257609467b48Spatrick          "Tried to create extractelement operation on non-vector type!");
257709467b48Spatrick   assert(Idx->getType()->isIntegerTy() &&
257809467b48Spatrick          "Extractelement index must be an integer type!");
257909467b48Spatrick 
258009467b48Spatrick   if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
258109467b48Spatrick     return FC;          // Fold a few common cases.
258209467b48Spatrick 
2583097a140dSpatrick   Type *ReqTy = cast<VectorType>(Val->getType())->getElementType();
258409467b48Spatrick   if (OnlyIfReducedTy == ReqTy)
258509467b48Spatrick     return nullptr;
258609467b48Spatrick 
258709467b48Spatrick   // Look up the constant in the table first to ensure uniqueness
258809467b48Spatrick   Constant *ArgVec[] = { Val, Idx };
258909467b48Spatrick   const ConstantExprKeyType Key(Instruction::ExtractElement, ArgVec);
259009467b48Spatrick 
259109467b48Spatrick   LLVMContextImpl *pImpl = Val->getContext().pImpl;
259209467b48Spatrick   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
259309467b48Spatrick }
259409467b48Spatrick 
getInsertElement(Constant * Val,Constant * Elt,Constant * Idx,Type * OnlyIfReducedTy)259509467b48Spatrick Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
259609467b48Spatrick                                          Constant *Idx, Type *OnlyIfReducedTy) {
259709467b48Spatrick   assert(Val->getType()->isVectorTy() &&
259809467b48Spatrick          "Tried to create insertelement operation on non-vector type!");
2599097a140dSpatrick   assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType() &&
260009467b48Spatrick          "Insertelement types must match!");
260109467b48Spatrick   assert(Idx->getType()->isIntegerTy() &&
260209467b48Spatrick          "Insertelement index must be i32 type!");
260309467b48Spatrick 
260409467b48Spatrick   if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
260509467b48Spatrick     return FC;          // Fold a few common cases.
260609467b48Spatrick 
260709467b48Spatrick   if (OnlyIfReducedTy == Val->getType())
260809467b48Spatrick     return nullptr;
260909467b48Spatrick 
261009467b48Spatrick   // Look up the constant in the table first to ensure uniqueness
261109467b48Spatrick   Constant *ArgVec[] = { Val, Elt, Idx };
261209467b48Spatrick   const ConstantExprKeyType Key(Instruction::InsertElement, ArgVec);
261309467b48Spatrick 
261409467b48Spatrick   LLVMContextImpl *pImpl = Val->getContext().pImpl;
261509467b48Spatrick   return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
261609467b48Spatrick }
261709467b48Spatrick 
getShuffleVector(Constant * V1,Constant * V2,ArrayRef<int> Mask,Type * OnlyIfReducedTy)261809467b48Spatrick Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2619097a140dSpatrick                                          ArrayRef<int> Mask,
2620097a140dSpatrick                                          Type *OnlyIfReducedTy) {
262109467b48Spatrick   assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
262209467b48Spatrick          "Invalid shuffle vector constant expr operands!");
262309467b48Spatrick 
262409467b48Spatrick   if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
262509467b48Spatrick     return FC;          // Fold a few common cases.
262609467b48Spatrick 
2627097a140dSpatrick   unsigned NElts = Mask.size();
2628097a140dSpatrick   auto V1VTy = cast<VectorType>(V1->getType());
2629097a140dSpatrick   Type *EltTy = V1VTy->getElementType();
2630097a140dSpatrick   bool TypeIsScalable = isa<ScalableVectorType>(V1VTy);
2631097a140dSpatrick   Type *ShufTy = VectorType::get(EltTy, NElts, TypeIsScalable);
263209467b48Spatrick 
263309467b48Spatrick   if (OnlyIfReducedTy == ShufTy)
263409467b48Spatrick     return nullptr;
263509467b48Spatrick 
263609467b48Spatrick   // Look up the constant in the table first to ensure uniqueness
2637097a140dSpatrick   Constant *ArgVec[] = {V1, V2};
2638*d415bd75Srobert   ConstantExprKeyType Key(Instruction::ShuffleVector, ArgVec, 0, 0, Mask);
263909467b48Spatrick 
264009467b48Spatrick   LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
264109467b48Spatrick   return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
264209467b48Spatrick }
264309467b48Spatrick 
getNeg(Constant * C,bool HasNUW,bool HasNSW)264409467b48Spatrick Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
264509467b48Spatrick   assert(C->getType()->isIntOrIntVectorTy() &&
264609467b48Spatrick          "Cannot NEG a nonintegral value!");
264709467b48Spatrick   return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
264809467b48Spatrick                 C, HasNUW, HasNSW);
264909467b48Spatrick }
265009467b48Spatrick 
getNot(Constant * C)265109467b48Spatrick Constant *ConstantExpr::getNot(Constant *C) {
265209467b48Spatrick   assert(C->getType()->isIntOrIntVectorTy() &&
265309467b48Spatrick          "Cannot NOT a nonintegral value!");
265409467b48Spatrick   return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
265509467b48Spatrick }
265609467b48Spatrick 
getAdd(Constant * C1,Constant * C2,bool HasNUW,bool HasNSW)265709467b48Spatrick Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
265809467b48Spatrick                                bool HasNUW, bool HasNSW) {
265909467b48Spatrick   unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
266009467b48Spatrick                    (HasNSW ? OverflowingBinaryOperator::NoSignedWrap   : 0);
266109467b48Spatrick   return get(Instruction::Add, C1, C2, Flags);
266209467b48Spatrick }
266309467b48Spatrick 
getSub(Constant * C1,Constant * C2,bool HasNUW,bool HasNSW)266409467b48Spatrick Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
266509467b48Spatrick                                bool HasNUW, bool HasNSW) {
266609467b48Spatrick   unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
266709467b48Spatrick                    (HasNSW ? OverflowingBinaryOperator::NoSignedWrap   : 0);
266809467b48Spatrick   return get(Instruction::Sub, C1, C2, Flags);
266909467b48Spatrick }
267009467b48Spatrick 
getMul(Constant * C1,Constant * C2,bool HasNUW,bool HasNSW)267109467b48Spatrick Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
267209467b48Spatrick                                bool HasNUW, bool HasNSW) {
267309467b48Spatrick   unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
267409467b48Spatrick                    (HasNSW ? OverflowingBinaryOperator::NoSignedWrap   : 0);
267509467b48Spatrick   return get(Instruction::Mul, C1, C2, Flags);
267609467b48Spatrick }
267709467b48Spatrick 
getAnd(Constant * C1,Constant * C2)267809467b48Spatrick Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
267909467b48Spatrick   return get(Instruction::And, C1, C2);
268009467b48Spatrick }
268109467b48Spatrick 
getOr(Constant * C1,Constant * C2)268209467b48Spatrick Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
268309467b48Spatrick   return get(Instruction::Or, C1, C2);
268409467b48Spatrick }
268509467b48Spatrick 
getXor(Constant * C1,Constant * C2)268609467b48Spatrick Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
268709467b48Spatrick   return get(Instruction::Xor, C1, C2);
268809467b48Spatrick }
268909467b48Spatrick 
getUMin(Constant * C1,Constant * C2)269073471bf0Spatrick Constant *ConstantExpr::getUMin(Constant *C1, Constant *C2) {
269173471bf0Spatrick   Constant *Cmp = ConstantExpr::getICmp(CmpInst::ICMP_ULT, C1, C2);
269273471bf0Spatrick   return getSelect(Cmp, C1, C2);
269373471bf0Spatrick }
269473471bf0Spatrick 
getShl(Constant * C1,Constant * C2,bool HasNUW,bool HasNSW)269509467b48Spatrick Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
269609467b48Spatrick                                bool HasNUW, bool HasNSW) {
269709467b48Spatrick   unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
269809467b48Spatrick                    (HasNSW ? OverflowingBinaryOperator::NoSignedWrap   : 0);
269909467b48Spatrick   return get(Instruction::Shl, C1, C2, Flags);
270009467b48Spatrick }
270109467b48Spatrick 
getLShr(Constant * C1,Constant * C2,bool isExact)270209467b48Spatrick Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
270309467b48Spatrick   return get(Instruction::LShr, C1, C2,
270409467b48Spatrick              isExact ? PossiblyExactOperator::IsExact : 0);
270509467b48Spatrick }
270609467b48Spatrick 
getAShr(Constant * C1,Constant * C2,bool isExact)270709467b48Spatrick Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
270809467b48Spatrick   return get(Instruction::AShr, C1, C2,
270909467b48Spatrick              isExact ? PossiblyExactOperator::IsExact : 0);
271009467b48Spatrick }
271109467b48Spatrick 
getExactLogBase2(Constant * C)271273471bf0Spatrick Constant *ConstantExpr::getExactLogBase2(Constant *C) {
271373471bf0Spatrick   Type *Ty = C->getType();
271473471bf0Spatrick   const APInt *IVal;
271573471bf0Spatrick   if (match(C, m_APInt(IVal)) && IVal->isPowerOf2())
271673471bf0Spatrick     return ConstantInt::get(Ty, IVal->logBase2());
271773471bf0Spatrick 
271873471bf0Spatrick   // FIXME: We can extract pow of 2 of splat constant for scalable vectors.
271973471bf0Spatrick   auto *VecTy = dyn_cast<FixedVectorType>(Ty);
272073471bf0Spatrick   if (!VecTy)
272173471bf0Spatrick     return nullptr;
272273471bf0Spatrick 
272373471bf0Spatrick   SmallVector<Constant *, 4> Elts;
272473471bf0Spatrick   for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
272573471bf0Spatrick     Constant *Elt = C->getAggregateElement(I);
272673471bf0Spatrick     if (!Elt)
272773471bf0Spatrick       return nullptr;
272873471bf0Spatrick     // Note that log2(iN undef) is *NOT* iN undef, because log2(iN undef) u< N.
272973471bf0Spatrick     if (isa<UndefValue>(Elt)) {
273073471bf0Spatrick       Elts.push_back(Constant::getNullValue(Ty->getScalarType()));
273173471bf0Spatrick       continue;
273273471bf0Spatrick     }
273373471bf0Spatrick     if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
273473471bf0Spatrick       return nullptr;
273573471bf0Spatrick     Elts.push_back(ConstantInt::get(Ty->getScalarType(), IVal->logBase2()));
273673471bf0Spatrick   }
273773471bf0Spatrick 
273873471bf0Spatrick   return ConstantVector::get(Elts);
273973471bf0Spatrick }
274073471bf0Spatrick 
getBinOpIdentity(unsigned Opcode,Type * Ty,bool AllowRHSConstant,bool NSZ)274109467b48Spatrick Constant *ConstantExpr::getBinOpIdentity(unsigned Opcode, Type *Ty,
2742*d415bd75Srobert                                          bool AllowRHSConstant, bool NSZ) {
274309467b48Spatrick   assert(Instruction::isBinaryOp(Opcode) && "Only binops allowed");
274409467b48Spatrick 
274509467b48Spatrick   // Commutative opcodes: it does not matter if AllowRHSConstant is set.
274609467b48Spatrick   if (Instruction::isCommutative(Opcode)) {
274709467b48Spatrick     switch (Opcode) {
274809467b48Spatrick       case Instruction::Add: // X + 0 = X
274909467b48Spatrick       case Instruction::Or:  // X | 0 = X
275009467b48Spatrick       case Instruction::Xor: // X ^ 0 = X
275109467b48Spatrick         return Constant::getNullValue(Ty);
275209467b48Spatrick       case Instruction::Mul: // X * 1 = X
275309467b48Spatrick         return ConstantInt::get(Ty, 1);
275409467b48Spatrick       case Instruction::And: // X & -1 = X
275509467b48Spatrick         return Constant::getAllOnesValue(Ty);
275609467b48Spatrick       case Instruction::FAdd: // X + -0.0 = X
2757*d415bd75Srobert         return ConstantFP::getZero(Ty, !NSZ);
275809467b48Spatrick       case Instruction::FMul: // X * 1.0 = X
275909467b48Spatrick         return ConstantFP::get(Ty, 1.0);
276009467b48Spatrick       default:
276109467b48Spatrick         llvm_unreachable("Every commutative binop has an identity constant");
276209467b48Spatrick     }
276309467b48Spatrick   }
276409467b48Spatrick 
276509467b48Spatrick   // Non-commutative opcodes: AllowRHSConstant must be set.
276609467b48Spatrick   if (!AllowRHSConstant)
276709467b48Spatrick     return nullptr;
276809467b48Spatrick 
276909467b48Spatrick   switch (Opcode) {
277009467b48Spatrick     case Instruction::Sub:  // X - 0 = X
277109467b48Spatrick     case Instruction::Shl:  // X << 0 = X
277209467b48Spatrick     case Instruction::LShr: // X >>u 0 = X
277309467b48Spatrick     case Instruction::AShr: // X >> 0 = X
277409467b48Spatrick     case Instruction::FSub: // X - 0.0 = X
277509467b48Spatrick       return Constant::getNullValue(Ty);
277609467b48Spatrick     case Instruction::SDiv: // X / 1 = X
277709467b48Spatrick     case Instruction::UDiv: // X /u 1 = X
277809467b48Spatrick       return ConstantInt::get(Ty, 1);
277909467b48Spatrick     case Instruction::FDiv: // X / 1.0 = X
278009467b48Spatrick       return ConstantFP::get(Ty, 1.0);
278109467b48Spatrick     default:
278209467b48Spatrick       return nullptr;
278309467b48Spatrick   }
278409467b48Spatrick }
278509467b48Spatrick 
getBinOpAbsorber(unsigned Opcode,Type * Ty)278609467b48Spatrick Constant *ConstantExpr::getBinOpAbsorber(unsigned Opcode, Type *Ty) {
278709467b48Spatrick   switch (Opcode) {
278809467b48Spatrick   default:
278909467b48Spatrick     // Doesn't have an absorber.
279009467b48Spatrick     return nullptr;
279109467b48Spatrick 
279209467b48Spatrick   case Instruction::Or:
279309467b48Spatrick     return Constant::getAllOnesValue(Ty);
279409467b48Spatrick 
279509467b48Spatrick   case Instruction::And:
279609467b48Spatrick   case Instruction::Mul:
279709467b48Spatrick     return Constant::getNullValue(Ty);
279809467b48Spatrick   }
279909467b48Spatrick }
280009467b48Spatrick 
280109467b48Spatrick /// Remove the constant from the constant table.
destroyConstantImpl()280209467b48Spatrick void ConstantExpr::destroyConstantImpl() {
280309467b48Spatrick   getType()->getContext().pImpl->ExprConstants.remove(this);
280409467b48Spatrick }
280509467b48Spatrick 
getOpcodeName() const280609467b48Spatrick const char *ConstantExpr::getOpcodeName() const {
280709467b48Spatrick   return Instruction::getOpcodeName(getOpcode());
280809467b48Spatrick }
280909467b48Spatrick 
GetElementPtrConstantExpr(Type * SrcElementTy,Constant * C,ArrayRef<Constant * > IdxList,Type * DestTy)281009467b48Spatrick GetElementPtrConstantExpr::GetElementPtrConstantExpr(
281109467b48Spatrick     Type *SrcElementTy, Constant *C, ArrayRef<Constant *> IdxList, Type *DestTy)
281209467b48Spatrick     : ConstantExpr(DestTy, Instruction::GetElementPtr,
281309467b48Spatrick                    OperandTraits<GetElementPtrConstantExpr>::op_end(this) -
281409467b48Spatrick                        (IdxList.size() + 1),
281509467b48Spatrick                    IdxList.size() + 1),
281609467b48Spatrick       SrcElementTy(SrcElementTy),
281709467b48Spatrick       ResElementTy(GetElementPtrInst::getIndexedType(SrcElementTy, IdxList)) {
281809467b48Spatrick   Op<0>() = C;
281909467b48Spatrick   Use *OperandList = getOperandList();
282009467b48Spatrick   for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
282109467b48Spatrick     OperandList[i+1] = IdxList[i];
282209467b48Spatrick }
282309467b48Spatrick 
getSourceElementType() const282409467b48Spatrick Type *GetElementPtrConstantExpr::getSourceElementType() const {
282509467b48Spatrick   return SrcElementTy;
282609467b48Spatrick }
282709467b48Spatrick 
getResultElementType() const282809467b48Spatrick Type *GetElementPtrConstantExpr::getResultElementType() const {
282909467b48Spatrick   return ResElementTy;
283009467b48Spatrick }
283109467b48Spatrick 
283209467b48Spatrick //===----------------------------------------------------------------------===//
283309467b48Spatrick //                       ConstantData* implementations
283409467b48Spatrick 
getElementType() const283509467b48Spatrick Type *ConstantDataSequential::getElementType() const {
2836097a140dSpatrick   if (ArrayType *ATy = dyn_cast<ArrayType>(getType()))
2837097a140dSpatrick     return ATy->getElementType();
2838097a140dSpatrick   return cast<VectorType>(getType())->getElementType();
283909467b48Spatrick }
284009467b48Spatrick 
getRawDataValues() const284109467b48Spatrick StringRef ConstantDataSequential::getRawDataValues() const {
284209467b48Spatrick   return StringRef(DataElements, getNumElements()*getElementByteSize());
284309467b48Spatrick }
284409467b48Spatrick 
isElementTypeCompatible(Type * Ty)284509467b48Spatrick bool ConstantDataSequential::isElementTypeCompatible(Type *Ty) {
2846097a140dSpatrick   if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() || Ty->isDoubleTy())
2847097a140dSpatrick     return true;
284809467b48Spatrick   if (auto *IT = dyn_cast<IntegerType>(Ty)) {
284909467b48Spatrick     switch (IT->getBitWidth()) {
285009467b48Spatrick     case 8:
285109467b48Spatrick     case 16:
285209467b48Spatrick     case 32:
285309467b48Spatrick     case 64:
285409467b48Spatrick       return true;
285509467b48Spatrick     default: break;
285609467b48Spatrick     }
285709467b48Spatrick   }
285809467b48Spatrick   return false;
285909467b48Spatrick }
286009467b48Spatrick 
getNumElements() const286109467b48Spatrick unsigned ConstantDataSequential::getNumElements() const {
286209467b48Spatrick   if (ArrayType *AT = dyn_cast<ArrayType>(getType()))
286309467b48Spatrick     return AT->getNumElements();
286473471bf0Spatrick   return cast<FixedVectorType>(getType())->getNumElements();
286509467b48Spatrick }
286609467b48Spatrick 
286709467b48Spatrick 
getElementByteSize() const286809467b48Spatrick uint64_t ConstantDataSequential::getElementByteSize() const {
286909467b48Spatrick   return getElementType()->getPrimitiveSizeInBits()/8;
287009467b48Spatrick }
287109467b48Spatrick 
287209467b48Spatrick /// Return the start of the specified element.
getElementPointer(unsigned Elt) const287309467b48Spatrick const char *ConstantDataSequential::getElementPointer(unsigned Elt) const {
287409467b48Spatrick   assert(Elt < getNumElements() && "Invalid Elt");
287509467b48Spatrick   return DataElements+Elt*getElementByteSize();
287609467b48Spatrick }
287709467b48Spatrick 
287809467b48Spatrick 
287909467b48Spatrick /// Return true if the array is empty or all zeros.
isAllZeros(StringRef Arr)288009467b48Spatrick static bool isAllZeros(StringRef Arr) {
288109467b48Spatrick   for (char I : Arr)
288209467b48Spatrick     if (I != 0)
288309467b48Spatrick       return false;
288409467b48Spatrick   return true;
288509467b48Spatrick }
288609467b48Spatrick 
288709467b48Spatrick /// This is the underlying implementation of all of the
288809467b48Spatrick /// ConstantDataSequential::get methods.  They all thunk down to here, providing
288909467b48Spatrick /// the correct element type.  We take the bytes in as a StringRef because
289009467b48Spatrick /// we *want* an underlying "char*" to avoid TBAA type punning violations.
getImpl(StringRef Elements,Type * Ty)289109467b48Spatrick Constant *ConstantDataSequential::getImpl(StringRef Elements, Type *Ty) {
2892097a140dSpatrick #ifndef NDEBUG
2893097a140dSpatrick   if (ArrayType *ATy = dyn_cast<ArrayType>(Ty))
2894097a140dSpatrick     assert(isElementTypeCompatible(ATy->getElementType()));
2895097a140dSpatrick   else
2896097a140dSpatrick     assert(isElementTypeCompatible(cast<VectorType>(Ty)->getElementType()));
2897097a140dSpatrick #endif
289809467b48Spatrick   // If the elements are all zero or there are no elements, return a CAZ, which
289909467b48Spatrick   // is more dense and canonical.
290009467b48Spatrick   if (isAllZeros(Elements))
290109467b48Spatrick     return ConstantAggregateZero::get(Ty);
290209467b48Spatrick 
290309467b48Spatrick   // Do a lookup to see if we have already formed one of these.
290409467b48Spatrick   auto &Slot =
290509467b48Spatrick       *Ty->getContext()
290609467b48Spatrick            .pImpl->CDSConstants.insert(std::make_pair(Elements, nullptr))
290709467b48Spatrick            .first;
290809467b48Spatrick 
290909467b48Spatrick   // The bucket can point to a linked list of different CDS's that have the same
291009467b48Spatrick   // body but different types.  For example, 0,0,0,1 could be a 4 element array
291109467b48Spatrick   // of i8, or a 1-element array of i32.  They'll both end up in the same
291209467b48Spatrick   /// StringMap bucket, linked up by their Next pointers.  Walk the list.
291373471bf0Spatrick   std::unique_ptr<ConstantDataSequential> *Entry = &Slot.second;
291473471bf0Spatrick   for (; *Entry; Entry = &(*Entry)->Next)
291573471bf0Spatrick     if ((*Entry)->getType() == Ty)
291673471bf0Spatrick       return Entry->get();
291709467b48Spatrick 
291809467b48Spatrick   // Okay, we didn't get a hit.  Create a node of the right class, link it in,
291909467b48Spatrick   // and return it.
292073471bf0Spatrick   if (isa<ArrayType>(Ty)) {
292173471bf0Spatrick     // Use reset because std::make_unique can't access the constructor.
292273471bf0Spatrick     Entry->reset(new ConstantDataArray(Ty, Slot.first().data()));
292373471bf0Spatrick     return Entry->get();
292473471bf0Spatrick   }
292509467b48Spatrick 
292609467b48Spatrick   assert(isa<VectorType>(Ty));
292773471bf0Spatrick   // Use reset because std::make_unique can't access the constructor.
292873471bf0Spatrick   Entry->reset(new ConstantDataVector(Ty, Slot.first().data()));
292973471bf0Spatrick   return Entry->get();
293009467b48Spatrick }
293109467b48Spatrick 
destroyConstantImpl()293209467b48Spatrick void ConstantDataSequential::destroyConstantImpl() {
293309467b48Spatrick   // Remove the constant from the StringMap.
293473471bf0Spatrick   StringMap<std::unique_ptr<ConstantDataSequential>> &CDSConstants =
293509467b48Spatrick       getType()->getContext().pImpl->CDSConstants;
293609467b48Spatrick 
293773471bf0Spatrick   auto Slot = CDSConstants.find(getRawDataValues());
293809467b48Spatrick 
293909467b48Spatrick   assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
294009467b48Spatrick 
294173471bf0Spatrick   std::unique_ptr<ConstantDataSequential> *Entry = &Slot->getValue();
294209467b48Spatrick 
294309467b48Spatrick   // Remove the entry from the hash table.
294409467b48Spatrick   if (!(*Entry)->Next) {
294509467b48Spatrick     // If there is only one value in the bucket (common case) it must be this
294609467b48Spatrick     // entry, and removing the entry should remove the bucket completely.
294773471bf0Spatrick     assert(Entry->get() == this && "Hash mismatch in ConstantDataSequential");
294809467b48Spatrick     getContext().pImpl->CDSConstants.erase(Slot);
294973471bf0Spatrick     return;
295009467b48Spatrick   }
295109467b48Spatrick 
295273471bf0Spatrick   // Otherwise, there are multiple entries linked off the bucket, unlink the
295373471bf0Spatrick   // node we care about but keep the bucket around.
295473471bf0Spatrick   while (true) {
295573471bf0Spatrick     std::unique_ptr<ConstantDataSequential> &Node = *Entry;
295673471bf0Spatrick     assert(Node && "Didn't find entry in its uniquing hash table!");
295773471bf0Spatrick     // If we found our entry, unlink it from the list and we're done.
295873471bf0Spatrick     if (Node.get() == this) {
295973471bf0Spatrick       Node = std::move(Node->Next);
296073471bf0Spatrick       return;
296173471bf0Spatrick     }
296273471bf0Spatrick 
296373471bf0Spatrick     Entry = &Node->Next;
296473471bf0Spatrick   }
296509467b48Spatrick }
296609467b48Spatrick 
2967097a140dSpatrick /// getFP() constructors - Return a constant of array type with a float
2968097a140dSpatrick /// element type taken from argument `ElementType', and count taken from
2969097a140dSpatrick /// argument `Elts'.  The amount of bits of the contained type must match the
2970097a140dSpatrick /// number of bits of the type contained in the passed in ArrayRef.
2971097a140dSpatrick /// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note
2972097a140dSpatrick /// that this can return a ConstantAggregateZero object.
getFP(Type * ElementType,ArrayRef<uint16_t> Elts)2973097a140dSpatrick Constant *ConstantDataArray::getFP(Type *ElementType, ArrayRef<uint16_t> Elts) {
2974097a140dSpatrick   assert((ElementType->isHalfTy() || ElementType->isBFloatTy()) &&
2975097a140dSpatrick          "Element type is not a 16-bit float type");
2976097a140dSpatrick   Type *Ty = ArrayType::get(ElementType, Elts.size());
297709467b48Spatrick   const char *Data = reinterpret_cast<const char *>(Elts.data());
297809467b48Spatrick   return getImpl(StringRef(Data, Elts.size() * 2), Ty);
297909467b48Spatrick }
getFP(Type * ElementType,ArrayRef<uint32_t> Elts)2980097a140dSpatrick Constant *ConstantDataArray::getFP(Type *ElementType, ArrayRef<uint32_t> Elts) {
2981097a140dSpatrick   assert(ElementType->isFloatTy() && "Element type is not a 32-bit float type");
2982097a140dSpatrick   Type *Ty = ArrayType::get(ElementType, Elts.size());
298309467b48Spatrick   const char *Data = reinterpret_cast<const char *>(Elts.data());
298409467b48Spatrick   return getImpl(StringRef(Data, Elts.size() * 4), Ty);
298509467b48Spatrick }
getFP(Type * ElementType,ArrayRef<uint64_t> Elts)2986097a140dSpatrick Constant *ConstantDataArray::getFP(Type *ElementType, ArrayRef<uint64_t> Elts) {
2987097a140dSpatrick   assert(ElementType->isDoubleTy() &&
2988097a140dSpatrick          "Element type is not a 64-bit float type");
2989097a140dSpatrick   Type *Ty = ArrayType::get(ElementType, Elts.size());
299009467b48Spatrick   const char *Data = reinterpret_cast<const char *>(Elts.data());
299109467b48Spatrick   return getImpl(StringRef(Data, Elts.size() * 8), Ty);
299209467b48Spatrick }
299309467b48Spatrick 
getString(LLVMContext & Context,StringRef Str,bool AddNull)299409467b48Spatrick Constant *ConstantDataArray::getString(LLVMContext &Context,
299509467b48Spatrick                                        StringRef Str, bool AddNull) {
299609467b48Spatrick   if (!AddNull) {
299709467b48Spatrick     const uint8_t *Data = Str.bytes_begin();
2998*d415bd75Srobert     return get(Context, ArrayRef(Data, Str.size()));
299909467b48Spatrick   }
300009467b48Spatrick 
300109467b48Spatrick   SmallVector<uint8_t, 64> ElementVals;
300209467b48Spatrick   ElementVals.append(Str.begin(), Str.end());
300309467b48Spatrick   ElementVals.push_back(0);
300409467b48Spatrick   return get(Context, ElementVals);
300509467b48Spatrick }
300609467b48Spatrick 
300709467b48Spatrick /// get() constructors - Return a constant with vector type with an element
300809467b48Spatrick /// count and element type matching the ArrayRef passed in.  Note that this
300909467b48Spatrick /// can return a ConstantAggregateZero object.
get(LLVMContext & Context,ArrayRef<uint8_t> Elts)301009467b48Spatrick Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> Elts){
3011097a140dSpatrick   auto *Ty = FixedVectorType::get(Type::getInt8Ty(Context), Elts.size());
301209467b48Spatrick   const char *Data = reinterpret_cast<const char *>(Elts.data());
301309467b48Spatrick   return getImpl(StringRef(Data, Elts.size() * 1), Ty);
301409467b48Spatrick }
get(LLVMContext & Context,ArrayRef<uint16_t> Elts)301509467b48Spatrick Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
3016097a140dSpatrick   auto *Ty = FixedVectorType::get(Type::getInt16Ty(Context), Elts.size());
301709467b48Spatrick   const char *Data = reinterpret_cast<const char *>(Elts.data());
301809467b48Spatrick   return getImpl(StringRef(Data, Elts.size() * 2), Ty);
301909467b48Spatrick }
get(LLVMContext & Context,ArrayRef<uint32_t> Elts)302009467b48Spatrick Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
3021097a140dSpatrick   auto *Ty = FixedVectorType::get(Type::getInt32Ty(Context), Elts.size());
302209467b48Spatrick   const char *Data = reinterpret_cast<const char *>(Elts.data());
302309467b48Spatrick   return getImpl(StringRef(Data, Elts.size() * 4), Ty);
302409467b48Spatrick }
get(LLVMContext & Context,ArrayRef<uint64_t> Elts)302509467b48Spatrick Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
3026097a140dSpatrick   auto *Ty = FixedVectorType::get(Type::getInt64Ty(Context), Elts.size());
302709467b48Spatrick   const char *Data = reinterpret_cast<const char *>(Elts.data());
302809467b48Spatrick   return getImpl(StringRef(Data, Elts.size() * 8), Ty);
302909467b48Spatrick }
get(LLVMContext & Context,ArrayRef<float> Elts)303009467b48Spatrick Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> Elts) {
3031097a140dSpatrick   auto *Ty = FixedVectorType::get(Type::getFloatTy(Context), Elts.size());
303209467b48Spatrick   const char *Data = reinterpret_cast<const char *>(Elts.data());
303309467b48Spatrick   return getImpl(StringRef(Data, Elts.size() * 4), Ty);
303409467b48Spatrick }
get(LLVMContext & Context,ArrayRef<double> Elts)303509467b48Spatrick Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<double> Elts) {
3036097a140dSpatrick   auto *Ty = FixedVectorType::get(Type::getDoubleTy(Context), Elts.size());
303709467b48Spatrick   const char *Data = reinterpret_cast<const char *>(Elts.data());
303809467b48Spatrick   return getImpl(StringRef(Data, Elts.size() * 8), Ty);
303909467b48Spatrick }
304009467b48Spatrick 
3041097a140dSpatrick /// getFP() constructors - Return a constant of vector type with a float
3042097a140dSpatrick /// element type taken from argument `ElementType', and count taken from
3043097a140dSpatrick /// argument `Elts'.  The amount of bits of the contained type must match the
3044097a140dSpatrick /// number of bits of the type contained in the passed in ArrayRef.
3045097a140dSpatrick /// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note
3046097a140dSpatrick /// that this can return a ConstantAggregateZero object.
getFP(Type * ElementType,ArrayRef<uint16_t> Elts)3047097a140dSpatrick Constant *ConstantDataVector::getFP(Type *ElementType,
304809467b48Spatrick                                     ArrayRef<uint16_t> Elts) {
3049097a140dSpatrick   assert((ElementType->isHalfTy() || ElementType->isBFloatTy()) &&
3050097a140dSpatrick          "Element type is not a 16-bit float type");
3051097a140dSpatrick   auto *Ty = FixedVectorType::get(ElementType, Elts.size());
305209467b48Spatrick   const char *Data = reinterpret_cast<const char *>(Elts.data());
305309467b48Spatrick   return getImpl(StringRef(Data, Elts.size() * 2), Ty);
305409467b48Spatrick }
getFP(Type * ElementType,ArrayRef<uint32_t> Elts)3055097a140dSpatrick Constant *ConstantDataVector::getFP(Type *ElementType,
305609467b48Spatrick                                     ArrayRef<uint32_t> Elts) {
3057097a140dSpatrick   assert(ElementType->isFloatTy() && "Element type is not a 32-bit float type");
3058097a140dSpatrick   auto *Ty = FixedVectorType::get(ElementType, Elts.size());
305909467b48Spatrick   const char *Data = reinterpret_cast<const char *>(Elts.data());
306009467b48Spatrick   return getImpl(StringRef(Data, Elts.size() * 4), Ty);
306109467b48Spatrick }
getFP(Type * ElementType,ArrayRef<uint64_t> Elts)3062097a140dSpatrick Constant *ConstantDataVector::getFP(Type *ElementType,
306309467b48Spatrick                                     ArrayRef<uint64_t> Elts) {
3064097a140dSpatrick   assert(ElementType->isDoubleTy() &&
3065097a140dSpatrick          "Element type is not a 64-bit float type");
3066097a140dSpatrick   auto *Ty = FixedVectorType::get(ElementType, Elts.size());
306709467b48Spatrick   const char *Data = reinterpret_cast<const char *>(Elts.data());
306809467b48Spatrick   return getImpl(StringRef(Data, Elts.size() * 8), Ty);
306909467b48Spatrick }
307009467b48Spatrick 
getSplat(unsigned NumElts,Constant * V)307109467b48Spatrick Constant *ConstantDataVector::getSplat(unsigned NumElts, Constant *V) {
307209467b48Spatrick   assert(isElementTypeCompatible(V->getType()) &&
307309467b48Spatrick          "Element type not compatible with ConstantData");
307409467b48Spatrick   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
307509467b48Spatrick     if (CI->getType()->isIntegerTy(8)) {
307609467b48Spatrick       SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
307709467b48Spatrick       return get(V->getContext(), Elts);
307809467b48Spatrick     }
307909467b48Spatrick     if (CI->getType()->isIntegerTy(16)) {
308009467b48Spatrick       SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
308109467b48Spatrick       return get(V->getContext(), Elts);
308209467b48Spatrick     }
308309467b48Spatrick     if (CI->getType()->isIntegerTy(32)) {
308409467b48Spatrick       SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
308509467b48Spatrick       return get(V->getContext(), Elts);
308609467b48Spatrick     }
308709467b48Spatrick     assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
308809467b48Spatrick     SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
308909467b48Spatrick     return get(V->getContext(), Elts);
309009467b48Spatrick   }
309109467b48Spatrick 
309209467b48Spatrick   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
309309467b48Spatrick     if (CFP->getType()->isHalfTy()) {
309409467b48Spatrick       SmallVector<uint16_t, 16> Elts(
309509467b48Spatrick           NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3096097a140dSpatrick       return getFP(V->getType(), Elts);
3097097a140dSpatrick     }
3098097a140dSpatrick     if (CFP->getType()->isBFloatTy()) {
3099097a140dSpatrick       SmallVector<uint16_t, 16> Elts(
3100097a140dSpatrick           NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3101097a140dSpatrick       return getFP(V->getType(), Elts);
310209467b48Spatrick     }
310309467b48Spatrick     if (CFP->getType()->isFloatTy()) {
310409467b48Spatrick       SmallVector<uint32_t, 16> Elts(
310509467b48Spatrick           NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3106097a140dSpatrick       return getFP(V->getType(), Elts);
310709467b48Spatrick     }
310809467b48Spatrick     if (CFP->getType()->isDoubleTy()) {
310909467b48Spatrick       SmallVector<uint64_t, 16> Elts(
311009467b48Spatrick           NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3111097a140dSpatrick       return getFP(V->getType(), Elts);
311209467b48Spatrick     }
311309467b48Spatrick   }
311473471bf0Spatrick   return ConstantVector::getSplat(ElementCount::getFixed(NumElts), V);
311509467b48Spatrick }
311609467b48Spatrick 
311709467b48Spatrick 
getElementAsInteger(unsigned Elt) const311809467b48Spatrick uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const {
311909467b48Spatrick   assert(isa<IntegerType>(getElementType()) &&
312009467b48Spatrick          "Accessor can only be used when element is an integer");
312109467b48Spatrick   const char *EltPtr = getElementPointer(Elt);
312209467b48Spatrick 
312309467b48Spatrick   // The data is stored in host byte order, make sure to cast back to the right
312409467b48Spatrick   // type to load with the right endianness.
312509467b48Spatrick   switch (getElementType()->getIntegerBitWidth()) {
312609467b48Spatrick   default: llvm_unreachable("Invalid bitwidth for CDS");
312709467b48Spatrick   case 8:
312809467b48Spatrick     return *reinterpret_cast<const uint8_t *>(EltPtr);
312909467b48Spatrick   case 16:
313009467b48Spatrick     return *reinterpret_cast<const uint16_t *>(EltPtr);
313109467b48Spatrick   case 32:
313209467b48Spatrick     return *reinterpret_cast<const uint32_t *>(EltPtr);
313309467b48Spatrick   case 64:
313409467b48Spatrick     return *reinterpret_cast<const uint64_t *>(EltPtr);
313509467b48Spatrick   }
313609467b48Spatrick }
313709467b48Spatrick 
getElementAsAPInt(unsigned Elt) const313809467b48Spatrick APInt ConstantDataSequential::getElementAsAPInt(unsigned Elt) const {
313909467b48Spatrick   assert(isa<IntegerType>(getElementType()) &&
314009467b48Spatrick          "Accessor can only be used when element is an integer");
314109467b48Spatrick   const char *EltPtr = getElementPointer(Elt);
314209467b48Spatrick 
314309467b48Spatrick   // The data is stored in host byte order, make sure to cast back to the right
314409467b48Spatrick   // type to load with the right endianness.
314509467b48Spatrick   switch (getElementType()->getIntegerBitWidth()) {
314609467b48Spatrick   default: llvm_unreachable("Invalid bitwidth for CDS");
314709467b48Spatrick   case 8: {
314809467b48Spatrick     auto EltVal = *reinterpret_cast<const uint8_t *>(EltPtr);
314909467b48Spatrick     return APInt(8, EltVal);
315009467b48Spatrick   }
315109467b48Spatrick   case 16: {
315209467b48Spatrick     auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
315309467b48Spatrick     return APInt(16, EltVal);
315409467b48Spatrick   }
315509467b48Spatrick   case 32: {
315609467b48Spatrick     auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
315709467b48Spatrick     return APInt(32, EltVal);
315809467b48Spatrick   }
315909467b48Spatrick   case 64: {
316009467b48Spatrick     auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
316109467b48Spatrick     return APInt(64, EltVal);
316209467b48Spatrick   }
316309467b48Spatrick   }
316409467b48Spatrick }
316509467b48Spatrick 
getElementAsAPFloat(unsigned Elt) const316609467b48Spatrick APFloat ConstantDataSequential::getElementAsAPFloat(unsigned Elt) const {
316709467b48Spatrick   const char *EltPtr = getElementPointer(Elt);
316809467b48Spatrick 
316909467b48Spatrick   switch (getElementType()->getTypeID()) {
317009467b48Spatrick   default:
317109467b48Spatrick     llvm_unreachable("Accessor can only be used when element is float/double!");
317209467b48Spatrick   case Type::HalfTyID: {
317309467b48Spatrick     auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
317409467b48Spatrick     return APFloat(APFloat::IEEEhalf(), APInt(16, EltVal));
317509467b48Spatrick   }
3176097a140dSpatrick   case Type::BFloatTyID: {
3177097a140dSpatrick     auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3178097a140dSpatrick     return APFloat(APFloat::BFloat(), APInt(16, EltVal));
3179097a140dSpatrick   }
318009467b48Spatrick   case Type::FloatTyID: {
318109467b48Spatrick     auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
318209467b48Spatrick     return APFloat(APFloat::IEEEsingle(), APInt(32, EltVal));
318309467b48Spatrick   }
318409467b48Spatrick   case Type::DoubleTyID: {
318509467b48Spatrick     auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
318609467b48Spatrick     return APFloat(APFloat::IEEEdouble(), APInt(64, EltVal));
318709467b48Spatrick   }
318809467b48Spatrick   }
318909467b48Spatrick }
319009467b48Spatrick 
getElementAsFloat(unsigned Elt) const319109467b48Spatrick float ConstantDataSequential::getElementAsFloat(unsigned Elt) const {
319209467b48Spatrick   assert(getElementType()->isFloatTy() &&
319309467b48Spatrick          "Accessor can only be used when element is a 'float'");
319409467b48Spatrick   return *reinterpret_cast<const float *>(getElementPointer(Elt));
319509467b48Spatrick }
319609467b48Spatrick 
getElementAsDouble(unsigned Elt) const319709467b48Spatrick double ConstantDataSequential::getElementAsDouble(unsigned Elt) const {
319809467b48Spatrick   assert(getElementType()->isDoubleTy() &&
319909467b48Spatrick          "Accessor can only be used when element is a 'float'");
320009467b48Spatrick   return *reinterpret_cast<const double *>(getElementPointer(Elt));
320109467b48Spatrick }
320209467b48Spatrick 
getElementAsConstant(unsigned Elt) const320309467b48Spatrick Constant *ConstantDataSequential::getElementAsConstant(unsigned Elt) const {
3204097a140dSpatrick   if (getElementType()->isHalfTy() || getElementType()->isBFloatTy() ||
3205097a140dSpatrick       getElementType()->isFloatTy() || getElementType()->isDoubleTy())
320609467b48Spatrick     return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
320709467b48Spatrick 
320809467b48Spatrick   return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
320909467b48Spatrick }
321009467b48Spatrick 
isString(unsigned CharSize) const321109467b48Spatrick bool ConstantDataSequential::isString(unsigned CharSize) const {
321209467b48Spatrick   return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(CharSize);
321309467b48Spatrick }
321409467b48Spatrick 
isCString() const321509467b48Spatrick bool ConstantDataSequential::isCString() const {
321609467b48Spatrick   if (!isString())
321709467b48Spatrick     return false;
321809467b48Spatrick 
321909467b48Spatrick   StringRef Str = getAsString();
322009467b48Spatrick 
322109467b48Spatrick   // The last value must be nul.
322209467b48Spatrick   if (Str.back() != 0) return false;
322309467b48Spatrick 
322409467b48Spatrick   // Other elements must be non-nul.
3225*d415bd75Srobert   return !Str.drop_back().contains(0);
322609467b48Spatrick }
322709467b48Spatrick 
isSplatData() const3228097a140dSpatrick bool ConstantDataVector::isSplatData() const {
322909467b48Spatrick   const char *Base = getRawDataValues().data();
323009467b48Spatrick 
323109467b48Spatrick   // Compare elements 1+ to the 0'th element.
323209467b48Spatrick   unsigned EltSize = getElementByteSize();
323309467b48Spatrick   for (unsigned i = 1, e = getNumElements(); i != e; ++i)
323409467b48Spatrick     if (memcmp(Base, Base+i*EltSize, EltSize))
323509467b48Spatrick       return false;
323609467b48Spatrick 
323709467b48Spatrick   return true;
323809467b48Spatrick }
323909467b48Spatrick 
isSplat() const3240097a140dSpatrick bool ConstantDataVector::isSplat() const {
3241097a140dSpatrick   if (!IsSplatSet) {
3242097a140dSpatrick     IsSplatSet = true;
3243097a140dSpatrick     IsSplat = isSplatData();
3244097a140dSpatrick   }
3245097a140dSpatrick   return IsSplat;
3246097a140dSpatrick }
3247097a140dSpatrick 
getSplatValue() const324809467b48Spatrick Constant *ConstantDataVector::getSplatValue() const {
324909467b48Spatrick   // If they're all the same, return the 0th one as a representative.
325009467b48Spatrick   return isSplat() ? getElementAsConstant(0) : nullptr;
325109467b48Spatrick }
325209467b48Spatrick 
325309467b48Spatrick //===----------------------------------------------------------------------===//
325409467b48Spatrick //                handleOperandChange implementations
325509467b48Spatrick 
325609467b48Spatrick /// Update this constant array to change uses of
325709467b48Spatrick /// 'From' to be uses of 'To'.  This must update the uniquing data structures
325809467b48Spatrick /// etc.
325909467b48Spatrick ///
326009467b48Spatrick /// Note that we intentionally replace all uses of From with To here.  Consider
326109467b48Spatrick /// a large array that uses 'From' 1000 times.  By handling this case all here,
326209467b48Spatrick /// ConstantArray::handleOperandChange is only invoked once, and that
326309467b48Spatrick /// single invocation handles all 1000 uses.  Handling them one at a time would
326409467b48Spatrick /// work, but would be really slow because it would have to unique each updated
326509467b48Spatrick /// array instance.
326609467b48Spatrick ///
handleOperandChange(Value * From,Value * To)326709467b48Spatrick void Constant::handleOperandChange(Value *From, Value *To) {
326809467b48Spatrick   Value *Replacement = nullptr;
326909467b48Spatrick   switch (getValueID()) {
327009467b48Spatrick   default:
327109467b48Spatrick     llvm_unreachable("Not a constant!");
327209467b48Spatrick #define HANDLE_CONSTANT(Name)                                                  \
327309467b48Spatrick   case Value::Name##Val:                                                       \
327409467b48Spatrick     Replacement = cast<Name>(this)->handleOperandChangeImpl(From, To);         \
327509467b48Spatrick     break;
327609467b48Spatrick #include "llvm/IR/Value.def"
327709467b48Spatrick   }
327809467b48Spatrick 
327909467b48Spatrick   // If handleOperandChangeImpl returned nullptr, then it handled
328009467b48Spatrick   // replacing itself and we don't want to delete or replace anything else here.
328109467b48Spatrick   if (!Replacement)
328209467b48Spatrick     return;
328309467b48Spatrick 
328409467b48Spatrick   // I do need to replace this with an existing value.
328509467b48Spatrick   assert(Replacement != this && "I didn't contain From!");
328609467b48Spatrick 
328709467b48Spatrick   // Everyone using this now uses the replacement.
328809467b48Spatrick   replaceAllUsesWith(Replacement);
328909467b48Spatrick 
329009467b48Spatrick   // Delete the old constant!
329109467b48Spatrick   destroyConstant();
329209467b48Spatrick }
329309467b48Spatrick 
handleOperandChangeImpl(Value * From,Value * To)329409467b48Spatrick Value *ConstantArray::handleOperandChangeImpl(Value *From, Value *To) {
329509467b48Spatrick   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
329609467b48Spatrick   Constant *ToC = cast<Constant>(To);
329709467b48Spatrick 
329809467b48Spatrick   SmallVector<Constant*, 8> Values;
329909467b48Spatrick   Values.reserve(getNumOperands());  // Build replacement array.
330009467b48Spatrick 
330109467b48Spatrick   // Fill values with the modified operands of the constant array.  Also,
330209467b48Spatrick   // compute whether this turns into an all-zeros array.
330309467b48Spatrick   unsigned NumUpdated = 0;
330409467b48Spatrick 
330509467b48Spatrick   // Keep track of whether all the values in the array are "ToC".
330609467b48Spatrick   bool AllSame = true;
330709467b48Spatrick   Use *OperandList = getOperandList();
330809467b48Spatrick   unsigned OperandNo = 0;
330909467b48Spatrick   for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
331009467b48Spatrick     Constant *Val = cast<Constant>(O->get());
331109467b48Spatrick     if (Val == From) {
331209467b48Spatrick       OperandNo = (O - OperandList);
331309467b48Spatrick       Val = ToC;
331409467b48Spatrick       ++NumUpdated;
331509467b48Spatrick     }
331609467b48Spatrick     Values.push_back(Val);
331709467b48Spatrick     AllSame &= Val == ToC;
331809467b48Spatrick   }
331909467b48Spatrick 
332009467b48Spatrick   if (AllSame && ToC->isNullValue())
332109467b48Spatrick     return ConstantAggregateZero::get(getType());
332209467b48Spatrick 
332309467b48Spatrick   if (AllSame && isa<UndefValue>(ToC))
332409467b48Spatrick     return UndefValue::get(getType());
332509467b48Spatrick 
332609467b48Spatrick   // Check for any other type of constant-folding.
332709467b48Spatrick   if (Constant *C = getImpl(getType(), Values))
332809467b48Spatrick     return C;
332909467b48Spatrick 
333009467b48Spatrick   // Update to the new value.
333109467b48Spatrick   return getContext().pImpl->ArrayConstants.replaceOperandsInPlace(
333209467b48Spatrick       Values, this, From, ToC, NumUpdated, OperandNo);
333309467b48Spatrick }
333409467b48Spatrick 
handleOperandChangeImpl(Value * From,Value * To)333509467b48Spatrick Value *ConstantStruct::handleOperandChangeImpl(Value *From, Value *To) {
333609467b48Spatrick   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
333709467b48Spatrick   Constant *ToC = cast<Constant>(To);
333809467b48Spatrick 
333909467b48Spatrick   Use *OperandList = getOperandList();
334009467b48Spatrick 
334109467b48Spatrick   SmallVector<Constant*, 8> Values;
334209467b48Spatrick   Values.reserve(getNumOperands());  // Build replacement struct.
334309467b48Spatrick 
334409467b48Spatrick   // Fill values with the modified operands of the constant struct.  Also,
334509467b48Spatrick   // compute whether this turns into an all-zeros struct.
334609467b48Spatrick   unsigned NumUpdated = 0;
334709467b48Spatrick   bool AllSame = true;
334809467b48Spatrick   unsigned OperandNo = 0;
334909467b48Spatrick   for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) {
335009467b48Spatrick     Constant *Val = cast<Constant>(O->get());
335109467b48Spatrick     if (Val == From) {
335209467b48Spatrick       OperandNo = (O - OperandList);
335309467b48Spatrick       Val = ToC;
335409467b48Spatrick       ++NumUpdated;
335509467b48Spatrick     }
335609467b48Spatrick     Values.push_back(Val);
335709467b48Spatrick     AllSame &= Val == ToC;
335809467b48Spatrick   }
335909467b48Spatrick 
336009467b48Spatrick   if (AllSame && ToC->isNullValue())
336109467b48Spatrick     return ConstantAggregateZero::get(getType());
336209467b48Spatrick 
336309467b48Spatrick   if (AllSame && isa<UndefValue>(ToC))
336409467b48Spatrick     return UndefValue::get(getType());
336509467b48Spatrick 
336609467b48Spatrick   // Update to the new value.
336709467b48Spatrick   return getContext().pImpl->StructConstants.replaceOperandsInPlace(
336809467b48Spatrick       Values, this, From, ToC, NumUpdated, OperandNo);
336909467b48Spatrick }
337009467b48Spatrick 
handleOperandChangeImpl(Value * From,Value * To)337109467b48Spatrick Value *ConstantVector::handleOperandChangeImpl(Value *From, Value *To) {
337209467b48Spatrick   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
337309467b48Spatrick   Constant *ToC = cast<Constant>(To);
337409467b48Spatrick 
337509467b48Spatrick   SmallVector<Constant*, 8> Values;
337609467b48Spatrick   Values.reserve(getNumOperands());  // Build replacement array...
337709467b48Spatrick   unsigned NumUpdated = 0;
337809467b48Spatrick   unsigned OperandNo = 0;
337909467b48Spatrick   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
338009467b48Spatrick     Constant *Val = getOperand(i);
338109467b48Spatrick     if (Val == From) {
338209467b48Spatrick       OperandNo = i;
338309467b48Spatrick       ++NumUpdated;
338409467b48Spatrick       Val = ToC;
338509467b48Spatrick     }
338609467b48Spatrick     Values.push_back(Val);
338709467b48Spatrick   }
338809467b48Spatrick 
338909467b48Spatrick   if (Constant *C = getImpl(Values))
339009467b48Spatrick     return C;
339109467b48Spatrick 
339209467b48Spatrick   // Update to the new value.
339309467b48Spatrick   return getContext().pImpl->VectorConstants.replaceOperandsInPlace(
339409467b48Spatrick       Values, this, From, ToC, NumUpdated, OperandNo);
339509467b48Spatrick }
339609467b48Spatrick 
handleOperandChangeImpl(Value * From,Value * ToV)339709467b48Spatrick Value *ConstantExpr::handleOperandChangeImpl(Value *From, Value *ToV) {
339809467b48Spatrick   assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
339909467b48Spatrick   Constant *To = cast<Constant>(ToV);
340009467b48Spatrick 
340109467b48Spatrick   SmallVector<Constant*, 8> NewOps;
340209467b48Spatrick   unsigned NumUpdated = 0;
340309467b48Spatrick   unsigned OperandNo = 0;
340409467b48Spatrick   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
340509467b48Spatrick     Constant *Op = getOperand(i);
340609467b48Spatrick     if (Op == From) {
340709467b48Spatrick       OperandNo = i;
340809467b48Spatrick       ++NumUpdated;
340909467b48Spatrick       Op = To;
341009467b48Spatrick     }
341109467b48Spatrick     NewOps.push_back(Op);
341209467b48Spatrick   }
341309467b48Spatrick   assert(NumUpdated && "I didn't contain From!");
341409467b48Spatrick 
341509467b48Spatrick   if (Constant *C = getWithOperands(NewOps, getType(), true))
341609467b48Spatrick     return C;
341709467b48Spatrick 
341809467b48Spatrick   // Update to the new value.
341909467b48Spatrick   return getContext().pImpl->ExprConstants.replaceOperandsInPlace(
342009467b48Spatrick       NewOps, this, From, To, NumUpdated, OperandNo);
342109467b48Spatrick }
342209467b48Spatrick 
getAsInstruction(Instruction * InsertBefore) const3423*d415bd75Srobert Instruction *ConstantExpr::getAsInstruction(Instruction *InsertBefore) const {
342473471bf0Spatrick   SmallVector<Value *, 4> ValueOperands(operands());
342509467b48Spatrick   ArrayRef<Value*> Ops(ValueOperands);
342609467b48Spatrick 
342709467b48Spatrick   switch (getOpcode()) {
342809467b48Spatrick   case Instruction::Trunc:
342909467b48Spatrick   case Instruction::ZExt:
343009467b48Spatrick   case Instruction::SExt:
343109467b48Spatrick   case Instruction::FPTrunc:
343209467b48Spatrick   case Instruction::FPExt:
343309467b48Spatrick   case Instruction::UIToFP:
343409467b48Spatrick   case Instruction::SIToFP:
343509467b48Spatrick   case Instruction::FPToUI:
343609467b48Spatrick   case Instruction::FPToSI:
343709467b48Spatrick   case Instruction::PtrToInt:
343809467b48Spatrick   case Instruction::IntToPtr:
343909467b48Spatrick   case Instruction::BitCast:
344009467b48Spatrick   case Instruction::AddrSpaceCast:
3441*d415bd75Srobert     return CastInst::Create((Instruction::CastOps)getOpcode(), Ops[0],
3442*d415bd75Srobert                             getType(), "", InsertBefore);
344309467b48Spatrick   case Instruction::Select:
3444*d415bd75Srobert     return SelectInst::Create(Ops[0], Ops[1], Ops[2], "", InsertBefore);
344509467b48Spatrick   case Instruction::InsertElement:
3446*d415bd75Srobert     return InsertElementInst::Create(Ops[0], Ops[1], Ops[2], "", InsertBefore);
344709467b48Spatrick   case Instruction::ExtractElement:
3448*d415bd75Srobert     return ExtractElementInst::Create(Ops[0], Ops[1], "", InsertBefore);
344909467b48Spatrick   case Instruction::ShuffleVector:
3450*d415bd75Srobert     return new ShuffleVectorInst(Ops[0], Ops[1], getShuffleMask(), "",
3451*d415bd75Srobert                                  InsertBefore);
345209467b48Spatrick 
345309467b48Spatrick   case Instruction::GetElementPtr: {
345409467b48Spatrick     const auto *GO = cast<GEPOperator>(this);
345509467b48Spatrick     if (GO->isInBounds())
3456*d415bd75Srobert       return GetElementPtrInst::CreateInBounds(
3457*d415bd75Srobert           GO->getSourceElementType(), Ops[0], Ops.slice(1), "", InsertBefore);
345809467b48Spatrick     return GetElementPtrInst::Create(GO->getSourceElementType(), Ops[0],
3459*d415bd75Srobert                                      Ops.slice(1), "", InsertBefore);
346009467b48Spatrick   }
346109467b48Spatrick   case Instruction::ICmp:
346209467b48Spatrick   case Instruction::FCmp:
346309467b48Spatrick     return CmpInst::Create((Instruction::OtherOps)getOpcode(),
3464*d415bd75Srobert                            (CmpInst::Predicate)getPredicate(), Ops[0], Ops[1],
3465*d415bd75Srobert                            "", InsertBefore);
346609467b48Spatrick   default:
346709467b48Spatrick     assert(getNumOperands() == 2 && "Must be binary operator?");
3468*d415bd75Srobert     BinaryOperator *BO = BinaryOperator::Create(
3469*d415bd75Srobert         (Instruction::BinaryOps)getOpcode(), Ops[0], Ops[1], "", InsertBefore);
347009467b48Spatrick     if (isa<OverflowingBinaryOperator>(BO)) {
347109467b48Spatrick       BO->setHasNoUnsignedWrap(SubclassOptionalData &
347209467b48Spatrick                                OverflowingBinaryOperator::NoUnsignedWrap);
347309467b48Spatrick       BO->setHasNoSignedWrap(SubclassOptionalData &
347409467b48Spatrick                              OverflowingBinaryOperator::NoSignedWrap);
347509467b48Spatrick     }
347609467b48Spatrick     if (isa<PossiblyExactOperator>(BO))
347709467b48Spatrick       BO->setIsExact(SubclassOptionalData & PossiblyExactOperator::IsExact);
347809467b48Spatrick     return BO;
347909467b48Spatrick   }
348009467b48Spatrick }
3481