1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Constant* classes.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/IR/Constants.h"
15 #include "ConstantFold.h"
16 #include "LLVMContextImpl.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/GetElementPtrTypeIterator.h"
23 #include "llvm/IR/GlobalValue.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/IR/Operator.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/ManagedStatic.h"
30 #include "llvm/Support/MathExtras.h"
31 #include "llvm/Support/raw_ostream.h"
36 //===----------------------------------------------------------------------===//
38 //===----------------------------------------------------------------------===//
40 bool Constant::isNegativeZeroValue() const {
41 // Floating point values have an explicit -0.0 value.
42 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
43 return CFP->isZero() && CFP->isNegative();
45 // Equivalent for a vector of -0.0's.
46 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
47 if (CV->getElementType()->isFloatingPointTy() && CV->isSplat())
48 if (CV->getElementAsAPFloat(0).isNegZero())
51 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
52 if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
53 if (SplatCFP && SplatCFP->isZero() && SplatCFP->isNegative())
56 // We've already handled true FP case; any other FP vectors can't represent -0.0.
57 if (getType()->isFPOrFPVectorTy())
60 // Otherwise, just use +0.0.
64 // Return true iff this constant is positive zero (floating point), negative
65 // zero (floating point), or a null value.
66 bool Constant::isZeroValue() const {
67 // Floating point values have an explicit -0.0 value.
68 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
71 // Equivalent for a vector of -0.0's.
72 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
73 if (CV->getElementType()->isFloatingPointTy() && CV->isSplat())
74 if (CV->getElementAsAPFloat(0).isZero())
77 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
78 if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
79 if (SplatCFP && SplatCFP->isZero())
82 // Otherwise, just use +0.0.
86 bool Constant::isNullValue() const {
88 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
92 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
93 return CFP->isZero() && !CFP->isNegative();
95 // constant zero is zero for aggregates, cpnull is null for pointers, none for
97 return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this) ||
98 isa<ConstantTokenNone>(this);
101 bool Constant::isAllOnesValue() const {
102 // Check for -1 integers
103 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
104 return CI->isMinusOne();
106 // Check for FP which are bitcasted from -1 integers
107 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
108 return CFP->getValueAPF().bitcastToAPInt().isAllOnesValue();
110 // Check for constant vectors which are splats of -1 values.
111 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
112 if (Constant *Splat = CV->getSplatValue())
113 return Splat->isAllOnesValue();
115 // Check for constant vectors which are splats of -1 values.
116 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) {
118 if (CV->getElementType()->isFloatingPointTy())
119 return CV->getElementAsAPFloat(0).bitcastToAPInt().isAllOnesValue();
120 return CV->getElementAsAPInt(0).isAllOnesValue();
127 bool Constant::isOneValue() const {
128 // Check for 1 integers
129 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
132 // Check for FP which are bitcasted from 1 integers
133 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
134 return CFP->getValueAPF().bitcastToAPInt().isOneValue();
136 // Check for constant vectors which are splats of 1 values.
137 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
138 if (Constant *Splat = CV->getSplatValue())
139 return Splat->isOneValue();
141 // Check for constant vectors which are splats of 1 values.
142 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) {
144 if (CV->getElementType()->isFloatingPointTy())
145 return CV->getElementAsAPFloat(0).bitcastToAPInt().isOneValue();
146 return CV->getElementAsAPInt(0).isOneValue();
153 bool Constant::isMinSignedValue() const {
154 // Check for INT_MIN integers
155 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
156 return CI->isMinValue(/*isSigned=*/true);
158 // Check for FP which are bitcasted from INT_MIN integers
159 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
160 return CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
162 // Check for constant vectors which are splats of INT_MIN values.
163 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
164 if (Constant *Splat = CV->getSplatValue())
165 return Splat->isMinSignedValue();
167 // Check for constant vectors which are splats of INT_MIN values.
168 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) {
170 if (CV->getElementType()->isFloatingPointTy())
171 return CV->getElementAsAPFloat(0).bitcastToAPInt().isMinSignedValue();
172 return CV->getElementAsAPInt(0).isMinSignedValue();
179 bool Constant::isNotMinSignedValue() const {
180 // Check for INT_MIN integers
181 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
182 return !CI->isMinValue(/*isSigned=*/true);
184 // Check for FP which are bitcasted from INT_MIN integers
185 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
186 return !CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
188 // Check for constant vectors which are splats of INT_MIN values.
189 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
190 if (Constant *Splat = CV->getSplatValue())
191 return Splat->isNotMinSignedValue();
193 // Check for constant vectors which are splats of INT_MIN values.
194 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) {
196 if (CV->getElementType()->isFloatingPointTy())
197 return !CV->getElementAsAPFloat(0).bitcastToAPInt().isMinSignedValue();
198 return !CV->getElementAsAPInt(0).isMinSignedValue();
202 // It *may* contain INT_MIN, we can't tell.
206 /// Constructor to create a '0' constant of arbitrary type.
207 Constant *Constant::getNullValue(Type *Ty) {
208 switch (Ty->getTypeID()) {
209 case Type::IntegerTyID:
210 return ConstantInt::get(Ty, 0);
212 return ConstantFP::get(Ty->getContext(),
213 APFloat::getZero(APFloat::IEEEhalf()));
214 case Type::FloatTyID:
215 return ConstantFP::get(Ty->getContext(),
216 APFloat::getZero(APFloat::IEEEsingle()));
217 case Type::DoubleTyID:
218 return ConstantFP::get(Ty->getContext(),
219 APFloat::getZero(APFloat::IEEEdouble()));
220 case Type::X86_FP80TyID:
221 return ConstantFP::get(Ty->getContext(),
222 APFloat::getZero(APFloat::x87DoubleExtended()));
223 case Type::FP128TyID:
224 return ConstantFP::get(Ty->getContext(),
225 APFloat::getZero(APFloat::IEEEquad()));
226 case Type::PPC_FP128TyID:
227 return ConstantFP::get(Ty->getContext(),
228 APFloat(APFloat::PPCDoubleDouble(),
229 APInt::getNullValue(128)));
230 case Type::PointerTyID:
231 return ConstantPointerNull::get(cast<PointerType>(Ty));
232 case Type::StructTyID:
233 case Type::ArrayTyID:
234 case Type::VectorTyID:
235 return ConstantAggregateZero::get(Ty);
236 case Type::TokenTyID:
237 return ConstantTokenNone::get(Ty->getContext());
239 // Function, Label, or Opaque type?
240 llvm_unreachable("Cannot create a null constant of that type!");
244 Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) {
245 Type *ScalarTy = Ty->getScalarType();
247 // Create the base integer constant.
248 Constant *C = ConstantInt::get(Ty->getContext(), V);
250 // Convert an integer to a pointer, if necessary.
251 if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
252 C = ConstantExpr::getIntToPtr(C, PTy);
254 // Broadcast a scalar to a vector, if necessary.
255 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
256 C = ConstantVector::getSplat(VTy->getNumElements(), C);
261 Constant *Constant::getAllOnesValue(Type *Ty) {
262 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
263 return ConstantInt::get(Ty->getContext(),
264 APInt::getAllOnesValue(ITy->getBitWidth()));
266 if (Ty->isFloatingPointTy()) {
267 APFloat FL = APFloat::getAllOnesValue(Ty->getPrimitiveSizeInBits(),
268 !Ty->isPPC_FP128Ty());
269 return ConstantFP::get(Ty->getContext(), FL);
272 VectorType *VTy = cast<VectorType>(Ty);
273 return ConstantVector::getSplat(VTy->getNumElements(),
274 getAllOnesValue(VTy->getElementType()));
277 Constant *Constant::getAggregateElement(unsigned Elt) const {
278 if (const ConstantAggregate *CC = dyn_cast<ConstantAggregate>(this))
279 return Elt < CC->getNumOperands() ? CC->getOperand(Elt) : nullptr;
281 if (const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(this))
282 return Elt < CAZ->getNumElements() ? CAZ->getElementValue(Elt) : nullptr;
284 if (const UndefValue *UV = dyn_cast<UndefValue>(this))
285 return Elt < UV->getNumElements() ? UV->getElementValue(Elt) : nullptr;
287 if (const ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(this))
288 return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt)
293 Constant *Constant::getAggregateElement(Constant *Elt) const {
294 assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
295 if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt))
296 return getAggregateElement(CI->getZExtValue());
300 void Constant::destroyConstant() {
301 /// First call destroyConstantImpl on the subclass. This gives the subclass
302 /// a chance to remove the constant from any maps/pools it's contained in.
303 switch (getValueID()) {
305 llvm_unreachable("Not a constant!");
306 #define HANDLE_CONSTANT(Name) \
307 case Value::Name##Val: \
308 cast<Name>(this)->destroyConstantImpl(); \
310 #include "llvm/IR/Value.def"
313 // When a Constant is destroyed, there may be lingering
314 // references to the constant by other constants in the constant pool. These
315 // constants are implicitly dependent on the module that is being deleted,
316 // but they don't know that. Because we only find out when the CPV is
317 // deleted, we must now notify all of our users (that should only be
318 // Constants) that they are, in fact, invalid now and should be deleted.
320 while (!use_empty()) {
321 Value *V = user_back();
322 #ifndef NDEBUG // Only in -g mode...
323 if (!isa<Constant>(V)) {
324 dbgs() << "While deleting: " << *this
325 << "\n\nUse still stuck around after Def is destroyed: " << *V
329 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
330 cast<Constant>(V)->destroyConstant();
332 // The constant should remove itself from our use list...
333 assert((use_empty() || user_back() != V) && "Constant not removed!");
336 // Value has no outstanding references it is safe to delete it now...
340 static bool canTrapImpl(const Constant *C,
341 SmallPtrSetImpl<const ConstantExpr *> &NonTrappingOps) {
342 assert(C->getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
343 // The only thing that could possibly trap are constant exprs.
344 const ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
348 // ConstantExpr traps if any operands can trap.
349 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
350 if (ConstantExpr *Op = dyn_cast<ConstantExpr>(CE->getOperand(i))) {
351 if (NonTrappingOps.insert(Op).second && canTrapImpl(Op, NonTrappingOps))
356 // Otherwise, only specific operations can trap.
357 switch (CE->getOpcode()) {
360 case Instruction::UDiv:
361 case Instruction::SDiv:
362 case Instruction::URem:
363 case Instruction::SRem:
364 // Div and rem can trap if the RHS is not known to be non-zero.
365 if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
371 bool Constant::canTrap() const {
372 SmallPtrSet<const ConstantExpr *, 4> NonTrappingOps;
373 return canTrapImpl(this, NonTrappingOps);
376 /// Check if C contains a GlobalValue for which Predicate is true.
378 ConstHasGlobalValuePredicate(const Constant *C,
379 bool (*Predicate)(const GlobalValue *)) {
380 SmallPtrSet<const Constant *, 8> Visited;
381 SmallVector<const Constant *, 8> WorkList;
382 WorkList.push_back(C);
385 while (!WorkList.empty()) {
386 const Constant *WorkItem = WorkList.pop_back_val();
387 if (const auto *GV = dyn_cast<GlobalValue>(WorkItem))
390 for (const Value *Op : WorkItem->operands()) {
391 const Constant *ConstOp = dyn_cast<Constant>(Op);
394 if (Visited.insert(ConstOp).second)
395 WorkList.push_back(ConstOp);
401 bool Constant::isThreadDependent() const {
402 auto DLLImportPredicate = [](const GlobalValue *GV) {
403 return GV->isThreadLocal();
405 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
408 bool Constant::isDLLImportDependent() const {
409 auto DLLImportPredicate = [](const GlobalValue *GV) {
410 return GV->hasDLLImportStorageClass();
412 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
415 bool Constant::isConstantUsed() const {
416 for (const User *U : users()) {
417 const Constant *UC = dyn_cast<Constant>(U);
418 if (!UC || isa<GlobalValue>(UC))
421 if (UC->isConstantUsed())
427 bool Constant::needsRelocation() const {
428 if (isa<GlobalValue>(this))
429 return true; // Global reference.
431 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
432 return BA->getFunction()->needsRelocation();
434 // While raw uses of blockaddress need to be relocated, differences between
435 // two of them don't when they are for labels in the same function. This is a
436 // common idiom when creating a table for the indirect goto extension, so we
437 // handle it efficiently here.
438 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this))
439 if (CE->getOpcode() == Instruction::Sub) {
440 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
441 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
442 if (LHS && RHS && LHS->getOpcode() == Instruction::PtrToInt &&
443 RHS->getOpcode() == Instruction::PtrToInt &&
444 isa<BlockAddress>(LHS->getOperand(0)) &&
445 isa<BlockAddress>(RHS->getOperand(0)) &&
446 cast<BlockAddress>(LHS->getOperand(0))->getFunction() ==
447 cast<BlockAddress>(RHS->getOperand(0))->getFunction())
452 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
453 Result |= cast<Constant>(getOperand(i))->needsRelocation();
458 /// If the specified constantexpr is dead, remove it. This involves recursively
459 /// eliminating any dead users of the constantexpr.
460 static bool removeDeadUsersOfConstant(const Constant *C) {
461 if (isa<GlobalValue>(C)) return false; // Cannot remove this
463 while (!C->use_empty()) {
464 const Constant *User = dyn_cast<Constant>(C->user_back());
465 if (!User) return false; // Non-constant usage;
466 if (!removeDeadUsersOfConstant(User))
467 return false; // Constant wasn't dead
470 const_cast<Constant*>(C)->destroyConstant();
475 void Constant::removeDeadConstantUsers() const {
476 Value::const_user_iterator I = user_begin(), E = user_end();
477 Value::const_user_iterator LastNonDeadUser = E;
479 const Constant *User = dyn_cast<Constant>(*I);
486 if (!removeDeadUsersOfConstant(User)) {
487 // If the constant wasn't dead, remember that this was the last live use
488 // and move on to the next constant.
494 // If the constant was dead, then the iterator is invalidated.
495 if (LastNonDeadUser == E) {
507 //===----------------------------------------------------------------------===//
509 //===----------------------------------------------------------------------===//
511 ConstantInt::ConstantInt(IntegerType *Ty, const APInt &V)
512 : ConstantData(Ty, ConstantIntVal), Val(V) {
513 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
516 ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
517 LLVMContextImpl *pImpl = Context.pImpl;
518 if (!pImpl->TheTrueVal)
519 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
520 return pImpl->TheTrueVal;
523 ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
524 LLVMContextImpl *pImpl = Context.pImpl;
525 if (!pImpl->TheFalseVal)
526 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
527 return pImpl->TheFalseVal;
530 Constant *ConstantInt::getTrue(Type *Ty) {
531 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
532 ConstantInt *TrueC = ConstantInt::getTrue(Ty->getContext());
533 if (auto *VTy = dyn_cast<VectorType>(Ty))
534 return ConstantVector::getSplat(VTy->getNumElements(), TrueC);
538 Constant *ConstantInt::getFalse(Type *Ty) {
539 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
540 ConstantInt *FalseC = ConstantInt::getFalse(Ty->getContext());
541 if (auto *VTy = dyn_cast<VectorType>(Ty))
542 return ConstantVector::getSplat(VTy->getNumElements(), FalseC);
546 // Get a ConstantInt from an APInt.
547 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
548 // get an existing value or the insertion position
549 LLVMContextImpl *pImpl = Context.pImpl;
550 std::unique_ptr<ConstantInt> &Slot = pImpl->IntConstants[V];
552 // Get the corresponding integer type for the bit width of the value.
553 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
554 Slot.reset(new ConstantInt(ITy, V));
556 assert(Slot->getType() == IntegerType::get(Context, V.getBitWidth()));
560 Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
561 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
563 // For vectors, broadcast the value.
564 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
565 return ConstantVector::getSplat(VTy->getNumElements(), C);
570 ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V, bool isSigned) {
571 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
574 ConstantInt *ConstantInt::getSigned(IntegerType *Ty, int64_t V) {
575 return get(Ty, V, true);
578 Constant *ConstantInt::getSigned(Type *Ty, int64_t V) {
579 return get(Ty, V, true);
582 Constant *ConstantInt::get(Type *Ty, const APInt& V) {
583 ConstantInt *C = get(Ty->getContext(), V);
584 assert(C->getType() == Ty->getScalarType() &&
585 "ConstantInt type doesn't match the type implied by its value!");
587 // For vectors, broadcast the value.
588 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
589 return ConstantVector::getSplat(VTy->getNumElements(), C);
594 ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str, uint8_t radix) {
595 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
598 /// Remove the constant from the constant table.
599 void ConstantInt::destroyConstantImpl() {
600 llvm_unreachable("You can't ConstantInt->destroyConstantImpl()!");
603 //===----------------------------------------------------------------------===//
605 //===----------------------------------------------------------------------===//
607 static const fltSemantics *TypeToFloatSemantics(Type *Ty) {
609 return &APFloat::IEEEhalf();
611 return &APFloat::IEEEsingle();
612 if (Ty->isDoubleTy())
613 return &APFloat::IEEEdouble();
614 if (Ty->isX86_FP80Ty())
615 return &APFloat::x87DoubleExtended();
616 else if (Ty->isFP128Ty())
617 return &APFloat::IEEEquad();
619 assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
620 return &APFloat::PPCDoubleDouble();
623 Constant *ConstantFP::get(Type *Ty, double V) {
624 LLVMContext &Context = Ty->getContext();
628 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
629 APFloat::rmNearestTiesToEven, &ignored);
630 Constant *C = get(Context, FV);
632 // For vectors, broadcast the value.
633 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
634 return ConstantVector::getSplat(VTy->getNumElements(), C);
640 Constant *ConstantFP::get(Type *Ty, StringRef Str) {
641 LLVMContext &Context = Ty->getContext();
643 APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
644 Constant *C = get(Context, FV);
646 // For vectors, broadcast the value.
647 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
648 return ConstantVector::getSplat(VTy->getNumElements(), C);
653 Constant *ConstantFP::getNaN(Type *Ty, bool Negative, unsigned Type) {
654 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
655 APFloat NaN = APFloat::getNaN(Semantics, Negative, Type);
656 Constant *C = get(Ty->getContext(), NaN);
658 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
659 return ConstantVector::getSplat(VTy->getNumElements(), C);
664 Constant *ConstantFP::getNegativeZero(Type *Ty) {
665 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
666 APFloat NegZero = APFloat::getZero(Semantics, /*Negative=*/true);
667 Constant *C = get(Ty->getContext(), NegZero);
669 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
670 return ConstantVector::getSplat(VTy->getNumElements(), C);
676 Constant *ConstantFP::getZeroValueForNegation(Type *Ty) {
677 if (Ty->isFPOrFPVectorTy())
678 return getNegativeZero(Ty);
680 return Constant::getNullValue(Ty);
684 // ConstantFP accessors.
685 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
686 LLVMContextImpl* pImpl = Context.pImpl;
688 std::unique_ptr<ConstantFP> &Slot = pImpl->FPConstants[V];
692 if (&V.getSemantics() == &APFloat::IEEEhalf())
693 Ty = Type::getHalfTy(Context);
694 else if (&V.getSemantics() == &APFloat::IEEEsingle())
695 Ty = Type::getFloatTy(Context);
696 else if (&V.getSemantics() == &APFloat::IEEEdouble())
697 Ty = Type::getDoubleTy(Context);
698 else if (&V.getSemantics() == &APFloat::x87DoubleExtended())
699 Ty = Type::getX86_FP80Ty(Context);
700 else if (&V.getSemantics() == &APFloat::IEEEquad())
701 Ty = Type::getFP128Ty(Context);
703 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble() &&
704 "Unknown FP format");
705 Ty = Type::getPPC_FP128Ty(Context);
707 Slot.reset(new ConstantFP(Ty, V));
713 Constant *ConstantFP::getInfinity(Type *Ty, bool Negative) {
714 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
715 Constant *C = get(Ty->getContext(), APFloat::getInf(Semantics, Negative));
717 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
718 return ConstantVector::getSplat(VTy->getNumElements(), C);
723 ConstantFP::ConstantFP(Type *Ty, const APFloat &V)
724 : ConstantData(Ty, ConstantFPVal), Val(V) {
725 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
729 bool ConstantFP::isExactlyValue(const APFloat &V) const {
730 return Val.bitwiseIsEqual(V);
733 /// Remove the constant from the constant table.
734 void ConstantFP::destroyConstantImpl() {
735 llvm_unreachable("You can't ConstantFP->destroyConstantImpl()!");
738 //===----------------------------------------------------------------------===//
739 // ConstantAggregateZero Implementation
740 //===----------------------------------------------------------------------===//
742 Constant *ConstantAggregateZero::getSequentialElement() const {
743 return Constant::getNullValue(getType()->getSequentialElementType());
746 Constant *ConstantAggregateZero::getStructElement(unsigned Elt) const {
747 return Constant::getNullValue(getType()->getStructElementType(Elt));
750 Constant *ConstantAggregateZero::getElementValue(Constant *C) const {
751 if (isa<SequentialType>(getType()))
752 return getSequentialElement();
753 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
756 Constant *ConstantAggregateZero::getElementValue(unsigned Idx) const {
757 if (isa<SequentialType>(getType()))
758 return getSequentialElement();
759 return getStructElement(Idx);
762 unsigned ConstantAggregateZero::getNumElements() const {
763 Type *Ty = getType();
764 if (auto *AT = dyn_cast<ArrayType>(Ty))
765 return AT->getNumElements();
766 if (auto *VT = dyn_cast<VectorType>(Ty))
767 return VT->getNumElements();
768 return Ty->getStructNumElements();
771 //===----------------------------------------------------------------------===//
772 // UndefValue Implementation
773 //===----------------------------------------------------------------------===//
775 UndefValue *UndefValue::getSequentialElement() const {
776 return UndefValue::get(getType()->getSequentialElementType());
779 UndefValue *UndefValue::getStructElement(unsigned Elt) const {
780 return UndefValue::get(getType()->getStructElementType(Elt));
783 UndefValue *UndefValue::getElementValue(Constant *C) const {
784 if (isa<SequentialType>(getType()))
785 return getSequentialElement();
786 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
789 UndefValue *UndefValue::getElementValue(unsigned Idx) const {
790 if (isa<SequentialType>(getType()))
791 return getSequentialElement();
792 return getStructElement(Idx);
795 unsigned UndefValue::getNumElements() const {
796 Type *Ty = getType();
797 if (auto *ST = dyn_cast<SequentialType>(Ty))
798 return ST->getNumElements();
799 return Ty->getStructNumElements();
802 //===----------------------------------------------------------------------===//
803 // ConstantXXX Classes
804 //===----------------------------------------------------------------------===//
806 template <typename ItTy, typename EltTy>
807 static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
808 for (; Start != End; ++Start)
814 template <typename SequentialTy, typename ElementTy>
815 static Constant *getIntSequenceIfElementsMatch(ArrayRef<Constant *> V) {
816 assert(!V.empty() && "Cannot get empty int sequence.");
818 SmallVector<ElementTy, 16> Elts;
819 for (Constant *C : V)
820 if (auto *CI = dyn_cast<ConstantInt>(C))
821 Elts.push_back(CI->getZExtValue());
824 return SequentialTy::get(V[0]->getContext(), Elts);
827 template <typename SequentialTy, typename ElementTy>
828 static Constant *getFPSequenceIfElementsMatch(ArrayRef<Constant *> V) {
829 assert(!V.empty() && "Cannot get empty FP sequence.");
831 SmallVector<ElementTy, 16> Elts;
832 for (Constant *C : V)
833 if (auto *CFP = dyn_cast<ConstantFP>(C))
834 Elts.push_back(CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
837 return SequentialTy::getFP(V[0]->getContext(), Elts);
840 template <typename SequenceTy>
841 static Constant *getSequenceIfElementsMatch(Constant *C,
842 ArrayRef<Constant *> V) {
843 // We speculatively build the elements here even if it turns out that there is
844 // a constantexpr or something else weird, since it is so uncommon for that to
846 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
847 if (CI->getType()->isIntegerTy(8))
848 return getIntSequenceIfElementsMatch<SequenceTy, uint8_t>(V);
849 else if (CI->getType()->isIntegerTy(16))
850 return getIntSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
851 else if (CI->getType()->isIntegerTy(32))
852 return getIntSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
853 else if (CI->getType()->isIntegerTy(64))
854 return getIntSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
855 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
856 if (CFP->getType()->isHalfTy())
857 return getFPSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
858 else if (CFP->getType()->isFloatTy())
859 return getFPSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
860 else if (CFP->getType()->isDoubleTy())
861 return getFPSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
867 ConstantAggregate::ConstantAggregate(CompositeType *T, ValueTy VT,
868 ArrayRef<Constant *> V)
869 : Constant(T, VT, OperandTraits<ConstantAggregate>::op_end(this) - V.size(),
871 std::copy(V.begin(), V.end(), op_begin());
873 // Check that types match, unless this is an opaque struct.
874 if (auto *ST = dyn_cast<StructType>(T))
877 for (unsigned I = 0, E = V.size(); I != E; ++I)
878 assert(V[I]->getType() == T->getTypeAtIndex(I) &&
879 "Initializer for composite element doesn't match!");
882 ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
883 : ConstantAggregate(T, ConstantArrayVal, V) {
884 assert(V.size() == T->getNumElements() &&
885 "Invalid initializer for constant array");
888 Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
889 if (Constant *C = getImpl(Ty, V))
891 return Ty->getContext().pImpl->ArrayConstants.getOrCreate(Ty, V);
894 Constant *ConstantArray::getImpl(ArrayType *Ty, ArrayRef<Constant*> V) {
895 // Empty arrays are canonicalized to ConstantAggregateZero.
897 return ConstantAggregateZero::get(Ty);
899 for (unsigned i = 0, e = V.size(); i != e; ++i) {
900 assert(V[i]->getType() == Ty->getElementType() &&
901 "Wrong type in array element initializer");
904 // If this is an all-zero array, return a ConstantAggregateZero object. If
905 // all undef, return an UndefValue, if "all simple", then return a
906 // ConstantDataArray.
908 if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
909 return UndefValue::get(Ty);
911 if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
912 return ConstantAggregateZero::get(Ty);
914 // Check to see if all of the elements are ConstantFP or ConstantInt and if
915 // the element type is compatible with ConstantDataVector. If so, use it.
916 if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
917 return getSequenceIfElementsMatch<ConstantDataArray>(C, V);
919 // Otherwise, we really do want to create a ConstantArray.
923 StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
924 ArrayRef<Constant*> V,
926 unsigned VecSize = V.size();
927 SmallVector<Type*, 16> EltTypes(VecSize);
928 for (unsigned i = 0; i != VecSize; ++i)
929 EltTypes[i] = V[i]->getType();
931 return StructType::get(Context, EltTypes, Packed);
935 StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
938 "ConstantStruct::getTypeForElements cannot be called on empty list");
939 return getTypeForElements(V[0]->getContext(), V, Packed);
942 ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
943 : ConstantAggregate(T, ConstantStructVal, V) {
944 assert((T->isOpaque() || V.size() == T->getNumElements()) &&
945 "Invalid initializer for constant struct");
948 // ConstantStruct accessors.
949 Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
950 assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
951 "Incorrect # elements specified to ConstantStruct::get");
953 // Create a ConstantAggregateZero value if all elements are zeros.
955 bool isUndef = false;
958 isUndef = isa<UndefValue>(V[0]);
959 isZero = V[0]->isNullValue();
960 if (isUndef || isZero) {
961 for (unsigned i = 0, e = V.size(); i != e; ++i) {
962 if (!V[i]->isNullValue())
964 if (!isa<UndefValue>(V[i]))
970 return ConstantAggregateZero::get(ST);
972 return UndefValue::get(ST);
974 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
977 ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
978 : ConstantAggregate(T, ConstantVectorVal, V) {
979 assert(V.size() == T->getNumElements() &&
980 "Invalid initializer for constant vector");
983 // ConstantVector accessors.
984 Constant *ConstantVector::get(ArrayRef<Constant*> V) {
985 if (Constant *C = getImpl(V))
987 VectorType *Ty = VectorType::get(V.front()->getType(), V.size());
988 return Ty->getContext().pImpl->VectorConstants.getOrCreate(Ty, V);
991 Constant *ConstantVector::getImpl(ArrayRef<Constant*> V) {
992 assert(!V.empty() && "Vectors can't be empty");
993 VectorType *T = VectorType::get(V.front()->getType(), V.size());
995 // If this is an all-undef or all-zero vector, return a
996 // ConstantAggregateZero or UndefValue.
998 bool isZero = C->isNullValue();
999 bool isUndef = isa<UndefValue>(C);
1001 if (isZero || isUndef) {
1002 for (unsigned i = 1, e = V.size(); i != e; ++i)
1004 isZero = isUndef = false;
1010 return ConstantAggregateZero::get(T);
1012 return UndefValue::get(T);
1014 // Check to see if all of the elements are ConstantFP or ConstantInt and if
1015 // the element type is compatible with ConstantDataVector. If so, use it.
1016 if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
1017 return getSequenceIfElementsMatch<ConstantDataVector>(C, V);
1019 // Otherwise, the element type isn't compatible with ConstantDataVector, or
1020 // the operand list contains a ConstantExpr or something else strange.
1024 Constant *ConstantVector::getSplat(unsigned NumElts, Constant *V) {
1025 // If this splat is compatible with ConstantDataVector, use it instead of
1027 if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&
1028 ConstantDataSequential::isElementTypeCompatible(V->getType()))
1029 return ConstantDataVector::getSplat(NumElts, V);
1031 SmallVector<Constant*, 32> Elts(NumElts, V);
1035 ConstantTokenNone *ConstantTokenNone::get(LLVMContext &Context) {
1036 LLVMContextImpl *pImpl = Context.pImpl;
1037 if (!pImpl->TheNoneToken)
1038 pImpl->TheNoneToken.reset(new ConstantTokenNone(Context));
1039 return pImpl->TheNoneToken.get();
1042 /// Remove the constant from the constant table.
1043 void ConstantTokenNone::destroyConstantImpl() {
1044 llvm_unreachable("You can't ConstantTokenNone->destroyConstantImpl()!");
1047 // Utility function for determining if a ConstantExpr is a CastOp or not. This
1048 // can't be inline because we don't want to #include Instruction.h into
1050 bool ConstantExpr::isCast() const {
1051 return Instruction::isCast(getOpcode());
1054 bool ConstantExpr::isCompare() const {
1055 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
1058 bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
1059 if (getOpcode() != Instruction::GetElementPtr) return false;
1061 gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
1062 User::const_op_iterator OI = std::next(this->op_begin());
1064 // The remaining indices may be compile-time known integers within the bounds
1065 // of the corresponding notional static array types.
1066 for (; GEPI != E; ++GEPI, ++OI) {
1067 if (isa<UndefValue>(*OI))
1069 auto *CI = dyn_cast<ConstantInt>(*OI);
1070 if (!CI || (GEPI.isBoundedSequential() &&
1071 (CI->getValue().getActiveBits() > 64 ||
1072 CI->getZExtValue() >= GEPI.getSequentialNumElements())))
1076 // All the indices checked out.
1080 bool ConstantExpr::hasIndices() const {
1081 return getOpcode() == Instruction::ExtractValue ||
1082 getOpcode() == Instruction::InsertValue;
1085 ArrayRef<unsigned> ConstantExpr::getIndices() const {
1086 if (const ExtractValueConstantExpr *EVCE =
1087 dyn_cast<ExtractValueConstantExpr>(this))
1088 return EVCE->Indices;
1090 return cast<InsertValueConstantExpr>(this)->Indices;
1093 unsigned ConstantExpr::getPredicate() const {
1094 return cast<CompareConstantExpr>(this)->predicate;
1098 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
1099 assert(Op->getType() == getOperand(OpNo)->getType() &&
1100 "Replacing operand with value of different type!");
1101 if (getOperand(OpNo) == Op)
1102 return const_cast<ConstantExpr*>(this);
1104 SmallVector<Constant*, 8> NewOps;
1105 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1106 NewOps.push_back(i == OpNo ? Op : getOperand(i));
1108 return getWithOperands(NewOps);
1111 Constant *ConstantExpr::getWithOperands(ArrayRef<Constant *> Ops, Type *Ty,
1112 bool OnlyIfReduced, Type *SrcTy) const {
1113 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
1115 // If no operands changed return self.
1116 if (Ty == getType() && std::equal(Ops.begin(), Ops.end(), op_begin()))
1117 return const_cast<ConstantExpr*>(this);
1119 Type *OnlyIfReducedTy = OnlyIfReduced ? Ty : nullptr;
1120 switch (getOpcode()) {
1121 case Instruction::Trunc:
1122 case Instruction::ZExt:
1123 case Instruction::SExt:
1124 case Instruction::FPTrunc:
1125 case Instruction::FPExt:
1126 case Instruction::UIToFP:
1127 case Instruction::SIToFP:
1128 case Instruction::FPToUI:
1129 case Instruction::FPToSI:
1130 case Instruction::PtrToInt:
1131 case Instruction::IntToPtr:
1132 case Instruction::BitCast:
1133 case Instruction::AddrSpaceCast:
1134 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty, OnlyIfReduced);
1135 case Instruction::Select:
1136 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2], OnlyIfReducedTy);
1137 case Instruction::InsertElement:
1138 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2],
1140 case Instruction::ExtractElement:
1141 return ConstantExpr::getExtractElement(Ops[0], Ops[1], OnlyIfReducedTy);
1142 case Instruction::InsertValue:
1143 return ConstantExpr::getInsertValue(Ops[0], Ops[1], getIndices(),
1145 case Instruction::ExtractValue:
1146 return ConstantExpr::getExtractValue(Ops[0], getIndices(), OnlyIfReducedTy);
1147 case Instruction::ShuffleVector:
1148 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2],
1150 case Instruction::GetElementPtr: {
1151 auto *GEPO = cast<GEPOperator>(this);
1152 assert(SrcTy || (Ops[0]->getType() == getOperand(0)->getType()));
1153 return ConstantExpr::getGetElementPtr(
1154 SrcTy ? SrcTy : GEPO->getSourceElementType(), Ops[0], Ops.slice(1),
1155 GEPO->isInBounds(), GEPO->getInRangeIndex(), OnlyIfReducedTy);
1157 case Instruction::ICmp:
1158 case Instruction::FCmp:
1159 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1],
1162 assert(getNumOperands() == 2 && "Must be binary operator?");
1163 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData,
1169 //===----------------------------------------------------------------------===//
1170 // isValueValidForType implementations
1172 bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
1173 unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
1174 if (Ty->isIntegerTy(1))
1175 return Val == 0 || Val == 1;
1176 return isUIntN(NumBits, Val);
1179 bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
1180 unsigned NumBits = Ty->getIntegerBitWidth();
1181 if (Ty->isIntegerTy(1))
1182 return Val == 0 || Val == 1 || Val == -1;
1183 return isIntN(NumBits, Val);
1186 bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {
1187 // convert modifies in place, so make a copy.
1188 APFloat Val2 = APFloat(Val);
1190 switch (Ty->getTypeID()) {
1192 return false; // These can't be represented as floating point!
1194 // FIXME rounding mode needs to be more flexible
1195 case Type::HalfTyID: {
1196 if (&Val2.getSemantics() == &APFloat::IEEEhalf())
1198 Val2.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &losesInfo);
1201 case Type::FloatTyID: {
1202 if (&Val2.getSemantics() == &APFloat::IEEEsingle())
1204 Val2.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &losesInfo);
1207 case Type::DoubleTyID: {
1208 if (&Val2.getSemantics() == &APFloat::IEEEhalf() ||
1209 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1210 &Val2.getSemantics() == &APFloat::IEEEdouble())
1212 Val2.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &losesInfo);
1215 case Type::X86_FP80TyID:
1216 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1217 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1218 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1219 &Val2.getSemantics() == &APFloat::x87DoubleExtended();
1220 case Type::FP128TyID:
1221 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1222 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1223 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1224 &Val2.getSemantics() == &APFloat::IEEEquad();
1225 case Type::PPC_FP128TyID:
1226 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1227 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1228 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1229 &Val2.getSemantics() == &APFloat::PPCDoubleDouble();
1234 //===----------------------------------------------------------------------===//
1235 // Factory Function Implementation
1237 ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
1238 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
1239 "Cannot create an aggregate zero of non-aggregate type!");
1241 std::unique_ptr<ConstantAggregateZero> &Entry =
1242 Ty->getContext().pImpl->CAZConstants[Ty];
1244 Entry.reset(new ConstantAggregateZero(Ty));
1249 /// Remove the constant from the constant table.
1250 void ConstantAggregateZero::destroyConstantImpl() {
1251 getContext().pImpl->CAZConstants.erase(getType());
1254 /// Remove the constant from the constant table.
1255 void ConstantArray::destroyConstantImpl() {
1256 getType()->getContext().pImpl->ArrayConstants.remove(this);
1260 //---- ConstantStruct::get() implementation...
1263 /// Remove the constant from the constant table.
1264 void ConstantStruct::destroyConstantImpl() {
1265 getType()->getContext().pImpl->StructConstants.remove(this);
1268 /// Remove the constant from the constant table.
1269 void ConstantVector::destroyConstantImpl() {
1270 getType()->getContext().pImpl->VectorConstants.remove(this);
1273 Constant *Constant::getSplatValue() const {
1274 assert(this->getType()->isVectorTy() && "Only valid for vectors!");
1275 if (isa<ConstantAggregateZero>(this))
1276 return getNullValue(this->getType()->getVectorElementType());
1277 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
1278 return CV->getSplatValue();
1279 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
1280 return CV->getSplatValue();
1284 Constant *ConstantVector::getSplatValue() const {
1285 // Check out first element.
1286 Constant *Elt = getOperand(0);
1287 // Then make sure all remaining elements point to the same value.
1288 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1289 if (getOperand(I) != Elt)
1294 const APInt &Constant::getUniqueInteger() const {
1295 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
1296 return CI->getValue();
1297 assert(this->getSplatValue() && "Doesn't contain a unique integer!");
1298 const Constant *C = this->getAggregateElement(0U);
1299 assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
1300 return cast<ConstantInt>(C)->getValue();
1303 //---- ConstantPointerNull::get() implementation.
1306 ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
1307 std::unique_ptr<ConstantPointerNull> &Entry =
1308 Ty->getContext().pImpl->CPNConstants[Ty];
1310 Entry.reset(new ConstantPointerNull(Ty));
1315 /// Remove the constant from the constant table.
1316 void ConstantPointerNull::destroyConstantImpl() {
1317 getContext().pImpl->CPNConstants.erase(getType());
1320 UndefValue *UndefValue::get(Type *Ty) {
1321 std::unique_ptr<UndefValue> &Entry = Ty->getContext().pImpl->UVConstants[Ty];
1323 Entry.reset(new UndefValue(Ty));
1328 /// Remove the constant from the constant table.
1329 void UndefValue::destroyConstantImpl() {
1330 // Free the constant and any dangling references to it.
1331 getContext().pImpl->UVConstants.erase(getType());
1334 BlockAddress *BlockAddress::get(BasicBlock *BB) {
1335 assert(BB->getParent() && "Block must have a parent");
1336 return get(BB->getParent(), BB);
1339 BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1341 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
1343 BA = new BlockAddress(F, BB);
1345 assert(BA->getFunction() == F && "Basic block moved between functions");
1349 BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1350 : Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1354 BB->AdjustBlockAddressRefCount(1);
1357 BlockAddress *BlockAddress::lookup(const BasicBlock *BB) {
1358 if (!BB->hasAddressTaken())
1361 const Function *F = BB->getParent();
1362 assert(F && "Block must have a parent");
1364 F->getContext().pImpl->BlockAddresses.lookup(std::make_pair(F, BB));
1365 assert(BA && "Refcount and block address map disagree!");
1369 /// Remove the constant from the constant table.
1370 void BlockAddress::destroyConstantImpl() {
1371 getFunction()->getType()->getContext().pImpl
1372 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
1373 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1376 Value *BlockAddress::handleOperandChangeImpl(Value *From, Value *To) {
1377 // This could be replacing either the Basic Block or the Function. In either
1378 // case, we have to remove the map entry.
1379 Function *NewF = getFunction();
1380 BasicBlock *NewBB = getBasicBlock();
1383 NewF = cast<Function>(To->stripPointerCasts());
1385 assert(From == NewBB && "From does not match any operand");
1386 NewBB = cast<BasicBlock>(To);
1389 // See if the 'new' entry already exists, if not, just update this in place
1390 // and return early.
1391 BlockAddress *&NewBA =
1392 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
1396 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1398 // Remove the old entry, this can't cause the map to rehash (just a
1399 // tombstone will get added).
1400 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1403 setOperand(0, NewF);
1404 setOperand(1, NewBB);
1405 getBasicBlock()->AdjustBlockAddressRefCount(1);
1407 // If we just want to keep the existing value, then return null.
1408 // Callers know that this means we shouldn't delete this value.
1412 //---- ConstantExpr::get() implementations.
1415 /// This is a utility function to handle folding of casts and lookup of the
1416 /// cast in the ExprConstants map. It is used by the various get* methods below.
1417 static Constant *getFoldedCast(Instruction::CastOps opc, Constant *C, Type *Ty,
1418 bool OnlyIfReduced = false) {
1419 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1420 // Fold a few common cases
1421 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1427 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1429 // Look up the constant in the table first to ensure uniqueness.
1430 ConstantExprKeyType Key(opc, C);
1432 return pImpl->ExprConstants.getOrCreate(Ty, Key);
1435 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty,
1436 bool OnlyIfReduced) {
1437 Instruction::CastOps opc = Instruction::CastOps(oc);
1438 assert(Instruction::isCast(opc) && "opcode out of range");
1439 assert(C && Ty && "Null arguments to getCast");
1440 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
1444 llvm_unreachable("Invalid cast opcode");
1445 case Instruction::Trunc:
1446 return getTrunc(C, Ty, OnlyIfReduced);
1447 case Instruction::ZExt:
1448 return getZExt(C, Ty, OnlyIfReduced);
1449 case Instruction::SExt:
1450 return getSExt(C, Ty, OnlyIfReduced);
1451 case Instruction::FPTrunc:
1452 return getFPTrunc(C, Ty, OnlyIfReduced);
1453 case Instruction::FPExt:
1454 return getFPExtend(C, Ty, OnlyIfReduced);
1455 case Instruction::UIToFP:
1456 return getUIToFP(C, Ty, OnlyIfReduced);
1457 case Instruction::SIToFP:
1458 return getSIToFP(C, Ty, OnlyIfReduced);
1459 case Instruction::FPToUI:
1460 return getFPToUI(C, Ty, OnlyIfReduced);
1461 case Instruction::FPToSI:
1462 return getFPToSI(C, Ty, OnlyIfReduced);
1463 case Instruction::PtrToInt:
1464 return getPtrToInt(C, Ty, OnlyIfReduced);
1465 case Instruction::IntToPtr:
1466 return getIntToPtr(C, Ty, OnlyIfReduced);
1467 case Instruction::BitCast:
1468 return getBitCast(C, Ty, OnlyIfReduced);
1469 case Instruction::AddrSpaceCast:
1470 return getAddrSpaceCast(C, Ty, OnlyIfReduced);
1474 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) {
1475 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1476 return getBitCast(C, Ty);
1477 return getZExt(C, Ty);
1480 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) {
1481 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1482 return getBitCast(C, Ty);
1483 return getSExt(C, Ty);
1486 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {
1487 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1488 return getBitCast(C, Ty);
1489 return getTrunc(C, Ty);
1492 Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {
1493 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1494 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
1497 if (Ty->isIntOrIntVectorTy())
1498 return getPtrToInt(S, Ty);
1500 unsigned SrcAS = S->getType()->getPointerAddressSpace();
1501 if (Ty->isPtrOrPtrVectorTy() && SrcAS != Ty->getPointerAddressSpace())
1502 return getAddrSpaceCast(S, Ty);
1504 return getBitCast(S, Ty);
1507 Constant *ConstantExpr::getPointerBitCastOrAddrSpaceCast(Constant *S,
1509 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1510 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
1512 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
1513 return getAddrSpaceCast(S, Ty);
1515 return getBitCast(S, Ty);
1518 Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty, bool isSigned) {
1519 assert(C->getType()->isIntOrIntVectorTy() &&
1520 Ty->isIntOrIntVectorTy() && "Invalid cast");
1521 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1522 unsigned DstBits = Ty->getScalarSizeInBits();
1523 Instruction::CastOps opcode =
1524 (SrcBits == DstBits ? Instruction::BitCast :
1525 (SrcBits > DstBits ? Instruction::Trunc :
1526 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1527 return getCast(opcode, C, Ty);
1530 Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) {
1531 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1533 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1534 unsigned DstBits = Ty->getScalarSizeInBits();
1535 if (SrcBits == DstBits)
1536 return C; // Avoid a useless cast
1537 Instruction::CastOps opcode =
1538 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1539 return getCast(opcode, C, Ty);
1542 Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
1544 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1545 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1547 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1548 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
1549 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
1550 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1551 "SrcTy must be larger than DestTy for Trunc!");
1553 return getFoldedCast(Instruction::Trunc, C, Ty, OnlyIfReduced);
1556 Constant *ConstantExpr::getSExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
1558 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1559 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1561 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1562 assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
1563 assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
1564 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1565 "SrcTy must be smaller than DestTy for SExt!");
1567 return getFoldedCast(Instruction::SExt, C, Ty, OnlyIfReduced);
1570 Constant *ConstantExpr::getZExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
1572 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1573 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1575 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1576 assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
1577 assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
1578 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1579 "SrcTy must be smaller than DestTy for ZExt!");
1581 return getFoldedCast(Instruction::ZExt, C, Ty, OnlyIfReduced);
1584 Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
1586 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1587 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1589 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1590 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1591 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1592 "This is an illegal floating point truncation!");
1593 return getFoldedCast(Instruction::FPTrunc, C, Ty, OnlyIfReduced);
1596 Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty, bool OnlyIfReduced) {
1598 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1599 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1601 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1602 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1603 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1604 "This is an illegal floating point extension!");
1605 return getFoldedCast(Instruction::FPExt, C, Ty, OnlyIfReduced);
1608 Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
1610 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1611 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1613 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1614 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1615 "This is an illegal uint to floating point cast!");
1616 return getFoldedCast(Instruction::UIToFP, C, Ty, OnlyIfReduced);
1619 Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
1621 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1622 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1624 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1625 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1626 "This is an illegal sint to floating point cast!");
1627 return getFoldedCast(Instruction::SIToFP, C, Ty, OnlyIfReduced);
1630 Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty, bool OnlyIfReduced) {
1632 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1633 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1635 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1636 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1637 "This is an illegal floating point to uint cast!");
1638 return getFoldedCast(Instruction::FPToUI, C, Ty, OnlyIfReduced);
1641 Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty, bool OnlyIfReduced) {
1643 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1644 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1646 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1647 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1648 "This is an illegal floating point to sint cast!");
1649 return getFoldedCast(Instruction::FPToSI, C, Ty, OnlyIfReduced);
1652 Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy,
1653 bool OnlyIfReduced) {
1654 assert(C->getType()->isPtrOrPtrVectorTy() &&
1655 "PtrToInt source must be pointer or pointer vector");
1656 assert(DstTy->isIntOrIntVectorTy() &&
1657 "PtrToInt destination must be integer or integer vector");
1658 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
1659 if (isa<VectorType>(C->getType()))
1660 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
1661 "Invalid cast between a different number of vector elements");
1662 return getFoldedCast(Instruction::PtrToInt, C, DstTy, OnlyIfReduced);
1665 Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy,
1666 bool OnlyIfReduced) {
1667 assert(C->getType()->isIntOrIntVectorTy() &&
1668 "IntToPtr source must be integer or integer vector");
1669 assert(DstTy->isPtrOrPtrVectorTy() &&
1670 "IntToPtr destination must be a pointer or pointer vector");
1671 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
1672 if (isa<VectorType>(C->getType()))
1673 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
1674 "Invalid cast between a different number of vector elements");
1675 return getFoldedCast(Instruction::IntToPtr, C, DstTy, OnlyIfReduced);
1678 Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy,
1679 bool OnlyIfReduced) {
1680 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
1681 "Invalid constantexpr bitcast!");
1683 // It is common to ask for a bitcast of a value to its own type, handle this
1685 if (C->getType() == DstTy) return C;
1687 return getFoldedCast(Instruction::BitCast, C, DstTy, OnlyIfReduced);
1690 Constant *ConstantExpr::getAddrSpaceCast(Constant *C, Type *DstTy,
1691 bool OnlyIfReduced) {
1692 assert(CastInst::castIsValid(Instruction::AddrSpaceCast, C, DstTy) &&
1693 "Invalid constantexpr addrspacecast!");
1695 // Canonicalize addrspacecasts between different pointer types by first
1696 // bitcasting the pointer type and then converting the address space.
1697 PointerType *SrcScalarTy = cast<PointerType>(C->getType()->getScalarType());
1698 PointerType *DstScalarTy = cast<PointerType>(DstTy->getScalarType());
1699 Type *DstElemTy = DstScalarTy->getElementType();
1700 if (SrcScalarTy->getElementType() != DstElemTy) {
1701 Type *MidTy = PointerType::get(DstElemTy, SrcScalarTy->getAddressSpace());
1702 if (VectorType *VT = dyn_cast<VectorType>(DstTy)) {
1703 // Handle vectors of pointers.
1704 MidTy = VectorType::get(MidTy, VT->getNumElements());
1706 C = getBitCast(C, MidTy);
1708 return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced);
1711 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
1712 unsigned Flags, Type *OnlyIfReducedTy) {
1713 // Check the operands for consistency first.
1714 assert(Opcode >= Instruction::BinaryOpsBegin &&
1715 Opcode < Instruction::BinaryOpsEnd &&
1716 "Invalid opcode in binary constant expression");
1717 assert(C1->getType() == C2->getType() &&
1718 "Operand types in binary constant expression should match");
1722 case Instruction::Add:
1723 case Instruction::Sub:
1724 case Instruction::Mul:
1725 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1726 assert(C1->getType()->isIntOrIntVectorTy() &&
1727 "Tried to create an integer operation on a non-integer type!");
1729 case Instruction::FAdd:
1730 case Instruction::FSub:
1731 case Instruction::FMul:
1732 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1733 assert(C1->getType()->isFPOrFPVectorTy() &&
1734 "Tried to create a floating-point operation on a "
1735 "non-floating-point type!");
1737 case Instruction::UDiv:
1738 case Instruction::SDiv:
1739 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1740 assert(C1->getType()->isIntOrIntVectorTy() &&
1741 "Tried to create an arithmetic operation on a non-arithmetic type!");
1743 case Instruction::FDiv:
1744 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1745 assert(C1->getType()->isFPOrFPVectorTy() &&
1746 "Tried to create an arithmetic operation on a non-arithmetic type!");
1748 case Instruction::URem:
1749 case Instruction::SRem:
1750 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1751 assert(C1->getType()->isIntOrIntVectorTy() &&
1752 "Tried to create an arithmetic operation on a non-arithmetic type!");
1754 case Instruction::FRem:
1755 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1756 assert(C1->getType()->isFPOrFPVectorTy() &&
1757 "Tried to create an arithmetic operation on a non-arithmetic type!");
1759 case Instruction::And:
1760 case Instruction::Or:
1761 case Instruction::Xor:
1762 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1763 assert(C1->getType()->isIntOrIntVectorTy() &&
1764 "Tried to create a logical operation on a non-integral type!");
1766 case Instruction::Shl:
1767 case Instruction::LShr:
1768 case Instruction::AShr:
1769 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1770 assert(C1->getType()->isIntOrIntVectorTy() &&
1771 "Tried to create a shift operation on a non-integer type!");
1778 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1779 return FC; // Fold a few common cases.
1781 if (OnlyIfReducedTy == C1->getType())
1784 Constant *ArgVec[] = { C1, C2 };
1785 ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
1787 LLVMContextImpl *pImpl = C1->getContext().pImpl;
1788 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
1791 Constant *ConstantExpr::getSizeOf(Type* Ty) {
1792 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1793 // Note that a non-inbounds gep is used, as null isn't within any object.
1794 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1795 Constant *GEP = getGetElementPtr(
1796 Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
1797 return getPtrToInt(GEP,
1798 Type::getInt64Ty(Ty->getContext()));
1801 Constant *ConstantExpr::getAlignOf(Type* Ty) {
1802 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
1803 // Note that a non-inbounds gep is used, as null isn't within any object.
1804 Type *AligningTy = StructType::get(Type::getInt1Ty(Ty->getContext()), Ty);
1805 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo(0));
1806 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
1807 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1808 Constant *Indices[2] = { Zero, One };
1809 Constant *GEP = getGetElementPtr(AligningTy, NullPtr, Indices);
1810 return getPtrToInt(GEP,
1811 Type::getInt64Ty(Ty->getContext()));
1814 Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) {
1815 return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
1819 Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) {
1820 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1821 // Note that a non-inbounds gep is used, as null isn't within any object.
1822 Constant *GEPIdx[] = {
1823 ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
1826 Constant *GEP = getGetElementPtr(
1827 Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
1828 return getPtrToInt(GEP,
1829 Type::getInt64Ty(Ty->getContext()));
1832 Constant *ConstantExpr::getCompare(unsigned short Predicate, Constant *C1,
1833 Constant *C2, bool OnlyIfReduced) {
1834 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1836 switch (Predicate) {
1837 default: llvm_unreachable("Invalid CmpInst predicate");
1838 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1839 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1840 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1841 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1842 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1843 case CmpInst::FCMP_TRUE:
1844 return getFCmp(Predicate, C1, C2, OnlyIfReduced);
1846 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1847 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1848 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1849 case CmpInst::ICMP_SLE:
1850 return getICmp(Predicate, C1, C2, OnlyIfReduced);
1854 Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2,
1855 Type *OnlyIfReducedTy) {
1856 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1858 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1859 return SC; // Fold common cases
1861 if (OnlyIfReducedTy == V1->getType())
1864 Constant *ArgVec[] = { C, V1, V2 };
1865 ConstantExprKeyType Key(Instruction::Select, ArgVec);
1867 LLVMContextImpl *pImpl = C->getContext().pImpl;
1868 return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
1871 Constant *ConstantExpr::getGetElementPtr(Type *Ty, Constant *C,
1872 ArrayRef<Value *> Idxs, bool InBounds,
1873 Optional<unsigned> InRangeIndex,
1874 Type *OnlyIfReducedTy) {
1876 Ty = cast<PointerType>(C->getType()->getScalarType())->getElementType();
1880 cast<PointerType>(C->getType()->getScalarType())->getContainedType(0u));
1883 ConstantFoldGetElementPtr(Ty, C, InBounds, InRangeIndex, Idxs))
1884 return FC; // Fold a few common cases.
1886 // Get the result type of the getelementptr!
1887 Type *DestTy = GetElementPtrInst::getIndexedType(Ty, Idxs);
1888 assert(DestTy && "GEP indices invalid!");
1889 unsigned AS = C->getType()->getPointerAddressSpace();
1890 Type *ReqTy = DestTy->getPointerTo(AS);
1892 unsigned NumVecElts = 0;
1893 if (C->getType()->isVectorTy())
1894 NumVecElts = C->getType()->getVectorNumElements();
1895 else for (auto Idx : Idxs)
1896 if (Idx->getType()->isVectorTy())
1897 NumVecElts = Idx->getType()->getVectorNumElements();
1900 ReqTy = VectorType::get(ReqTy, NumVecElts);
1902 if (OnlyIfReducedTy == ReqTy)
1905 // Look up the constant in the table first to ensure uniqueness
1906 std::vector<Constant*> ArgVec;
1907 ArgVec.reserve(1 + Idxs.size());
1908 ArgVec.push_back(C);
1909 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
1910 assert((!Idxs[i]->getType()->isVectorTy() ||
1911 Idxs[i]->getType()->getVectorNumElements() == NumVecElts) &&
1912 "getelementptr index type missmatch");
1914 Constant *Idx = cast<Constant>(Idxs[i]);
1915 if (NumVecElts && !Idxs[i]->getType()->isVectorTy())
1916 Idx = ConstantVector::getSplat(NumVecElts, Idx);
1917 ArgVec.push_back(Idx);
1920 unsigned SubClassOptionalData = InBounds ? GEPOperator::IsInBounds : 0;
1921 if (InRangeIndex && *InRangeIndex < 63)
1922 SubClassOptionalData |= (*InRangeIndex + 1) << 1;
1923 const ConstantExprKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
1924 SubClassOptionalData, None, Ty);
1926 LLVMContextImpl *pImpl = C->getContext().pImpl;
1927 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1930 Constant *ConstantExpr::getICmp(unsigned short pred, Constant *LHS,
1931 Constant *RHS, bool OnlyIfReduced) {
1932 assert(LHS->getType() == RHS->getType());
1933 assert(CmpInst::isIntPredicate((CmpInst::Predicate)pred) &&
1934 "Invalid ICmp Predicate");
1936 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1937 return FC; // Fold a few common cases...
1942 // Look up the constant in the table first to ensure uniqueness
1943 Constant *ArgVec[] = { LHS, RHS };
1944 // Get the key type with both the opcode and predicate
1945 const ConstantExprKeyType Key(Instruction::ICmp, ArgVec, pred);
1947 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1948 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1949 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1951 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1952 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
1955 Constant *ConstantExpr::getFCmp(unsigned short pred, Constant *LHS,
1956 Constant *RHS, bool OnlyIfReduced) {
1957 assert(LHS->getType() == RHS->getType());
1958 assert(CmpInst::isFPPredicate((CmpInst::Predicate)pred) &&
1959 "Invalid FCmp Predicate");
1961 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1962 return FC; // Fold a few common cases...
1967 // Look up the constant in the table first to ensure uniqueness
1968 Constant *ArgVec[] = { LHS, RHS };
1969 // Get the key type with both the opcode and predicate
1970 const ConstantExprKeyType Key(Instruction::FCmp, ArgVec, pred);
1972 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1973 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1974 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1976 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1977 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
1980 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx,
1981 Type *OnlyIfReducedTy) {
1982 assert(Val->getType()->isVectorTy() &&
1983 "Tried to create extractelement operation on non-vector type!");
1984 assert(Idx->getType()->isIntegerTy() &&
1985 "Extractelement index must be an integer type!");
1987 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1988 return FC; // Fold a few common cases.
1990 Type *ReqTy = Val->getType()->getVectorElementType();
1991 if (OnlyIfReducedTy == ReqTy)
1994 // Look up the constant in the table first to ensure uniqueness
1995 Constant *ArgVec[] = { Val, Idx };
1996 const ConstantExprKeyType Key(Instruction::ExtractElement, ArgVec);
1998 LLVMContextImpl *pImpl = Val->getContext().pImpl;
1999 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2002 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2003 Constant *Idx, Type *OnlyIfReducedTy) {
2004 assert(Val->getType()->isVectorTy() &&
2005 "Tried to create insertelement operation on non-vector type!");
2006 assert(Elt->getType() == Val->getType()->getVectorElementType() &&
2007 "Insertelement types must match!");
2008 assert(Idx->getType()->isIntegerTy() &&
2009 "Insertelement index must be i32 type!");
2011 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2012 return FC; // Fold a few common cases.
2014 if (OnlyIfReducedTy == Val->getType())
2017 // Look up the constant in the table first to ensure uniqueness
2018 Constant *ArgVec[] = { Val, Elt, Idx };
2019 const ConstantExprKeyType Key(Instruction::InsertElement, ArgVec);
2021 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2022 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
2025 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2026 Constant *Mask, Type *OnlyIfReducedTy) {
2027 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2028 "Invalid shuffle vector constant expr operands!");
2030 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2031 return FC; // Fold a few common cases.
2033 unsigned NElts = Mask->getType()->getVectorNumElements();
2034 Type *EltTy = V1->getType()->getVectorElementType();
2035 Type *ShufTy = VectorType::get(EltTy, NElts);
2037 if (OnlyIfReducedTy == ShufTy)
2040 // Look up the constant in the table first to ensure uniqueness
2041 Constant *ArgVec[] = { V1, V2, Mask };
2042 const ConstantExprKeyType Key(Instruction::ShuffleVector, ArgVec);
2044 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
2045 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
2048 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
2049 ArrayRef<unsigned> Idxs,
2050 Type *OnlyIfReducedTy) {
2051 assert(Agg->getType()->isFirstClassType() &&
2052 "Non-first-class type for constant insertvalue expression");
2054 assert(ExtractValueInst::getIndexedType(Agg->getType(),
2055 Idxs) == Val->getType() &&
2056 "insertvalue indices invalid!");
2057 Type *ReqTy = Val->getType();
2059 if (Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs))
2062 if (OnlyIfReducedTy == ReqTy)
2065 Constant *ArgVec[] = { Agg, Val };
2066 const ConstantExprKeyType Key(Instruction::InsertValue, ArgVec, 0, 0, Idxs);
2068 LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2069 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2072 Constant *ConstantExpr::getExtractValue(Constant *Agg, ArrayRef<unsigned> Idxs,
2073 Type *OnlyIfReducedTy) {
2074 assert(Agg->getType()->isFirstClassType() &&
2075 "Tried to create extractelement operation on non-first-class type!");
2077 Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs);
2079 assert(ReqTy && "extractvalue indices invalid!");
2081 assert(Agg->getType()->isFirstClassType() &&
2082 "Non-first-class type for constant extractvalue expression");
2083 if (Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs))
2086 if (OnlyIfReducedTy == ReqTy)
2089 Constant *ArgVec[] = { Agg };
2090 const ConstantExprKeyType Key(Instruction::ExtractValue, ArgVec, 0, 0, Idxs);
2092 LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2093 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2096 Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
2097 assert(C->getType()->isIntOrIntVectorTy() &&
2098 "Cannot NEG a nonintegral value!");
2099 return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
2103 Constant *ConstantExpr::getFNeg(Constant *C) {
2104 assert(C->getType()->isFPOrFPVectorTy() &&
2105 "Cannot FNEG a non-floating-point value!");
2106 return getFSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
2109 Constant *ConstantExpr::getNot(Constant *C) {
2110 assert(C->getType()->isIntOrIntVectorTy() &&
2111 "Cannot NOT a nonintegral value!");
2112 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
2115 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
2116 bool HasNUW, bool HasNSW) {
2117 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2118 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2119 return get(Instruction::Add, C1, C2, Flags);
2122 Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
2123 return get(Instruction::FAdd, C1, C2);
2126 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
2127 bool HasNUW, bool HasNSW) {
2128 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2129 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2130 return get(Instruction::Sub, C1, C2, Flags);
2133 Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
2134 return get(Instruction::FSub, C1, C2);
2137 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
2138 bool HasNUW, bool HasNSW) {
2139 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2140 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2141 return get(Instruction::Mul, C1, C2, Flags);
2144 Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
2145 return get(Instruction::FMul, C1, C2);
2148 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
2149 return get(Instruction::UDiv, C1, C2,
2150 isExact ? PossiblyExactOperator::IsExact : 0);
2153 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
2154 return get(Instruction::SDiv, C1, C2,
2155 isExact ? PossiblyExactOperator::IsExact : 0);
2158 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
2159 return get(Instruction::FDiv, C1, C2);
2162 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
2163 return get(Instruction::URem, C1, C2);
2166 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
2167 return get(Instruction::SRem, C1, C2);
2170 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
2171 return get(Instruction::FRem, C1, C2);
2174 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
2175 return get(Instruction::And, C1, C2);
2178 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
2179 return get(Instruction::Or, C1, C2);
2182 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
2183 return get(Instruction::Xor, C1, C2);
2186 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
2187 bool HasNUW, bool HasNSW) {
2188 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2189 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2190 return get(Instruction::Shl, C1, C2, Flags);
2193 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
2194 return get(Instruction::LShr, C1, C2,
2195 isExact ? PossiblyExactOperator::IsExact : 0);
2198 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
2199 return get(Instruction::AShr, C1, C2,
2200 isExact ? PossiblyExactOperator::IsExact : 0);
2203 Constant *ConstantExpr::getBinOpIdentity(unsigned Opcode, Type *Ty) {
2206 // Doesn't have an identity.
2209 case Instruction::Add:
2210 case Instruction::Or:
2211 case Instruction::Xor:
2212 return Constant::getNullValue(Ty);
2214 case Instruction::Mul:
2215 return ConstantInt::get(Ty, 1);
2217 case Instruction::And:
2218 return Constant::getAllOnesValue(Ty);
2222 Constant *ConstantExpr::getBinOpAbsorber(unsigned Opcode, Type *Ty) {
2225 // Doesn't have an absorber.
2228 case Instruction::Or:
2229 return Constant::getAllOnesValue(Ty);
2231 case Instruction::And:
2232 case Instruction::Mul:
2233 return Constant::getNullValue(Ty);
2237 /// Remove the constant from the constant table.
2238 void ConstantExpr::destroyConstantImpl() {
2239 getType()->getContext().pImpl->ExprConstants.remove(this);
2242 const char *ConstantExpr::getOpcodeName() const {
2243 return Instruction::getOpcodeName(getOpcode());
2246 GetElementPtrConstantExpr::GetElementPtrConstantExpr(
2247 Type *SrcElementTy, Constant *C, ArrayRef<Constant *> IdxList, Type *DestTy)
2248 : ConstantExpr(DestTy, Instruction::GetElementPtr,
2249 OperandTraits<GetElementPtrConstantExpr>::op_end(this) -
2250 (IdxList.size() + 1),
2251 IdxList.size() + 1),
2252 SrcElementTy(SrcElementTy),
2253 ResElementTy(GetElementPtrInst::getIndexedType(SrcElementTy, IdxList)) {
2255 Use *OperandList = getOperandList();
2256 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
2257 OperandList[i+1] = IdxList[i];
2260 Type *GetElementPtrConstantExpr::getSourceElementType() const {
2261 return SrcElementTy;
2264 Type *GetElementPtrConstantExpr::getResultElementType() const {
2265 return ResElementTy;
2268 //===----------------------------------------------------------------------===//
2269 // ConstantData* implementations
2271 Type *ConstantDataSequential::getElementType() const {
2272 return getType()->getElementType();
2275 StringRef ConstantDataSequential::getRawDataValues() const {
2276 return StringRef(DataElements, getNumElements()*getElementByteSize());
2279 bool ConstantDataSequential::isElementTypeCompatible(Type *Ty) {
2280 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) return true;
2281 if (auto *IT = dyn_cast<IntegerType>(Ty)) {
2282 switch (IT->getBitWidth()) {
2294 unsigned ConstantDataSequential::getNumElements() const {
2295 if (ArrayType *AT = dyn_cast<ArrayType>(getType()))
2296 return AT->getNumElements();
2297 return getType()->getVectorNumElements();
2301 uint64_t ConstantDataSequential::getElementByteSize() const {
2302 return getElementType()->getPrimitiveSizeInBits()/8;
2305 /// Return the start of the specified element.
2306 const char *ConstantDataSequential::getElementPointer(unsigned Elt) const {
2307 assert(Elt < getNumElements() && "Invalid Elt");
2308 return DataElements+Elt*getElementByteSize();
2312 /// Return true if the array is empty or all zeros.
2313 static bool isAllZeros(StringRef Arr) {
2320 /// This is the underlying implementation of all of the
2321 /// ConstantDataSequential::get methods. They all thunk down to here, providing
2322 /// the correct element type. We take the bytes in as a StringRef because
2323 /// we *want* an underlying "char*" to avoid TBAA type punning violations.
2324 Constant *ConstantDataSequential::getImpl(StringRef Elements, Type *Ty) {
2325 assert(isElementTypeCompatible(Ty->getSequentialElementType()));
2326 // If the elements are all zero or there are no elements, return a CAZ, which
2327 // is more dense and canonical.
2328 if (isAllZeros(Elements))
2329 return ConstantAggregateZero::get(Ty);
2331 // Do a lookup to see if we have already formed one of these.
2334 .pImpl->CDSConstants.insert(std::make_pair(Elements, nullptr))
2337 // The bucket can point to a linked list of different CDS's that have the same
2338 // body but different types. For example, 0,0,0,1 could be a 4 element array
2339 // of i8, or a 1-element array of i32. They'll both end up in the same
2340 /// StringMap bucket, linked up by their Next pointers. Walk the list.
2341 ConstantDataSequential **Entry = &Slot.second;
2342 for (ConstantDataSequential *Node = *Entry; Node;
2343 Entry = &Node->Next, Node = *Entry)
2344 if (Node->getType() == Ty)
2347 // Okay, we didn't get a hit. Create a node of the right class, link it in,
2349 if (isa<ArrayType>(Ty))
2350 return *Entry = new ConstantDataArray(Ty, Slot.first().data());
2352 assert(isa<VectorType>(Ty));
2353 return *Entry = new ConstantDataVector(Ty, Slot.first().data());
2356 void ConstantDataSequential::destroyConstantImpl() {
2357 // Remove the constant from the StringMap.
2358 StringMap<ConstantDataSequential*> &CDSConstants =
2359 getType()->getContext().pImpl->CDSConstants;
2361 StringMap<ConstantDataSequential*>::iterator Slot =
2362 CDSConstants.find(getRawDataValues());
2364 assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
2366 ConstantDataSequential **Entry = &Slot->getValue();
2368 // Remove the entry from the hash table.
2369 if (!(*Entry)->Next) {
2370 // If there is only one value in the bucket (common case) it must be this
2371 // entry, and removing the entry should remove the bucket completely.
2372 assert((*Entry) == this && "Hash mismatch in ConstantDataSequential");
2373 getContext().pImpl->CDSConstants.erase(Slot);
2375 // Otherwise, there are multiple entries linked off the bucket, unlink the
2376 // node we care about but keep the bucket around.
2377 for (ConstantDataSequential *Node = *Entry; ;
2378 Entry = &Node->Next, Node = *Entry) {
2379 assert(Node && "Didn't find entry in its uniquing hash table!");
2380 // If we found our entry, unlink it from the list and we're done.
2382 *Entry = Node->Next;
2388 // If we were part of a list, make sure that we don't delete the list that is
2389 // still owned by the uniquing map.
2393 /// get() constructors - Return a constant with array type with an element
2394 /// count and element type matching the ArrayRef passed in. Note that this
2395 /// can return a ConstantAggregateZero object.
2396 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint8_t> Elts) {
2397 Type *Ty = ArrayType::get(Type::getInt8Ty(Context), Elts.size());
2398 const char *Data = reinterpret_cast<const char *>(Elts.data());
2399 return getImpl(StringRef(Data, Elts.size() * 1), Ty);
2401 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
2402 Type *Ty = ArrayType::get(Type::getInt16Ty(Context), Elts.size());
2403 const char *Data = reinterpret_cast<const char *>(Elts.data());
2404 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
2406 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
2407 Type *Ty = ArrayType::get(Type::getInt32Ty(Context), Elts.size());
2408 const char *Data = reinterpret_cast<const char *>(Elts.data());
2409 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
2411 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
2412 Type *Ty = ArrayType::get(Type::getInt64Ty(Context), Elts.size());
2413 const char *Data = reinterpret_cast<const char *>(Elts.data());
2414 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
2416 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<float> Elts) {
2417 Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
2418 const char *Data = reinterpret_cast<const char *>(Elts.data());
2419 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
2421 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<double> Elts) {
2422 Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
2423 const char *Data = reinterpret_cast<const char *>(Elts.data());
2424 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
2427 /// getFP() constructors - Return a constant with array type with an element
2428 /// count and element type of float with precision matching the number of
2429 /// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits,
2430 /// double for 64bits) Note that this can return a ConstantAggregateZero
2432 Constant *ConstantDataArray::getFP(LLVMContext &Context,
2433 ArrayRef<uint16_t> Elts) {
2434 Type *Ty = ArrayType::get(Type::getHalfTy(Context), Elts.size());
2435 const char *Data = reinterpret_cast<const char *>(Elts.data());
2436 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
2438 Constant *ConstantDataArray::getFP(LLVMContext &Context,
2439 ArrayRef<uint32_t> Elts) {
2440 Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
2441 const char *Data = reinterpret_cast<const char *>(Elts.data());
2442 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
2444 Constant *ConstantDataArray::getFP(LLVMContext &Context,
2445 ArrayRef<uint64_t> Elts) {
2446 Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
2447 const char *Data = reinterpret_cast<const char *>(Elts.data());
2448 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
2451 Constant *ConstantDataArray::getString(LLVMContext &Context,
2452 StringRef Str, bool AddNull) {
2454 const uint8_t *Data = reinterpret_cast<const uint8_t *>(Str.data());
2455 return get(Context, makeArrayRef(Data, Str.size()));
2458 SmallVector<uint8_t, 64> ElementVals;
2459 ElementVals.append(Str.begin(), Str.end());
2460 ElementVals.push_back(0);
2461 return get(Context, ElementVals);
2464 /// get() constructors - Return a constant with vector type with an element
2465 /// count and element type matching the ArrayRef passed in. Note that this
2466 /// can return a ConstantAggregateZero object.
2467 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> Elts){
2468 Type *Ty = VectorType::get(Type::getInt8Ty(Context), Elts.size());
2469 const char *Data = reinterpret_cast<const char *>(Elts.data());
2470 return getImpl(StringRef(Data, Elts.size() * 1), Ty);
2472 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
2473 Type *Ty = VectorType::get(Type::getInt16Ty(Context), Elts.size());
2474 const char *Data = reinterpret_cast<const char *>(Elts.data());
2475 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
2477 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
2478 Type *Ty = VectorType::get(Type::getInt32Ty(Context), Elts.size());
2479 const char *Data = reinterpret_cast<const char *>(Elts.data());
2480 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
2482 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
2483 Type *Ty = VectorType::get(Type::getInt64Ty(Context), Elts.size());
2484 const char *Data = reinterpret_cast<const char *>(Elts.data());
2485 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
2487 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> Elts) {
2488 Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
2489 const char *Data = reinterpret_cast<const char *>(Elts.data());
2490 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
2492 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<double> Elts) {
2493 Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
2494 const char *Data = reinterpret_cast<const char *>(Elts.data());
2495 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
2498 /// getFP() constructors - Return a constant with vector type with an element
2499 /// count and element type of float with the precision matching the number of
2500 /// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits,
2501 /// double for 64bits) Note that this can return a ConstantAggregateZero
2503 Constant *ConstantDataVector::getFP(LLVMContext &Context,
2504 ArrayRef<uint16_t> Elts) {
2505 Type *Ty = VectorType::get(Type::getHalfTy(Context), Elts.size());
2506 const char *Data = reinterpret_cast<const char *>(Elts.data());
2507 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
2509 Constant *ConstantDataVector::getFP(LLVMContext &Context,
2510 ArrayRef<uint32_t> Elts) {
2511 Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
2512 const char *Data = reinterpret_cast<const char *>(Elts.data());
2513 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
2515 Constant *ConstantDataVector::getFP(LLVMContext &Context,
2516 ArrayRef<uint64_t> Elts) {
2517 Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
2518 const char *Data = reinterpret_cast<const char *>(Elts.data());
2519 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
2522 Constant *ConstantDataVector::getSplat(unsigned NumElts, Constant *V) {
2523 assert(isElementTypeCompatible(V->getType()) &&
2524 "Element type not compatible with ConstantData");
2525 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2526 if (CI->getType()->isIntegerTy(8)) {
2527 SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
2528 return get(V->getContext(), Elts);
2530 if (CI->getType()->isIntegerTy(16)) {
2531 SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
2532 return get(V->getContext(), Elts);
2534 if (CI->getType()->isIntegerTy(32)) {
2535 SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
2536 return get(V->getContext(), Elts);
2538 assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
2539 SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
2540 return get(V->getContext(), Elts);
2543 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2544 if (CFP->getType()->isHalfTy()) {
2545 SmallVector<uint16_t, 16> Elts(
2546 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2547 return getFP(V->getContext(), Elts);
2549 if (CFP->getType()->isFloatTy()) {
2550 SmallVector<uint32_t, 16> Elts(
2551 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2552 return getFP(V->getContext(), Elts);
2554 if (CFP->getType()->isDoubleTy()) {
2555 SmallVector<uint64_t, 16> Elts(
2556 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2557 return getFP(V->getContext(), Elts);
2560 return ConstantVector::getSplat(NumElts, V);
2564 uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const {
2565 assert(isa<IntegerType>(getElementType()) &&
2566 "Accessor can only be used when element is an integer");
2567 const char *EltPtr = getElementPointer(Elt);
2569 // The data is stored in host byte order, make sure to cast back to the right
2570 // type to load with the right endianness.
2571 switch (getElementType()->getIntegerBitWidth()) {
2572 default: llvm_unreachable("Invalid bitwidth for CDS");
2574 return *reinterpret_cast<const uint8_t *>(EltPtr);
2576 return *reinterpret_cast<const uint16_t *>(EltPtr);
2578 return *reinterpret_cast<const uint32_t *>(EltPtr);
2580 return *reinterpret_cast<const uint64_t *>(EltPtr);
2584 APInt ConstantDataSequential::getElementAsAPInt(unsigned Elt) const {
2585 assert(isa<IntegerType>(getElementType()) &&
2586 "Accessor can only be used when element is an integer");
2587 const char *EltPtr = getElementPointer(Elt);
2589 // The data is stored in host byte order, make sure to cast back to the right
2590 // type to load with the right endianness.
2591 switch (getElementType()->getIntegerBitWidth()) {
2592 default: llvm_unreachable("Invalid bitwidth for CDS");
2594 auto EltVal = *reinterpret_cast<const uint8_t *>(EltPtr);
2595 return APInt(8, EltVal);
2598 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
2599 return APInt(16, EltVal);
2602 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
2603 return APInt(32, EltVal);
2606 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
2607 return APInt(64, EltVal);
2612 APFloat ConstantDataSequential::getElementAsAPFloat(unsigned Elt) const {
2613 const char *EltPtr = getElementPointer(Elt);
2615 switch (getElementType()->getTypeID()) {
2617 llvm_unreachable("Accessor can only be used when element is float/double!");
2618 case Type::HalfTyID: {
2619 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
2620 return APFloat(APFloat::IEEEhalf(), APInt(16, EltVal));
2622 case Type::FloatTyID: {
2623 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
2624 return APFloat(APFloat::IEEEsingle(), APInt(32, EltVal));
2626 case Type::DoubleTyID: {
2627 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
2628 return APFloat(APFloat::IEEEdouble(), APInt(64, EltVal));
2633 float ConstantDataSequential::getElementAsFloat(unsigned Elt) const {
2634 assert(getElementType()->isFloatTy() &&
2635 "Accessor can only be used when element is a 'float'");
2636 return *reinterpret_cast<const float *>(getElementPointer(Elt));
2639 double ConstantDataSequential::getElementAsDouble(unsigned Elt) const {
2640 assert(getElementType()->isDoubleTy() &&
2641 "Accessor can only be used when element is a 'float'");
2642 return *reinterpret_cast<const double *>(getElementPointer(Elt));
2645 Constant *ConstantDataSequential::getElementAsConstant(unsigned Elt) const {
2646 if (getElementType()->isHalfTy() || getElementType()->isFloatTy() ||
2647 getElementType()->isDoubleTy())
2648 return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
2650 return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
2653 bool ConstantDataSequential::isString(unsigned CharSize) const {
2654 return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(CharSize);
2657 bool ConstantDataSequential::isCString() const {
2661 StringRef Str = getAsString();
2663 // The last value must be nul.
2664 if (Str.back() != 0) return false;
2666 // Other elements must be non-nul.
2667 return Str.drop_back().find(0) == StringRef::npos;
2670 bool ConstantDataVector::isSplat() const {
2671 const char *Base = getRawDataValues().data();
2673 // Compare elements 1+ to the 0'th element.
2674 unsigned EltSize = getElementByteSize();
2675 for (unsigned i = 1, e = getNumElements(); i != e; ++i)
2676 if (memcmp(Base, Base+i*EltSize, EltSize))
2682 Constant *ConstantDataVector::getSplatValue() const {
2683 // If they're all the same, return the 0th one as a representative.
2684 return isSplat() ? getElementAsConstant(0) : nullptr;
2687 //===----------------------------------------------------------------------===//
2688 // handleOperandChange implementations
2690 /// Update this constant array to change uses of
2691 /// 'From' to be uses of 'To'. This must update the uniquing data structures
2694 /// Note that we intentionally replace all uses of From with To here. Consider
2695 /// a large array that uses 'From' 1000 times. By handling this case all here,
2696 /// ConstantArray::handleOperandChange is only invoked once, and that
2697 /// single invocation handles all 1000 uses. Handling them one at a time would
2698 /// work, but would be really slow because it would have to unique each updated
2701 void Constant::handleOperandChange(Value *From, Value *To) {
2702 Value *Replacement = nullptr;
2703 switch (getValueID()) {
2705 llvm_unreachable("Not a constant!");
2706 #define HANDLE_CONSTANT(Name) \
2707 case Value::Name##Val: \
2708 Replacement = cast<Name>(this)->handleOperandChangeImpl(From, To); \
2710 #include "llvm/IR/Value.def"
2713 // If handleOperandChangeImpl returned nullptr, then it handled
2714 // replacing itself and we don't want to delete or replace anything else here.
2718 // I do need to replace this with an existing value.
2719 assert(Replacement != this && "I didn't contain From!");
2721 // Everyone using this now uses the replacement.
2722 replaceAllUsesWith(Replacement);
2724 // Delete the old constant!
2728 Value *ConstantArray::handleOperandChangeImpl(Value *From, Value *To) {
2729 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2730 Constant *ToC = cast<Constant>(To);
2732 SmallVector<Constant*, 8> Values;
2733 Values.reserve(getNumOperands()); // Build replacement array.
2735 // Fill values with the modified operands of the constant array. Also,
2736 // compute whether this turns into an all-zeros array.
2737 unsigned NumUpdated = 0;
2739 // Keep track of whether all the values in the array are "ToC".
2740 bool AllSame = true;
2741 Use *OperandList = getOperandList();
2742 unsigned OperandNo = 0;
2743 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2744 Constant *Val = cast<Constant>(O->get());
2746 OperandNo = (O - OperandList);
2750 Values.push_back(Val);
2751 AllSame &= Val == ToC;
2754 if (AllSame && ToC->isNullValue())
2755 return ConstantAggregateZero::get(getType());
2757 if (AllSame && isa<UndefValue>(ToC))
2758 return UndefValue::get(getType());
2760 // Check for any other type of constant-folding.
2761 if (Constant *C = getImpl(getType(), Values))
2764 // Update to the new value.
2765 return getContext().pImpl->ArrayConstants.replaceOperandsInPlace(
2766 Values, this, From, ToC, NumUpdated, OperandNo);
2769 Value *ConstantStruct::handleOperandChangeImpl(Value *From, Value *To) {
2770 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2771 Constant *ToC = cast<Constant>(To);
2773 Use *OperandList = getOperandList();
2775 SmallVector<Constant*, 8> Values;
2776 Values.reserve(getNumOperands()); // Build replacement struct.
2778 // Fill values with the modified operands of the constant struct. Also,
2779 // compute whether this turns into an all-zeros struct.
2780 unsigned NumUpdated = 0;
2781 bool AllSame = true;
2782 unsigned OperandNo = 0;
2783 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) {
2784 Constant *Val = cast<Constant>(O->get());
2786 OperandNo = (O - OperandList);
2790 Values.push_back(Val);
2791 AllSame &= Val == ToC;
2794 if (AllSame && ToC->isNullValue())
2795 return ConstantAggregateZero::get(getType());
2797 if (AllSame && isa<UndefValue>(ToC))
2798 return UndefValue::get(getType());
2800 // Update to the new value.
2801 return getContext().pImpl->StructConstants.replaceOperandsInPlace(
2802 Values, this, From, ToC, NumUpdated, OperandNo);
2805 Value *ConstantVector::handleOperandChangeImpl(Value *From, Value *To) {
2806 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2807 Constant *ToC = cast<Constant>(To);
2809 SmallVector<Constant*, 8> Values;
2810 Values.reserve(getNumOperands()); // Build replacement array...
2811 unsigned NumUpdated = 0;
2812 unsigned OperandNo = 0;
2813 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2814 Constant *Val = getOperand(i);
2820 Values.push_back(Val);
2823 if (Constant *C = getImpl(Values))
2826 // Update to the new value.
2827 return getContext().pImpl->VectorConstants.replaceOperandsInPlace(
2828 Values, this, From, ToC, NumUpdated, OperandNo);
2831 Value *ConstantExpr::handleOperandChangeImpl(Value *From, Value *ToV) {
2832 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2833 Constant *To = cast<Constant>(ToV);
2835 SmallVector<Constant*, 8> NewOps;
2836 unsigned NumUpdated = 0;
2837 unsigned OperandNo = 0;
2838 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2839 Constant *Op = getOperand(i);
2845 NewOps.push_back(Op);
2847 assert(NumUpdated && "I didn't contain From!");
2849 if (Constant *C = getWithOperands(NewOps, getType(), true))
2852 // Update to the new value.
2853 return getContext().pImpl->ExprConstants.replaceOperandsInPlace(
2854 NewOps, this, From, To, NumUpdated, OperandNo);
2857 Instruction *ConstantExpr::getAsInstruction() {
2858 SmallVector<Value *, 4> ValueOperands(op_begin(), op_end());
2859 ArrayRef<Value*> Ops(ValueOperands);
2861 switch (getOpcode()) {
2862 case Instruction::Trunc:
2863 case Instruction::ZExt:
2864 case Instruction::SExt:
2865 case Instruction::FPTrunc:
2866 case Instruction::FPExt:
2867 case Instruction::UIToFP:
2868 case Instruction::SIToFP:
2869 case Instruction::FPToUI:
2870 case Instruction::FPToSI:
2871 case Instruction::PtrToInt:
2872 case Instruction::IntToPtr:
2873 case Instruction::BitCast:
2874 case Instruction::AddrSpaceCast:
2875 return CastInst::Create((Instruction::CastOps)getOpcode(),
2877 case Instruction::Select:
2878 return SelectInst::Create(Ops[0], Ops[1], Ops[2]);
2879 case Instruction::InsertElement:
2880 return InsertElementInst::Create(Ops[0], Ops[1], Ops[2]);
2881 case Instruction::ExtractElement:
2882 return ExtractElementInst::Create(Ops[0], Ops[1]);
2883 case Instruction::InsertValue:
2884 return InsertValueInst::Create(Ops[0], Ops[1], getIndices());
2885 case Instruction::ExtractValue:
2886 return ExtractValueInst::Create(Ops[0], getIndices());
2887 case Instruction::ShuffleVector:
2888 return new ShuffleVectorInst(Ops[0], Ops[1], Ops[2]);
2890 case Instruction::GetElementPtr: {
2891 const auto *GO = cast<GEPOperator>(this);
2892 if (GO->isInBounds())
2893 return GetElementPtrInst::CreateInBounds(GO->getSourceElementType(),
2894 Ops[0], Ops.slice(1));
2895 return GetElementPtrInst::Create(GO->getSourceElementType(), Ops[0],
2898 case Instruction::ICmp:
2899 case Instruction::FCmp:
2900 return CmpInst::Create((Instruction::OtherOps)getOpcode(),
2901 (CmpInst::Predicate)getPredicate(), Ops[0], Ops[1]);
2904 assert(getNumOperands() == 2 && "Must be binary operator?");
2905 BinaryOperator *BO =
2906 BinaryOperator::Create((Instruction::BinaryOps)getOpcode(),
2908 if (isa<OverflowingBinaryOperator>(BO)) {
2909 BO->setHasNoUnsignedWrap(SubclassOptionalData &
2910 OverflowingBinaryOperator::NoUnsignedWrap);
2911 BO->setHasNoSignedWrap(SubclassOptionalData &
2912 OverflowingBinaryOperator::NoSignedWrap);
2914 if (isa<PossiblyExactOperator>(BO))
2915 BO->setIsExact(SubclassOptionalData & PossiblyExactOperator::IsExact);