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/IR/Constants.h"
15 #include "ConstantFold.h"
16 #include "LLVMContextImpl.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/FoldingSet.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/StringMap.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/GetElementPtrTypeIterator.h"
25 #include "llvm/IR/GlobalValue.h"
26 #include "llvm/IR/Instructions.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/Operator.h"
29 #include "llvm/Support/Compiler.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/ManagedStatic.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
39 //===----------------------------------------------------------------------===//
41 //===----------------------------------------------------------------------===//
43 void Constant::anchor() { }
45 bool Constant::isNegativeZeroValue() const {
46 // Floating point values have an explicit -0.0 value.
47 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
48 return CFP->isZero() && CFP->isNegative();
50 // Equivalent for a vector of -0.0's.
51 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
52 if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
53 if (SplatCFP && SplatCFP->isZero() && SplatCFP->isNegative())
56 // We've already handled true FP case; any other FP vectors can't represent -0.0.
57 if (getType()->isFPOrFPVectorTy())
60 // Otherwise, just use +0.0.
64 // Return true iff this constant is positive zero (floating point), negative
65 // zero (floating point), or a null value.
66 bool Constant::isZeroValue() const {
67 // Floating point values have an explicit -0.0 value.
68 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
71 // Otherwise, just use +0.0.
75 bool Constant::isNullValue() const {
77 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
81 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
82 return CFP->isZero() && !CFP->isNegative();
84 // constant zero is zero for aggregates and cpnull is null for pointers.
85 return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this);
88 bool Constant::isAllOnesValue() const {
89 // Check for -1 integers
90 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
91 return CI->isMinusOne();
93 // Check for FP which are bitcasted from -1 integers
94 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
95 return CFP->getValueAPF().bitcastToAPInt().isAllOnesValue();
97 // Check for constant vectors which are splats of -1 values.
98 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
99 if (Constant *Splat = CV->getSplatValue())
100 return Splat->isAllOnesValue();
102 // Check for constant vectors which are splats of -1 values.
103 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
104 if (Constant *Splat = CV->getSplatValue())
105 return Splat->isAllOnesValue();
110 bool Constant::isOneValue() const {
111 // Check for 1 integers
112 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
115 // Check for FP which are bitcasted from 1 integers
116 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
117 return CFP->getValueAPF().bitcastToAPInt() == 1;
119 // Check for constant vectors which are splats of 1 values.
120 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
121 if (Constant *Splat = CV->getSplatValue())
122 return Splat->isOneValue();
124 // Check for constant vectors which are splats of 1 values.
125 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
126 if (Constant *Splat = CV->getSplatValue())
127 return Splat->isOneValue();
132 bool Constant::isMinSignedValue() const {
133 // Check for INT_MIN integers
134 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
135 return CI->isMinValue(/*isSigned=*/true);
137 // Check for FP which are bitcasted from INT_MIN integers
138 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
139 return CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
141 // Check for constant vectors which are splats of INT_MIN values.
142 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
143 if (Constant *Splat = CV->getSplatValue())
144 return Splat->isMinSignedValue();
146 // Check for constant vectors which are splats of INT_MIN values.
147 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
148 if (Constant *Splat = CV->getSplatValue())
149 return Splat->isMinSignedValue();
154 bool Constant::isNotMinSignedValue() const {
155 // Check for INT_MIN integers
156 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
157 return !CI->isMinValue(/*isSigned=*/true);
159 // Check for FP which are bitcasted from INT_MIN integers
160 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
161 return !CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
163 // Check for constant vectors which are splats of INT_MIN values.
164 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
165 if (Constant *Splat = CV->getSplatValue())
166 return Splat->isNotMinSignedValue();
168 // Check for constant vectors which are splats of INT_MIN values.
169 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
170 if (Constant *Splat = CV->getSplatValue())
171 return Splat->isNotMinSignedValue();
173 // It *may* contain INT_MIN, we can't tell.
177 // Constructor to create a '0' constant of arbitrary type...
178 Constant *Constant::getNullValue(Type *Ty) {
179 switch (Ty->getTypeID()) {
180 case Type::IntegerTyID:
181 return ConstantInt::get(Ty, 0);
183 return ConstantFP::get(Ty->getContext(),
184 APFloat::getZero(APFloat::IEEEhalf));
185 case Type::FloatTyID:
186 return ConstantFP::get(Ty->getContext(),
187 APFloat::getZero(APFloat::IEEEsingle));
188 case Type::DoubleTyID:
189 return ConstantFP::get(Ty->getContext(),
190 APFloat::getZero(APFloat::IEEEdouble));
191 case Type::X86_FP80TyID:
192 return ConstantFP::get(Ty->getContext(),
193 APFloat::getZero(APFloat::x87DoubleExtended));
194 case Type::FP128TyID:
195 return ConstantFP::get(Ty->getContext(),
196 APFloat::getZero(APFloat::IEEEquad));
197 case Type::PPC_FP128TyID:
198 return ConstantFP::get(Ty->getContext(),
199 APFloat(APFloat::PPCDoubleDouble,
200 APInt::getNullValue(128)));
201 case Type::PointerTyID:
202 return ConstantPointerNull::get(cast<PointerType>(Ty));
203 case Type::StructTyID:
204 case Type::ArrayTyID:
205 case Type::VectorTyID:
206 return ConstantAggregateZero::get(Ty);
208 // Function, Label, or Opaque type?
209 llvm_unreachable("Cannot create a null constant of that type!");
213 Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) {
214 Type *ScalarTy = Ty->getScalarType();
216 // Create the base integer constant.
217 Constant *C = ConstantInt::get(Ty->getContext(), V);
219 // Convert an integer to a pointer, if necessary.
220 if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
221 C = ConstantExpr::getIntToPtr(C, PTy);
223 // Broadcast a scalar to a vector, if necessary.
224 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
225 C = ConstantVector::getSplat(VTy->getNumElements(), C);
230 Constant *Constant::getAllOnesValue(Type *Ty) {
231 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
232 return ConstantInt::get(Ty->getContext(),
233 APInt::getAllOnesValue(ITy->getBitWidth()));
235 if (Ty->isFloatingPointTy()) {
236 APFloat FL = APFloat::getAllOnesValue(Ty->getPrimitiveSizeInBits(),
237 !Ty->isPPC_FP128Ty());
238 return ConstantFP::get(Ty->getContext(), FL);
241 VectorType *VTy = cast<VectorType>(Ty);
242 return ConstantVector::getSplat(VTy->getNumElements(),
243 getAllOnesValue(VTy->getElementType()));
246 /// getAggregateElement - For aggregates (struct/array/vector) return the
247 /// constant that corresponds to the specified element if possible, or null if
248 /// not. This can return null if the element index is a ConstantExpr, or if
249 /// 'this' is a constant expr.
250 Constant *Constant::getAggregateElement(unsigned Elt) const {
251 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(this))
252 return Elt < CS->getNumOperands() ? CS->getOperand(Elt) : nullptr;
254 if (const ConstantArray *CA = dyn_cast<ConstantArray>(this))
255 return Elt < CA->getNumOperands() ? CA->getOperand(Elt) : nullptr;
257 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
258 return Elt < CV->getNumOperands() ? CV->getOperand(Elt) : nullptr;
260 if (const ConstantAggregateZero *CAZ =dyn_cast<ConstantAggregateZero>(this))
261 return CAZ->getElementValue(Elt);
263 if (const UndefValue *UV = dyn_cast<UndefValue>(this))
264 return UV->getElementValue(Elt);
266 if (const ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(this))
267 return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt)
272 Constant *Constant::getAggregateElement(Constant *Elt) const {
273 assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
274 if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt))
275 return getAggregateElement(CI->getZExtValue());
280 void Constant::destroyConstantImpl() {
281 // When a Constant is destroyed, there may be lingering
282 // references to the constant by other constants in the constant pool. These
283 // constants are implicitly dependent on the module that is being deleted,
284 // but they don't know that. Because we only find out when the CPV is
285 // deleted, we must now notify all of our users (that should only be
286 // Constants) that they are, in fact, invalid now and should be deleted.
288 while (!use_empty()) {
289 Value *V = user_back();
290 #ifndef NDEBUG // Only in -g mode...
291 if (!isa<Constant>(V)) {
292 dbgs() << "While deleting: " << *this
293 << "\n\nUse still stuck around after Def is destroyed: "
297 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
298 cast<Constant>(V)->destroyConstant();
300 // The constant should remove itself from our use list...
301 assert((use_empty() || user_back() != V) && "Constant not removed!");
304 // Value has no outstanding references it is safe to delete it now...
308 static bool canTrapImpl(const Constant *C,
309 SmallPtrSetImpl<const ConstantExpr *> &NonTrappingOps) {
310 assert(C->getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
311 // The only thing that could possibly trap are constant exprs.
312 const ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
316 // ConstantExpr traps if any operands can trap.
317 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
318 if (ConstantExpr *Op = dyn_cast<ConstantExpr>(CE->getOperand(i))) {
319 if (NonTrappingOps.insert(Op) && canTrapImpl(Op, NonTrappingOps))
324 // Otherwise, only specific operations can trap.
325 switch (CE->getOpcode()) {
328 case Instruction::UDiv:
329 case Instruction::SDiv:
330 case Instruction::FDiv:
331 case Instruction::URem:
332 case Instruction::SRem:
333 case Instruction::FRem:
334 // Div and rem can trap if the RHS is not known to be non-zero.
335 if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
341 /// canTrap - Return true if evaluation of this constant could trap. This is
342 /// true for things like constant expressions that could divide by zero.
343 bool Constant::canTrap() const {
344 SmallPtrSet<const ConstantExpr *, 4> NonTrappingOps;
345 return canTrapImpl(this, NonTrappingOps);
348 /// Check if C contains a GlobalValue for which Predicate is true.
350 ConstHasGlobalValuePredicate(const Constant *C,
351 bool (*Predicate)(const GlobalValue *)) {
352 SmallPtrSet<const Constant *, 8> Visited;
353 SmallVector<const Constant *, 8> WorkList;
354 WorkList.push_back(C);
357 while (!WorkList.empty()) {
358 const Constant *WorkItem = WorkList.pop_back_val();
359 if (const auto *GV = dyn_cast<GlobalValue>(WorkItem))
362 for (const Value *Op : WorkItem->operands()) {
363 const Constant *ConstOp = dyn_cast<Constant>(Op);
366 if (Visited.insert(ConstOp))
367 WorkList.push_back(ConstOp);
373 /// Return true if the value can vary between threads.
374 bool Constant::isThreadDependent() const {
375 auto DLLImportPredicate = [](const GlobalValue *GV) {
376 return GV->isThreadLocal();
378 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
381 bool Constant::isDLLImportDependent() const {
382 auto DLLImportPredicate = [](const GlobalValue *GV) {
383 return GV->hasDLLImportStorageClass();
385 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
388 /// Return true if the constant has users other than constant exprs and other
390 bool Constant::isConstantUsed() const {
391 for (const User *U : users()) {
392 const Constant *UC = dyn_cast<Constant>(U);
393 if (!UC || isa<GlobalValue>(UC))
396 if (UC->isConstantUsed())
404 /// getRelocationInfo - This method classifies the entry according to
405 /// whether or not it may generate a relocation entry. This must be
406 /// conservative, so if it might codegen to a relocatable entry, it should say
407 /// so. The return values are:
409 /// NoRelocation: This constant pool entry is guaranteed to never have a
410 /// relocation applied to it (because it holds a simple constant like
412 /// LocalRelocation: This entry has relocations, but the entries are
413 /// guaranteed to be resolvable by the static linker, so the dynamic
414 /// linker will never see them.
415 /// GlobalRelocations: This entry may have arbitrary relocations.
417 /// FIXME: This really should not be in IR.
418 Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
419 if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
420 if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
421 return LocalRelocation; // Local to this file/library.
422 return GlobalRelocations; // Global reference.
425 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
426 return BA->getFunction()->getRelocationInfo();
428 // While raw uses of blockaddress need to be relocated, differences between
429 // two of them don't when they are for labels in the same function. This is a
430 // common idiom when creating a table for the indirect goto extension, so we
431 // handle it efficiently here.
432 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this))
433 if (CE->getOpcode() == Instruction::Sub) {
434 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
435 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
437 LHS->getOpcode() == Instruction::PtrToInt &&
438 RHS->getOpcode() == Instruction::PtrToInt &&
439 isa<BlockAddress>(LHS->getOperand(0)) &&
440 isa<BlockAddress>(RHS->getOperand(0)) &&
441 cast<BlockAddress>(LHS->getOperand(0))->getFunction() ==
442 cast<BlockAddress>(RHS->getOperand(0))->getFunction())
446 PossibleRelocationsTy Result = NoRelocation;
447 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
448 Result = std::max(Result,
449 cast<Constant>(getOperand(i))->getRelocationInfo());
454 /// removeDeadUsersOfConstant - If the specified constantexpr is dead, remove
455 /// it. This involves recursively eliminating any dead users of the
457 static bool removeDeadUsersOfConstant(const Constant *C) {
458 if (isa<GlobalValue>(C)) return false; // Cannot remove this
460 while (!C->use_empty()) {
461 const Constant *User = dyn_cast<Constant>(C->user_back());
462 if (!User) return false; // Non-constant usage;
463 if (!removeDeadUsersOfConstant(User))
464 return false; // Constant wasn't dead
467 const_cast<Constant*>(C)->destroyConstant();
472 /// removeDeadConstantUsers - If there are any dead constant users dangling
473 /// off of this constant, remove them. This method is useful for clients
474 /// that want to check to see if a global is unused, but don't want to deal
475 /// with potentially dead constants hanging off of the globals.
476 void Constant::removeDeadConstantUsers() const {
477 Value::const_user_iterator I = user_begin(), E = user_end();
478 Value::const_user_iterator LastNonDeadUser = E;
480 const Constant *User = dyn_cast<Constant>(*I);
487 if (!removeDeadUsersOfConstant(User)) {
488 // If the constant wasn't dead, remember that this was the last live use
489 // and move on to the next constant.
495 // If the constant was dead, then the iterator is invalidated.
496 if (LastNonDeadUser == E) {
508 //===----------------------------------------------------------------------===//
510 //===----------------------------------------------------------------------===//
512 void ConstantInt::anchor() { }
514 ConstantInt::ConstantInt(IntegerType *Ty, const APInt& V)
515 : Constant(Ty, ConstantIntVal, nullptr, 0), Val(V) {
516 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
519 ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
520 LLVMContextImpl *pImpl = Context.pImpl;
521 if (!pImpl->TheTrueVal)
522 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
523 return pImpl->TheTrueVal;
526 ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
527 LLVMContextImpl *pImpl = Context.pImpl;
528 if (!pImpl->TheFalseVal)
529 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
530 return pImpl->TheFalseVal;
533 Constant *ConstantInt::getTrue(Type *Ty) {
534 VectorType *VTy = dyn_cast<VectorType>(Ty);
536 assert(Ty->isIntegerTy(1) && "True must be i1 or vector of i1.");
537 return ConstantInt::getTrue(Ty->getContext());
539 assert(VTy->getElementType()->isIntegerTy(1) &&
540 "True must be vector of i1 or i1.");
541 return ConstantVector::getSplat(VTy->getNumElements(),
542 ConstantInt::getTrue(Ty->getContext()));
545 Constant *ConstantInt::getFalse(Type *Ty) {
546 VectorType *VTy = dyn_cast<VectorType>(Ty);
548 assert(Ty->isIntegerTy(1) && "False must be i1 or vector of i1.");
549 return ConstantInt::getFalse(Ty->getContext());
551 assert(VTy->getElementType()->isIntegerTy(1) &&
552 "False must be vector of i1 or i1.");
553 return ConstantVector::getSplat(VTy->getNumElements(),
554 ConstantInt::getFalse(Ty->getContext()));
558 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
559 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
560 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
561 // compare APInt's of different widths, which would violate an APInt class
562 // invariant which generates an assertion.
563 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
564 // Get the corresponding integer type for the bit width of the value.
565 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
566 // get an existing value or the insertion position
567 LLVMContextImpl *pImpl = Context.pImpl;
568 ConstantInt *&Slot = pImpl->IntConstants[DenseMapAPIntKeyInfo::KeyTy(V, ITy)];
569 if (!Slot) Slot = new ConstantInt(ITy, V);
573 Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
574 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
576 // For vectors, broadcast the value.
577 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
578 return ConstantVector::getSplat(VTy->getNumElements(), C);
583 ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V,
585 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
588 ConstantInt *ConstantInt::getSigned(IntegerType *Ty, int64_t V) {
589 return get(Ty, V, true);
592 Constant *ConstantInt::getSigned(Type *Ty, int64_t V) {
593 return get(Ty, V, true);
596 Constant *ConstantInt::get(Type *Ty, const APInt& V) {
597 ConstantInt *C = get(Ty->getContext(), V);
598 assert(C->getType() == Ty->getScalarType() &&
599 "ConstantInt type doesn't match the type implied by its value!");
601 // For vectors, broadcast the value.
602 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
603 return ConstantVector::getSplat(VTy->getNumElements(), C);
608 ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str,
610 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
613 //===----------------------------------------------------------------------===//
615 //===----------------------------------------------------------------------===//
617 static const fltSemantics *TypeToFloatSemantics(Type *Ty) {
619 return &APFloat::IEEEhalf;
621 return &APFloat::IEEEsingle;
622 if (Ty->isDoubleTy())
623 return &APFloat::IEEEdouble;
624 if (Ty->isX86_FP80Ty())
625 return &APFloat::x87DoubleExtended;
626 else if (Ty->isFP128Ty())
627 return &APFloat::IEEEquad;
629 assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
630 return &APFloat::PPCDoubleDouble;
633 void ConstantFP::anchor() { }
635 /// get() - This returns a constant fp for the specified value in the
636 /// specified type. This should only be used for simple constant values like
637 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
638 Constant *ConstantFP::get(Type *Ty, double V) {
639 LLVMContext &Context = Ty->getContext();
643 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
644 APFloat::rmNearestTiesToEven, &ignored);
645 Constant *C = get(Context, FV);
647 // For vectors, broadcast the value.
648 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
649 return ConstantVector::getSplat(VTy->getNumElements(), C);
655 Constant *ConstantFP::get(Type *Ty, StringRef Str) {
656 LLVMContext &Context = Ty->getContext();
658 APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
659 Constant *C = get(Context, FV);
661 // For vectors, broadcast the value.
662 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
663 return ConstantVector::getSplat(VTy->getNumElements(), C);
668 Constant *ConstantFP::getNegativeZero(Type *Ty) {
669 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
670 APFloat NegZero = APFloat::getZero(Semantics, /*Negative=*/true);
671 Constant *C = get(Ty->getContext(), NegZero);
673 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
674 return ConstantVector::getSplat(VTy->getNumElements(), C);
680 Constant *ConstantFP::getZeroValueForNegation(Type *Ty) {
681 if (Ty->isFPOrFPVectorTy())
682 return getNegativeZero(Ty);
684 return Constant::getNullValue(Ty);
688 // ConstantFP accessors.
689 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
690 LLVMContextImpl* pImpl = Context.pImpl;
692 ConstantFP *&Slot = pImpl->FPConstants[DenseMapAPFloatKeyInfo::KeyTy(V)];
696 if (&V.getSemantics() == &APFloat::IEEEhalf)
697 Ty = Type::getHalfTy(Context);
698 else if (&V.getSemantics() == &APFloat::IEEEsingle)
699 Ty = Type::getFloatTy(Context);
700 else if (&V.getSemantics() == &APFloat::IEEEdouble)
701 Ty = Type::getDoubleTy(Context);
702 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
703 Ty = Type::getX86_FP80Ty(Context);
704 else if (&V.getSemantics() == &APFloat::IEEEquad)
705 Ty = Type::getFP128Ty(Context);
707 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
708 "Unknown FP format");
709 Ty = Type::getPPC_FP128Ty(Context);
711 Slot = new ConstantFP(Ty, V);
717 Constant *ConstantFP::getInfinity(Type *Ty, bool Negative) {
718 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
719 Constant *C = get(Ty->getContext(), APFloat::getInf(Semantics, Negative));
721 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
722 return ConstantVector::getSplat(VTy->getNumElements(), C);
727 ConstantFP::ConstantFP(Type *Ty, const APFloat& V)
728 : Constant(Ty, ConstantFPVal, nullptr, 0), Val(V) {
729 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
733 bool ConstantFP::isExactlyValue(const APFloat &V) const {
734 return Val.bitwiseIsEqual(V);
737 //===----------------------------------------------------------------------===//
738 // ConstantAggregateZero Implementation
739 //===----------------------------------------------------------------------===//
741 /// getSequentialElement - If this CAZ has array or vector type, return a zero
742 /// with the right element type.
743 Constant *ConstantAggregateZero::getSequentialElement() const {
744 return Constant::getNullValue(getType()->getSequentialElementType());
747 /// getStructElement - If this CAZ has struct type, return a zero with the
748 /// right element type for the specified element.
749 Constant *ConstantAggregateZero::getStructElement(unsigned Elt) const {
750 return Constant::getNullValue(getType()->getStructElementType(Elt));
753 /// getElementValue - Return a zero of the right value for the specified GEP
754 /// index if we can, otherwise return null (e.g. if C is a ConstantExpr).
755 Constant *ConstantAggregateZero::getElementValue(Constant *C) const {
756 if (isa<SequentialType>(getType()))
757 return getSequentialElement();
758 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
761 /// getElementValue - Return a zero of the right value for the specified GEP
763 Constant *ConstantAggregateZero::getElementValue(unsigned Idx) const {
764 if (isa<SequentialType>(getType()))
765 return getSequentialElement();
766 return getStructElement(Idx);
770 //===----------------------------------------------------------------------===//
771 // UndefValue Implementation
772 //===----------------------------------------------------------------------===//
774 /// getSequentialElement - If this undef has array or vector type, return an
775 /// undef with the right element type.
776 UndefValue *UndefValue::getSequentialElement() const {
777 return UndefValue::get(getType()->getSequentialElementType());
780 /// getStructElement - If this undef has struct type, return a zero with the
781 /// right element type for the specified element.
782 UndefValue *UndefValue::getStructElement(unsigned Elt) const {
783 return UndefValue::get(getType()->getStructElementType(Elt));
786 /// getElementValue - Return an undef of the right value for the specified GEP
787 /// index if we can, otherwise return null (e.g. if C is a ConstantExpr).
788 UndefValue *UndefValue::getElementValue(Constant *C) const {
789 if (isa<SequentialType>(getType()))
790 return getSequentialElement();
791 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
794 /// getElementValue - Return an undef of the right value for the specified GEP
796 UndefValue *UndefValue::getElementValue(unsigned Idx) const {
797 if (isa<SequentialType>(getType()))
798 return getSequentialElement();
799 return getStructElement(Idx);
804 //===----------------------------------------------------------------------===//
805 // ConstantXXX Classes
806 //===----------------------------------------------------------------------===//
808 template <typename ItTy, typename EltTy>
809 static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
810 for (; Start != End; ++Start)
816 ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
817 : Constant(T, ConstantArrayVal,
818 OperandTraits<ConstantArray>::op_end(this) - V.size(),
820 assert(V.size() == T->getNumElements() &&
821 "Invalid initializer vector for constant array");
822 for (unsigned i = 0, e = V.size(); i != e; ++i)
823 assert(V[i]->getType() == T->getElementType() &&
824 "Initializer for array element doesn't match array element type!");
825 std::copy(V.begin(), V.end(), op_begin());
828 Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
829 if (Constant *C = getImpl(Ty, V))
831 return Ty->getContext().pImpl->ArrayConstants.getOrCreate(Ty, V);
833 Constant *ConstantArray::getImpl(ArrayType *Ty, ArrayRef<Constant*> V) {
834 // Empty arrays are canonicalized to ConstantAggregateZero.
836 return ConstantAggregateZero::get(Ty);
838 for (unsigned i = 0, e = V.size(); i != e; ++i) {
839 assert(V[i]->getType() == Ty->getElementType() &&
840 "Wrong type in array element initializer");
843 // If this is an all-zero array, return a ConstantAggregateZero object. If
844 // all undef, return an UndefValue, if "all simple", then return a
845 // ConstantDataArray.
847 if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
848 return UndefValue::get(Ty);
850 if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
851 return ConstantAggregateZero::get(Ty);
853 // Check to see if all of the elements are ConstantFP or ConstantInt and if
854 // the element type is compatible with ConstantDataVector. If so, use it.
855 if (ConstantDataSequential::isElementTypeCompatible(C->getType())) {
856 // We speculatively build the elements here even if it turns out that there
857 // is a constantexpr or something else weird in the array, since it is so
858 // uncommon for that to happen.
859 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
860 if (CI->getType()->isIntegerTy(8)) {
861 SmallVector<uint8_t, 16> Elts;
862 for (unsigned i = 0, e = V.size(); i != e; ++i)
863 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
864 Elts.push_back(CI->getZExtValue());
867 if (Elts.size() == V.size())
868 return ConstantDataArray::get(C->getContext(), Elts);
869 } else if (CI->getType()->isIntegerTy(16)) {
870 SmallVector<uint16_t, 16> Elts;
871 for (unsigned i = 0, e = V.size(); i != e; ++i)
872 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
873 Elts.push_back(CI->getZExtValue());
876 if (Elts.size() == V.size())
877 return ConstantDataArray::get(C->getContext(), Elts);
878 } else if (CI->getType()->isIntegerTy(32)) {
879 SmallVector<uint32_t, 16> Elts;
880 for (unsigned i = 0, e = V.size(); i != e; ++i)
881 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
882 Elts.push_back(CI->getZExtValue());
885 if (Elts.size() == V.size())
886 return ConstantDataArray::get(C->getContext(), Elts);
887 } else if (CI->getType()->isIntegerTy(64)) {
888 SmallVector<uint64_t, 16> Elts;
889 for (unsigned i = 0, e = V.size(); i != e; ++i)
890 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
891 Elts.push_back(CI->getZExtValue());
894 if (Elts.size() == V.size())
895 return ConstantDataArray::get(C->getContext(), Elts);
899 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
900 if (CFP->getType()->isFloatTy()) {
901 SmallVector<float, 16> Elts;
902 for (unsigned i = 0, e = V.size(); i != e; ++i)
903 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
904 Elts.push_back(CFP->getValueAPF().convertToFloat());
907 if (Elts.size() == V.size())
908 return ConstantDataArray::get(C->getContext(), Elts);
909 } else if (CFP->getType()->isDoubleTy()) {
910 SmallVector<double, 16> Elts;
911 for (unsigned i = 0, e = V.size(); i != e; ++i)
912 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
913 Elts.push_back(CFP->getValueAPF().convertToDouble());
916 if (Elts.size() == V.size())
917 return ConstantDataArray::get(C->getContext(), Elts);
922 // Otherwise, we really do want to create a ConstantArray.
926 /// getTypeForElements - Return an anonymous struct type to use for a constant
927 /// with the specified set of elements. The list must not be empty.
928 StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
929 ArrayRef<Constant*> V,
931 unsigned VecSize = V.size();
932 SmallVector<Type*, 16> EltTypes(VecSize);
933 for (unsigned i = 0; i != VecSize; ++i)
934 EltTypes[i] = V[i]->getType();
936 return StructType::get(Context, EltTypes, Packed);
940 StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
943 "ConstantStruct::getTypeForElements cannot be called on empty list");
944 return getTypeForElements(V[0]->getContext(), V, Packed);
948 ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
949 : Constant(T, ConstantStructVal,
950 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
952 assert(V.size() == T->getNumElements() &&
953 "Invalid initializer vector for constant structure");
954 for (unsigned i = 0, e = V.size(); i != e; ++i)
955 assert((T->isOpaque() || V[i]->getType() == T->getElementType(i)) &&
956 "Initializer for struct element doesn't match struct element type!");
957 std::copy(V.begin(), V.end(), op_begin());
960 // ConstantStruct accessors.
961 Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
962 assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
963 "Incorrect # elements specified to ConstantStruct::get");
965 // Create a ConstantAggregateZero value if all elements are zeros.
967 bool isUndef = false;
970 isUndef = isa<UndefValue>(V[0]);
971 isZero = V[0]->isNullValue();
972 if (isUndef || isZero) {
973 for (unsigned i = 0, e = V.size(); i != e; ++i) {
974 if (!V[i]->isNullValue())
976 if (!isa<UndefValue>(V[i]))
982 return ConstantAggregateZero::get(ST);
984 return UndefValue::get(ST);
986 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
989 Constant *ConstantStruct::get(StructType *T, ...) {
991 SmallVector<Constant*, 8> Values;
993 while (Constant *Val = va_arg(ap, llvm::Constant*))
994 Values.push_back(Val);
996 return get(T, Values);
999 ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
1000 : Constant(T, ConstantVectorVal,
1001 OperandTraits<ConstantVector>::op_end(this) - V.size(),
1003 for (size_t i = 0, e = V.size(); i != e; i++)
1004 assert(V[i]->getType() == T->getElementType() &&
1005 "Initializer for vector element doesn't match vector element type!");
1006 std::copy(V.begin(), V.end(), op_begin());
1009 // ConstantVector accessors.
1010 Constant *ConstantVector::get(ArrayRef<Constant*> V) {
1011 if (Constant *C = getImpl(V))
1013 VectorType *Ty = VectorType::get(V.front()->getType(), V.size());
1014 return Ty->getContext().pImpl->VectorConstants.getOrCreate(Ty, V);
1016 Constant *ConstantVector::getImpl(ArrayRef<Constant*> V) {
1017 assert(!V.empty() && "Vectors can't be empty");
1018 VectorType *T = VectorType::get(V.front()->getType(), V.size());
1020 // If this is an all-undef or all-zero vector, return a
1021 // ConstantAggregateZero or UndefValue.
1023 bool isZero = C->isNullValue();
1024 bool isUndef = isa<UndefValue>(C);
1026 if (isZero || isUndef) {
1027 for (unsigned i = 1, e = V.size(); i != e; ++i)
1029 isZero = isUndef = false;
1035 return ConstantAggregateZero::get(T);
1037 return UndefValue::get(T);
1039 // Check to see if all of the elements are ConstantFP or ConstantInt and if
1040 // the element type is compatible with ConstantDataVector. If so, use it.
1041 if (ConstantDataSequential::isElementTypeCompatible(C->getType())) {
1042 // We speculatively build the elements here even if it turns out that there
1043 // is a constantexpr or something else weird in the array, since it is so
1044 // uncommon for that to happen.
1045 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
1046 if (CI->getType()->isIntegerTy(8)) {
1047 SmallVector<uint8_t, 16> Elts;
1048 for (unsigned i = 0, e = V.size(); i != e; ++i)
1049 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
1050 Elts.push_back(CI->getZExtValue());
1053 if (Elts.size() == V.size())
1054 return ConstantDataVector::get(C->getContext(), Elts);
1055 } else if (CI->getType()->isIntegerTy(16)) {
1056 SmallVector<uint16_t, 16> Elts;
1057 for (unsigned i = 0, e = V.size(); i != e; ++i)
1058 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
1059 Elts.push_back(CI->getZExtValue());
1062 if (Elts.size() == V.size())
1063 return ConstantDataVector::get(C->getContext(), Elts);
1064 } else if (CI->getType()->isIntegerTy(32)) {
1065 SmallVector<uint32_t, 16> Elts;
1066 for (unsigned i = 0, e = V.size(); i != e; ++i)
1067 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
1068 Elts.push_back(CI->getZExtValue());
1071 if (Elts.size() == V.size())
1072 return ConstantDataVector::get(C->getContext(), Elts);
1073 } else if (CI->getType()->isIntegerTy(64)) {
1074 SmallVector<uint64_t, 16> Elts;
1075 for (unsigned i = 0, e = V.size(); i != e; ++i)
1076 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
1077 Elts.push_back(CI->getZExtValue());
1080 if (Elts.size() == V.size())
1081 return ConstantDataVector::get(C->getContext(), Elts);
1085 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
1086 if (CFP->getType()->isFloatTy()) {
1087 SmallVector<float, 16> Elts;
1088 for (unsigned i = 0, e = V.size(); i != e; ++i)
1089 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
1090 Elts.push_back(CFP->getValueAPF().convertToFloat());
1093 if (Elts.size() == V.size())
1094 return ConstantDataVector::get(C->getContext(), Elts);
1095 } else if (CFP->getType()->isDoubleTy()) {
1096 SmallVector<double, 16> Elts;
1097 for (unsigned i = 0, e = V.size(); i != e; ++i)
1098 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
1099 Elts.push_back(CFP->getValueAPF().convertToDouble());
1102 if (Elts.size() == V.size())
1103 return ConstantDataVector::get(C->getContext(), Elts);
1108 // Otherwise, the element type isn't compatible with ConstantDataVector, or
1109 // the operand list constants a ConstantExpr or something else strange.
1113 Constant *ConstantVector::getSplat(unsigned NumElts, Constant *V) {
1114 // If this splat is compatible with ConstantDataVector, use it instead of
1116 if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&
1117 ConstantDataSequential::isElementTypeCompatible(V->getType()))
1118 return ConstantDataVector::getSplat(NumElts, V);
1120 SmallVector<Constant*, 32> Elts(NumElts, V);
1125 // Utility function for determining if a ConstantExpr is a CastOp or not. This
1126 // can't be inline because we don't want to #include Instruction.h into
1128 bool ConstantExpr::isCast() const {
1129 return Instruction::isCast(getOpcode());
1132 bool ConstantExpr::isCompare() const {
1133 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
1136 bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
1137 if (getOpcode() != Instruction::GetElementPtr) return false;
1139 gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
1140 User::const_op_iterator OI = std::next(this->op_begin());
1142 // Skip the first index, as it has no static limit.
1146 // The remaining indices must be compile-time known integers within the
1147 // bounds of the corresponding notional static array types.
1148 for (; GEPI != E; ++GEPI, ++OI) {
1149 ConstantInt *CI = dyn_cast<ConstantInt>(*OI);
1150 if (!CI) return false;
1151 if (ArrayType *ATy = dyn_cast<ArrayType>(*GEPI))
1152 if (CI->getValue().getActiveBits() > 64 ||
1153 CI->getZExtValue() >= ATy->getNumElements())
1157 // All the indices checked out.
1161 bool ConstantExpr::hasIndices() const {
1162 return getOpcode() == Instruction::ExtractValue ||
1163 getOpcode() == Instruction::InsertValue;
1166 ArrayRef<unsigned> ConstantExpr::getIndices() const {
1167 if (const ExtractValueConstantExpr *EVCE =
1168 dyn_cast<ExtractValueConstantExpr>(this))
1169 return EVCE->Indices;
1171 return cast<InsertValueConstantExpr>(this)->Indices;
1174 unsigned ConstantExpr::getPredicate() const {
1175 assert(isCompare());
1176 return ((const CompareConstantExpr*)this)->predicate;
1179 /// getWithOperandReplaced - Return a constant expression identical to this
1180 /// one, but with the specified operand set to the specified value.
1182 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
1183 assert(Op->getType() == getOperand(OpNo)->getType() &&
1184 "Replacing operand with value of different type!");
1185 if (getOperand(OpNo) == Op)
1186 return const_cast<ConstantExpr*>(this);
1188 SmallVector<Constant*, 8> NewOps;
1189 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1190 NewOps.push_back(i == OpNo ? Op : getOperand(i));
1192 return getWithOperands(NewOps);
1195 /// getWithOperands - This returns the current constant expression with the
1196 /// operands replaced with the specified values. The specified array must
1197 /// have the same number of operands as our current one.
1198 Constant *ConstantExpr::getWithOperands(ArrayRef<Constant *> Ops, Type *Ty,
1199 bool OnlyIfReduced) const {
1200 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
1201 bool AnyChange = Ty != getType();
1202 for (unsigned i = 0; i != Ops.size(); ++i)
1203 AnyChange |= Ops[i] != getOperand(i);
1205 if (!AnyChange) // No operands changed, return self.
1206 return const_cast<ConstantExpr*>(this);
1208 Type *OnlyIfReducedTy = OnlyIfReduced ? Ty : nullptr;
1209 switch (getOpcode()) {
1210 case Instruction::Trunc:
1211 case Instruction::ZExt:
1212 case Instruction::SExt:
1213 case Instruction::FPTrunc:
1214 case Instruction::FPExt:
1215 case Instruction::UIToFP:
1216 case Instruction::SIToFP:
1217 case Instruction::FPToUI:
1218 case Instruction::FPToSI:
1219 case Instruction::PtrToInt:
1220 case Instruction::IntToPtr:
1221 case Instruction::BitCast:
1222 case Instruction::AddrSpaceCast:
1223 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty, OnlyIfReduced);
1224 case Instruction::Select:
1225 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2], OnlyIfReducedTy);
1226 case Instruction::InsertElement:
1227 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2],
1229 case Instruction::ExtractElement:
1230 return ConstantExpr::getExtractElement(Ops[0], Ops[1], OnlyIfReducedTy);
1231 case Instruction::InsertValue:
1232 return ConstantExpr::getInsertValue(Ops[0], Ops[1], getIndices(),
1234 case Instruction::ExtractValue:
1235 return ConstantExpr::getExtractValue(Ops[0], getIndices(), OnlyIfReducedTy);
1236 case Instruction::ShuffleVector:
1237 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2],
1239 case Instruction::GetElementPtr:
1240 return ConstantExpr::getGetElementPtr(Ops[0], Ops.slice(1),
1241 cast<GEPOperator>(this)->isInBounds(),
1243 case Instruction::ICmp:
1244 case Instruction::FCmp:
1245 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1],
1248 assert(getNumOperands() == 2 && "Must be binary operator?");
1249 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData,
1255 //===----------------------------------------------------------------------===//
1256 // isValueValidForType implementations
1258 bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
1259 unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
1260 if (Ty->isIntegerTy(1))
1261 return Val == 0 || Val == 1;
1263 return true; // always true, has to fit in largest type
1264 uint64_t Max = (1ll << NumBits) - 1;
1268 bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
1269 unsigned NumBits = Ty->getIntegerBitWidth();
1270 if (Ty->isIntegerTy(1))
1271 return Val == 0 || Val == 1 || Val == -1;
1273 return true; // always true, has to fit in largest type
1274 int64_t Min = -(1ll << (NumBits-1));
1275 int64_t Max = (1ll << (NumBits-1)) - 1;
1276 return (Val >= Min && Val <= Max);
1279 bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {
1280 // convert modifies in place, so make a copy.
1281 APFloat Val2 = APFloat(Val);
1283 switch (Ty->getTypeID()) {
1285 return false; // These can't be represented as floating point!
1287 // FIXME rounding mode needs to be more flexible
1288 case Type::HalfTyID: {
1289 if (&Val2.getSemantics() == &APFloat::IEEEhalf)
1291 Val2.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &losesInfo);
1294 case Type::FloatTyID: {
1295 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
1297 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
1300 case Type::DoubleTyID: {
1301 if (&Val2.getSemantics() == &APFloat::IEEEhalf ||
1302 &Val2.getSemantics() == &APFloat::IEEEsingle ||
1303 &Val2.getSemantics() == &APFloat::IEEEdouble)
1305 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
1308 case Type::X86_FP80TyID:
1309 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1310 &Val2.getSemantics() == &APFloat::IEEEsingle ||
1311 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1312 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
1313 case Type::FP128TyID:
1314 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1315 &Val2.getSemantics() == &APFloat::IEEEsingle ||
1316 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1317 &Val2.getSemantics() == &APFloat::IEEEquad;
1318 case Type::PPC_FP128TyID:
1319 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1320 &Val2.getSemantics() == &APFloat::IEEEsingle ||
1321 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1322 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
1327 //===----------------------------------------------------------------------===//
1328 // Factory Function Implementation
1330 ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
1331 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
1332 "Cannot create an aggregate zero of non-aggregate type!");
1334 ConstantAggregateZero *&Entry = Ty->getContext().pImpl->CAZConstants[Ty];
1336 Entry = new ConstantAggregateZero(Ty);
1341 /// destroyConstant - Remove the constant from the constant table.
1343 void ConstantAggregateZero::destroyConstant() {
1344 getContext().pImpl->CAZConstants.erase(getType());
1345 destroyConstantImpl();
1348 /// destroyConstant - Remove the constant from the constant table...
1350 void ConstantArray::destroyConstant() {
1351 getType()->getContext().pImpl->ArrayConstants.remove(this);
1352 destroyConstantImpl();
1356 //---- ConstantStruct::get() implementation...
1359 // destroyConstant - Remove the constant from the constant table...
1361 void ConstantStruct::destroyConstant() {
1362 getType()->getContext().pImpl->StructConstants.remove(this);
1363 destroyConstantImpl();
1366 // destroyConstant - Remove the constant from the constant table...
1368 void ConstantVector::destroyConstant() {
1369 getType()->getContext().pImpl->VectorConstants.remove(this);
1370 destroyConstantImpl();
1373 /// getSplatValue - If this is a splat vector constant, meaning that all of
1374 /// the elements have the same value, return that value. Otherwise return 0.
1375 Constant *Constant::getSplatValue() const {
1376 assert(this->getType()->isVectorTy() && "Only valid for vectors!");
1377 if (isa<ConstantAggregateZero>(this))
1378 return getNullValue(this->getType()->getVectorElementType());
1379 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
1380 return CV->getSplatValue();
1381 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
1382 return CV->getSplatValue();
1386 /// getSplatValue - If this is a splat constant, where all of the
1387 /// elements have the same value, return that value. Otherwise return null.
1388 Constant *ConstantVector::getSplatValue() const {
1389 // Check out first element.
1390 Constant *Elt = getOperand(0);
1391 // Then make sure all remaining elements point to the same value.
1392 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1393 if (getOperand(I) != Elt)
1398 /// If C is a constant integer then return its value, otherwise C must be a
1399 /// vector of constant integers, all equal, and the common value is returned.
1400 const APInt &Constant::getUniqueInteger() const {
1401 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
1402 return CI->getValue();
1403 assert(this->getSplatValue() && "Doesn't contain a unique integer!");
1404 const Constant *C = this->getAggregateElement(0U);
1405 assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
1406 return cast<ConstantInt>(C)->getValue();
1410 //---- ConstantPointerNull::get() implementation.
1413 ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
1414 ConstantPointerNull *&Entry = Ty->getContext().pImpl->CPNConstants[Ty];
1416 Entry = new ConstantPointerNull(Ty);
1421 // destroyConstant - Remove the constant from the constant table...
1423 void ConstantPointerNull::destroyConstant() {
1424 getContext().pImpl->CPNConstants.erase(getType());
1425 // Free the constant and any dangling references to it.
1426 destroyConstantImpl();
1430 //---- UndefValue::get() implementation.
1433 UndefValue *UndefValue::get(Type *Ty) {
1434 UndefValue *&Entry = Ty->getContext().pImpl->UVConstants[Ty];
1436 Entry = new UndefValue(Ty);
1441 // destroyConstant - Remove the constant from the constant table.
1443 void UndefValue::destroyConstant() {
1444 // Free the constant and any dangling references to it.
1445 getContext().pImpl->UVConstants.erase(getType());
1446 destroyConstantImpl();
1449 //---- BlockAddress::get() implementation.
1452 BlockAddress *BlockAddress::get(BasicBlock *BB) {
1453 assert(BB->getParent() && "Block must have a parent");
1454 return get(BB->getParent(), BB);
1457 BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1459 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
1461 BA = new BlockAddress(F, BB);
1463 assert(BA->getFunction() == F && "Basic block moved between functions");
1467 BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1468 : Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1472 BB->AdjustBlockAddressRefCount(1);
1475 BlockAddress *BlockAddress::lookup(const BasicBlock *BB) {
1476 if (!BB->hasAddressTaken())
1479 const Function *F = BB->getParent();
1480 assert(F && "Block must have a parent");
1482 F->getContext().pImpl->BlockAddresses.lookup(std::make_pair(F, BB));
1483 assert(BA && "Refcount and block address map disagree!");
1487 // destroyConstant - Remove the constant from the constant table.
1489 void BlockAddress::destroyConstant() {
1490 getFunction()->getType()->getContext().pImpl
1491 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
1492 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1493 destroyConstantImpl();
1496 void BlockAddress::replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U) {
1497 // This could be replacing either the Basic Block or the Function. In either
1498 // case, we have to remove the map entry.
1499 Function *NewF = getFunction();
1500 BasicBlock *NewBB = getBasicBlock();
1503 NewF = cast<Function>(To->stripPointerCasts());
1505 NewBB = cast<BasicBlock>(To);
1507 // See if the 'new' entry already exists, if not, just update this in place
1508 // and return early.
1509 BlockAddress *&NewBA =
1510 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
1512 replaceUsesOfWithOnConstantImpl(NewBA);
1516 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1518 // Remove the old entry, this can't cause the map to rehash (just a
1519 // tombstone will get added).
1520 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1523 setOperand(0, NewF);
1524 setOperand(1, NewBB);
1525 getBasicBlock()->AdjustBlockAddressRefCount(1);
1528 //---- ConstantExpr::get() implementations.
1531 /// This is a utility function to handle folding of casts and lookup of the
1532 /// cast in the ExprConstants map. It is used by the various get* methods below.
1533 static Constant *getFoldedCast(Instruction::CastOps opc, Constant *C, Type *Ty,
1534 bool OnlyIfReduced = false) {
1535 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1536 // Fold a few common cases
1537 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1543 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1545 // Look up the constant in the table first to ensure uniqueness.
1546 ConstantExprKeyType Key(opc, C);
1548 return pImpl->ExprConstants.getOrCreate(Ty, Key);
1551 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty,
1552 bool OnlyIfReduced) {
1553 Instruction::CastOps opc = Instruction::CastOps(oc);
1554 assert(Instruction::isCast(opc) && "opcode out of range");
1555 assert(C && Ty && "Null arguments to getCast");
1556 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
1560 llvm_unreachable("Invalid cast opcode");
1561 case Instruction::Trunc:
1562 return getTrunc(C, Ty, OnlyIfReduced);
1563 case Instruction::ZExt:
1564 return getZExt(C, Ty, OnlyIfReduced);
1565 case Instruction::SExt:
1566 return getSExt(C, Ty, OnlyIfReduced);
1567 case Instruction::FPTrunc:
1568 return getFPTrunc(C, Ty, OnlyIfReduced);
1569 case Instruction::FPExt:
1570 return getFPExtend(C, Ty, OnlyIfReduced);
1571 case Instruction::UIToFP:
1572 return getUIToFP(C, Ty, OnlyIfReduced);
1573 case Instruction::SIToFP:
1574 return getSIToFP(C, Ty, OnlyIfReduced);
1575 case Instruction::FPToUI:
1576 return getFPToUI(C, Ty, OnlyIfReduced);
1577 case Instruction::FPToSI:
1578 return getFPToSI(C, Ty, OnlyIfReduced);
1579 case Instruction::PtrToInt:
1580 return getPtrToInt(C, Ty, OnlyIfReduced);
1581 case Instruction::IntToPtr:
1582 return getIntToPtr(C, Ty, OnlyIfReduced);
1583 case Instruction::BitCast:
1584 return getBitCast(C, Ty, OnlyIfReduced);
1585 case Instruction::AddrSpaceCast:
1586 return getAddrSpaceCast(C, Ty, OnlyIfReduced);
1590 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) {
1591 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1592 return getBitCast(C, Ty);
1593 return getZExt(C, Ty);
1596 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) {
1597 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1598 return getBitCast(C, Ty);
1599 return getSExt(C, Ty);
1602 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {
1603 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1604 return getBitCast(C, Ty);
1605 return getTrunc(C, Ty);
1608 Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {
1609 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1610 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
1613 if (Ty->isIntOrIntVectorTy())
1614 return getPtrToInt(S, Ty);
1616 unsigned SrcAS = S->getType()->getPointerAddressSpace();
1617 if (Ty->isPtrOrPtrVectorTy() && SrcAS != Ty->getPointerAddressSpace())
1618 return getAddrSpaceCast(S, Ty);
1620 return getBitCast(S, Ty);
1623 Constant *ConstantExpr::getPointerBitCastOrAddrSpaceCast(Constant *S,
1625 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1626 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
1628 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
1629 return getAddrSpaceCast(S, Ty);
1631 return getBitCast(S, Ty);
1634 Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty,
1636 assert(C->getType()->isIntOrIntVectorTy() &&
1637 Ty->isIntOrIntVectorTy() && "Invalid cast");
1638 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1639 unsigned DstBits = Ty->getScalarSizeInBits();
1640 Instruction::CastOps opcode =
1641 (SrcBits == DstBits ? Instruction::BitCast :
1642 (SrcBits > DstBits ? Instruction::Trunc :
1643 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1644 return getCast(opcode, C, Ty);
1647 Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) {
1648 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1650 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1651 unsigned DstBits = Ty->getScalarSizeInBits();
1652 if (SrcBits == DstBits)
1653 return C; // Avoid a useless cast
1654 Instruction::CastOps opcode =
1655 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1656 return getCast(opcode, C, Ty);
1659 Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
1661 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1662 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1664 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1665 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
1666 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
1667 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1668 "SrcTy must be larger than DestTy for Trunc!");
1670 return getFoldedCast(Instruction::Trunc, C, Ty, OnlyIfReduced);
1673 Constant *ConstantExpr::getSExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
1675 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1676 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1678 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1679 assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
1680 assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
1681 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1682 "SrcTy must be smaller than DestTy for SExt!");
1684 return getFoldedCast(Instruction::SExt, C, Ty, OnlyIfReduced);
1687 Constant *ConstantExpr::getZExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
1689 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1690 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1692 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1693 assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
1694 assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
1695 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1696 "SrcTy must be smaller than DestTy for ZExt!");
1698 return getFoldedCast(Instruction::ZExt, C, Ty, OnlyIfReduced);
1701 Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
1703 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1704 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1706 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1707 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1708 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1709 "This is an illegal floating point truncation!");
1710 return getFoldedCast(Instruction::FPTrunc, C, Ty, OnlyIfReduced);
1713 Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty, bool OnlyIfReduced) {
1715 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1716 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1718 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1719 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1720 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1721 "This is an illegal floating point extension!");
1722 return getFoldedCast(Instruction::FPExt, C, Ty, OnlyIfReduced);
1725 Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
1727 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1728 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1730 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1731 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1732 "This is an illegal uint to floating point cast!");
1733 return getFoldedCast(Instruction::UIToFP, C, Ty, OnlyIfReduced);
1736 Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
1738 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1739 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1741 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1742 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1743 "This is an illegal sint to floating point cast!");
1744 return getFoldedCast(Instruction::SIToFP, C, Ty, OnlyIfReduced);
1747 Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty, bool OnlyIfReduced) {
1749 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1750 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1752 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1753 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1754 "This is an illegal floating point to uint cast!");
1755 return getFoldedCast(Instruction::FPToUI, C, Ty, OnlyIfReduced);
1758 Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty, bool OnlyIfReduced) {
1760 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1761 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1763 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1764 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1765 "This is an illegal floating point to sint cast!");
1766 return getFoldedCast(Instruction::FPToSI, C, Ty, OnlyIfReduced);
1769 Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy,
1770 bool OnlyIfReduced) {
1771 assert(C->getType()->getScalarType()->isPointerTy() &&
1772 "PtrToInt source must be pointer or pointer vector");
1773 assert(DstTy->getScalarType()->isIntegerTy() &&
1774 "PtrToInt destination must be integer or integer vector");
1775 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
1776 if (isa<VectorType>(C->getType()))
1777 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
1778 "Invalid cast between a different number of vector elements");
1779 return getFoldedCast(Instruction::PtrToInt, C, DstTy, OnlyIfReduced);
1782 Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy,
1783 bool OnlyIfReduced) {
1784 assert(C->getType()->getScalarType()->isIntegerTy() &&
1785 "IntToPtr source must be integer or integer vector");
1786 assert(DstTy->getScalarType()->isPointerTy() &&
1787 "IntToPtr destination must be a pointer or pointer vector");
1788 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
1789 if (isa<VectorType>(C->getType()))
1790 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
1791 "Invalid cast between a different number of vector elements");
1792 return getFoldedCast(Instruction::IntToPtr, C, DstTy, OnlyIfReduced);
1795 Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy,
1796 bool OnlyIfReduced) {
1797 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
1798 "Invalid constantexpr bitcast!");
1800 // It is common to ask for a bitcast of a value to its own type, handle this
1802 if (C->getType() == DstTy) return C;
1804 return getFoldedCast(Instruction::BitCast, C, DstTy, OnlyIfReduced);
1807 Constant *ConstantExpr::getAddrSpaceCast(Constant *C, Type *DstTy,
1808 bool OnlyIfReduced) {
1809 assert(CastInst::castIsValid(Instruction::AddrSpaceCast, C, DstTy) &&
1810 "Invalid constantexpr addrspacecast!");
1812 // Canonicalize addrspacecasts between different pointer types by first
1813 // bitcasting the pointer type and then converting the address space.
1814 PointerType *SrcScalarTy = cast<PointerType>(C->getType()->getScalarType());
1815 PointerType *DstScalarTy = cast<PointerType>(DstTy->getScalarType());
1816 Type *DstElemTy = DstScalarTy->getElementType();
1817 if (SrcScalarTy->getElementType() != DstElemTy) {
1818 Type *MidTy = PointerType::get(DstElemTy, SrcScalarTy->getAddressSpace());
1819 if (VectorType *VT = dyn_cast<VectorType>(DstTy)) {
1820 // Handle vectors of pointers.
1821 MidTy = VectorType::get(MidTy, VT->getNumElements());
1823 C = getBitCast(C, MidTy);
1825 return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced);
1828 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
1829 unsigned Flags, Type *OnlyIfReducedTy) {
1830 // Check the operands for consistency first.
1831 assert(Opcode >= Instruction::BinaryOpsBegin &&
1832 Opcode < Instruction::BinaryOpsEnd &&
1833 "Invalid opcode in binary constant expression");
1834 assert(C1->getType() == C2->getType() &&
1835 "Operand types in binary constant expression should match");
1839 case Instruction::Add:
1840 case Instruction::Sub:
1841 case Instruction::Mul:
1842 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1843 assert(C1->getType()->isIntOrIntVectorTy() &&
1844 "Tried to create an integer operation on a non-integer type!");
1846 case Instruction::FAdd:
1847 case Instruction::FSub:
1848 case Instruction::FMul:
1849 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1850 assert(C1->getType()->isFPOrFPVectorTy() &&
1851 "Tried to create a floating-point operation on a "
1852 "non-floating-point type!");
1854 case Instruction::UDiv:
1855 case Instruction::SDiv:
1856 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1857 assert(C1->getType()->isIntOrIntVectorTy() &&
1858 "Tried to create an arithmetic operation on a non-arithmetic type!");
1860 case Instruction::FDiv:
1861 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1862 assert(C1->getType()->isFPOrFPVectorTy() &&
1863 "Tried to create an arithmetic operation on a non-arithmetic type!");
1865 case Instruction::URem:
1866 case Instruction::SRem:
1867 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1868 assert(C1->getType()->isIntOrIntVectorTy() &&
1869 "Tried to create an arithmetic operation on a non-arithmetic type!");
1871 case Instruction::FRem:
1872 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1873 assert(C1->getType()->isFPOrFPVectorTy() &&
1874 "Tried to create an arithmetic operation on a non-arithmetic type!");
1876 case Instruction::And:
1877 case Instruction::Or:
1878 case Instruction::Xor:
1879 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1880 assert(C1->getType()->isIntOrIntVectorTy() &&
1881 "Tried to create a logical operation on a non-integral type!");
1883 case Instruction::Shl:
1884 case Instruction::LShr:
1885 case Instruction::AShr:
1886 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1887 assert(C1->getType()->isIntOrIntVectorTy() &&
1888 "Tried to create a shift operation on a non-integer type!");
1895 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1896 return FC; // Fold a few common cases.
1898 if (OnlyIfReducedTy == C1->getType())
1901 Constant *ArgVec[] = { C1, C2 };
1902 ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
1904 LLVMContextImpl *pImpl = C1->getContext().pImpl;
1905 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
1908 Constant *ConstantExpr::getSizeOf(Type* Ty) {
1909 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1910 // Note that a non-inbounds gep is used, as null isn't within any object.
1911 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1912 Constant *GEP = getGetElementPtr(
1913 Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
1914 return getPtrToInt(GEP,
1915 Type::getInt64Ty(Ty->getContext()));
1918 Constant *ConstantExpr::getAlignOf(Type* Ty) {
1919 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
1920 // Note that a non-inbounds gep is used, as null isn't within any object.
1922 StructType::get(Type::getInt1Ty(Ty->getContext()), Ty, NULL);
1923 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo(0));
1924 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
1925 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1926 Constant *Indices[2] = { Zero, One };
1927 Constant *GEP = getGetElementPtr(NullPtr, Indices);
1928 return getPtrToInt(GEP,
1929 Type::getInt64Ty(Ty->getContext()));
1932 Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) {
1933 return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
1937 Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) {
1938 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1939 // Note that a non-inbounds gep is used, as null isn't within any object.
1940 Constant *GEPIdx[] = {
1941 ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
1944 Constant *GEP = getGetElementPtr(
1945 Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
1946 return getPtrToInt(GEP,
1947 Type::getInt64Ty(Ty->getContext()));
1950 Constant *ConstantExpr::getCompare(unsigned short Predicate, Constant *C1,
1951 Constant *C2, bool OnlyIfReduced) {
1952 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1954 switch (Predicate) {
1955 default: llvm_unreachable("Invalid CmpInst predicate");
1956 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1957 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1958 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1959 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1960 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1961 case CmpInst::FCMP_TRUE:
1962 return getFCmp(Predicate, C1, C2, OnlyIfReduced);
1964 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1965 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1966 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1967 case CmpInst::ICMP_SLE:
1968 return getICmp(Predicate, C1, C2, OnlyIfReduced);
1972 Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2,
1973 Type *OnlyIfReducedTy) {
1974 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1976 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1977 return SC; // Fold common cases
1979 if (OnlyIfReducedTy == V1->getType())
1982 Constant *ArgVec[] = { C, V1, V2 };
1983 ConstantExprKeyType Key(Instruction::Select, ArgVec);
1985 LLVMContextImpl *pImpl = C->getContext().pImpl;
1986 return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
1989 Constant *ConstantExpr::getGetElementPtr(Constant *C, ArrayRef<Value *> Idxs,
1990 bool InBounds, Type *OnlyIfReducedTy) {
1991 assert(C->getType()->isPtrOrPtrVectorTy() &&
1992 "Non-pointer type for constant GetElementPtr expression");
1994 if (Constant *FC = ConstantFoldGetElementPtr(C, InBounds, Idxs))
1995 return FC; // Fold a few common cases.
1997 // Get the result type of the getelementptr!
1998 Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), Idxs);
1999 assert(Ty && "GEP indices invalid!");
2000 unsigned AS = C->getType()->getPointerAddressSpace();
2001 Type *ReqTy = Ty->getPointerTo(AS);
2002 if (VectorType *VecTy = dyn_cast<VectorType>(C->getType()))
2003 ReqTy = VectorType::get(ReqTy, VecTy->getNumElements());
2005 if (OnlyIfReducedTy == ReqTy)
2008 // Look up the constant in the table first to ensure uniqueness
2009 std::vector<Constant*> ArgVec;
2010 ArgVec.reserve(1 + Idxs.size());
2011 ArgVec.push_back(C);
2012 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
2013 assert(Idxs[i]->getType()->isVectorTy() == ReqTy->isVectorTy() &&
2014 "getelementptr index type missmatch");
2015 assert((!Idxs[i]->getType()->isVectorTy() ||
2016 ReqTy->getVectorNumElements() ==
2017 Idxs[i]->getType()->getVectorNumElements()) &&
2018 "getelementptr index type missmatch");
2019 ArgVec.push_back(cast<Constant>(Idxs[i]));
2021 const ConstantExprKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
2022 InBounds ? GEPOperator::IsInBounds : 0);
2024 LLVMContextImpl *pImpl = C->getContext().pImpl;
2025 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2028 Constant *ConstantExpr::getICmp(unsigned short pred, Constant *LHS,
2029 Constant *RHS, bool OnlyIfReduced) {
2030 assert(LHS->getType() == RHS->getType());
2031 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2032 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
2034 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2035 return FC; // Fold a few common cases...
2040 // Look up the constant in the table first to ensure uniqueness
2041 Constant *ArgVec[] = { LHS, RHS };
2042 // Get the key type with both the opcode and predicate
2043 const ConstantExprKeyType Key(Instruction::ICmp, ArgVec, pred);
2045 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
2046 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
2047 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
2049 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
2050 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
2053 Constant *ConstantExpr::getFCmp(unsigned short pred, Constant *LHS,
2054 Constant *RHS, bool OnlyIfReduced) {
2055 assert(LHS->getType() == RHS->getType());
2056 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
2058 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2059 return FC; // Fold a few common cases...
2064 // Look up the constant in the table first to ensure uniqueness
2065 Constant *ArgVec[] = { LHS, RHS };
2066 // Get the key type with both the opcode and predicate
2067 const ConstantExprKeyType Key(Instruction::FCmp, ArgVec, pred);
2069 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
2070 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
2071 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
2073 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
2074 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
2077 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx,
2078 Type *OnlyIfReducedTy) {
2079 assert(Val->getType()->isVectorTy() &&
2080 "Tried to create extractelement operation on non-vector type!");
2081 assert(Idx->getType()->isIntegerTy() &&
2082 "Extractelement index must be an integer type!");
2084 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
2085 return FC; // Fold a few common cases.
2087 Type *ReqTy = Val->getType()->getVectorElementType();
2088 if (OnlyIfReducedTy == ReqTy)
2091 // Look up the constant in the table first to ensure uniqueness
2092 Constant *ArgVec[] = { Val, Idx };
2093 const ConstantExprKeyType Key(Instruction::ExtractElement, ArgVec);
2095 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2096 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2099 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2100 Constant *Idx, Type *OnlyIfReducedTy) {
2101 assert(Val->getType()->isVectorTy() &&
2102 "Tried to create insertelement operation on non-vector type!");
2103 assert(Elt->getType() == Val->getType()->getVectorElementType() &&
2104 "Insertelement types must match!");
2105 assert(Idx->getType()->isIntegerTy() &&
2106 "Insertelement index must be i32 type!");
2108 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2109 return FC; // Fold a few common cases.
2111 if (OnlyIfReducedTy == Val->getType())
2114 // Look up the constant in the table first to ensure uniqueness
2115 Constant *ArgVec[] = { Val, Elt, Idx };
2116 const ConstantExprKeyType Key(Instruction::InsertElement, ArgVec);
2118 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2119 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
2122 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2123 Constant *Mask, Type *OnlyIfReducedTy) {
2124 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2125 "Invalid shuffle vector constant expr operands!");
2127 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2128 return FC; // Fold a few common cases.
2130 unsigned NElts = Mask->getType()->getVectorNumElements();
2131 Type *EltTy = V1->getType()->getVectorElementType();
2132 Type *ShufTy = VectorType::get(EltTy, NElts);
2134 if (OnlyIfReducedTy == ShufTy)
2137 // Look up the constant in the table first to ensure uniqueness
2138 Constant *ArgVec[] = { V1, V2, Mask };
2139 const ConstantExprKeyType Key(Instruction::ShuffleVector, ArgVec);
2141 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
2142 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
2145 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
2146 ArrayRef<unsigned> Idxs,
2147 Type *OnlyIfReducedTy) {
2148 assert(Agg->getType()->isFirstClassType() &&
2149 "Non-first-class type for constant insertvalue expression");
2151 assert(ExtractValueInst::getIndexedType(Agg->getType(),
2152 Idxs) == Val->getType() &&
2153 "insertvalue indices invalid!");
2154 Type *ReqTy = Val->getType();
2156 if (Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs))
2159 if (OnlyIfReducedTy == ReqTy)
2162 Constant *ArgVec[] = { Agg, Val };
2163 const ConstantExprKeyType Key(Instruction::InsertValue, ArgVec, 0, 0, Idxs);
2165 LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2166 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2169 Constant *ConstantExpr::getExtractValue(Constant *Agg, ArrayRef<unsigned> Idxs,
2170 Type *OnlyIfReducedTy) {
2171 assert(Agg->getType()->isFirstClassType() &&
2172 "Tried to create extractelement operation on non-first-class type!");
2174 Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs);
2176 assert(ReqTy && "extractvalue indices invalid!");
2178 assert(Agg->getType()->isFirstClassType() &&
2179 "Non-first-class type for constant extractvalue expression");
2180 if (Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs))
2183 if (OnlyIfReducedTy == ReqTy)
2186 Constant *ArgVec[] = { Agg };
2187 const ConstantExprKeyType Key(Instruction::ExtractValue, ArgVec, 0, 0, Idxs);
2189 LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2190 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2193 Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
2194 assert(C->getType()->isIntOrIntVectorTy() &&
2195 "Cannot NEG a nonintegral value!");
2196 return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
2200 Constant *ConstantExpr::getFNeg(Constant *C) {
2201 assert(C->getType()->isFPOrFPVectorTy() &&
2202 "Cannot FNEG a non-floating-point value!");
2203 return getFSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
2206 Constant *ConstantExpr::getNot(Constant *C) {
2207 assert(C->getType()->isIntOrIntVectorTy() &&
2208 "Cannot NOT a nonintegral value!");
2209 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
2212 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
2213 bool HasNUW, bool HasNSW) {
2214 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2215 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2216 return get(Instruction::Add, C1, C2, Flags);
2219 Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
2220 return get(Instruction::FAdd, C1, C2);
2223 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
2224 bool HasNUW, bool HasNSW) {
2225 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2226 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2227 return get(Instruction::Sub, C1, C2, Flags);
2230 Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
2231 return get(Instruction::FSub, C1, C2);
2234 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
2235 bool HasNUW, bool HasNSW) {
2236 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2237 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2238 return get(Instruction::Mul, C1, C2, Flags);
2241 Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
2242 return get(Instruction::FMul, C1, C2);
2245 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
2246 return get(Instruction::UDiv, C1, C2,
2247 isExact ? PossiblyExactOperator::IsExact : 0);
2250 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
2251 return get(Instruction::SDiv, C1, C2,
2252 isExact ? PossiblyExactOperator::IsExact : 0);
2255 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
2256 return get(Instruction::FDiv, C1, C2);
2259 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
2260 return get(Instruction::URem, C1, C2);
2263 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
2264 return get(Instruction::SRem, C1, C2);
2267 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
2268 return get(Instruction::FRem, C1, C2);
2271 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
2272 return get(Instruction::And, C1, C2);
2275 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
2276 return get(Instruction::Or, C1, C2);
2279 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
2280 return get(Instruction::Xor, C1, C2);
2283 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
2284 bool HasNUW, bool HasNSW) {
2285 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2286 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2287 return get(Instruction::Shl, C1, C2, Flags);
2290 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
2291 return get(Instruction::LShr, C1, C2,
2292 isExact ? PossiblyExactOperator::IsExact : 0);
2295 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
2296 return get(Instruction::AShr, C1, C2,
2297 isExact ? PossiblyExactOperator::IsExact : 0);
2300 /// getBinOpIdentity - Return the identity for the given binary operation,
2301 /// i.e. a constant C such that X op C = X and C op X = X for every X. It
2302 /// returns null if the operator doesn't have an identity.
2303 Constant *ConstantExpr::getBinOpIdentity(unsigned Opcode, Type *Ty) {
2306 // Doesn't have an identity.
2309 case Instruction::Add:
2310 case Instruction::Or:
2311 case Instruction::Xor:
2312 return Constant::getNullValue(Ty);
2314 case Instruction::Mul:
2315 return ConstantInt::get(Ty, 1);
2317 case Instruction::And:
2318 return Constant::getAllOnesValue(Ty);
2322 /// getBinOpAbsorber - Return the absorbing element for the given binary
2323 /// operation, i.e. a constant C such that X op C = C and C op X = C for
2324 /// every X. For example, this returns zero for integer multiplication.
2325 /// It returns null if the operator doesn't have an absorbing element.
2326 Constant *ConstantExpr::getBinOpAbsorber(unsigned Opcode, Type *Ty) {
2329 // Doesn't have an absorber.
2332 case Instruction::Or:
2333 return Constant::getAllOnesValue(Ty);
2335 case Instruction::And:
2336 case Instruction::Mul:
2337 return Constant::getNullValue(Ty);
2341 // destroyConstant - Remove the constant from the constant table...
2343 void ConstantExpr::destroyConstant() {
2344 getType()->getContext().pImpl->ExprConstants.remove(this);
2345 destroyConstantImpl();
2348 const char *ConstantExpr::getOpcodeName() const {
2349 return Instruction::getOpcodeName(getOpcode());
2354 GetElementPtrConstantExpr::
2355 GetElementPtrConstantExpr(Constant *C, ArrayRef<Constant*> IdxList,
2357 : ConstantExpr(DestTy, Instruction::GetElementPtr,
2358 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
2359 - (IdxList.size()+1), IdxList.size()+1) {
2361 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
2362 OperandList[i+1] = IdxList[i];
2365 //===----------------------------------------------------------------------===//
2366 // ConstantData* implementations
2368 void ConstantDataArray::anchor() {}
2369 void ConstantDataVector::anchor() {}
2371 /// getElementType - Return the element type of the array/vector.
2372 Type *ConstantDataSequential::getElementType() const {
2373 return getType()->getElementType();
2376 StringRef ConstantDataSequential::getRawDataValues() const {
2377 return StringRef(DataElements, getNumElements()*getElementByteSize());
2380 /// isElementTypeCompatible - Return true if a ConstantDataSequential can be
2381 /// formed with a vector or array of the specified element type.
2382 /// ConstantDataArray only works with normal float and int types that are
2383 /// stored densely in memory, not with things like i42 or x86_f80.
2384 bool ConstantDataSequential::isElementTypeCompatible(const Type *Ty) {
2385 if (Ty->isFloatTy() || Ty->isDoubleTy()) return true;
2386 if (const IntegerType *IT = dyn_cast<IntegerType>(Ty)) {
2387 switch (IT->getBitWidth()) {
2399 /// getNumElements - Return the number of elements in the array or vector.
2400 unsigned ConstantDataSequential::getNumElements() const {
2401 if (ArrayType *AT = dyn_cast<ArrayType>(getType()))
2402 return AT->getNumElements();
2403 return getType()->getVectorNumElements();
2407 /// getElementByteSize - Return the size in bytes of the elements in the data.
2408 uint64_t ConstantDataSequential::getElementByteSize() const {
2409 return getElementType()->getPrimitiveSizeInBits()/8;
2412 /// getElementPointer - Return the start of the specified element.
2413 const char *ConstantDataSequential::getElementPointer(unsigned Elt) const {
2414 assert(Elt < getNumElements() && "Invalid Elt");
2415 return DataElements+Elt*getElementByteSize();
2419 /// isAllZeros - return true if the array is empty or all zeros.
2420 static bool isAllZeros(StringRef Arr) {
2421 for (StringRef::iterator I = Arr.begin(), E = Arr.end(); I != E; ++I)
2427 /// getImpl - This is the underlying implementation of all of the
2428 /// ConstantDataSequential::get methods. They all thunk down to here, providing
2429 /// the correct element type. We take the bytes in as a StringRef because
2430 /// we *want* an underlying "char*" to avoid TBAA type punning violations.
2431 Constant *ConstantDataSequential::getImpl(StringRef Elements, Type *Ty) {
2432 assert(isElementTypeCompatible(Ty->getSequentialElementType()));
2433 // If the elements are all zero or there are no elements, return a CAZ, which
2434 // is more dense and canonical.
2435 if (isAllZeros(Elements))
2436 return ConstantAggregateZero::get(Ty);
2438 // Do a lookup to see if we have already formed one of these.
2439 StringMap<ConstantDataSequential*>::MapEntryTy &Slot =
2440 Ty->getContext().pImpl->CDSConstants.GetOrCreateValue(Elements);
2442 // The bucket can point to a linked list of different CDS's that have the same
2443 // body but different types. For example, 0,0,0,1 could be a 4 element array
2444 // of i8, or a 1-element array of i32. They'll both end up in the same
2445 /// StringMap bucket, linked up by their Next pointers. Walk the list.
2446 ConstantDataSequential **Entry = &Slot.getValue();
2447 for (ConstantDataSequential *Node = *Entry; Node;
2448 Entry = &Node->Next, Node = *Entry)
2449 if (Node->getType() == Ty)
2452 // Okay, we didn't get a hit. Create a node of the right class, link it in,
2454 if (isa<ArrayType>(Ty))
2455 return *Entry = new ConstantDataArray(Ty, Slot.getKeyData());
2457 assert(isa<VectorType>(Ty));
2458 return *Entry = new ConstantDataVector(Ty, Slot.getKeyData());
2461 void ConstantDataSequential::destroyConstant() {
2462 // Remove the constant from the StringMap.
2463 StringMap<ConstantDataSequential*> &CDSConstants =
2464 getType()->getContext().pImpl->CDSConstants;
2466 StringMap<ConstantDataSequential*>::iterator Slot =
2467 CDSConstants.find(getRawDataValues());
2469 assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
2471 ConstantDataSequential **Entry = &Slot->getValue();
2473 // Remove the entry from the hash table.
2474 if (!(*Entry)->Next) {
2475 // If there is only one value in the bucket (common case) it must be this
2476 // entry, and removing the entry should remove the bucket completely.
2477 assert((*Entry) == this && "Hash mismatch in ConstantDataSequential");
2478 getContext().pImpl->CDSConstants.erase(Slot);
2480 // Otherwise, there are multiple entries linked off the bucket, unlink the
2481 // node we care about but keep the bucket around.
2482 for (ConstantDataSequential *Node = *Entry; ;
2483 Entry = &Node->Next, Node = *Entry) {
2484 assert(Node && "Didn't find entry in its uniquing hash table!");
2485 // If we found our entry, unlink it from the list and we're done.
2487 *Entry = Node->Next;
2493 // If we were part of a list, make sure that we don't delete the list that is
2494 // still owned by the uniquing map.
2497 // Finally, actually delete it.
2498 destroyConstantImpl();
2501 /// get() constructors - Return a constant with array type with an element
2502 /// count and element type matching the ArrayRef passed in. Note that this
2503 /// can return a ConstantAggregateZero object.
2504 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint8_t> Elts) {
2505 Type *Ty = ArrayType::get(Type::getInt8Ty(Context), Elts.size());
2506 const char *Data = reinterpret_cast<const char *>(Elts.data());
2507 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*1), Ty);
2509 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
2510 Type *Ty = ArrayType::get(Type::getInt16Ty(Context), Elts.size());
2511 const char *Data = reinterpret_cast<const char *>(Elts.data());
2512 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*2), Ty);
2514 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
2515 Type *Ty = ArrayType::get(Type::getInt32Ty(Context), Elts.size());
2516 const char *Data = reinterpret_cast<const char *>(Elts.data());
2517 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
2519 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
2520 Type *Ty = ArrayType::get(Type::getInt64Ty(Context), Elts.size());
2521 const char *Data = reinterpret_cast<const char *>(Elts.data());
2522 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
2524 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<float> Elts) {
2525 Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
2526 const char *Data = reinterpret_cast<const char *>(Elts.data());
2527 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
2529 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<double> Elts) {
2530 Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
2531 const char *Data = reinterpret_cast<const char *>(Elts.data());
2532 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
2535 /// getString - This method constructs a CDS and initializes it with a text
2536 /// string. The default behavior (AddNull==true) causes a null terminator to
2537 /// be placed at the end of the array (increasing the length of the string by
2538 /// one more than the StringRef would normally indicate. Pass AddNull=false
2539 /// to disable this behavior.
2540 Constant *ConstantDataArray::getString(LLVMContext &Context,
2541 StringRef Str, bool AddNull) {
2543 const uint8_t *Data = reinterpret_cast<const uint8_t *>(Str.data());
2544 return get(Context, makeArrayRef(const_cast<uint8_t *>(Data),
2548 SmallVector<uint8_t, 64> ElementVals;
2549 ElementVals.append(Str.begin(), Str.end());
2550 ElementVals.push_back(0);
2551 return get(Context, ElementVals);
2554 /// get() constructors - Return a constant with vector type with an element
2555 /// count and element type matching the ArrayRef passed in. Note that this
2556 /// can return a ConstantAggregateZero object.
2557 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> Elts){
2558 Type *Ty = VectorType::get(Type::getInt8Ty(Context), Elts.size());
2559 const char *Data = reinterpret_cast<const char *>(Elts.data());
2560 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*1), Ty);
2562 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
2563 Type *Ty = VectorType::get(Type::getInt16Ty(Context), Elts.size());
2564 const char *Data = reinterpret_cast<const char *>(Elts.data());
2565 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*2), Ty);
2567 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
2568 Type *Ty = VectorType::get(Type::getInt32Ty(Context), Elts.size());
2569 const char *Data = reinterpret_cast<const char *>(Elts.data());
2570 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
2572 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
2573 Type *Ty = VectorType::get(Type::getInt64Ty(Context), Elts.size());
2574 const char *Data = reinterpret_cast<const char *>(Elts.data());
2575 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
2577 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> Elts) {
2578 Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
2579 const char *Data = reinterpret_cast<const char *>(Elts.data());
2580 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
2582 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<double> Elts) {
2583 Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
2584 const char *Data = reinterpret_cast<const char *>(Elts.data());
2585 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
2588 Constant *ConstantDataVector::getSplat(unsigned NumElts, Constant *V) {
2589 assert(isElementTypeCompatible(V->getType()) &&
2590 "Element type not compatible with ConstantData");
2591 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2592 if (CI->getType()->isIntegerTy(8)) {
2593 SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
2594 return get(V->getContext(), Elts);
2596 if (CI->getType()->isIntegerTy(16)) {
2597 SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
2598 return get(V->getContext(), Elts);
2600 if (CI->getType()->isIntegerTy(32)) {
2601 SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
2602 return get(V->getContext(), Elts);
2604 assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
2605 SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
2606 return get(V->getContext(), Elts);
2609 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2610 if (CFP->getType()->isFloatTy()) {
2611 SmallVector<float, 16> Elts(NumElts, CFP->getValueAPF().convertToFloat());
2612 return get(V->getContext(), Elts);
2614 if (CFP->getType()->isDoubleTy()) {
2615 SmallVector<double, 16> Elts(NumElts,
2616 CFP->getValueAPF().convertToDouble());
2617 return get(V->getContext(), Elts);
2620 return ConstantVector::getSplat(NumElts, V);
2624 /// getElementAsInteger - If this is a sequential container of integers (of
2625 /// any size), return the specified element in the low bits of a uint64_t.
2626 uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const {
2627 assert(isa<IntegerType>(getElementType()) &&
2628 "Accessor can only be used when element is an integer");
2629 const char *EltPtr = getElementPointer(Elt);
2631 // The data is stored in host byte order, make sure to cast back to the right
2632 // type to load with the right endianness.
2633 switch (getElementType()->getIntegerBitWidth()) {
2634 default: llvm_unreachable("Invalid bitwidth for CDS");
2636 return *const_cast<uint8_t *>(reinterpret_cast<const uint8_t *>(EltPtr));
2638 return *const_cast<uint16_t *>(reinterpret_cast<const uint16_t *>(EltPtr));
2640 return *const_cast<uint32_t *>(reinterpret_cast<const uint32_t *>(EltPtr));
2642 return *const_cast<uint64_t *>(reinterpret_cast<const uint64_t *>(EltPtr));
2646 /// getElementAsAPFloat - If this is a sequential container of floating point
2647 /// type, return the specified element as an APFloat.
2648 APFloat ConstantDataSequential::getElementAsAPFloat(unsigned Elt) const {
2649 const char *EltPtr = getElementPointer(Elt);
2651 switch (getElementType()->getTypeID()) {
2653 llvm_unreachable("Accessor can only be used when element is float/double!");
2654 case Type::FloatTyID: {
2655 const float *FloatPrt = reinterpret_cast<const float *>(EltPtr);
2656 return APFloat(*const_cast<float *>(FloatPrt));
2658 case Type::DoubleTyID: {
2659 const double *DoublePtr = reinterpret_cast<const double *>(EltPtr);
2660 return APFloat(*const_cast<double *>(DoublePtr));
2665 /// getElementAsFloat - If this is an sequential container of floats, return
2666 /// the specified element as a float.
2667 float ConstantDataSequential::getElementAsFloat(unsigned Elt) const {
2668 assert(getElementType()->isFloatTy() &&
2669 "Accessor can only be used when element is a 'float'");
2670 const float *EltPtr = reinterpret_cast<const float *>(getElementPointer(Elt));
2671 return *const_cast<float *>(EltPtr);
2674 /// getElementAsDouble - If this is an sequential container of doubles, return
2675 /// the specified element as a float.
2676 double ConstantDataSequential::getElementAsDouble(unsigned Elt) const {
2677 assert(getElementType()->isDoubleTy() &&
2678 "Accessor can only be used when element is a 'float'");
2679 const double *EltPtr =
2680 reinterpret_cast<const double *>(getElementPointer(Elt));
2681 return *const_cast<double *>(EltPtr);
2684 /// getElementAsConstant - Return a Constant for a specified index's element.
2685 /// Note that this has to compute a new constant to return, so it isn't as
2686 /// efficient as getElementAsInteger/Float/Double.
2687 Constant *ConstantDataSequential::getElementAsConstant(unsigned Elt) const {
2688 if (getElementType()->isFloatTy() || getElementType()->isDoubleTy())
2689 return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
2691 return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
2694 /// isString - This method returns true if this is an array of i8.
2695 bool ConstantDataSequential::isString() const {
2696 return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(8);
2699 /// isCString - This method returns true if the array "isString", ends with a
2700 /// nul byte, and does not contains any other nul bytes.
2701 bool ConstantDataSequential::isCString() const {
2705 StringRef Str = getAsString();
2707 // The last value must be nul.
2708 if (Str.back() != 0) return false;
2710 // Other elements must be non-nul.
2711 return Str.drop_back().find(0) == StringRef::npos;
2714 /// getSplatValue - If this is a splat constant, meaning that all of the
2715 /// elements have the same value, return that value. Otherwise return NULL.
2716 Constant *ConstantDataVector::getSplatValue() const {
2717 const char *Base = getRawDataValues().data();
2719 // Compare elements 1+ to the 0'th element.
2720 unsigned EltSize = getElementByteSize();
2721 for (unsigned i = 1, e = getNumElements(); i != e; ++i)
2722 if (memcmp(Base, Base+i*EltSize, EltSize))
2725 // If they're all the same, return the 0th one as a representative.
2726 return getElementAsConstant(0);
2729 //===----------------------------------------------------------------------===//
2730 // replaceUsesOfWithOnConstant implementations
2732 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2733 /// 'From' to be uses of 'To'. This must update the uniquing data structures
2736 /// Note that we intentionally replace all uses of From with To here. Consider
2737 /// a large array that uses 'From' 1000 times. By handling this case all here,
2738 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2739 /// single invocation handles all 1000 uses. Handling them one at a time would
2740 /// work, but would be really slow because it would have to unique each updated
2743 void Constant::replaceUsesOfWithOnConstantImpl(Constant *Replacement) {
2744 // I do need to replace this with an existing value.
2745 assert(Replacement != this && "I didn't contain From!");
2747 // Everyone using this now uses the replacement.
2748 replaceAllUsesWith(Replacement);
2750 // Delete the old constant!
2754 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
2756 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2757 Constant *ToC = cast<Constant>(To);
2759 SmallVector<Constant*, 8> Values;
2760 Values.reserve(getNumOperands()); // Build replacement array.
2762 // Fill values with the modified operands of the constant array. Also,
2763 // compute whether this turns into an all-zeros array.
2764 unsigned NumUpdated = 0;
2766 // Keep track of whether all the values in the array are "ToC".
2767 bool AllSame = true;
2768 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2769 Constant *Val = cast<Constant>(O->get());
2774 Values.push_back(Val);
2775 AllSame &= Val == ToC;
2778 if (AllSame && ToC->isNullValue()) {
2779 replaceUsesOfWithOnConstantImpl(ConstantAggregateZero::get(getType()));
2782 if (AllSame && isa<UndefValue>(ToC)) {
2783 replaceUsesOfWithOnConstantImpl(UndefValue::get(getType()));
2787 // Check for any other type of constant-folding.
2788 if (Constant *C = getImpl(getType(), Values)) {
2789 replaceUsesOfWithOnConstantImpl(C);
2793 // Update to the new value.
2794 if (Constant *C = getContext().pImpl->ArrayConstants.replaceOperandsInPlace(
2795 Values, this, From, ToC, NumUpdated, U - OperandList))
2796 replaceUsesOfWithOnConstantImpl(C);
2799 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2801 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2802 Constant *ToC = cast<Constant>(To);
2804 unsigned OperandToUpdate = U-OperandList;
2805 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2807 SmallVector<Constant*, 8> Values;
2808 Values.reserve(getNumOperands()); // Build replacement struct.
2810 // Fill values with the modified operands of the constant struct. Also,
2811 // compute whether this turns into an all-zeros struct.
2812 bool isAllZeros = false;
2813 bool isAllUndef = false;
2814 if (ToC->isNullValue()) {
2816 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2817 Constant *Val = cast<Constant>(O->get());
2818 Values.push_back(Val);
2819 if (isAllZeros) isAllZeros = Val->isNullValue();
2821 } else if (isa<UndefValue>(ToC)) {
2823 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2824 Constant *Val = cast<Constant>(O->get());
2825 Values.push_back(Val);
2826 if (isAllUndef) isAllUndef = isa<UndefValue>(Val);
2829 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
2830 Values.push_back(cast<Constant>(O->get()));
2832 Values[OperandToUpdate] = ToC;
2835 replaceUsesOfWithOnConstantImpl(ConstantAggregateZero::get(getType()));
2839 replaceUsesOfWithOnConstantImpl(UndefValue::get(getType()));
2843 // Update to the new value.
2844 if (Constant *C = getContext().pImpl->StructConstants.replaceOperandsInPlace(
2845 Values, this, From, ToC))
2846 replaceUsesOfWithOnConstantImpl(C);
2849 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2851 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2852 Constant *ToC = cast<Constant>(To);
2854 SmallVector<Constant*, 8> Values;
2855 Values.reserve(getNumOperands()); // Build replacement array...
2856 unsigned NumUpdated = 0;
2857 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2858 Constant *Val = getOperand(i);
2863 Values.push_back(Val);
2866 if (Constant *C = getImpl(Values)) {
2867 replaceUsesOfWithOnConstantImpl(C);
2871 // Update to the new value.
2872 if (Constant *C = getContext().pImpl->VectorConstants.replaceOperandsInPlace(
2873 Values, this, From, ToC, NumUpdated, U - OperandList))
2874 replaceUsesOfWithOnConstantImpl(C);
2877 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2879 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2880 Constant *To = cast<Constant>(ToV);
2882 SmallVector<Constant*, 8> NewOps;
2883 unsigned NumUpdated = 0;
2884 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2885 Constant *Op = getOperand(i);
2890 NewOps.push_back(Op);
2892 assert(NumUpdated && "I didn't contain From!");
2894 if (Constant *C = getWithOperands(NewOps, getType(), true)) {
2895 replaceUsesOfWithOnConstantImpl(C);
2899 // Update to the new value.
2900 if (Constant *C = getContext().pImpl->ExprConstants.replaceOperandsInPlace(
2901 NewOps, this, From, To, NumUpdated, U - OperandList))
2902 replaceUsesOfWithOnConstantImpl(C);
2905 Instruction *ConstantExpr::getAsInstruction() {
2906 SmallVector<Value*,4> ValueOperands;
2907 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
2908 ValueOperands.push_back(cast<Value>(I));
2910 ArrayRef<Value*> Ops(ValueOperands);
2912 switch (getOpcode()) {
2913 case Instruction::Trunc:
2914 case Instruction::ZExt:
2915 case Instruction::SExt:
2916 case Instruction::FPTrunc:
2917 case Instruction::FPExt:
2918 case Instruction::UIToFP:
2919 case Instruction::SIToFP:
2920 case Instruction::FPToUI:
2921 case Instruction::FPToSI:
2922 case Instruction::PtrToInt:
2923 case Instruction::IntToPtr:
2924 case Instruction::BitCast:
2925 case Instruction::AddrSpaceCast:
2926 return CastInst::Create((Instruction::CastOps)getOpcode(),
2928 case Instruction::Select:
2929 return SelectInst::Create(Ops[0], Ops[1], Ops[2]);
2930 case Instruction::InsertElement:
2931 return InsertElementInst::Create(Ops[0], Ops[1], Ops[2]);
2932 case Instruction::ExtractElement:
2933 return ExtractElementInst::Create(Ops[0], Ops[1]);
2934 case Instruction::InsertValue:
2935 return InsertValueInst::Create(Ops[0], Ops[1], getIndices());
2936 case Instruction::ExtractValue:
2937 return ExtractValueInst::Create(Ops[0], getIndices());
2938 case Instruction::ShuffleVector:
2939 return new ShuffleVectorInst(Ops[0], Ops[1], Ops[2]);
2941 case Instruction::GetElementPtr:
2942 if (cast<GEPOperator>(this)->isInBounds())
2943 return GetElementPtrInst::CreateInBounds(Ops[0], Ops.slice(1));
2945 return GetElementPtrInst::Create(Ops[0], Ops.slice(1));
2947 case Instruction::ICmp:
2948 case Instruction::FCmp:
2949 return CmpInst::Create((Instruction::OtherOps)getOpcode(),
2950 getPredicate(), Ops[0], Ops[1]);
2953 assert(getNumOperands() == 2 && "Must be binary operator?");
2954 BinaryOperator *BO =
2955 BinaryOperator::Create((Instruction::BinaryOps)getOpcode(),
2957 if (isa<OverflowingBinaryOperator>(BO)) {
2958 BO->setHasNoUnsignedWrap(SubclassOptionalData &
2959 OverflowingBinaryOperator::NoUnsignedWrap);
2960 BO->setHasNoSignedWrap(SubclassOptionalData &
2961 OverflowingBinaryOperator::NoSignedWrap);
2963 if (isa<PossiblyExactOperator>(BO))
2964 BO->setIsExact(SubclassOptionalData & PossiblyExactOperator::IsExact);