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"
38 //===----------------------------------------------------------------------===//
40 //===----------------------------------------------------------------------===//
42 // Constructor to create a '0' constant of arbitrary type...
43 static const uint64_t zero[2] = {0, 0};
44 Constant *Constant::getNullValue(const Type *Ty) {
45 switch (Ty->getTypeID()) {
46 case Type::IntegerTyID:
47 return ConstantInt::get(Ty, 0);
49 return ConstantFP::get(Ty->getContext(), APFloat(APInt(32, 0)));
50 case Type::DoubleTyID:
51 return ConstantFP::get(Ty->getContext(), APFloat(APInt(64, 0)));
52 case Type::X86_FP80TyID:
53 return ConstantFP::get(Ty->getContext(), APFloat(APInt(80, 2, zero)));
55 return ConstantFP::get(Ty->getContext(),
56 APFloat(APInt(128, 2, zero), true));
57 case Type::PPC_FP128TyID:
58 return ConstantFP::get(Ty->getContext(), APFloat(APInt(128, 2, zero)));
59 case Type::PointerTyID:
60 return ConstantPointerNull::get(cast<PointerType>(Ty));
61 case Type::StructTyID:
63 case Type::VectorTyID:
64 return ConstantAggregateZero::get(Ty);
66 // Function, Label, or Opaque type?
67 assert(!"Cannot create a null constant of that type!");
72 Constant* Constant::getIntegerValue(const Type *Ty, const APInt &V) {
73 const Type *ScalarTy = Ty->getScalarType();
75 // Create the base integer constant.
76 Constant *C = ConstantInt::get(Ty->getContext(), V);
78 // Convert an integer to a pointer, if necessary.
79 if (const PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
80 C = ConstantExpr::getIntToPtr(C, PTy);
82 // Broadcast a scalar to a vector, if necessary.
83 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
84 C = ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
89 Constant* Constant::getAllOnesValue(const Type *Ty) {
90 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty))
91 return ConstantInt::get(Ty->getContext(),
92 APInt::getAllOnesValue(ITy->getBitWidth()));
94 std::vector<Constant*> Elts;
95 const VectorType *VTy = cast<VectorType>(Ty);
96 Elts.resize(VTy->getNumElements(), getAllOnesValue(VTy->getElementType()));
97 assert(Elts[0] && "Not a vector integer type!");
98 return cast<ConstantVector>(ConstantVector::get(Elts));
101 void Constant::destroyConstantImpl() {
102 // When a Constant is destroyed, there may be lingering
103 // references to the constant by other constants in the constant pool. These
104 // constants are implicitly dependent on the module that is being deleted,
105 // but they don't know that. Because we only find out when the CPV is
106 // deleted, we must now notify all of our users (that should only be
107 // Constants) that they are, in fact, invalid now and should be deleted.
109 while (!use_empty()) {
110 Value *V = use_back();
111 #ifndef NDEBUG // Only in -g mode...
112 if (!isa<Constant>(V)) {
113 dbgs() << "While deleting: " << *this
114 << "\n\nUse still stuck around after Def is destroyed: "
118 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
119 Constant *CV = cast<Constant>(V);
120 CV->destroyConstant();
122 // The constant should remove itself from our use list...
123 assert((use_empty() || use_back() != V) && "Constant not removed!");
126 // Value has no outstanding references it is safe to delete it now...
130 /// canTrap - Return true if evaluation of this constant could trap. This is
131 /// true for things like constant expressions that could divide by zero.
132 bool Constant::canTrap() const {
133 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
134 // The only thing that could possibly trap are constant exprs.
135 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
136 if (!CE) return false;
138 // ConstantExpr traps if any operands can trap.
139 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
140 if (CE->getOperand(i)->canTrap())
143 // Otherwise, only specific operations can trap.
144 switch (CE->getOpcode()) {
147 case Instruction::UDiv:
148 case Instruction::SDiv:
149 case Instruction::FDiv:
150 case Instruction::URem:
151 case Instruction::SRem:
152 case Instruction::FRem:
153 // Div and rem can trap if the RHS is not known to be non-zero.
154 if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
160 /// isConstantUsed - Return true if the constant has users other than constant
161 /// exprs and other dangling things.
162 bool Constant::isConstantUsed() const {
163 for (const_use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
164 const Constant *UC = dyn_cast<Constant>(*UI);
165 if (UC == 0 || isa<GlobalValue>(UC))
168 if (UC->isConstantUsed())
176 /// getRelocationInfo - This method classifies the entry according to
177 /// whether or not it may generate a relocation entry. This must be
178 /// conservative, so if it might codegen to a relocatable entry, it should say
179 /// so. The return values are:
181 /// NoRelocation: This constant pool entry is guaranteed to never have a
182 /// relocation applied to it (because it holds a simple constant like
184 /// LocalRelocation: This entry has relocations, but the entries are
185 /// guaranteed to be resolvable by the static linker, so the dynamic
186 /// linker will never see them.
187 /// GlobalRelocations: This entry may have arbitrary relocations.
189 /// FIXME: This really should not be in VMCore.
190 Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
191 if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
192 if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
193 return LocalRelocation; // Local to this file/library.
194 return GlobalRelocations; // Global reference.
197 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
198 return BA->getFunction()->getRelocationInfo();
200 // While raw uses of blockaddress need to be relocated, differences between
201 // two of them don't when they are for labels in the same function. This is a
202 // common idiom when creating a table for the indirect goto extension, so we
203 // handle it efficiently here.
204 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this))
205 if (CE->getOpcode() == Instruction::Sub) {
206 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
207 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
209 LHS->getOpcode() == Instruction::PtrToInt &&
210 RHS->getOpcode() == Instruction::PtrToInt &&
211 isa<BlockAddress>(LHS->getOperand(0)) &&
212 isa<BlockAddress>(RHS->getOperand(0)) &&
213 cast<BlockAddress>(LHS->getOperand(0))->getFunction() ==
214 cast<BlockAddress>(RHS->getOperand(0))->getFunction())
218 PossibleRelocationsTy Result = NoRelocation;
219 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
220 Result = std::max(Result,
221 cast<Constant>(getOperand(i))->getRelocationInfo());
227 /// getVectorElements - This method, which is only valid on constant of vector
228 /// type, returns the elements of the vector in the specified smallvector.
229 /// This handles breaking down a vector undef into undef elements, etc. For
230 /// constant exprs and other cases we can't handle, we return an empty vector.
231 void Constant::getVectorElements(SmallVectorImpl<Constant*> &Elts) const {
232 assert(getType()->isVectorTy() && "Not a vector constant!");
234 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
235 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
236 Elts.push_back(CV->getOperand(i));
240 const VectorType *VT = cast<VectorType>(getType());
241 if (isa<ConstantAggregateZero>(this)) {
242 Elts.assign(VT->getNumElements(),
243 Constant::getNullValue(VT->getElementType()));
247 if (isa<UndefValue>(this)) {
248 Elts.assign(VT->getNumElements(), UndefValue::get(VT->getElementType()));
252 // Unknown type, must be constant expr etc.
257 //===----------------------------------------------------------------------===//
259 //===----------------------------------------------------------------------===//
261 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
262 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
263 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
266 ConstantInt* ConstantInt::getTrue(LLVMContext &Context) {
267 LLVMContextImpl *pImpl = Context.pImpl;
268 if (!pImpl->TheTrueVal)
269 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
270 return pImpl->TheTrueVal;
273 ConstantInt* ConstantInt::getFalse(LLVMContext &Context) {
274 LLVMContextImpl *pImpl = Context.pImpl;
275 if (!pImpl->TheFalseVal)
276 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
277 return pImpl->TheFalseVal;
281 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
282 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
283 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
284 // compare APInt's of different widths, which would violate an APInt class
285 // invariant which generates an assertion.
286 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt& V) {
287 // Get the corresponding integer type for the bit width of the value.
288 const IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
289 // get an existing value or the insertion position
290 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
291 ConstantInt *&Slot = Context.pImpl->IntConstants[Key];
292 if (!Slot) Slot = new ConstantInt(ITy, V);
296 Constant* ConstantInt::get(const Type* Ty, uint64_t V, bool isSigned) {
297 Constant *C = get(cast<IntegerType>(Ty->getScalarType()),
300 // For vectors, broadcast the value.
301 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
302 return ConstantVector::get(
303 std::vector<Constant *>(VTy->getNumElements(), C));
308 ConstantInt* ConstantInt::get(const IntegerType* Ty, uint64_t V,
310 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
313 ConstantInt* ConstantInt::getSigned(const IntegerType* Ty, int64_t V) {
314 return get(Ty, V, true);
317 Constant *ConstantInt::getSigned(const Type *Ty, int64_t V) {
318 return get(Ty, V, true);
321 Constant* ConstantInt::get(const Type* Ty, const APInt& V) {
322 ConstantInt *C = get(Ty->getContext(), V);
323 assert(C->getType() == Ty->getScalarType() &&
324 "ConstantInt type doesn't match the type implied by its value!");
326 // For vectors, broadcast the value.
327 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
328 return ConstantVector::get(
329 std::vector<Constant *>(VTy->getNumElements(), C));
334 ConstantInt* ConstantInt::get(const IntegerType* Ty, StringRef Str,
336 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
339 //===----------------------------------------------------------------------===//
341 //===----------------------------------------------------------------------===//
343 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
345 return &APFloat::IEEEsingle;
346 if (Ty->isDoubleTy())
347 return &APFloat::IEEEdouble;
348 if (Ty->isX86_FP80Ty())
349 return &APFloat::x87DoubleExtended;
350 else if (Ty->isFP128Ty())
351 return &APFloat::IEEEquad;
353 assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
354 return &APFloat::PPCDoubleDouble;
357 /// get() - This returns a constant fp for the specified value in the
358 /// specified type. This should only be used for simple constant values like
359 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
360 Constant* ConstantFP::get(const Type* Ty, double V) {
361 LLVMContext &Context = Ty->getContext();
365 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
366 APFloat::rmNearestTiesToEven, &ignored);
367 Constant *C = get(Context, FV);
369 // For vectors, broadcast the value.
370 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
371 return ConstantVector::get(
372 std::vector<Constant *>(VTy->getNumElements(), C));
378 Constant* ConstantFP::get(const Type* Ty, StringRef Str) {
379 LLVMContext &Context = Ty->getContext();
381 APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
382 Constant *C = get(Context, FV);
384 // For vectors, broadcast the value.
385 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
386 return ConstantVector::get(
387 std::vector<Constant *>(VTy->getNumElements(), C));
393 ConstantFP* ConstantFP::getNegativeZero(const Type* Ty) {
394 LLVMContext &Context = Ty->getContext();
395 APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
397 return get(Context, apf);
401 Constant* ConstantFP::getZeroValueForNegation(const Type* Ty) {
402 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
403 if (PTy->getElementType()->isFloatingPointTy()) {
404 std::vector<Constant*> zeros(PTy->getNumElements(),
405 getNegativeZero(PTy->getElementType()));
406 return ConstantVector::get(PTy, zeros);
409 if (Ty->isFloatingPointTy())
410 return getNegativeZero(Ty);
412 return Constant::getNullValue(Ty);
416 // ConstantFP accessors.
417 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
418 DenseMapAPFloatKeyInfo::KeyTy Key(V);
420 LLVMContextImpl* pImpl = Context.pImpl;
422 ConstantFP *&Slot = pImpl->FPConstants[Key];
426 if (&V.getSemantics() == &APFloat::IEEEsingle)
427 Ty = Type::getFloatTy(Context);
428 else if (&V.getSemantics() == &APFloat::IEEEdouble)
429 Ty = Type::getDoubleTy(Context);
430 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
431 Ty = Type::getX86_FP80Ty(Context);
432 else if (&V.getSemantics() == &APFloat::IEEEquad)
433 Ty = Type::getFP128Ty(Context);
435 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
436 "Unknown FP format");
437 Ty = Type::getPPC_FP128Ty(Context);
439 Slot = new ConstantFP(Ty, V);
445 ConstantFP *ConstantFP::getInfinity(const Type *Ty, bool Negative) {
446 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty);
447 return ConstantFP::get(Ty->getContext(),
448 APFloat::getInf(Semantics, Negative));
451 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
452 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
453 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
457 bool ConstantFP::isNullValue() const {
458 return Val.isZero() && !Val.isNegative();
461 bool ConstantFP::isExactlyValue(const APFloat& V) const {
462 return Val.bitwiseIsEqual(V);
465 //===----------------------------------------------------------------------===//
466 // ConstantXXX Classes
467 //===----------------------------------------------------------------------===//
470 ConstantArray::ConstantArray(const ArrayType *T,
471 const std::vector<Constant*> &V)
472 : Constant(T, ConstantArrayVal,
473 OperandTraits<ConstantArray>::op_end(this) - V.size(),
475 assert(V.size() == T->getNumElements() &&
476 "Invalid initializer vector for constant array");
477 Use *OL = OperandList;
478 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
481 assert(C->getType() == T->getElementType() &&
482 "Initializer for array element doesn't match array element type!");
487 Constant *ConstantArray::get(const ArrayType *Ty,
488 const std::vector<Constant*> &V) {
489 for (unsigned i = 0, e = V.size(); i != e; ++i) {
490 assert(V[i]->getType() == Ty->getElementType() &&
491 "Wrong type in array element initializer");
493 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
494 // If this is an all-zero array, return a ConstantAggregateZero object
497 if (!C->isNullValue())
498 return pImpl->ArrayConstants.getOrCreate(Ty, V);
500 for (unsigned i = 1, e = V.size(); i != e; ++i)
502 return pImpl->ArrayConstants.getOrCreate(Ty, V);
505 return ConstantAggregateZero::get(Ty);
509 Constant* ConstantArray::get(const ArrayType* T, Constant* const* Vals,
511 // FIXME: make this the primary ctor method.
512 return get(T, std::vector<Constant*>(Vals, Vals+NumVals));
515 /// ConstantArray::get(const string&) - Return an array that is initialized to
516 /// contain the specified string. If length is zero then a null terminator is
517 /// added to the specified string so that it may be used in a natural way.
518 /// Otherwise, the length parameter specifies how much of the string to use
519 /// and it won't be null terminated.
521 Constant* ConstantArray::get(LLVMContext &Context, StringRef Str,
523 std::vector<Constant*> ElementVals;
524 ElementVals.reserve(Str.size() + size_t(AddNull));
525 for (unsigned i = 0; i < Str.size(); ++i)
526 ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), Str[i]));
528 // Add a null terminator to the string...
530 ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), 0));
533 ArrayType *ATy = ArrayType::get(Type::getInt8Ty(Context), ElementVals.size());
534 return get(ATy, ElementVals);
539 ConstantStruct::ConstantStruct(const StructType *T,
540 const std::vector<Constant*> &V)
541 : Constant(T, ConstantStructVal,
542 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
544 assert(V.size() == T->getNumElements() &&
545 "Invalid initializer vector for constant structure");
546 Use *OL = OperandList;
547 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
550 assert(C->getType() == T->getElementType(I-V.begin()) &&
551 "Initializer for struct element doesn't match struct element type!");
556 // ConstantStruct accessors.
557 Constant* ConstantStruct::get(const StructType* T,
558 const std::vector<Constant*>& V) {
559 LLVMContextImpl* pImpl = T->getContext().pImpl;
561 // Create a ConstantAggregateZero value if all elements are zeros...
562 for (unsigned i = 0, e = V.size(); i != e; ++i)
563 if (!V[i]->isNullValue())
564 return pImpl->StructConstants.getOrCreate(T, V);
566 return ConstantAggregateZero::get(T);
569 Constant* ConstantStruct::get(LLVMContext &Context,
570 const std::vector<Constant*>& V, bool packed) {
571 std::vector<const Type*> StructEls;
572 StructEls.reserve(V.size());
573 for (unsigned i = 0, e = V.size(); i != e; ++i)
574 StructEls.push_back(V[i]->getType());
575 return get(StructType::get(Context, StructEls, packed), V);
578 Constant* ConstantStruct::get(LLVMContext &Context,
579 Constant* const *Vals, unsigned NumVals,
581 // FIXME: make this the primary ctor method.
582 return get(Context, std::vector<Constant*>(Vals, Vals+NumVals), Packed);
585 ConstantVector::ConstantVector(const VectorType *T,
586 const std::vector<Constant*> &V)
587 : Constant(T, ConstantVectorVal,
588 OperandTraits<ConstantVector>::op_end(this) - V.size(),
590 Use *OL = OperandList;
591 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
594 assert(C->getType() == T->getElementType() &&
595 "Initializer for vector element doesn't match vector element type!");
600 // ConstantVector accessors.
601 Constant* ConstantVector::get(const VectorType* T,
602 const std::vector<Constant*>& V) {
603 assert(!V.empty() && "Vectors can't be empty");
604 LLVMContext &Context = T->getContext();
605 LLVMContextImpl *pImpl = Context.pImpl;
607 // If this is an all-undef or alll-zero vector, return a
608 // ConstantAggregateZero or UndefValue.
610 bool isZero = C->isNullValue();
611 bool isUndef = isa<UndefValue>(C);
613 if (isZero || isUndef) {
614 for (unsigned i = 1, e = V.size(); i != e; ++i)
616 isZero = isUndef = false;
622 return ConstantAggregateZero::get(T);
624 return UndefValue::get(T);
626 return pImpl->VectorConstants.getOrCreate(T, V);
629 Constant* ConstantVector::get(const std::vector<Constant*>& V) {
630 assert(!V.empty() && "Cannot infer type if V is empty");
631 return get(VectorType::get(V.front()->getType(),V.size()), V);
634 Constant* ConstantVector::get(Constant* const* Vals, unsigned NumVals) {
635 // FIXME: make this the primary ctor method.
636 return get(std::vector<Constant*>(Vals, Vals+NumVals));
639 Constant* ConstantExpr::getNSWNeg(Constant* C) {
640 assert(C->getType()->isIntOrIntVectorTy() &&
641 "Cannot NEG a nonintegral value!");
642 return getNSWSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
645 Constant* ConstantExpr::getNUWNeg(Constant* C) {
646 assert(C->getType()->isIntOrIntVectorTy() &&
647 "Cannot NEG a nonintegral value!");
648 return getNUWSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
651 Constant* ConstantExpr::getNSWAdd(Constant* C1, Constant* C2) {
652 return getTy(C1->getType(), Instruction::Add, C1, C2,
653 OverflowingBinaryOperator::NoSignedWrap);
656 Constant* ConstantExpr::getNUWAdd(Constant* C1, Constant* C2) {
657 return getTy(C1->getType(), Instruction::Add, C1, C2,
658 OverflowingBinaryOperator::NoUnsignedWrap);
661 Constant* ConstantExpr::getNSWSub(Constant* C1, Constant* C2) {
662 return getTy(C1->getType(), Instruction::Sub, C1, C2,
663 OverflowingBinaryOperator::NoSignedWrap);
666 Constant* ConstantExpr::getNUWSub(Constant* C1, Constant* C2) {
667 return getTy(C1->getType(), Instruction::Sub, C1, C2,
668 OverflowingBinaryOperator::NoUnsignedWrap);
671 Constant* ConstantExpr::getNSWMul(Constant* C1, Constant* C2) {
672 return getTy(C1->getType(), Instruction::Mul, C1, C2,
673 OverflowingBinaryOperator::NoSignedWrap);
676 Constant* ConstantExpr::getNUWMul(Constant* C1, Constant* C2) {
677 return getTy(C1->getType(), Instruction::Mul, C1, C2,
678 OverflowingBinaryOperator::NoUnsignedWrap);
681 Constant* ConstantExpr::getExactSDiv(Constant* C1, Constant* C2) {
682 return getTy(C1->getType(), Instruction::SDiv, C1, C2,
683 SDivOperator::IsExact);
686 // Utility function for determining if a ConstantExpr is a CastOp or not. This
687 // can't be inline because we don't want to #include Instruction.h into
689 bool ConstantExpr::isCast() const {
690 return Instruction::isCast(getOpcode());
693 bool ConstantExpr::isCompare() const {
694 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
697 bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
698 if (getOpcode() != Instruction::GetElementPtr) return false;
700 gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
701 User::const_op_iterator OI = llvm::next(this->op_begin());
703 // Skip the first index, as it has no static limit.
707 // The remaining indices must be compile-time known integers within the
708 // bounds of the corresponding notional static array types.
709 for (; GEPI != E; ++GEPI, ++OI) {
710 ConstantInt *CI = dyn_cast<ConstantInt>(*OI);
711 if (!CI) return false;
712 if (const ArrayType *ATy = dyn_cast<ArrayType>(*GEPI))
713 if (CI->getValue().getActiveBits() > 64 ||
714 CI->getZExtValue() >= ATy->getNumElements())
718 // All the indices checked out.
722 bool ConstantExpr::hasIndices() const {
723 return getOpcode() == Instruction::ExtractValue ||
724 getOpcode() == Instruction::InsertValue;
727 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
728 if (const ExtractValueConstantExpr *EVCE =
729 dyn_cast<ExtractValueConstantExpr>(this))
730 return EVCE->Indices;
732 return cast<InsertValueConstantExpr>(this)->Indices;
735 unsigned ConstantExpr::getPredicate() const {
736 assert(getOpcode() == Instruction::FCmp ||
737 getOpcode() == Instruction::ICmp);
738 return ((const CompareConstantExpr*)this)->predicate;
741 /// getWithOperandReplaced - Return a constant expression identical to this
742 /// one, but with the specified operand set to the specified value.
744 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
745 assert(OpNo < getNumOperands() && "Operand num is out of range!");
746 assert(Op->getType() == getOperand(OpNo)->getType() &&
747 "Replacing operand with value of different type!");
748 if (getOperand(OpNo) == Op)
749 return const_cast<ConstantExpr*>(this);
751 Constant *Op0, *Op1, *Op2;
752 switch (getOpcode()) {
753 case Instruction::Trunc:
754 case Instruction::ZExt:
755 case Instruction::SExt:
756 case Instruction::FPTrunc:
757 case Instruction::FPExt:
758 case Instruction::UIToFP:
759 case Instruction::SIToFP:
760 case Instruction::FPToUI:
761 case Instruction::FPToSI:
762 case Instruction::PtrToInt:
763 case Instruction::IntToPtr:
764 case Instruction::BitCast:
765 return ConstantExpr::getCast(getOpcode(), Op, getType());
766 case Instruction::Select:
767 Op0 = (OpNo == 0) ? Op : getOperand(0);
768 Op1 = (OpNo == 1) ? Op : getOperand(1);
769 Op2 = (OpNo == 2) ? Op : getOperand(2);
770 return ConstantExpr::getSelect(Op0, Op1, Op2);
771 case Instruction::InsertElement:
772 Op0 = (OpNo == 0) ? Op : getOperand(0);
773 Op1 = (OpNo == 1) ? Op : getOperand(1);
774 Op2 = (OpNo == 2) ? Op : getOperand(2);
775 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
776 case Instruction::ExtractElement:
777 Op0 = (OpNo == 0) ? Op : getOperand(0);
778 Op1 = (OpNo == 1) ? Op : getOperand(1);
779 return ConstantExpr::getExtractElement(Op0, Op1);
780 case Instruction::ShuffleVector:
781 Op0 = (OpNo == 0) ? Op : getOperand(0);
782 Op1 = (OpNo == 1) ? Op : getOperand(1);
783 Op2 = (OpNo == 2) ? Op : getOperand(2);
784 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
785 case Instruction::GetElementPtr: {
786 SmallVector<Constant*, 8> Ops;
787 Ops.resize(getNumOperands()-1);
788 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
789 Ops[i-1] = getOperand(i);
791 return cast<GEPOperator>(this)->isInBounds() ?
792 ConstantExpr::getInBoundsGetElementPtr(Op, &Ops[0], Ops.size()) :
793 ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
795 return cast<GEPOperator>(this)->isInBounds() ?
796 ConstantExpr::getInBoundsGetElementPtr(getOperand(0), &Ops[0],Ops.size()):
797 ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
800 assert(getNumOperands() == 2 && "Must be binary operator?");
801 Op0 = (OpNo == 0) ? Op : getOperand(0);
802 Op1 = (OpNo == 1) ? Op : getOperand(1);
803 return ConstantExpr::get(getOpcode(), Op0, Op1, SubclassOptionalData);
807 /// getWithOperands - This returns the current constant expression with the
808 /// operands replaced with the specified values. The specified operands must
809 /// match count and type with the existing ones.
810 Constant *ConstantExpr::
811 getWithOperands(Constant* const *Ops, unsigned NumOps) const {
812 assert(NumOps == getNumOperands() && "Operand count mismatch!");
813 bool AnyChange = false;
814 for (unsigned i = 0; i != NumOps; ++i) {
815 assert(Ops[i]->getType() == getOperand(i)->getType() &&
816 "Operand type mismatch!");
817 AnyChange |= Ops[i] != getOperand(i);
819 if (!AnyChange) // No operands changed, return self.
820 return const_cast<ConstantExpr*>(this);
822 switch (getOpcode()) {
823 case Instruction::Trunc:
824 case Instruction::ZExt:
825 case Instruction::SExt:
826 case Instruction::FPTrunc:
827 case Instruction::FPExt:
828 case Instruction::UIToFP:
829 case Instruction::SIToFP:
830 case Instruction::FPToUI:
831 case Instruction::FPToSI:
832 case Instruction::PtrToInt:
833 case Instruction::IntToPtr:
834 case Instruction::BitCast:
835 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
836 case Instruction::Select:
837 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
838 case Instruction::InsertElement:
839 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
840 case Instruction::ExtractElement:
841 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
842 case Instruction::ShuffleVector:
843 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
844 case Instruction::GetElementPtr:
845 return cast<GEPOperator>(this)->isInBounds() ?
846 ConstantExpr::getInBoundsGetElementPtr(Ops[0], &Ops[1], NumOps-1) :
847 ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
848 case Instruction::ICmp:
849 case Instruction::FCmp:
850 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
852 assert(getNumOperands() == 2 && "Must be binary operator?");
853 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData);
858 //===----------------------------------------------------------------------===//
859 // isValueValidForType implementations
861 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
862 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
863 if (Ty == Type::getInt1Ty(Ty->getContext()))
864 return Val == 0 || Val == 1;
866 return true; // always true, has to fit in largest type
867 uint64_t Max = (1ll << NumBits) - 1;
871 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
872 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
873 if (Ty == Type::getInt1Ty(Ty->getContext()))
874 return Val == 0 || Val == 1 || Val == -1;
876 return true; // always true, has to fit in largest type
877 int64_t Min = -(1ll << (NumBits-1));
878 int64_t Max = (1ll << (NumBits-1)) - 1;
879 return (Val >= Min && Val <= Max);
882 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
883 // convert modifies in place, so make a copy.
884 APFloat Val2 = APFloat(Val);
886 switch (Ty->getTypeID()) {
888 return false; // These can't be represented as floating point!
890 // FIXME rounding mode needs to be more flexible
891 case Type::FloatTyID: {
892 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
894 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
897 case Type::DoubleTyID: {
898 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
899 &Val2.getSemantics() == &APFloat::IEEEdouble)
901 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
904 case Type::X86_FP80TyID:
905 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
906 &Val2.getSemantics() == &APFloat::IEEEdouble ||
907 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
908 case Type::FP128TyID:
909 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
910 &Val2.getSemantics() == &APFloat::IEEEdouble ||
911 &Val2.getSemantics() == &APFloat::IEEEquad;
912 case Type::PPC_FP128TyID:
913 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
914 &Val2.getSemantics() == &APFloat::IEEEdouble ||
915 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
919 //===----------------------------------------------------------------------===//
920 // Factory Function Implementation
922 ConstantAggregateZero* ConstantAggregateZero::get(const Type* Ty) {
923 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
924 "Cannot create an aggregate zero of non-aggregate type!");
926 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
927 return pImpl->AggZeroConstants.getOrCreate(Ty, 0);
930 /// destroyConstant - Remove the constant from the constant table...
932 void ConstantAggregateZero::destroyConstant() {
933 getRawType()->getContext().pImpl->AggZeroConstants.remove(this);
934 destroyConstantImpl();
937 /// destroyConstant - Remove the constant from the constant table...
939 void ConstantArray::destroyConstant() {
940 getRawType()->getContext().pImpl->ArrayConstants.remove(this);
941 destroyConstantImpl();
944 /// isString - This method returns true if the array is an array of i8, and
945 /// if the elements of the array are all ConstantInt's.
946 bool ConstantArray::isString() const {
947 // Check the element type for i8...
948 if (!getType()->getElementType()->isIntegerTy(8))
950 // Check the elements to make sure they are all integers, not constant
952 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
953 if (!isa<ConstantInt>(getOperand(i)))
958 /// isCString - This method returns true if the array is a string (see
959 /// isString) and it ends in a null byte \\0 and does not contains any other
960 /// null bytes except its terminator.
961 bool ConstantArray::isCString() const {
962 // Check the element type for i8...
963 if (!getType()->getElementType()->isIntegerTy(8))
966 // Last element must be a null.
967 if (!getOperand(getNumOperands()-1)->isNullValue())
969 // Other elements must be non-null integers.
970 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
971 if (!isa<ConstantInt>(getOperand(i)))
973 if (getOperand(i)->isNullValue())
980 /// getAsString - If the sub-element type of this array is i8
981 /// then this method converts the array to an std::string and returns it.
982 /// Otherwise, it asserts out.
984 std::string ConstantArray::getAsString() const {
985 assert(isString() && "Not a string!");
987 Result.reserve(getNumOperands());
988 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
989 Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
994 //---- ConstantStruct::get() implementation...
1001 // destroyConstant - Remove the constant from the constant table...
1003 void ConstantStruct::destroyConstant() {
1004 getRawType()->getContext().pImpl->StructConstants.remove(this);
1005 destroyConstantImpl();
1008 // destroyConstant - Remove the constant from the constant table...
1010 void ConstantVector::destroyConstant() {
1011 getRawType()->getContext().pImpl->VectorConstants.remove(this);
1012 destroyConstantImpl();
1015 /// This function will return true iff every element in this vector constant
1016 /// is set to all ones.
1017 /// @returns true iff this constant's emements are all set to all ones.
1018 /// @brief Determine if the value is all ones.
1019 bool ConstantVector::isAllOnesValue() const {
1020 // Check out first element.
1021 const Constant *Elt = getOperand(0);
1022 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1023 if (!CI || !CI->isAllOnesValue()) return false;
1024 // Then make sure all remaining elements point to the same value.
1025 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1026 if (getOperand(I) != Elt) return false;
1031 /// getSplatValue - If this is a splat constant, where all of the
1032 /// elements have the same value, return that value. Otherwise return null.
1033 Constant *ConstantVector::getSplatValue() {
1034 // Check out first element.
1035 Constant *Elt = getOperand(0);
1036 // Then make sure all remaining elements point to the same value.
1037 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1038 if (getOperand(I) != Elt) return 0;
1042 //---- ConstantPointerNull::get() implementation.
1045 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1046 return Ty->getContext().pImpl->NullPtrConstants.getOrCreate(Ty, 0);
1049 // destroyConstant - Remove the constant from the constant table...
1051 void ConstantPointerNull::destroyConstant() {
1052 getRawType()->getContext().pImpl->NullPtrConstants.remove(this);
1053 destroyConstantImpl();
1057 //---- UndefValue::get() implementation.
1060 UndefValue *UndefValue::get(const Type *Ty) {
1061 return Ty->getContext().pImpl->UndefValueConstants.getOrCreate(Ty, 0);
1064 // destroyConstant - Remove the constant from the constant table.
1066 void UndefValue::destroyConstant() {
1067 getRawType()->getContext().pImpl->UndefValueConstants.remove(this);
1068 destroyConstantImpl();
1071 //---- BlockAddress::get() implementation.
1074 BlockAddress *BlockAddress::get(BasicBlock *BB) {
1075 assert(BB->getParent() != 0 && "Block must have a parent");
1076 return get(BB->getParent(), BB);
1079 BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1081 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
1083 BA = new BlockAddress(F, BB);
1085 assert(BA->getFunction() == F && "Basic block moved between functions");
1089 BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1090 : Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1094 BB->AdjustBlockAddressRefCount(1);
1098 // destroyConstant - Remove the constant from the constant table.
1100 void BlockAddress::destroyConstant() {
1101 getFunction()->getRawType()->getContext().pImpl
1102 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
1103 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1104 destroyConstantImpl();
1107 void BlockAddress::replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U) {
1108 // This could be replacing either the Basic Block or the Function. In either
1109 // case, we have to remove the map entry.
1110 Function *NewF = getFunction();
1111 BasicBlock *NewBB = getBasicBlock();
1114 NewF = cast<Function>(To);
1116 NewBB = cast<BasicBlock>(To);
1118 // See if the 'new' entry already exists, if not, just update this in place
1119 // and return early.
1120 BlockAddress *&NewBA =
1121 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
1123 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1125 // Remove the old entry, this can't cause the map to rehash (just a
1126 // tombstone will get added).
1127 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1130 setOperand(0, NewF);
1131 setOperand(1, NewBB);
1132 getBasicBlock()->AdjustBlockAddressRefCount(1);
1136 // Otherwise, I do need to replace this with an existing value.
1137 assert(NewBA != this && "I didn't contain From!");
1139 // Everyone using this now uses the replacement.
1140 uncheckedReplaceAllUsesWith(NewBA);
1145 //---- ConstantExpr::get() implementations.
1148 /// This is a utility function to handle folding of casts and lookup of the
1149 /// cast in the ExprConstants map. It is used by the various get* methods below.
1150 static inline Constant *getFoldedCast(
1151 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1152 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1153 // Fold a few common cases
1154 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1157 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1159 // Look up the constant in the table first to ensure uniqueness
1160 std::vector<Constant*> argVec(1, C);
1161 ExprMapKeyType Key(opc, argVec);
1163 return pImpl->ExprConstants.getOrCreate(Ty, Key);
1166 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1167 Instruction::CastOps opc = Instruction::CastOps(oc);
1168 assert(Instruction::isCast(opc) && "opcode out of range");
1169 assert(C && Ty && "Null arguments to getCast");
1170 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
1174 llvm_unreachable("Invalid cast opcode");
1176 case Instruction::Trunc: return getTrunc(C, Ty);
1177 case Instruction::ZExt: return getZExt(C, Ty);
1178 case Instruction::SExt: return getSExt(C, Ty);
1179 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1180 case Instruction::FPExt: return getFPExtend(C, Ty);
1181 case Instruction::UIToFP: return getUIToFP(C, Ty);
1182 case Instruction::SIToFP: return getSIToFP(C, Ty);
1183 case Instruction::FPToUI: return getFPToUI(C, Ty);
1184 case Instruction::FPToSI: return getFPToSI(C, Ty);
1185 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1186 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1187 case Instruction::BitCast: return getBitCast(C, Ty);
1192 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1193 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1194 return getBitCast(C, Ty);
1195 return getZExt(C, Ty);
1198 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1199 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1200 return getBitCast(C, Ty);
1201 return getSExt(C, Ty);
1204 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1205 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1206 return getBitCast(C, Ty);
1207 return getTrunc(C, Ty);
1210 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1211 assert(S->getType()->isPointerTy() && "Invalid cast");
1212 assert((Ty->isIntegerTy() || Ty->isPointerTy()) && "Invalid cast");
1214 if (Ty->isIntegerTy())
1215 return getPtrToInt(S, Ty);
1216 return getBitCast(S, Ty);
1219 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1221 assert(C->getType()->isIntOrIntVectorTy() &&
1222 Ty->isIntOrIntVectorTy() && "Invalid cast");
1223 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1224 unsigned DstBits = Ty->getScalarSizeInBits();
1225 Instruction::CastOps opcode =
1226 (SrcBits == DstBits ? Instruction::BitCast :
1227 (SrcBits > DstBits ? Instruction::Trunc :
1228 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1229 return getCast(opcode, C, Ty);
1232 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1233 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1235 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1236 unsigned DstBits = Ty->getScalarSizeInBits();
1237 if (SrcBits == DstBits)
1238 return C; // Avoid a useless cast
1239 Instruction::CastOps opcode =
1240 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1241 return getCast(opcode, C, Ty);
1244 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1246 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1247 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1249 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1250 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
1251 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
1252 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1253 "SrcTy must be larger than DestTy for Trunc!");
1255 return getFoldedCast(Instruction::Trunc, C, Ty);
1258 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1260 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1261 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1263 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1264 assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
1265 assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
1266 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1267 "SrcTy must be smaller than DestTy for SExt!");
1269 return getFoldedCast(Instruction::SExt, C, Ty);
1272 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1274 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1275 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1277 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1278 assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
1279 assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
1280 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1281 "SrcTy must be smaller than DestTy for ZExt!");
1283 return getFoldedCast(Instruction::ZExt, C, Ty);
1286 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1288 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1289 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1291 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1292 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1293 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1294 "This is an illegal floating point truncation!");
1295 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1298 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1300 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1301 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1303 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1304 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1305 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1306 "This is an illegal floating point extension!");
1307 return getFoldedCast(Instruction::FPExt, C, Ty);
1310 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1312 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1313 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1315 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1316 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1317 "This is an illegal uint to floating point cast!");
1318 return getFoldedCast(Instruction::UIToFP, C, Ty);
1321 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1323 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1324 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1326 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1327 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1328 "This is an illegal sint to floating point cast!");
1329 return getFoldedCast(Instruction::SIToFP, C, Ty);
1332 Constant *ConstantExpr::getFPToUI(Constant *C, const 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->isIntOrIntVectorTy() &&
1339 "This is an illegal floating point to uint cast!");
1340 return getFoldedCast(Instruction::FPToUI, C, Ty);
1343 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1345 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1346 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1348 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1349 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1350 "This is an illegal floating point to sint cast!");
1351 return getFoldedCast(Instruction::FPToSI, C, Ty);
1354 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1355 assert(C->getType()->isPointerTy() && "PtrToInt source must be pointer");
1356 assert(DstTy->isIntegerTy() && "PtrToInt destination must be integral");
1357 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1360 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1361 assert(C->getType()->isIntegerTy() && "IntToPtr source must be integral");
1362 assert(DstTy->isPointerTy() && "IntToPtr destination must be a pointer");
1363 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1366 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1367 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
1368 "Invalid constantexpr bitcast!");
1370 // It is common to ask for a bitcast of a value to its own type, handle this
1372 if (C->getType() == DstTy) return C;
1374 return getFoldedCast(Instruction::BitCast, C, DstTy);
1377 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1378 Constant *C1, Constant *C2,
1380 // Check the operands for consistency first
1381 assert(Opcode >= Instruction::BinaryOpsBegin &&
1382 Opcode < Instruction::BinaryOpsEnd &&
1383 "Invalid opcode in binary constant expression");
1384 assert(C1->getType() == C2->getType() &&
1385 "Operand types in binary constant expression should match");
1387 if (ReqTy == C1->getType() || ReqTy == Type::getInt1Ty(ReqTy->getContext()))
1388 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1389 return FC; // Fold a few common cases...
1391 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1392 ExprMapKeyType Key(Opcode, argVec, 0, Flags);
1394 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1395 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1398 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1399 Constant *C1, Constant *C2) {
1400 switch (predicate) {
1401 default: llvm_unreachable("Invalid CmpInst predicate");
1402 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1403 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1404 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1405 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1406 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1407 case CmpInst::FCMP_TRUE:
1408 return getFCmp(predicate, C1, C2);
1410 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1411 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1412 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1413 case CmpInst::ICMP_SLE:
1414 return getICmp(predicate, C1, C2);
1418 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
1422 case Instruction::Add:
1423 case Instruction::Sub:
1424 case Instruction::Mul:
1425 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1426 assert(C1->getType()->isIntOrIntVectorTy() &&
1427 "Tried to create an integer operation on a non-integer type!");
1429 case Instruction::FAdd:
1430 case Instruction::FSub:
1431 case Instruction::FMul:
1432 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1433 assert(C1->getType()->isFPOrFPVectorTy() &&
1434 "Tried to create a floating-point operation on a "
1435 "non-floating-point type!");
1437 case Instruction::UDiv:
1438 case Instruction::SDiv:
1439 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1440 assert(C1->getType()->isIntOrIntVectorTy() &&
1441 "Tried to create an arithmetic operation on a non-arithmetic type!");
1443 case Instruction::FDiv:
1444 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1445 assert(C1->getType()->isFPOrFPVectorTy() &&
1446 "Tried to create an arithmetic operation on a non-arithmetic type!");
1448 case Instruction::URem:
1449 case Instruction::SRem:
1450 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1451 assert(C1->getType()->isIntOrIntVectorTy() &&
1452 "Tried to create an arithmetic operation on a non-arithmetic type!");
1454 case Instruction::FRem:
1455 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1456 assert(C1->getType()->isFPOrFPVectorTy() &&
1457 "Tried to create an arithmetic operation on a non-arithmetic type!");
1459 case Instruction::And:
1460 case Instruction::Or:
1461 case Instruction::Xor:
1462 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1463 assert(C1->getType()->isIntOrIntVectorTy() &&
1464 "Tried to create a logical operation on a non-integral type!");
1466 case Instruction::Shl:
1467 case Instruction::LShr:
1468 case Instruction::AShr:
1469 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1470 assert(C1->getType()->isIntOrIntVectorTy() &&
1471 "Tried to create a shift operation on a non-integer type!");
1478 return getTy(C1->getType(), Opcode, C1, C2, Flags);
1481 Constant* ConstantExpr::getSizeOf(const Type* Ty) {
1482 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1483 // Note that a non-inbounds gep is used, as null isn't within any object.
1484 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1485 Constant *GEP = getGetElementPtr(
1486 Constant::getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
1487 return getPtrToInt(GEP,
1488 Type::getInt64Ty(Ty->getContext()));
1491 Constant* ConstantExpr::getAlignOf(const Type* Ty) {
1492 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
1493 // Note that a non-inbounds gep is used, as null isn't within any object.
1494 const Type *AligningTy = StructType::get(Ty->getContext(),
1495 Type::getInt1Ty(Ty->getContext()), Ty, NULL);
1496 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo());
1497 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
1498 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1499 Constant *Indices[2] = { Zero, One };
1500 Constant *GEP = getGetElementPtr(NullPtr, Indices, 2);
1501 return getPtrToInt(GEP,
1502 Type::getInt64Ty(Ty->getContext()));
1505 Constant* ConstantExpr::getOffsetOf(const StructType* STy, unsigned FieldNo) {
1506 return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
1510 Constant* ConstantExpr::getOffsetOf(const Type* Ty, Constant *FieldNo) {
1511 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1512 // Note that a non-inbounds gep is used, as null isn't within any object.
1513 Constant *GEPIdx[] = {
1514 ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
1517 Constant *GEP = getGetElementPtr(
1518 Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx, 2);
1519 return getPtrToInt(GEP,
1520 Type::getInt64Ty(Ty->getContext()));
1523 Constant *ConstantExpr::getCompare(unsigned short pred,
1524 Constant *C1, Constant *C2) {
1525 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1526 return getCompareTy(pred, C1, C2);
1529 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1530 Constant *V1, Constant *V2) {
1531 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1533 if (ReqTy == V1->getType())
1534 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1535 return SC; // Fold common cases
1537 std::vector<Constant*> argVec(3, C);
1540 ExprMapKeyType Key(Instruction::Select, argVec);
1542 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1543 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1546 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1549 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
1551 cast<PointerType>(ReqTy)->getElementType() &&
1552 "GEP indices invalid!");
1554 if (Constant *FC = ConstantFoldGetElementPtr(C, /*inBounds=*/false,
1555 (Constant**)Idxs, NumIdx))
1556 return FC; // Fold a few common cases...
1558 assert(C->getType()->isPointerTy() &&
1559 "Non-pointer type for constant GetElementPtr expression");
1560 // Look up the constant in the table first to ensure uniqueness
1561 std::vector<Constant*> ArgVec;
1562 ArgVec.reserve(NumIdx+1);
1563 ArgVec.push_back(C);
1564 for (unsigned i = 0; i != NumIdx; ++i)
1565 ArgVec.push_back(cast<Constant>(Idxs[i]));
1566 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
1568 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1569 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1572 Constant *ConstantExpr::getInBoundsGetElementPtrTy(const Type *ReqTy,
1576 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
1578 cast<PointerType>(ReqTy)->getElementType() &&
1579 "GEP indices invalid!");
1581 if (Constant *FC = ConstantFoldGetElementPtr(C, /*inBounds=*/true,
1582 (Constant**)Idxs, NumIdx))
1583 return FC; // Fold a few common cases...
1585 assert(C->getType()->isPointerTy() &&
1586 "Non-pointer type for constant GetElementPtr expression");
1587 // Look up the constant in the table first to ensure uniqueness
1588 std::vector<Constant*> ArgVec;
1589 ArgVec.reserve(NumIdx+1);
1590 ArgVec.push_back(C);
1591 for (unsigned i = 0; i != NumIdx; ++i)
1592 ArgVec.push_back(cast<Constant>(Idxs[i]));
1593 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
1594 GEPOperator::IsInBounds);
1596 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1597 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1600 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1602 // Get the result type of the getelementptr!
1604 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
1605 assert(Ty && "GEP indices invalid!");
1606 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
1607 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
1610 Constant *ConstantExpr::getInBoundsGetElementPtr(Constant *C,
1613 // Get the result type of the getelementptr!
1615 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
1616 assert(Ty && "GEP indices invalid!");
1617 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
1618 return getInBoundsGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
1621 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1623 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1626 Constant *ConstantExpr::getInBoundsGetElementPtr(Constant *C,
1627 Constant* const *Idxs,
1629 return getInBoundsGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1633 ConstantExpr::getICmp(unsigned short pred, Constant *LHS, Constant *RHS) {
1634 assert(LHS->getType() == RHS->getType());
1635 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1636 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1638 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1639 return FC; // Fold a few common cases...
1641 // Look up the constant in the table first to ensure uniqueness
1642 std::vector<Constant*> ArgVec;
1643 ArgVec.push_back(LHS);
1644 ArgVec.push_back(RHS);
1645 // Get the key type with both the opcode and predicate
1646 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1648 const Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1649 if (const VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1650 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1652 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1653 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
1657 ConstantExpr::getFCmp(unsigned short pred, Constant *LHS, Constant *RHS) {
1658 assert(LHS->getType() == RHS->getType());
1659 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1661 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1662 return FC; // Fold a few common cases...
1664 // Look up the constant in the table first to ensure uniqueness
1665 std::vector<Constant*> ArgVec;
1666 ArgVec.push_back(LHS);
1667 ArgVec.push_back(RHS);
1668 // Get the key type with both the opcode and predicate
1669 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1671 const Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1672 if (const VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1673 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1675 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1676 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
1679 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1681 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, 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(Idx);
1686 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1688 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1689 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1692 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1693 assert(Val->getType()->isVectorTy() &&
1694 "Tried to create extractelement operation on non-vector type!");
1695 assert(Idx->getType()->isIntegerTy(32) &&
1696 "Extractelement index must be i32 type!");
1697 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
1701 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1702 Constant *Elt, Constant *Idx) {
1703 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1704 return FC; // Fold a few common cases.
1705 // Look up the constant in the table first to ensure uniqueness
1706 std::vector<Constant*> ArgVec(1, Val);
1707 ArgVec.push_back(Elt);
1708 ArgVec.push_back(Idx);
1709 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1711 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1712 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1715 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1717 assert(Val->getType()->isVectorTy() &&
1718 "Tried to create insertelement operation on non-vector type!");
1719 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
1720 && "Insertelement types must match!");
1721 assert(Idx->getType()->isIntegerTy(32) &&
1722 "Insertelement index must be i32 type!");
1723 return getInsertElementTy(Val->getType(), Val, Elt, Idx);
1726 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1727 Constant *V2, Constant *Mask) {
1728 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1729 return FC; // Fold a few common cases...
1730 // Look up the constant in the table first to ensure uniqueness
1731 std::vector<Constant*> ArgVec(1, V1);
1732 ArgVec.push_back(V2);
1733 ArgVec.push_back(Mask);
1734 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1736 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1737 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1740 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1742 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1743 "Invalid shuffle vector constant expr operands!");
1745 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
1746 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
1747 const Type *ShufTy = VectorType::get(EltTy, NElts);
1748 return getShuffleVectorTy(ShufTy, V1, V2, Mask);
1751 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
1753 const unsigned *Idxs, unsigned NumIdx) {
1754 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1755 Idxs+NumIdx) == Val->getType() &&
1756 "insertvalue indices invalid!");
1757 assert(Agg->getType() == ReqTy &&
1758 "insertvalue type invalid!");
1759 assert(Agg->getType()->isFirstClassType() &&
1760 "Non-first-class type for constant InsertValue expression");
1761 Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs, NumIdx);
1762 assert(FC && "InsertValue constant expr couldn't be folded!");
1766 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
1767 const unsigned *IdxList, unsigned NumIdx) {
1768 assert(Agg->getType()->isFirstClassType() &&
1769 "Tried to create insertelement operation on non-first-class type!");
1771 const Type *ReqTy = Agg->getType();
1774 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1776 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
1777 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
1780 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
1781 const unsigned *Idxs, unsigned NumIdx) {
1782 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1783 Idxs+NumIdx) == ReqTy &&
1784 "extractvalue indices invalid!");
1785 assert(Agg->getType()->isFirstClassType() &&
1786 "Non-first-class type for constant extractvalue expression");
1787 Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs, NumIdx);
1788 assert(FC && "ExtractValue constant expr couldn't be folded!");
1792 Constant *ConstantExpr::getExtractValue(Constant *Agg,
1793 const unsigned *IdxList, unsigned NumIdx) {
1794 assert(Agg->getType()->isFirstClassType() &&
1795 "Tried to create extractelement operation on non-first-class type!");
1798 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1799 assert(ReqTy && "extractvalue indices invalid!");
1800 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
1803 Constant* ConstantExpr::getNeg(Constant* C) {
1804 assert(C->getType()->isIntOrIntVectorTy() &&
1805 "Cannot NEG a nonintegral value!");
1806 return get(Instruction::Sub,
1807 ConstantFP::getZeroValueForNegation(C->getType()),
1811 Constant* ConstantExpr::getFNeg(Constant* C) {
1812 assert(C->getType()->isFPOrFPVectorTy() &&
1813 "Cannot FNEG a non-floating-point value!");
1814 return get(Instruction::FSub,
1815 ConstantFP::getZeroValueForNegation(C->getType()),
1819 Constant* ConstantExpr::getNot(Constant* C) {
1820 assert(C->getType()->isIntOrIntVectorTy() &&
1821 "Cannot NOT a nonintegral value!");
1822 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
1825 Constant* ConstantExpr::getAdd(Constant* C1, Constant* C2) {
1826 return get(Instruction::Add, C1, C2);
1829 Constant* ConstantExpr::getFAdd(Constant* C1, Constant* C2) {
1830 return get(Instruction::FAdd, C1, C2);
1833 Constant* ConstantExpr::getSub(Constant* C1, Constant* C2) {
1834 return get(Instruction::Sub, C1, C2);
1837 Constant* ConstantExpr::getFSub(Constant* C1, Constant* C2) {
1838 return get(Instruction::FSub, C1, C2);
1841 Constant* ConstantExpr::getMul(Constant* C1, Constant* C2) {
1842 return get(Instruction::Mul, C1, C2);
1845 Constant* ConstantExpr::getFMul(Constant* C1, Constant* C2) {
1846 return get(Instruction::FMul, C1, C2);
1849 Constant* ConstantExpr::getUDiv(Constant* C1, Constant* C2) {
1850 return get(Instruction::UDiv, C1, C2);
1853 Constant* ConstantExpr::getSDiv(Constant* C1, Constant* C2) {
1854 return get(Instruction::SDiv, C1, C2);
1857 Constant* ConstantExpr::getFDiv(Constant* C1, Constant* C2) {
1858 return get(Instruction::FDiv, C1, C2);
1861 Constant* ConstantExpr::getURem(Constant* C1, Constant* C2) {
1862 return get(Instruction::URem, C1, C2);
1865 Constant* ConstantExpr::getSRem(Constant* C1, Constant* C2) {
1866 return get(Instruction::SRem, C1, C2);
1869 Constant* ConstantExpr::getFRem(Constant* C1, Constant* C2) {
1870 return get(Instruction::FRem, C1, C2);
1873 Constant* ConstantExpr::getAnd(Constant* C1, Constant* C2) {
1874 return get(Instruction::And, C1, C2);
1877 Constant* ConstantExpr::getOr(Constant* C1, Constant* C2) {
1878 return get(Instruction::Or, C1, C2);
1881 Constant* ConstantExpr::getXor(Constant* C1, Constant* C2) {
1882 return get(Instruction::Xor, C1, C2);
1885 Constant* ConstantExpr::getShl(Constant* C1, Constant* C2) {
1886 return get(Instruction::Shl, C1, C2);
1889 Constant* ConstantExpr::getLShr(Constant* C1, Constant* C2) {
1890 return get(Instruction::LShr, C1, C2);
1893 Constant* ConstantExpr::getAShr(Constant* C1, Constant* C2) {
1894 return get(Instruction::AShr, C1, C2);
1897 // destroyConstant - Remove the constant from the constant table...
1899 void ConstantExpr::destroyConstant() {
1900 getRawType()->getContext().pImpl->ExprConstants.remove(this);
1901 destroyConstantImpl();
1904 const char *ConstantExpr::getOpcodeName() const {
1905 return Instruction::getOpcodeName(getOpcode());
1910 GetElementPtrConstantExpr::
1911 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
1913 : ConstantExpr(DestTy, Instruction::GetElementPtr,
1914 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
1915 - (IdxList.size()+1), IdxList.size()+1) {
1917 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
1918 OperandList[i+1] = IdxList[i];
1922 //===----------------------------------------------------------------------===//
1923 // replaceUsesOfWithOnConstant implementations
1925 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
1926 /// 'From' to be uses of 'To'. This must update the uniquing data structures
1929 /// Note that we intentionally replace all uses of From with To here. Consider
1930 /// a large array that uses 'From' 1000 times. By handling this case all here,
1931 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
1932 /// single invocation handles all 1000 uses. Handling them one at a time would
1933 /// work, but would be really slow because it would have to unique each updated
1936 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1938 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1939 Constant *ToC = cast<Constant>(To);
1941 LLVMContextImpl *pImpl = getRawType()->getContext().pImpl;
1943 std::pair<LLVMContextImpl::ArrayConstantsTy::MapKey, ConstantArray*> Lookup;
1944 Lookup.first.first = cast<ArrayType>(getRawType());
1945 Lookup.second = this;
1947 std::vector<Constant*> &Values = Lookup.first.second;
1948 Values.reserve(getNumOperands()); // Build replacement array.
1950 // Fill values with the modified operands of the constant array. Also,
1951 // compute whether this turns into an all-zeros array.
1952 bool isAllZeros = false;
1953 unsigned NumUpdated = 0;
1954 if (!ToC->isNullValue()) {
1955 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1956 Constant *Val = cast<Constant>(O->get());
1961 Values.push_back(Val);
1965 for (Use *O = OperandList, *E = OperandList+getNumOperands();O != E; ++O) {
1966 Constant *Val = cast<Constant>(O->get());
1971 Values.push_back(Val);
1972 if (isAllZeros) isAllZeros = Val->isNullValue();
1976 Constant *Replacement = 0;
1978 Replacement = ConstantAggregateZero::get(getRawType());
1980 // Check to see if we have this array type already.
1982 LLVMContextImpl::ArrayConstantsTy::MapTy::iterator I =
1983 pImpl->ArrayConstants.InsertOrGetItem(Lookup, Exists);
1986 Replacement = I->second;
1988 // Okay, the new shape doesn't exist in the system yet. Instead of
1989 // creating a new constant array, inserting it, replaceallusesof'ing the
1990 // old with the new, then deleting the old... just update the current one
1992 pImpl->ArrayConstants.MoveConstantToNewSlot(this, I);
1994 // Update to the new value. Optimize for the case when we have a single
1995 // operand that we're changing, but handle bulk updates efficiently.
1996 if (NumUpdated == 1) {
1997 unsigned OperandToUpdate = U - OperandList;
1998 assert(getOperand(OperandToUpdate) == From &&
1999 "ReplaceAllUsesWith broken!");
2000 setOperand(OperandToUpdate, ToC);
2002 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2003 if (getOperand(i) == From)
2010 // Otherwise, I do need to replace this with an existing value.
2011 assert(Replacement != this && "I didn't contain From!");
2013 // Everyone using this now uses the replacement.
2014 uncheckedReplaceAllUsesWith(Replacement);
2016 // Delete the old constant!
2020 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2022 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2023 Constant *ToC = cast<Constant>(To);
2025 unsigned OperandToUpdate = U-OperandList;
2026 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2028 std::pair<LLVMContextImpl::StructConstantsTy::MapKey, ConstantStruct*> Lookup;
2029 Lookup.first.first = cast<StructType>(getRawType());
2030 Lookup.second = this;
2031 std::vector<Constant*> &Values = Lookup.first.second;
2032 Values.reserve(getNumOperands()); // Build replacement struct.
2035 // Fill values with the modified operands of the constant struct. Also,
2036 // compute whether this turns into an all-zeros struct.
2037 bool isAllZeros = false;
2038 if (!ToC->isNullValue()) {
2039 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
2040 Values.push_back(cast<Constant>(O->get()));
2043 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2044 Constant *Val = cast<Constant>(O->get());
2045 Values.push_back(Val);
2046 if (isAllZeros) isAllZeros = Val->isNullValue();
2049 Values[OperandToUpdate] = ToC;
2051 LLVMContextImpl *pImpl = getRawType()->getContext().pImpl;
2053 Constant *Replacement = 0;
2055 Replacement = ConstantAggregateZero::get(getRawType());
2057 // Check to see if we have this struct type already.
2059 LLVMContextImpl::StructConstantsTy::MapTy::iterator I =
2060 pImpl->StructConstants.InsertOrGetItem(Lookup, Exists);
2063 Replacement = I->second;
2065 // Okay, the new shape doesn't exist in the system yet. Instead of
2066 // creating a new constant struct, inserting it, replaceallusesof'ing the
2067 // old with the new, then deleting the old... just update the current one
2069 pImpl->StructConstants.MoveConstantToNewSlot(this, I);
2071 // Update to the new value.
2072 setOperand(OperandToUpdate, ToC);
2077 assert(Replacement != this && "I didn't contain From!");
2079 // Everyone using this now uses the replacement.
2080 uncheckedReplaceAllUsesWith(Replacement);
2082 // Delete the old constant!
2086 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2088 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2090 std::vector<Constant*> Values;
2091 Values.reserve(getNumOperands()); // Build replacement array...
2092 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2093 Constant *Val = getOperand(i);
2094 if (Val == From) Val = cast<Constant>(To);
2095 Values.push_back(Val);
2098 Constant *Replacement = get(cast<VectorType>(getRawType()), Values);
2099 assert(Replacement != this && "I didn't contain From!");
2101 // Everyone using this now uses the replacement.
2102 uncheckedReplaceAllUsesWith(Replacement);
2104 // Delete the old constant!
2108 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2110 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2111 Constant *To = cast<Constant>(ToV);
2113 Constant *Replacement = 0;
2114 if (getOpcode() == Instruction::GetElementPtr) {
2115 SmallVector<Constant*, 8> Indices;
2116 Constant *Pointer = getOperand(0);
2117 Indices.reserve(getNumOperands()-1);
2118 if (Pointer == From) Pointer = To;
2120 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2121 Constant *Val = getOperand(i);
2122 if (Val == From) Val = To;
2123 Indices.push_back(Val);
2125 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2126 &Indices[0], Indices.size());
2127 } else if (getOpcode() == Instruction::ExtractValue) {
2128 Constant *Agg = getOperand(0);
2129 if (Agg == From) Agg = To;
2131 const SmallVector<unsigned, 4> &Indices = getIndices();
2132 Replacement = ConstantExpr::getExtractValue(Agg,
2133 &Indices[0], Indices.size());
2134 } else if (getOpcode() == Instruction::InsertValue) {
2135 Constant *Agg = getOperand(0);
2136 Constant *Val = getOperand(1);
2137 if (Agg == From) Agg = To;
2138 if (Val == From) Val = To;
2140 const SmallVector<unsigned, 4> &Indices = getIndices();
2141 Replacement = ConstantExpr::getInsertValue(Agg, Val,
2142 &Indices[0], Indices.size());
2143 } else if (isCast()) {
2144 assert(getOperand(0) == From && "Cast only has one use!");
2145 Replacement = ConstantExpr::getCast(getOpcode(), To, getRawType());
2146 } else if (getOpcode() == Instruction::Select) {
2147 Constant *C1 = getOperand(0);
2148 Constant *C2 = getOperand(1);
2149 Constant *C3 = getOperand(2);
2150 if (C1 == From) C1 = To;
2151 if (C2 == From) C2 = To;
2152 if (C3 == From) C3 = To;
2153 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2154 } else if (getOpcode() == Instruction::ExtractElement) {
2155 Constant *C1 = getOperand(0);
2156 Constant *C2 = getOperand(1);
2157 if (C1 == From) C1 = To;
2158 if (C2 == From) C2 = To;
2159 Replacement = ConstantExpr::getExtractElement(C1, C2);
2160 } else if (getOpcode() == Instruction::InsertElement) {
2161 Constant *C1 = getOperand(0);
2162 Constant *C2 = getOperand(1);
2163 Constant *C3 = getOperand(1);
2164 if (C1 == From) C1 = To;
2165 if (C2 == From) C2 = To;
2166 if (C3 == From) C3 = To;
2167 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2168 } else if (getOpcode() == Instruction::ShuffleVector) {
2169 Constant *C1 = getOperand(0);
2170 Constant *C2 = getOperand(1);
2171 Constant *C3 = getOperand(2);
2172 if (C1 == From) C1 = To;
2173 if (C2 == From) C2 = To;
2174 if (C3 == From) C3 = To;
2175 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2176 } else if (isCompare()) {
2177 Constant *C1 = getOperand(0);
2178 Constant *C2 = getOperand(1);
2179 if (C1 == From) C1 = To;
2180 if (C2 == From) C2 = To;
2181 if (getOpcode() == Instruction::ICmp)
2182 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2184 assert(getOpcode() == Instruction::FCmp);
2185 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2187 } else if (getNumOperands() == 2) {
2188 Constant *C1 = getOperand(0);
2189 Constant *C2 = getOperand(1);
2190 if (C1 == From) C1 = To;
2191 if (C2 == From) C2 = To;
2192 Replacement = ConstantExpr::get(getOpcode(), C1, C2, SubclassOptionalData);
2194 llvm_unreachable("Unknown ConstantExpr type!");
2198 assert(Replacement != this && "I didn't contain From!");
2200 // Everyone using this now uses the replacement.
2201 uncheckedReplaceAllUsesWith(Replacement);
2203 // Delete the old constant!