1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Constant* classes.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Constants.h"
15 #include "LLVMContextImpl.h"
16 #include "ConstantFold.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/GlobalValue.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Module.h"
21 #include "llvm/Operator.h"
22 #include "llvm/ADT/FoldingSet.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/StringMap.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/MathExtras.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Support/GetElementPtrTypeIterator.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/STLExtras.h"
39 //===----------------------------------------------------------------------===//
41 //===----------------------------------------------------------------------===//
43 bool Constant::isNegativeZeroValue() const {
44 // Floating point values have an explicit -0.0 value.
45 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
46 return CFP->isZero() && CFP->isNegative();
48 // Otherwise, just use +0.0.
52 bool Constant::isNullValue() const {
54 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
58 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
59 return CFP->isZero() && !CFP->isNegative();
61 // constant zero is zero for aggregates and cpnull is null for pointers.
62 return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this);
65 bool Constant::isAllOnesValue() const {
66 // Check for -1 integers
67 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
68 return CI->isMinusOne();
70 // Check for FP which are bitcasted from -1 integers
71 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
72 return CFP->getValueAPF().bitcastToAPInt().isAllOnesValue();
74 // Check for constant vectors which are splats of -1 values.
75 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
76 if (Constant *Splat = CV->getSplatValue())
77 return Splat->isAllOnesValue();
82 // Constructor to create a '0' constant of arbitrary type...
83 Constant *Constant::getNullValue(Type *Ty) {
84 switch (Ty->getTypeID()) {
85 case Type::IntegerTyID:
86 return ConstantInt::get(Ty, 0);
88 return ConstantFP::get(Ty->getContext(),
89 APFloat::getZero(APFloat::IEEEhalf));
91 return ConstantFP::get(Ty->getContext(),
92 APFloat::getZero(APFloat::IEEEsingle));
93 case Type::DoubleTyID:
94 return ConstantFP::get(Ty->getContext(),
95 APFloat::getZero(APFloat::IEEEdouble));
96 case Type::X86_FP80TyID:
97 return ConstantFP::get(Ty->getContext(),
98 APFloat::getZero(APFloat::x87DoubleExtended));
100 return ConstantFP::get(Ty->getContext(),
101 APFloat::getZero(APFloat::IEEEquad));
102 case Type::PPC_FP128TyID:
103 return ConstantFP::get(Ty->getContext(),
104 APFloat(APInt::getNullValue(128)));
105 case Type::PointerTyID:
106 return ConstantPointerNull::get(cast<PointerType>(Ty));
107 case Type::StructTyID:
108 case Type::ArrayTyID:
109 case Type::VectorTyID:
110 return ConstantAggregateZero::get(Ty);
112 // Function, Label, or Opaque type?
113 assert(0 && "Cannot create a null constant of that type!");
118 Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) {
119 Type *ScalarTy = Ty->getScalarType();
121 // Create the base integer constant.
122 Constant *C = ConstantInt::get(Ty->getContext(), V);
124 // Convert an integer to a pointer, if necessary.
125 if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
126 C = ConstantExpr::getIntToPtr(C, PTy);
128 // Broadcast a scalar to a vector, if necessary.
129 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
130 C = ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
135 Constant *Constant::getAllOnesValue(Type *Ty) {
136 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
137 return ConstantInt::get(Ty->getContext(),
138 APInt::getAllOnesValue(ITy->getBitWidth()));
140 if (Ty->isFloatingPointTy()) {
141 APFloat FL = APFloat::getAllOnesValue(Ty->getPrimitiveSizeInBits(),
142 !Ty->isPPC_FP128Ty());
143 return ConstantFP::get(Ty->getContext(), FL);
146 SmallVector<Constant*, 16> Elts;
147 VectorType *VTy = cast<VectorType>(Ty);
148 Elts.resize(VTy->getNumElements(), getAllOnesValue(VTy->getElementType()));
149 assert(Elts[0] && "Invalid AllOnes value!");
150 return cast<ConstantVector>(ConstantVector::get(Elts));
153 void Constant::destroyConstantImpl() {
154 // When a Constant is destroyed, there may be lingering
155 // references to the constant by other constants in the constant pool. These
156 // constants are implicitly dependent on the module that is being deleted,
157 // but they don't know that. Because we only find out when the CPV is
158 // deleted, we must now notify all of our users (that should only be
159 // Constants) that they are, in fact, invalid now and should be deleted.
161 while (!use_empty()) {
162 Value *V = use_back();
163 #ifndef NDEBUG // Only in -g mode...
164 if (!isa<Constant>(V)) {
165 dbgs() << "While deleting: " << *this
166 << "\n\nUse still stuck around after Def is destroyed: "
170 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
171 Constant *CV = cast<Constant>(V);
172 CV->destroyConstant();
174 // The constant should remove itself from our use list...
175 assert((use_empty() || use_back() != V) && "Constant not removed!");
178 // Value has no outstanding references it is safe to delete it now...
182 /// canTrap - Return true if evaluation of this constant could trap. This is
183 /// true for things like constant expressions that could divide by zero.
184 bool Constant::canTrap() const {
185 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
186 // The only thing that could possibly trap are constant exprs.
187 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
188 if (!CE) return false;
190 // ConstantExpr traps if any operands can trap.
191 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
192 if (CE->getOperand(i)->canTrap())
195 // Otherwise, only specific operations can trap.
196 switch (CE->getOpcode()) {
199 case Instruction::UDiv:
200 case Instruction::SDiv:
201 case Instruction::FDiv:
202 case Instruction::URem:
203 case Instruction::SRem:
204 case Instruction::FRem:
205 // Div and rem can trap if the RHS is not known to be non-zero.
206 if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
212 /// isConstantUsed - Return true if the constant has users other than constant
213 /// exprs and other dangling things.
214 bool Constant::isConstantUsed() const {
215 for (const_use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
216 const Constant *UC = dyn_cast<Constant>(*UI);
217 if (UC == 0 || isa<GlobalValue>(UC))
220 if (UC->isConstantUsed())
228 /// getRelocationInfo - This method classifies the entry according to
229 /// whether or not it may generate a relocation entry. This must be
230 /// conservative, so if it might codegen to a relocatable entry, it should say
231 /// so. The return values are:
233 /// NoRelocation: This constant pool entry is guaranteed to never have a
234 /// relocation applied to it (because it holds a simple constant like
236 /// LocalRelocation: This entry has relocations, but the entries are
237 /// guaranteed to be resolvable by the static linker, so the dynamic
238 /// linker will never see them.
239 /// GlobalRelocations: This entry may have arbitrary relocations.
241 /// FIXME: This really should not be in VMCore.
242 Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
243 if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
244 if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
245 return LocalRelocation; // Local to this file/library.
246 return GlobalRelocations; // Global reference.
249 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
250 return BA->getFunction()->getRelocationInfo();
252 // While raw uses of blockaddress need to be relocated, differences between
253 // two of them don't when they are for labels in the same function. This is a
254 // common idiom when creating a table for the indirect goto extension, so we
255 // handle it efficiently here.
256 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this))
257 if (CE->getOpcode() == Instruction::Sub) {
258 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
259 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
261 LHS->getOpcode() == Instruction::PtrToInt &&
262 RHS->getOpcode() == Instruction::PtrToInt &&
263 isa<BlockAddress>(LHS->getOperand(0)) &&
264 isa<BlockAddress>(RHS->getOperand(0)) &&
265 cast<BlockAddress>(LHS->getOperand(0))->getFunction() ==
266 cast<BlockAddress>(RHS->getOperand(0))->getFunction())
270 PossibleRelocationsTy Result = NoRelocation;
271 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
272 Result = std::max(Result,
273 cast<Constant>(getOperand(i))->getRelocationInfo());
279 /// getVectorElements - This method, which is only valid on constant of vector
280 /// type, returns the elements of the vector in the specified smallvector.
281 /// This handles breaking down a vector undef into undef elements, etc. For
282 /// constant exprs and other cases we can't handle, we return an empty vector.
283 void Constant::getVectorElements(SmallVectorImpl<Constant*> &Elts) const {
284 assert(getType()->isVectorTy() && "Not a vector constant!");
286 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
287 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
288 Elts.push_back(CV->getOperand(i));
292 VectorType *VT = cast<VectorType>(getType());
293 if (isa<ConstantAggregateZero>(this)) {
294 Elts.assign(VT->getNumElements(),
295 Constant::getNullValue(VT->getElementType()));
299 if (isa<UndefValue>(this)) {
300 Elts.assign(VT->getNumElements(), UndefValue::get(VT->getElementType()));
304 // Unknown type, must be constant expr etc.
308 /// removeDeadUsersOfConstant - If the specified constantexpr is dead, remove
309 /// it. This involves recursively eliminating any dead users of the
311 static bool removeDeadUsersOfConstant(const Constant *C) {
312 if (isa<GlobalValue>(C)) return false; // Cannot remove this
314 while (!C->use_empty()) {
315 const Constant *User = dyn_cast<Constant>(C->use_back());
316 if (!User) return false; // Non-constant usage;
317 if (!removeDeadUsersOfConstant(User))
318 return false; // Constant wasn't dead
321 const_cast<Constant*>(C)->destroyConstant();
326 /// removeDeadConstantUsers - If there are any dead constant users dangling
327 /// off of this constant, remove them. This method is useful for clients
328 /// that want to check to see if a global is unused, but don't want to deal
329 /// with potentially dead constants hanging off of the globals.
330 void Constant::removeDeadConstantUsers() const {
331 Value::const_use_iterator I = use_begin(), E = use_end();
332 Value::const_use_iterator LastNonDeadUser = E;
334 const Constant *User = dyn_cast<Constant>(*I);
341 if (!removeDeadUsersOfConstant(User)) {
342 // If the constant wasn't dead, remember that this was the last live use
343 // and move on to the next constant.
349 // If the constant was dead, then the iterator is invalidated.
350 if (LastNonDeadUser == E) {
362 //===----------------------------------------------------------------------===//
364 //===----------------------------------------------------------------------===//
366 ConstantInt::ConstantInt(IntegerType *Ty, const APInt& V)
367 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
368 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
371 ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
372 LLVMContextImpl *pImpl = Context.pImpl;
373 if (!pImpl->TheTrueVal)
374 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
375 return pImpl->TheTrueVal;
378 ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
379 LLVMContextImpl *pImpl = Context.pImpl;
380 if (!pImpl->TheFalseVal)
381 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
382 return pImpl->TheFalseVal;
385 Constant *ConstantInt::getTrue(Type *Ty) {
386 VectorType *VTy = dyn_cast<VectorType>(Ty);
388 assert(Ty->isIntegerTy(1) && "True must be i1 or vector of i1.");
389 return ConstantInt::getTrue(Ty->getContext());
391 assert(VTy->getElementType()->isIntegerTy(1) &&
392 "True must be vector of i1 or i1.");
393 SmallVector<Constant*, 16> Splat(VTy->getNumElements(),
394 ConstantInt::getTrue(Ty->getContext()));
395 return ConstantVector::get(Splat);
398 Constant *ConstantInt::getFalse(Type *Ty) {
399 VectorType *VTy = dyn_cast<VectorType>(Ty);
401 assert(Ty->isIntegerTy(1) && "False must be i1 or vector of i1.");
402 return ConstantInt::getFalse(Ty->getContext());
404 assert(VTy->getElementType()->isIntegerTy(1) &&
405 "False must be vector of i1 or i1.");
406 SmallVector<Constant*, 16> Splat(VTy->getNumElements(),
407 ConstantInt::getFalse(Ty->getContext()));
408 return ConstantVector::get(Splat);
412 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
413 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
414 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
415 // compare APInt's of different widths, which would violate an APInt class
416 // invariant which generates an assertion.
417 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
418 // Get the corresponding integer type for the bit width of the value.
419 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
420 // get an existing value or the insertion position
421 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
422 ConstantInt *&Slot = Context.pImpl->IntConstants[Key];
423 if (!Slot) Slot = new ConstantInt(ITy, V);
427 Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
428 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
430 // For vectors, broadcast the value.
431 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
432 return ConstantVector::get(SmallVector<Constant*,
433 16>(VTy->getNumElements(), C));
438 ConstantInt* ConstantInt::get(IntegerType* Ty, uint64_t V,
440 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
443 ConstantInt* ConstantInt::getSigned(IntegerType* Ty, int64_t V) {
444 return get(Ty, V, true);
447 Constant *ConstantInt::getSigned(Type *Ty, int64_t V) {
448 return get(Ty, V, true);
451 Constant *ConstantInt::get(Type* Ty, const APInt& V) {
452 ConstantInt *C = get(Ty->getContext(), V);
453 assert(C->getType() == Ty->getScalarType() &&
454 "ConstantInt type doesn't match the type implied by its value!");
456 // For vectors, broadcast the value.
457 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
458 return ConstantVector::get(
459 SmallVector<Constant *, 16>(VTy->getNumElements(), C));
464 ConstantInt* ConstantInt::get(IntegerType* Ty, StringRef Str,
466 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
469 //===----------------------------------------------------------------------===//
471 //===----------------------------------------------------------------------===//
473 static const fltSemantics *TypeToFloatSemantics(Type *Ty) {
475 return &APFloat::IEEEhalf;
477 return &APFloat::IEEEsingle;
478 if (Ty->isDoubleTy())
479 return &APFloat::IEEEdouble;
480 if (Ty->isX86_FP80Ty())
481 return &APFloat::x87DoubleExtended;
482 else if (Ty->isFP128Ty())
483 return &APFloat::IEEEquad;
485 assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
486 return &APFloat::PPCDoubleDouble;
489 /// get() - This returns a constant fp for the specified value in the
490 /// specified type. This should only be used for simple constant values like
491 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
492 Constant *ConstantFP::get(Type* Ty, double V) {
493 LLVMContext &Context = Ty->getContext();
497 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
498 APFloat::rmNearestTiesToEven, &ignored);
499 Constant *C = get(Context, FV);
501 // For vectors, broadcast the value.
502 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
503 return ConstantVector::get(
504 SmallVector<Constant *, 16>(VTy->getNumElements(), C));
510 Constant *ConstantFP::get(Type* Ty, StringRef Str) {
511 LLVMContext &Context = Ty->getContext();
513 APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
514 Constant *C = get(Context, FV);
516 // For vectors, broadcast the value.
517 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
518 return ConstantVector::get(
519 SmallVector<Constant *, 16>(VTy->getNumElements(), C));
525 ConstantFP* ConstantFP::getNegativeZero(Type* Ty) {
526 LLVMContext &Context = Ty->getContext();
527 APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
529 return get(Context, apf);
533 Constant *ConstantFP::getZeroValueForNegation(Type* Ty) {
534 if (VectorType *PTy = dyn_cast<VectorType>(Ty))
535 if (PTy->getElementType()->isFloatingPointTy()) {
536 SmallVector<Constant*, 16> zeros(PTy->getNumElements(),
537 getNegativeZero(PTy->getElementType()));
538 return ConstantVector::get(zeros);
541 if (Ty->isFloatingPointTy())
542 return getNegativeZero(Ty);
544 return Constant::getNullValue(Ty);
548 // ConstantFP accessors.
549 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
550 DenseMapAPFloatKeyInfo::KeyTy Key(V);
552 LLVMContextImpl* pImpl = Context.pImpl;
554 ConstantFP *&Slot = pImpl->FPConstants[Key];
558 if (&V.getSemantics() == &APFloat::IEEEhalf)
559 Ty = Type::getHalfTy(Context);
560 else if (&V.getSemantics() == &APFloat::IEEEsingle)
561 Ty = Type::getFloatTy(Context);
562 else if (&V.getSemantics() == &APFloat::IEEEdouble)
563 Ty = Type::getDoubleTy(Context);
564 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
565 Ty = Type::getX86_FP80Ty(Context);
566 else if (&V.getSemantics() == &APFloat::IEEEquad)
567 Ty = Type::getFP128Ty(Context);
569 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
570 "Unknown FP format");
571 Ty = Type::getPPC_FP128Ty(Context);
573 Slot = new ConstantFP(Ty, V);
579 ConstantFP *ConstantFP::getInfinity(Type *Ty, bool Negative) {
580 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty);
581 return ConstantFP::get(Ty->getContext(),
582 APFloat::getInf(Semantics, Negative));
585 ConstantFP::ConstantFP(Type *Ty, const APFloat& V)
586 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
587 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
591 bool ConstantFP::isExactlyValue(const APFloat &V) const {
592 return Val.bitwiseIsEqual(V);
595 //===----------------------------------------------------------------------===//
596 // ConstantXXX Classes
597 //===----------------------------------------------------------------------===//
600 ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
601 : Constant(T, ConstantArrayVal,
602 OperandTraits<ConstantArray>::op_end(this) - V.size(),
604 assert(V.size() == T->getNumElements() &&
605 "Invalid initializer vector for constant array");
606 for (unsigned i = 0, e = V.size(); i != e; ++i)
607 assert(V[i]->getType() == T->getElementType() &&
608 "Initializer for array element doesn't match array element type!");
609 std::copy(V.begin(), V.end(), op_begin());
612 Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
613 for (unsigned i = 0, e = V.size(); i != e; ++i) {
614 assert(V[i]->getType() == Ty->getElementType() &&
615 "Wrong type in array element initializer");
617 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
618 // If this is an all-zero array, return a ConstantAggregateZero object
621 if (!C->isNullValue())
622 return pImpl->ArrayConstants.getOrCreate(Ty, V);
624 for (unsigned i = 1, e = V.size(); i != e; ++i)
626 return pImpl->ArrayConstants.getOrCreate(Ty, V);
629 return ConstantAggregateZero::get(Ty);
632 /// ConstantArray::get(const string&) - Return an array that is initialized to
633 /// contain the specified string. If length is zero then a null terminator is
634 /// added to the specified string so that it may be used in a natural way.
635 /// Otherwise, the length parameter specifies how much of the string to use
636 /// and it won't be null terminated.
638 Constant *ConstantArray::get(LLVMContext &Context, StringRef Str,
640 std::vector<Constant*> ElementVals;
641 ElementVals.reserve(Str.size() + size_t(AddNull));
642 for (unsigned i = 0; i < Str.size(); ++i)
643 ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), Str[i]));
645 // Add a null terminator to the string...
647 ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), 0));
650 ArrayType *ATy = ArrayType::get(Type::getInt8Ty(Context), ElementVals.size());
651 return get(ATy, ElementVals);
654 /// getTypeForElements - Return an anonymous struct type to use for a constant
655 /// with the specified set of elements. The list must not be empty.
656 StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
657 ArrayRef<Constant*> V,
659 SmallVector<Type*, 16> EltTypes;
660 for (unsigned i = 0, e = V.size(); i != e; ++i)
661 EltTypes.push_back(V[i]->getType());
663 return StructType::get(Context, EltTypes, Packed);
667 StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
670 "ConstantStruct::getTypeForElements cannot be called on empty list");
671 return getTypeForElements(V[0]->getContext(), V, Packed);
675 ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
676 : Constant(T, ConstantStructVal,
677 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
679 assert(V.size() == T->getNumElements() &&
680 "Invalid initializer vector for constant structure");
681 for (unsigned i = 0, e = V.size(); i != e; ++i)
682 assert((T->isOpaque() || V[i]->getType() == T->getElementType(i)) &&
683 "Initializer for struct element doesn't match struct element type!");
684 std::copy(V.begin(), V.end(), op_begin());
687 // ConstantStruct accessors.
688 Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
689 // Create a ConstantAggregateZero value if all elements are zeros.
690 for (unsigned i = 0, e = V.size(); i != e; ++i)
691 if (!V[i]->isNullValue())
692 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
694 assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
695 "Incorrect # elements specified to ConstantStruct::get");
696 return ConstantAggregateZero::get(ST);
699 Constant *ConstantStruct::get(StructType *T, ...) {
701 SmallVector<Constant*, 8> Values;
703 while (Constant *Val = va_arg(ap, llvm::Constant*))
704 Values.push_back(Val);
706 return get(T, Values);
709 ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
710 : Constant(T, ConstantVectorVal,
711 OperandTraits<ConstantVector>::op_end(this) - V.size(),
713 for (size_t i = 0, e = V.size(); i != e; i++)
714 assert(V[i]->getType() == T->getElementType() &&
715 "Initializer for vector element doesn't match vector element type!");
716 std::copy(V.begin(), V.end(), op_begin());
719 // ConstantVector accessors.
720 Constant *ConstantVector::get(ArrayRef<Constant*> V) {
721 assert(!V.empty() && "Vectors can't be empty");
722 VectorType *T = VectorType::get(V.front()->getType(), V.size());
723 LLVMContextImpl *pImpl = T->getContext().pImpl;
725 // If this is an all-undef or all-zero vector, return a
726 // ConstantAggregateZero or UndefValue.
728 bool isZero = C->isNullValue();
729 bool isUndef = isa<UndefValue>(C);
731 if (isZero || isUndef) {
732 for (unsigned i = 1, e = V.size(); i != e; ++i)
734 isZero = isUndef = false;
740 return ConstantAggregateZero::get(T);
742 return UndefValue::get(T);
744 return pImpl->VectorConstants.getOrCreate(T, V);
747 // Utility function for determining if a ConstantExpr is a CastOp or not. This
748 // can't be inline because we don't want to #include Instruction.h into
750 bool ConstantExpr::isCast() const {
751 return Instruction::isCast(getOpcode());
754 bool ConstantExpr::isCompare() const {
755 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
758 bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
759 if (getOpcode() != Instruction::GetElementPtr) return false;
761 gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
762 User::const_op_iterator OI = llvm::next(this->op_begin());
764 // Skip the first index, as it has no static limit.
768 // The remaining indices must be compile-time known integers within the
769 // bounds of the corresponding notional static array types.
770 for (; GEPI != E; ++GEPI, ++OI) {
771 ConstantInt *CI = dyn_cast<ConstantInt>(*OI);
772 if (!CI) return false;
773 if (ArrayType *ATy = dyn_cast<ArrayType>(*GEPI))
774 if (CI->getValue().getActiveBits() > 64 ||
775 CI->getZExtValue() >= ATy->getNumElements())
779 // All the indices checked out.
783 bool ConstantExpr::hasIndices() const {
784 return getOpcode() == Instruction::ExtractValue ||
785 getOpcode() == Instruction::InsertValue;
788 ArrayRef<unsigned> ConstantExpr::getIndices() const {
789 if (const ExtractValueConstantExpr *EVCE =
790 dyn_cast<ExtractValueConstantExpr>(this))
791 return EVCE->Indices;
793 return cast<InsertValueConstantExpr>(this)->Indices;
796 unsigned ConstantExpr::getPredicate() const {
798 return ((const CompareConstantExpr*)this)->predicate;
801 /// getWithOperandReplaced - Return a constant expression identical to this
802 /// one, but with the specified operand set to the specified value.
804 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
805 assert(OpNo < getNumOperands() && "Operand num is out of range!");
806 assert(Op->getType() == getOperand(OpNo)->getType() &&
807 "Replacing operand with value of different type!");
808 if (getOperand(OpNo) == Op)
809 return const_cast<ConstantExpr*>(this);
811 Constant *Op0, *Op1, *Op2;
812 switch (getOpcode()) {
813 case Instruction::Trunc:
814 case Instruction::ZExt:
815 case Instruction::SExt:
816 case Instruction::FPTrunc:
817 case Instruction::FPExt:
818 case Instruction::UIToFP:
819 case Instruction::SIToFP:
820 case Instruction::FPToUI:
821 case Instruction::FPToSI:
822 case Instruction::PtrToInt:
823 case Instruction::IntToPtr:
824 case Instruction::BitCast:
825 return ConstantExpr::getCast(getOpcode(), Op, getType());
826 case Instruction::Select:
827 Op0 = (OpNo == 0) ? Op : getOperand(0);
828 Op1 = (OpNo == 1) ? Op : getOperand(1);
829 Op2 = (OpNo == 2) ? Op : getOperand(2);
830 return ConstantExpr::getSelect(Op0, Op1, Op2);
831 case Instruction::InsertElement:
832 Op0 = (OpNo == 0) ? Op : getOperand(0);
833 Op1 = (OpNo == 1) ? Op : getOperand(1);
834 Op2 = (OpNo == 2) ? Op : getOperand(2);
835 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
836 case Instruction::ExtractElement:
837 Op0 = (OpNo == 0) ? Op : getOperand(0);
838 Op1 = (OpNo == 1) ? Op : getOperand(1);
839 return ConstantExpr::getExtractElement(Op0, Op1);
840 case Instruction::ShuffleVector:
841 Op0 = (OpNo == 0) ? Op : getOperand(0);
842 Op1 = (OpNo == 1) ? Op : getOperand(1);
843 Op2 = (OpNo == 2) ? Op : getOperand(2);
844 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
845 case Instruction::GetElementPtr: {
846 SmallVector<Constant*, 8> Ops;
847 Ops.resize(getNumOperands()-1);
848 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
849 Ops[i-1] = getOperand(i);
852 ConstantExpr::getGetElementPtr(Op, Ops,
853 cast<GEPOperator>(this)->isInBounds());
856 ConstantExpr::getGetElementPtr(getOperand(0), Ops,
857 cast<GEPOperator>(this)->isInBounds());
860 assert(getNumOperands() == 2 && "Must be binary operator?");
861 Op0 = (OpNo == 0) ? Op : getOperand(0);
862 Op1 = (OpNo == 1) ? Op : getOperand(1);
863 return ConstantExpr::get(getOpcode(), Op0, Op1, SubclassOptionalData);
867 /// getWithOperands - This returns the current constant expression with the
868 /// operands replaced with the specified values. The specified array must
869 /// have the same number of operands as our current one.
870 Constant *ConstantExpr::
871 getWithOperands(ArrayRef<Constant*> Ops, Type *Ty) const {
872 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
873 bool AnyChange = Ty != getType();
874 for (unsigned i = 0; i != Ops.size(); ++i)
875 AnyChange |= Ops[i] != getOperand(i);
877 if (!AnyChange) // No operands changed, return self.
878 return const_cast<ConstantExpr*>(this);
880 switch (getOpcode()) {
881 case Instruction::Trunc:
882 case Instruction::ZExt:
883 case Instruction::SExt:
884 case Instruction::FPTrunc:
885 case Instruction::FPExt:
886 case Instruction::UIToFP:
887 case Instruction::SIToFP:
888 case Instruction::FPToUI:
889 case Instruction::FPToSI:
890 case Instruction::PtrToInt:
891 case Instruction::IntToPtr:
892 case Instruction::BitCast:
893 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty);
894 case Instruction::Select:
895 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
896 case Instruction::InsertElement:
897 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
898 case Instruction::ExtractElement:
899 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
900 case Instruction::ShuffleVector:
901 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
902 case Instruction::GetElementPtr:
904 ConstantExpr::getGetElementPtr(Ops[0], Ops.slice(1),
905 cast<GEPOperator>(this)->isInBounds());
906 case Instruction::ICmp:
907 case Instruction::FCmp:
908 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
910 assert(getNumOperands() == 2 && "Must be binary operator?");
911 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData);
916 //===----------------------------------------------------------------------===//
917 // isValueValidForType implementations
919 bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
920 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
921 if (Ty == Type::getInt1Ty(Ty->getContext()))
922 return Val == 0 || Val == 1;
924 return true; // always true, has to fit in largest type
925 uint64_t Max = (1ll << NumBits) - 1;
929 bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
930 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
931 if (Ty == Type::getInt1Ty(Ty->getContext()))
932 return Val == 0 || Val == 1 || Val == -1;
934 return true; // always true, has to fit in largest type
935 int64_t Min = -(1ll << (NumBits-1));
936 int64_t Max = (1ll << (NumBits-1)) - 1;
937 return (Val >= Min && Val <= Max);
940 bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {
941 // convert modifies in place, so make a copy.
942 APFloat Val2 = APFloat(Val);
944 switch (Ty->getTypeID()) {
946 return false; // These can't be represented as floating point!
948 // FIXME rounding mode needs to be more flexible
949 case Type::HalfTyID: {
950 if (&Val2.getSemantics() == &APFloat::IEEEhalf)
952 Val2.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &losesInfo);
955 case Type::FloatTyID: {
956 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
958 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
961 case Type::DoubleTyID: {
962 if (&Val2.getSemantics() == &APFloat::IEEEhalf ||
963 &Val2.getSemantics() == &APFloat::IEEEsingle ||
964 &Val2.getSemantics() == &APFloat::IEEEdouble)
966 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
969 case Type::X86_FP80TyID:
970 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
971 &Val2.getSemantics() == &APFloat::IEEEsingle ||
972 &Val2.getSemantics() == &APFloat::IEEEdouble ||
973 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
974 case Type::FP128TyID:
975 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
976 &Val2.getSemantics() == &APFloat::IEEEsingle ||
977 &Val2.getSemantics() == &APFloat::IEEEdouble ||
978 &Val2.getSemantics() == &APFloat::IEEEquad;
979 case Type::PPC_FP128TyID:
980 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
981 &Val2.getSemantics() == &APFloat::IEEEsingle ||
982 &Val2.getSemantics() == &APFloat::IEEEdouble ||
983 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
987 //===----------------------------------------------------------------------===//
988 // Factory Function Implementation
990 ConstantAggregateZero* ConstantAggregateZero::get(Type* Ty) {
991 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
992 "Cannot create an aggregate zero of non-aggregate type!");
994 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
995 return pImpl->AggZeroConstants.getOrCreate(Ty, 0);
998 /// destroyConstant - Remove the constant from the constant table...
1000 void ConstantAggregateZero::destroyConstant() {
1001 getType()->getContext().pImpl->AggZeroConstants.remove(this);
1002 destroyConstantImpl();
1005 /// destroyConstant - Remove the constant from the constant table...
1007 void ConstantArray::destroyConstant() {
1008 getType()->getContext().pImpl->ArrayConstants.remove(this);
1009 destroyConstantImpl();
1012 /// isString - This method returns true if the array is an array of i8, and
1013 /// if the elements of the array are all ConstantInt's.
1014 bool ConstantArray::isString() const {
1015 // Check the element type for i8...
1016 if (!getType()->getElementType()->isIntegerTy(8))
1018 // Check the elements to make sure they are all integers, not constant
1020 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1021 if (!isa<ConstantInt>(getOperand(i)))
1026 /// isCString - This method returns true if the array is a string (see
1027 /// isString) and it ends in a null byte \\0 and does not contains any other
1028 /// null bytes except its terminator.
1029 bool ConstantArray::isCString() const {
1030 // Check the element type for i8...
1031 if (!getType()->getElementType()->isIntegerTy(8))
1034 // Last element must be a null.
1035 if (!getOperand(getNumOperands()-1)->isNullValue())
1037 // Other elements must be non-null integers.
1038 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1039 if (!isa<ConstantInt>(getOperand(i)))
1041 if (getOperand(i)->isNullValue())
1048 /// convertToString - Helper function for getAsString() and getAsCString().
1049 static std::string convertToString(const User *U, unsigned len) {
1051 Result.reserve(len);
1052 for (unsigned i = 0; i != len; ++i)
1053 Result.push_back((char)cast<ConstantInt>(U->getOperand(i))->getZExtValue());
1057 /// getAsString - If this array is isString(), then this method converts the
1058 /// array to an std::string and returns it. Otherwise, it asserts out.
1060 std::string ConstantArray::getAsString() const {
1061 assert(isString() && "Not a string!");
1062 return convertToString(this, getNumOperands());
1066 /// getAsCString - If this array is isCString(), then this method converts the
1067 /// array (without the trailing null byte) to an std::string and returns it.
1068 /// Otherwise, it asserts out.
1070 std::string ConstantArray::getAsCString() const {
1071 assert(isCString() && "Not a string!");
1072 return convertToString(this, getNumOperands() - 1);
1076 //---- ConstantStruct::get() implementation...
1079 // destroyConstant - Remove the constant from the constant table...
1081 void ConstantStruct::destroyConstant() {
1082 getType()->getContext().pImpl->StructConstants.remove(this);
1083 destroyConstantImpl();
1086 // destroyConstant - Remove the constant from the constant table...
1088 void ConstantVector::destroyConstant() {
1089 getType()->getContext().pImpl->VectorConstants.remove(this);
1090 destroyConstantImpl();
1093 /// getSplatValue - If this is a splat constant, where all of the
1094 /// elements have the same value, return that value. Otherwise return null.
1095 Constant *ConstantVector::getSplatValue() const {
1096 // Check out first element.
1097 Constant *Elt = getOperand(0);
1098 // Then make sure all remaining elements point to the same value.
1099 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1100 if (getOperand(I) != Elt)
1105 //---- ConstantPointerNull::get() implementation.
1108 ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
1109 return Ty->getContext().pImpl->NullPtrConstants.getOrCreate(Ty, 0);
1112 // destroyConstant - Remove the constant from the constant table...
1114 void ConstantPointerNull::destroyConstant() {
1115 getType()->getContext().pImpl->NullPtrConstants.remove(this);
1116 destroyConstantImpl();
1120 //---- UndefValue::get() implementation.
1123 UndefValue *UndefValue::get(Type *Ty) {
1124 return Ty->getContext().pImpl->UndefValueConstants.getOrCreate(Ty, 0);
1127 // destroyConstant - Remove the constant from the constant table.
1129 void UndefValue::destroyConstant() {
1130 getType()->getContext().pImpl->UndefValueConstants.remove(this);
1131 destroyConstantImpl();
1134 //---- BlockAddress::get() implementation.
1137 BlockAddress *BlockAddress::get(BasicBlock *BB) {
1138 assert(BB->getParent() != 0 && "Block must have a parent");
1139 return get(BB->getParent(), BB);
1142 BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1144 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
1146 BA = new BlockAddress(F, BB);
1148 assert(BA->getFunction() == F && "Basic block moved between functions");
1152 BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1153 : Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1157 BB->AdjustBlockAddressRefCount(1);
1161 // destroyConstant - Remove the constant from the constant table.
1163 void BlockAddress::destroyConstant() {
1164 getFunction()->getType()->getContext().pImpl
1165 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
1166 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1167 destroyConstantImpl();
1170 void BlockAddress::replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U) {
1171 // This could be replacing either the Basic Block or the Function. In either
1172 // case, we have to remove the map entry.
1173 Function *NewF = getFunction();
1174 BasicBlock *NewBB = getBasicBlock();
1177 NewF = cast<Function>(To);
1179 NewBB = cast<BasicBlock>(To);
1181 // See if the 'new' entry already exists, if not, just update this in place
1182 // and return early.
1183 BlockAddress *&NewBA =
1184 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
1186 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1188 // Remove the old entry, this can't cause the map to rehash (just a
1189 // tombstone will get added).
1190 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1193 setOperand(0, NewF);
1194 setOperand(1, NewBB);
1195 getBasicBlock()->AdjustBlockAddressRefCount(1);
1199 // Otherwise, I do need to replace this with an existing value.
1200 assert(NewBA != this && "I didn't contain From!");
1202 // Everyone using this now uses the replacement.
1203 replaceAllUsesWith(NewBA);
1208 //---- ConstantExpr::get() implementations.
1211 /// This is a utility function to handle folding of casts and lookup of the
1212 /// cast in the ExprConstants map. It is used by the various get* methods below.
1213 static inline Constant *getFoldedCast(
1214 Instruction::CastOps opc, Constant *C, Type *Ty) {
1215 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1216 // Fold a few common cases
1217 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1220 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1222 // Look up the constant in the table first to ensure uniqueness
1223 std::vector<Constant*> argVec(1, C);
1224 ExprMapKeyType Key(opc, argVec);
1226 return pImpl->ExprConstants.getOrCreate(Ty, Key);
1229 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty) {
1230 Instruction::CastOps opc = Instruction::CastOps(oc);
1231 assert(Instruction::isCast(opc) && "opcode out of range");
1232 assert(C && Ty && "Null arguments to getCast");
1233 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
1237 llvm_unreachable("Invalid cast opcode");
1239 case Instruction::Trunc: return getTrunc(C, Ty);
1240 case Instruction::ZExt: return getZExt(C, Ty);
1241 case Instruction::SExt: return getSExt(C, Ty);
1242 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1243 case Instruction::FPExt: return getFPExtend(C, Ty);
1244 case Instruction::UIToFP: return getUIToFP(C, Ty);
1245 case Instruction::SIToFP: return getSIToFP(C, Ty);
1246 case Instruction::FPToUI: return getFPToUI(C, Ty);
1247 case Instruction::FPToSI: return getFPToSI(C, Ty);
1248 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1249 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1250 case Instruction::BitCast: return getBitCast(C, Ty);
1255 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) {
1256 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1257 return getBitCast(C, Ty);
1258 return getZExt(C, Ty);
1261 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) {
1262 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1263 return getBitCast(C, Ty);
1264 return getSExt(C, Ty);
1267 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {
1268 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1269 return getBitCast(C, Ty);
1270 return getTrunc(C, Ty);
1273 Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {
1274 assert(S->getType()->isPointerTy() && "Invalid cast");
1275 assert((Ty->isIntegerTy() || Ty->isPointerTy()) && "Invalid cast");
1277 if (Ty->isIntegerTy())
1278 return getPtrToInt(S, Ty);
1279 return getBitCast(S, Ty);
1282 Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty,
1284 assert(C->getType()->isIntOrIntVectorTy() &&
1285 Ty->isIntOrIntVectorTy() && "Invalid cast");
1286 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1287 unsigned DstBits = Ty->getScalarSizeInBits();
1288 Instruction::CastOps opcode =
1289 (SrcBits == DstBits ? Instruction::BitCast :
1290 (SrcBits > DstBits ? Instruction::Trunc :
1291 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1292 return getCast(opcode, C, Ty);
1295 Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) {
1296 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1298 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1299 unsigned DstBits = Ty->getScalarSizeInBits();
1300 if (SrcBits == DstBits)
1301 return C; // Avoid a useless cast
1302 Instruction::CastOps opcode =
1303 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1304 return getCast(opcode, C, Ty);
1307 Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty) {
1309 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1310 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1312 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1313 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
1314 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
1315 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1316 "SrcTy must be larger than DestTy for Trunc!");
1318 return getFoldedCast(Instruction::Trunc, C, Ty);
1321 Constant *ConstantExpr::getSExt(Constant *C, Type *Ty) {
1323 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1324 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1326 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1327 assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
1328 assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
1329 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1330 "SrcTy must be smaller than DestTy for SExt!");
1332 return getFoldedCast(Instruction::SExt, C, Ty);
1335 Constant *ConstantExpr::getZExt(Constant *C, Type *Ty) {
1337 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1338 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1340 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1341 assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
1342 assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
1343 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1344 "SrcTy must be smaller than DestTy for ZExt!");
1346 return getFoldedCast(Instruction::ZExt, C, Ty);
1349 Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty) {
1351 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1352 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1354 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1355 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1356 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1357 "This is an illegal floating point truncation!");
1358 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1361 Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty) {
1363 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1364 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1366 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1367 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1368 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1369 "This is an illegal floating point extension!");
1370 return getFoldedCast(Instruction::FPExt, C, Ty);
1373 Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty) {
1375 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1376 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1378 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1379 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1380 "This is an illegal uint to floating point cast!");
1381 return getFoldedCast(Instruction::UIToFP, C, Ty);
1384 Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty) {
1386 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1387 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1389 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1390 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1391 "This is an illegal sint to floating point cast!");
1392 return getFoldedCast(Instruction::SIToFP, C, Ty);
1395 Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty) {
1397 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1398 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1400 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1401 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1402 "This is an illegal floating point to uint cast!");
1403 return getFoldedCast(Instruction::FPToUI, C, Ty);
1406 Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty) {
1408 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1409 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1411 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1412 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1413 "This is an illegal floating point to sint cast!");
1414 return getFoldedCast(Instruction::FPToSI, C, Ty);
1417 Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy) {
1418 assert(C->getType()->getScalarType()->isPointerTy() &&
1419 "PtrToInt source must be pointer or pointer vector");
1420 assert(DstTy->getScalarType()->isIntegerTy() &&
1421 "PtrToInt destination must be integer or integer vector");
1422 assert(C->getType()->getNumElements() == DstTy->getNumElements() &&
1423 "Invalid cast between a different number of vector elements");
1424 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1427 Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy) {
1428 assert(C->getType()->getScalarType()->isIntegerTy() &&
1429 "IntToPtr source must be integer or integer vector");
1430 assert(DstTy->getScalarType()->isPointerTy() &&
1431 "IntToPtr destination must be a pointer or pointer vector");
1432 assert(C->getType()->getNumElements() == DstTy->getNumElements() &&
1433 "Invalid cast between a different number of vector elements");
1434 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1437 Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy) {
1438 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
1439 "Invalid constantexpr bitcast!");
1441 // It is common to ask for a bitcast of a value to its own type, handle this
1443 if (C->getType() == DstTy) return C;
1445 return getFoldedCast(Instruction::BitCast, C, DstTy);
1448 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
1450 // Check the operands for consistency first.
1451 assert(Opcode >= Instruction::BinaryOpsBegin &&
1452 Opcode < Instruction::BinaryOpsEnd &&
1453 "Invalid opcode in binary constant expression");
1454 assert(C1->getType() == C2->getType() &&
1455 "Operand types in binary constant expression should match");
1459 case Instruction::Add:
1460 case Instruction::Sub:
1461 case Instruction::Mul:
1462 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1463 assert(C1->getType()->isIntOrIntVectorTy() &&
1464 "Tried to create an integer operation on a non-integer type!");
1466 case Instruction::FAdd:
1467 case Instruction::FSub:
1468 case Instruction::FMul:
1469 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1470 assert(C1->getType()->isFPOrFPVectorTy() &&
1471 "Tried to create a floating-point operation on a "
1472 "non-floating-point type!");
1474 case Instruction::UDiv:
1475 case Instruction::SDiv:
1476 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1477 assert(C1->getType()->isIntOrIntVectorTy() &&
1478 "Tried to create an arithmetic operation on a non-arithmetic type!");
1480 case Instruction::FDiv:
1481 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1482 assert(C1->getType()->isFPOrFPVectorTy() &&
1483 "Tried to create an arithmetic operation on a non-arithmetic type!");
1485 case Instruction::URem:
1486 case Instruction::SRem:
1487 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1488 assert(C1->getType()->isIntOrIntVectorTy() &&
1489 "Tried to create an arithmetic operation on a non-arithmetic type!");
1491 case Instruction::FRem:
1492 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1493 assert(C1->getType()->isFPOrFPVectorTy() &&
1494 "Tried to create an arithmetic operation on a non-arithmetic type!");
1496 case Instruction::And:
1497 case Instruction::Or:
1498 case Instruction::Xor:
1499 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1500 assert(C1->getType()->isIntOrIntVectorTy() &&
1501 "Tried to create a logical operation on a non-integral type!");
1503 case Instruction::Shl:
1504 case Instruction::LShr:
1505 case Instruction::AShr:
1506 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1507 assert(C1->getType()->isIntOrIntVectorTy() &&
1508 "Tried to create a shift operation on a non-integer type!");
1515 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1516 return FC; // Fold a few common cases.
1518 std::vector<Constant*> argVec(1, C1);
1519 argVec.push_back(C2);
1520 ExprMapKeyType Key(Opcode, argVec, 0, Flags);
1522 LLVMContextImpl *pImpl = C1->getContext().pImpl;
1523 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
1526 Constant *ConstantExpr::getSizeOf(Type* Ty) {
1527 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1528 // Note that a non-inbounds gep is used, as null isn't within any object.
1529 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1530 Constant *GEP = getGetElementPtr(
1531 Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
1532 return getPtrToInt(GEP,
1533 Type::getInt64Ty(Ty->getContext()));
1536 Constant *ConstantExpr::getAlignOf(Type* Ty) {
1537 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
1538 // Note that a non-inbounds gep is used, as null isn't within any object.
1540 StructType::get(Type::getInt1Ty(Ty->getContext()), Ty, NULL);
1541 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo());
1542 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
1543 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1544 Constant *Indices[2] = { Zero, One };
1545 Constant *GEP = getGetElementPtr(NullPtr, Indices);
1546 return getPtrToInt(GEP,
1547 Type::getInt64Ty(Ty->getContext()));
1550 Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) {
1551 return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
1555 Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) {
1556 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1557 // Note that a non-inbounds gep is used, as null isn't within any object.
1558 Constant *GEPIdx[] = {
1559 ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
1562 Constant *GEP = getGetElementPtr(
1563 Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
1564 return getPtrToInt(GEP,
1565 Type::getInt64Ty(Ty->getContext()));
1568 Constant *ConstantExpr::getCompare(unsigned short Predicate,
1569 Constant *C1, Constant *C2) {
1570 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1572 switch (Predicate) {
1573 default: llvm_unreachable("Invalid CmpInst predicate");
1574 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1575 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1576 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1577 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1578 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1579 case CmpInst::FCMP_TRUE:
1580 return getFCmp(Predicate, C1, C2);
1582 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1583 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1584 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1585 case CmpInst::ICMP_SLE:
1586 return getICmp(Predicate, C1, C2);
1590 Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2) {
1591 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1593 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1594 return SC; // Fold common cases
1596 std::vector<Constant*> argVec(3, C);
1599 ExprMapKeyType Key(Instruction::Select, argVec);
1601 LLVMContextImpl *pImpl = C->getContext().pImpl;
1602 return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
1605 Constant *ConstantExpr::getGetElementPtr(Constant *C, ArrayRef<Value *> Idxs,
1607 if (Constant *FC = ConstantFoldGetElementPtr(C, InBounds, Idxs))
1608 return FC; // Fold a few common cases.
1610 // Get the result type of the getelementptr!
1611 Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), Idxs);
1612 assert(Ty && "GEP indices invalid!");
1613 unsigned AS = cast<PointerType>(C->getType())->getAddressSpace();
1614 Type *ReqTy = Ty->getPointerTo(AS);
1616 assert(C->getType()->isPointerTy() &&
1617 "Non-pointer type for constant GetElementPtr expression");
1618 // Look up the constant in the table first to ensure uniqueness
1619 std::vector<Constant*> ArgVec;
1620 ArgVec.reserve(1 + Idxs.size());
1621 ArgVec.push_back(C);
1622 for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
1623 ArgVec.push_back(cast<Constant>(Idxs[i]));
1624 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
1625 InBounds ? GEPOperator::IsInBounds : 0);
1627 LLVMContextImpl *pImpl = C->getContext().pImpl;
1628 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1632 ConstantExpr::getICmp(unsigned short pred, Constant *LHS, Constant *RHS) {
1633 assert(LHS->getType() == RHS->getType());
1634 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1635 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1637 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1638 return FC; // Fold a few common cases...
1640 // Look up the constant in the table first to ensure uniqueness
1641 std::vector<Constant*> ArgVec;
1642 ArgVec.push_back(LHS);
1643 ArgVec.push_back(RHS);
1644 // Get the key type with both the opcode and predicate
1645 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1647 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1648 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1649 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1651 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1652 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
1656 ConstantExpr::getFCmp(unsigned short pred, Constant *LHS, Constant *RHS) {
1657 assert(LHS->getType() == RHS->getType());
1658 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1660 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1661 return FC; // Fold a few common cases...
1663 // Look up the constant in the table first to ensure uniqueness
1664 std::vector<Constant*> ArgVec;
1665 ArgVec.push_back(LHS);
1666 ArgVec.push_back(RHS);
1667 // Get the key type with both the opcode and predicate
1668 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1670 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1671 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1672 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1674 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1675 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
1678 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1679 assert(Val->getType()->isVectorTy() &&
1680 "Tried to create extractelement operation on non-vector type!");
1681 assert(Idx->getType()->isIntegerTy(32) &&
1682 "Extractelement index must be i32 type!");
1684 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1685 return FC; // Fold a few common cases.
1687 // Look up the constant in the table first to ensure uniqueness
1688 std::vector<Constant*> ArgVec(1, Val);
1689 ArgVec.push_back(Idx);
1690 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1692 LLVMContextImpl *pImpl = Val->getContext().pImpl;
1693 Type *ReqTy = cast<VectorType>(Val->getType())->getElementType();
1694 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1697 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1699 assert(Val->getType()->isVectorTy() &&
1700 "Tried to create insertelement operation on non-vector type!");
1701 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
1702 && "Insertelement types must match!");
1703 assert(Idx->getType()->isIntegerTy(32) &&
1704 "Insertelement index must be i32 type!");
1706 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1707 return FC; // Fold a few common cases.
1708 // Look up the constant in the table first to ensure uniqueness
1709 std::vector<Constant*> ArgVec(1, Val);
1710 ArgVec.push_back(Elt);
1711 ArgVec.push_back(Idx);
1712 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1714 LLVMContextImpl *pImpl = Val->getContext().pImpl;
1715 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
1718 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1720 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1721 "Invalid shuffle vector constant expr operands!");
1723 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1724 return FC; // Fold a few common cases.
1726 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
1727 Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
1728 Type *ShufTy = VectorType::get(EltTy, NElts);
1730 // Look up the constant in the table first to ensure uniqueness
1731 std::vector<Constant*> ArgVec(1, V1);
1732 ArgVec.push_back(V2);
1733 ArgVec.push_back(Mask);
1734 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1736 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
1737 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
1740 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
1741 ArrayRef<unsigned> Idxs) {
1742 assert(ExtractValueInst::getIndexedType(Agg->getType(),
1743 Idxs) == Val->getType() &&
1744 "insertvalue indices invalid!");
1745 assert(Agg->getType()->isFirstClassType() &&
1746 "Non-first-class type for constant insertvalue expression");
1747 Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs);
1748 assert(FC && "insertvalue constant expr couldn't be folded!");
1752 Constant *ConstantExpr::getExtractValue(Constant *Agg,
1753 ArrayRef<unsigned> Idxs) {
1754 assert(Agg->getType()->isFirstClassType() &&
1755 "Tried to create extractelement operation on non-first-class type!");
1757 Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs);
1759 assert(ReqTy && "extractvalue indices invalid!");
1761 assert(Agg->getType()->isFirstClassType() &&
1762 "Non-first-class type for constant extractvalue expression");
1763 Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs);
1764 assert(FC && "ExtractValue constant expr couldn't be folded!");
1768 Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
1769 assert(C->getType()->isIntOrIntVectorTy() &&
1770 "Cannot NEG a nonintegral value!");
1771 return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
1775 Constant *ConstantExpr::getFNeg(Constant *C) {
1776 assert(C->getType()->isFPOrFPVectorTy() &&
1777 "Cannot FNEG a non-floating-point value!");
1778 return getFSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
1781 Constant *ConstantExpr::getNot(Constant *C) {
1782 assert(C->getType()->isIntOrIntVectorTy() &&
1783 "Cannot NOT a nonintegral value!");
1784 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
1787 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
1788 bool HasNUW, bool HasNSW) {
1789 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1790 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
1791 return get(Instruction::Add, C1, C2, Flags);
1794 Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
1795 return get(Instruction::FAdd, C1, C2);
1798 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
1799 bool HasNUW, bool HasNSW) {
1800 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1801 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
1802 return get(Instruction::Sub, C1, C2, Flags);
1805 Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
1806 return get(Instruction::FSub, C1, C2);
1809 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
1810 bool HasNUW, bool HasNSW) {
1811 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1812 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
1813 return get(Instruction::Mul, C1, C2, Flags);
1816 Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
1817 return get(Instruction::FMul, C1, C2);
1820 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
1821 return get(Instruction::UDiv, C1, C2,
1822 isExact ? PossiblyExactOperator::IsExact : 0);
1825 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
1826 return get(Instruction::SDiv, C1, C2,
1827 isExact ? PossiblyExactOperator::IsExact : 0);
1830 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
1831 return get(Instruction::FDiv, C1, C2);
1834 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
1835 return get(Instruction::URem, C1, C2);
1838 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
1839 return get(Instruction::SRem, C1, C2);
1842 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
1843 return get(Instruction::FRem, C1, C2);
1846 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
1847 return get(Instruction::And, C1, C2);
1850 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
1851 return get(Instruction::Or, C1, C2);
1854 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
1855 return get(Instruction::Xor, C1, C2);
1858 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
1859 bool HasNUW, bool HasNSW) {
1860 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1861 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
1862 return get(Instruction::Shl, C1, C2, Flags);
1865 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
1866 return get(Instruction::LShr, C1, C2,
1867 isExact ? PossiblyExactOperator::IsExact : 0);
1870 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
1871 return get(Instruction::AShr, C1, C2,
1872 isExact ? PossiblyExactOperator::IsExact : 0);
1875 // destroyConstant - Remove the constant from the constant table...
1877 void ConstantExpr::destroyConstant() {
1878 getType()->getContext().pImpl->ExprConstants.remove(this);
1879 destroyConstantImpl();
1882 const char *ConstantExpr::getOpcodeName() const {
1883 return Instruction::getOpcodeName(getOpcode());
1888 GetElementPtrConstantExpr::
1889 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
1891 : ConstantExpr(DestTy, Instruction::GetElementPtr,
1892 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
1893 - (IdxList.size()+1), IdxList.size()+1) {
1895 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
1896 OperandList[i+1] = IdxList[i];
1900 //===----------------------------------------------------------------------===//
1901 // replaceUsesOfWithOnConstant implementations
1903 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
1904 /// 'From' to be uses of 'To'. This must update the uniquing data structures
1907 /// Note that we intentionally replace all uses of From with To here. Consider
1908 /// a large array that uses 'From' 1000 times. By handling this case all here,
1909 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
1910 /// single invocation handles all 1000 uses. Handling them one at a time would
1911 /// work, but would be really slow because it would have to unique each updated
1914 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1916 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1917 Constant *ToC = cast<Constant>(To);
1919 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
1921 std::pair<LLVMContextImpl::ArrayConstantsTy::MapKey, ConstantArray*> Lookup;
1922 Lookup.first.first = cast<ArrayType>(getType());
1923 Lookup.second = this;
1925 std::vector<Constant*> &Values = Lookup.first.second;
1926 Values.reserve(getNumOperands()); // Build replacement array.
1928 // Fill values with the modified operands of the constant array. Also,
1929 // compute whether this turns into an all-zeros array.
1930 bool isAllZeros = false;
1931 unsigned NumUpdated = 0;
1932 if (!ToC->isNullValue()) {
1933 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1934 Constant *Val = cast<Constant>(O->get());
1939 Values.push_back(Val);
1943 for (Use *O = OperandList, *E = OperandList+getNumOperands();O != E; ++O) {
1944 Constant *Val = cast<Constant>(O->get());
1949 Values.push_back(Val);
1950 if (isAllZeros) isAllZeros = Val->isNullValue();
1954 Constant *Replacement = 0;
1956 Replacement = ConstantAggregateZero::get(getType());
1958 // Check to see if we have this array type already.
1960 LLVMContextImpl::ArrayConstantsTy::MapTy::iterator I =
1961 pImpl->ArrayConstants.InsertOrGetItem(Lookup, Exists);
1964 Replacement = I->second;
1966 // Okay, the new shape doesn't exist in the system yet. Instead of
1967 // creating a new constant array, inserting it, replaceallusesof'ing the
1968 // old with the new, then deleting the old... just update the current one
1970 pImpl->ArrayConstants.MoveConstantToNewSlot(this, I);
1972 // Update to the new value. Optimize for the case when we have a single
1973 // operand that we're changing, but handle bulk updates efficiently.
1974 if (NumUpdated == 1) {
1975 unsigned OperandToUpdate = U - OperandList;
1976 assert(getOperand(OperandToUpdate) == From &&
1977 "ReplaceAllUsesWith broken!");
1978 setOperand(OperandToUpdate, ToC);
1980 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1981 if (getOperand(i) == From)
1988 // Otherwise, I do need to replace this with an existing value.
1989 assert(Replacement != this && "I didn't contain From!");
1991 // Everyone using this now uses the replacement.
1992 replaceAllUsesWith(Replacement);
1994 // Delete the old constant!
1998 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2000 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2001 Constant *ToC = cast<Constant>(To);
2003 unsigned OperandToUpdate = U-OperandList;
2004 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2006 std::pair<LLVMContextImpl::StructConstantsTy::MapKey, ConstantStruct*> Lookup;
2007 Lookup.first.first = cast<StructType>(getType());
2008 Lookup.second = this;
2009 std::vector<Constant*> &Values = Lookup.first.second;
2010 Values.reserve(getNumOperands()); // Build replacement struct.
2013 // Fill values with the modified operands of the constant struct. Also,
2014 // compute whether this turns into an all-zeros struct.
2015 bool isAllZeros = false;
2016 if (!ToC->isNullValue()) {
2017 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
2018 Values.push_back(cast<Constant>(O->get()));
2021 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2022 Constant *Val = cast<Constant>(O->get());
2023 Values.push_back(Val);
2024 if (isAllZeros) isAllZeros = Val->isNullValue();
2027 Values[OperandToUpdate] = ToC;
2029 LLVMContextImpl *pImpl = getContext().pImpl;
2031 Constant *Replacement = 0;
2033 Replacement = ConstantAggregateZero::get(getType());
2035 // Check to see if we have this struct 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 replaceAllUsesWith(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(Values);
2077 assert(Replacement != this && "I didn't contain From!");
2079 // Everyone using this now uses the replacement.
2080 replaceAllUsesWith(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, Indices,
2104 cast<GEPOperator>(this)->isInBounds());
2105 } else if (getOpcode() == Instruction::ExtractValue) {
2106 Constant *Agg = getOperand(0);
2107 if (Agg == From) Agg = To;
2109 ArrayRef<unsigned> Indices = getIndices();
2110 Replacement = ConstantExpr::getExtractValue(Agg, Indices);
2111 } else if (getOpcode() == Instruction::InsertValue) {
2112 Constant *Agg = getOperand(0);
2113 Constant *Val = getOperand(1);
2114 if (Agg == From) Agg = To;
2115 if (Val == From) Val = To;
2117 ArrayRef<unsigned> Indices = getIndices();
2118 Replacement = ConstantExpr::getInsertValue(Agg, Val, Indices);
2119 } else if (isCast()) {
2120 assert(getOperand(0) == From && "Cast only has one use!");
2121 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2122 } else if (getOpcode() == Instruction::Select) {
2123 Constant *C1 = getOperand(0);
2124 Constant *C2 = getOperand(1);
2125 Constant *C3 = getOperand(2);
2126 if (C1 == From) C1 = To;
2127 if (C2 == From) C2 = To;
2128 if (C3 == From) C3 = To;
2129 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2130 } else if (getOpcode() == Instruction::ExtractElement) {
2131 Constant *C1 = getOperand(0);
2132 Constant *C2 = getOperand(1);
2133 if (C1 == From) C1 = To;
2134 if (C2 == From) C2 = To;
2135 Replacement = ConstantExpr::getExtractElement(C1, C2);
2136 } else if (getOpcode() == Instruction::InsertElement) {
2137 Constant *C1 = getOperand(0);
2138 Constant *C2 = getOperand(1);
2139 Constant *C3 = getOperand(1);
2140 if (C1 == From) C1 = To;
2141 if (C2 == From) C2 = To;
2142 if (C3 == From) C3 = To;
2143 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2144 } else if (getOpcode() == Instruction::ShuffleVector) {
2145 Constant *C1 = getOperand(0);
2146 Constant *C2 = getOperand(1);
2147 Constant *C3 = getOperand(2);
2148 if (C1 == From) C1 = To;
2149 if (C2 == From) C2 = To;
2150 if (C3 == From) C3 = To;
2151 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2152 } else if (isCompare()) {
2153 Constant *C1 = getOperand(0);
2154 Constant *C2 = getOperand(1);
2155 if (C1 == From) C1 = To;
2156 if (C2 == From) C2 = To;
2157 if (getOpcode() == Instruction::ICmp)
2158 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2160 assert(getOpcode() == Instruction::FCmp);
2161 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2163 } else if (getNumOperands() == 2) {
2164 Constant *C1 = getOperand(0);
2165 Constant *C2 = getOperand(1);
2166 if (C1 == From) C1 = To;
2167 if (C2 == From) C2 = To;
2168 Replacement = ConstantExpr::get(getOpcode(), C1, C2, SubclassOptionalData);
2170 llvm_unreachable("Unknown ConstantExpr type!");
2174 assert(Replacement != this && "I didn't contain From!");
2176 // Everyone using this now uses the replacement.
2177 replaceAllUsesWith(Replacement);
2179 // Delete the old constant!