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/Constants.h"
15 #include "LLVMContextImpl.h"
16 #include "ConstantFold.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/GlobalValue.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Module.h"
21 #include "llvm/Operator.h"
22 #include "llvm/ADT/FoldingSet.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/StringMap.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/MathExtras.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Support/GetElementPtrTypeIterator.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/STLExtras.h"
39 //===----------------------------------------------------------------------===//
41 //===----------------------------------------------------------------------===//
43 bool Constant::isNegativeZeroValue() const {
44 // Floating point values have an explicit -0.0 value.
45 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
46 return CFP->isZero() && CFP->isNegative();
48 // Otherwise, just use +0.0.
52 bool Constant::isNullValue() const {
54 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
58 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
59 return CFP->isZero() && !CFP->isNegative();
61 // constant zero is zero for aggregates and cpnull is null for pointers.
62 return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this);
65 // Constructor to create a '0' constant of arbitrary type...
66 Constant *Constant::getNullValue(Type *Ty) {
67 switch (Ty->getTypeID()) {
68 case Type::IntegerTyID:
69 return ConstantInt::get(Ty, 0);
71 return ConstantFP::get(Ty->getContext(),
72 APFloat::getZero(APFloat::IEEEsingle));
73 case Type::DoubleTyID:
74 return ConstantFP::get(Ty->getContext(),
75 APFloat::getZero(APFloat::IEEEdouble));
76 case Type::X86_FP80TyID:
77 return ConstantFP::get(Ty->getContext(),
78 APFloat::getZero(APFloat::x87DoubleExtended));
80 return ConstantFP::get(Ty->getContext(),
81 APFloat::getZero(APFloat::IEEEquad));
82 case Type::PPC_FP128TyID:
83 return ConstantFP::get(Ty->getContext(),
84 APFloat(APInt::getNullValue(128)));
85 case Type::PointerTyID:
86 return ConstantPointerNull::get(cast<PointerType>(Ty));
87 case Type::StructTyID:
89 case Type::VectorTyID:
90 return ConstantAggregateZero::get(Ty);
92 // Function, Label, or Opaque type?
93 assert(!"Cannot create a null constant of that type!");
98 Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) {
99 Type *ScalarTy = Ty->getScalarType();
101 // Create the base integer constant.
102 Constant *C = ConstantInt::get(Ty->getContext(), V);
104 // Convert an integer to a pointer, if necessary.
105 if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
106 C = ConstantExpr::getIntToPtr(C, PTy);
108 // Broadcast a scalar to a vector, if necessary.
109 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
110 C = ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
115 Constant *Constant::getAllOnesValue(Type *Ty) {
116 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
117 return ConstantInt::get(Ty->getContext(),
118 APInt::getAllOnesValue(ITy->getBitWidth()));
120 if (Ty->isFloatingPointTy()) {
121 APFloat FL = APFloat::getAllOnesValue(Ty->getPrimitiveSizeInBits(),
122 !Ty->isPPC_FP128Ty());
123 return ConstantFP::get(Ty->getContext(), FL);
126 SmallVector<Constant*, 16> Elts;
127 VectorType *VTy = cast<VectorType>(Ty);
128 Elts.resize(VTy->getNumElements(), getAllOnesValue(VTy->getElementType()));
129 assert(Elts[0] && "Not a vector integer type!");
130 return cast<ConstantVector>(ConstantVector::get(Elts));
133 void Constant::destroyConstantImpl() {
134 // When a Constant is destroyed, there may be lingering
135 // references to the constant by other constants in the constant pool. These
136 // constants are implicitly dependent on the module that is being deleted,
137 // but they don't know that. Because we only find out when the CPV is
138 // deleted, we must now notify all of our users (that should only be
139 // Constants) that they are, in fact, invalid now and should be deleted.
141 while (!use_empty()) {
142 Value *V = use_back();
143 #ifndef NDEBUG // Only in -g mode...
144 if (!isa<Constant>(V)) {
145 dbgs() << "While deleting: " << *this
146 << "\n\nUse still stuck around after Def is destroyed: "
150 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
151 Constant *CV = cast<Constant>(V);
152 CV->destroyConstant();
154 // The constant should remove itself from our use list...
155 assert((use_empty() || use_back() != V) && "Constant not removed!");
158 // Value has no outstanding references it is safe to delete it now...
162 /// canTrap - Return true if evaluation of this constant could trap. This is
163 /// true for things like constant expressions that could divide by zero.
164 bool Constant::canTrap() const {
165 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
166 // The only thing that could possibly trap are constant exprs.
167 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
168 if (!CE) return false;
170 // ConstantExpr traps if any operands can trap.
171 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
172 if (CE->getOperand(i)->canTrap())
175 // Otherwise, only specific operations can trap.
176 switch (CE->getOpcode()) {
179 case Instruction::UDiv:
180 case Instruction::SDiv:
181 case Instruction::FDiv:
182 case Instruction::URem:
183 case Instruction::SRem:
184 case Instruction::FRem:
185 // Div and rem can trap if the RHS is not known to be non-zero.
186 if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
192 /// isConstantUsed - Return true if the constant has users other than constant
193 /// exprs and other dangling things.
194 bool Constant::isConstantUsed() const {
195 for (const_use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
196 const Constant *UC = dyn_cast<Constant>(*UI);
197 if (UC == 0 || isa<GlobalValue>(UC))
200 if (UC->isConstantUsed())
208 /// getRelocationInfo - This method classifies the entry according to
209 /// whether or not it may generate a relocation entry. This must be
210 /// conservative, so if it might codegen to a relocatable entry, it should say
211 /// so. The return values are:
213 /// NoRelocation: This constant pool entry is guaranteed to never have a
214 /// relocation applied to it (because it holds a simple constant like
216 /// LocalRelocation: This entry has relocations, but the entries are
217 /// guaranteed to be resolvable by the static linker, so the dynamic
218 /// linker will never see them.
219 /// GlobalRelocations: This entry may have arbitrary relocations.
221 /// FIXME: This really should not be in VMCore.
222 Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
223 if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
224 if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
225 return LocalRelocation; // Local to this file/library.
226 return GlobalRelocations; // Global reference.
229 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
230 return BA->getFunction()->getRelocationInfo();
232 // While raw uses of blockaddress need to be relocated, differences between
233 // two of them don't when they are for labels in the same function. This is a
234 // common idiom when creating a table for the indirect goto extension, so we
235 // handle it efficiently here.
236 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this))
237 if (CE->getOpcode() == Instruction::Sub) {
238 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
239 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
241 LHS->getOpcode() == Instruction::PtrToInt &&
242 RHS->getOpcode() == Instruction::PtrToInt &&
243 isa<BlockAddress>(LHS->getOperand(0)) &&
244 isa<BlockAddress>(RHS->getOperand(0)) &&
245 cast<BlockAddress>(LHS->getOperand(0))->getFunction() ==
246 cast<BlockAddress>(RHS->getOperand(0))->getFunction())
250 PossibleRelocationsTy Result = NoRelocation;
251 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
252 Result = std::max(Result,
253 cast<Constant>(getOperand(i))->getRelocationInfo());
259 /// getVectorElements - This method, which is only valid on constant of vector
260 /// type, returns the elements of the vector in the specified smallvector.
261 /// This handles breaking down a vector undef into undef elements, etc. For
262 /// constant exprs and other cases we can't handle, we return an empty vector.
263 void Constant::getVectorElements(SmallVectorImpl<Constant*> &Elts) const {
264 assert(getType()->isVectorTy() && "Not a vector constant!");
266 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
267 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
268 Elts.push_back(CV->getOperand(i));
272 VectorType *VT = cast<VectorType>(getType());
273 if (isa<ConstantAggregateZero>(this)) {
274 Elts.assign(VT->getNumElements(),
275 Constant::getNullValue(VT->getElementType()));
279 if (isa<UndefValue>(this)) {
280 Elts.assign(VT->getNumElements(), UndefValue::get(VT->getElementType()));
284 // Unknown type, must be constant expr etc.
288 /// removeDeadUsersOfConstant - If the specified constantexpr is dead, remove
289 /// it. This involves recursively eliminating any dead users of the
291 static bool removeDeadUsersOfConstant(const Constant *C) {
292 if (isa<GlobalValue>(C)) return false; // Cannot remove this
294 while (!C->use_empty()) {
295 const Constant *User = dyn_cast<Constant>(C->use_back());
296 if (!User) return false; // Non-constant usage;
297 if (!removeDeadUsersOfConstant(User))
298 return false; // Constant wasn't dead
301 const_cast<Constant*>(C)->destroyConstant();
306 /// removeDeadConstantUsers - If there are any dead constant users dangling
307 /// off of this constant, remove them. This method is useful for clients
308 /// that want to check to see if a global is unused, but don't want to deal
309 /// with potentially dead constants hanging off of the globals.
310 void Constant::removeDeadConstantUsers() const {
311 Value::const_use_iterator I = use_begin(), E = use_end();
312 Value::const_use_iterator LastNonDeadUser = E;
314 const Constant *User = dyn_cast<Constant>(*I);
321 if (!removeDeadUsersOfConstant(User)) {
322 // If the constant wasn't dead, remember that this was the last live use
323 // and move on to the next constant.
329 // If the constant was dead, then the iterator is invalidated.
330 if (LastNonDeadUser == E) {
342 //===----------------------------------------------------------------------===//
344 //===----------------------------------------------------------------------===//
346 ConstantInt::ConstantInt(IntegerType *Ty, const APInt& V)
347 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
348 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
351 ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
352 LLVMContextImpl *pImpl = Context.pImpl;
353 if (!pImpl->TheTrueVal)
354 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
355 return pImpl->TheTrueVal;
358 ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
359 LLVMContextImpl *pImpl = Context.pImpl;
360 if (!pImpl->TheFalseVal)
361 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
362 return pImpl->TheFalseVal;
365 Constant *ConstantInt::getTrue(Type *Ty) {
366 VectorType *VTy = dyn_cast<VectorType>(Ty);
368 assert(Ty->isIntegerTy(1) && "True must be i1 or vector of i1.");
369 return ConstantInt::getTrue(Ty->getContext());
371 assert(VTy->getElementType()->isIntegerTy(1) &&
372 "True must be vector of i1 or i1.");
373 SmallVector<Constant*, 16> Splat(VTy->getNumElements(),
374 ConstantInt::getTrue(Ty->getContext()));
375 return ConstantVector::get(Splat);
378 Constant *ConstantInt::getFalse(Type *Ty) {
379 VectorType *VTy = dyn_cast<VectorType>(Ty);
381 assert(Ty->isIntegerTy(1) && "False must be i1 or vector of i1.");
382 return ConstantInt::getFalse(Ty->getContext());
384 assert(VTy->getElementType()->isIntegerTy(1) &&
385 "False must be vector of i1 or i1.");
386 SmallVector<Constant*, 16> Splat(VTy->getNumElements(),
387 ConstantInt::getFalse(Ty->getContext()));
388 return ConstantVector::get(Splat);
392 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
393 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
394 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
395 // compare APInt's of different widths, which would violate an APInt class
396 // invariant which generates an assertion.
397 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
398 // Get the corresponding integer type for the bit width of the value.
399 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
400 // get an existing value or the insertion position
401 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
402 ConstantInt *&Slot = Context.pImpl->IntConstants[Key];
403 if (!Slot) Slot = new ConstantInt(ITy, V);
407 Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
408 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
410 // For vectors, broadcast the value.
411 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
412 return ConstantVector::get(SmallVector<Constant*,
413 16>(VTy->getNumElements(), C));
418 ConstantInt* ConstantInt::get(IntegerType* Ty, uint64_t V,
420 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
423 ConstantInt* ConstantInt::getSigned(IntegerType* Ty, int64_t V) {
424 return get(Ty, V, true);
427 Constant *ConstantInt::getSigned(Type *Ty, int64_t V) {
428 return get(Ty, V, true);
431 Constant *ConstantInt::get(Type* Ty, const APInt& V) {
432 ConstantInt *C = get(Ty->getContext(), V);
433 assert(C->getType() == Ty->getScalarType() &&
434 "ConstantInt type doesn't match the type implied by its value!");
436 // For vectors, broadcast the value.
437 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
438 return ConstantVector::get(
439 SmallVector<Constant *, 16>(VTy->getNumElements(), C));
444 ConstantInt* ConstantInt::get(IntegerType* Ty, StringRef Str,
446 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
449 //===----------------------------------------------------------------------===//
451 //===----------------------------------------------------------------------===//
453 static const fltSemantics *TypeToFloatSemantics(Type *Ty) {
455 return &APFloat::IEEEsingle;
456 if (Ty->isDoubleTy())
457 return &APFloat::IEEEdouble;
458 if (Ty->isX86_FP80Ty())
459 return &APFloat::x87DoubleExtended;
460 else if (Ty->isFP128Ty())
461 return &APFloat::IEEEquad;
463 assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
464 return &APFloat::PPCDoubleDouble;
467 /// get() - This returns a constant fp for the specified value in the
468 /// specified type. This should only be used for simple constant values like
469 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
470 Constant *ConstantFP::get(Type* Ty, double V) {
471 LLVMContext &Context = Ty->getContext();
475 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
476 APFloat::rmNearestTiesToEven, &ignored);
477 Constant *C = get(Context, FV);
479 // For vectors, broadcast the value.
480 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
481 return ConstantVector::get(
482 SmallVector<Constant *, 16>(VTy->getNumElements(), C));
488 Constant *ConstantFP::get(Type* Ty, StringRef Str) {
489 LLVMContext &Context = Ty->getContext();
491 APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
492 Constant *C = get(Context, FV);
494 // For vectors, broadcast the value.
495 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
496 return ConstantVector::get(
497 SmallVector<Constant *, 16>(VTy->getNumElements(), C));
503 ConstantFP* ConstantFP::getNegativeZero(Type* Ty) {
504 LLVMContext &Context = Ty->getContext();
505 APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
507 return get(Context, apf);
511 Constant *ConstantFP::getZeroValueForNegation(Type* Ty) {
512 if (VectorType *PTy = dyn_cast<VectorType>(Ty))
513 if (PTy->getElementType()->isFloatingPointTy()) {
514 SmallVector<Constant*, 16> zeros(PTy->getNumElements(),
515 getNegativeZero(PTy->getElementType()));
516 return ConstantVector::get(zeros);
519 if (Ty->isFloatingPointTy())
520 return getNegativeZero(Ty);
522 return Constant::getNullValue(Ty);
526 // ConstantFP accessors.
527 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
528 DenseMapAPFloatKeyInfo::KeyTy Key(V);
530 LLVMContextImpl* pImpl = Context.pImpl;
532 ConstantFP *&Slot = pImpl->FPConstants[Key];
536 if (&V.getSemantics() == &APFloat::IEEEsingle)
537 Ty = Type::getFloatTy(Context);
538 else if (&V.getSemantics() == &APFloat::IEEEdouble)
539 Ty = Type::getDoubleTy(Context);
540 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
541 Ty = Type::getX86_FP80Ty(Context);
542 else if (&V.getSemantics() == &APFloat::IEEEquad)
543 Ty = Type::getFP128Ty(Context);
545 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
546 "Unknown FP format");
547 Ty = Type::getPPC_FP128Ty(Context);
549 Slot = new ConstantFP(Ty, V);
555 ConstantFP *ConstantFP::getInfinity(Type *Ty, bool Negative) {
556 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty);
557 return ConstantFP::get(Ty->getContext(),
558 APFloat::getInf(Semantics, Negative));
561 ConstantFP::ConstantFP(Type *Ty, const APFloat& V)
562 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
563 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
567 bool ConstantFP::isExactlyValue(const APFloat &V) const {
568 return Val.bitwiseIsEqual(V);
571 //===----------------------------------------------------------------------===//
572 // ConstantXXX Classes
573 //===----------------------------------------------------------------------===//
576 ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
577 : Constant(T, ConstantArrayVal,
578 OperandTraits<ConstantArray>::op_end(this) - V.size(),
580 assert(V.size() == T->getNumElements() &&
581 "Invalid initializer vector for constant array");
582 for (unsigned i = 0, e = V.size(); i != e; ++i)
583 assert(V[i]->getType() == T->getElementType() &&
584 "Initializer for array element doesn't match array element type!");
585 std::copy(V.begin(), V.end(), op_begin());
588 Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
589 for (unsigned i = 0, e = V.size(); i != e; ++i) {
590 assert(V[i]->getType() == Ty->getElementType() &&
591 "Wrong type in array element initializer");
593 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
594 // If this is an all-zero array, return a ConstantAggregateZero object
597 if (!C->isNullValue())
598 return pImpl->ArrayConstants.getOrCreate(Ty, V);
600 for (unsigned i = 1, e = V.size(); i != e; ++i)
602 return pImpl->ArrayConstants.getOrCreate(Ty, V);
605 return ConstantAggregateZero::get(Ty);
608 /// ConstantArray::get(const string&) - Return an array that is initialized to
609 /// contain the specified string. If length is zero then a null terminator is
610 /// added to the specified string so that it may be used in a natural way.
611 /// Otherwise, the length parameter specifies how much of the string to use
612 /// and it won't be null terminated.
614 Constant *ConstantArray::get(LLVMContext &Context, StringRef Str,
616 std::vector<Constant*> ElementVals;
617 ElementVals.reserve(Str.size() + size_t(AddNull));
618 for (unsigned i = 0; i < Str.size(); ++i)
619 ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), Str[i]));
621 // Add a null terminator to the string...
623 ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), 0));
626 ArrayType *ATy = ArrayType::get(Type::getInt8Ty(Context), ElementVals.size());
627 return get(ATy, ElementVals);
630 /// getTypeForElements - Return an anonymous struct type to use for a constant
631 /// with the specified set of elements. The list must not be empty.
632 StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
633 ArrayRef<Constant*> V,
635 SmallVector<Type*, 16> EltTypes;
636 for (unsigned i = 0, e = V.size(); i != e; ++i)
637 EltTypes.push_back(V[i]->getType());
639 return StructType::get(Context, EltTypes, Packed);
643 StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
646 "ConstantStruct::getTypeForElements cannot be called on empty list");
647 return getTypeForElements(V[0]->getContext(), V, Packed);
651 ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
652 : Constant(T, ConstantStructVal,
653 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
655 assert(V.size() == T->getNumElements() &&
656 "Invalid initializer vector for constant structure");
657 for (unsigned i = 0, e = V.size(); i != e; ++i)
658 assert((T->isOpaque() || V[i]->getType() == T->getElementType(i)) &&
659 "Initializer for struct element doesn't match struct element type!");
660 std::copy(V.begin(), V.end(), op_begin());
663 // ConstantStruct accessors.
664 Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
665 // Create a ConstantAggregateZero value if all elements are zeros.
666 for (unsigned i = 0, e = V.size(); i != e; ++i)
667 if (!V[i]->isNullValue())
668 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
670 assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
671 "Incorrect # elements specified to ConstantStruct::get");
672 return ConstantAggregateZero::get(ST);
675 Constant *ConstantStruct::get(StructType *T, ...) {
677 SmallVector<Constant*, 8> Values;
679 while (Constant *Val = va_arg(ap, llvm::Constant*))
680 Values.push_back(Val);
682 return get(T, Values);
685 ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
686 : Constant(T, ConstantVectorVal,
687 OperandTraits<ConstantVector>::op_end(this) - V.size(),
689 for (size_t i = 0, e = V.size(); i != e; i++)
690 assert(V[i]->getType() == T->getElementType() &&
691 "Initializer for vector element doesn't match vector element type!");
692 std::copy(V.begin(), V.end(), op_begin());
695 // ConstantVector accessors.
696 Constant *ConstantVector::get(ArrayRef<Constant*> V) {
697 assert(!V.empty() && "Vectors can't be empty");
698 VectorType *T = VectorType::get(V.front()->getType(), V.size());
699 LLVMContextImpl *pImpl = T->getContext().pImpl;
701 // If this is an all-undef or all-zero vector, return a
702 // ConstantAggregateZero or UndefValue.
704 bool isZero = C->isNullValue();
705 bool isUndef = isa<UndefValue>(C);
707 if (isZero || isUndef) {
708 for (unsigned i = 1, e = V.size(); i != e; ++i)
710 isZero = isUndef = false;
716 return ConstantAggregateZero::get(T);
718 return UndefValue::get(T);
720 return pImpl->VectorConstants.getOrCreate(T, V);
723 // Utility function for determining if a ConstantExpr is a CastOp or not. This
724 // can't be inline because we don't want to #include Instruction.h into
726 bool ConstantExpr::isCast() const {
727 return Instruction::isCast(getOpcode());
730 bool ConstantExpr::isCompare() const {
731 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
734 bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
735 if (getOpcode() != Instruction::GetElementPtr) return false;
737 gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
738 User::const_op_iterator OI = llvm::next(this->op_begin());
740 // Skip the first index, as it has no static limit.
744 // The remaining indices must be compile-time known integers within the
745 // bounds of the corresponding notional static array types.
746 for (; GEPI != E; ++GEPI, ++OI) {
747 ConstantInt *CI = dyn_cast<ConstantInt>(*OI);
748 if (!CI) return false;
749 if (ArrayType *ATy = dyn_cast<ArrayType>(*GEPI))
750 if (CI->getValue().getActiveBits() > 64 ||
751 CI->getZExtValue() >= ATy->getNumElements())
755 // All the indices checked out.
759 bool ConstantExpr::hasIndices() const {
760 return getOpcode() == Instruction::ExtractValue ||
761 getOpcode() == Instruction::InsertValue;
764 ArrayRef<unsigned> ConstantExpr::getIndices() const {
765 if (const ExtractValueConstantExpr *EVCE =
766 dyn_cast<ExtractValueConstantExpr>(this))
767 return EVCE->Indices;
769 return cast<InsertValueConstantExpr>(this)->Indices;
772 unsigned ConstantExpr::getPredicate() const {
774 return ((const CompareConstantExpr*)this)->predicate;
777 /// getWithOperandReplaced - Return a constant expression identical to this
778 /// one, but with the specified operand set to the specified value.
780 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
781 assert(OpNo < getNumOperands() && "Operand num is out of range!");
782 assert(Op->getType() == getOperand(OpNo)->getType() &&
783 "Replacing operand with value of different type!");
784 if (getOperand(OpNo) == Op)
785 return const_cast<ConstantExpr*>(this);
787 Constant *Op0, *Op1, *Op2;
788 switch (getOpcode()) {
789 case Instruction::Trunc:
790 case Instruction::ZExt:
791 case Instruction::SExt:
792 case Instruction::FPTrunc:
793 case Instruction::FPExt:
794 case Instruction::UIToFP:
795 case Instruction::SIToFP:
796 case Instruction::FPToUI:
797 case Instruction::FPToSI:
798 case Instruction::PtrToInt:
799 case Instruction::IntToPtr:
800 case Instruction::BitCast:
801 return ConstantExpr::getCast(getOpcode(), Op, getType());
802 case Instruction::Select:
803 Op0 = (OpNo == 0) ? Op : getOperand(0);
804 Op1 = (OpNo == 1) ? Op : getOperand(1);
805 Op2 = (OpNo == 2) ? Op : getOperand(2);
806 return ConstantExpr::getSelect(Op0, Op1, Op2);
807 case Instruction::InsertElement:
808 Op0 = (OpNo == 0) ? Op : getOperand(0);
809 Op1 = (OpNo == 1) ? Op : getOperand(1);
810 Op2 = (OpNo == 2) ? Op : getOperand(2);
811 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
812 case Instruction::ExtractElement:
813 Op0 = (OpNo == 0) ? Op : getOperand(0);
814 Op1 = (OpNo == 1) ? Op : getOperand(1);
815 return ConstantExpr::getExtractElement(Op0, Op1);
816 case Instruction::ShuffleVector:
817 Op0 = (OpNo == 0) ? Op : getOperand(0);
818 Op1 = (OpNo == 1) ? Op : getOperand(1);
819 Op2 = (OpNo == 2) ? Op : getOperand(2);
820 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
821 case Instruction::GetElementPtr: {
822 SmallVector<Constant*, 8> Ops;
823 Ops.resize(getNumOperands()-1);
824 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
825 Ops[i-1] = getOperand(i);
828 ConstantExpr::getGetElementPtr(Op, Ops,
829 cast<GEPOperator>(this)->isInBounds());
832 ConstantExpr::getGetElementPtr(getOperand(0), Ops,
833 cast<GEPOperator>(this)->isInBounds());
836 assert(getNumOperands() == 2 && "Must be binary operator?");
837 Op0 = (OpNo == 0) ? Op : getOperand(0);
838 Op1 = (OpNo == 1) ? Op : getOperand(1);
839 return ConstantExpr::get(getOpcode(), Op0, Op1, SubclassOptionalData);
843 /// getWithOperands - This returns the current constant expression with the
844 /// operands replaced with the specified values. The specified array must
845 /// have the same number of operands as our current one.
846 Constant *ConstantExpr::
847 getWithOperands(ArrayRef<Constant*> Ops, Type *Ty) const {
848 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
849 bool AnyChange = Ty != getType();
850 for (unsigned i = 0; i != Ops.size(); ++i)
851 AnyChange |= Ops[i] != getOperand(i);
853 if (!AnyChange) // No operands changed, return self.
854 return const_cast<ConstantExpr*>(this);
856 switch (getOpcode()) {
857 case Instruction::Trunc:
858 case Instruction::ZExt:
859 case Instruction::SExt:
860 case Instruction::FPTrunc:
861 case Instruction::FPExt:
862 case Instruction::UIToFP:
863 case Instruction::SIToFP:
864 case Instruction::FPToUI:
865 case Instruction::FPToSI:
866 case Instruction::PtrToInt:
867 case Instruction::IntToPtr:
868 case Instruction::BitCast:
869 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty);
870 case Instruction::Select:
871 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
872 case Instruction::InsertElement:
873 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
874 case Instruction::ExtractElement:
875 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
876 case Instruction::ShuffleVector:
877 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
878 case Instruction::GetElementPtr:
880 ConstantExpr::getGetElementPtr(Ops[0], Ops.slice(1),
881 cast<GEPOperator>(this)->isInBounds());
882 case Instruction::ICmp:
883 case Instruction::FCmp:
884 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
886 assert(getNumOperands() == 2 && "Must be binary operator?");
887 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData);
892 //===----------------------------------------------------------------------===//
893 // isValueValidForType implementations
895 bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
896 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
897 if (Ty == Type::getInt1Ty(Ty->getContext()))
898 return Val == 0 || Val == 1;
900 return true; // always true, has to fit in largest type
901 uint64_t Max = (1ll << NumBits) - 1;
905 bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
906 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
907 if (Ty == Type::getInt1Ty(Ty->getContext()))
908 return Val == 0 || Val == 1 || Val == -1;
910 return true; // always true, has to fit in largest type
911 int64_t Min = -(1ll << (NumBits-1));
912 int64_t Max = (1ll << (NumBits-1)) - 1;
913 return (Val >= Min && Val <= Max);
916 bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {
917 // convert modifies in place, so make a copy.
918 APFloat Val2 = APFloat(Val);
920 switch (Ty->getTypeID()) {
922 return false; // These can't be represented as floating point!
924 // FIXME rounding mode needs to be more flexible
925 case Type::FloatTyID: {
926 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
928 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
931 case Type::DoubleTyID: {
932 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
933 &Val2.getSemantics() == &APFloat::IEEEdouble)
935 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
938 case Type::X86_FP80TyID:
939 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
940 &Val2.getSemantics() == &APFloat::IEEEdouble ||
941 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
942 case Type::FP128TyID:
943 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
944 &Val2.getSemantics() == &APFloat::IEEEdouble ||
945 &Val2.getSemantics() == &APFloat::IEEEquad;
946 case Type::PPC_FP128TyID:
947 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
948 &Val2.getSemantics() == &APFloat::IEEEdouble ||
949 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
953 //===----------------------------------------------------------------------===//
954 // Factory Function Implementation
956 ConstantAggregateZero* ConstantAggregateZero::get(Type* Ty) {
957 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
958 "Cannot create an aggregate zero of non-aggregate type!");
960 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
961 return pImpl->AggZeroConstants.getOrCreate(Ty, 0);
964 /// destroyConstant - Remove the constant from the constant table...
966 void ConstantAggregateZero::destroyConstant() {
967 getType()->getContext().pImpl->AggZeroConstants.remove(this);
968 destroyConstantImpl();
971 /// destroyConstant - Remove the constant from the constant table...
973 void ConstantArray::destroyConstant() {
974 getType()->getContext().pImpl->ArrayConstants.remove(this);
975 destroyConstantImpl();
978 /// isString - This method returns true if the array is an array of i8, and
979 /// if the elements of the array are all ConstantInt's.
980 bool ConstantArray::isString() const {
981 // Check the element type for i8...
982 if (!getType()->getElementType()->isIntegerTy(8))
984 // Check the elements to make sure they are all integers, not constant
986 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
987 if (!isa<ConstantInt>(getOperand(i)))
992 /// isCString - This method returns true if the array is a string (see
993 /// isString) and it ends in a null byte \\0 and does not contains any other
994 /// null bytes except its terminator.
995 bool ConstantArray::isCString() const {
996 // Check the element type for i8...
997 if (!getType()->getElementType()->isIntegerTy(8))
1000 // Last element must be a null.
1001 if (!getOperand(getNumOperands()-1)->isNullValue())
1003 // Other elements must be non-null integers.
1004 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1005 if (!isa<ConstantInt>(getOperand(i)))
1007 if (getOperand(i)->isNullValue())
1014 /// convertToString - Helper function for getAsString() and getAsCString().
1015 static std::string convertToString(const User *U, unsigned len) {
1017 Result.reserve(len);
1018 for (unsigned i = 0; i != len; ++i)
1019 Result.push_back((char)cast<ConstantInt>(U->getOperand(i))->getZExtValue());
1023 /// getAsString - If this array is isString(), then this method converts the
1024 /// array to an std::string and returns it. Otherwise, it asserts out.
1026 std::string ConstantArray::getAsString() const {
1027 assert(isString() && "Not a string!");
1028 return convertToString(this, getNumOperands());
1032 /// getAsCString - If this array is isCString(), then this method converts the
1033 /// array (without the trailing null byte) to an std::string and returns it.
1034 /// Otherwise, it asserts out.
1036 std::string ConstantArray::getAsCString() const {
1037 assert(isCString() && "Not a string!");
1038 return convertToString(this, getNumOperands() - 1);
1042 //---- ConstantStruct::get() implementation...
1045 // destroyConstant - Remove the constant from the constant table...
1047 void ConstantStruct::destroyConstant() {
1048 getType()->getContext().pImpl->StructConstants.remove(this);
1049 destroyConstantImpl();
1052 // destroyConstant - Remove the constant from the constant table...
1054 void ConstantVector::destroyConstant() {
1055 getType()->getContext().pImpl->VectorConstants.remove(this);
1056 destroyConstantImpl();
1059 /// This function will return true iff every element in this vector constant
1060 /// is set to all ones.
1061 /// @returns true iff this constant's elements are all set to all ones.
1062 /// @brief Determine if the value is all ones.
1063 bool ConstantVector::isAllOnesValue() const {
1064 // Check out first element.
1065 const Constant *Elt = getOperand(0);
1066 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1067 if (!CI || !CI->isAllOnesValue()) return false;
1068 // Then make sure all remaining elements point to the same value.
1069 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1070 if (getOperand(I) != Elt)
1076 /// getSplatValue - If this is a splat constant, where all of the
1077 /// elements have the same value, return that value. Otherwise return null.
1078 Constant *ConstantVector::getSplatValue() const {
1079 // Check out first element.
1080 Constant *Elt = getOperand(0);
1081 // Then make sure all remaining elements point to the same value.
1082 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1083 if (getOperand(I) != Elt)
1088 //---- ConstantPointerNull::get() implementation.
1091 ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
1092 return Ty->getContext().pImpl->NullPtrConstants.getOrCreate(Ty, 0);
1095 // destroyConstant - Remove the constant from the constant table...
1097 void ConstantPointerNull::destroyConstant() {
1098 getType()->getContext().pImpl->NullPtrConstants.remove(this);
1099 destroyConstantImpl();
1103 //---- UndefValue::get() implementation.
1106 UndefValue *UndefValue::get(Type *Ty) {
1107 return Ty->getContext().pImpl->UndefValueConstants.getOrCreate(Ty, 0);
1110 // destroyConstant - Remove the constant from the constant table.
1112 void UndefValue::destroyConstant() {
1113 getType()->getContext().pImpl->UndefValueConstants.remove(this);
1114 destroyConstantImpl();
1117 //---- BlockAddress::get() implementation.
1120 BlockAddress *BlockAddress::get(BasicBlock *BB) {
1121 assert(BB->getParent() != 0 && "Block must have a parent");
1122 return get(BB->getParent(), BB);
1125 BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1127 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
1129 BA = new BlockAddress(F, BB);
1131 assert(BA->getFunction() == F && "Basic block moved between functions");
1135 BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1136 : Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1140 BB->AdjustBlockAddressRefCount(1);
1144 // destroyConstant - Remove the constant from the constant table.
1146 void BlockAddress::destroyConstant() {
1147 getFunction()->getType()->getContext().pImpl
1148 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
1149 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1150 destroyConstantImpl();
1153 void BlockAddress::replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U) {
1154 // This could be replacing either the Basic Block or the Function. In either
1155 // case, we have to remove the map entry.
1156 Function *NewF = getFunction();
1157 BasicBlock *NewBB = getBasicBlock();
1160 NewF = cast<Function>(To);
1162 NewBB = cast<BasicBlock>(To);
1164 // See if the 'new' entry already exists, if not, just update this in place
1165 // and return early.
1166 BlockAddress *&NewBA =
1167 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
1169 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1171 // Remove the old entry, this can't cause the map to rehash (just a
1172 // tombstone will get added).
1173 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1176 setOperand(0, NewF);
1177 setOperand(1, NewBB);
1178 getBasicBlock()->AdjustBlockAddressRefCount(1);
1182 // Otherwise, I do need to replace this with an existing value.
1183 assert(NewBA != this && "I didn't contain From!");
1185 // Everyone using this now uses the replacement.
1186 replaceAllUsesWith(NewBA);
1191 //---- ConstantExpr::get() implementations.
1194 /// This is a utility function to handle folding of casts and lookup of the
1195 /// cast in the ExprConstants map. It is used by the various get* methods below.
1196 static inline Constant *getFoldedCast(
1197 Instruction::CastOps opc, Constant *C, Type *Ty) {
1198 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1199 // Fold a few common cases
1200 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1203 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1205 // Look up the constant in the table first to ensure uniqueness
1206 std::vector<Constant*> argVec(1, C);
1207 ExprMapKeyType Key(opc, argVec);
1209 return pImpl->ExprConstants.getOrCreate(Ty, Key);
1212 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty) {
1213 Instruction::CastOps opc = Instruction::CastOps(oc);
1214 assert(Instruction::isCast(opc) && "opcode out of range");
1215 assert(C && Ty && "Null arguments to getCast");
1216 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
1220 llvm_unreachable("Invalid cast opcode");
1222 case Instruction::Trunc: return getTrunc(C, Ty);
1223 case Instruction::ZExt: return getZExt(C, Ty);
1224 case Instruction::SExt: return getSExt(C, Ty);
1225 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1226 case Instruction::FPExt: return getFPExtend(C, Ty);
1227 case Instruction::UIToFP: return getUIToFP(C, Ty);
1228 case Instruction::SIToFP: return getSIToFP(C, Ty);
1229 case Instruction::FPToUI: return getFPToUI(C, Ty);
1230 case Instruction::FPToSI: return getFPToSI(C, Ty);
1231 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1232 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1233 case Instruction::BitCast: return getBitCast(C, Ty);
1238 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) {
1239 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1240 return getBitCast(C, Ty);
1241 return getZExt(C, Ty);
1244 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) {
1245 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1246 return getBitCast(C, Ty);
1247 return getSExt(C, Ty);
1250 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {
1251 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1252 return getBitCast(C, Ty);
1253 return getTrunc(C, Ty);
1256 Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {
1257 assert(S->getType()->isPointerTy() && "Invalid cast");
1258 assert((Ty->isIntegerTy() || Ty->isPointerTy()) && "Invalid cast");
1260 if (Ty->isIntegerTy())
1261 return getPtrToInt(S, Ty);
1262 return getBitCast(S, Ty);
1265 Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty,
1267 assert(C->getType()->isIntOrIntVectorTy() &&
1268 Ty->isIntOrIntVectorTy() && "Invalid cast");
1269 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1270 unsigned DstBits = Ty->getScalarSizeInBits();
1271 Instruction::CastOps opcode =
1272 (SrcBits == DstBits ? Instruction::BitCast :
1273 (SrcBits > DstBits ? Instruction::Trunc :
1274 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1275 return getCast(opcode, C, Ty);
1278 Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) {
1279 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1281 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1282 unsigned DstBits = Ty->getScalarSizeInBits();
1283 if (SrcBits == DstBits)
1284 return C; // Avoid a useless cast
1285 Instruction::CastOps opcode =
1286 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1287 return getCast(opcode, C, Ty);
1290 Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty) {
1292 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1293 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1295 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1296 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
1297 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
1298 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1299 "SrcTy must be larger than DestTy for Trunc!");
1301 return getFoldedCast(Instruction::Trunc, C, Ty);
1304 Constant *ConstantExpr::getSExt(Constant *C, Type *Ty) {
1306 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1307 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1309 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1310 assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
1311 assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
1312 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1313 "SrcTy must be smaller than DestTy for SExt!");
1315 return getFoldedCast(Instruction::SExt, C, Ty);
1318 Constant *ConstantExpr::getZExt(Constant *C, Type *Ty) {
1320 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1321 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1323 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1324 assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
1325 assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
1326 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1327 "SrcTy must be smaller than DestTy for ZExt!");
1329 return getFoldedCast(Instruction::ZExt, C, Ty);
1332 Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty) {
1334 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1335 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1337 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1338 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1339 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1340 "This is an illegal floating point truncation!");
1341 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1344 Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty) {
1346 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1347 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1349 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1350 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1351 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1352 "This is an illegal floating point extension!");
1353 return getFoldedCast(Instruction::FPExt, C, Ty);
1356 Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty) {
1358 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1359 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1361 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1362 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1363 "This is an illegal uint to floating point cast!");
1364 return getFoldedCast(Instruction::UIToFP, C, Ty);
1367 Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty) {
1369 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1370 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1372 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1373 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1374 "This is an illegal sint to floating point cast!");
1375 return getFoldedCast(Instruction::SIToFP, C, Ty);
1378 Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty) {
1380 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1381 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1383 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1384 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1385 "This is an illegal floating point to uint cast!");
1386 return getFoldedCast(Instruction::FPToUI, C, Ty);
1389 Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty) {
1391 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1392 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1394 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1395 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1396 "This is an illegal floating point to sint cast!");
1397 return getFoldedCast(Instruction::FPToSI, C, Ty);
1400 Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy) {
1401 assert(C->getType()->isPointerTy() && "PtrToInt source must be pointer");
1402 assert(DstTy->isIntegerTy() && "PtrToInt destination must be integral");
1403 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1406 Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy) {
1407 assert(C->getType()->isIntegerTy() && "IntToPtr source must be integral");
1408 assert(DstTy->isPointerTy() && "IntToPtr destination must be a pointer");
1409 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1412 Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy) {
1413 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
1414 "Invalid constantexpr bitcast!");
1416 // It is common to ask for a bitcast of a value to its own type, handle this
1418 if (C->getType() == DstTy) return C;
1420 return getFoldedCast(Instruction::BitCast, C, DstTy);
1423 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
1425 // Check the operands for consistency first.
1426 assert(Opcode >= Instruction::BinaryOpsBegin &&
1427 Opcode < Instruction::BinaryOpsEnd &&
1428 "Invalid opcode in binary constant expression");
1429 assert(C1->getType() == C2->getType() &&
1430 "Operand types in binary constant expression should match");
1434 case Instruction::Add:
1435 case Instruction::Sub:
1436 case Instruction::Mul:
1437 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1438 assert(C1->getType()->isIntOrIntVectorTy() &&
1439 "Tried to create an integer operation on a non-integer type!");
1441 case Instruction::FAdd:
1442 case Instruction::FSub:
1443 case Instruction::FMul:
1444 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1445 assert(C1->getType()->isFPOrFPVectorTy() &&
1446 "Tried to create a floating-point operation on a "
1447 "non-floating-point type!");
1449 case Instruction::UDiv:
1450 case Instruction::SDiv:
1451 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1452 assert(C1->getType()->isIntOrIntVectorTy() &&
1453 "Tried to create an arithmetic operation on a non-arithmetic type!");
1455 case Instruction::FDiv:
1456 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1457 assert(C1->getType()->isFPOrFPVectorTy() &&
1458 "Tried to create an arithmetic operation on a non-arithmetic type!");
1460 case Instruction::URem:
1461 case Instruction::SRem:
1462 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1463 assert(C1->getType()->isIntOrIntVectorTy() &&
1464 "Tried to create an arithmetic operation on a non-arithmetic type!");
1466 case Instruction::FRem:
1467 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1468 assert(C1->getType()->isFPOrFPVectorTy() &&
1469 "Tried to create an arithmetic operation on a non-arithmetic type!");
1471 case Instruction::And:
1472 case Instruction::Or:
1473 case Instruction::Xor:
1474 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1475 assert(C1->getType()->isIntOrIntVectorTy() &&
1476 "Tried to create a logical operation on a non-integral type!");
1478 case Instruction::Shl:
1479 case Instruction::LShr:
1480 case Instruction::AShr:
1481 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1482 assert(C1->getType()->isIntOrIntVectorTy() &&
1483 "Tried to create a shift operation on a non-integer type!");
1490 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1491 return FC; // Fold a few common cases.
1493 std::vector<Constant*> argVec(1, C1);
1494 argVec.push_back(C2);
1495 ExprMapKeyType Key(Opcode, argVec, 0, Flags);
1497 LLVMContextImpl *pImpl = C1->getContext().pImpl;
1498 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
1501 Constant *ConstantExpr::getSizeOf(Type* Ty) {
1502 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1503 // Note that a non-inbounds gep is used, as null isn't within any object.
1504 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1505 Constant *GEP = getGetElementPtr(
1506 Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
1507 return getPtrToInt(GEP,
1508 Type::getInt64Ty(Ty->getContext()));
1511 Constant *ConstantExpr::getAlignOf(Type* Ty) {
1512 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
1513 // Note that a non-inbounds gep is used, as null isn't within any object.
1515 StructType::get(Type::getInt1Ty(Ty->getContext()), Ty, NULL);
1516 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo());
1517 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
1518 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1519 Constant *Indices[2] = { Zero, One };
1520 Constant *GEP = getGetElementPtr(NullPtr, Indices);
1521 return getPtrToInt(GEP,
1522 Type::getInt64Ty(Ty->getContext()));
1525 Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) {
1526 return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
1530 Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) {
1531 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1532 // Note that a non-inbounds gep is used, as null isn't within any object.
1533 Constant *GEPIdx[] = {
1534 ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
1537 Constant *GEP = getGetElementPtr(
1538 Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
1539 return getPtrToInt(GEP,
1540 Type::getInt64Ty(Ty->getContext()));
1543 Constant *ConstantExpr::getCompare(unsigned short Predicate,
1544 Constant *C1, Constant *C2) {
1545 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1547 switch (Predicate) {
1548 default: llvm_unreachable("Invalid CmpInst predicate");
1549 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1550 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1551 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1552 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1553 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1554 case CmpInst::FCMP_TRUE:
1555 return getFCmp(Predicate, C1, C2);
1557 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1558 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1559 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1560 case CmpInst::ICMP_SLE:
1561 return getICmp(Predicate, C1, C2);
1565 Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2) {
1566 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1568 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1569 return SC; // Fold common cases
1571 std::vector<Constant*> argVec(3, C);
1574 ExprMapKeyType Key(Instruction::Select, argVec);
1576 LLVMContextImpl *pImpl = C->getContext().pImpl;
1577 return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
1580 Constant *ConstantExpr::getGetElementPtr(Constant *C, ArrayRef<Value *> Idxs,
1582 if (Constant *FC = ConstantFoldGetElementPtr(C, InBounds, Idxs))
1583 return FC; // Fold a few common cases.
1585 // Get the result type of the getelementptr!
1586 Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), Idxs);
1587 assert(Ty && "GEP indices invalid!");
1588 unsigned AS = cast<PointerType>(C->getType())->getAddressSpace();
1589 Type *ReqTy = Ty->getPointerTo(AS);
1591 assert(C->getType()->isPointerTy() &&
1592 "Non-pointer type for constant GetElementPtr expression");
1593 // Look up the constant in the table first to ensure uniqueness
1594 std::vector<Constant*> ArgVec;
1595 ArgVec.reserve(1 + Idxs.size());
1596 ArgVec.push_back(C);
1597 for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
1598 ArgVec.push_back(cast<Constant>(Idxs[i]));
1599 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
1600 InBounds ? GEPOperator::IsInBounds : 0);
1602 LLVMContextImpl *pImpl = C->getContext().pImpl;
1603 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1607 ConstantExpr::getICmp(unsigned short pred, Constant *LHS, Constant *RHS) {
1608 assert(LHS->getType() == RHS->getType());
1609 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1610 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1612 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1613 return FC; // Fold a few common cases...
1615 // Look up the constant in the table first to ensure uniqueness
1616 std::vector<Constant*> ArgVec;
1617 ArgVec.push_back(LHS);
1618 ArgVec.push_back(RHS);
1619 // Get the key type with both the opcode and predicate
1620 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1622 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1623 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1624 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1626 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1627 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
1631 ConstantExpr::getFCmp(unsigned short pred, Constant *LHS, Constant *RHS) {
1632 assert(LHS->getType() == RHS->getType());
1633 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1635 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1636 return FC; // Fold a few common cases...
1638 // Look up the constant in the table first to ensure uniqueness
1639 std::vector<Constant*> ArgVec;
1640 ArgVec.push_back(LHS);
1641 ArgVec.push_back(RHS);
1642 // Get the key type with both the opcode and predicate
1643 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1645 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1646 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1647 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1649 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1650 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
1653 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1654 assert(Val->getType()->isVectorTy() &&
1655 "Tried to create extractelement operation on non-vector type!");
1656 assert(Idx->getType()->isIntegerTy(32) &&
1657 "Extractelement index must be i32 type!");
1659 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1660 return FC; // Fold a few common cases.
1662 // Look up the constant in the table first to ensure uniqueness
1663 std::vector<Constant*> ArgVec(1, Val);
1664 ArgVec.push_back(Idx);
1665 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1667 LLVMContextImpl *pImpl = Val->getContext().pImpl;
1668 Type *ReqTy = cast<VectorType>(Val->getType())->getElementType();
1669 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1672 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1674 assert(Val->getType()->isVectorTy() &&
1675 "Tried to create insertelement operation on non-vector type!");
1676 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
1677 && "Insertelement types must match!");
1678 assert(Idx->getType()->isIntegerTy(32) &&
1679 "Insertelement index must be i32 type!");
1681 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1682 return FC; // Fold a few common cases.
1683 // Look up the constant in the table first to ensure uniqueness
1684 std::vector<Constant*> ArgVec(1, Val);
1685 ArgVec.push_back(Elt);
1686 ArgVec.push_back(Idx);
1687 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1689 LLVMContextImpl *pImpl = Val->getContext().pImpl;
1690 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
1693 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1695 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1696 "Invalid shuffle vector constant expr operands!");
1698 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1699 return FC; // Fold a few common cases.
1701 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
1702 Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
1703 Type *ShufTy = VectorType::get(EltTy, NElts);
1705 // Look up the constant in the table first to ensure uniqueness
1706 std::vector<Constant*> ArgVec(1, V1);
1707 ArgVec.push_back(V2);
1708 ArgVec.push_back(Mask);
1709 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1711 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
1712 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
1715 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
1716 ArrayRef<unsigned> Idxs) {
1717 assert(ExtractValueInst::getIndexedType(Agg->getType(),
1718 Idxs) == Val->getType() &&
1719 "insertvalue indices invalid!");
1720 assert(Agg->getType()->isFirstClassType() &&
1721 "Non-first-class type for constant insertvalue expression");
1722 Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs);
1723 assert(FC && "insertvalue constant expr couldn't be folded!");
1727 Constant *ConstantExpr::getExtractValue(Constant *Agg,
1728 ArrayRef<unsigned> Idxs) {
1729 assert(Agg->getType()->isFirstClassType() &&
1730 "Tried to create extractelement operation on non-first-class type!");
1732 Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs);
1734 assert(ReqTy && "extractvalue indices invalid!");
1736 assert(Agg->getType()->isFirstClassType() &&
1737 "Non-first-class type for constant extractvalue expression");
1738 Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs);
1739 assert(FC && "ExtractValue constant expr couldn't be folded!");
1743 Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
1744 assert(C->getType()->isIntOrIntVectorTy() &&
1745 "Cannot NEG a nonintegral value!");
1746 return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
1750 Constant *ConstantExpr::getFNeg(Constant *C) {
1751 assert(C->getType()->isFPOrFPVectorTy() &&
1752 "Cannot FNEG a non-floating-point value!");
1753 return getFSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
1756 Constant *ConstantExpr::getNot(Constant *C) {
1757 assert(C->getType()->isIntOrIntVectorTy() &&
1758 "Cannot NOT a nonintegral value!");
1759 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
1762 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
1763 bool HasNUW, bool HasNSW) {
1764 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1765 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
1766 return get(Instruction::Add, C1, C2, Flags);
1769 Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
1770 return get(Instruction::FAdd, C1, C2);
1773 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
1774 bool HasNUW, bool HasNSW) {
1775 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1776 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
1777 return get(Instruction::Sub, C1, C2, Flags);
1780 Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
1781 return get(Instruction::FSub, C1, C2);
1784 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
1785 bool HasNUW, bool HasNSW) {
1786 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1787 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
1788 return get(Instruction::Mul, C1, C2, Flags);
1791 Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
1792 return get(Instruction::FMul, C1, C2);
1795 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
1796 return get(Instruction::UDiv, C1, C2,
1797 isExact ? PossiblyExactOperator::IsExact : 0);
1800 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
1801 return get(Instruction::SDiv, C1, C2,
1802 isExact ? PossiblyExactOperator::IsExact : 0);
1805 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
1806 return get(Instruction::FDiv, C1, C2);
1809 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
1810 return get(Instruction::URem, C1, C2);
1813 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
1814 return get(Instruction::SRem, C1, C2);
1817 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
1818 return get(Instruction::FRem, C1, C2);
1821 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
1822 return get(Instruction::And, C1, C2);
1825 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
1826 return get(Instruction::Or, C1, C2);
1829 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
1830 return get(Instruction::Xor, C1, C2);
1833 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
1834 bool HasNUW, bool HasNSW) {
1835 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1836 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
1837 return get(Instruction::Shl, C1, C2, Flags);
1840 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
1841 return get(Instruction::LShr, C1, C2,
1842 isExact ? PossiblyExactOperator::IsExact : 0);
1845 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
1846 return get(Instruction::AShr, C1, C2,
1847 isExact ? PossiblyExactOperator::IsExact : 0);
1850 // destroyConstant - Remove the constant from the constant table...
1852 void ConstantExpr::destroyConstant() {
1853 getType()->getContext().pImpl->ExprConstants.remove(this);
1854 destroyConstantImpl();
1857 const char *ConstantExpr::getOpcodeName() const {
1858 return Instruction::getOpcodeName(getOpcode());
1863 GetElementPtrConstantExpr::
1864 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
1866 : ConstantExpr(DestTy, Instruction::GetElementPtr,
1867 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
1868 - (IdxList.size()+1), IdxList.size()+1) {
1870 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
1871 OperandList[i+1] = IdxList[i];
1875 //===----------------------------------------------------------------------===//
1876 // replaceUsesOfWithOnConstant implementations
1878 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
1879 /// 'From' to be uses of 'To'. This must update the uniquing data structures
1882 /// Note that we intentionally replace all uses of From with To here. Consider
1883 /// a large array that uses 'From' 1000 times. By handling this case all here,
1884 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
1885 /// single invocation handles all 1000 uses. Handling them one at a time would
1886 /// work, but would be really slow because it would have to unique each updated
1889 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1891 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1892 Constant *ToC = cast<Constant>(To);
1894 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
1896 std::pair<LLVMContextImpl::ArrayConstantsTy::MapKey, ConstantArray*> Lookup;
1897 Lookup.first.first = cast<ArrayType>(getType());
1898 Lookup.second = this;
1900 std::vector<Constant*> &Values = Lookup.first.second;
1901 Values.reserve(getNumOperands()); // Build replacement array.
1903 // Fill values with the modified operands of the constant array. Also,
1904 // compute whether this turns into an all-zeros array.
1905 bool isAllZeros = false;
1906 unsigned NumUpdated = 0;
1907 if (!ToC->isNullValue()) {
1908 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1909 Constant *Val = cast<Constant>(O->get());
1914 Values.push_back(Val);
1918 for (Use *O = OperandList, *E = OperandList+getNumOperands();O != E; ++O) {
1919 Constant *Val = cast<Constant>(O->get());
1924 Values.push_back(Val);
1925 if (isAllZeros) isAllZeros = Val->isNullValue();
1929 Constant *Replacement = 0;
1931 Replacement = ConstantAggregateZero::get(getType());
1933 // Check to see if we have this array type already.
1935 LLVMContextImpl::ArrayConstantsTy::MapTy::iterator I =
1936 pImpl->ArrayConstants.InsertOrGetItem(Lookup, Exists);
1939 Replacement = I->second;
1941 // Okay, the new shape doesn't exist in the system yet. Instead of
1942 // creating a new constant array, inserting it, replaceallusesof'ing the
1943 // old with the new, then deleting the old... just update the current one
1945 pImpl->ArrayConstants.MoveConstantToNewSlot(this, I);
1947 // Update to the new value. Optimize for the case when we have a single
1948 // operand that we're changing, but handle bulk updates efficiently.
1949 if (NumUpdated == 1) {
1950 unsigned OperandToUpdate = U - OperandList;
1951 assert(getOperand(OperandToUpdate) == From &&
1952 "ReplaceAllUsesWith broken!");
1953 setOperand(OperandToUpdate, ToC);
1955 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1956 if (getOperand(i) == From)
1963 // Otherwise, I do need to replace this with an existing value.
1964 assert(Replacement != this && "I didn't contain From!");
1966 // Everyone using this now uses the replacement.
1967 replaceAllUsesWith(Replacement);
1969 // Delete the old constant!
1973 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
1975 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1976 Constant *ToC = cast<Constant>(To);
1978 unsigned OperandToUpdate = U-OperandList;
1979 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1981 std::pair<LLVMContextImpl::StructConstantsTy::MapKey, ConstantStruct*> Lookup;
1982 Lookup.first.first = cast<StructType>(getType());
1983 Lookup.second = this;
1984 std::vector<Constant*> &Values = Lookup.first.second;
1985 Values.reserve(getNumOperands()); // Build replacement struct.
1988 // Fill values with the modified operands of the constant struct. Also,
1989 // compute whether this turns into an all-zeros struct.
1990 bool isAllZeros = false;
1991 if (!ToC->isNullValue()) {
1992 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
1993 Values.push_back(cast<Constant>(O->get()));
1996 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1997 Constant *Val = cast<Constant>(O->get());
1998 Values.push_back(Val);
1999 if (isAllZeros) isAllZeros = Val->isNullValue();
2002 Values[OperandToUpdate] = ToC;
2004 LLVMContextImpl *pImpl = getContext().pImpl;
2006 Constant *Replacement = 0;
2008 Replacement = ConstantAggregateZero::get(getType());
2010 // Check to see if we have this struct type already.
2012 LLVMContextImpl::StructConstantsTy::MapTy::iterator I =
2013 pImpl->StructConstants.InsertOrGetItem(Lookup, Exists);
2016 Replacement = I->second;
2018 // Okay, the new shape doesn't exist in the system yet. Instead of
2019 // creating a new constant struct, inserting it, replaceallusesof'ing the
2020 // old with the new, then deleting the old... just update the current one
2022 pImpl->StructConstants.MoveConstantToNewSlot(this, I);
2024 // Update to the new value.
2025 setOperand(OperandToUpdate, ToC);
2030 assert(Replacement != this && "I didn't contain From!");
2032 // Everyone using this now uses the replacement.
2033 replaceAllUsesWith(Replacement);
2035 // Delete the old constant!
2039 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2041 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2043 std::vector<Constant*> Values;
2044 Values.reserve(getNumOperands()); // Build replacement array...
2045 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2046 Constant *Val = getOperand(i);
2047 if (Val == From) Val = cast<Constant>(To);
2048 Values.push_back(Val);
2051 Constant *Replacement = get(Values);
2052 assert(Replacement != this && "I didn't contain From!");
2054 // Everyone using this now uses the replacement.
2055 replaceAllUsesWith(Replacement);
2057 // Delete the old constant!
2061 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2063 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2064 Constant *To = cast<Constant>(ToV);
2066 Constant *Replacement = 0;
2067 if (getOpcode() == Instruction::GetElementPtr) {
2068 SmallVector<Constant*, 8> Indices;
2069 Constant *Pointer = getOperand(0);
2070 Indices.reserve(getNumOperands()-1);
2071 if (Pointer == From) Pointer = To;
2073 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2074 Constant *Val = getOperand(i);
2075 if (Val == From) Val = To;
2076 Indices.push_back(Val);
2078 Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices,
2079 cast<GEPOperator>(this)->isInBounds());
2080 } else if (getOpcode() == Instruction::ExtractValue) {
2081 Constant *Agg = getOperand(0);
2082 if (Agg == From) Agg = To;
2084 ArrayRef<unsigned> Indices = getIndices();
2085 Replacement = ConstantExpr::getExtractValue(Agg, Indices);
2086 } else if (getOpcode() == Instruction::InsertValue) {
2087 Constant *Agg = getOperand(0);
2088 Constant *Val = getOperand(1);
2089 if (Agg == From) Agg = To;
2090 if (Val == From) Val = To;
2092 ArrayRef<unsigned> Indices = getIndices();
2093 Replacement = ConstantExpr::getInsertValue(Agg, Val, Indices);
2094 } else if (isCast()) {
2095 assert(getOperand(0) == From && "Cast only has one use!");
2096 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2097 } else if (getOpcode() == Instruction::Select) {
2098 Constant *C1 = getOperand(0);
2099 Constant *C2 = getOperand(1);
2100 Constant *C3 = getOperand(2);
2101 if (C1 == From) C1 = To;
2102 if (C2 == From) C2 = To;
2103 if (C3 == From) C3 = To;
2104 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2105 } else if (getOpcode() == Instruction::ExtractElement) {
2106 Constant *C1 = getOperand(0);
2107 Constant *C2 = getOperand(1);
2108 if (C1 == From) C1 = To;
2109 if (C2 == From) C2 = To;
2110 Replacement = ConstantExpr::getExtractElement(C1, C2);
2111 } else if (getOpcode() == Instruction::InsertElement) {
2112 Constant *C1 = getOperand(0);
2113 Constant *C2 = getOperand(1);
2114 Constant *C3 = getOperand(1);
2115 if (C1 == From) C1 = To;
2116 if (C2 == From) C2 = To;
2117 if (C3 == From) C3 = To;
2118 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2119 } else if (getOpcode() == Instruction::ShuffleVector) {
2120 Constant *C1 = getOperand(0);
2121 Constant *C2 = getOperand(1);
2122 Constant *C3 = getOperand(2);
2123 if (C1 == From) C1 = To;
2124 if (C2 == From) C2 = To;
2125 if (C3 == From) C3 = To;
2126 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2127 } else if (isCompare()) {
2128 Constant *C1 = getOperand(0);
2129 Constant *C2 = getOperand(1);
2130 if (C1 == From) C1 = To;
2131 if (C2 == From) C2 = To;
2132 if (getOpcode() == Instruction::ICmp)
2133 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2135 assert(getOpcode() == Instruction::FCmp);
2136 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2138 } else if (getNumOperands() == 2) {
2139 Constant *C1 = getOperand(0);
2140 Constant *C2 = getOperand(1);
2141 if (C1 == From) C1 = To;
2142 if (C2 == From) C2 = To;
2143 Replacement = ConstantExpr::get(getOpcode(), C1, C2, SubclassOptionalData);
2145 llvm_unreachable("Unknown ConstantExpr type!");
2149 assert(Replacement != this && "I didn't contain From!");
2151 // Everyone using this now uses the replacement.
2152 replaceAllUsesWith(Replacement);
2154 // Delete the old constant!