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/DenseMap.h"
18 #include "llvm/ADT/FoldingSet.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/StringMap.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/GetElementPtrTypeIterator.h"
25 #include "llvm/IR/GlobalValue.h"
26 #include "llvm/IR/Instructions.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/Operator.h"
29 #include "llvm/Support/Compiler.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/ManagedStatic.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
39 //===----------------------------------------------------------------------===//
41 //===----------------------------------------------------------------------===//
43 void Constant::anchor() { }
45 bool Constant::isNegativeZeroValue() const {
46 // Floating point values have an explicit -0.0 value.
47 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
48 return CFP->isZero() && CFP->isNegative();
50 // Equivalent for a vector of -0.0's.
51 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(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 // Otherwise, just use +0.0.
75 bool Constant::isNullValue() const {
77 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
81 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
82 return CFP->isZero() && !CFP->isNegative();
84 // constant zero is zero for aggregates, cpnull is null for pointers, none for
86 return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this) ||
87 isa<ConstantTokenNone>(this);
90 bool Constant::isAllOnesValue() const {
91 // Check for -1 integers
92 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
93 return CI->isMinusOne();
95 // Check for FP which are bitcasted from -1 integers
96 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
97 return CFP->getValueAPF().bitcastToAPInt().isAllOnesValue();
99 // Check for constant vectors which are splats of -1 values.
100 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
101 if (Constant *Splat = CV->getSplatValue())
102 return Splat->isAllOnesValue();
104 // Check for constant vectors which are splats of -1 values.
105 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
106 if (Constant *Splat = CV->getSplatValue())
107 return Splat->isAllOnesValue();
112 bool Constant::isOneValue() const {
113 // Check for 1 integers
114 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
117 // Check for FP which are bitcasted from 1 integers
118 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
119 return CFP->getValueAPF().bitcastToAPInt() == 1;
121 // Check for constant vectors which are splats of 1 values.
122 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
123 if (Constant *Splat = CV->getSplatValue())
124 return Splat->isOneValue();
126 // Check for constant vectors which are splats of 1 values.
127 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
128 if (Constant *Splat = CV->getSplatValue())
129 return Splat->isOneValue();
134 bool Constant::isMinSignedValue() const {
135 // Check for INT_MIN integers
136 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
137 return CI->isMinValue(/*isSigned=*/true);
139 // Check for FP which are bitcasted from INT_MIN integers
140 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
141 return CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
143 // Check for constant vectors which are splats of INT_MIN values.
144 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
145 if (Constant *Splat = CV->getSplatValue())
146 return Splat->isMinSignedValue();
148 // Check for constant vectors which are splats of INT_MIN values.
149 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
150 if (Constant *Splat = CV->getSplatValue())
151 return Splat->isMinSignedValue();
156 bool Constant::isNotMinSignedValue() const {
157 // Check for INT_MIN integers
158 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
159 return !CI->isMinValue(/*isSigned=*/true);
161 // Check for FP which are bitcasted from INT_MIN integers
162 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
163 return !CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
165 // Check for constant vectors which are splats of INT_MIN values.
166 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
167 if (Constant *Splat = CV->getSplatValue())
168 return Splat->isNotMinSignedValue();
170 // Check for constant vectors which are splats of INT_MIN values.
171 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
172 if (Constant *Splat = CV->getSplatValue())
173 return Splat->isNotMinSignedValue();
175 // It *may* contain INT_MIN, we can't tell.
179 // Constructor to create a '0' constant of arbitrary type...
180 Constant *Constant::getNullValue(Type *Ty) {
181 switch (Ty->getTypeID()) {
182 case Type::IntegerTyID:
183 return ConstantInt::get(Ty, 0);
185 return ConstantFP::get(Ty->getContext(),
186 APFloat::getZero(APFloat::IEEEhalf));
187 case Type::FloatTyID:
188 return ConstantFP::get(Ty->getContext(),
189 APFloat::getZero(APFloat::IEEEsingle));
190 case Type::DoubleTyID:
191 return ConstantFP::get(Ty->getContext(),
192 APFloat::getZero(APFloat::IEEEdouble));
193 case Type::X86_FP80TyID:
194 return ConstantFP::get(Ty->getContext(),
195 APFloat::getZero(APFloat::x87DoubleExtended));
196 case Type::FP128TyID:
197 return ConstantFP::get(Ty->getContext(),
198 APFloat::getZero(APFloat::IEEEquad));
199 case Type::PPC_FP128TyID:
200 return ConstantFP::get(Ty->getContext(),
201 APFloat(APFloat::PPCDoubleDouble,
202 APInt::getNullValue(128)));
203 case Type::PointerTyID:
204 return ConstantPointerNull::get(cast<PointerType>(Ty));
205 case Type::StructTyID:
206 case Type::ArrayTyID:
207 case Type::VectorTyID:
208 return ConstantAggregateZero::get(Ty);
209 case Type::TokenTyID:
210 return ConstantTokenNone::get(Ty->getContext());
212 // Function, Label, or Opaque type?
213 llvm_unreachable("Cannot create a null constant of that type!");
217 Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) {
218 Type *ScalarTy = Ty->getScalarType();
220 // Create the base integer constant.
221 Constant *C = ConstantInt::get(Ty->getContext(), V);
223 // Convert an integer to a pointer, if necessary.
224 if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
225 C = ConstantExpr::getIntToPtr(C, PTy);
227 // Broadcast a scalar to a vector, if necessary.
228 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
229 C = ConstantVector::getSplat(VTy->getNumElements(), C);
234 Constant *Constant::getAllOnesValue(Type *Ty) {
235 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
236 return ConstantInt::get(Ty->getContext(),
237 APInt::getAllOnesValue(ITy->getBitWidth()));
239 if (Ty->isFloatingPointTy()) {
240 APFloat FL = APFloat::getAllOnesValue(Ty->getPrimitiveSizeInBits(),
241 !Ty->isPPC_FP128Ty());
242 return ConstantFP::get(Ty->getContext(), FL);
245 VectorType *VTy = cast<VectorType>(Ty);
246 return ConstantVector::getSplat(VTy->getNumElements(),
247 getAllOnesValue(VTy->getElementType()));
250 /// getAggregateElement - For aggregates (struct/array/vector) return the
251 /// constant that corresponds to the specified element if possible, or null if
252 /// not. This can return null if the element index is a ConstantExpr, or if
253 /// 'this' is a constant expr.
254 Constant *Constant::getAggregateElement(unsigned Elt) const {
255 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(this))
256 return Elt < CS->getNumOperands() ? CS->getOperand(Elt) : nullptr;
258 if (const ConstantArray *CA = dyn_cast<ConstantArray>(this))
259 return Elt < CA->getNumOperands() ? CA->getOperand(Elt) : nullptr;
261 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
262 return Elt < CV->getNumOperands() ? CV->getOperand(Elt) : nullptr;
264 if (const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(this))
265 return Elt < CAZ->getNumElements() ? CAZ->getElementValue(Elt) : nullptr;
267 if (const UndefValue *UV = dyn_cast<UndefValue>(this))
268 return Elt < UV->getNumElements() ? UV->getElementValue(Elt) : nullptr;
270 if (const ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(this))
271 return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt)
276 Constant *Constant::getAggregateElement(Constant *Elt) const {
277 assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
278 if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt))
279 return getAggregateElement(CI->getZExtValue());
283 void Constant::destroyConstant() {
284 /// First call destroyConstantImpl on the subclass. This gives the subclass
285 /// a chance to remove the constant from any maps/pools it's contained in.
286 switch (getValueID()) {
288 llvm_unreachable("Not a constant!");
289 #define HANDLE_CONSTANT(Name) \
290 case Value::Name##Val: \
291 cast<Name>(this)->destroyConstantImpl(); \
293 #include "llvm/IR/Value.def"
296 // When a Constant is destroyed, there may be lingering
297 // references to the constant by other constants in the constant pool. These
298 // constants are implicitly dependent on the module that is being deleted,
299 // but they don't know that. Because we only find out when the CPV is
300 // deleted, we must now notify all of our users (that should only be
301 // Constants) that they are, in fact, invalid now and should be deleted.
303 while (!use_empty()) {
304 Value *V = user_back();
305 #ifndef NDEBUG // Only in -g mode...
306 if (!isa<Constant>(V)) {
307 dbgs() << "While deleting: " << *this
308 << "\n\nUse still stuck around after Def is destroyed: " << *V
312 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
313 cast<Constant>(V)->destroyConstant();
315 // The constant should remove itself from our use list...
316 assert((use_empty() || user_back() != V) && "Constant not removed!");
319 // Value has no outstanding references it is safe to delete it now...
323 static bool canTrapImpl(const Constant *C,
324 SmallPtrSetImpl<const ConstantExpr *> &NonTrappingOps) {
325 assert(C->getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
326 // The only thing that could possibly trap are constant exprs.
327 const ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
331 // ConstantExpr traps if any operands can trap.
332 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
333 if (ConstantExpr *Op = dyn_cast<ConstantExpr>(CE->getOperand(i))) {
334 if (NonTrappingOps.insert(Op).second && canTrapImpl(Op, NonTrappingOps))
339 // Otherwise, only specific operations can trap.
340 switch (CE->getOpcode()) {
343 case Instruction::UDiv:
344 case Instruction::SDiv:
345 case Instruction::FDiv:
346 case Instruction::URem:
347 case Instruction::SRem:
348 case Instruction::FRem:
349 // Div and rem can trap if the RHS is not known to be non-zero.
350 if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
356 /// canTrap - Return true if evaluation of this constant could trap. This is
357 /// true for things like constant expressions that could divide by zero.
358 bool Constant::canTrap() const {
359 SmallPtrSet<const ConstantExpr *, 4> NonTrappingOps;
360 return canTrapImpl(this, NonTrappingOps);
363 /// Check if C contains a GlobalValue for which Predicate is true.
365 ConstHasGlobalValuePredicate(const Constant *C,
366 bool (*Predicate)(const GlobalValue *)) {
367 SmallPtrSet<const Constant *, 8> Visited;
368 SmallVector<const Constant *, 8> WorkList;
369 WorkList.push_back(C);
372 while (!WorkList.empty()) {
373 const Constant *WorkItem = WorkList.pop_back_val();
374 if (const auto *GV = dyn_cast<GlobalValue>(WorkItem))
377 for (const Value *Op : WorkItem->operands()) {
378 const Constant *ConstOp = dyn_cast<Constant>(Op);
381 if (Visited.insert(ConstOp).second)
382 WorkList.push_back(ConstOp);
388 /// Return true if the value can vary between threads.
389 bool Constant::isThreadDependent() const {
390 auto DLLImportPredicate = [](const GlobalValue *GV) {
391 return GV->isThreadLocal();
393 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
396 bool Constant::isDLLImportDependent() const {
397 auto DLLImportPredicate = [](const GlobalValue *GV) {
398 return GV->hasDLLImportStorageClass();
400 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
403 /// Return true if the constant has users other than constant exprs and other
405 bool Constant::isConstantUsed() const {
406 for (const User *U : users()) {
407 const Constant *UC = dyn_cast<Constant>(U);
408 if (!UC || isa<GlobalValue>(UC))
411 if (UC->isConstantUsed())
417 bool Constant::needsRelocation() const {
418 if (isa<GlobalValue>(this))
419 return true; // Global reference.
421 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
422 return BA->getFunction()->needsRelocation();
424 // While raw uses of blockaddress need to be relocated, differences between
425 // two of them don't when they are for labels in the same function. This is a
426 // common idiom when creating a table for the indirect goto extension, so we
427 // handle it efficiently here.
428 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this))
429 if (CE->getOpcode() == Instruction::Sub) {
430 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
431 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
432 if (LHS && RHS && LHS->getOpcode() == Instruction::PtrToInt &&
433 RHS->getOpcode() == Instruction::PtrToInt &&
434 isa<BlockAddress>(LHS->getOperand(0)) &&
435 isa<BlockAddress>(RHS->getOperand(0)) &&
436 cast<BlockAddress>(LHS->getOperand(0))->getFunction() ==
437 cast<BlockAddress>(RHS->getOperand(0))->getFunction())
442 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
443 Result |= cast<Constant>(getOperand(i))->needsRelocation();
448 /// removeDeadUsersOfConstant - If the specified constantexpr is dead, remove
449 /// it. This involves recursively eliminating any dead users of the
451 static bool removeDeadUsersOfConstant(const Constant *C) {
452 if (isa<GlobalValue>(C)) return false; // Cannot remove this
454 while (!C->use_empty()) {
455 const Constant *User = dyn_cast<Constant>(C->user_back());
456 if (!User) return false; // Non-constant usage;
457 if (!removeDeadUsersOfConstant(User))
458 return false; // Constant wasn't dead
461 const_cast<Constant*>(C)->destroyConstant();
466 /// removeDeadConstantUsers - If there are any dead constant users dangling
467 /// off of this constant, remove them. This method is useful for clients
468 /// that want to check to see if a global is unused, but don't want to deal
469 /// with potentially dead constants hanging off of the globals.
470 void Constant::removeDeadConstantUsers() const {
471 Value::const_user_iterator I = user_begin(), E = user_end();
472 Value::const_user_iterator LastNonDeadUser = E;
474 const Constant *User = dyn_cast<Constant>(*I);
481 if (!removeDeadUsersOfConstant(User)) {
482 // If the constant wasn't dead, remember that this was the last live use
483 // and move on to the next constant.
489 // If the constant was dead, then the iterator is invalidated.
490 if (LastNonDeadUser == E) {
502 //===----------------------------------------------------------------------===//
504 //===----------------------------------------------------------------------===//
506 void ConstantInt::anchor() { }
508 ConstantInt::ConstantInt(IntegerType *Ty, const APInt& V)
509 : Constant(Ty, ConstantIntVal, nullptr, 0), Val(V) {
510 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
513 ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
514 LLVMContextImpl *pImpl = Context.pImpl;
515 if (!pImpl->TheTrueVal)
516 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
517 return pImpl->TheTrueVal;
520 ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
521 LLVMContextImpl *pImpl = Context.pImpl;
522 if (!pImpl->TheFalseVal)
523 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
524 return pImpl->TheFalseVal;
527 Constant *ConstantInt::getTrue(Type *Ty) {
528 VectorType *VTy = dyn_cast<VectorType>(Ty);
530 assert(Ty->isIntegerTy(1) && "True must be i1 or vector of i1.");
531 return ConstantInt::getTrue(Ty->getContext());
533 assert(VTy->getElementType()->isIntegerTy(1) &&
534 "True must be vector of i1 or i1.");
535 return ConstantVector::getSplat(VTy->getNumElements(),
536 ConstantInt::getTrue(Ty->getContext()));
539 Constant *ConstantInt::getFalse(Type *Ty) {
540 VectorType *VTy = dyn_cast<VectorType>(Ty);
542 assert(Ty->isIntegerTy(1) && "False must be i1 or vector of i1.");
543 return ConstantInt::getFalse(Ty->getContext());
545 assert(VTy->getElementType()->isIntegerTy(1) &&
546 "False must be vector of i1 or i1.");
547 return ConstantVector::getSplat(VTy->getNumElements(),
548 ConstantInt::getFalse(Ty->getContext()));
551 // Get a ConstantInt from an APInt.
552 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
553 // get an existing value or the insertion position
554 LLVMContextImpl *pImpl = Context.pImpl;
555 ConstantInt *&Slot = pImpl->IntConstants[V];
557 // Get the corresponding integer type for the bit width of the value.
558 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
559 Slot = new ConstantInt(ITy, V);
561 assert(Slot->getType() == IntegerType::get(Context, V.getBitWidth()));
565 Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
566 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
568 // For vectors, broadcast the value.
569 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
570 return ConstantVector::getSplat(VTy->getNumElements(), C);
575 ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V,
577 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
580 ConstantInt *ConstantInt::getSigned(IntegerType *Ty, int64_t V) {
581 return get(Ty, V, true);
584 Constant *ConstantInt::getSigned(Type *Ty, int64_t V) {
585 return get(Ty, V, true);
588 Constant *ConstantInt::get(Type *Ty, const APInt& V) {
589 ConstantInt *C = get(Ty->getContext(), V);
590 assert(C->getType() == Ty->getScalarType() &&
591 "ConstantInt type doesn't match the type implied by its value!");
593 // For vectors, broadcast the value.
594 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
595 return ConstantVector::getSplat(VTy->getNumElements(), C);
600 ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str,
602 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
605 /// Remove the constant from the constant table.
606 void ConstantInt::destroyConstantImpl() {
607 llvm_unreachable("You can't ConstantInt->destroyConstantImpl()!");
610 //===----------------------------------------------------------------------===//
612 //===----------------------------------------------------------------------===//
614 static const fltSemantics *TypeToFloatSemantics(Type *Ty) {
616 return &APFloat::IEEEhalf;
618 return &APFloat::IEEEsingle;
619 if (Ty->isDoubleTy())
620 return &APFloat::IEEEdouble;
621 if (Ty->isX86_FP80Ty())
622 return &APFloat::x87DoubleExtended;
623 else if (Ty->isFP128Ty())
624 return &APFloat::IEEEquad;
626 assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
627 return &APFloat::PPCDoubleDouble;
630 void ConstantFP::anchor() { }
632 /// get() - This returns a constant fp for the specified value in the
633 /// specified type. This should only be used for simple constant values like
634 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
635 Constant *ConstantFP::get(Type *Ty, double V) {
636 LLVMContext &Context = Ty->getContext();
640 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
641 APFloat::rmNearestTiesToEven, &ignored);
642 Constant *C = get(Context, FV);
644 // For vectors, broadcast the value.
645 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
646 return ConstantVector::getSplat(VTy->getNumElements(), C);
652 Constant *ConstantFP::get(Type *Ty, StringRef Str) {
653 LLVMContext &Context = Ty->getContext();
655 APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
656 Constant *C = get(Context, FV);
658 // For vectors, broadcast the value.
659 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
660 return ConstantVector::getSplat(VTy->getNumElements(), C);
665 Constant *ConstantFP::getNaN(Type *Ty, bool Negative, unsigned Type) {
666 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
667 APFloat NaN = APFloat::getNaN(Semantics, Negative, Type);
668 Constant *C = get(Ty->getContext(), NaN);
670 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
671 return ConstantVector::getSplat(VTy->getNumElements(), C);
676 Constant *ConstantFP::getNegativeZero(Type *Ty) {
677 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
678 APFloat NegZero = APFloat::getZero(Semantics, /*Negative=*/true);
679 Constant *C = get(Ty->getContext(), NegZero);
681 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
682 return ConstantVector::getSplat(VTy->getNumElements(), C);
688 Constant *ConstantFP::getZeroValueForNegation(Type *Ty) {
689 if (Ty->isFPOrFPVectorTy())
690 return getNegativeZero(Ty);
692 return Constant::getNullValue(Ty);
696 // ConstantFP accessors.
697 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
698 LLVMContextImpl* pImpl = Context.pImpl;
700 ConstantFP *&Slot = pImpl->FPConstants[V];
704 if (&V.getSemantics() == &APFloat::IEEEhalf)
705 Ty = Type::getHalfTy(Context);
706 else if (&V.getSemantics() == &APFloat::IEEEsingle)
707 Ty = Type::getFloatTy(Context);
708 else if (&V.getSemantics() == &APFloat::IEEEdouble)
709 Ty = Type::getDoubleTy(Context);
710 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
711 Ty = Type::getX86_FP80Ty(Context);
712 else if (&V.getSemantics() == &APFloat::IEEEquad)
713 Ty = Type::getFP128Ty(Context);
715 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
716 "Unknown FP format");
717 Ty = Type::getPPC_FP128Ty(Context);
719 Slot = new ConstantFP(Ty, V);
725 Constant *ConstantFP::getInfinity(Type *Ty, bool Negative) {
726 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
727 Constant *C = get(Ty->getContext(), APFloat::getInf(Semantics, Negative));
729 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
730 return ConstantVector::getSplat(VTy->getNumElements(), C);
735 ConstantFP::ConstantFP(Type *Ty, const APFloat& V)
736 : Constant(Ty, ConstantFPVal, nullptr, 0), Val(V) {
737 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
741 bool ConstantFP::isExactlyValue(const APFloat &V) const {
742 return Val.bitwiseIsEqual(V);
745 /// Remove the constant from the constant table.
746 void ConstantFP::destroyConstantImpl() {
747 llvm_unreachable("You can't ConstantInt->destroyConstantImpl()!");
750 //===----------------------------------------------------------------------===//
751 // ConstantAggregateZero Implementation
752 //===----------------------------------------------------------------------===//
754 /// getSequentialElement - If this CAZ has array or vector type, return a zero
755 /// with the right element type.
756 Constant *ConstantAggregateZero::getSequentialElement() const {
757 return Constant::getNullValue(getType()->getSequentialElementType());
760 /// getStructElement - If this CAZ has struct type, return a zero with the
761 /// right element type for the specified element.
762 Constant *ConstantAggregateZero::getStructElement(unsigned Elt) const {
763 return Constant::getNullValue(getType()->getStructElementType(Elt));
766 /// getElementValue - Return a zero of the right value for the specified GEP
767 /// index if we can, otherwise return null (e.g. if C is a ConstantExpr).
768 Constant *ConstantAggregateZero::getElementValue(Constant *C) const {
769 if (isa<SequentialType>(getType()))
770 return getSequentialElement();
771 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
774 /// getElementValue - Return a zero of the right value for the specified GEP
776 Constant *ConstantAggregateZero::getElementValue(unsigned Idx) const {
777 if (isa<SequentialType>(getType()))
778 return getSequentialElement();
779 return getStructElement(Idx);
782 unsigned ConstantAggregateZero::getNumElements() const {
783 Type *Ty = getType();
784 if (auto *AT = dyn_cast<ArrayType>(Ty))
785 return AT->getNumElements();
786 if (auto *VT = dyn_cast<VectorType>(Ty))
787 return VT->getNumElements();
788 return Ty->getStructNumElements();
791 //===----------------------------------------------------------------------===//
792 // UndefValue Implementation
793 //===----------------------------------------------------------------------===//
795 /// getSequentialElement - If this undef has array or vector type, return an
796 /// undef with the right element type.
797 UndefValue *UndefValue::getSequentialElement() const {
798 return UndefValue::get(getType()->getSequentialElementType());
801 /// getStructElement - If this undef has struct type, return a zero with the
802 /// right element type for the specified element.
803 UndefValue *UndefValue::getStructElement(unsigned Elt) const {
804 return UndefValue::get(getType()->getStructElementType(Elt));
807 /// getElementValue - Return an undef of the right value for the specified GEP
808 /// index if we can, otherwise return null (e.g. if C is a ConstantExpr).
809 UndefValue *UndefValue::getElementValue(Constant *C) const {
810 if (isa<SequentialType>(getType()))
811 return getSequentialElement();
812 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
815 /// getElementValue - Return an undef of the right value for the specified GEP
817 UndefValue *UndefValue::getElementValue(unsigned Idx) const {
818 if (isa<SequentialType>(getType()))
819 return getSequentialElement();
820 return getStructElement(Idx);
823 unsigned UndefValue::getNumElements() const {
824 Type *Ty = getType();
825 if (auto *AT = dyn_cast<ArrayType>(Ty))
826 return AT->getNumElements();
827 if (auto *VT = dyn_cast<VectorType>(Ty))
828 return VT->getNumElements();
829 return Ty->getStructNumElements();
832 //===----------------------------------------------------------------------===//
833 // ConstantXXX Classes
834 //===----------------------------------------------------------------------===//
836 template <typename ItTy, typename EltTy>
837 static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
838 for (; Start != End; ++Start)
844 ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
845 : Constant(T, ConstantArrayVal,
846 OperandTraits<ConstantArray>::op_end(this) - V.size(),
848 assert(V.size() == T->getNumElements() &&
849 "Invalid initializer vector for constant array");
850 for (unsigned i = 0, e = V.size(); i != e; ++i)
851 assert(V[i]->getType() == T->getElementType() &&
852 "Initializer for array element doesn't match array element type!");
853 std::copy(V.begin(), V.end(), op_begin());
856 Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
857 if (Constant *C = getImpl(Ty, V))
859 return Ty->getContext().pImpl->ArrayConstants.getOrCreate(Ty, V);
861 Constant *ConstantArray::getImpl(ArrayType *Ty, ArrayRef<Constant*> V) {
862 // Empty arrays are canonicalized to ConstantAggregateZero.
864 return ConstantAggregateZero::get(Ty);
866 for (unsigned i = 0, e = V.size(); i != e; ++i) {
867 assert(V[i]->getType() == Ty->getElementType() &&
868 "Wrong type in array element initializer");
871 // If this is an all-zero array, return a ConstantAggregateZero object. If
872 // all undef, return an UndefValue, if "all simple", then return a
873 // ConstantDataArray.
875 if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
876 return UndefValue::get(Ty);
878 if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
879 return ConstantAggregateZero::get(Ty);
881 // Check to see if all of the elements are ConstantFP or ConstantInt and if
882 // the element type is compatible with ConstantDataVector. If so, use it.
883 if (ConstantDataSequential::isElementTypeCompatible(C->getType())) {
884 // We speculatively build the elements here even if it turns out that there
885 // is a constantexpr or something else weird in the array, since it is so
886 // uncommon for that to happen.
887 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
888 if (CI->getType()->isIntegerTy(8)) {
889 SmallVector<uint8_t, 16> Elts;
890 for (unsigned i = 0, e = V.size(); i != e; ++i)
891 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
892 Elts.push_back(CI->getZExtValue());
895 if (Elts.size() == V.size())
896 return ConstantDataArray::get(C->getContext(), Elts);
897 } else if (CI->getType()->isIntegerTy(16)) {
898 SmallVector<uint16_t, 16> Elts;
899 for (unsigned i = 0, e = V.size(); i != e; ++i)
900 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
901 Elts.push_back(CI->getZExtValue());
904 if (Elts.size() == V.size())
905 return ConstantDataArray::get(C->getContext(), Elts);
906 } else if (CI->getType()->isIntegerTy(32)) {
907 SmallVector<uint32_t, 16> Elts;
908 for (unsigned i = 0, e = V.size(); i != e; ++i)
909 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
910 Elts.push_back(CI->getZExtValue());
913 if (Elts.size() == V.size())
914 return ConstantDataArray::get(C->getContext(), Elts);
915 } else if (CI->getType()->isIntegerTy(64)) {
916 SmallVector<uint64_t, 16> Elts;
917 for (unsigned i = 0, e = V.size(); i != e; ++i)
918 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
919 Elts.push_back(CI->getZExtValue());
922 if (Elts.size() == V.size())
923 return ConstantDataArray::get(C->getContext(), Elts);
927 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
928 if (CFP->getType()->isFloatTy()) {
929 SmallVector<uint32_t, 16> Elts;
930 for (unsigned i = 0, e = V.size(); i != e; ++i)
931 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
933 CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
936 if (Elts.size() == V.size())
937 return ConstantDataArray::getFP(C->getContext(), Elts);
938 } else if (CFP->getType()->isDoubleTy()) {
939 SmallVector<uint64_t, 16> Elts;
940 for (unsigned i = 0, e = V.size(); i != e; ++i)
941 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
943 CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
946 if (Elts.size() == V.size())
947 return ConstantDataArray::getFP(C->getContext(), Elts);
952 // Otherwise, we really do want to create a ConstantArray.
956 /// getTypeForElements - Return an anonymous struct type to use for a constant
957 /// with the specified set of elements. The list must not be empty.
958 StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
959 ArrayRef<Constant*> V,
961 unsigned VecSize = V.size();
962 SmallVector<Type*, 16> EltTypes(VecSize);
963 for (unsigned i = 0; i != VecSize; ++i)
964 EltTypes[i] = V[i]->getType();
966 return StructType::get(Context, EltTypes, Packed);
970 StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
973 "ConstantStruct::getTypeForElements cannot be called on empty list");
974 return getTypeForElements(V[0]->getContext(), V, Packed);
978 ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
979 : Constant(T, ConstantStructVal,
980 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
982 assert(V.size() == T->getNumElements() &&
983 "Invalid initializer vector for constant structure");
984 for (unsigned i = 0, e = V.size(); i != e; ++i)
985 assert((T->isOpaque() || V[i]->getType() == T->getElementType(i)) &&
986 "Initializer for struct element doesn't match struct element type!");
987 std::copy(V.begin(), V.end(), op_begin());
990 // ConstantStruct accessors.
991 Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
992 assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
993 "Incorrect # elements specified to ConstantStruct::get");
995 // Create a ConstantAggregateZero value if all elements are zeros.
997 bool isUndef = false;
1000 isUndef = isa<UndefValue>(V[0]);
1001 isZero = V[0]->isNullValue();
1002 if (isUndef || isZero) {
1003 for (unsigned i = 0, e = V.size(); i != e; ++i) {
1004 if (!V[i]->isNullValue())
1006 if (!isa<UndefValue>(V[i]))
1012 return ConstantAggregateZero::get(ST);
1014 return UndefValue::get(ST);
1016 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
1019 Constant *ConstantStruct::get(StructType *T, ...) {
1021 SmallVector<Constant*, 8> Values;
1023 while (Constant *Val = va_arg(ap, llvm::Constant*))
1024 Values.push_back(Val);
1026 return get(T, Values);
1029 ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
1030 : Constant(T, ConstantVectorVal,
1031 OperandTraits<ConstantVector>::op_end(this) - V.size(),
1033 for (size_t i = 0, e = V.size(); i != e; i++)
1034 assert(V[i]->getType() == T->getElementType() &&
1035 "Initializer for vector element doesn't match vector element type!");
1036 std::copy(V.begin(), V.end(), op_begin());
1039 // ConstantVector accessors.
1040 Constant *ConstantVector::get(ArrayRef<Constant*> V) {
1041 if (Constant *C = getImpl(V))
1043 VectorType *Ty = VectorType::get(V.front()->getType(), V.size());
1044 return Ty->getContext().pImpl->VectorConstants.getOrCreate(Ty, V);
1046 Constant *ConstantVector::getImpl(ArrayRef<Constant*> V) {
1047 assert(!V.empty() && "Vectors can't be empty");
1048 VectorType *T = VectorType::get(V.front()->getType(), V.size());
1050 // If this is an all-undef or all-zero vector, return a
1051 // ConstantAggregateZero or UndefValue.
1053 bool isZero = C->isNullValue();
1054 bool isUndef = isa<UndefValue>(C);
1056 if (isZero || isUndef) {
1057 for (unsigned i = 1, e = V.size(); i != e; ++i)
1059 isZero = isUndef = false;
1065 return ConstantAggregateZero::get(T);
1067 return UndefValue::get(T);
1069 // Check to see if all of the elements are ConstantFP or ConstantInt and if
1070 // the element type is compatible with ConstantDataVector. If so, use it.
1071 if (ConstantDataSequential::isElementTypeCompatible(C->getType())) {
1072 // We speculatively build the elements here even if it turns out that there
1073 // is a constantexpr or something else weird in the array, since it is so
1074 // uncommon for that to happen.
1075 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
1076 if (CI->getType()->isIntegerTy(8)) {
1077 SmallVector<uint8_t, 16> Elts;
1078 for (unsigned i = 0, e = V.size(); i != e; ++i)
1079 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
1080 Elts.push_back(CI->getZExtValue());
1083 if (Elts.size() == V.size())
1084 return ConstantDataVector::get(C->getContext(), Elts);
1085 } else if (CI->getType()->isIntegerTy(16)) {
1086 SmallVector<uint16_t, 16> Elts;
1087 for (unsigned i = 0, e = V.size(); i != e; ++i)
1088 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
1089 Elts.push_back(CI->getZExtValue());
1092 if (Elts.size() == V.size())
1093 return ConstantDataVector::get(C->getContext(), Elts);
1094 } else if (CI->getType()->isIntegerTy(32)) {
1095 SmallVector<uint32_t, 16> Elts;
1096 for (unsigned i = 0, e = V.size(); i != e; ++i)
1097 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
1098 Elts.push_back(CI->getZExtValue());
1101 if (Elts.size() == V.size())
1102 return ConstantDataVector::get(C->getContext(), Elts);
1103 } else if (CI->getType()->isIntegerTy(64)) {
1104 SmallVector<uint64_t, 16> Elts;
1105 for (unsigned i = 0, e = V.size(); i != e; ++i)
1106 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
1107 Elts.push_back(CI->getZExtValue());
1110 if (Elts.size() == V.size())
1111 return ConstantDataVector::get(C->getContext(), Elts);
1115 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
1116 if (CFP->getType()->isFloatTy()) {
1117 SmallVector<uint32_t, 16> Elts;
1118 for (unsigned i = 0, e = V.size(); i != e; ++i)
1119 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
1121 CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
1124 if (Elts.size() == V.size())
1125 return ConstantDataVector::getFP(C->getContext(), Elts);
1126 } else if (CFP->getType()->isDoubleTy()) {
1127 SmallVector<uint64_t, 16> Elts;
1128 for (unsigned i = 0, e = V.size(); i != e; ++i)
1129 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
1131 CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
1134 if (Elts.size() == V.size())
1135 return ConstantDataVector::getFP(C->getContext(), Elts);
1140 // Otherwise, the element type isn't compatible with ConstantDataVector, or
1141 // the operand list constants a ConstantExpr or something else strange.
1145 Constant *ConstantVector::getSplat(unsigned NumElts, Constant *V) {
1146 // If this splat is compatible with ConstantDataVector, use it instead of
1148 if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&
1149 ConstantDataSequential::isElementTypeCompatible(V->getType()))
1150 return ConstantDataVector::getSplat(NumElts, V);
1152 SmallVector<Constant*, 32> Elts(NumElts, V);
1156 ConstantTokenNone *ConstantTokenNone::get(LLVMContext &Context) {
1157 LLVMContextImpl *pImpl = Context.pImpl;
1158 if (!pImpl->TheNoneToken)
1159 pImpl->TheNoneToken.reset(new ConstantTokenNone(Context));
1160 return pImpl->TheNoneToken.get();
1163 /// Remove the constant from the constant table.
1164 void ConstantTokenNone::destroyConstantImpl() {
1165 llvm_unreachable("You can't ConstantTokenNone->destroyConstantImpl()!");
1168 // Utility function for determining if a ConstantExpr is a CastOp or not. This
1169 // can't be inline because we don't want to #include Instruction.h into
1171 bool ConstantExpr::isCast() const {
1172 return Instruction::isCast(getOpcode());
1175 bool ConstantExpr::isCompare() const {
1176 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
1179 bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
1180 if (getOpcode() != Instruction::GetElementPtr) return false;
1182 gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
1183 User::const_op_iterator OI = std::next(this->op_begin());
1185 // Skip the first index, as it has no static limit.
1189 // The remaining indices must be compile-time known integers within the
1190 // bounds of the corresponding notional static array types.
1191 for (; GEPI != E; ++GEPI, ++OI) {
1192 ConstantInt *CI = dyn_cast<ConstantInt>(*OI);
1193 if (!CI) return false;
1194 if (ArrayType *ATy = dyn_cast<ArrayType>(*GEPI))
1195 if (CI->getValue().getActiveBits() > 64 ||
1196 CI->getZExtValue() >= ATy->getNumElements())
1200 // All the indices checked out.
1204 bool ConstantExpr::hasIndices() const {
1205 return getOpcode() == Instruction::ExtractValue ||
1206 getOpcode() == Instruction::InsertValue;
1209 ArrayRef<unsigned> ConstantExpr::getIndices() const {
1210 if (const ExtractValueConstantExpr *EVCE =
1211 dyn_cast<ExtractValueConstantExpr>(this))
1212 return EVCE->Indices;
1214 return cast<InsertValueConstantExpr>(this)->Indices;
1217 unsigned ConstantExpr::getPredicate() const {
1218 assert(isCompare());
1219 return ((const CompareConstantExpr*)this)->predicate;
1222 /// getWithOperandReplaced - Return a constant expression identical to this
1223 /// one, but with the specified operand set to the specified value.
1225 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
1226 assert(Op->getType() == getOperand(OpNo)->getType() &&
1227 "Replacing operand with value of different type!");
1228 if (getOperand(OpNo) == Op)
1229 return const_cast<ConstantExpr*>(this);
1231 SmallVector<Constant*, 8> NewOps;
1232 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1233 NewOps.push_back(i == OpNo ? Op : getOperand(i));
1235 return getWithOperands(NewOps);
1238 /// getWithOperands - This returns the current constant expression with the
1239 /// operands replaced with the specified values. The specified array must
1240 /// have the same number of operands as our current one.
1241 Constant *ConstantExpr::getWithOperands(ArrayRef<Constant *> Ops, Type *Ty,
1242 bool OnlyIfReduced, Type *SrcTy) const {
1243 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
1245 // If no operands changed return self.
1246 if (Ty == getType() && std::equal(Ops.begin(), Ops.end(), op_begin()))
1247 return const_cast<ConstantExpr*>(this);
1249 Type *OnlyIfReducedTy = OnlyIfReduced ? Ty : nullptr;
1250 switch (getOpcode()) {
1251 case Instruction::Trunc:
1252 case Instruction::ZExt:
1253 case Instruction::SExt:
1254 case Instruction::FPTrunc:
1255 case Instruction::FPExt:
1256 case Instruction::UIToFP:
1257 case Instruction::SIToFP:
1258 case Instruction::FPToUI:
1259 case Instruction::FPToSI:
1260 case Instruction::PtrToInt:
1261 case Instruction::IntToPtr:
1262 case Instruction::BitCast:
1263 case Instruction::AddrSpaceCast:
1264 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty, OnlyIfReduced);
1265 case Instruction::Select:
1266 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2], OnlyIfReducedTy);
1267 case Instruction::InsertElement:
1268 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2],
1270 case Instruction::ExtractElement:
1271 return ConstantExpr::getExtractElement(Ops[0], Ops[1], OnlyIfReducedTy);
1272 case Instruction::InsertValue:
1273 return ConstantExpr::getInsertValue(Ops[0], Ops[1], getIndices(),
1275 case Instruction::ExtractValue:
1276 return ConstantExpr::getExtractValue(Ops[0], getIndices(), OnlyIfReducedTy);
1277 case Instruction::ShuffleVector:
1278 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2],
1280 case Instruction::GetElementPtr: {
1281 auto *GEPO = cast<GEPOperator>(this);
1282 assert(SrcTy || (Ops[0]->getType() == getOperand(0)->getType()));
1283 return ConstantExpr::getGetElementPtr(
1284 SrcTy ? SrcTy : GEPO->getSourceElementType(), Ops[0], Ops.slice(1),
1285 GEPO->isInBounds(), OnlyIfReducedTy);
1287 case Instruction::ICmp:
1288 case Instruction::FCmp:
1289 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1],
1292 assert(getNumOperands() == 2 && "Must be binary operator?");
1293 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData,
1299 //===----------------------------------------------------------------------===//
1300 // isValueValidForType implementations
1302 bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
1303 unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
1304 if (Ty->isIntegerTy(1))
1305 return Val == 0 || Val == 1;
1307 return true; // always true, has to fit in largest type
1308 uint64_t Max = (1ll << NumBits) - 1;
1312 bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
1313 unsigned NumBits = Ty->getIntegerBitWidth();
1314 if (Ty->isIntegerTy(1))
1315 return Val == 0 || Val == 1 || Val == -1;
1317 return true; // always true, has to fit in largest type
1318 int64_t Min = -(1ll << (NumBits-1));
1319 int64_t Max = (1ll << (NumBits-1)) - 1;
1320 return (Val >= Min && Val <= Max);
1323 bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {
1324 // convert modifies in place, so make a copy.
1325 APFloat Val2 = APFloat(Val);
1327 switch (Ty->getTypeID()) {
1329 return false; // These can't be represented as floating point!
1331 // FIXME rounding mode needs to be more flexible
1332 case Type::HalfTyID: {
1333 if (&Val2.getSemantics() == &APFloat::IEEEhalf)
1335 Val2.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &losesInfo);
1338 case Type::FloatTyID: {
1339 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
1341 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
1344 case Type::DoubleTyID: {
1345 if (&Val2.getSemantics() == &APFloat::IEEEhalf ||
1346 &Val2.getSemantics() == &APFloat::IEEEsingle ||
1347 &Val2.getSemantics() == &APFloat::IEEEdouble)
1349 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
1352 case Type::X86_FP80TyID:
1353 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1354 &Val2.getSemantics() == &APFloat::IEEEsingle ||
1355 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1356 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
1357 case Type::FP128TyID:
1358 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1359 &Val2.getSemantics() == &APFloat::IEEEsingle ||
1360 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1361 &Val2.getSemantics() == &APFloat::IEEEquad;
1362 case Type::PPC_FP128TyID:
1363 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1364 &Val2.getSemantics() == &APFloat::IEEEsingle ||
1365 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1366 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
1371 //===----------------------------------------------------------------------===//
1372 // Factory Function Implementation
1374 ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
1375 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
1376 "Cannot create an aggregate zero of non-aggregate type!");
1378 ConstantAggregateZero *&Entry = Ty->getContext().pImpl->CAZConstants[Ty];
1380 Entry = new ConstantAggregateZero(Ty);
1385 /// destroyConstant - Remove the constant from the constant table.
1387 void ConstantAggregateZero::destroyConstantImpl() {
1388 getContext().pImpl->CAZConstants.erase(getType());
1391 /// destroyConstant - Remove the constant from the constant table...
1393 void ConstantArray::destroyConstantImpl() {
1394 getType()->getContext().pImpl->ArrayConstants.remove(this);
1398 //---- ConstantStruct::get() implementation...
1401 // destroyConstant - Remove the constant from the constant table...
1403 void ConstantStruct::destroyConstantImpl() {
1404 getType()->getContext().pImpl->StructConstants.remove(this);
1407 // destroyConstant - Remove the constant from the constant table...
1409 void ConstantVector::destroyConstantImpl() {
1410 getType()->getContext().pImpl->VectorConstants.remove(this);
1413 /// getSplatValue - If this is a splat vector constant, meaning that all of
1414 /// the elements have the same value, return that value. Otherwise return 0.
1415 Constant *Constant::getSplatValue() const {
1416 assert(this->getType()->isVectorTy() && "Only valid for vectors!");
1417 if (isa<ConstantAggregateZero>(this))
1418 return getNullValue(this->getType()->getVectorElementType());
1419 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
1420 return CV->getSplatValue();
1421 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
1422 return CV->getSplatValue();
1426 /// getSplatValue - If this is a splat constant, where all of the
1427 /// elements have the same value, return that value. Otherwise return null.
1428 Constant *ConstantVector::getSplatValue() const {
1429 // Check out first element.
1430 Constant *Elt = getOperand(0);
1431 // Then make sure all remaining elements point to the same value.
1432 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1433 if (getOperand(I) != Elt)
1438 /// If C is a constant integer then return its value, otherwise C must be a
1439 /// vector of constant integers, all equal, and the common value is returned.
1440 const APInt &Constant::getUniqueInteger() const {
1441 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
1442 return CI->getValue();
1443 assert(this->getSplatValue() && "Doesn't contain a unique integer!");
1444 const Constant *C = this->getAggregateElement(0U);
1445 assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
1446 return cast<ConstantInt>(C)->getValue();
1449 //---- ConstantPointerNull::get() implementation.
1452 ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
1453 ConstantPointerNull *&Entry = Ty->getContext().pImpl->CPNConstants[Ty];
1455 Entry = new ConstantPointerNull(Ty);
1460 // destroyConstant - Remove the constant from the constant table...
1462 void ConstantPointerNull::destroyConstantImpl() {
1463 getContext().pImpl->CPNConstants.erase(getType());
1467 //---- UndefValue::get() implementation.
1470 UndefValue *UndefValue::get(Type *Ty) {
1471 UndefValue *&Entry = Ty->getContext().pImpl->UVConstants[Ty];
1473 Entry = new UndefValue(Ty);
1478 // destroyConstant - Remove the constant from the constant table.
1480 void UndefValue::destroyConstantImpl() {
1481 // Free the constant and any dangling references to it.
1482 getContext().pImpl->UVConstants.erase(getType());
1485 //---- BlockAddress::get() implementation.
1488 BlockAddress *BlockAddress::get(BasicBlock *BB) {
1489 assert(BB->getParent() && "Block must have a parent");
1490 return get(BB->getParent(), BB);
1493 BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1495 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
1497 BA = new BlockAddress(F, BB);
1499 assert(BA->getFunction() == F && "Basic block moved between functions");
1503 BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1504 : Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1508 BB->AdjustBlockAddressRefCount(1);
1511 BlockAddress *BlockAddress::lookup(const BasicBlock *BB) {
1512 if (!BB->hasAddressTaken())
1515 const Function *F = BB->getParent();
1516 assert(F && "Block must have a parent");
1518 F->getContext().pImpl->BlockAddresses.lookup(std::make_pair(F, BB));
1519 assert(BA && "Refcount and block address map disagree!");
1523 // destroyConstant - Remove the constant from the constant table.
1525 void BlockAddress::destroyConstantImpl() {
1526 getFunction()->getType()->getContext().pImpl
1527 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
1528 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1531 Value *BlockAddress::handleOperandChangeImpl(Value *From, Value *To, Use *U) {
1532 // This could be replacing either the Basic Block or the Function. In either
1533 // case, we have to remove the map entry.
1534 Function *NewF = getFunction();
1535 BasicBlock *NewBB = getBasicBlock();
1538 NewF = cast<Function>(To->stripPointerCasts());
1540 NewBB = cast<BasicBlock>(To);
1542 // See if the 'new' entry already exists, if not, just update this in place
1543 // and return early.
1544 BlockAddress *&NewBA =
1545 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
1549 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1551 // Remove the old entry, this can't cause the map to rehash (just a
1552 // tombstone will get added).
1553 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1556 setOperand(0, NewF);
1557 setOperand(1, NewBB);
1558 getBasicBlock()->AdjustBlockAddressRefCount(1);
1560 // If we just want to keep the existing value, then return null.
1561 // Callers know that this means we shouldn't delete this value.
1565 //---- ConstantExpr::get() implementations.
1568 /// This is a utility function to handle folding of casts and lookup of the
1569 /// cast in the ExprConstants map. It is used by the various get* methods below.
1570 static Constant *getFoldedCast(Instruction::CastOps opc, Constant *C, Type *Ty,
1571 bool OnlyIfReduced = false) {
1572 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1573 // Fold a few common cases
1574 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1580 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1582 // Look up the constant in the table first to ensure uniqueness.
1583 ConstantExprKeyType Key(opc, C);
1585 return pImpl->ExprConstants.getOrCreate(Ty, Key);
1588 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty,
1589 bool OnlyIfReduced) {
1590 Instruction::CastOps opc = Instruction::CastOps(oc);
1591 assert(Instruction::isCast(opc) && "opcode out of range");
1592 assert(C && Ty && "Null arguments to getCast");
1593 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
1597 llvm_unreachable("Invalid cast opcode");
1598 case Instruction::Trunc:
1599 return getTrunc(C, Ty, OnlyIfReduced);
1600 case Instruction::ZExt:
1601 return getZExt(C, Ty, OnlyIfReduced);
1602 case Instruction::SExt:
1603 return getSExt(C, Ty, OnlyIfReduced);
1604 case Instruction::FPTrunc:
1605 return getFPTrunc(C, Ty, OnlyIfReduced);
1606 case Instruction::FPExt:
1607 return getFPExtend(C, Ty, OnlyIfReduced);
1608 case Instruction::UIToFP:
1609 return getUIToFP(C, Ty, OnlyIfReduced);
1610 case Instruction::SIToFP:
1611 return getSIToFP(C, Ty, OnlyIfReduced);
1612 case Instruction::FPToUI:
1613 return getFPToUI(C, Ty, OnlyIfReduced);
1614 case Instruction::FPToSI:
1615 return getFPToSI(C, Ty, OnlyIfReduced);
1616 case Instruction::PtrToInt:
1617 return getPtrToInt(C, Ty, OnlyIfReduced);
1618 case Instruction::IntToPtr:
1619 return getIntToPtr(C, Ty, OnlyIfReduced);
1620 case Instruction::BitCast:
1621 return getBitCast(C, Ty, OnlyIfReduced);
1622 case Instruction::AddrSpaceCast:
1623 return getAddrSpaceCast(C, Ty, OnlyIfReduced);
1627 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) {
1628 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1629 return getBitCast(C, Ty);
1630 return getZExt(C, Ty);
1633 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) {
1634 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1635 return getBitCast(C, Ty);
1636 return getSExt(C, Ty);
1639 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {
1640 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1641 return getBitCast(C, Ty);
1642 return getTrunc(C, Ty);
1645 Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {
1646 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1647 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
1650 if (Ty->isIntOrIntVectorTy())
1651 return getPtrToInt(S, Ty);
1653 unsigned SrcAS = S->getType()->getPointerAddressSpace();
1654 if (Ty->isPtrOrPtrVectorTy() && SrcAS != Ty->getPointerAddressSpace())
1655 return getAddrSpaceCast(S, Ty);
1657 return getBitCast(S, Ty);
1660 Constant *ConstantExpr::getPointerBitCastOrAddrSpaceCast(Constant *S,
1662 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1663 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
1665 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
1666 return getAddrSpaceCast(S, Ty);
1668 return getBitCast(S, Ty);
1671 Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty,
1673 assert(C->getType()->isIntOrIntVectorTy() &&
1674 Ty->isIntOrIntVectorTy() && "Invalid cast");
1675 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1676 unsigned DstBits = Ty->getScalarSizeInBits();
1677 Instruction::CastOps opcode =
1678 (SrcBits == DstBits ? Instruction::BitCast :
1679 (SrcBits > DstBits ? Instruction::Trunc :
1680 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1681 return getCast(opcode, C, Ty);
1684 Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) {
1685 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1687 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1688 unsigned DstBits = Ty->getScalarSizeInBits();
1689 if (SrcBits == DstBits)
1690 return C; // Avoid a useless cast
1691 Instruction::CastOps opcode =
1692 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1693 return getCast(opcode, C, Ty);
1696 Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
1698 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1699 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1701 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1702 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
1703 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
1704 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1705 "SrcTy must be larger than DestTy for Trunc!");
1707 return getFoldedCast(Instruction::Trunc, C, Ty, OnlyIfReduced);
1710 Constant *ConstantExpr::getSExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
1712 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1713 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1715 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1716 assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
1717 assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
1718 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1719 "SrcTy must be smaller than DestTy for SExt!");
1721 return getFoldedCast(Instruction::SExt, C, Ty, OnlyIfReduced);
1724 Constant *ConstantExpr::getZExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
1726 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1727 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1729 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1730 assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
1731 assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
1732 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1733 "SrcTy must be smaller than DestTy for ZExt!");
1735 return getFoldedCast(Instruction::ZExt, C, Ty, OnlyIfReduced);
1738 Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
1740 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1741 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1743 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1744 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1745 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1746 "This is an illegal floating point truncation!");
1747 return getFoldedCast(Instruction::FPTrunc, C, Ty, OnlyIfReduced);
1750 Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty, bool OnlyIfReduced) {
1752 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1753 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1755 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1756 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1757 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1758 "This is an illegal floating point extension!");
1759 return getFoldedCast(Instruction::FPExt, C, Ty, OnlyIfReduced);
1762 Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
1764 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1765 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1767 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1768 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1769 "This is an illegal uint to floating point cast!");
1770 return getFoldedCast(Instruction::UIToFP, C, Ty, OnlyIfReduced);
1773 Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
1775 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1776 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1778 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1779 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1780 "This is an illegal sint to floating point cast!");
1781 return getFoldedCast(Instruction::SIToFP, C, Ty, OnlyIfReduced);
1784 Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty, bool OnlyIfReduced) {
1786 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1787 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1789 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1790 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1791 "This is an illegal floating point to uint cast!");
1792 return getFoldedCast(Instruction::FPToUI, C, Ty, OnlyIfReduced);
1795 Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty, bool OnlyIfReduced) {
1797 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1798 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1800 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1801 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1802 "This is an illegal floating point to sint cast!");
1803 return getFoldedCast(Instruction::FPToSI, C, Ty, OnlyIfReduced);
1806 Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy,
1807 bool OnlyIfReduced) {
1808 assert(C->getType()->getScalarType()->isPointerTy() &&
1809 "PtrToInt source must be pointer or pointer vector");
1810 assert(DstTy->getScalarType()->isIntegerTy() &&
1811 "PtrToInt destination must be integer or integer vector");
1812 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
1813 if (isa<VectorType>(C->getType()))
1814 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
1815 "Invalid cast between a different number of vector elements");
1816 return getFoldedCast(Instruction::PtrToInt, C, DstTy, OnlyIfReduced);
1819 Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy,
1820 bool OnlyIfReduced) {
1821 assert(C->getType()->getScalarType()->isIntegerTy() &&
1822 "IntToPtr source must be integer or integer vector");
1823 assert(DstTy->getScalarType()->isPointerTy() &&
1824 "IntToPtr destination must be a pointer or pointer vector");
1825 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
1826 if (isa<VectorType>(C->getType()))
1827 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
1828 "Invalid cast between a different number of vector elements");
1829 return getFoldedCast(Instruction::IntToPtr, C, DstTy, OnlyIfReduced);
1832 Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy,
1833 bool OnlyIfReduced) {
1834 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
1835 "Invalid constantexpr bitcast!");
1837 // It is common to ask for a bitcast of a value to its own type, handle this
1839 if (C->getType() == DstTy) return C;
1841 return getFoldedCast(Instruction::BitCast, C, DstTy, OnlyIfReduced);
1844 Constant *ConstantExpr::getAddrSpaceCast(Constant *C, Type *DstTy,
1845 bool OnlyIfReduced) {
1846 assert(CastInst::castIsValid(Instruction::AddrSpaceCast, C, DstTy) &&
1847 "Invalid constantexpr addrspacecast!");
1849 // Canonicalize addrspacecasts between different pointer types by first
1850 // bitcasting the pointer type and then converting the address space.
1851 PointerType *SrcScalarTy = cast<PointerType>(C->getType()->getScalarType());
1852 PointerType *DstScalarTy = cast<PointerType>(DstTy->getScalarType());
1853 Type *DstElemTy = DstScalarTy->getElementType();
1854 if (SrcScalarTy->getElementType() != DstElemTy) {
1855 Type *MidTy = PointerType::get(DstElemTy, SrcScalarTy->getAddressSpace());
1856 if (VectorType *VT = dyn_cast<VectorType>(DstTy)) {
1857 // Handle vectors of pointers.
1858 MidTy = VectorType::get(MidTy, VT->getNumElements());
1860 C = getBitCast(C, MidTy);
1862 return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced);
1865 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
1866 unsigned Flags, Type *OnlyIfReducedTy) {
1867 // Check the operands for consistency first.
1868 assert(Opcode >= Instruction::BinaryOpsBegin &&
1869 Opcode < Instruction::BinaryOpsEnd &&
1870 "Invalid opcode in binary constant expression");
1871 assert(C1->getType() == C2->getType() &&
1872 "Operand types in binary constant expression should match");
1876 case Instruction::Add:
1877 case Instruction::Sub:
1878 case Instruction::Mul:
1879 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1880 assert(C1->getType()->isIntOrIntVectorTy() &&
1881 "Tried to create an integer operation on a non-integer type!");
1883 case Instruction::FAdd:
1884 case Instruction::FSub:
1885 case Instruction::FMul:
1886 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1887 assert(C1->getType()->isFPOrFPVectorTy() &&
1888 "Tried to create a floating-point operation on a "
1889 "non-floating-point type!");
1891 case Instruction::UDiv:
1892 case Instruction::SDiv:
1893 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1894 assert(C1->getType()->isIntOrIntVectorTy() &&
1895 "Tried to create an arithmetic operation on a non-arithmetic type!");
1897 case Instruction::FDiv:
1898 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1899 assert(C1->getType()->isFPOrFPVectorTy() &&
1900 "Tried to create an arithmetic operation on a non-arithmetic type!");
1902 case Instruction::URem:
1903 case Instruction::SRem:
1904 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1905 assert(C1->getType()->isIntOrIntVectorTy() &&
1906 "Tried to create an arithmetic operation on a non-arithmetic type!");
1908 case Instruction::FRem:
1909 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1910 assert(C1->getType()->isFPOrFPVectorTy() &&
1911 "Tried to create an arithmetic operation on a non-arithmetic type!");
1913 case Instruction::And:
1914 case Instruction::Or:
1915 case Instruction::Xor:
1916 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1917 assert(C1->getType()->isIntOrIntVectorTy() &&
1918 "Tried to create a logical operation on a non-integral type!");
1920 case Instruction::Shl:
1921 case Instruction::LShr:
1922 case Instruction::AShr:
1923 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1924 assert(C1->getType()->isIntOrIntVectorTy() &&
1925 "Tried to create a shift operation on a non-integer type!");
1932 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1933 return FC; // Fold a few common cases.
1935 if (OnlyIfReducedTy == C1->getType())
1938 Constant *ArgVec[] = { C1, C2 };
1939 ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
1941 LLVMContextImpl *pImpl = C1->getContext().pImpl;
1942 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
1945 Constant *ConstantExpr::getSizeOf(Type* Ty) {
1946 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1947 // Note that a non-inbounds gep is used, as null isn't within any object.
1948 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1949 Constant *GEP = getGetElementPtr(
1950 Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
1951 return getPtrToInt(GEP,
1952 Type::getInt64Ty(Ty->getContext()));
1955 Constant *ConstantExpr::getAlignOf(Type* Ty) {
1956 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
1957 // Note that a non-inbounds gep is used, as null isn't within any object.
1959 StructType::get(Type::getInt1Ty(Ty->getContext()), Ty, nullptr);
1960 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo(0));
1961 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
1962 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1963 Constant *Indices[2] = { Zero, One };
1964 Constant *GEP = getGetElementPtr(AligningTy, NullPtr, Indices);
1965 return getPtrToInt(GEP,
1966 Type::getInt64Ty(Ty->getContext()));
1969 Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) {
1970 return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
1974 Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) {
1975 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1976 // Note that a non-inbounds gep is used, as null isn't within any object.
1977 Constant *GEPIdx[] = {
1978 ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
1981 Constant *GEP = getGetElementPtr(
1982 Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
1983 return getPtrToInt(GEP,
1984 Type::getInt64Ty(Ty->getContext()));
1987 Constant *ConstantExpr::getCompare(unsigned short Predicate, Constant *C1,
1988 Constant *C2, bool OnlyIfReduced) {
1989 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1991 switch (Predicate) {
1992 default: llvm_unreachable("Invalid CmpInst predicate");
1993 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1994 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1995 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1996 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1997 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1998 case CmpInst::FCMP_TRUE:
1999 return getFCmp(Predicate, C1, C2, OnlyIfReduced);
2001 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
2002 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
2003 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
2004 case CmpInst::ICMP_SLE:
2005 return getICmp(Predicate, C1, C2, OnlyIfReduced);
2009 Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2,
2010 Type *OnlyIfReducedTy) {
2011 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
2013 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
2014 return SC; // Fold common cases
2016 if (OnlyIfReducedTy == V1->getType())
2019 Constant *ArgVec[] = { C, V1, V2 };
2020 ConstantExprKeyType Key(Instruction::Select, ArgVec);
2022 LLVMContextImpl *pImpl = C->getContext().pImpl;
2023 return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
2026 Constant *ConstantExpr::getGetElementPtr(Type *Ty, Constant *C,
2027 ArrayRef<Value *> Idxs, bool InBounds,
2028 Type *OnlyIfReducedTy) {
2030 Ty = cast<PointerType>(C->getType()->getScalarType())->getElementType();
2034 cast<PointerType>(C->getType()->getScalarType())->getContainedType(0u));
2036 if (Constant *FC = ConstantFoldGetElementPtr(Ty, C, InBounds, Idxs))
2037 return FC; // Fold a few common cases.
2039 // Get the result type of the getelementptr!
2040 Type *DestTy = GetElementPtrInst::getIndexedType(Ty, Idxs);
2041 assert(DestTy && "GEP indices invalid!");
2042 unsigned AS = C->getType()->getPointerAddressSpace();
2043 Type *ReqTy = DestTy->getPointerTo(AS);
2044 if (VectorType *VecTy = dyn_cast<VectorType>(C->getType()))
2045 ReqTy = VectorType::get(ReqTy, VecTy->getNumElements());
2047 if (OnlyIfReducedTy == ReqTy)
2050 // Look up the constant in the table first to ensure uniqueness
2051 std::vector<Constant*> ArgVec;
2052 ArgVec.reserve(1 + Idxs.size());
2053 ArgVec.push_back(C);
2054 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
2055 assert(Idxs[i]->getType()->isVectorTy() == ReqTy->isVectorTy() &&
2056 "getelementptr index type missmatch");
2057 assert((!Idxs[i]->getType()->isVectorTy() ||
2058 ReqTy->getVectorNumElements() ==
2059 Idxs[i]->getType()->getVectorNumElements()) &&
2060 "getelementptr index type missmatch");
2061 ArgVec.push_back(cast<Constant>(Idxs[i]));
2063 const ConstantExprKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
2064 InBounds ? GEPOperator::IsInBounds : 0, None,
2067 LLVMContextImpl *pImpl = C->getContext().pImpl;
2068 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2071 Constant *ConstantExpr::getICmp(unsigned short pred, Constant *LHS,
2072 Constant *RHS, bool OnlyIfReduced) {
2073 assert(LHS->getType() == RHS->getType());
2074 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2075 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
2077 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2078 return FC; // Fold a few common cases...
2083 // Look up the constant in the table first to ensure uniqueness
2084 Constant *ArgVec[] = { LHS, RHS };
2085 // Get the key type with both the opcode and predicate
2086 const ConstantExprKeyType Key(Instruction::ICmp, ArgVec, pred);
2088 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
2089 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
2090 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
2092 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
2093 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
2096 Constant *ConstantExpr::getFCmp(unsigned short pred, Constant *LHS,
2097 Constant *RHS, bool OnlyIfReduced) {
2098 assert(LHS->getType() == RHS->getType());
2099 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
2101 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2102 return FC; // Fold a few common cases...
2107 // Look up the constant in the table first to ensure uniqueness
2108 Constant *ArgVec[] = { LHS, RHS };
2109 // Get the key type with both the opcode and predicate
2110 const ConstantExprKeyType Key(Instruction::FCmp, ArgVec, pred);
2112 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
2113 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
2114 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
2116 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
2117 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
2120 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx,
2121 Type *OnlyIfReducedTy) {
2122 assert(Val->getType()->isVectorTy() &&
2123 "Tried to create extractelement operation on non-vector type!");
2124 assert(Idx->getType()->isIntegerTy() &&
2125 "Extractelement index must be an integer type!");
2127 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
2128 return FC; // Fold a few common cases.
2130 Type *ReqTy = Val->getType()->getVectorElementType();
2131 if (OnlyIfReducedTy == ReqTy)
2134 // Look up the constant in the table first to ensure uniqueness
2135 Constant *ArgVec[] = { Val, Idx };
2136 const ConstantExprKeyType Key(Instruction::ExtractElement, ArgVec);
2138 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2139 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2142 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2143 Constant *Idx, Type *OnlyIfReducedTy) {
2144 assert(Val->getType()->isVectorTy() &&
2145 "Tried to create insertelement operation on non-vector type!");
2146 assert(Elt->getType() == Val->getType()->getVectorElementType() &&
2147 "Insertelement types must match!");
2148 assert(Idx->getType()->isIntegerTy() &&
2149 "Insertelement index must be i32 type!");
2151 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2152 return FC; // Fold a few common cases.
2154 if (OnlyIfReducedTy == Val->getType())
2157 // Look up the constant in the table first to ensure uniqueness
2158 Constant *ArgVec[] = { Val, Elt, Idx };
2159 const ConstantExprKeyType Key(Instruction::InsertElement, ArgVec);
2161 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2162 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
2165 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2166 Constant *Mask, Type *OnlyIfReducedTy) {
2167 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2168 "Invalid shuffle vector constant expr operands!");
2170 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2171 return FC; // Fold a few common cases.
2173 unsigned NElts = Mask->getType()->getVectorNumElements();
2174 Type *EltTy = V1->getType()->getVectorElementType();
2175 Type *ShufTy = VectorType::get(EltTy, NElts);
2177 if (OnlyIfReducedTy == ShufTy)
2180 // Look up the constant in the table first to ensure uniqueness
2181 Constant *ArgVec[] = { V1, V2, Mask };
2182 const ConstantExprKeyType Key(Instruction::ShuffleVector, ArgVec);
2184 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
2185 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
2188 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
2189 ArrayRef<unsigned> Idxs,
2190 Type *OnlyIfReducedTy) {
2191 assert(Agg->getType()->isFirstClassType() &&
2192 "Non-first-class type for constant insertvalue expression");
2194 assert(ExtractValueInst::getIndexedType(Agg->getType(),
2195 Idxs) == Val->getType() &&
2196 "insertvalue indices invalid!");
2197 Type *ReqTy = Val->getType();
2199 if (Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs))
2202 if (OnlyIfReducedTy == ReqTy)
2205 Constant *ArgVec[] = { Agg, Val };
2206 const ConstantExprKeyType Key(Instruction::InsertValue, ArgVec, 0, 0, Idxs);
2208 LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2209 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2212 Constant *ConstantExpr::getExtractValue(Constant *Agg, ArrayRef<unsigned> Idxs,
2213 Type *OnlyIfReducedTy) {
2214 assert(Agg->getType()->isFirstClassType() &&
2215 "Tried to create extractelement operation on non-first-class type!");
2217 Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs);
2219 assert(ReqTy && "extractvalue indices invalid!");
2221 assert(Agg->getType()->isFirstClassType() &&
2222 "Non-first-class type for constant extractvalue expression");
2223 if (Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs))
2226 if (OnlyIfReducedTy == ReqTy)
2229 Constant *ArgVec[] = { Agg };
2230 const ConstantExprKeyType Key(Instruction::ExtractValue, ArgVec, 0, 0, Idxs);
2232 LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2233 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2236 Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
2237 assert(C->getType()->isIntOrIntVectorTy() &&
2238 "Cannot NEG a nonintegral value!");
2239 return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
2243 Constant *ConstantExpr::getFNeg(Constant *C) {
2244 assert(C->getType()->isFPOrFPVectorTy() &&
2245 "Cannot FNEG a non-floating-point value!");
2246 return getFSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
2249 Constant *ConstantExpr::getNot(Constant *C) {
2250 assert(C->getType()->isIntOrIntVectorTy() &&
2251 "Cannot NOT a nonintegral value!");
2252 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
2255 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
2256 bool HasNUW, bool HasNSW) {
2257 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2258 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2259 return get(Instruction::Add, C1, C2, Flags);
2262 Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
2263 return get(Instruction::FAdd, C1, C2);
2266 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
2267 bool HasNUW, bool HasNSW) {
2268 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2269 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2270 return get(Instruction::Sub, C1, C2, Flags);
2273 Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
2274 return get(Instruction::FSub, C1, C2);
2277 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
2278 bool HasNUW, bool HasNSW) {
2279 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2280 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2281 return get(Instruction::Mul, C1, C2, Flags);
2284 Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
2285 return get(Instruction::FMul, C1, C2);
2288 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
2289 return get(Instruction::UDiv, C1, C2,
2290 isExact ? PossiblyExactOperator::IsExact : 0);
2293 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
2294 return get(Instruction::SDiv, C1, C2,
2295 isExact ? PossiblyExactOperator::IsExact : 0);
2298 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
2299 return get(Instruction::FDiv, C1, C2);
2302 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
2303 return get(Instruction::URem, C1, C2);
2306 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
2307 return get(Instruction::SRem, C1, C2);
2310 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
2311 return get(Instruction::FRem, C1, C2);
2314 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
2315 return get(Instruction::And, C1, C2);
2318 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
2319 return get(Instruction::Or, C1, C2);
2322 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
2323 return get(Instruction::Xor, C1, C2);
2326 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
2327 bool HasNUW, bool HasNSW) {
2328 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2329 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2330 return get(Instruction::Shl, C1, C2, Flags);
2333 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
2334 return get(Instruction::LShr, C1, C2,
2335 isExact ? PossiblyExactOperator::IsExact : 0);
2338 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
2339 return get(Instruction::AShr, C1, C2,
2340 isExact ? PossiblyExactOperator::IsExact : 0);
2343 /// getBinOpIdentity - Return the identity for the given binary operation,
2344 /// i.e. a constant C such that X op C = X and C op X = X for every X. It
2345 /// returns null if the operator doesn't have an identity.
2346 Constant *ConstantExpr::getBinOpIdentity(unsigned Opcode, Type *Ty) {
2349 // Doesn't have an identity.
2352 case Instruction::Add:
2353 case Instruction::Or:
2354 case Instruction::Xor:
2355 return Constant::getNullValue(Ty);
2357 case Instruction::Mul:
2358 return ConstantInt::get(Ty, 1);
2360 case Instruction::And:
2361 return Constant::getAllOnesValue(Ty);
2365 /// getBinOpAbsorber - Return the absorbing element for the given binary
2366 /// operation, i.e. a constant C such that X op C = C and C op X = C for
2367 /// every X. For example, this returns zero for integer multiplication.
2368 /// It returns null if the operator doesn't have an absorbing element.
2369 Constant *ConstantExpr::getBinOpAbsorber(unsigned Opcode, Type *Ty) {
2372 // Doesn't have an absorber.
2375 case Instruction::Or:
2376 return Constant::getAllOnesValue(Ty);
2378 case Instruction::And:
2379 case Instruction::Mul:
2380 return Constant::getNullValue(Ty);
2384 // destroyConstant - Remove the constant from the constant table...
2386 void ConstantExpr::destroyConstantImpl() {
2387 getType()->getContext().pImpl->ExprConstants.remove(this);
2390 const char *ConstantExpr::getOpcodeName() const {
2391 return Instruction::getOpcodeName(getOpcode());
2394 GetElementPtrConstantExpr::GetElementPtrConstantExpr(
2395 Type *SrcElementTy, Constant *C, ArrayRef<Constant *> IdxList, Type *DestTy)
2396 : ConstantExpr(DestTy, Instruction::GetElementPtr,
2397 OperandTraits<GetElementPtrConstantExpr>::op_end(this) -
2398 (IdxList.size() + 1),
2399 IdxList.size() + 1),
2400 SrcElementTy(SrcElementTy) {
2402 Use *OperandList = getOperandList();
2403 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
2404 OperandList[i+1] = IdxList[i];
2407 Type *GetElementPtrConstantExpr::getSourceElementType() const {
2408 return SrcElementTy;
2411 //===----------------------------------------------------------------------===//
2412 // ConstantData* implementations
2414 void ConstantDataArray::anchor() {}
2415 void ConstantDataVector::anchor() {}
2417 /// getElementType - Return the element type of the array/vector.
2418 Type *ConstantDataSequential::getElementType() const {
2419 return getType()->getElementType();
2422 StringRef ConstantDataSequential::getRawDataValues() const {
2423 return StringRef(DataElements, getNumElements()*getElementByteSize());
2426 /// isElementTypeCompatible - Return true if a ConstantDataSequential can be
2427 /// formed with a vector or array of the specified element type.
2428 /// ConstantDataArray only works with normal float and int types that are
2429 /// stored densely in memory, not with things like i42 or x86_f80.
2430 bool ConstantDataSequential::isElementTypeCompatible(Type *Ty) {
2431 if (Ty->isFloatTy() || Ty->isDoubleTy()) return true;
2432 if (auto *IT = dyn_cast<IntegerType>(Ty)) {
2433 switch (IT->getBitWidth()) {
2445 /// getNumElements - Return the number of elements in the array or vector.
2446 unsigned ConstantDataSequential::getNumElements() const {
2447 if (ArrayType *AT = dyn_cast<ArrayType>(getType()))
2448 return AT->getNumElements();
2449 return getType()->getVectorNumElements();
2453 /// getElementByteSize - Return the size in bytes of the elements in the data.
2454 uint64_t ConstantDataSequential::getElementByteSize() const {
2455 return getElementType()->getPrimitiveSizeInBits()/8;
2458 /// getElementPointer - Return the start of the specified element.
2459 const char *ConstantDataSequential::getElementPointer(unsigned Elt) const {
2460 assert(Elt < getNumElements() && "Invalid Elt");
2461 return DataElements+Elt*getElementByteSize();
2465 /// isAllZeros - return true if the array is empty or all zeros.
2466 static bool isAllZeros(StringRef Arr) {
2467 for (StringRef::iterator I = Arr.begin(), E = Arr.end(); I != E; ++I)
2473 /// getImpl - This is the underlying implementation of all of the
2474 /// ConstantDataSequential::get methods. They all thunk down to here, providing
2475 /// the correct element type. We take the bytes in as a StringRef because
2476 /// we *want* an underlying "char*" to avoid TBAA type punning violations.
2477 Constant *ConstantDataSequential::getImpl(StringRef Elements, Type *Ty) {
2478 assert(isElementTypeCompatible(Ty->getSequentialElementType()));
2479 // If the elements are all zero or there are no elements, return a CAZ, which
2480 // is more dense and canonical.
2481 if (isAllZeros(Elements))
2482 return ConstantAggregateZero::get(Ty);
2484 // Do a lookup to see if we have already formed one of these.
2487 .pImpl->CDSConstants.insert(std::make_pair(Elements, nullptr))
2490 // The bucket can point to a linked list of different CDS's that have the same
2491 // body but different types. For example, 0,0,0,1 could be a 4 element array
2492 // of i8, or a 1-element array of i32. They'll both end up in the same
2493 /// StringMap bucket, linked up by their Next pointers. Walk the list.
2494 ConstantDataSequential **Entry = &Slot.second;
2495 for (ConstantDataSequential *Node = *Entry; Node;
2496 Entry = &Node->Next, Node = *Entry)
2497 if (Node->getType() == Ty)
2500 // Okay, we didn't get a hit. Create a node of the right class, link it in,
2502 if (isa<ArrayType>(Ty))
2503 return *Entry = new ConstantDataArray(Ty, Slot.first().data());
2505 assert(isa<VectorType>(Ty));
2506 return *Entry = new ConstantDataVector(Ty, Slot.first().data());
2509 void ConstantDataSequential::destroyConstantImpl() {
2510 // Remove the constant from the StringMap.
2511 StringMap<ConstantDataSequential*> &CDSConstants =
2512 getType()->getContext().pImpl->CDSConstants;
2514 StringMap<ConstantDataSequential*>::iterator Slot =
2515 CDSConstants.find(getRawDataValues());
2517 assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
2519 ConstantDataSequential **Entry = &Slot->getValue();
2521 // Remove the entry from the hash table.
2522 if (!(*Entry)->Next) {
2523 // If there is only one value in the bucket (common case) it must be this
2524 // entry, and removing the entry should remove the bucket completely.
2525 assert((*Entry) == this && "Hash mismatch in ConstantDataSequential");
2526 getContext().pImpl->CDSConstants.erase(Slot);
2528 // Otherwise, there are multiple entries linked off the bucket, unlink the
2529 // node we care about but keep the bucket around.
2530 for (ConstantDataSequential *Node = *Entry; ;
2531 Entry = &Node->Next, Node = *Entry) {
2532 assert(Node && "Didn't find entry in its uniquing hash table!");
2533 // If we found our entry, unlink it from the list and we're done.
2535 *Entry = Node->Next;
2541 // If we were part of a list, make sure that we don't delete the list that is
2542 // still owned by the uniquing map.
2546 /// get() constructors - Return a constant with array type with an element
2547 /// count and element type matching the ArrayRef passed in. Note that this
2548 /// can return a ConstantAggregateZero object.
2549 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint8_t> Elts) {
2550 Type *Ty = ArrayType::get(Type::getInt8Ty(Context), Elts.size());
2551 const char *Data = reinterpret_cast<const char *>(Elts.data());
2552 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*1), Ty);
2554 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
2555 Type *Ty = ArrayType::get(Type::getInt16Ty(Context), Elts.size());
2556 const char *Data = reinterpret_cast<const char *>(Elts.data());
2557 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*2), Ty);
2559 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
2560 Type *Ty = ArrayType::get(Type::getInt32Ty(Context), Elts.size());
2561 const char *Data = reinterpret_cast<const char *>(Elts.data());
2562 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
2564 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
2565 Type *Ty = ArrayType::get(Type::getInt64Ty(Context), Elts.size());
2566 const char *Data = reinterpret_cast<const char *>(Elts.data());
2567 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
2569 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<float> Elts) {
2570 Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
2571 const char *Data = reinterpret_cast<const char *>(Elts.data());
2572 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
2574 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<double> Elts) {
2575 Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
2576 const char *Data = reinterpret_cast<const char *>(Elts.data());
2577 return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 8), Ty);
2580 /// getFP() constructors - Return a constant with array type with an element
2581 /// count and element type of float with precision matching the number of
2582 /// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits,
2583 /// double for 64bits) Note that this can return a ConstantAggregateZero
2585 Constant *ConstantDataArray::getFP(LLVMContext &Context,
2586 ArrayRef<uint16_t> Elts) {
2587 Type *Ty = VectorType::get(Type::getHalfTy(Context), Elts.size());
2588 const char *Data = reinterpret_cast<const char *>(Elts.data());
2589 return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 2), Ty);
2591 Constant *ConstantDataArray::getFP(LLVMContext &Context,
2592 ArrayRef<uint32_t> Elts) {
2593 Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
2594 const char *Data = reinterpret_cast<const char *>(Elts.data());
2595 return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 4), Ty);
2597 Constant *ConstantDataArray::getFP(LLVMContext &Context,
2598 ArrayRef<uint64_t> Elts) {
2599 Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
2600 const char *Data = reinterpret_cast<const char *>(Elts.data());
2601 return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 8), Ty);
2604 /// getString - This method constructs a CDS and initializes it with a text
2605 /// string. The default behavior (AddNull==true) causes a null terminator to
2606 /// be placed at the end of the array (increasing the length of the string by
2607 /// one more than the StringRef would normally indicate. Pass AddNull=false
2608 /// to disable this behavior.
2609 Constant *ConstantDataArray::getString(LLVMContext &Context,
2610 StringRef Str, bool AddNull) {
2612 const uint8_t *Data = reinterpret_cast<const uint8_t *>(Str.data());
2613 return get(Context, makeArrayRef(const_cast<uint8_t *>(Data),
2617 SmallVector<uint8_t, 64> ElementVals;
2618 ElementVals.append(Str.begin(), Str.end());
2619 ElementVals.push_back(0);
2620 return get(Context, ElementVals);
2623 /// get() constructors - Return a constant with vector type with an element
2624 /// count and element type matching the ArrayRef passed in. Note that this
2625 /// can return a ConstantAggregateZero object.
2626 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> Elts){
2627 Type *Ty = VectorType::get(Type::getInt8Ty(Context), Elts.size());
2628 const char *Data = reinterpret_cast<const char *>(Elts.data());
2629 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*1), Ty);
2631 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
2632 Type *Ty = VectorType::get(Type::getInt16Ty(Context), Elts.size());
2633 const char *Data = reinterpret_cast<const char *>(Elts.data());
2634 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*2), Ty);
2636 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
2637 Type *Ty = VectorType::get(Type::getInt32Ty(Context), Elts.size());
2638 const char *Data = reinterpret_cast<const char *>(Elts.data());
2639 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
2641 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
2642 Type *Ty = VectorType::get(Type::getInt64Ty(Context), Elts.size());
2643 const char *Data = reinterpret_cast<const char *>(Elts.data());
2644 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
2646 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> Elts) {
2647 Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
2648 const char *Data = reinterpret_cast<const char *>(Elts.data());
2649 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
2651 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<double> Elts) {
2652 Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
2653 const char *Data = reinterpret_cast<const char *>(Elts.data());
2654 return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 8), Ty);
2657 /// getFP() constructors - Return a constant with vector type with an element
2658 /// count and element type of float with the precision matching the number of
2659 /// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits,
2660 /// double for 64bits) Note that this can return a ConstantAggregateZero
2662 Constant *ConstantDataVector::getFP(LLVMContext &Context,
2663 ArrayRef<uint16_t> Elts) {
2664 Type *Ty = VectorType::get(Type::getHalfTy(Context), Elts.size());
2665 const char *Data = reinterpret_cast<const char *>(Elts.data());
2666 return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 2), Ty);
2668 Constant *ConstantDataVector::getFP(LLVMContext &Context,
2669 ArrayRef<uint32_t> Elts) {
2670 Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
2671 const char *Data = reinterpret_cast<const char *>(Elts.data());
2672 return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 4), Ty);
2674 Constant *ConstantDataVector::getFP(LLVMContext &Context,
2675 ArrayRef<uint64_t> Elts) {
2676 Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
2677 const char *Data = reinterpret_cast<const char *>(Elts.data());
2678 return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 8), Ty);
2681 Constant *ConstantDataVector::getSplat(unsigned NumElts, Constant *V) {
2682 assert(isElementTypeCompatible(V->getType()) &&
2683 "Element type not compatible with ConstantData");
2684 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2685 if (CI->getType()->isIntegerTy(8)) {
2686 SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
2687 return get(V->getContext(), Elts);
2689 if (CI->getType()->isIntegerTy(16)) {
2690 SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
2691 return get(V->getContext(), Elts);
2693 if (CI->getType()->isIntegerTy(32)) {
2694 SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
2695 return get(V->getContext(), Elts);
2697 assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
2698 SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
2699 return get(V->getContext(), Elts);
2702 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2703 if (CFP->getType()->isFloatTy()) {
2704 SmallVector<uint32_t, 16> Elts(
2705 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2706 return getFP(V->getContext(), Elts);
2708 if (CFP->getType()->isDoubleTy()) {
2709 SmallVector<uint64_t, 16> Elts(
2710 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2711 return getFP(V->getContext(), Elts);
2714 return ConstantVector::getSplat(NumElts, V);
2718 /// getElementAsInteger - If this is a sequential container of integers (of
2719 /// any size), return the specified element in the low bits of a uint64_t.
2720 uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const {
2721 assert(isa<IntegerType>(getElementType()) &&
2722 "Accessor can only be used when element is an integer");
2723 const char *EltPtr = getElementPointer(Elt);
2725 // The data is stored in host byte order, make sure to cast back to the right
2726 // type to load with the right endianness.
2727 switch (getElementType()->getIntegerBitWidth()) {
2728 default: llvm_unreachable("Invalid bitwidth for CDS");
2730 return *const_cast<uint8_t *>(reinterpret_cast<const uint8_t *>(EltPtr));
2732 return *const_cast<uint16_t *>(reinterpret_cast<const uint16_t *>(EltPtr));
2734 return *const_cast<uint32_t *>(reinterpret_cast<const uint32_t *>(EltPtr));
2736 return *const_cast<uint64_t *>(reinterpret_cast<const uint64_t *>(EltPtr));
2740 /// getElementAsAPFloat - If this is a sequential container of floating point
2741 /// type, return the specified element as an APFloat.
2742 APFloat ConstantDataSequential::getElementAsAPFloat(unsigned Elt) const {
2743 const char *EltPtr = getElementPointer(Elt);
2745 switch (getElementType()->getTypeID()) {
2747 llvm_unreachable("Accessor can only be used when element is float/double!");
2748 case Type::FloatTyID: {
2749 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
2750 return APFloat(APFloat::IEEEsingle, APInt(32, EltVal));
2752 case Type::DoubleTyID: {
2753 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
2754 return APFloat(APFloat::IEEEdouble, APInt(64, EltVal));
2759 /// getElementAsFloat - If this is an sequential container of floats, return
2760 /// the specified element as a float.
2761 float ConstantDataSequential::getElementAsFloat(unsigned Elt) const {
2762 assert(getElementType()->isFloatTy() &&
2763 "Accessor can only be used when element is a 'float'");
2764 const float *EltPtr = reinterpret_cast<const float *>(getElementPointer(Elt));
2765 return *const_cast<float *>(EltPtr);
2768 /// getElementAsDouble - If this is an sequential container of doubles, return
2769 /// the specified element as a float.
2770 double ConstantDataSequential::getElementAsDouble(unsigned Elt) const {
2771 assert(getElementType()->isDoubleTy() &&
2772 "Accessor can only be used when element is a 'float'");
2773 const double *EltPtr =
2774 reinterpret_cast<const double *>(getElementPointer(Elt));
2775 return *const_cast<double *>(EltPtr);
2778 /// getElementAsConstant - Return a Constant for a specified index's element.
2779 /// Note that this has to compute a new constant to return, so it isn't as
2780 /// efficient as getElementAsInteger/Float/Double.
2781 Constant *ConstantDataSequential::getElementAsConstant(unsigned Elt) const {
2782 if (getElementType()->isFloatTy() || getElementType()->isDoubleTy())
2783 return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
2785 return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
2788 /// isString - This method returns true if this is an array of i8.
2789 bool ConstantDataSequential::isString() const {
2790 return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(8);
2793 /// isCString - This method returns true if the array "isString", ends with a
2794 /// nul byte, and does not contains any other nul bytes.
2795 bool ConstantDataSequential::isCString() const {
2799 StringRef Str = getAsString();
2801 // The last value must be nul.
2802 if (Str.back() != 0) return false;
2804 // Other elements must be non-nul.
2805 return Str.drop_back().find(0) == StringRef::npos;
2808 /// getSplatValue - If this is a splat constant, meaning that all of the
2809 /// elements have the same value, return that value. Otherwise return nullptr.
2810 Constant *ConstantDataVector::getSplatValue() const {
2811 const char *Base = getRawDataValues().data();
2813 // Compare elements 1+ to the 0'th element.
2814 unsigned EltSize = getElementByteSize();
2815 for (unsigned i = 1, e = getNumElements(); i != e; ++i)
2816 if (memcmp(Base, Base+i*EltSize, EltSize))
2819 // If they're all the same, return the 0th one as a representative.
2820 return getElementAsConstant(0);
2823 //===----------------------------------------------------------------------===//
2824 // handleOperandChange implementations
2826 /// Update this constant array to change uses of
2827 /// 'From' to be uses of 'To'. This must update the uniquing data structures
2830 /// Note that we intentionally replace all uses of From with To here. Consider
2831 /// a large array that uses 'From' 1000 times. By handling this case all here,
2832 /// ConstantArray::handleOperandChange is only invoked once, and that
2833 /// single invocation handles all 1000 uses. Handling them one at a time would
2834 /// work, but would be really slow because it would have to unique each updated
2837 void Constant::handleOperandChange(Value *From, Value *To, Use *U) {
2838 Value *Replacement = nullptr;
2839 switch (getValueID()) {
2841 llvm_unreachable("Not a constant!");
2842 #define HANDLE_CONSTANT(Name) \
2843 case Value::Name##Val: \
2844 Replacement = cast<Name>(this)->handleOperandChangeImpl(From, To, U); \
2846 #include "llvm/IR/Value.def"
2849 // If handleOperandChangeImpl returned nullptr, then it handled
2850 // replacing itself and we don't want to delete or replace anything else here.
2854 // I do need to replace this with an existing value.
2855 assert(Replacement != this && "I didn't contain From!");
2857 // Everyone using this now uses the replacement.
2858 replaceAllUsesWith(Replacement);
2860 // Delete the old constant!
2864 Value *ConstantInt::handleOperandChangeImpl(Value *From, Value *To, Use *U) {
2865 llvm_unreachable("Unsupported class for handleOperandChange()!");
2868 Value *ConstantFP::handleOperandChangeImpl(Value *From, Value *To, Use *U) {
2869 llvm_unreachable("Unsupported class for handleOperandChange()!");
2872 Value *ConstantTokenNone::handleOperandChangeImpl(Value *From, Value *To,
2874 llvm_unreachable("Unsupported class for handleOperandChange()!");
2877 Value *UndefValue::handleOperandChangeImpl(Value *From, Value *To, Use *U) {
2878 llvm_unreachable("Unsupported class for handleOperandChange()!");
2881 Value *ConstantPointerNull::handleOperandChangeImpl(Value *From, Value *To,
2883 llvm_unreachable("Unsupported class for handleOperandChange()!");
2886 Value *ConstantAggregateZero::handleOperandChangeImpl(Value *From, Value *To,
2888 llvm_unreachable("Unsupported class for handleOperandChange()!");
2891 Value *ConstantDataSequential::handleOperandChangeImpl(Value *From, Value *To,
2893 llvm_unreachable("Unsupported class for handleOperandChange()!");
2896 Value *ConstantArray::handleOperandChangeImpl(Value *From, Value *To, Use *U) {
2897 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2898 Constant *ToC = cast<Constant>(To);
2900 SmallVector<Constant*, 8> Values;
2901 Values.reserve(getNumOperands()); // Build replacement array.
2903 // Fill values with the modified operands of the constant array. Also,
2904 // compute whether this turns into an all-zeros array.
2905 unsigned NumUpdated = 0;
2907 // Keep track of whether all the values in the array are "ToC".
2908 bool AllSame = true;
2909 Use *OperandList = getOperandList();
2910 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2911 Constant *Val = cast<Constant>(O->get());
2916 Values.push_back(Val);
2917 AllSame &= Val == ToC;
2920 if (AllSame && ToC->isNullValue())
2921 return ConstantAggregateZero::get(getType());
2923 if (AllSame && isa<UndefValue>(ToC))
2924 return UndefValue::get(getType());
2926 // Check for any other type of constant-folding.
2927 if (Constant *C = getImpl(getType(), Values))
2930 // Update to the new value.
2931 return getContext().pImpl->ArrayConstants.replaceOperandsInPlace(
2932 Values, this, From, ToC, NumUpdated, U - OperandList);
2935 Value *ConstantStruct::handleOperandChangeImpl(Value *From, Value *To, Use *U) {
2936 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2937 Constant *ToC = cast<Constant>(To);
2939 Use *OperandList = getOperandList();
2940 unsigned OperandToUpdate = U-OperandList;
2941 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2943 SmallVector<Constant*, 8> Values;
2944 Values.reserve(getNumOperands()); // Build replacement struct.
2946 // Fill values with the modified operands of the constant struct. Also,
2947 // compute whether this turns into an all-zeros struct.
2948 bool isAllZeros = false;
2949 bool isAllUndef = false;
2950 if (ToC->isNullValue()) {
2952 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2953 Constant *Val = cast<Constant>(O->get());
2954 Values.push_back(Val);
2955 if (isAllZeros) isAllZeros = Val->isNullValue();
2957 } else if (isa<UndefValue>(ToC)) {
2959 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2960 Constant *Val = cast<Constant>(O->get());
2961 Values.push_back(Val);
2962 if (isAllUndef) isAllUndef = isa<UndefValue>(Val);
2965 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
2966 Values.push_back(cast<Constant>(O->get()));
2968 Values[OperandToUpdate] = ToC;
2971 return ConstantAggregateZero::get(getType());
2974 return UndefValue::get(getType());
2976 // Update to the new value.
2977 return getContext().pImpl->StructConstants.replaceOperandsInPlace(
2978 Values, this, From, ToC);
2981 Value *ConstantVector::handleOperandChangeImpl(Value *From, Value *To, Use *U) {
2982 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2983 Constant *ToC = cast<Constant>(To);
2985 SmallVector<Constant*, 8> Values;
2986 Values.reserve(getNumOperands()); // Build replacement array...
2987 unsigned NumUpdated = 0;
2988 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2989 Constant *Val = getOperand(i);
2994 Values.push_back(Val);
2997 if (Constant *C = getImpl(Values))
3000 // Update to the new value.
3001 Use *OperandList = getOperandList();
3002 return getContext().pImpl->VectorConstants.replaceOperandsInPlace(
3003 Values, this, From, ToC, NumUpdated, U - OperandList);
3006 Value *ConstantExpr::handleOperandChangeImpl(Value *From, Value *ToV, Use *U) {
3007 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
3008 Constant *To = cast<Constant>(ToV);
3010 SmallVector<Constant*, 8> NewOps;
3011 unsigned NumUpdated = 0;
3012 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
3013 Constant *Op = getOperand(i);
3018 NewOps.push_back(Op);
3020 assert(NumUpdated && "I didn't contain From!");
3022 if (Constant *C = getWithOperands(NewOps, getType(), true))
3025 // Update to the new value.
3026 Use *OperandList = getOperandList();
3027 return getContext().pImpl->ExprConstants.replaceOperandsInPlace(
3028 NewOps, this, From, To, NumUpdated, U - OperandList);
3031 Instruction *ConstantExpr::getAsInstruction() {
3032 SmallVector<Value *, 4> ValueOperands(op_begin(), op_end());
3033 ArrayRef<Value*> Ops(ValueOperands);
3035 switch (getOpcode()) {
3036 case Instruction::Trunc:
3037 case Instruction::ZExt:
3038 case Instruction::SExt:
3039 case Instruction::FPTrunc:
3040 case Instruction::FPExt:
3041 case Instruction::UIToFP:
3042 case Instruction::SIToFP:
3043 case Instruction::FPToUI:
3044 case Instruction::FPToSI:
3045 case Instruction::PtrToInt:
3046 case Instruction::IntToPtr:
3047 case Instruction::BitCast:
3048 case Instruction::AddrSpaceCast:
3049 return CastInst::Create((Instruction::CastOps)getOpcode(),
3051 case Instruction::Select:
3052 return SelectInst::Create(Ops[0], Ops[1], Ops[2]);
3053 case Instruction::InsertElement:
3054 return InsertElementInst::Create(Ops[0], Ops[1], Ops[2]);
3055 case Instruction::ExtractElement:
3056 return ExtractElementInst::Create(Ops[0], Ops[1]);
3057 case Instruction::InsertValue:
3058 return InsertValueInst::Create(Ops[0], Ops[1], getIndices());
3059 case Instruction::ExtractValue:
3060 return ExtractValueInst::Create(Ops[0], getIndices());
3061 case Instruction::ShuffleVector:
3062 return new ShuffleVectorInst(Ops[0], Ops[1], Ops[2]);
3064 case Instruction::GetElementPtr: {
3065 const auto *GO = cast<GEPOperator>(this);
3066 if (GO->isInBounds())
3067 return GetElementPtrInst::CreateInBounds(GO->getSourceElementType(),
3068 Ops[0], Ops.slice(1));
3069 return GetElementPtrInst::Create(GO->getSourceElementType(), Ops[0],
3072 case Instruction::ICmp:
3073 case Instruction::FCmp:
3074 return CmpInst::Create((Instruction::OtherOps)getOpcode(),
3075 getPredicate(), Ops[0], Ops[1]);
3078 assert(getNumOperands() == 2 && "Must be binary operator?");
3079 BinaryOperator *BO =
3080 BinaryOperator::Create((Instruction::BinaryOps)getOpcode(),
3082 if (isa<OverflowingBinaryOperator>(BO)) {
3083 BO->setHasNoUnsignedWrap(SubclassOptionalData &
3084 OverflowingBinaryOperator::NoUnsignedWrap);
3085 BO->setHasNoSignedWrap(SubclassOptionalData &
3086 OverflowingBinaryOperator::NoSignedWrap);
3088 if (isa<PossiblyExactOperator>(BO))
3089 BO->setIsExact(SubclassOptionalData & PossiblyExactOperator::IsExact);