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,
577 const std::vector<Constant*> &V)
578 : Constant(T, ConstantArrayVal,
579 OperandTraits<ConstantArray>::op_end(this) - V.size(),
581 assert(V.size() == T->getNumElements() &&
582 "Invalid initializer vector for constant array");
583 Use *OL = OperandList;
584 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
587 assert(C->getType() == T->getElementType() &&
588 "Initializer for array element doesn't match array element type!");
593 Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
594 for (unsigned i = 0, e = V.size(); i != e; ++i) {
595 assert(V[i]->getType() == Ty->getElementType() &&
596 "Wrong type in array element initializer");
598 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
599 // If this is an all-zero array, return a ConstantAggregateZero object
602 if (!C->isNullValue())
603 return pImpl->ArrayConstants.getOrCreate(Ty, V);
605 for (unsigned i = 1, e = V.size(); i != e; ++i)
607 return pImpl->ArrayConstants.getOrCreate(Ty, V);
610 return ConstantAggregateZero::get(Ty);
613 /// ConstantArray::get(const string&) - Return an array that is initialized to
614 /// contain the specified string. If length is zero then a null terminator is
615 /// added to the specified string so that it may be used in a natural way.
616 /// Otherwise, the length parameter specifies how much of the string to use
617 /// and it won't be null terminated.
619 Constant *ConstantArray::get(LLVMContext &Context, StringRef Str,
621 std::vector<Constant*> ElementVals;
622 ElementVals.reserve(Str.size() + size_t(AddNull));
623 for (unsigned i = 0; i < Str.size(); ++i)
624 ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), Str[i]));
626 // Add a null terminator to the string...
628 ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), 0));
631 ArrayType *ATy = ArrayType::get(Type::getInt8Ty(Context), ElementVals.size());
632 return get(ATy, ElementVals);
635 /// getTypeForElements - Return an anonymous struct type to use for a constant
636 /// with the specified set of elements. The list must not be empty.
637 StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
638 ArrayRef<Constant*> V,
640 SmallVector<Type*, 16> EltTypes;
641 for (unsigned i = 0, e = V.size(); i != e; ++i)
642 EltTypes.push_back(V[i]->getType());
644 return StructType::get(Context, EltTypes, Packed);
648 StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
651 "ConstantStruct::getTypeForElements cannot be called on empty list");
652 return getTypeForElements(V[0]->getContext(), V, Packed);
656 ConstantStruct::ConstantStruct(StructType *T,
657 const std::vector<Constant*> &V)
658 : Constant(T, ConstantStructVal,
659 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
661 assert((T->isOpaque() || V.size() == T->getNumElements()) &&
662 "Invalid initializer vector for constant structure");
663 Use *OL = OperandList;
664 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
667 assert((T->isOpaque() || C->getType() == T->getElementType(I-V.begin())) &&
668 "Initializer for struct element doesn't match struct element type!");
673 // ConstantStruct accessors.
674 Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
675 // Create a ConstantAggregateZero value if all elements are zeros.
676 for (unsigned i = 0, e = V.size(); i != e; ++i)
677 if (!V[i]->isNullValue())
678 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
680 assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
681 "Incorrect # elements specified to ConstantStruct::get");
682 return ConstantAggregateZero::get(ST);
685 Constant* ConstantStruct::get(StructType *T, ...) {
687 SmallVector<Constant*, 8> Values;
689 while (Constant *Val = va_arg(ap, llvm::Constant*))
690 Values.push_back(Val);
692 return get(T, Values);
695 ConstantVector::ConstantVector(VectorType *T,
696 const std::vector<Constant*> &V)
697 : Constant(T, ConstantVectorVal,
698 OperandTraits<ConstantVector>::op_end(this) - V.size(),
700 Use *OL = OperandList;
701 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
704 assert(C->getType() == T->getElementType() &&
705 "Initializer for vector element doesn't match vector element type!");
710 // ConstantVector accessors.
711 Constant *ConstantVector::get(ArrayRef<Constant*> V) {
712 assert(!V.empty() && "Vectors can't be empty");
713 VectorType *T = VectorType::get(V.front()->getType(), V.size());
714 LLVMContextImpl *pImpl = T->getContext().pImpl;
716 // If this is an all-undef or all-zero vector, return a
717 // ConstantAggregateZero or UndefValue.
719 bool isZero = C->isNullValue();
720 bool isUndef = isa<UndefValue>(C);
722 if (isZero || isUndef) {
723 for (unsigned i = 1, e = V.size(); i != e; ++i)
725 isZero = isUndef = false;
731 return ConstantAggregateZero::get(T);
733 return UndefValue::get(T);
735 return pImpl->VectorConstants.getOrCreate(T, V);
738 // Utility function for determining if a ConstantExpr is a CastOp or not. This
739 // can't be inline because we don't want to #include Instruction.h into
741 bool ConstantExpr::isCast() const {
742 return Instruction::isCast(getOpcode());
745 bool ConstantExpr::isCompare() const {
746 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
749 bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
750 if (getOpcode() != Instruction::GetElementPtr) return false;
752 gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
753 User::const_op_iterator OI = llvm::next(this->op_begin());
755 // Skip the first index, as it has no static limit.
759 // The remaining indices must be compile-time known integers within the
760 // bounds of the corresponding notional static array types.
761 for (; GEPI != E; ++GEPI, ++OI) {
762 ConstantInt *CI = dyn_cast<ConstantInt>(*OI);
763 if (!CI) return false;
764 if (ArrayType *ATy = dyn_cast<ArrayType>(*GEPI))
765 if (CI->getValue().getActiveBits() > 64 ||
766 CI->getZExtValue() >= ATy->getNumElements())
770 // All the indices checked out.
774 bool ConstantExpr::hasIndices() const {
775 return getOpcode() == Instruction::ExtractValue ||
776 getOpcode() == Instruction::InsertValue;
779 ArrayRef<unsigned> ConstantExpr::getIndices() const {
780 if (const ExtractValueConstantExpr *EVCE =
781 dyn_cast<ExtractValueConstantExpr>(this))
782 return EVCE->Indices;
784 return cast<InsertValueConstantExpr>(this)->Indices;
787 unsigned ConstantExpr::getPredicate() const {
789 return ((const CompareConstantExpr*)this)->predicate;
792 /// getWithOperandReplaced - Return a constant expression identical to this
793 /// one, but with the specified operand set to the specified value.
795 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
796 assert(OpNo < getNumOperands() && "Operand num is out of range!");
797 assert(Op->getType() == getOperand(OpNo)->getType() &&
798 "Replacing operand with value of different type!");
799 if (getOperand(OpNo) == Op)
800 return const_cast<ConstantExpr*>(this);
802 Constant *Op0, *Op1, *Op2;
803 switch (getOpcode()) {
804 case Instruction::Trunc:
805 case Instruction::ZExt:
806 case Instruction::SExt:
807 case Instruction::FPTrunc:
808 case Instruction::FPExt:
809 case Instruction::UIToFP:
810 case Instruction::SIToFP:
811 case Instruction::FPToUI:
812 case Instruction::FPToSI:
813 case Instruction::PtrToInt:
814 case Instruction::IntToPtr:
815 case Instruction::BitCast:
816 return ConstantExpr::getCast(getOpcode(), Op, getType());
817 case Instruction::Select:
818 Op0 = (OpNo == 0) ? Op : getOperand(0);
819 Op1 = (OpNo == 1) ? Op : getOperand(1);
820 Op2 = (OpNo == 2) ? Op : getOperand(2);
821 return ConstantExpr::getSelect(Op0, Op1, Op2);
822 case Instruction::InsertElement:
823 Op0 = (OpNo == 0) ? Op : getOperand(0);
824 Op1 = (OpNo == 1) ? Op : getOperand(1);
825 Op2 = (OpNo == 2) ? Op : getOperand(2);
826 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
827 case Instruction::ExtractElement:
828 Op0 = (OpNo == 0) ? Op : getOperand(0);
829 Op1 = (OpNo == 1) ? Op : getOperand(1);
830 return ConstantExpr::getExtractElement(Op0, Op1);
831 case Instruction::ShuffleVector:
832 Op0 = (OpNo == 0) ? Op : getOperand(0);
833 Op1 = (OpNo == 1) ? Op : getOperand(1);
834 Op2 = (OpNo == 2) ? Op : getOperand(2);
835 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
836 case Instruction::GetElementPtr: {
837 SmallVector<Constant*, 8> Ops;
838 Ops.resize(getNumOperands()-1);
839 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
840 Ops[i-1] = getOperand(i);
842 return cast<GEPOperator>(this)->isInBounds() ?
843 ConstantExpr::getInBoundsGetElementPtr(Op, &Ops[0], Ops.size()) :
844 ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
846 return cast<GEPOperator>(this)->isInBounds() ?
847 ConstantExpr::getInBoundsGetElementPtr(getOperand(0), &Ops[0],Ops.size()):
848 ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
851 assert(getNumOperands() == 2 && "Must be binary operator?");
852 Op0 = (OpNo == 0) ? Op : getOperand(0);
853 Op1 = (OpNo == 1) ? Op : getOperand(1);
854 return ConstantExpr::get(getOpcode(), Op0, Op1, SubclassOptionalData);
858 /// getWithOperands - This returns the current constant expression with the
859 /// operands replaced with the specified values. The specified array must
860 /// have the same number of operands as our current one.
861 Constant *ConstantExpr::
862 getWithOperands(ArrayRef<Constant*> Ops, Type *Ty) const {
863 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
864 bool AnyChange = Ty != getType();
865 for (unsigned i = 0; i != Ops.size(); ++i)
866 AnyChange |= Ops[i] != getOperand(i);
868 if (!AnyChange) // No operands changed, return self.
869 return const_cast<ConstantExpr*>(this);
871 switch (getOpcode()) {
872 case Instruction::Trunc:
873 case Instruction::ZExt:
874 case Instruction::SExt:
875 case Instruction::FPTrunc:
876 case Instruction::FPExt:
877 case Instruction::UIToFP:
878 case Instruction::SIToFP:
879 case Instruction::FPToUI:
880 case Instruction::FPToSI:
881 case Instruction::PtrToInt:
882 case Instruction::IntToPtr:
883 case Instruction::BitCast:
884 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty);
885 case Instruction::Select:
886 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
887 case Instruction::InsertElement:
888 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
889 case Instruction::ExtractElement:
890 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
891 case Instruction::ShuffleVector:
892 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
893 case Instruction::GetElementPtr:
894 return cast<GEPOperator>(this)->isInBounds() ?
895 ConstantExpr::getInBoundsGetElementPtr(Ops[0], &Ops[1], Ops.size()-1) :
896 ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], Ops.size()-1);
897 case Instruction::ICmp:
898 case Instruction::FCmp:
899 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
901 assert(getNumOperands() == 2 && "Must be binary operator?");
902 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData);
907 //===----------------------------------------------------------------------===//
908 // isValueValidForType implementations
910 bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
911 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
912 if (Ty == Type::getInt1Ty(Ty->getContext()))
913 return Val == 0 || Val == 1;
915 return true; // always true, has to fit in largest type
916 uint64_t Max = (1ll << NumBits) - 1;
920 bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
921 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
922 if (Ty == Type::getInt1Ty(Ty->getContext()))
923 return Val == 0 || Val == 1 || Val == -1;
925 return true; // always true, has to fit in largest type
926 int64_t Min = -(1ll << (NumBits-1));
927 int64_t Max = (1ll << (NumBits-1)) - 1;
928 return (Val >= Min && Val <= Max);
931 bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {
932 // convert modifies in place, so make a copy.
933 APFloat Val2 = APFloat(Val);
935 switch (Ty->getTypeID()) {
937 return false; // These can't be represented as floating point!
939 // FIXME rounding mode needs to be more flexible
940 case Type::FloatTyID: {
941 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
943 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
946 case Type::DoubleTyID: {
947 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
948 &Val2.getSemantics() == &APFloat::IEEEdouble)
950 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
953 case Type::X86_FP80TyID:
954 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
955 &Val2.getSemantics() == &APFloat::IEEEdouble ||
956 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
957 case Type::FP128TyID:
958 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
959 &Val2.getSemantics() == &APFloat::IEEEdouble ||
960 &Val2.getSemantics() == &APFloat::IEEEquad;
961 case Type::PPC_FP128TyID:
962 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
963 &Val2.getSemantics() == &APFloat::IEEEdouble ||
964 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
968 //===----------------------------------------------------------------------===//
969 // Factory Function Implementation
971 ConstantAggregateZero* ConstantAggregateZero::get(Type* Ty) {
972 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
973 "Cannot create an aggregate zero of non-aggregate type!");
975 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
976 return pImpl->AggZeroConstants.getOrCreate(Ty, 0);
979 /// destroyConstant - Remove the constant from the constant table...
981 void ConstantAggregateZero::destroyConstant() {
982 getType()->getContext().pImpl->AggZeroConstants.remove(this);
983 destroyConstantImpl();
986 /// destroyConstant - Remove the constant from the constant table...
988 void ConstantArray::destroyConstant() {
989 getType()->getContext().pImpl->ArrayConstants.remove(this);
990 destroyConstantImpl();
993 /// isString - This method returns true if the array is an array of i8, and
994 /// if the elements of the array are all ConstantInt's.
995 bool ConstantArray::isString() const {
996 // Check the element type for i8...
997 if (!getType()->getElementType()->isIntegerTy(8))
999 // Check the elements to make sure they are all integers, not constant
1001 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1002 if (!isa<ConstantInt>(getOperand(i)))
1007 /// isCString - This method returns true if the array is a string (see
1008 /// isString) and it ends in a null byte \\0 and does not contains any other
1009 /// null bytes except its terminator.
1010 bool ConstantArray::isCString() const {
1011 // Check the element type for i8...
1012 if (!getType()->getElementType()->isIntegerTy(8))
1015 // Last element must be a null.
1016 if (!getOperand(getNumOperands()-1)->isNullValue())
1018 // Other elements must be non-null integers.
1019 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1020 if (!isa<ConstantInt>(getOperand(i)))
1022 if (getOperand(i)->isNullValue())
1029 /// convertToString - Helper function for getAsString() and getAsCString().
1030 static std::string convertToString(const User *U, unsigned len) {
1032 Result.reserve(len);
1033 for (unsigned i = 0; i != len; ++i)
1034 Result.push_back((char)cast<ConstantInt>(U->getOperand(i))->getZExtValue());
1038 /// getAsString - If this array is isString(), then this method converts the
1039 /// array to an std::string and returns it. Otherwise, it asserts out.
1041 std::string ConstantArray::getAsString() const {
1042 assert(isString() && "Not a string!");
1043 return convertToString(this, getNumOperands());
1047 /// getAsCString - If this array is isCString(), then this method converts the
1048 /// array (without the trailing null byte) to an std::string and returns it.
1049 /// Otherwise, it asserts out.
1051 std::string ConstantArray::getAsCString() const {
1052 assert(isCString() && "Not a string!");
1053 return convertToString(this, getNumOperands() - 1);
1057 //---- ConstantStruct::get() implementation...
1060 // destroyConstant - Remove the constant from the constant table...
1062 void ConstantStruct::destroyConstant() {
1063 getType()->getContext().pImpl->StructConstants.remove(this);
1064 destroyConstantImpl();
1067 // destroyConstant - Remove the constant from the constant table...
1069 void ConstantVector::destroyConstant() {
1070 getType()->getContext().pImpl->VectorConstants.remove(this);
1071 destroyConstantImpl();
1074 /// This function will return true iff every element in this vector constant
1075 /// is set to all ones.
1076 /// @returns true iff this constant's elements are all set to all ones.
1077 /// @brief Determine if the value is all ones.
1078 bool ConstantVector::isAllOnesValue() const {
1079 // Check out first element.
1080 const Constant *Elt = getOperand(0);
1081 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1082 if (!CI || !CI->isAllOnesValue()) return false;
1083 // Then make sure all remaining elements point to the same value.
1084 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1085 if (getOperand(I) != Elt)
1091 /// getSplatValue - If this is a splat constant, where all of the
1092 /// elements have the same value, return that value. Otherwise return null.
1093 Constant *ConstantVector::getSplatValue() const {
1094 // Check out first element.
1095 Constant *Elt = getOperand(0);
1096 // Then make sure all remaining elements point to the same value.
1097 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1098 if (getOperand(I) != Elt)
1103 //---- ConstantPointerNull::get() implementation.
1106 ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
1107 return Ty->getContext().pImpl->NullPtrConstants.getOrCreate(Ty, 0);
1110 // destroyConstant - Remove the constant from the constant table...
1112 void ConstantPointerNull::destroyConstant() {
1113 getType()->getContext().pImpl->NullPtrConstants.remove(this);
1114 destroyConstantImpl();
1118 //---- UndefValue::get() implementation.
1121 UndefValue *UndefValue::get(Type *Ty) {
1122 return Ty->getContext().pImpl->UndefValueConstants.getOrCreate(Ty, 0);
1125 // destroyConstant - Remove the constant from the constant table.
1127 void UndefValue::destroyConstant() {
1128 getType()->getContext().pImpl->UndefValueConstants.remove(this);
1129 destroyConstantImpl();
1132 //---- BlockAddress::get() implementation.
1135 BlockAddress *BlockAddress::get(BasicBlock *BB) {
1136 assert(BB->getParent() != 0 && "Block must have a parent");
1137 return get(BB->getParent(), BB);
1140 BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1142 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
1144 BA = new BlockAddress(F, BB);
1146 assert(BA->getFunction() == F && "Basic block moved between functions");
1150 BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1151 : Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1155 BB->AdjustBlockAddressRefCount(1);
1159 // destroyConstant - Remove the constant from the constant table.
1161 void BlockAddress::destroyConstant() {
1162 getFunction()->getType()->getContext().pImpl
1163 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
1164 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1165 destroyConstantImpl();
1168 void BlockAddress::replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U) {
1169 // This could be replacing either the Basic Block or the Function. In either
1170 // case, we have to remove the map entry.
1171 Function *NewF = getFunction();
1172 BasicBlock *NewBB = getBasicBlock();
1175 NewF = cast<Function>(To);
1177 NewBB = cast<BasicBlock>(To);
1179 // See if the 'new' entry already exists, if not, just update this in place
1180 // and return early.
1181 BlockAddress *&NewBA =
1182 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
1184 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1186 // Remove the old entry, this can't cause the map to rehash (just a
1187 // tombstone will get added).
1188 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1191 setOperand(0, NewF);
1192 setOperand(1, NewBB);
1193 getBasicBlock()->AdjustBlockAddressRefCount(1);
1197 // Otherwise, I do need to replace this with an existing value.
1198 assert(NewBA != this && "I didn't contain From!");
1200 // Everyone using this now uses the replacement.
1201 replaceAllUsesWith(NewBA);
1206 //---- ConstantExpr::get() implementations.
1209 /// This is a utility function to handle folding of casts and lookup of the
1210 /// cast in the ExprConstants map. It is used by the various get* methods below.
1211 static inline Constant *getFoldedCast(
1212 Instruction::CastOps opc, Constant *C, Type *Ty) {
1213 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1214 // Fold a few common cases
1215 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1218 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1220 // Look up the constant in the table first to ensure uniqueness
1221 std::vector<Constant*> argVec(1, C);
1222 ExprMapKeyType Key(opc, argVec);
1224 return pImpl->ExprConstants.getOrCreate(Ty, Key);
1227 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty) {
1228 Instruction::CastOps opc = Instruction::CastOps(oc);
1229 assert(Instruction::isCast(opc) && "opcode out of range");
1230 assert(C && Ty && "Null arguments to getCast");
1231 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
1235 llvm_unreachable("Invalid cast opcode");
1237 case Instruction::Trunc: return getTrunc(C, Ty);
1238 case Instruction::ZExt: return getZExt(C, Ty);
1239 case Instruction::SExt: return getSExt(C, Ty);
1240 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1241 case Instruction::FPExt: return getFPExtend(C, Ty);
1242 case Instruction::UIToFP: return getUIToFP(C, Ty);
1243 case Instruction::SIToFP: return getSIToFP(C, Ty);
1244 case Instruction::FPToUI: return getFPToUI(C, Ty);
1245 case Instruction::FPToSI: return getFPToSI(C, Ty);
1246 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1247 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1248 case Instruction::BitCast: return getBitCast(C, Ty);
1253 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) {
1254 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1255 return getBitCast(C, Ty);
1256 return getZExt(C, Ty);
1259 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) {
1260 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1261 return getBitCast(C, Ty);
1262 return getSExt(C, Ty);
1265 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {
1266 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1267 return getBitCast(C, Ty);
1268 return getTrunc(C, Ty);
1271 Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {
1272 assert(S->getType()->isPointerTy() && "Invalid cast");
1273 assert((Ty->isIntegerTy() || Ty->isPointerTy()) && "Invalid cast");
1275 if (Ty->isIntegerTy())
1276 return getPtrToInt(S, Ty);
1277 return getBitCast(S, Ty);
1280 Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty,
1282 assert(C->getType()->isIntOrIntVectorTy() &&
1283 Ty->isIntOrIntVectorTy() && "Invalid cast");
1284 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1285 unsigned DstBits = Ty->getScalarSizeInBits();
1286 Instruction::CastOps opcode =
1287 (SrcBits == DstBits ? Instruction::BitCast :
1288 (SrcBits > DstBits ? Instruction::Trunc :
1289 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1290 return getCast(opcode, C, Ty);
1293 Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) {
1294 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1296 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1297 unsigned DstBits = Ty->getScalarSizeInBits();
1298 if (SrcBits == DstBits)
1299 return C; // Avoid a useless cast
1300 Instruction::CastOps opcode =
1301 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1302 return getCast(opcode, C, Ty);
1305 Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty) {
1307 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1308 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1310 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1311 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
1312 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
1313 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1314 "SrcTy must be larger than DestTy for Trunc!");
1316 return getFoldedCast(Instruction::Trunc, C, Ty);
1319 Constant *ConstantExpr::getSExt(Constant *C, Type *Ty) {
1321 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1322 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1324 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1325 assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
1326 assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
1327 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1328 "SrcTy must be smaller than DestTy for SExt!");
1330 return getFoldedCast(Instruction::SExt, C, Ty);
1333 Constant *ConstantExpr::getZExt(Constant *C, Type *Ty) {
1335 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1336 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1338 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1339 assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
1340 assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
1341 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1342 "SrcTy must be smaller than DestTy for ZExt!");
1344 return getFoldedCast(Instruction::ZExt, C, Ty);
1347 Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty) {
1349 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1350 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1352 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1353 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1354 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1355 "This is an illegal floating point truncation!");
1356 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1359 Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty) {
1361 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1362 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1364 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1365 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1366 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1367 "This is an illegal floating point extension!");
1368 return getFoldedCast(Instruction::FPExt, C, Ty);
1371 Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty) {
1373 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1374 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1376 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1377 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1378 "This is an illegal uint to floating point cast!");
1379 return getFoldedCast(Instruction::UIToFP, C, Ty);
1382 Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty) {
1384 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1385 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1387 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1388 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1389 "This is an illegal sint to floating point cast!");
1390 return getFoldedCast(Instruction::SIToFP, C, Ty);
1393 Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty) {
1395 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1396 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1398 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1399 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1400 "This is an illegal floating point to uint cast!");
1401 return getFoldedCast(Instruction::FPToUI, C, Ty);
1404 Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty) {
1406 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1407 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1409 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1410 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1411 "This is an illegal floating point to sint cast!");
1412 return getFoldedCast(Instruction::FPToSI, C, Ty);
1415 Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy) {
1416 assert(C->getType()->isPointerTy() && "PtrToInt source must be pointer");
1417 assert(DstTy->isIntegerTy() && "PtrToInt destination must be integral");
1418 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1421 Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy) {
1422 assert(C->getType()->isIntegerTy() && "IntToPtr source must be integral");
1423 assert(DstTy->isPointerTy() && "IntToPtr destination must be a pointer");
1424 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1427 Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy) {
1428 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
1429 "Invalid constantexpr bitcast!");
1431 // It is common to ask for a bitcast of a value to its own type, handle this
1433 if (C->getType() == DstTy) return C;
1435 return getFoldedCast(Instruction::BitCast, C, DstTy);
1438 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
1440 // Check the operands for consistency first.
1441 assert(Opcode >= Instruction::BinaryOpsBegin &&
1442 Opcode < Instruction::BinaryOpsEnd &&
1443 "Invalid opcode in binary constant expression");
1444 assert(C1->getType() == C2->getType() &&
1445 "Operand types in binary constant expression should match");
1449 case Instruction::Add:
1450 case Instruction::Sub:
1451 case Instruction::Mul:
1452 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1453 assert(C1->getType()->isIntOrIntVectorTy() &&
1454 "Tried to create an integer operation on a non-integer type!");
1456 case Instruction::FAdd:
1457 case Instruction::FSub:
1458 case Instruction::FMul:
1459 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1460 assert(C1->getType()->isFPOrFPVectorTy() &&
1461 "Tried to create a floating-point operation on a "
1462 "non-floating-point type!");
1464 case Instruction::UDiv:
1465 case Instruction::SDiv:
1466 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1467 assert(C1->getType()->isIntOrIntVectorTy() &&
1468 "Tried to create an arithmetic operation on a non-arithmetic type!");
1470 case Instruction::FDiv:
1471 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1472 assert(C1->getType()->isFPOrFPVectorTy() &&
1473 "Tried to create an arithmetic operation on a non-arithmetic type!");
1475 case Instruction::URem:
1476 case Instruction::SRem:
1477 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1478 assert(C1->getType()->isIntOrIntVectorTy() &&
1479 "Tried to create an arithmetic operation on a non-arithmetic type!");
1481 case Instruction::FRem:
1482 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1483 assert(C1->getType()->isFPOrFPVectorTy() &&
1484 "Tried to create an arithmetic operation on a non-arithmetic type!");
1486 case Instruction::And:
1487 case Instruction::Or:
1488 case Instruction::Xor:
1489 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1490 assert(C1->getType()->isIntOrIntVectorTy() &&
1491 "Tried to create a logical operation on a non-integral type!");
1493 case Instruction::Shl:
1494 case Instruction::LShr:
1495 case Instruction::AShr:
1496 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1497 assert(C1->getType()->isIntOrIntVectorTy() &&
1498 "Tried to create a shift operation on a non-integer type!");
1505 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1506 return FC; // Fold a few common cases.
1508 std::vector<Constant*> argVec(1, C1);
1509 argVec.push_back(C2);
1510 ExprMapKeyType Key(Opcode, argVec, 0, Flags);
1512 LLVMContextImpl *pImpl = C1->getContext().pImpl;
1513 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
1516 Constant *ConstantExpr::getSizeOf(Type* Ty) {
1517 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1518 // Note that a non-inbounds gep is used, as null isn't within any object.
1519 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1520 Constant *GEP = getGetElementPtr(
1521 Constant::getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
1522 return getPtrToInt(GEP,
1523 Type::getInt64Ty(Ty->getContext()));
1526 Constant *ConstantExpr::getAlignOf(Type* Ty) {
1527 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
1528 // Note that a non-inbounds gep is used, as null isn't within any object.
1530 StructType::get(Type::getInt1Ty(Ty->getContext()), Ty, NULL);
1531 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo());
1532 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
1533 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1534 Constant *Indices[2] = { Zero, One };
1535 Constant *GEP = getGetElementPtr(NullPtr, Indices, 2);
1536 return getPtrToInt(GEP,
1537 Type::getInt64Ty(Ty->getContext()));
1540 Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) {
1541 return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
1545 Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) {
1546 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1547 // Note that a non-inbounds gep is used, as null isn't within any object.
1548 Constant *GEPIdx[] = {
1549 ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
1552 Constant *GEP = getGetElementPtr(
1553 Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx, 2);
1554 return getPtrToInt(GEP,
1555 Type::getInt64Ty(Ty->getContext()));
1558 Constant *ConstantExpr::getCompare(unsigned short Predicate,
1559 Constant *C1, Constant *C2) {
1560 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1562 switch (Predicate) {
1563 default: llvm_unreachable("Invalid CmpInst predicate");
1564 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1565 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1566 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1567 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1568 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1569 case CmpInst::FCMP_TRUE:
1570 return getFCmp(Predicate, C1, C2);
1572 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1573 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1574 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1575 case CmpInst::ICMP_SLE:
1576 return getICmp(Predicate, C1, C2);
1580 Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2) {
1581 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1583 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1584 return SC; // Fold common cases
1586 std::vector<Constant*> argVec(3, C);
1589 ExprMapKeyType Key(Instruction::Select, argVec);
1591 LLVMContextImpl *pImpl = C->getContext().pImpl;
1592 return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
1595 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1596 unsigned NumIdx, bool InBounds) {
1597 if (Constant *FC = ConstantFoldGetElementPtr(C, InBounds, Idxs, NumIdx))
1598 return FC; // Fold a few common cases.
1600 // Get the result type of the getelementptr!
1602 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
1603 assert(Ty && "GEP indices invalid!");
1604 unsigned AS = cast<PointerType>(C->getType())->getAddressSpace();
1605 Type *ReqTy = Ty->getPointerTo(AS);
1607 assert(C->getType()->isPointerTy() &&
1608 "Non-pointer type for constant GetElementPtr expression");
1609 // Look up the constant in the table first to ensure uniqueness
1610 std::vector<Constant*> ArgVec;
1611 ArgVec.reserve(NumIdx+1);
1612 ArgVec.push_back(C);
1613 for (unsigned i = 0; i != NumIdx; ++i)
1614 ArgVec.push_back(cast<Constant>(Idxs[i]));
1615 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
1616 InBounds ? GEPOperator::IsInBounds : 0);
1618 LLVMContextImpl *pImpl = C->getContext().pImpl;
1619 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1623 ConstantExpr::getICmp(unsigned short pred, Constant *LHS, Constant *RHS) {
1624 assert(LHS->getType() == RHS->getType());
1625 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1626 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1628 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1629 return FC; // Fold a few common cases...
1631 // Look up the constant in the table first to ensure uniqueness
1632 std::vector<Constant*> ArgVec;
1633 ArgVec.push_back(LHS);
1634 ArgVec.push_back(RHS);
1635 // Get the key type with both the opcode and predicate
1636 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1638 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1639 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1640 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1642 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1643 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
1647 ConstantExpr::getFCmp(unsigned short pred, Constant *LHS, Constant *RHS) {
1648 assert(LHS->getType() == RHS->getType());
1649 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1651 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1652 return FC; // Fold a few common cases...
1654 // Look up the constant in the table first to ensure uniqueness
1655 std::vector<Constant*> ArgVec;
1656 ArgVec.push_back(LHS);
1657 ArgVec.push_back(RHS);
1658 // Get the key type with both the opcode and predicate
1659 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1661 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1662 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1663 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1665 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1666 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
1669 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1670 assert(Val->getType()->isVectorTy() &&
1671 "Tried to create extractelement operation on non-vector type!");
1672 assert(Idx->getType()->isIntegerTy(32) &&
1673 "Extractelement index must be i32 type!");
1675 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1676 return FC; // Fold a few common cases.
1678 // Look up the constant in the table first to ensure uniqueness
1679 std::vector<Constant*> ArgVec(1, Val);
1680 ArgVec.push_back(Idx);
1681 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1683 LLVMContextImpl *pImpl = Val->getContext().pImpl;
1684 Type *ReqTy = cast<VectorType>(Val->getType())->getElementType();
1685 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1688 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1690 assert(Val->getType()->isVectorTy() &&
1691 "Tried to create insertelement operation on non-vector type!");
1692 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
1693 && "Insertelement types must match!");
1694 assert(Idx->getType()->isIntegerTy(32) &&
1695 "Insertelement index must be i32 type!");
1697 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1698 return FC; // Fold a few common cases.
1699 // Look up the constant in the table first to ensure uniqueness
1700 std::vector<Constant*> ArgVec(1, Val);
1701 ArgVec.push_back(Elt);
1702 ArgVec.push_back(Idx);
1703 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1705 LLVMContextImpl *pImpl = Val->getContext().pImpl;
1706 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
1709 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1711 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1712 "Invalid shuffle vector constant expr operands!");
1714 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1715 return FC; // Fold a few common cases.
1717 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
1718 Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
1719 Type *ShufTy = VectorType::get(EltTy, NElts);
1721 // Look up the constant in the table first to ensure uniqueness
1722 std::vector<Constant*> ArgVec(1, V1);
1723 ArgVec.push_back(V2);
1724 ArgVec.push_back(Mask);
1725 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1727 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
1728 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
1731 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
1732 ArrayRef<unsigned> Idxs) {
1733 assert(ExtractValueInst::getIndexedType(Agg->getType(),
1734 Idxs) == Val->getType() &&
1735 "insertvalue indices invalid!");
1736 assert(Agg->getType()->isFirstClassType() &&
1737 "Non-first-class type for constant insertvalue expression");
1738 Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs);
1739 assert(FC && "insertvalue constant expr couldn't be folded!");
1743 Constant *ConstantExpr::getExtractValue(Constant *Agg,
1744 ArrayRef<unsigned> Idxs) {
1745 assert(Agg->getType()->isFirstClassType() &&
1746 "Tried to create extractelement operation on non-first-class type!");
1748 Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs);
1750 assert(ReqTy && "extractvalue indices invalid!");
1752 assert(Agg->getType()->isFirstClassType() &&
1753 "Non-first-class type for constant extractvalue expression");
1754 Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs);
1755 assert(FC && "ExtractValue constant expr couldn't be folded!");
1759 Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
1760 assert(C->getType()->isIntOrIntVectorTy() &&
1761 "Cannot NEG a nonintegral value!");
1762 return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
1766 Constant *ConstantExpr::getFNeg(Constant *C) {
1767 assert(C->getType()->isFPOrFPVectorTy() &&
1768 "Cannot FNEG a non-floating-point value!");
1769 return getFSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
1772 Constant *ConstantExpr::getNot(Constant *C) {
1773 assert(C->getType()->isIntOrIntVectorTy() &&
1774 "Cannot NOT a nonintegral value!");
1775 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
1778 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
1779 bool HasNUW, bool HasNSW) {
1780 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1781 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
1782 return get(Instruction::Add, C1, C2, Flags);
1785 Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
1786 return get(Instruction::FAdd, C1, C2);
1789 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
1790 bool HasNUW, bool HasNSW) {
1791 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1792 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
1793 return get(Instruction::Sub, C1, C2, Flags);
1796 Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
1797 return get(Instruction::FSub, C1, C2);
1800 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
1801 bool HasNUW, bool HasNSW) {
1802 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1803 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
1804 return get(Instruction::Mul, C1, C2, Flags);
1807 Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
1808 return get(Instruction::FMul, C1, C2);
1811 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
1812 return get(Instruction::UDiv, C1, C2,
1813 isExact ? PossiblyExactOperator::IsExact : 0);
1816 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
1817 return get(Instruction::SDiv, C1, C2,
1818 isExact ? PossiblyExactOperator::IsExact : 0);
1821 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
1822 return get(Instruction::FDiv, C1, C2);
1825 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
1826 return get(Instruction::URem, C1, C2);
1829 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
1830 return get(Instruction::SRem, C1, C2);
1833 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
1834 return get(Instruction::FRem, C1, C2);
1837 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
1838 return get(Instruction::And, C1, C2);
1841 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
1842 return get(Instruction::Or, C1, C2);
1845 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
1846 return get(Instruction::Xor, C1, C2);
1849 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
1850 bool HasNUW, bool HasNSW) {
1851 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1852 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
1853 return get(Instruction::Shl, C1, C2, Flags);
1856 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
1857 return get(Instruction::LShr, C1, C2,
1858 isExact ? PossiblyExactOperator::IsExact : 0);
1861 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
1862 return get(Instruction::AShr, C1, C2,
1863 isExact ? PossiblyExactOperator::IsExact : 0);
1866 // destroyConstant - Remove the constant from the constant table...
1868 void ConstantExpr::destroyConstant() {
1869 getType()->getContext().pImpl->ExprConstants.remove(this);
1870 destroyConstantImpl();
1873 const char *ConstantExpr::getOpcodeName() const {
1874 return Instruction::getOpcodeName(getOpcode());
1879 GetElementPtrConstantExpr::
1880 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
1882 : ConstantExpr(DestTy, Instruction::GetElementPtr,
1883 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
1884 - (IdxList.size()+1), IdxList.size()+1) {
1886 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
1887 OperandList[i+1] = IdxList[i];
1891 //===----------------------------------------------------------------------===//
1892 // replaceUsesOfWithOnConstant implementations
1894 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
1895 /// 'From' to be uses of 'To'. This must update the uniquing data structures
1898 /// Note that we intentionally replace all uses of From with To here. Consider
1899 /// a large array that uses 'From' 1000 times. By handling this case all here,
1900 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
1901 /// single invocation handles all 1000 uses. Handling them one at a time would
1902 /// work, but would be really slow because it would have to unique each updated
1905 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1907 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1908 Constant *ToC = cast<Constant>(To);
1910 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
1912 std::pair<LLVMContextImpl::ArrayConstantsTy::MapKey, ConstantArray*> Lookup;
1913 Lookup.first.first = cast<ArrayType>(getType());
1914 Lookup.second = this;
1916 std::vector<Constant*> &Values = Lookup.first.second;
1917 Values.reserve(getNumOperands()); // Build replacement array.
1919 // Fill values with the modified operands of the constant array. Also,
1920 // compute whether this turns into an all-zeros array.
1921 bool isAllZeros = false;
1922 unsigned NumUpdated = 0;
1923 if (!ToC->isNullValue()) {
1924 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1925 Constant *Val = cast<Constant>(O->get());
1930 Values.push_back(Val);
1934 for (Use *O = OperandList, *E = OperandList+getNumOperands();O != E; ++O) {
1935 Constant *Val = cast<Constant>(O->get());
1940 Values.push_back(Val);
1941 if (isAllZeros) isAllZeros = Val->isNullValue();
1945 Constant *Replacement = 0;
1947 Replacement = ConstantAggregateZero::get(getType());
1949 // Check to see if we have this array type already.
1951 LLVMContextImpl::ArrayConstantsTy::MapTy::iterator I =
1952 pImpl->ArrayConstants.InsertOrGetItem(Lookup, Exists);
1955 Replacement = I->second;
1957 // Okay, the new shape doesn't exist in the system yet. Instead of
1958 // creating a new constant array, inserting it, replaceallusesof'ing the
1959 // old with the new, then deleting the old... just update the current one
1961 pImpl->ArrayConstants.MoveConstantToNewSlot(this, I);
1963 // Update to the new value. Optimize for the case when we have a single
1964 // operand that we're changing, but handle bulk updates efficiently.
1965 if (NumUpdated == 1) {
1966 unsigned OperandToUpdate = U - OperandList;
1967 assert(getOperand(OperandToUpdate) == From &&
1968 "ReplaceAllUsesWith broken!");
1969 setOperand(OperandToUpdate, ToC);
1971 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1972 if (getOperand(i) == From)
1979 // Otherwise, I do need to replace this with an existing value.
1980 assert(Replacement != this && "I didn't contain From!");
1982 // Everyone using this now uses the replacement.
1983 replaceAllUsesWith(Replacement);
1985 // Delete the old constant!
1989 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
1991 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1992 Constant *ToC = cast<Constant>(To);
1994 unsigned OperandToUpdate = U-OperandList;
1995 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1997 std::pair<LLVMContextImpl::StructConstantsTy::MapKey, ConstantStruct*> Lookup;
1998 Lookup.first.first = cast<StructType>(getType());
1999 Lookup.second = this;
2000 std::vector<Constant*> &Values = Lookup.first.second;
2001 Values.reserve(getNumOperands()); // Build replacement struct.
2004 // Fill values with the modified operands of the constant struct. Also,
2005 // compute whether this turns into an all-zeros struct.
2006 bool isAllZeros = false;
2007 if (!ToC->isNullValue()) {
2008 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
2009 Values.push_back(cast<Constant>(O->get()));
2012 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2013 Constant *Val = cast<Constant>(O->get());
2014 Values.push_back(Val);
2015 if (isAllZeros) isAllZeros = Val->isNullValue();
2018 Values[OperandToUpdate] = ToC;
2020 LLVMContextImpl *pImpl = getContext().pImpl;
2022 Constant *Replacement = 0;
2024 Replacement = ConstantAggregateZero::get(getType());
2026 // Check to see if we have this struct type already.
2028 LLVMContextImpl::StructConstantsTy::MapTy::iterator I =
2029 pImpl->StructConstants.InsertOrGetItem(Lookup, Exists);
2032 Replacement = I->second;
2034 // Okay, the new shape doesn't exist in the system yet. Instead of
2035 // creating a new constant struct, inserting it, replaceallusesof'ing the
2036 // old with the new, then deleting the old... just update the current one
2038 pImpl->StructConstants.MoveConstantToNewSlot(this, I);
2040 // Update to the new value.
2041 setOperand(OperandToUpdate, ToC);
2046 assert(Replacement != this && "I didn't contain From!");
2048 // Everyone using this now uses the replacement.
2049 replaceAllUsesWith(Replacement);
2051 // Delete the old constant!
2055 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2057 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2059 std::vector<Constant*> Values;
2060 Values.reserve(getNumOperands()); // Build replacement array...
2061 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2062 Constant *Val = getOperand(i);
2063 if (Val == From) Val = cast<Constant>(To);
2064 Values.push_back(Val);
2067 Constant *Replacement = get(Values);
2068 assert(Replacement != this && "I didn't contain From!");
2070 // Everyone using this now uses the replacement.
2071 replaceAllUsesWith(Replacement);
2073 // Delete the old constant!
2077 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2079 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2080 Constant *To = cast<Constant>(ToV);
2082 Constant *Replacement = 0;
2083 if (getOpcode() == Instruction::GetElementPtr) {
2084 SmallVector<Constant*, 8> Indices;
2085 Constant *Pointer = getOperand(0);
2086 Indices.reserve(getNumOperands()-1);
2087 if (Pointer == From) Pointer = To;
2089 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2090 Constant *Val = getOperand(i);
2091 if (Val == From) Val = To;
2092 Indices.push_back(Val);
2094 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2095 &Indices[0], Indices.size(),
2096 cast<GEPOperator>(this)->isInBounds());
2097 } else if (getOpcode() == Instruction::ExtractValue) {
2098 Constant *Agg = getOperand(0);
2099 if (Agg == From) Agg = To;
2101 ArrayRef<unsigned> Indices = getIndices();
2102 Replacement = ConstantExpr::getExtractValue(Agg, Indices);
2103 } else if (getOpcode() == Instruction::InsertValue) {
2104 Constant *Agg = getOperand(0);
2105 Constant *Val = getOperand(1);
2106 if (Agg == From) Agg = To;
2107 if (Val == From) Val = To;
2109 ArrayRef<unsigned> Indices = getIndices();
2110 Replacement = ConstantExpr::getInsertValue(Agg, Val, Indices);
2111 } else if (isCast()) {
2112 assert(getOperand(0) == From && "Cast only has one use!");
2113 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2114 } else if (getOpcode() == Instruction::Select) {
2115 Constant *C1 = getOperand(0);
2116 Constant *C2 = getOperand(1);
2117 Constant *C3 = getOperand(2);
2118 if (C1 == From) C1 = To;
2119 if (C2 == From) C2 = To;
2120 if (C3 == From) C3 = To;
2121 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2122 } else if (getOpcode() == Instruction::ExtractElement) {
2123 Constant *C1 = getOperand(0);
2124 Constant *C2 = getOperand(1);
2125 if (C1 == From) C1 = To;
2126 if (C2 == From) C2 = To;
2127 Replacement = ConstantExpr::getExtractElement(C1, C2);
2128 } else if (getOpcode() == Instruction::InsertElement) {
2129 Constant *C1 = getOperand(0);
2130 Constant *C2 = getOperand(1);
2131 Constant *C3 = getOperand(1);
2132 if (C1 == From) C1 = To;
2133 if (C2 == From) C2 = To;
2134 if (C3 == From) C3 = To;
2135 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2136 } else if (getOpcode() == Instruction::ShuffleVector) {
2137 Constant *C1 = getOperand(0);
2138 Constant *C2 = getOperand(1);
2139 Constant *C3 = getOperand(2);
2140 if (C1 == From) C1 = To;
2141 if (C2 == From) C2 = To;
2142 if (C3 == From) C3 = To;
2143 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2144 } else if (isCompare()) {
2145 Constant *C1 = getOperand(0);
2146 Constant *C2 = getOperand(1);
2147 if (C1 == From) C1 = To;
2148 if (C2 == From) C2 = To;
2149 if (getOpcode() == Instruction::ICmp)
2150 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2152 assert(getOpcode() == Instruction::FCmp);
2153 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2155 } else if (getNumOperands() == 2) {
2156 Constant *C1 = getOperand(0);
2157 Constant *C2 = getOperand(1);
2158 if (C1 == From) C1 = To;
2159 if (C2 == From) C2 = To;
2160 Replacement = ConstantExpr::get(getOpcode(), C1, C2, SubclassOptionalData);
2162 llvm_unreachable("Unknown ConstantExpr type!");
2166 assert(Replacement != this && "I didn't contain From!");
2168 // Everyone using this now uses the replacement.
2169 replaceAllUsesWith(Replacement);
2171 // Delete the old constant!