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/System/Mutex.h"
33 #include "llvm/System/RWMutex.h"
34 #include "llvm/System/Threading.h"
35 #include "llvm/ADT/DenseMap.h"
36 #include "llvm/ADT/SmallVector.h"
41 //===----------------------------------------------------------------------===//
43 //===----------------------------------------------------------------------===//
45 // Constructor to create a '0' constant of arbitrary type...
46 static const uint64_t zero[2] = {0, 0};
47 Constant* Constant::getNullValue(const Type* Ty) {
48 switch (Ty->getTypeID()) {
49 case Type::IntegerTyID:
50 return ConstantInt::get(Ty, 0);
52 return ConstantFP::get(Ty->getContext(), APFloat(APInt(32, 0)));
53 case Type::DoubleTyID:
54 return ConstantFP::get(Ty->getContext(), APFloat(APInt(64, 0)));
55 case Type::X86_FP80TyID:
56 return ConstantFP::get(Ty->getContext(), APFloat(APInt(80, 2, zero)));
58 return ConstantFP::get(Ty->getContext(),
59 APFloat(APInt(128, 2, zero), true));
60 case Type::PPC_FP128TyID:
61 return ConstantFP::get(Ty->getContext(), APFloat(APInt(128, 2, zero)));
62 case Type::PointerTyID:
63 return ConstantPointerNull::get(cast<PointerType>(Ty));
64 case Type::StructTyID:
66 case Type::VectorTyID:
67 return ConstantAggregateZero::get(Ty);
69 // Function, Label, or Opaque type?
70 assert(!"Cannot create a null constant of that type!");
75 Constant* Constant::getIntegerValue(const Type* Ty, const APInt &V) {
76 const Type *ScalarTy = Ty->getScalarType();
78 // Create the base integer constant.
79 Constant *C = ConstantInt::get(Ty->getContext(), V);
81 // Convert an integer to a pointer, if necessary.
82 if (const PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
83 C = ConstantExpr::getIntToPtr(C, PTy);
85 // Broadcast a scalar to a vector, if necessary.
86 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
87 C = ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
92 Constant* Constant::getAllOnesValue(const Type* Ty) {
93 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
94 return ConstantInt::get(Ty->getContext(),
95 APInt::getAllOnesValue(ITy->getBitWidth()));
97 std::vector<Constant*> Elts;
98 const VectorType* VTy = cast<VectorType>(Ty);
99 Elts.resize(VTy->getNumElements(), getAllOnesValue(VTy->getElementType()));
100 assert(Elts[0] && "Not a vector integer type!");
101 return cast<ConstantVector>(ConstantVector::get(Elts));
104 void Constant::destroyConstantImpl() {
105 // When a Constant is destroyed, there may be lingering
106 // references to the constant by other constants in the constant pool. These
107 // constants are implicitly dependent on the module that is being deleted,
108 // but they don't know that. Because we only find out when the CPV is
109 // deleted, we must now notify all of our users (that should only be
110 // Constants) that they are, in fact, invalid now and should be deleted.
112 while (!use_empty()) {
113 Value *V = use_back();
114 #ifndef NDEBUG // Only in -g mode...
115 if (!isa<Constant>(V)) {
116 errs() << "While deleting: " << *this
117 << "\n\nUse still stuck around after Def is destroyed: "
121 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
122 Constant *CV = cast<Constant>(V);
123 CV->destroyConstant();
125 // The constant should remove itself from our use list...
126 assert((use_empty() || use_back() != V) && "Constant not removed!");
129 // Value has no outstanding references it is safe to delete it now...
133 /// canTrap - Return true if evaluation of this constant could trap. This is
134 /// true for things like constant expressions that could divide by zero.
135 bool Constant::canTrap() const {
136 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
137 // The only thing that could possibly trap are constant exprs.
138 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
139 if (!CE) return false;
141 // ConstantExpr traps if any operands can trap.
142 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
143 if (getOperand(i)->canTrap())
146 // Otherwise, only specific operations can trap.
147 switch (CE->getOpcode()) {
150 case Instruction::UDiv:
151 case Instruction::SDiv:
152 case Instruction::FDiv:
153 case Instruction::URem:
154 case Instruction::SRem:
155 case Instruction::FRem:
156 // Div and rem can trap if the RHS is not known to be non-zero.
157 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
164 /// getRelocationInfo - This method classifies the entry according to
165 /// whether or not it may generate a relocation entry. This must be
166 /// conservative, so if it might codegen to a relocatable entry, it should say
167 /// so. The return values are:
169 /// NoRelocation: This constant pool entry is guaranteed to never have a
170 /// relocation applied to it (because it holds a simple constant like
172 /// LocalRelocation: This entry has relocations, but the entries are
173 /// guaranteed to be resolvable by the static linker, so the dynamic
174 /// linker will never see them.
175 /// GlobalRelocations: This entry may have arbitrary relocations.
177 /// FIXME: This really should not be in VMCore.
178 Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
179 if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
180 if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
181 return LocalRelocation; // Local to this file/library.
182 return GlobalRelocations; // Global reference.
185 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
186 return BA->getFunction()->getRelocationInfo();
188 PossibleRelocationsTy Result = NoRelocation;
189 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
190 Result = std::max(Result, getOperand(i)->getRelocationInfo());
196 /// getVectorElements - This method, which is only valid on constant of vector
197 /// type, returns the elements of the vector in the specified smallvector.
198 /// This handles breaking down a vector undef into undef elements, etc. For
199 /// constant exprs and other cases we can't handle, we return an empty vector.
200 void Constant::getVectorElements(LLVMContext &Context,
201 SmallVectorImpl<Constant*> &Elts) const {
202 assert(isa<VectorType>(getType()) && "Not a vector constant!");
204 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
205 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
206 Elts.push_back(CV->getOperand(i));
210 const VectorType *VT = cast<VectorType>(getType());
211 if (isa<ConstantAggregateZero>(this)) {
212 Elts.assign(VT->getNumElements(),
213 Constant::getNullValue(VT->getElementType()));
217 if (isa<UndefValue>(this)) {
218 Elts.assign(VT->getNumElements(), UndefValue::get(VT->getElementType()));
222 // Unknown type, must be constant expr etc.
227 //===----------------------------------------------------------------------===//
229 //===----------------------------------------------------------------------===//
231 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
232 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
233 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
236 ConstantInt* ConstantInt::getTrue(LLVMContext &Context) {
237 LLVMContextImpl *pImpl = Context.pImpl;
238 if (pImpl->TheTrueVal)
239 return pImpl->TheTrueVal;
241 return (pImpl->TheTrueVal =
242 ConstantInt::get(IntegerType::get(Context, 1), 1));
245 ConstantInt* ConstantInt::getFalse(LLVMContext &Context) {
246 LLVMContextImpl *pImpl = Context.pImpl;
247 if (pImpl->TheFalseVal)
248 return pImpl->TheFalseVal;
250 return (pImpl->TheFalseVal =
251 ConstantInt::get(IntegerType::get(Context, 1), 0));
255 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
256 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
257 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
258 // compare APInt's of different widths, which would violate an APInt class
259 // invariant which generates an assertion.
260 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt& V) {
261 // Get the corresponding integer type for the bit width of the value.
262 const IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
263 // get an existing value or the insertion position
264 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
265 ConstantInt *&Slot = Context.pImpl->IntConstants[Key];
266 if (!Slot) Slot = new ConstantInt(ITy, V);
270 Constant* ConstantInt::get(const Type* Ty, uint64_t V, bool isSigned) {
271 Constant *C = get(cast<IntegerType>(Ty->getScalarType()),
274 // For vectors, broadcast the value.
275 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
276 return ConstantVector::get(
277 std::vector<Constant *>(VTy->getNumElements(), C));
282 ConstantInt* ConstantInt::get(const IntegerType* Ty, uint64_t V,
284 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
287 ConstantInt* ConstantInt::getSigned(const IntegerType* Ty, int64_t V) {
288 return get(Ty, V, true);
291 Constant *ConstantInt::getSigned(const Type *Ty, int64_t V) {
292 return get(Ty, V, true);
295 Constant* ConstantInt::get(const Type* Ty, const APInt& V) {
296 ConstantInt *C = get(Ty->getContext(), V);
297 assert(C->getType() == Ty->getScalarType() &&
298 "ConstantInt type doesn't match the type implied by its value!");
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, const StringRef& Str,
310 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
313 //===----------------------------------------------------------------------===//
315 //===----------------------------------------------------------------------===//
317 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
319 return &APFloat::IEEEsingle;
320 if (Ty->isDoubleTy())
321 return &APFloat::IEEEdouble;
322 if (Ty->isX86_FP80Ty())
323 return &APFloat::x87DoubleExtended;
324 else if (Ty->isFP128Ty())
325 return &APFloat::IEEEquad;
327 assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
328 return &APFloat::PPCDoubleDouble;
331 /// get() - This returns a constant fp for the specified value in the
332 /// specified type. This should only be used for simple constant values like
333 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
334 Constant* ConstantFP::get(const Type* Ty, double V) {
335 LLVMContext &Context = Ty->getContext();
339 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
340 APFloat::rmNearestTiesToEven, &ignored);
341 Constant *C = get(Context, FV);
343 // For vectors, broadcast the value.
344 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
345 return ConstantVector::get(
346 std::vector<Constant *>(VTy->getNumElements(), C));
352 Constant* ConstantFP::get(const Type* Ty, const StringRef& Str) {
353 LLVMContext &Context = Ty->getContext();
355 APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
356 Constant *C = get(Context, FV);
358 // For vectors, broadcast the value.
359 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
360 return ConstantVector::get(
361 std::vector<Constant *>(VTy->getNumElements(), C));
367 ConstantFP* ConstantFP::getNegativeZero(const Type* Ty) {
368 LLVMContext &Context = Ty->getContext();
369 APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
371 return get(Context, apf);
375 Constant* ConstantFP::getZeroValueForNegation(const Type* Ty) {
376 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
377 if (PTy->getElementType()->isFloatingPoint()) {
378 std::vector<Constant*> zeros(PTy->getNumElements(),
379 getNegativeZero(PTy->getElementType()));
380 return ConstantVector::get(PTy, zeros);
383 if (Ty->isFloatingPoint())
384 return getNegativeZero(Ty);
386 return Constant::getNullValue(Ty);
390 // ConstantFP accessors.
391 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
392 DenseMapAPFloatKeyInfo::KeyTy Key(V);
394 LLVMContextImpl* pImpl = Context.pImpl;
396 ConstantFP *&Slot = pImpl->FPConstants[Key];
400 if (&V.getSemantics() == &APFloat::IEEEsingle)
401 Ty = Type::getFloatTy(Context);
402 else if (&V.getSemantics() == &APFloat::IEEEdouble)
403 Ty = Type::getDoubleTy(Context);
404 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
405 Ty = Type::getX86_FP80Ty(Context);
406 else if (&V.getSemantics() == &APFloat::IEEEquad)
407 Ty = Type::getFP128Ty(Context);
409 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
410 "Unknown FP format");
411 Ty = Type::getPPC_FP128Ty(Context);
413 Slot = new ConstantFP(Ty, V);
419 ConstantFP *ConstantFP::getInfinity(const Type *Ty, bool Negative) {
420 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty);
421 return ConstantFP::get(Ty->getContext(),
422 APFloat::getInf(Semantics, Negative));
425 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
426 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
427 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
431 bool ConstantFP::isNullValue() const {
432 return Val.isZero() && !Val.isNegative();
435 bool ConstantFP::isExactlyValue(const APFloat& V) const {
436 return Val.bitwiseIsEqual(V);
439 //===----------------------------------------------------------------------===//
440 // ConstantXXX Classes
441 //===----------------------------------------------------------------------===//
444 ConstantArray::ConstantArray(const ArrayType *T,
445 const std::vector<Constant*> &V)
446 : Constant(T, ConstantArrayVal,
447 OperandTraits<ConstantArray>::op_end(this) - V.size(),
449 assert(V.size() == T->getNumElements() &&
450 "Invalid initializer vector for constant array");
451 Use *OL = OperandList;
452 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
455 assert(C->getType() == T->getElementType() &&
456 "Initializer for array element doesn't match array element type!");
461 Constant *ConstantArray::get(const ArrayType *Ty,
462 const std::vector<Constant*> &V) {
463 for (unsigned i = 0, e = V.size(); i != e; ++i) {
464 assert(V[i]->getType() == Ty->getElementType() &&
465 "Wrong type in array element initializer");
467 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
468 // If this is an all-zero array, return a ConstantAggregateZero object
471 if (!C->isNullValue()) {
472 // Implicitly locked.
473 return pImpl->ArrayConstants.getOrCreate(Ty, V);
475 for (unsigned i = 1, e = V.size(); i != e; ++i)
477 // Implicitly locked.
478 return pImpl->ArrayConstants.getOrCreate(Ty, V);
482 return ConstantAggregateZero::get(Ty);
486 Constant* ConstantArray::get(const ArrayType* T, Constant* const* Vals,
488 // FIXME: make this the primary ctor method.
489 return get(T, std::vector<Constant*>(Vals, Vals+NumVals));
492 /// ConstantArray::get(const string&) - Return an array that is initialized to
493 /// contain the specified string. If length is zero then a null terminator is
494 /// added to the specified string so that it may be used in a natural way.
495 /// Otherwise, the length parameter specifies how much of the string to use
496 /// and it won't be null terminated.
498 Constant* ConstantArray::get(LLVMContext &Context, const StringRef &Str,
500 std::vector<Constant*> ElementVals;
501 for (unsigned i = 0; i < Str.size(); ++i)
502 ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), Str[i]));
504 // Add a null terminator to the string...
506 ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), 0));
509 ArrayType *ATy = ArrayType::get(Type::getInt8Ty(Context), ElementVals.size());
510 return get(ATy, ElementVals);
515 ConstantStruct::ConstantStruct(const StructType *T,
516 const std::vector<Constant*> &V)
517 : Constant(T, ConstantStructVal,
518 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
520 assert(V.size() == T->getNumElements() &&
521 "Invalid initializer vector for constant structure");
522 Use *OL = OperandList;
523 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
526 assert(C->getType() == T->getElementType(I-V.begin()) &&
527 "Initializer for struct element doesn't match struct element type!");
532 // ConstantStruct accessors.
533 Constant* ConstantStruct::get(const StructType* T,
534 const std::vector<Constant*>& V) {
535 LLVMContextImpl* pImpl = T->getContext().pImpl;
537 // Create a ConstantAggregateZero value if all elements are zeros...
538 for (unsigned i = 0, e = V.size(); i != e; ++i)
539 if (!V[i]->isNullValue())
540 // Implicitly locked.
541 return pImpl->StructConstants.getOrCreate(T, V);
543 return ConstantAggregateZero::get(T);
546 Constant* ConstantStruct::get(LLVMContext &Context,
547 const std::vector<Constant*>& V, bool packed) {
548 std::vector<const Type*> StructEls;
549 StructEls.reserve(V.size());
550 for (unsigned i = 0, e = V.size(); i != e; ++i)
551 StructEls.push_back(V[i]->getType());
552 return get(StructType::get(Context, StructEls, packed), V);
555 Constant* ConstantStruct::get(LLVMContext &Context,
556 Constant* const *Vals, unsigned NumVals,
558 // FIXME: make this the primary ctor method.
559 return get(Context, std::vector<Constant*>(Vals, Vals+NumVals), Packed);
562 ConstantVector::ConstantVector(const VectorType *T,
563 const std::vector<Constant*> &V)
564 : Constant(T, ConstantVectorVal,
565 OperandTraits<ConstantVector>::op_end(this) - V.size(),
567 Use *OL = OperandList;
568 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
571 assert(C->getType() == T->getElementType() &&
572 "Initializer for vector element doesn't match vector element type!");
577 // ConstantVector accessors.
578 Constant* ConstantVector::get(const VectorType* T,
579 const std::vector<Constant*>& V) {
580 assert(!V.empty() && "Vectors can't be empty");
581 LLVMContext &Context = T->getContext();
582 LLVMContextImpl *pImpl = Context.pImpl;
584 // If this is an all-undef or alll-zero vector, return a
585 // ConstantAggregateZero or UndefValue.
587 bool isZero = C->isNullValue();
588 bool isUndef = isa<UndefValue>(C);
590 if (isZero || isUndef) {
591 for (unsigned i = 1, e = V.size(); i != e; ++i)
593 isZero = isUndef = false;
599 return ConstantAggregateZero::get(T);
601 return UndefValue::get(T);
603 // Implicitly locked.
604 return pImpl->VectorConstants.getOrCreate(T, V);
607 Constant* ConstantVector::get(const std::vector<Constant*>& V) {
608 assert(!V.empty() && "Cannot infer type if V is empty");
609 return get(VectorType::get(V.front()->getType(),V.size()), V);
612 Constant* ConstantVector::get(Constant* const* Vals, unsigned NumVals) {
613 // FIXME: make this the primary ctor method.
614 return get(std::vector<Constant*>(Vals, Vals+NumVals));
617 Constant* ConstantExpr::getNSWAdd(Constant* C1, Constant* C2) {
618 return getTy(C1->getType(), Instruction::Add, C1, C2,
619 OverflowingBinaryOperator::NoSignedWrap);
622 Constant* ConstantExpr::getNSWSub(Constant* C1, Constant* C2) {
623 return getTy(C1->getType(), Instruction::Sub, C1, C2,
624 OverflowingBinaryOperator::NoSignedWrap);
627 Constant* ConstantExpr::getExactSDiv(Constant* C1, Constant* C2) {
628 return getTy(C1->getType(), Instruction::SDiv, C1, C2,
629 SDivOperator::IsExact);
632 // Utility function for determining if a ConstantExpr is a CastOp or not. This
633 // can't be inline because we don't want to #include Instruction.h into
635 bool ConstantExpr::isCast() const {
636 return Instruction::isCast(getOpcode());
639 bool ConstantExpr::isCompare() const {
640 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
643 bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
644 if (getOpcode() != Instruction::GetElementPtr) return false;
646 gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
647 User::const_op_iterator OI = next(this->op_begin());
649 // Skip the first index, as it has no static limit.
653 // The remaining indices must be compile-time known integers within the
654 // bounds of the corresponding notional static array types.
655 for (; GEPI != E; ++GEPI, ++OI) {
656 ConstantInt *CI = dyn_cast<ConstantInt>(*OI);
657 if (!CI) return false;
658 if (const ArrayType *ATy = dyn_cast<ArrayType>(*GEPI))
659 if (CI->getValue().getActiveBits() > 64 ||
660 CI->getZExtValue() >= ATy->getNumElements())
664 // All the indices checked out.
668 bool ConstantExpr::hasIndices() const {
669 return getOpcode() == Instruction::ExtractValue ||
670 getOpcode() == Instruction::InsertValue;
673 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
674 if (const ExtractValueConstantExpr *EVCE =
675 dyn_cast<ExtractValueConstantExpr>(this))
676 return EVCE->Indices;
678 return cast<InsertValueConstantExpr>(this)->Indices;
681 unsigned ConstantExpr::getPredicate() const {
682 assert(getOpcode() == Instruction::FCmp ||
683 getOpcode() == Instruction::ICmp);
684 return ((const CompareConstantExpr*)this)->predicate;
687 /// getWithOperandReplaced - Return a constant expression identical to this
688 /// one, but with the specified operand set to the specified value.
690 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
691 assert(OpNo < getNumOperands() && "Operand num is out of range!");
692 assert(Op->getType() == getOperand(OpNo)->getType() &&
693 "Replacing operand with value of different type!");
694 if (getOperand(OpNo) == Op)
695 return const_cast<ConstantExpr*>(this);
697 Constant *Op0, *Op1, *Op2;
698 switch (getOpcode()) {
699 case Instruction::Trunc:
700 case Instruction::ZExt:
701 case Instruction::SExt:
702 case Instruction::FPTrunc:
703 case Instruction::FPExt:
704 case Instruction::UIToFP:
705 case Instruction::SIToFP:
706 case Instruction::FPToUI:
707 case Instruction::FPToSI:
708 case Instruction::PtrToInt:
709 case Instruction::IntToPtr:
710 case Instruction::BitCast:
711 return ConstantExpr::getCast(getOpcode(), Op, getType());
712 case Instruction::Select:
713 Op0 = (OpNo == 0) ? Op : getOperand(0);
714 Op1 = (OpNo == 1) ? Op : getOperand(1);
715 Op2 = (OpNo == 2) ? Op : getOperand(2);
716 return ConstantExpr::getSelect(Op0, Op1, Op2);
717 case Instruction::InsertElement:
718 Op0 = (OpNo == 0) ? Op : getOperand(0);
719 Op1 = (OpNo == 1) ? Op : getOperand(1);
720 Op2 = (OpNo == 2) ? Op : getOperand(2);
721 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
722 case Instruction::ExtractElement:
723 Op0 = (OpNo == 0) ? Op : getOperand(0);
724 Op1 = (OpNo == 1) ? Op : getOperand(1);
725 return ConstantExpr::getExtractElement(Op0, Op1);
726 case Instruction::ShuffleVector:
727 Op0 = (OpNo == 0) ? Op : getOperand(0);
728 Op1 = (OpNo == 1) ? Op : getOperand(1);
729 Op2 = (OpNo == 2) ? Op : getOperand(2);
730 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
731 case Instruction::GetElementPtr: {
732 SmallVector<Constant*, 8> Ops;
733 Ops.resize(getNumOperands()-1);
734 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
735 Ops[i-1] = getOperand(i);
737 return cast<GEPOperator>(this)->isInBounds() ?
738 ConstantExpr::getInBoundsGetElementPtr(Op, &Ops[0], Ops.size()) :
739 ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
741 return cast<GEPOperator>(this)->isInBounds() ?
742 ConstantExpr::getInBoundsGetElementPtr(getOperand(0), &Ops[0], Ops.size()) :
743 ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
746 assert(getNumOperands() == 2 && "Must be binary operator?");
747 Op0 = (OpNo == 0) ? Op : getOperand(0);
748 Op1 = (OpNo == 1) ? Op : getOperand(1);
749 return ConstantExpr::get(getOpcode(), Op0, Op1, SubclassData);
753 /// getWithOperands - This returns the current constant expression with the
754 /// operands replaced with the specified values. The specified operands must
755 /// match count and type with the existing ones.
756 Constant *ConstantExpr::
757 getWithOperands(Constant* const *Ops, unsigned NumOps) const {
758 assert(NumOps == getNumOperands() && "Operand count mismatch!");
759 bool AnyChange = false;
760 for (unsigned i = 0; i != NumOps; ++i) {
761 assert(Ops[i]->getType() == getOperand(i)->getType() &&
762 "Operand type mismatch!");
763 AnyChange |= Ops[i] != getOperand(i);
765 if (!AnyChange) // No operands changed, return self.
766 return const_cast<ConstantExpr*>(this);
768 switch (getOpcode()) {
769 case Instruction::Trunc:
770 case Instruction::ZExt:
771 case Instruction::SExt:
772 case Instruction::FPTrunc:
773 case Instruction::FPExt:
774 case Instruction::UIToFP:
775 case Instruction::SIToFP:
776 case Instruction::FPToUI:
777 case Instruction::FPToSI:
778 case Instruction::PtrToInt:
779 case Instruction::IntToPtr:
780 case Instruction::BitCast:
781 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
782 case Instruction::Select:
783 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
784 case Instruction::InsertElement:
785 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
786 case Instruction::ExtractElement:
787 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
788 case Instruction::ShuffleVector:
789 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
790 case Instruction::GetElementPtr:
791 return cast<GEPOperator>(this)->isInBounds() ?
792 ConstantExpr::getInBoundsGetElementPtr(Ops[0], &Ops[1], NumOps-1) :
793 ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
794 case Instruction::ICmp:
795 case Instruction::FCmp:
796 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
798 assert(getNumOperands() == 2 && "Must be binary operator?");
799 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassData);
804 //===----------------------------------------------------------------------===//
805 // isValueValidForType implementations
807 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
808 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
809 if (Ty == Type::getInt1Ty(Ty->getContext()))
810 return Val == 0 || Val == 1;
812 return true; // always true, has to fit in largest type
813 uint64_t Max = (1ll << NumBits) - 1;
817 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
818 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
819 if (Ty == Type::getInt1Ty(Ty->getContext()))
820 return Val == 0 || Val == 1 || Val == -1;
822 return true; // always true, has to fit in largest type
823 int64_t Min = -(1ll << (NumBits-1));
824 int64_t Max = (1ll << (NumBits-1)) - 1;
825 return (Val >= Min && Val <= Max);
828 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
829 // convert modifies in place, so make a copy.
830 APFloat Val2 = APFloat(Val);
832 switch (Ty->getTypeID()) {
834 return false; // These can't be represented as floating point!
836 // FIXME rounding mode needs to be more flexible
837 case Type::FloatTyID: {
838 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
840 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
843 case Type::DoubleTyID: {
844 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
845 &Val2.getSemantics() == &APFloat::IEEEdouble)
847 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
850 case Type::X86_FP80TyID:
851 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
852 &Val2.getSemantics() == &APFloat::IEEEdouble ||
853 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
854 case Type::FP128TyID:
855 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
856 &Val2.getSemantics() == &APFloat::IEEEdouble ||
857 &Val2.getSemantics() == &APFloat::IEEEquad;
858 case Type::PPC_FP128TyID:
859 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
860 &Val2.getSemantics() == &APFloat::IEEEdouble ||
861 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
865 //===----------------------------------------------------------------------===//
866 // Factory Function Implementation
868 ConstantAggregateZero* ConstantAggregateZero::get(const Type* Ty) {
869 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
870 "Cannot create an aggregate zero of non-aggregate type!");
872 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
873 // Implicitly locked.
874 return pImpl->AggZeroConstants.getOrCreate(Ty, 0);
877 /// destroyConstant - Remove the constant from the constant table...
879 void ConstantAggregateZero::destroyConstant() {
880 // Implicitly locked.
881 getType()->getContext().pImpl->AggZeroConstants.remove(this);
882 destroyConstantImpl();
885 /// destroyConstant - Remove the constant from the constant table...
887 void ConstantArray::destroyConstant() {
888 // Implicitly locked.
889 getType()->getContext().pImpl->ArrayConstants.remove(this);
890 destroyConstantImpl();
893 /// isString - This method returns true if the array is an array of i8, and
894 /// if the elements of the array are all ConstantInt's.
895 bool ConstantArray::isString() const {
896 // Check the element type for i8...
897 if (getType()->getElementType() != Type::getInt8Ty(getContext()))
899 // Check the elements to make sure they are all integers, not constant
901 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
902 if (!isa<ConstantInt>(getOperand(i)))
907 /// isCString - This method returns true if the array is a string (see
908 /// isString) and it ends in a null byte \\0 and does not contains any other
909 /// null bytes except its terminator.
910 bool ConstantArray::isCString() const {
911 // Check the element type for i8...
912 if (getType()->getElementType() != Type::getInt8Ty(getContext()))
915 // Last element must be a null.
916 if (!getOperand(getNumOperands()-1)->isNullValue())
918 // Other elements must be non-null integers.
919 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
920 if (!isa<ConstantInt>(getOperand(i)))
922 if (getOperand(i)->isNullValue())
929 /// getAsString - If the sub-element type of this array is i8
930 /// then this method converts the array to an std::string and returns it.
931 /// Otherwise, it asserts out.
933 std::string ConstantArray::getAsString() const {
934 assert(isString() && "Not a string!");
936 Result.reserve(getNumOperands());
937 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
938 Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
943 //---- ConstantStruct::get() implementation...
950 // destroyConstant - Remove the constant from the constant table...
952 void ConstantStruct::destroyConstant() {
953 // Implicitly locked.
954 getType()->getContext().pImpl->StructConstants.remove(this);
955 destroyConstantImpl();
958 // destroyConstant - Remove the constant from the constant table...
960 void ConstantVector::destroyConstant() {
961 // Implicitly locked.
962 getType()->getContext().pImpl->VectorConstants.remove(this);
963 destroyConstantImpl();
966 /// This function will return true iff every element in this vector constant
967 /// is set to all ones.
968 /// @returns true iff this constant's emements are all set to all ones.
969 /// @brief Determine if the value is all ones.
970 bool ConstantVector::isAllOnesValue() const {
971 // Check out first element.
972 const Constant *Elt = getOperand(0);
973 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
974 if (!CI || !CI->isAllOnesValue()) return false;
975 // Then make sure all remaining elements point to the same value.
976 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
977 if (getOperand(I) != Elt) return false;
982 /// getSplatValue - If this is a splat constant, where all of the
983 /// elements have the same value, return that value. Otherwise return null.
984 Constant *ConstantVector::getSplatValue() {
985 // Check out first element.
986 Constant *Elt = getOperand(0);
987 // Then make sure all remaining elements point to the same value.
988 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
989 if (getOperand(I) != Elt) return 0;
993 //---- ConstantPointerNull::get() implementation.
996 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
997 // Implicitly locked.
998 return Ty->getContext().pImpl->NullPtrConstants.getOrCreate(Ty, 0);
1001 // destroyConstant - Remove the constant from the constant table...
1003 void ConstantPointerNull::destroyConstant() {
1004 // Implicitly locked.
1005 getType()->getContext().pImpl->NullPtrConstants.remove(this);
1006 destroyConstantImpl();
1010 //---- UndefValue::get() implementation.
1013 UndefValue *UndefValue::get(const Type *Ty) {
1014 return Ty->getContext().pImpl->UndefValueConstants.getOrCreate(Ty, 0);
1017 // destroyConstant - Remove the constant from the constant table.
1019 void UndefValue::destroyConstant() {
1020 getType()->getContext().pImpl->UndefValueConstants.remove(this);
1021 destroyConstantImpl();
1024 //---- BlockAddress::get() implementation.
1027 BlockAddress *BlockAddress::get(BasicBlock *BB) {
1028 assert(BB->getParent() != 0 && "Block must have a parent");
1029 return get(BB->getParent(), BB);
1032 BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1034 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
1036 BA = new BlockAddress(F, BB);
1038 assert(BA->getFunction() == F && "Basic block moved between functions");
1042 BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1043 : Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1050 // destroyConstant - Remove the constant from the constant table.
1052 void BlockAddress::destroyConstant() {
1053 getFunction()->getType()->getContext().pImpl
1054 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
1055 destroyConstantImpl();
1058 void BlockAddress::replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U) {
1059 // This could be replacing either the Basic Block or the Function. In either
1060 // case, we have to remove the map entry.
1061 Function *NewF = getFunction();
1062 BasicBlock *NewBB = getBasicBlock();
1065 NewF = cast<Function>(To);
1067 NewBB = cast<BasicBlock>(To);
1069 // See if the 'new' entry already exists, if not, just update this in place
1070 // and return early.
1071 BlockAddress *&NewBA =
1072 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
1074 // Remove the old entry, this can't cause the map to rehash (just a
1075 // tombstone will get added).
1076 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1084 // Otherwise, I do need to replace this with an existing value.
1085 assert(NewBA != this && "I didn't contain From!");
1087 // Everyone using this now uses the replacement.
1088 uncheckedReplaceAllUsesWith(NewBA);
1093 //---- ConstantExpr::get() implementations.
1096 /// This is a utility function to handle folding of casts and lookup of the
1097 /// cast in the ExprConstants map. It is used by the various get* methods below.
1098 static inline Constant *getFoldedCast(
1099 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1100 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1101 // Fold a few common cases
1102 if (Constant *FC = ConstantFoldCastInstruction(Ty->getContext(), opc, C, Ty))
1105 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1107 // Look up the constant in the table first to ensure uniqueness
1108 std::vector<Constant*> argVec(1, C);
1109 ExprMapKeyType Key(opc, argVec);
1111 // Implicitly locked.
1112 return pImpl->ExprConstants.getOrCreate(Ty, Key);
1115 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1116 Instruction::CastOps opc = Instruction::CastOps(oc);
1117 assert(Instruction::isCast(opc) && "opcode out of range");
1118 assert(C && Ty && "Null arguments to getCast");
1119 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1123 llvm_unreachable("Invalid cast opcode");
1125 case Instruction::Trunc: return getTrunc(C, Ty);
1126 case Instruction::ZExt: return getZExt(C, Ty);
1127 case Instruction::SExt: return getSExt(C, Ty);
1128 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1129 case Instruction::FPExt: return getFPExtend(C, Ty);
1130 case Instruction::UIToFP: return getUIToFP(C, Ty);
1131 case Instruction::SIToFP: return getSIToFP(C, Ty);
1132 case Instruction::FPToUI: return getFPToUI(C, Ty);
1133 case Instruction::FPToSI: return getFPToSI(C, Ty);
1134 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1135 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1136 case Instruction::BitCast: return getBitCast(C, Ty);
1141 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1142 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1143 return getCast(Instruction::BitCast, C, Ty);
1144 return getCast(Instruction::ZExt, C, Ty);
1147 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1148 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1149 return getCast(Instruction::BitCast, C, Ty);
1150 return getCast(Instruction::SExt, C, Ty);
1153 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1154 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1155 return getCast(Instruction::BitCast, C, Ty);
1156 return getCast(Instruction::Trunc, C, Ty);
1159 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1160 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1161 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1163 if (Ty->isInteger())
1164 return getCast(Instruction::PtrToInt, S, Ty);
1165 return getCast(Instruction::BitCast, S, Ty);
1168 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1170 assert(C->getType()->isIntOrIntVector() &&
1171 Ty->isIntOrIntVector() && "Invalid cast");
1172 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1173 unsigned DstBits = Ty->getScalarSizeInBits();
1174 Instruction::CastOps opcode =
1175 (SrcBits == DstBits ? Instruction::BitCast :
1176 (SrcBits > DstBits ? Instruction::Trunc :
1177 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1178 return getCast(opcode, C, Ty);
1181 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1182 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1184 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1185 unsigned DstBits = Ty->getScalarSizeInBits();
1186 if (SrcBits == DstBits)
1187 return C; // Avoid a useless cast
1188 Instruction::CastOps opcode =
1189 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1190 return getCast(opcode, C, Ty);
1193 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1195 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1196 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1198 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1199 assert(C->getType()->isIntOrIntVector() && "Trunc operand must be integer");
1200 assert(Ty->isIntOrIntVector() && "Trunc produces only integral");
1201 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1202 "SrcTy must be larger than DestTy for Trunc!");
1204 return getFoldedCast(Instruction::Trunc, C, Ty);
1207 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1209 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1210 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1212 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1213 assert(C->getType()->isIntOrIntVector() && "SExt operand must be integral");
1214 assert(Ty->isIntOrIntVector() && "SExt produces only integer");
1215 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1216 "SrcTy must be smaller than DestTy for SExt!");
1218 return getFoldedCast(Instruction::SExt, C, Ty);
1221 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1223 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1224 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1226 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1227 assert(C->getType()->isIntOrIntVector() && "ZEXt operand must be integral");
1228 assert(Ty->isIntOrIntVector() && "ZExt produces only integer");
1229 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1230 "SrcTy must be smaller than DestTy for ZExt!");
1232 return getFoldedCast(Instruction::ZExt, C, Ty);
1235 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1237 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1238 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1240 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1241 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1242 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1243 "This is an illegal floating point truncation!");
1244 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1247 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1249 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1250 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1252 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1253 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1254 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1255 "This is an illegal floating point extension!");
1256 return getFoldedCast(Instruction::FPExt, C, Ty);
1259 Constant *ConstantExpr::getUIToFP(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() && Ty->isFPOrFPVector() &&
1266 "This is an illegal uint to floating point cast!");
1267 return getFoldedCast(Instruction::UIToFP, C, Ty);
1270 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1272 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1273 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1275 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1276 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1277 "This is an illegal sint to floating point cast!");
1278 return getFoldedCast(Instruction::SIToFP, C, Ty);
1281 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1283 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1284 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1286 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1287 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1288 "This is an illegal floating point to uint cast!");
1289 return getFoldedCast(Instruction::FPToUI, C, Ty);
1292 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1294 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1295 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1297 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1298 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1299 "This is an illegal floating point to sint cast!");
1300 return getFoldedCast(Instruction::FPToSI, C, Ty);
1303 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1304 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1305 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1306 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1309 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1310 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1311 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1312 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1315 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1316 // BitCast implies a no-op cast of type only. No bits change. However, you
1317 // can't cast pointers to anything but pointers.
1319 const Type *SrcTy = C->getType();
1320 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1321 "BitCast cannot cast pointer to non-pointer and vice versa");
1323 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1324 // or nonptr->ptr). For all the other types, the cast is okay if source and
1325 // destination bit widths are identical.
1326 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1327 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1329 assert(SrcBitSize == DstBitSize && "BitCast requires types of same width");
1331 // It is common to ask for a bitcast of a value to its own type, handle this
1333 if (C->getType() == DstTy) return C;
1335 return getFoldedCast(Instruction::BitCast, C, DstTy);
1338 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1339 Constant *C1, Constant *C2,
1341 // Check the operands for consistency first
1342 assert(Opcode >= Instruction::BinaryOpsBegin &&
1343 Opcode < Instruction::BinaryOpsEnd &&
1344 "Invalid opcode in binary constant expression");
1345 assert(C1->getType() == C2->getType() &&
1346 "Operand types in binary constant expression should match");
1348 if (ReqTy == C1->getType() || ReqTy == Type::getInt1Ty(ReqTy->getContext()))
1349 if (Constant *FC = ConstantFoldBinaryInstruction(ReqTy->getContext(),
1351 return FC; // Fold a few common cases...
1353 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1354 ExprMapKeyType Key(Opcode, argVec, 0, Flags);
1356 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1358 // Implicitly locked.
1359 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1362 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1363 Constant *C1, Constant *C2) {
1364 switch (predicate) {
1365 default: llvm_unreachable("Invalid CmpInst predicate");
1366 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1367 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1368 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1369 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1370 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1371 case CmpInst::FCMP_TRUE:
1372 return getFCmp(predicate, C1, C2);
1374 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1375 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1376 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1377 case CmpInst::ICMP_SLE:
1378 return getICmp(predicate, C1, C2);
1382 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
1384 // API compatibility: Adjust integer opcodes to floating-point opcodes.
1385 if (C1->getType()->isFPOrFPVector()) {
1386 if (Opcode == Instruction::Add) Opcode = Instruction::FAdd;
1387 else if (Opcode == Instruction::Sub) Opcode = Instruction::FSub;
1388 else if (Opcode == Instruction::Mul) Opcode = Instruction::FMul;
1392 case Instruction::Add:
1393 case Instruction::Sub:
1394 case Instruction::Mul:
1395 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1396 assert(C1->getType()->isIntOrIntVector() &&
1397 "Tried to create an integer operation on a non-integer type!");
1399 case Instruction::FAdd:
1400 case Instruction::FSub:
1401 case Instruction::FMul:
1402 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1403 assert(C1->getType()->isFPOrFPVector() &&
1404 "Tried to create a floating-point operation on a "
1405 "non-floating-point type!");
1407 case Instruction::UDiv:
1408 case Instruction::SDiv:
1409 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1410 assert(C1->getType()->isIntOrIntVector() &&
1411 "Tried to create an arithmetic operation on a non-arithmetic type!");
1413 case Instruction::FDiv:
1414 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1415 assert(C1->getType()->isFPOrFPVector() &&
1416 "Tried to create an arithmetic operation on a non-arithmetic type!");
1418 case Instruction::URem:
1419 case Instruction::SRem:
1420 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1421 assert(C1->getType()->isIntOrIntVector() &&
1422 "Tried to create an arithmetic operation on a non-arithmetic type!");
1424 case Instruction::FRem:
1425 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1426 assert(C1->getType()->isFPOrFPVector() &&
1427 "Tried to create an arithmetic operation on a non-arithmetic type!");
1429 case Instruction::And:
1430 case Instruction::Or:
1431 case Instruction::Xor:
1432 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1433 assert(C1->getType()->isIntOrIntVector() &&
1434 "Tried to create a logical operation on a non-integral type!");
1436 case Instruction::Shl:
1437 case Instruction::LShr:
1438 case Instruction::AShr:
1439 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1440 assert(C1->getType()->isIntOrIntVector() &&
1441 "Tried to create a shift operation on a non-integer type!");
1448 return getTy(C1->getType(), Opcode, C1, C2, Flags);
1451 Constant* ConstantExpr::getSizeOf(const Type* Ty) {
1452 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1453 // Note that a non-inbounds gep is used, as null isn't within any object.
1454 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1455 Constant *GEP = getGetElementPtr(
1456 Constant::getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
1457 return getCast(Instruction::PtrToInt, GEP,
1458 Type::getInt64Ty(Ty->getContext()));
1461 Constant* ConstantExpr::getAlignOf(const Type* Ty) {
1462 // alignof is implemented as: (i64) gep ({i8,Ty}*)null, 0, 1
1463 // Note that a non-inbounds gep is used, as null isn't within any object.
1464 const Type *AligningTy = StructType::get(Ty->getContext(),
1465 Type::getInt8Ty(Ty->getContext()), Ty, NULL);
1466 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo());
1467 Constant *Zero = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 0);
1468 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1469 Constant *Indices[2] = { Zero, One };
1470 Constant *GEP = getGetElementPtr(NullPtr, Indices, 2);
1471 return getCast(Instruction::PtrToInt, GEP,
1472 Type::getInt32Ty(Ty->getContext()));
1475 Constant* ConstantExpr::getOffsetOf(const StructType* STy, unsigned FieldNo) {
1476 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1477 // Note that a non-inbounds gep is used, as null isn't within any object.
1478 Constant *GEPIdx[] = {
1479 ConstantInt::get(Type::getInt64Ty(STy->getContext()), 0),
1480 ConstantInt::get(Type::getInt32Ty(STy->getContext()), FieldNo)
1482 Constant *GEP = getGetElementPtr(
1483 Constant::getNullValue(PointerType::getUnqual(STy)), GEPIdx, 2);
1484 return getCast(Instruction::PtrToInt, GEP,
1485 Type::getInt64Ty(STy->getContext()));
1488 Constant *ConstantExpr::getCompare(unsigned short pred,
1489 Constant *C1, Constant *C2) {
1490 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1491 return getCompareTy(pred, C1, C2);
1494 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1495 Constant *V1, Constant *V2) {
1496 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1498 if (ReqTy == V1->getType())
1499 if (Constant *SC = ConstantFoldSelectInstruction(
1500 ReqTy->getContext(), C, V1, V2))
1501 return SC; // Fold common cases
1503 std::vector<Constant*> argVec(3, C);
1506 ExprMapKeyType Key(Instruction::Select, argVec);
1508 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1510 // Implicitly locked.
1511 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1514 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1517 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
1519 cast<PointerType>(ReqTy)->getElementType() &&
1520 "GEP indices invalid!");
1522 if (Constant *FC = ConstantFoldGetElementPtr(
1523 ReqTy->getContext(), C, /*inBounds=*/false,
1524 (Constant**)Idxs, NumIdx))
1525 return FC; // Fold a few common cases...
1527 assert(isa<PointerType>(C->getType()) &&
1528 "Non-pointer type for constant GetElementPtr expression");
1529 // Look up the constant in the table first to ensure uniqueness
1530 std::vector<Constant*> ArgVec;
1531 ArgVec.reserve(NumIdx+1);
1532 ArgVec.push_back(C);
1533 for (unsigned i = 0; i != NumIdx; ++i)
1534 ArgVec.push_back(cast<Constant>(Idxs[i]));
1535 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
1537 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1539 // Implicitly locked.
1540 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1543 Constant *ConstantExpr::getInBoundsGetElementPtrTy(const Type *ReqTy,
1547 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
1549 cast<PointerType>(ReqTy)->getElementType() &&
1550 "GEP indices invalid!");
1552 if (Constant *FC = ConstantFoldGetElementPtr(
1553 ReqTy->getContext(), C, /*inBounds=*/true,
1554 (Constant**)Idxs, NumIdx))
1555 return FC; // Fold a few common cases...
1557 assert(isa<PointerType>(C->getType()) &&
1558 "Non-pointer type for constant GetElementPtr expression");
1559 // Look up the constant in the table first to ensure uniqueness
1560 std::vector<Constant*> ArgVec;
1561 ArgVec.reserve(NumIdx+1);
1562 ArgVec.push_back(C);
1563 for (unsigned i = 0; i != NumIdx; ++i)
1564 ArgVec.push_back(cast<Constant>(Idxs[i]));
1565 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
1566 GEPOperator::IsInBounds);
1568 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1570 // Implicitly locked.
1571 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1574 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1576 // Get the result type of the getelementptr!
1578 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
1579 assert(Ty && "GEP indices invalid!");
1580 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
1581 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
1584 Constant *ConstantExpr::getInBoundsGetElementPtr(Constant *C,
1587 // Get the result type of the getelementptr!
1589 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
1590 assert(Ty && "GEP indices invalid!");
1591 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
1592 return getInBoundsGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
1595 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1597 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1600 Constant *ConstantExpr::getInBoundsGetElementPtr(Constant *C,
1601 Constant* const *Idxs,
1603 return getInBoundsGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1607 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1608 assert(LHS->getType() == RHS->getType());
1609 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1610 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1612 if (Constant *FC = ConstantFoldCompareInstruction(
1613 LHS->getContext(), pred, LHS, RHS))
1614 return FC; // Fold a few common cases...
1616 // Look up the constant in the table first to ensure uniqueness
1617 std::vector<Constant*> ArgVec;
1618 ArgVec.push_back(LHS);
1619 ArgVec.push_back(RHS);
1620 // Get the key type with both the opcode and predicate
1621 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1623 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1625 // Implicitly locked.
1627 pImpl->ExprConstants.getOrCreate(Type::getInt1Ty(LHS->getContext()), Key);
1631 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1632 assert(LHS->getType() == RHS->getType());
1633 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1635 if (Constant *FC = ConstantFoldCompareInstruction(
1636 LHS->getContext(), pred, LHS, RHS))
1637 return FC; // Fold a few common cases...
1639 // Look up the constant in the table first to ensure uniqueness
1640 std::vector<Constant*> ArgVec;
1641 ArgVec.push_back(LHS);
1642 ArgVec.push_back(RHS);
1643 // Get the key type with both the opcode and predicate
1644 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1646 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1648 // Implicitly locked.
1650 pImpl->ExprConstants.getOrCreate(Type::getInt1Ty(LHS->getContext()), Key);
1653 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1655 if (Constant *FC = ConstantFoldExtractElementInstruction(
1656 ReqTy->getContext(), Val, Idx))
1657 return FC; // Fold a few common cases...
1658 // Look up the constant in the table first to ensure uniqueness
1659 std::vector<Constant*> ArgVec(1, Val);
1660 ArgVec.push_back(Idx);
1661 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1663 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1665 // Implicitly locked.
1666 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1669 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1670 assert(isa<VectorType>(Val->getType()) &&
1671 "Tried to create extractelement operation on non-vector type!");
1672 assert(Idx->getType() == Type::getInt32Ty(Val->getContext()) &&
1673 "Extractelement index must be i32 type!");
1674 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
1678 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1679 Constant *Elt, Constant *Idx) {
1680 if (Constant *FC = ConstantFoldInsertElementInstruction(
1681 ReqTy->getContext(), Val, Elt, Idx))
1682 return FC; // Fold a few common cases...
1683 // Look up the constant in the table first to ensure uniqueness
1684 std::vector<Constant*> ArgVec(1, Val);
1685 ArgVec.push_back(Elt);
1686 ArgVec.push_back(Idx);
1687 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1689 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1691 // Implicitly locked.
1692 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1695 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1697 assert(isa<VectorType>(Val->getType()) &&
1698 "Tried to create insertelement operation on non-vector type!");
1699 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
1700 && "Insertelement types must match!");
1701 assert(Idx->getType() == Type::getInt32Ty(Val->getContext()) &&
1702 "Insertelement index must be i32 type!");
1703 return getInsertElementTy(Val->getType(), Val, Elt, Idx);
1706 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1707 Constant *V2, Constant *Mask) {
1708 if (Constant *FC = ConstantFoldShuffleVectorInstruction(
1709 ReqTy->getContext(), V1, V2, Mask))
1710 return FC; // Fold a few common cases...
1711 // Look up the constant in the table first to ensure uniqueness
1712 std::vector<Constant*> ArgVec(1, V1);
1713 ArgVec.push_back(V2);
1714 ArgVec.push_back(Mask);
1715 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1717 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1719 // Implicitly locked.
1720 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1723 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1725 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1726 "Invalid shuffle vector constant expr operands!");
1728 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
1729 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
1730 const Type *ShufTy = VectorType::get(EltTy, NElts);
1731 return getShuffleVectorTy(ShufTy, V1, V2, Mask);
1734 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
1736 const unsigned *Idxs, unsigned NumIdx) {
1737 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1738 Idxs+NumIdx) == Val->getType() &&
1739 "insertvalue indices invalid!");
1740 assert(Agg->getType() == ReqTy &&
1741 "insertvalue type invalid!");
1742 assert(Agg->getType()->isFirstClassType() &&
1743 "Non-first-class type for constant InsertValue expression");
1744 Constant *FC = ConstantFoldInsertValueInstruction(
1745 ReqTy->getContext(), Agg, Val, Idxs, NumIdx);
1746 assert(FC && "InsertValue constant expr couldn't be folded!");
1750 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
1751 const unsigned *IdxList, unsigned NumIdx) {
1752 assert(Agg->getType()->isFirstClassType() &&
1753 "Tried to create insertelement operation on non-first-class type!");
1755 const Type *ReqTy = Agg->getType();
1758 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1760 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
1761 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
1764 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
1765 const unsigned *Idxs, unsigned NumIdx) {
1766 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1767 Idxs+NumIdx) == ReqTy &&
1768 "extractvalue indices invalid!");
1769 assert(Agg->getType()->isFirstClassType() &&
1770 "Non-first-class type for constant extractvalue expression");
1771 Constant *FC = ConstantFoldExtractValueInstruction(
1772 ReqTy->getContext(), Agg, Idxs, NumIdx);
1773 assert(FC && "ExtractValue constant expr couldn't be folded!");
1777 Constant *ConstantExpr::getExtractValue(Constant *Agg,
1778 const unsigned *IdxList, unsigned NumIdx) {
1779 assert(Agg->getType()->isFirstClassType() &&
1780 "Tried to create extractelement operation on non-first-class type!");
1783 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1784 assert(ReqTy && "extractvalue indices invalid!");
1785 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
1788 Constant* ConstantExpr::getNeg(Constant* C) {
1789 // API compatibility: Adjust integer opcodes to floating-point opcodes.
1790 if (C->getType()->isFPOrFPVector())
1792 assert(C->getType()->isIntOrIntVector() &&
1793 "Cannot NEG a nonintegral value!");
1794 return get(Instruction::Sub,
1795 ConstantFP::getZeroValueForNegation(C->getType()),
1799 Constant* ConstantExpr::getFNeg(Constant* C) {
1800 assert(C->getType()->isFPOrFPVector() &&
1801 "Cannot FNEG a non-floating-point value!");
1802 return get(Instruction::FSub,
1803 ConstantFP::getZeroValueForNegation(C->getType()),
1807 Constant* ConstantExpr::getNot(Constant* C) {
1808 assert(C->getType()->isIntOrIntVector() &&
1809 "Cannot NOT a nonintegral value!");
1810 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
1813 Constant* ConstantExpr::getAdd(Constant* C1, Constant* C2) {
1814 return get(Instruction::Add, C1, C2);
1817 Constant* ConstantExpr::getFAdd(Constant* C1, Constant* C2) {
1818 return get(Instruction::FAdd, C1, C2);
1821 Constant* ConstantExpr::getSub(Constant* C1, Constant* C2) {
1822 return get(Instruction::Sub, C1, C2);
1825 Constant* ConstantExpr::getFSub(Constant* C1, Constant* C2) {
1826 return get(Instruction::FSub, C1, C2);
1829 Constant* ConstantExpr::getMul(Constant* C1, Constant* C2) {
1830 return get(Instruction::Mul, C1, C2);
1833 Constant* ConstantExpr::getFMul(Constant* C1, Constant* C2) {
1834 return get(Instruction::FMul, C1, C2);
1837 Constant* ConstantExpr::getUDiv(Constant* C1, Constant* C2) {
1838 return get(Instruction::UDiv, C1, C2);
1841 Constant* ConstantExpr::getSDiv(Constant* C1, Constant* C2) {
1842 return get(Instruction::SDiv, C1, C2);
1845 Constant* ConstantExpr::getFDiv(Constant* C1, Constant* C2) {
1846 return get(Instruction::FDiv, C1, C2);
1849 Constant* ConstantExpr::getURem(Constant* C1, Constant* C2) {
1850 return get(Instruction::URem, C1, C2);
1853 Constant* ConstantExpr::getSRem(Constant* C1, Constant* C2) {
1854 return get(Instruction::SRem, C1, C2);
1857 Constant* ConstantExpr::getFRem(Constant* C1, Constant* C2) {
1858 return get(Instruction::FRem, C1, C2);
1861 Constant* ConstantExpr::getAnd(Constant* C1, Constant* C2) {
1862 return get(Instruction::And, C1, C2);
1865 Constant* ConstantExpr::getOr(Constant* C1, Constant* C2) {
1866 return get(Instruction::Or, C1, C2);
1869 Constant* ConstantExpr::getXor(Constant* C1, Constant* C2) {
1870 return get(Instruction::Xor, C1, C2);
1873 Constant* ConstantExpr::getShl(Constant* C1, Constant* C2) {
1874 return get(Instruction::Shl, C1, C2);
1877 Constant* ConstantExpr::getLShr(Constant* C1, Constant* C2) {
1878 return get(Instruction::LShr, C1, C2);
1881 Constant* ConstantExpr::getAShr(Constant* C1, Constant* C2) {
1882 return get(Instruction::AShr, C1, C2);
1885 // destroyConstant - Remove the constant from the constant table...
1887 void ConstantExpr::destroyConstant() {
1888 // Implicitly locked.
1889 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
1890 pImpl->ExprConstants.remove(this);
1891 destroyConstantImpl();
1894 const char *ConstantExpr::getOpcodeName() const {
1895 return Instruction::getOpcodeName(getOpcode());
1898 //===----------------------------------------------------------------------===//
1899 // replaceUsesOfWithOnConstant implementations
1901 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
1902 /// 'From' to be uses of 'To'. This must update the uniquing data structures
1905 /// Note that we intentionally replace all uses of From with To here. Consider
1906 /// a large array that uses 'From' 1000 times. By handling this case all here,
1907 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
1908 /// single invocation handles all 1000 uses. Handling them one at a time would
1909 /// work, but would be really slow because it would have to unique each updated
1912 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1914 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1915 Constant *ToC = cast<Constant>(To);
1917 LLVMContext &Context = getType()->getContext();
1918 LLVMContextImpl *pImpl = Context.pImpl;
1920 std::pair<LLVMContextImpl::ArrayConstantsTy::MapKey, ConstantArray*> Lookup;
1921 Lookup.first.first = getType();
1922 Lookup.second = this;
1924 std::vector<Constant*> &Values = Lookup.first.second;
1925 Values.reserve(getNumOperands()); // Build replacement array.
1927 // Fill values with the modified operands of the constant array. Also,
1928 // compute whether this turns into an all-zeros array.
1929 bool isAllZeros = false;
1930 unsigned NumUpdated = 0;
1931 if (!ToC->isNullValue()) {
1932 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1933 Constant *Val = cast<Constant>(O->get());
1938 Values.push_back(Val);
1942 for (Use *O = OperandList, *E = OperandList+getNumOperands();O != E; ++O) {
1943 Constant *Val = cast<Constant>(O->get());
1948 Values.push_back(Val);
1949 if (isAllZeros) isAllZeros = Val->isNullValue();
1953 Constant *Replacement = 0;
1955 Replacement = ConstantAggregateZero::get(getType());
1957 // Check to see if we have this array type already.
1959 LLVMContextImpl::ArrayConstantsTy::MapTy::iterator I =
1960 pImpl->ArrayConstants.InsertOrGetItem(Lookup, Exists);
1963 Replacement = I->second;
1965 // Okay, the new shape doesn't exist in the system yet. Instead of
1966 // creating a new constant array, inserting it, replaceallusesof'ing the
1967 // old with the new, then deleting the old... just update the current one
1969 pImpl->ArrayConstants.MoveConstantToNewSlot(this, I);
1971 // Update to the new value. Optimize for the case when we have a single
1972 // operand that we're changing, but handle bulk updates efficiently.
1973 if (NumUpdated == 1) {
1974 unsigned OperandToUpdate = U - OperandList;
1975 assert(getOperand(OperandToUpdate) == From &&
1976 "ReplaceAllUsesWith broken!");
1977 setOperand(OperandToUpdate, ToC);
1979 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1980 if (getOperand(i) == From)
1987 // Otherwise, I do need to replace this with an existing value.
1988 assert(Replacement != this && "I didn't contain From!");
1990 // Everyone using this now uses the replacement.
1991 uncheckedReplaceAllUsesWith(Replacement);
1993 // Delete the old constant!
1997 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
1999 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2000 Constant *ToC = cast<Constant>(To);
2002 unsigned OperandToUpdate = U-OperandList;
2003 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2005 std::pair<LLVMContextImpl::StructConstantsTy::MapKey, ConstantStruct*> Lookup;
2006 Lookup.first.first = getType();
2007 Lookup.second = this;
2008 std::vector<Constant*> &Values = Lookup.first.second;
2009 Values.reserve(getNumOperands()); // Build replacement struct.
2012 // Fill values with the modified operands of the constant struct. Also,
2013 // compute whether this turns into an all-zeros struct.
2014 bool isAllZeros = false;
2015 if (!ToC->isNullValue()) {
2016 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
2017 Values.push_back(cast<Constant>(O->get()));
2020 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2021 Constant *Val = cast<Constant>(O->get());
2022 Values.push_back(Val);
2023 if (isAllZeros) isAllZeros = Val->isNullValue();
2026 Values[OperandToUpdate] = ToC;
2028 LLVMContext &Context = getType()->getContext();
2029 LLVMContextImpl *pImpl = Context.pImpl;
2031 Constant *Replacement = 0;
2033 Replacement = ConstantAggregateZero::get(getType());
2035 // Check to see if we have this array type already.
2037 LLVMContextImpl::StructConstantsTy::MapTy::iterator I =
2038 pImpl->StructConstants.InsertOrGetItem(Lookup, Exists);
2041 Replacement = I->second;
2043 // Okay, the new shape doesn't exist in the system yet. Instead of
2044 // creating a new constant struct, inserting it, replaceallusesof'ing the
2045 // old with the new, then deleting the old... just update the current one
2047 pImpl->StructConstants.MoveConstantToNewSlot(this, I);
2049 // Update to the new value.
2050 setOperand(OperandToUpdate, ToC);
2055 assert(Replacement != this && "I didn't contain From!");
2057 // Everyone using this now uses the replacement.
2058 uncheckedReplaceAllUsesWith(Replacement);
2060 // Delete the old constant!
2064 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2066 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2068 std::vector<Constant*> Values;
2069 Values.reserve(getNumOperands()); // Build replacement array...
2070 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2071 Constant *Val = getOperand(i);
2072 if (Val == From) Val = cast<Constant>(To);
2073 Values.push_back(Val);
2076 Constant *Replacement = get(getType(), Values);
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 ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2088 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2089 Constant *To = cast<Constant>(ToV);
2091 Constant *Replacement = 0;
2092 if (getOpcode() == Instruction::GetElementPtr) {
2093 SmallVector<Constant*, 8> Indices;
2094 Constant *Pointer = getOperand(0);
2095 Indices.reserve(getNumOperands()-1);
2096 if (Pointer == From) Pointer = To;
2098 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2099 Constant *Val = getOperand(i);
2100 if (Val == From) Val = To;
2101 Indices.push_back(Val);
2103 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2104 &Indices[0], Indices.size());
2105 } else if (getOpcode() == Instruction::ExtractValue) {
2106 Constant *Agg = getOperand(0);
2107 if (Agg == From) Agg = To;
2109 const SmallVector<unsigned, 4> &Indices = getIndices();
2110 Replacement = ConstantExpr::getExtractValue(Agg,
2111 &Indices[0], Indices.size());
2112 } else if (getOpcode() == Instruction::InsertValue) {
2113 Constant *Agg = getOperand(0);
2114 Constant *Val = getOperand(1);
2115 if (Agg == From) Agg = To;
2116 if (Val == From) Val = To;
2118 const SmallVector<unsigned, 4> &Indices = getIndices();
2119 Replacement = ConstantExpr::getInsertValue(Agg, Val,
2120 &Indices[0], Indices.size());
2121 } else if (isCast()) {
2122 assert(getOperand(0) == From && "Cast only has one use!");
2123 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2124 } else if (getOpcode() == Instruction::Select) {
2125 Constant *C1 = getOperand(0);
2126 Constant *C2 = getOperand(1);
2127 Constant *C3 = getOperand(2);
2128 if (C1 == From) C1 = To;
2129 if (C2 == From) C2 = To;
2130 if (C3 == From) C3 = To;
2131 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2132 } else if (getOpcode() == Instruction::ExtractElement) {
2133 Constant *C1 = getOperand(0);
2134 Constant *C2 = getOperand(1);
2135 if (C1 == From) C1 = To;
2136 if (C2 == From) C2 = To;
2137 Replacement = ConstantExpr::getExtractElement(C1, C2);
2138 } else if (getOpcode() == Instruction::InsertElement) {
2139 Constant *C1 = getOperand(0);
2140 Constant *C2 = getOperand(1);
2141 Constant *C3 = getOperand(1);
2142 if (C1 == From) C1 = To;
2143 if (C2 == From) C2 = To;
2144 if (C3 == From) C3 = To;
2145 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2146 } else if (getOpcode() == Instruction::ShuffleVector) {
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::getShuffleVector(C1, C2, C3);
2154 } else if (isCompare()) {
2155 Constant *C1 = getOperand(0);
2156 Constant *C2 = getOperand(1);
2157 if (C1 == From) C1 = To;
2158 if (C2 == From) C2 = To;
2159 if (getOpcode() == Instruction::ICmp)
2160 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2162 assert(getOpcode() == Instruction::FCmp);
2163 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2165 } else if (getNumOperands() == 2) {
2166 Constant *C1 = getOperand(0);
2167 Constant *C2 = getOperand(1);
2168 if (C1 == From) C1 = To;
2169 if (C2 == From) C2 = To;
2170 Replacement = ConstantExpr::get(getOpcode(), C1, C2, SubclassData);
2172 llvm_unreachable("Unknown ConstantExpr type!");
2176 assert(Replacement != this && "I didn't contain From!");
2178 // Everyone using this now uses the replacement.
2179 uncheckedReplaceAllUsesWith(Replacement);
2181 // Delete the old constant!