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 (use_const_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(isa<VectorType>(getType()) && "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 return pImpl->TheTrueVal;
271 return (pImpl->TheTrueVal =
272 ConstantInt::get(IntegerType::get(Context, 1), 1));
275 ConstantInt* ConstantInt::getFalse(LLVMContext &Context) {
276 LLVMContextImpl *pImpl = Context.pImpl;
277 if (pImpl->TheFalseVal)
278 return pImpl->TheFalseVal;
280 return (pImpl->TheFalseVal =
281 ConstantInt::get(IntegerType::get(Context, 1), 0));
285 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
286 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
287 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
288 // compare APInt's of different widths, which would violate an APInt class
289 // invariant which generates an assertion.
290 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt& V) {
291 // Get the corresponding integer type for the bit width of the value.
292 const IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
293 // get an existing value or the insertion position
294 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
295 ConstantInt *&Slot = Context.pImpl->IntConstants[Key];
296 if (!Slot) Slot = new ConstantInt(ITy, V);
300 Constant* ConstantInt::get(const Type* Ty, uint64_t V, bool isSigned) {
301 Constant *C = get(cast<IntegerType>(Ty->getScalarType()),
304 // For vectors, broadcast the value.
305 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
306 return ConstantVector::get(
307 std::vector<Constant *>(VTy->getNumElements(), C));
312 ConstantInt* ConstantInt::get(const IntegerType* Ty, uint64_t V,
314 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
317 ConstantInt* ConstantInt::getSigned(const IntegerType* Ty, int64_t V) {
318 return get(Ty, V, true);
321 Constant *ConstantInt::getSigned(const Type *Ty, int64_t V) {
322 return get(Ty, V, true);
325 Constant* ConstantInt::get(const Type* Ty, const APInt& V) {
326 ConstantInt *C = get(Ty->getContext(), V);
327 assert(C->getType() == Ty->getScalarType() &&
328 "ConstantInt type doesn't match the type implied by its value!");
330 // For vectors, broadcast the value.
331 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
332 return ConstantVector::get(
333 std::vector<Constant *>(VTy->getNumElements(), C));
338 ConstantInt* ConstantInt::get(const IntegerType* Ty, StringRef Str,
340 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
343 //===----------------------------------------------------------------------===//
345 //===----------------------------------------------------------------------===//
347 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
349 return &APFloat::IEEEsingle;
350 if (Ty->isDoubleTy())
351 return &APFloat::IEEEdouble;
352 if (Ty->isX86_FP80Ty())
353 return &APFloat::x87DoubleExtended;
354 else if (Ty->isFP128Ty())
355 return &APFloat::IEEEquad;
357 assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
358 return &APFloat::PPCDoubleDouble;
361 /// get() - This returns a constant fp for the specified value in the
362 /// specified type. This should only be used for simple constant values like
363 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
364 Constant* ConstantFP::get(const Type* Ty, double V) {
365 LLVMContext &Context = Ty->getContext();
369 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
370 APFloat::rmNearestTiesToEven, &ignored);
371 Constant *C = get(Context, FV);
373 // For vectors, broadcast the value.
374 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
375 return ConstantVector::get(
376 std::vector<Constant *>(VTy->getNumElements(), C));
382 Constant* ConstantFP::get(const Type* Ty, StringRef Str) {
383 LLVMContext &Context = Ty->getContext();
385 APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
386 Constant *C = get(Context, FV);
388 // For vectors, broadcast the value.
389 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
390 return ConstantVector::get(
391 std::vector<Constant *>(VTy->getNumElements(), C));
397 ConstantFP* ConstantFP::getNegativeZero(const Type* Ty) {
398 LLVMContext &Context = Ty->getContext();
399 APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
401 return get(Context, apf);
405 Constant* ConstantFP::getZeroValueForNegation(const Type* Ty) {
406 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
407 if (PTy->getElementType()->isFloatingPoint()) {
408 std::vector<Constant*> zeros(PTy->getNumElements(),
409 getNegativeZero(PTy->getElementType()));
410 return ConstantVector::get(PTy, zeros);
413 if (Ty->isFloatingPoint())
414 return getNegativeZero(Ty);
416 return Constant::getNullValue(Ty);
420 // ConstantFP accessors.
421 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
422 DenseMapAPFloatKeyInfo::KeyTy Key(V);
424 LLVMContextImpl* pImpl = Context.pImpl;
426 ConstantFP *&Slot = pImpl->FPConstants[Key];
430 if (&V.getSemantics() == &APFloat::IEEEsingle)
431 Ty = Type::getFloatTy(Context);
432 else if (&V.getSemantics() == &APFloat::IEEEdouble)
433 Ty = Type::getDoubleTy(Context);
434 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
435 Ty = Type::getX86_FP80Ty(Context);
436 else if (&V.getSemantics() == &APFloat::IEEEquad)
437 Ty = Type::getFP128Ty(Context);
439 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
440 "Unknown FP format");
441 Ty = Type::getPPC_FP128Ty(Context);
443 Slot = new ConstantFP(Ty, V);
449 ConstantFP *ConstantFP::getInfinity(const Type *Ty, bool Negative) {
450 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty);
451 return ConstantFP::get(Ty->getContext(),
452 APFloat::getInf(Semantics, Negative));
455 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
456 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
457 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
461 bool ConstantFP::isNullValue() const {
462 return Val.isZero() && !Val.isNegative();
465 bool ConstantFP::isExactlyValue(const APFloat& V) const {
466 return Val.bitwiseIsEqual(V);
469 //===----------------------------------------------------------------------===//
470 // ConstantXXX Classes
471 //===----------------------------------------------------------------------===//
474 ConstantArray::ConstantArray(const ArrayType *T,
475 const std::vector<Constant*> &V)
476 : Constant(T, ConstantArrayVal,
477 OperandTraits<ConstantArray>::op_end(this) - V.size(),
479 assert(V.size() == T->getNumElements() &&
480 "Invalid initializer vector for constant array");
481 Use *OL = OperandList;
482 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
485 assert(C->getType() == T->getElementType() &&
486 "Initializer for array element doesn't match array element type!");
491 Constant *ConstantArray::get(const ArrayType *Ty,
492 const std::vector<Constant*> &V) {
493 for (unsigned i = 0, e = V.size(); i != e; ++i) {
494 assert(V[i]->getType() == Ty->getElementType() &&
495 "Wrong type in array element initializer");
497 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
498 // If this is an all-zero array, return a ConstantAggregateZero object
501 if (!C->isNullValue())
502 return pImpl->ArrayConstants.getOrCreate(Ty, V);
504 for (unsigned i = 1, e = V.size(); i != e; ++i)
506 return pImpl->ArrayConstants.getOrCreate(Ty, V);
509 return ConstantAggregateZero::get(Ty);
513 Constant* ConstantArray::get(const ArrayType* T, Constant* const* Vals,
515 // FIXME: make this the primary ctor method.
516 return get(T, std::vector<Constant*>(Vals, Vals+NumVals));
519 /// ConstantArray::get(const string&) - Return an array that is initialized to
520 /// contain the specified string. If length is zero then a null terminator is
521 /// added to the specified string so that it may be used in a natural way.
522 /// Otherwise, the length parameter specifies how much of the string to use
523 /// and it won't be null terminated.
525 Constant* ConstantArray::get(LLVMContext &Context, StringRef Str,
527 std::vector<Constant*> ElementVals;
528 for (unsigned i = 0; i < Str.size(); ++i)
529 ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), Str[i]));
531 // Add a null terminator to the string...
533 ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), 0));
536 ArrayType *ATy = ArrayType::get(Type::getInt8Ty(Context), ElementVals.size());
537 return get(ATy, ElementVals);
542 ConstantStruct::ConstantStruct(const StructType *T,
543 const std::vector<Constant*> &V)
544 : Constant(T, ConstantStructVal,
545 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
547 assert(V.size() == T->getNumElements() &&
548 "Invalid initializer vector for constant structure");
549 Use *OL = OperandList;
550 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
553 assert(C->getType() == T->getElementType(I-V.begin()) &&
554 "Initializer for struct element doesn't match struct element type!");
559 // ConstantStruct accessors.
560 Constant* ConstantStruct::get(const StructType* T,
561 const std::vector<Constant*>& V) {
562 LLVMContextImpl* pImpl = T->getContext().pImpl;
564 // Create a ConstantAggregateZero value if all elements are zeros...
565 for (unsigned i = 0, e = V.size(); i != e; ++i)
566 if (!V[i]->isNullValue())
567 return pImpl->StructConstants.getOrCreate(T, V);
569 return ConstantAggregateZero::get(T);
572 Constant* ConstantStruct::get(LLVMContext &Context,
573 const std::vector<Constant*>& V, bool packed) {
574 std::vector<const Type*> StructEls;
575 StructEls.reserve(V.size());
576 for (unsigned i = 0, e = V.size(); i != e; ++i)
577 StructEls.push_back(V[i]->getType());
578 return get(StructType::get(Context, StructEls, packed), V);
581 Constant* ConstantStruct::get(LLVMContext &Context,
582 Constant* const *Vals, unsigned NumVals,
584 // FIXME: make this the primary ctor method.
585 return get(Context, std::vector<Constant*>(Vals, Vals+NumVals), Packed);
588 ConstantVector::ConstantVector(const VectorType *T,
589 const std::vector<Constant*> &V)
590 : Constant(T, ConstantVectorVal,
591 OperandTraits<ConstantVector>::op_end(this) - V.size(),
593 Use *OL = OperandList;
594 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
597 assert(C->getType() == T->getElementType() &&
598 "Initializer for vector element doesn't match vector element type!");
603 // ConstantVector accessors.
604 Constant* ConstantVector::get(const VectorType* T,
605 const std::vector<Constant*>& V) {
606 assert(!V.empty() && "Vectors can't be empty");
607 LLVMContext &Context = T->getContext();
608 LLVMContextImpl *pImpl = Context.pImpl;
610 // If this is an all-undef or alll-zero vector, return a
611 // ConstantAggregateZero or UndefValue.
613 bool isZero = C->isNullValue();
614 bool isUndef = isa<UndefValue>(C);
616 if (isZero || isUndef) {
617 for (unsigned i = 1, e = V.size(); i != e; ++i)
619 isZero = isUndef = false;
625 return ConstantAggregateZero::get(T);
627 return UndefValue::get(T);
629 return pImpl->VectorConstants.getOrCreate(T, V);
632 Constant* ConstantVector::get(const std::vector<Constant*>& V) {
633 assert(!V.empty() && "Cannot infer type if V is empty");
634 return get(VectorType::get(V.front()->getType(),V.size()), V);
637 Constant* ConstantVector::get(Constant* const* Vals, unsigned NumVals) {
638 // FIXME: make this the primary ctor method.
639 return get(std::vector<Constant*>(Vals, Vals+NumVals));
642 Constant* ConstantExpr::getNSWNeg(Constant* C) {
643 assert(C->getType()->isIntOrIntVector() &&
644 "Cannot NEG a nonintegral value!");
645 return getNSWSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
648 Constant* ConstantExpr::getNSWAdd(Constant* C1, Constant* C2) {
649 return getTy(C1->getType(), Instruction::Add, C1, C2,
650 OverflowingBinaryOperator::NoSignedWrap);
653 Constant* ConstantExpr::getNSWSub(Constant* C1, Constant* C2) {
654 return getTy(C1->getType(), Instruction::Sub, C1, C2,
655 OverflowingBinaryOperator::NoSignedWrap);
658 Constant* ConstantExpr::getNUWMul(Constant* C1, Constant* C2) {
659 return getTy(C1->getType(), Instruction::Mul, C1, C2,
660 OverflowingBinaryOperator::NoUnsignedWrap);
663 Constant* ConstantExpr::getNSWMul(Constant* C1, Constant* C2) {
664 return getTy(C1->getType(), Instruction::Mul, C1, C2,
665 OverflowingBinaryOperator::NoSignedWrap);
668 Constant* ConstantExpr::getExactSDiv(Constant* C1, Constant* C2) {
669 return getTy(C1->getType(), Instruction::SDiv, C1, C2,
670 SDivOperator::IsExact);
673 // Utility function for determining if a ConstantExpr is a CastOp or not. This
674 // can't be inline because we don't want to #include Instruction.h into
676 bool ConstantExpr::isCast() const {
677 return Instruction::isCast(getOpcode());
680 bool ConstantExpr::isCompare() const {
681 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
684 bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
685 if (getOpcode() != Instruction::GetElementPtr) return false;
687 gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
688 User::const_op_iterator OI = next(this->op_begin());
690 // Skip the first index, as it has no static limit.
694 // The remaining indices must be compile-time known integers within the
695 // bounds of the corresponding notional static array types.
696 for (; GEPI != E; ++GEPI, ++OI) {
697 ConstantInt *CI = dyn_cast<ConstantInt>(*OI);
698 if (!CI) return false;
699 if (const ArrayType *ATy = dyn_cast<ArrayType>(*GEPI))
700 if (CI->getValue().getActiveBits() > 64 ||
701 CI->getZExtValue() >= ATy->getNumElements())
705 // All the indices checked out.
709 bool ConstantExpr::hasIndices() const {
710 return getOpcode() == Instruction::ExtractValue ||
711 getOpcode() == Instruction::InsertValue;
714 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
715 if (const ExtractValueConstantExpr *EVCE =
716 dyn_cast<ExtractValueConstantExpr>(this))
717 return EVCE->Indices;
719 return cast<InsertValueConstantExpr>(this)->Indices;
722 unsigned ConstantExpr::getPredicate() const {
723 assert(getOpcode() == Instruction::FCmp ||
724 getOpcode() == Instruction::ICmp);
725 return ((const CompareConstantExpr*)this)->predicate;
728 /// getWithOperandReplaced - Return a constant expression identical to this
729 /// one, but with the specified operand set to the specified value.
731 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
732 assert(OpNo < getNumOperands() && "Operand num is out of range!");
733 assert(Op->getType() == getOperand(OpNo)->getType() &&
734 "Replacing operand with value of different type!");
735 if (getOperand(OpNo) == Op)
736 return const_cast<ConstantExpr*>(this);
738 Constant *Op0, *Op1, *Op2;
739 switch (getOpcode()) {
740 case Instruction::Trunc:
741 case Instruction::ZExt:
742 case Instruction::SExt:
743 case Instruction::FPTrunc:
744 case Instruction::FPExt:
745 case Instruction::UIToFP:
746 case Instruction::SIToFP:
747 case Instruction::FPToUI:
748 case Instruction::FPToSI:
749 case Instruction::PtrToInt:
750 case Instruction::IntToPtr:
751 case Instruction::BitCast:
752 return ConstantExpr::getCast(getOpcode(), Op, getType());
753 case Instruction::Select:
754 Op0 = (OpNo == 0) ? Op : getOperand(0);
755 Op1 = (OpNo == 1) ? Op : getOperand(1);
756 Op2 = (OpNo == 2) ? Op : getOperand(2);
757 return ConstantExpr::getSelect(Op0, Op1, Op2);
758 case Instruction::InsertElement:
759 Op0 = (OpNo == 0) ? Op : getOperand(0);
760 Op1 = (OpNo == 1) ? Op : getOperand(1);
761 Op2 = (OpNo == 2) ? Op : getOperand(2);
762 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
763 case Instruction::ExtractElement:
764 Op0 = (OpNo == 0) ? Op : getOperand(0);
765 Op1 = (OpNo == 1) ? Op : getOperand(1);
766 return ConstantExpr::getExtractElement(Op0, Op1);
767 case Instruction::ShuffleVector:
768 Op0 = (OpNo == 0) ? Op : getOperand(0);
769 Op1 = (OpNo == 1) ? Op : getOperand(1);
770 Op2 = (OpNo == 2) ? Op : getOperand(2);
771 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
772 case Instruction::GetElementPtr: {
773 SmallVector<Constant*, 8> Ops;
774 Ops.resize(getNumOperands()-1);
775 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
776 Ops[i-1] = getOperand(i);
778 return cast<GEPOperator>(this)->isInBounds() ?
779 ConstantExpr::getInBoundsGetElementPtr(Op, &Ops[0], Ops.size()) :
780 ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
782 return cast<GEPOperator>(this)->isInBounds() ?
783 ConstantExpr::getInBoundsGetElementPtr(getOperand(0), &Ops[0],Ops.size()):
784 ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
787 assert(getNumOperands() == 2 && "Must be binary operator?");
788 Op0 = (OpNo == 0) ? Op : getOperand(0);
789 Op1 = (OpNo == 1) ? Op : getOperand(1);
790 return ConstantExpr::get(getOpcode(), Op0, Op1, SubclassOptionalData);
794 /// getWithOperands - This returns the current constant expression with the
795 /// operands replaced with the specified values. The specified operands must
796 /// match count and type with the existing ones.
797 Constant *ConstantExpr::
798 getWithOperands(Constant* const *Ops, unsigned NumOps) const {
799 assert(NumOps == getNumOperands() && "Operand count mismatch!");
800 bool AnyChange = false;
801 for (unsigned i = 0; i != NumOps; ++i) {
802 assert(Ops[i]->getType() == getOperand(i)->getType() &&
803 "Operand type mismatch!");
804 AnyChange |= Ops[i] != getOperand(i);
806 if (!AnyChange) // No operands changed, return self.
807 return const_cast<ConstantExpr*>(this);
809 switch (getOpcode()) {
810 case Instruction::Trunc:
811 case Instruction::ZExt:
812 case Instruction::SExt:
813 case Instruction::FPTrunc:
814 case Instruction::FPExt:
815 case Instruction::UIToFP:
816 case Instruction::SIToFP:
817 case Instruction::FPToUI:
818 case Instruction::FPToSI:
819 case Instruction::PtrToInt:
820 case Instruction::IntToPtr:
821 case Instruction::BitCast:
822 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
823 case Instruction::Select:
824 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
825 case Instruction::InsertElement:
826 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
827 case Instruction::ExtractElement:
828 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
829 case Instruction::ShuffleVector:
830 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
831 case Instruction::GetElementPtr:
832 return cast<GEPOperator>(this)->isInBounds() ?
833 ConstantExpr::getInBoundsGetElementPtr(Ops[0], &Ops[1], NumOps-1) :
834 ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
835 case Instruction::ICmp:
836 case Instruction::FCmp:
837 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
839 assert(getNumOperands() == 2 && "Must be binary operator?");
840 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData);
845 //===----------------------------------------------------------------------===//
846 // isValueValidForType implementations
848 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
849 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
850 if (Ty == Type::getInt1Ty(Ty->getContext()))
851 return Val == 0 || Val == 1;
853 return true; // always true, has to fit in largest type
854 uint64_t Max = (1ll << NumBits) - 1;
858 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
859 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
860 if (Ty == Type::getInt1Ty(Ty->getContext()))
861 return Val == 0 || Val == 1 || Val == -1;
863 return true; // always true, has to fit in largest type
864 int64_t Min = -(1ll << (NumBits-1));
865 int64_t Max = (1ll << (NumBits-1)) - 1;
866 return (Val >= Min && Val <= Max);
869 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
870 // convert modifies in place, so make a copy.
871 APFloat Val2 = APFloat(Val);
873 switch (Ty->getTypeID()) {
875 return false; // These can't be represented as floating point!
877 // FIXME rounding mode needs to be more flexible
878 case Type::FloatTyID: {
879 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
881 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
884 case Type::DoubleTyID: {
885 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
886 &Val2.getSemantics() == &APFloat::IEEEdouble)
888 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
891 case Type::X86_FP80TyID:
892 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
893 &Val2.getSemantics() == &APFloat::IEEEdouble ||
894 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
895 case Type::FP128TyID:
896 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
897 &Val2.getSemantics() == &APFloat::IEEEdouble ||
898 &Val2.getSemantics() == &APFloat::IEEEquad;
899 case Type::PPC_FP128TyID:
900 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
901 &Val2.getSemantics() == &APFloat::IEEEdouble ||
902 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
906 //===----------------------------------------------------------------------===//
907 // Factory Function Implementation
909 ConstantAggregateZero* ConstantAggregateZero::get(const Type* Ty) {
910 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
911 "Cannot create an aggregate zero of non-aggregate type!");
913 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
914 return pImpl->AggZeroConstants.getOrCreate(Ty, 0);
917 /// destroyConstant - Remove the constant from the constant table...
919 void ConstantAggregateZero::destroyConstant() {
920 getType()->getContext().pImpl->AggZeroConstants.remove(this);
921 destroyConstantImpl();
924 /// destroyConstant - Remove the constant from the constant table...
926 void ConstantArray::destroyConstant() {
927 getType()->getContext().pImpl->ArrayConstants.remove(this);
928 destroyConstantImpl();
931 /// isString - This method returns true if the array is an array of i8, and
932 /// if the elements of the array are all ConstantInt's.
933 bool ConstantArray::isString() const {
934 // Check the element type for i8...
935 if (!getType()->getElementType()->isInteger(8))
937 // Check the elements to make sure they are all integers, not constant
939 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
940 if (!isa<ConstantInt>(getOperand(i)))
945 /// isCString - This method returns true if the array is a string (see
946 /// isString) and it ends in a null byte \\0 and does not contains any other
947 /// null bytes except its terminator.
948 bool ConstantArray::isCString() const {
949 // Check the element type for i8...
950 if (!getType()->getElementType()->isInteger(8))
953 // Last element must be a null.
954 if (!getOperand(getNumOperands()-1)->isNullValue())
956 // Other elements must be non-null integers.
957 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
958 if (!isa<ConstantInt>(getOperand(i)))
960 if (getOperand(i)->isNullValue())
967 /// getAsString - If the sub-element type of this array is i8
968 /// then this method converts the array to an std::string and returns it.
969 /// Otherwise, it asserts out.
971 std::string ConstantArray::getAsString() const {
972 assert(isString() && "Not a string!");
974 Result.reserve(getNumOperands());
975 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
976 Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
981 //---- ConstantStruct::get() implementation...
988 // destroyConstant - Remove the constant from the constant table...
990 void ConstantStruct::destroyConstant() {
991 getType()->getContext().pImpl->StructConstants.remove(this);
992 destroyConstantImpl();
995 // destroyConstant - Remove the constant from the constant table...
997 void ConstantVector::destroyConstant() {
998 getType()->getContext().pImpl->VectorConstants.remove(this);
999 destroyConstantImpl();
1002 /// This function will return true iff every element in this vector constant
1003 /// is set to all ones.
1004 /// @returns true iff this constant's emements are all set to all ones.
1005 /// @brief Determine if the value is all ones.
1006 bool ConstantVector::isAllOnesValue() const {
1007 // Check out first element.
1008 const Constant *Elt = getOperand(0);
1009 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1010 if (!CI || !CI->isAllOnesValue()) return false;
1011 // Then make sure all remaining elements point to the same value.
1012 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1013 if (getOperand(I) != Elt) return false;
1018 /// getSplatValue - If this is a splat constant, where all of the
1019 /// elements have the same value, return that value. Otherwise return null.
1020 Constant *ConstantVector::getSplatValue() {
1021 // Check out first element.
1022 Constant *Elt = getOperand(0);
1023 // Then make sure all remaining elements point to the same value.
1024 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1025 if (getOperand(I) != Elt) return 0;
1029 //---- ConstantPointerNull::get() implementation.
1032 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1033 return Ty->getContext().pImpl->NullPtrConstants.getOrCreate(Ty, 0);
1036 // destroyConstant - Remove the constant from the constant table...
1038 void ConstantPointerNull::destroyConstant() {
1039 getType()->getContext().pImpl->NullPtrConstants.remove(this);
1040 destroyConstantImpl();
1044 //---- UndefValue::get() implementation.
1047 UndefValue *UndefValue::get(const Type *Ty) {
1048 return Ty->getContext().pImpl->UndefValueConstants.getOrCreate(Ty, 0);
1051 // destroyConstant - Remove the constant from the constant table.
1053 void UndefValue::destroyConstant() {
1054 getType()->getContext().pImpl->UndefValueConstants.remove(this);
1055 destroyConstantImpl();
1058 //---- BlockAddress::get() implementation.
1061 BlockAddress *BlockAddress::get(BasicBlock *BB) {
1062 assert(BB->getParent() != 0 && "Block must have a parent");
1063 return get(BB->getParent(), BB);
1066 BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1068 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
1070 BA = new BlockAddress(F, BB);
1072 assert(BA->getFunction() == F && "Basic block moved between functions");
1076 BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1077 : Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1081 BB->AdjustBlockAddressRefCount(1);
1085 // destroyConstant - Remove the constant from the constant table.
1087 void BlockAddress::destroyConstant() {
1088 getFunction()->getType()->getContext().pImpl
1089 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
1090 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1091 destroyConstantImpl();
1094 void BlockAddress::replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U) {
1095 // This could be replacing either the Basic Block or the Function. In either
1096 // case, we have to remove the map entry.
1097 Function *NewF = getFunction();
1098 BasicBlock *NewBB = getBasicBlock();
1101 NewF = cast<Function>(To);
1103 NewBB = cast<BasicBlock>(To);
1105 // See if the 'new' entry already exists, if not, just update this in place
1106 // and return early.
1107 BlockAddress *&NewBA =
1108 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
1110 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1112 // Remove the old entry, this can't cause the map to rehash (just a
1113 // tombstone will get added).
1114 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1117 setOperand(0, NewF);
1118 setOperand(1, NewBB);
1119 getBasicBlock()->AdjustBlockAddressRefCount(1);
1123 // Otherwise, I do need to replace this with an existing value.
1124 assert(NewBA != this && "I didn't contain From!");
1126 // Everyone using this now uses the replacement.
1127 uncheckedReplaceAllUsesWith(NewBA);
1132 //---- ConstantExpr::get() implementations.
1135 /// This is a utility function to handle folding of casts and lookup of the
1136 /// cast in the ExprConstants map. It is used by the various get* methods below.
1137 static inline Constant *getFoldedCast(
1138 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1139 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1140 // Fold a few common cases
1141 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1144 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1146 // Look up the constant in the table first to ensure uniqueness
1147 std::vector<Constant*> argVec(1, C);
1148 ExprMapKeyType Key(opc, argVec);
1150 return pImpl->ExprConstants.getOrCreate(Ty, Key);
1153 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1154 Instruction::CastOps opc = Instruction::CastOps(oc);
1155 assert(Instruction::isCast(opc) && "opcode out of range");
1156 assert(C && Ty && "Null arguments to getCast");
1157 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
1161 llvm_unreachable("Invalid cast opcode");
1163 case Instruction::Trunc: return getTrunc(C, Ty);
1164 case Instruction::ZExt: return getZExt(C, Ty);
1165 case Instruction::SExt: return getSExt(C, Ty);
1166 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1167 case Instruction::FPExt: return getFPExtend(C, Ty);
1168 case Instruction::UIToFP: return getUIToFP(C, Ty);
1169 case Instruction::SIToFP: return getSIToFP(C, Ty);
1170 case Instruction::FPToUI: return getFPToUI(C, Ty);
1171 case Instruction::FPToSI: return getFPToSI(C, Ty);
1172 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1173 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1174 case Instruction::BitCast: return getBitCast(C, Ty);
1179 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1180 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1181 return getCast(Instruction::BitCast, C, Ty);
1182 return getCast(Instruction::ZExt, C, Ty);
1185 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1186 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1187 return getCast(Instruction::BitCast, C, Ty);
1188 return getCast(Instruction::SExt, C, Ty);
1191 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1192 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1193 return getCast(Instruction::BitCast, C, Ty);
1194 return getCast(Instruction::Trunc, C, Ty);
1197 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1198 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1199 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1201 if (Ty->isInteger())
1202 return getCast(Instruction::PtrToInt, S, Ty);
1203 return getCast(Instruction::BitCast, S, Ty);
1206 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1208 assert(C->getType()->isIntOrIntVector() &&
1209 Ty->isIntOrIntVector() && "Invalid cast");
1210 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1211 unsigned DstBits = Ty->getScalarSizeInBits();
1212 Instruction::CastOps opcode =
1213 (SrcBits == DstBits ? Instruction::BitCast :
1214 (SrcBits > DstBits ? Instruction::Trunc :
1215 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1216 return getCast(opcode, C, Ty);
1219 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1220 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1222 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1223 unsigned DstBits = Ty->getScalarSizeInBits();
1224 if (SrcBits == DstBits)
1225 return C; // Avoid a useless cast
1226 Instruction::CastOps opcode =
1227 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1228 return getCast(opcode, C, Ty);
1231 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1233 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1234 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1236 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1237 assert(C->getType()->isIntOrIntVector() && "Trunc operand must be integer");
1238 assert(Ty->isIntOrIntVector() && "Trunc produces only integral");
1239 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1240 "SrcTy must be larger than DestTy for Trunc!");
1242 return getFoldedCast(Instruction::Trunc, C, Ty);
1245 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1247 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1248 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1250 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1251 assert(C->getType()->isIntOrIntVector() && "SExt operand must be integral");
1252 assert(Ty->isIntOrIntVector() && "SExt produces only integer");
1253 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1254 "SrcTy must be smaller than DestTy for SExt!");
1256 return getFoldedCast(Instruction::SExt, C, Ty);
1259 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1261 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1262 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1264 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1265 assert(C->getType()->isIntOrIntVector() && "ZEXt operand must be integral");
1266 assert(Ty->isIntOrIntVector() && "ZExt produces only integer");
1267 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1268 "SrcTy must be smaller than DestTy for ZExt!");
1270 return getFoldedCast(Instruction::ZExt, C, Ty);
1273 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1275 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1276 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1278 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1279 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1280 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1281 "This is an illegal floating point truncation!");
1282 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1285 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1287 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1288 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1290 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1291 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1292 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1293 "This is an illegal floating point extension!");
1294 return getFoldedCast(Instruction::FPExt, C, Ty);
1297 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1299 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1300 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1302 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1303 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1304 "This is an illegal uint to floating point cast!");
1305 return getFoldedCast(Instruction::UIToFP, C, Ty);
1308 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1310 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1311 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1313 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1314 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1315 "This is an illegal sint to floating point cast!");
1316 return getFoldedCast(Instruction::SIToFP, C, Ty);
1319 Constant *ConstantExpr::getFPToUI(Constant *C, const 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()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1326 "This is an illegal floating point to uint cast!");
1327 return getFoldedCast(Instruction::FPToUI, C, Ty);
1330 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1332 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1333 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1335 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1336 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1337 "This is an illegal floating point to sint cast!");
1338 return getFoldedCast(Instruction::FPToSI, C, Ty);
1341 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1342 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1343 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1344 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1347 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1348 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1349 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1350 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1353 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1354 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
1355 "Invalid constantexpr bitcast!");
1357 // It is common to ask for a bitcast of a value to its own type, handle this
1359 if (C->getType() == DstTy) return C;
1361 return getFoldedCast(Instruction::BitCast, C, DstTy);
1364 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1365 Constant *C1, Constant *C2,
1367 // Check the operands for consistency first
1368 assert(Opcode >= Instruction::BinaryOpsBegin &&
1369 Opcode < Instruction::BinaryOpsEnd &&
1370 "Invalid opcode in binary constant expression");
1371 assert(C1->getType() == C2->getType() &&
1372 "Operand types in binary constant expression should match");
1374 if (ReqTy == C1->getType() || ReqTy == Type::getInt1Ty(ReqTy->getContext()))
1375 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1376 return FC; // Fold a few common cases...
1378 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1379 ExprMapKeyType Key(Opcode, argVec, 0, Flags);
1381 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1382 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1385 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1386 Constant *C1, Constant *C2) {
1387 switch (predicate) {
1388 default: llvm_unreachable("Invalid CmpInst predicate");
1389 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1390 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1391 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1392 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1393 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1394 case CmpInst::FCMP_TRUE:
1395 return getFCmp(predicate, C1, C2);
1397 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1398 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1399 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1400 case CmpInst::ICMP_SLE:
1401 return getICmp(predicate, C1, C2);
1405 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
1407 // API compatibility: Adjust integer opcodes to floating-point opcodes.
1408 if (C1->getType()->isFPOrFPVector()) {
1409 if (Opcode == Instruction::Add) Opcode = Instruction::FAdd;
1410 else if (Opcode == Instruction::Sub) Opcode = Instruction::FSub;
1411 else if (Opcode == Instruction::Mul) Opcode = Instruction::FMul;
1415 case Instruction::Add:
1416 case Instruction::Sub:
1417 case Instruction::Mul:
1418 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1419 assert(C1->getType()->isIntOrIntVector() &&
1420 "Tried to create an integer operation on a non-integer type!");
1422 case Instruction::FAdd:
1423 case Instruction::FSub:
1424 case Instruction::FMul:
1425 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1426 assert(C1->getType()->isFPOrFPVector() &&
1427 "Tried to create a floating-point operation on a "
1428 "non-floating-point type!");
1430 case Instruction::UDiv:
1431 case Instruction::SDiv:
1432 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1433 assert(C1->getType()->isIntOrIntVector() &&
1434 "Tried to create an arithmetic operation on a non-arithmetic type!");
1436 case Instruction::FDiv:
1437 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1438 assert(C1->getType()->isFPOrFPVector() &&
1439 "Tried to create an arithmetic operation on a non-arithmetic type!");
1441 case Instruction::URem:
1442 case Instruction::SRem:
1443 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1444 assert(C1->getType()->isIntOrIntVector() &&
1445 "Tried to create an arithmetic operation on a non-arithmetic type!");
1447 case Instruction::FRem:
1448 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1449 assert(C1->getType()->isFPOrFPVector() &&
1450 "Tried to create an arithmetic operation on a non-arithmetic type!");
1452 case Instruction::And:
1453 case Instruction::Or:
1454 case Instruction::Xor:
1455 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1456 assert(C1->getType()->isIntOrIntVector() &&
1457 "Tried to create a logical operation on a non-integral type!");
1459 case Instruction::Shl:
1460 case Instruction::LShr:
1461 case Instruction::AShr:
1462 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1463 assert(C1->getType()->isIntOrIntVector() &&
1464 "Tried to create a shift operation on a non-integer type!");
1471 return getTy(C1->getType(), Opcode, C1, C2, Flags);
1474 Constant* ConstantExpr::getSizeOf(const Type* Ty) {
1475 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1476 // Note that a non-inbounds gep is used, as null isn't within any object.
1477 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1478 Constant *GEP = getGetElementPtr(
1479 Constant::getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
1480 return getCast(Instruction::PtrToInt, GEP,
1481 Type::getInt64Ty(Ty->getContext()));
1484 Constant* ConstantExpr::getAlignOf(const Type* Ty) {
1485 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
1486 // Note that a non-inbounds gep is used, as null isn't within any object.
1487 const Type *AligningTy = StructType::get(Ty->getContext(),
1488 Type::getInt1Ty(Ty->getContext()), Ty, NULL);
1489 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo());
1490 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
1491 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1492 Constant *Indices[2] = { Zero, One };
1493 Constant *GEP = getGetElementPtr(NullPtr, Indices, 2);
1494 return getCast(Instruction::PtrToInt, GEP,
1495 Type::getInt64Ty(Ty->getContext()));
1498 Constant* ConstantExpr::getOffsetOf(const StructType* STy, unsigned FieldNo) {
1499 return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
1503 Constant* ConstantExpr::getOffsetOf(const Type* Ty, Constant *FieldNo) {
1504 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1505 // Note that a non-inbounds gep is used, as null isn't within any object.
1506 Constant *GEPIdx[] = {
1507 ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
1510 Constant *GEP = getGetElementPtr(
1511 Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx, 2);
1512 return getCast(Instruction::PtrToInt, GEP,
1513 Type::getInt64Ty(Ty->getContext()));
1516 Constant *ConstantExpr::getCompare(unsigned short pred,
1517 Constant *C1, Constant *C2) {
1518 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1519 return getCompareTy(pred, C1, C2);
1522 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1523 Constant *V1, Constant *V2) {
1524 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1526 if (ReqTy == V1->getType())
1527 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1528 return SC; // Fold common cases
1530 std::vector<Constant*> argVec(3, C);
1533 ExprMapKeyType Key(Instruction::Select, argVec);
1535 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1536 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1539 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1542 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
1544 cast<PointerType>(ReqTy)->getElementType() &&
1545 "GEP indices invalid!");
1547 if (Constant *FC = ConstantFoldGetElementPtr(C, /*inBounds=*/false,
1548 (Constant**)Idxs, NumIdx))
1549 return FC; // Fold a few common cases...
1551 assert(isa<PointerType>(C->getType()) &&
1552 "Non-pointer type for constant GetElementPtr expression");
1553 // Look up the constant in the table first to ensure uniqueness
1554 std::vector<Constant*> ArgVec;
1555 ArgVec.reserve(NumIdx+1);
1556 ArgVec.push_back(C);
1557 for (unsigned i = 0; i != NumIdx; ++i)
1558 ArgVec.push_back(cast<Constant>(Idxs[i]));
1559 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
1561 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1562 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1565 Constant *ConstantExpr::getInBoundsGetElementPtrTy(const Type *ReqTy,
1569 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
1571 cast<PointerType>(ReqTy)->getElementType() &&
1572 "GEP indices invalid!");
1574 if (Constant *FC = ConstantFoldGetElementPtr(C, /*inBounds=*/true,
1575 (Constant**)Idxs, NumIdx))
1576 return FC; // Fold a few common cases...
1578 assert(isa<PointerType>(C->getType()) &&
1579 "Non-pointer type for constant GetElementPtr expression");
1580 // Look up the constant in the table first to ensure uniqueness
1581 std::vector<Constant*> ArgVec;
1582 ArgVec.reserve(NumIdx+1);
1583 ArgVec.push_back(C);
1584 for (unsigned i = 0; i != NumIdx; ++i)
1585 ArgVec.push_back(cast<Constant>(Idxs[i]));
1586 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
1587 GEPOperator::IsInBounds);
1589 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1590 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1593 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1595 // Get the result type of the getelementptr!
1597 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
1598 assert(Ty && "GEP indices invalid!");
1599 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
1600 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
1603 Constant *ConstantExpr::getInBoundsGetElementPtr(Constant *C,
1606 // Get the result type of the getelementptr!
1608 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
1609 assert(Ty && "GEP indices invalid!");
1610 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
1611 return getInBoundsGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
1614 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1616 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1619 Constant *ConstantExpr::getInBoundsGetElementPtr(Constant *C,
1620 Constant* const *Idxs,
1622 return getInBoundsGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1626 ConstantExpr::getICmp(unsigned short pred, Constant *LHS, Constant *RHS) {
1627 assert(LHS->getType() == RHS->getType());
1628 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1629 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1631 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1632 return FC; // Fold a few common cases...
1634 // Look up the constant in the table first to ensure uniqueness
1635 std::vector<Constant*> ArgVec;
1636 ArgVec.push_back(LHS);
1637 ArgVec.push_back(RHS);
1638 // Get the key type with both the opcode and predicate
1639 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1641 const Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1642 if (const VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1643 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1645 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1646 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
1650 ConstantExpr::getFCmp(unsigned short pred, Constant *LHS, Constant *RHS) {
1651 assert(LHS->getType() == RHS->getType());
1652 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1654 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1655 return FC; // Fold a few common cases...
1657 // Look up the constant in the table first to ensure uniqueness
1658 std::vector<Constant*> ArgVec;
1659 ArgVec.push_back(LHS);
1660 ArgVec.push_back(RHS);
1661 // Get the key type with both the opcode and predicate
1662 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1664 const Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1665 if (const VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1666 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1668 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1669 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
1672 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1674 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1675 return FC; // Fold a few common cases.
1676 // Look up the constant in the table first to ensure uniqueness
1677 std::vector<Constant*> ArgVec(1, Val);
1678 ArgVec.push_back(Idx);
1679 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1681 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1682 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1685 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1686 assert(isa<VectorType>(Val->getType()) &&
1687 "Tried to create extractelement operation on non-vector type!");
1688 assert(Idx->getType()->isInteger(32) &&
1689 "Extractelement index must be i32 type!");
1690 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
1694 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1695 Constant *Elt, Constant *Idx) {
1696 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1697 return FC; // Fold a few common cases.
1698 // Look up the constant in the table first to ensure uniqueness
1699 std::vector<Constant*> ArgVec(1, Val);
1700 ArgVec.push_back(Elt);
1701 ArgVec.push_back(Idx);
1702 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1704 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1705 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1708 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1710 assert(isa<VectorType>(Val->getType()) &&
1711 "Tried to create insertelement operation on non-vector type!");
1712 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
1713 && "Insertelement types must match!");
1714 assert(Idx->getType()->isInteger(32) &&
1715 "Insertelement index must be i32 type!");
1716 return getInsertElementTy(Val->getType(), Val, Elt, Idx);
1719 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1720 Constant *V2, Constant *Mask) {
1721 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1722 return FC; // Fold a few common cases...
1723 // Look up the constant in the table first to ensure uniqueness
1724 std::vector<Constant*> ArgVec(1, V1);
1725 ArgVec.push_back(V2);
1726 ArgVec.push_back(Mask);
1727 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1729 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1730 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1733 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1735 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1736 "Invalid shuffle vector constant expr operands!");
1738 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
1739 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
1740 const Type *ShufTy = VectorType::get(EltTy, NElts);
1741 return getShuffleVectorTy(ShufTy, V1, V2, Mask);
1744 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
1746 const unsigned *Idxs, unsigned NumIdx) {
1747 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1748 Idxs+NumIdx) == Val->getType() &&
1749 "insertvalue indices invalid!");
1750 assert(Agg->getType() == ReqTy &&
1751 "insertvalue type invalid!");
1752 assert(Agg->getType()->isFirstClassType() &&
1753 "Non-first-class type for constant InsertValue expression");
1754 Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs, NumIdx);
1755 assert(FC && "InsertValue constant expr couldn't be folded!");
1759 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
1760 const unsigned *IdxList, unsigned NumIdx) {
1761 assert(Agg->getType()->isFirstClassType() &&
1762 "Tried to create insertelement operation on non-first-class type!");
1764 const Type *ReqTy = Agg->getType();
1767 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1769 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
1770 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
1773 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
1774 const unsigned *Idxs, unsigned NumIdx) {
1775 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1776 Idxs+NumIdx) == ReqTy &&
1777 "extractvalue indices invalid!");
1778 assert(Agg->getType()->isFirstClassType() &&
1779 "Non-first-class type for constant extractvalue expression");
1780 Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs, NumIdx);
1781 assert(FC && "ExtractValue constant expr couldn't be folded!");
1785 Constant *ConstantExpr::getExtractValue(Constant *Agg,
1786 const unsigned *IdxList, unsigned NumIdx) {
1787 assert(Agg->getType()->isFirstClassType() &&
1788 "Tried to create extractelement operation on non-first-class type!");
1791 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1792 assert(ReqTy && "extractvalue indices invalid!");
1793 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
1796 Constant* ConstantExpr::getNeg(Constant* C) {
1797 // API compatibility: Adjust integer opcodes to floating-point opcodes.
1798 if (C->getType()->isFPOrFPVector())
1800 assert(C->getType()->isIntOrIntVector() &&
1801 "Cannot NEG a nonintegral value!");
1802 return get(Instruction::Sub,
1803 ConstantFP::getZeroValueForNegation(C->getType()),
1807 Constant* ConstantExpr::getFNeg(Constant* C) {
1808 assert(C->getType()->isFPOrFPVector() &&
1809 "Cannot FNEG a non-floating-point value!");
1810 return get(Instruction::FSub,
1811 ConstantFP::getZeroValueForNegation(C->getType()),
1815 Constant* ConstantExpr::getNot(Constant* C) {
1816 assert(C->getType()->isIntOrIntVector() &&
1817 "Cannot NOT a nonintegral value!");
1818 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
1821 Constant* ConstantExpr::getAdd(Constant* C1, Constant* C2) {
1822 return get(Instruction::Add, C1, C2);
1825 Constant* ConstantExpr::getFAdd(Constant* C1, Constant* C2) {
1826 return get(Instruction::FAdd, C1, C2);
1829 Constant* ConstantExpr::getSub(Constant* C1, Constant* C2) {
1830 return get(Instruction::Sub, C1, C2);
1833 Constant* ConstantExpr::getFSub(Constant* C1, Constant* C2) {
1834 return get(Instruction::FSub, C1, C2);
1837 Constant* ConstantExpr::getMul(Constant* C1, Constant* C2) {
1838 return get(Instruction::Mul, C1, C2);
1841 Constant* ConstantExpr::getFMul(Constant* C1, Constant* C2) {
1842 return get(Instruction::FMul, C1, C2);
1845 Constant* ConstantExpr::getUDiv(Constant* C1, Constant* C2) {
1846 return get(Instruction::UDiv, C1, C2);
1849 Constant* ConstantExpr::getSDiv(Constant* C1, Constant* C2) {
1850 return get(Instruction::SDiv, C1, C2);
1853 Constant* ConstantExpr::getFDiv(Constant* C1, Constant* C2) {
1854 return get(Instruction::FDiv, C1, C2);
1857 Constant* ConstantExpr::getURem(Constant* C1, Constant* C2) {
1858 return get(Instruction::URem, C1, C2);
1861 Constant* ConstantExpr::getSRem(Constant* C1, Constant* C2) {
1862 return get(Instruction::SRem, C1, C2);
1865 Constant* ConstantExpr::getFRem(Constant* C1, Constant* C2) {
1866 return get(Instruction::FRem, C1, C2);
1869 Constant* ConstantExpr::getAnd(Constant* C1, Constant* C2) {
1870 return get(Instruction::And, C1, C2);
1873 Constant* ConstantExpr::getOr(Constant* C1, Constant* C2) {
1874 return get(Instruction::Or, C1, C2);
1877 Constant* ConstantExpr::getXor(Constant* C1, Constant* C2) {
1878 return get(Instruction::Xor, C1, C2);
1881 Constant* ConstantExpr::getShl(Constant* C1, Constant* C2) {
1882 return get(Instruction::Shl, C1, C2);
1885 Constant* ConstantExpr::getLShr(Constant* C1, Constant* C2) {
1886 return get(Instruction::LShr, C1, C2);
1889 Constant* ConstantExpr::getAShr(Constant* C1, Constant* C2) {
1890 return get(Instruction::AShr, C1, C2);
1893 // destroyConstant - Remove the constant from the constant table...
1895 void ConstantExpr::destroyConstant() {
1896 getType()->getContext().pImpl->ExprConstants.remove(this);
1897 destroyConstantImpl();
1900 const char *ConstantExpr::getOpcodeName() const {
1901 return Instruction::getOpcodeName(getOpcode());
1904 //===----------------------------------------------------------------------===//
1905 // replaceUsesOfWithOnConstant implementations
1907 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
1908 /// 'From' to be uses of 'To'. This must update the uniquing data structures
1911 /// Note that we intentionally replace all uses of From with To here. Consider
1912 /// a large array that uses 'From' 1000 times. By handling this case all here,
1913 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
1914 /// single invocation handles all 1000 uses. Handling them one at a time would
1915 /// work, but would be really slow because it would have to unique each updated
1918 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1920 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1921 Constant *ToC = cast<Constant>(To);
1923 LLVMContext &Context = getType()->getContext();
1924 LLVMContextImpl *pImpl = Context.pImpl;
1926 std::pair<LLVMContextImpl::ArrayConstantsTy::MapKey, ConstantArray*> Lookup;
1927 Lookup.first.first = getType();
1928 Lookup.second = this;
1930 std::vector<Constant*> &Values = Lookup.first.second;
1931 Values.reserve(getNumOperands()); // Build replacement array.
1933 // Fill values with the modified operands of the constant array. Also,
1934 // compute whether this turns into an all-zeros array.
1935 bool isAllZeros = false;
1936 unsigned NumUpdated = 0;
1937 if (!ToC->isNullValue()) {
1938 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1939 Constant *Val = cast<Constant>(O->get());
1944 Values.push_back(Val);
1948 for (Use *O = OperandList, *E = OperandList+getNumOperands();O != E; ++O) {
1949 Constant *Val = cast<Constant>(O->get());
1954 Values.push_back(Val);
1955 if (isAllZeros) isAllZeros = Val->isNullValue();
1959 Constant *Replacement = 0;
1961 Replacement = ConstantAggregateZero::get(getType());
1963 // Check to see if we have this array type already.
1965 LLVMContextImpl::ArrayConstantsTy::MapTy::iterator I =
1966 pImpl->ArrayConstants.InsertOrGetItem(Lookup, Exists);
1969 Replacement = I->second;
1971 // Okay, the new shape doesn't exist in the system yet. Instead of
1972 // creating a new constant array, inserting it, replaceallusesof'ing the
1973 // old with the new, then deleting the old... just update the current one
1975 pImpl->ArrayConstants.MoveConstantToNewSlot(this, I);
1977 // Update to the new value. Optimize for the case when we have a single
1978 // operand that we're changing, but handle bulk updates efficiently.
1979 if (NumUpdated == 1) {
1980 unsigned OperandToUpdate = U - OperandList;
1981 assert(getOperand(OperandToUpdate) == From &&
1982 "ReplaceAllUsesWith broken!");
1983 setOperand(OperandToUpdate, ToC);
1985 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1986 if (getOperand(i) == From)
1993 // Otherwise, I do need to replace this with an existing value.
1994 assert(Replacement != this && "I didn't contain From!");
1996 // Everyone using this now uses the replacement.
1997 uncheckedReplaceAllUsesWith(Replacement);
1999 // Delete the old constant!
2003 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2005 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2006 Constant *ToC = cast<Constant>(To);
2008 unsigned OperandToUpdate = U-OperandList;
2009 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2011 std::pair<LLVMContextImpl::StructConstantsTy::MapKey, ConstantStruct*> Lookup;
2012 Lookup.first.first = getType();
2013 Lookup.second = this;
2014 std::vector<Constant*> &Values = Lookup.first.second;
2015 Values.reserve(getNumOperands()); // Build replacement struct.
2018 // Fill values with the modified operands of the constant struct. Also,
2019 // compute whether this turns into an all-zeros struct.
2020 bool isAllZeros = false;
2021 if (!ToC->isNullValue()) {
2022 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
2023 Values.push_back(cast<Constant>(O->get()));
2026 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2027 Constant *Val = cast<Constant>(O->get());
2028 Values.push_back(Val);
2029 if (isAllZeros) isAllZeros = Val->isNullValue();
2032 Values[OperandToUpdate] = ToC;
2034 LLVMContext &Context = getType()->getContext();
2035 LLVMContextImpl *pImpl = Context.pImpl;
2037 Constant *Replacement = 0;
2039 Replacement = ConstantAggregateZero::get(getType());
2041 // Check to see if we have this array type already.
2043 LLVMContextImpl::StructConstantsTy::MapTy::iterator I =
2044 pImpl->StructConstants.InsertOrGetItem(Lookup, Exists);
2047 Replacement = I->second;
2049 // Okay, the new shape doesn't exist in the system yet. Instead of
2050 // creating a new constant struct, inserting it, replaceallusesof'ing the
2051 // old with the new, then deleting the old... just update the current one
2053 pImpl->StructConstants.MoveConstantToNewSlot(this, I);
2055 // Update to the new value.
2056 setOperand(OperandToUpdate, ToC);
2061 assert(Replacement != this && "I didn't contain From!");
2063 // Everyone using this now uses the replacement.
2064 uncheckedReplaceAllUsesWith(Replacement);
2066 // Delete the old constant!
2070 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2072 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2074 std::vector<Constant*> Values;
2075 Values.reserve(getNumOperands()); // Build replacement array...
2076 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2077 Constant *Val = getOperand(i);
2078 if (Val == From) Val = cast<Constant>(To);
2079 Values.push_back(Val);
2082 Constant *Replacement = get(getType(), Values);
2083 assert(Replacement != this && "I didn't contain From!");
2085 // Everyone using this now uses the replacement.
2086 uncheckedReplaceAllUsesWith(Replacement);
2088 // Delete the old constant!
2092 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2094 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2095 Constant *To = cast<Constant>(ToV);
2097 Constant *Replacement = 0;
2098 if (getOpcode() == Instruction::GetElementPtr) {
2099 SmallVector<Constant*, 8> Indices;
2100 Constant *Pointer = getOperand(0);
2101 Indices.reserve(getNumOperands()-1);
2102 if (Pointer == From) Pointer = To;
2104 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2105 Constant *Val = getOperand(i);
2106 if (Val == From) Val = To;
2107 Indices.push_back(Val);
2109 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2110 &Indices[0], Indices.size());
2111 } else if (getOpcode() == Instruction::ExtractValue) {
2112 Constant *Agg = getOperand(0);
2113 if (Agg == From) Agg = To;
2115 const SmallVector<unsigned, 4> &Indices = getIndices();
2116 Replacement = ConstantExpr::getExtractValue(Agg,
2117 &Indices[0], Indices.size());
2118 } else if (getOpcode() == Instruction::InsertValue) {
2119 Constant *Agg = getOperand(0);
2120 Constant *Val = getOperand(1);
2121 if (Agg == From) Agg = To;
2122 if (Val == From) Val = To;
2124 const SmallVector<unsigned, 4> &Indices = getIndices();
2125 Replacement = ConstantExpr::getInsertValue(Agg, Val,
2126 &Indices[0], Indices.size());
2127 } else if (isCast()) {
2128 assert(getOperand(0) == From && "Cast only has one use!");
2129 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2130 } else if (getOpcode() == Instruction::Select) {
2131 Constant *C1 = getOperand(0);
2132 Constant *C2 = getOperand(1);
2133 Constant *C3 = getOperand(2);
2134 if (C1 == From) C1 = To;
2135 if (C2 == From) C2 = To;
2136 if (C3 == From) C3 = To;
2137 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2138 } else if (getOpcode() == Instruction::ExtractElement) {
2139 Constant *C1 = getOperand(0);
2140 Constant *C2 = getOperand(1);
2141 if (C1 == From) C1 = To;
2142 if (C2 == From) C2 = To;
2143 Replacement = ConstantExpr::getExtractElement(C1, C2);
2144 } else if (getOpcode() == Instruction::InsertElement) {
2145 Constant *C1 = getOperand(0);
2146 Constant *C2 = getOperand(1);
2147 Constant *C3 = getOperand(1);
2148 if (C1 == From) C1 = To;
2149 if (C2 == From) C2 = To;
2150 if (C3 == From) C3 = To;
2151 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2152 } else if (getOpcode() == Instruction::ShuffleVector) {
2153 Constant *C1 = getOperand(0);
2154 Constant *C2 = getOperand(1);
2155 Constant *C3 = getOperand(2);
2156 if (C1 == From) C1 = To;
2157 if (C2 == From) C2 = To;
2158 if (C3 == From) C3 = To;
2159 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2160 } else if (isCompare()) {
2161 Constant *C1 = getOperand(0);
2162 Constant *C2 = getOperand(1);
2163 if (C1 == From) C1 = To;
2164 if (C2 == From) C2 = To;
2165 if (getOpcode() == Instruction::ICmp)
2166 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2168 assert(getOpcode() == Instruction::FCmp);
2169 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2171 } else if (getNumOperands() == 2) {
2172 Constant *C1 = getOperand(0);
2173 Constant *C2 = getOperand(1);
2174 if (C1 == From) C1 = To;
2175 if (C2 == From) C2 = To;
2176 Replacement = ConstantExpr::get(getOpcode(), C1, C2, SubclassOptionalData);
2178 llvm_unreachable("Unknown ConstantExpr type!");
2182 assert(Replacement != this && "I didn't contain From!");
2184 // Everyone using this now uses the replacement.
2185 uncheckedReplaceAllUsesWith(Replacement);
2187 // Delete the old constant!