1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Constant* classes.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Constants.h"
15 #include "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/DerivedTypes.h"
24 #include "llvm/GlobalValue.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Module.h"
27 #include "llvm/Operator.h"
28 #include "llvm/Support/Compiler.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/GetElementPtrTypeIterator.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 // Otherwise, just use +0.0.
54 bool Constant::isNullValue() const {
56 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
60 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
61 return CFP->isZero() && !CFP->isNegative();
63 // constant zero is zero for aggregates and cpnull is null for pointers.
64 return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this);
67 bool Constant::isAllOnesValue() const {
68 // Check for -1 integers
69 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
70 return CI->isMinusOne();
72 // Check for FP which are bitcasted from -1 integers
73 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
74 return CFP->getValueAPF().bitcastToAPInt().isAllOnesValue();
76 // Check for constant vectors which are splats of -1 values.
77 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
78 if (Constant *Splat = CV->getSplatValue())
79 return Splat->isAllOnesValue();
81 // Check for constant vectors which are splats of -1 values.
82 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
83 if (Constant *Splat = CV->getSplatValue())
84 return Splat->isAllOnesValue();
89 // Constructor to create a '0' constant of arbitrary type...
90 Constant *Constant::getNullValue(Type *Ty) {
91 switch (Ty->getTypeID()) {
92 case Type::IntegerTyID:
93 return ConstantInt::get(Ty, 0);
95 return ConstantFP::get(Ty->getContext(),
96 APFloat::getZero(APFloat::IEEEhalf));
98 return ConstantFP::get(Ty->getContext(),
99 APFloat::getZero(APFloat::IEEEsingle));
100 case Type::DoubleTyID:
101 return ConstantFP::get(Ty->getContext(),
102 APFloat::getZero(APFloat::IEEEdouble));
103 case Type::X86_FP80TyID:
104 return ConstantFP::get(Ty->getContext(),
105 APFloat::getZero(APFloat::x87DoubleExtended));
106 case Type::FP128TyID:
107 return ConstantFP::get(Ty->getContext(),
108 APFloat::getZero(APFloat::IEEEquad));
109 case Type::PPC_FP128TyID:
110 return ConstantFP::get(Ty->getContext(),
111 APFloat(APInt::getNullValue(128)));
112 case Type::PointerTyID:
113 return ConstantPointerNull::get(cast<PointerType>(Ty));
114 case Type::StructTyID:
115 case Type::ArrayTyID:
116 case Type::VectorTyID:
117 return ConstantAggregateZero::get(Ty);
119 // Function, Label, or Opaque type?
120 llvm_unreachable("Cannot create a null constant of that type!");
124 Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) {
125 Type *ScalarTy = Ty->getScalarType();
127 // Create the base integer constant.
128 Constant *C = ConstantInt::get(Ty->getContext(), V);
130 // Convert an integer to a pointer, if necessary.
131 if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
132 C = ConstantExpr::getIntToPtr(C, PTy);
134 // Broadcast a scalar to a vector, if necessary.
135 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
136 C = ConstantVector::getSplat(VTy->getNumElements(), C);
141 Constant *Constant::getAllOnesValue(Type *Ty) {
142 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
143 return ConstantInt::get(Ty->getContext(),
144 APInt::getAllOnesValue(ITy->getBitWidth()));
146 if (Ty->isFloatingPointTy()) {
147 APFloat FL = APFloat::getAllOnesValue(Ty->getPrimitiveSizeInBits(),
148 !Ty->isPPC_FP128Ty());
149 return ConstantFP::get(Ty->getContext(), FL);
152 VectorType *VTy = cast<VectorType>(Ty);
153 return ConstantVector::getSplat(VTy->getNumElements(),
154 getAllOnesValue(VTy->getElementType()));
157 /// getAggregateElement - For aggregates (struct/array/vector) return the
158 /// constant that corresponds to the specified element if possible, or null if
159 /// not. This can return null if the element index is a ConstantExpr, or if
160 /// 'this' is a constant expr.
161 Constant *Constant::getAggregateElement(unsigned Elt) const {
162 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(this))
163 return Elt < CS->getNumOperands() ? CS->getOperand(Elt) : 0;
165 if (const ConstantArray *CA = dyn_cast<ConstantArray>(this))
166 return Elt < CA->getNumOperands() ? CA->getOperand(Elt) : 0;
168 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
169 return Elt < CV->getNumOperands() ? CV->getOperand(Elt) : 0;
171 if (const ConstantAggregateZero *CAZ =dyn_cast<ConstantAggregateZero>(this))
172 return CAZ->getElementValue(Elt);
174 if (const UndefValue *UV = dyn_cast<UndefValue>(this))
175 return UV->getElementValue(Elt);
177 if (const ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(this))
178 return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt) : 0;
182 Constant *Constant::getAggregateElement(Constant *Elt) const {
183 assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
184 if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt))
185 return getAggregateElement(CI->getZExtValue());
190 void Constant::destroyConstantImpl() {
191 // When a Constant is destroyed, there may be lingering
192 // references to the constant by other constants in the constant pool. These
193 // constants are implicitly dependent on the module that is being deleted,
194 // but they don't know that. Because we only find out when the CPV is
195 // deleted, we must now notify all of our users (that should only be
196 // Constants) that they are, in fact, invalid now and should be deleted.
198 while (!use_empty()) {
199 Value *V = use_back();
200 #ifndef NDEBUG // Only in -g mode...
201 if (!isa<Constant>(V)) {
202 dbgs() << "While deleting: " << *this
203 << "\n\nUse still stuck around after Def is destroyed: "
207 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
208 cast<Constant>(V)->destroyConstant();
210 // The constant should remove itself from our use list...
211 assert((use_empty() || use_back() != V) && "Constant not removed!");
214 // Value has no outstanding references it is safe to delete it now...
218 /// canTrap - Return true if evaluation of this constant could trap. This is
219 /// true for things like constant expressions that could divide by zero.
220 bool Constant::canTrap() const {
221 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
222 // The only thing that could possibly trap are constant exprs.
223 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
224 if (!CE) return false;
226 // ConstantExpr traps if any operands can trap.
227 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
228 if (CE->getOperand(i)->canTrap())
231 // Otherwise, only specific operations can trap.
232 switch (CE->getOpcode()) {
235 case Instruction::UDiv:
236 case Instruction::SDiv:
237 case Instruction::FDiv:
238 case Instruction::URem:
239 case Instruction::SRem:
240 case Instruction::FRem:
241 // Div and rem can trap if the RHS is not known to be non-zero.
242 if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
248 /// isThreadDependent - Return true if the value can vary between threads.
249 bool Constant::isThreadDependent() const {
250 SmallPtrSet<const Constant*, 64> Visited;
251 SmallVector<const Constant*, 64> WorkList;
252 WorkList.push_back(this);
253 Visited.insert(this);
255 while (!WorkList.empty()) {
256 const Constant *C = WorkList.pop_back_val();
258 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
259 if (GV->isThreadLocal())
263 for (unsigned I = 0, E = C->getNumOperands(); I != E; ++I) {
264 const Constant *D = dyn_cast<Constant>(C->getOperand(I));
267 if (Visited.insert(D))
268 WorkList.push_back(D);
275 /// isConstantUsed - Return true if the constant has users other than constant
276 /// exprs and other dangling things.
277 bool Constant::isConstantUsed() const {
278 for (const_use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
279 const Constant *UC = dyn_cast<Constant>(*UI);
280 if (UC == 0 || isa<GlobalValue>(UC))
283 if (UC->isConstantUsed())
291 /// getRelocationInfo - This method classifies the entry according to
292 /// whether or not it may generate a relocation entry. This must be
293 /// conservative, so if it might codegen to a relocatable entry, it should say
294 /// so. The return values are:
296 /// NoRelocation: This constant pool entry is guaranteed to never have a
297 /// relocation applied to it (because it holds a simple constant like
299 /// LocalRelocation: This entry has relocations, but the entries are
300 /// guaranteed to be resolvable by the static linker, so the dynamic
301 /// linker will never see them.
302 /// GlobalRelocations: This entry may have arbitrary relocations.
304 /// FIXME: This really should not be in VMCore.
305 Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
306 if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
307 if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
308 return LocalRelocation; // Local to this file/library.
309 return GlobalRelocations; // Global reference.
312 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
313 return BA->getFunction()->getRelocationInfo();
315 // While raw uses of blockaddress need to be relocated, differences between
316 // two of them don't when they are for labels in the same function. This is a
317 // common idiom when creating a table for the indirect goto extension, so we
318 // handle it efficiently here.
319 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this))
320 if (CE->getOpcode() == Instruction::Sub) {
321 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
322 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
324 LHS->getOpcode() == Instruction::PtrToInt &&
325 RHS->getOpcode() == Instruction::PtrToInt &&
326 isa<BlockAddress>(LHS->getOperand(0)) &&
327 isa<BlockAddress>(RHS->getOperand(0)) &&
328 cast<BlockAddress>(LHS->getOperand(0))->getFunction() ==
329 cast<BlockAddress>(RHS->getOperand(0))->getFunction())
333 PossibleRelocationsTy Result = NoRelocation;
334 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
335 Result = std::max(Result,
336 cast<Constant>(getOperand(i))->getRelocationInfo());
341 /// removeDeadUsersOfConstant - If the specified constantexpr is dead, remove
342 /// it. This involves recursively eliminating any dead users of the
344 static bool removeDeadUsersOfConstant(const Constant *C) {
345 if (isa<GlobalValue>(C)) return false; // Cannot remove this
347 while (!C->use_empty()) {
348 const Constant *User = dyn_cast<Constant>(C->use_back());
349 if (!User) return false; // Non-constant usage;
350 if (!removeDeadUsersOfConstant(User))
351 return false; // Constant wasn't dead
354 const_cast<Constant*>(C)->destroyConstant();
359 /// removeDeadConstantUsers - If there are any dead constant users dangling
360 /// off of this constant, remove them. This method is useful for clients
361 /// that want to check to see if a global is unused, but don't want to deal
362 /// with potentially dead constants hanging off of the globals.
363 void Constant::removeDeadConstantUsers() const {
364 Value::const_use_iterator I = use_begin(), E = use_end();
365 Value::const_use_iterator LastNonDeadUser = E;
367 const Constant *User = dyn_cast<Constant>(*I);
374 if (!removeDeadUsersOfConstant(User)) {
375 // If the constant wasn't dead, remember that this was the last live use
376 // and move on to the next constant.
382 // If the constant was dead, then the iterator is invalidated.
383 if (LastNonDeadUser == E) {
395 //===----------------------------------------------------------------------===//
397 //===----------------------------------------------------------------------===//
399 void ConstantInt::anchor() { }
401 ConstantInt::ConstantInt(IntegerType *Ty, const APInt& V)
402 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
403 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
406 ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
407 LLVMContextImpl *pImpl = Context.pImpl;
408 if (!pImpl->TheTrueVal)
409 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
410 return pImpl->TheTrueVal;
413 ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
414 LLVMContextImpl *pImpl = Context.pImpl;
415 if (!pImpl->TheFalseVal)
416 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
417 return pImpl->TheFalseVal;
420 Constant *ConstantInt::getTrue(Type *Ty) {
421 VectorType *VTy = dyn_cast<VectorType>(Ty);
423 assert(Ty->isIntegerTy(1) && "True must be i1 or vector of i1.");
424 return ConstantInt::getTrue(Ty->getContext());
426 assert(VTy->getElementType()->isIntegerTy(1) &&
427 "True must be vector of i1 or i1.");
428 return ConstantVector::getSplat(VTy->getNumElements(),
429 ConstantInt::getTrue(Ty->getContext()));
432 Constant *ConstantInt::getFalse(Type *Ty) {
433 VectorType *VTy = dyn_cast<VectorType>(Ty);
435 assert(Ty->isIntegerTy(1) && "False must be i1 or vector of i1.");
436 return ConstantInt::getFalse(Ty->getContext());
438 assert(VTy->getElementType()->isIntegerTy(1) &&
439 "False must be vector of i1 or i1.");
440 return ConstantVector::getSplat(VTy->getNumElements(),
441 ConstantInt::getFalse(Ty->getContext()));
445 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
446 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
447 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
448 // compare APInt's of different widths, which would violate an APInt class
449 // invariant which generates an assertion.
450 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
451 // Get the corresponding integer type for the bit width of the value.
452 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
453 // get an existing value or the insertion position
454 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
455 ConstantInt *&Slot = Context.pImpl->IntConstants[Key];
456 if (!Slot) Slot = new ConstantInt(ITy, V);
460 Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
461 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
463 // For vectors, broadcast the value.
464 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
465 return ConstantVector::getSplat(VTy->getNumElements(), C);
470 ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V,
472 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
475 ConstantInt *ConstantInt::getSigned(IntegerType *Ty, int64_t V) {
476 return get(Ty, V, true);
479 Constant *ConstantInt::getSigned(Type *Ty, int64_t V) {
480 return get(Ty, V, true);
483 Constant *ConstantInt::get(Type *Ty, const APInt& V) {
484 ConstantInt *C = get(Ty->getContext(), V);
485 assert(C->getType() == Ty->getScalarType() &&
486 "ConstantInt type doesn't match the type implied by its value!");
488 // For vectors, broadcast the value.
489 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
490 return ConstantVector::getSplat(VTy->getNumElements(), C);
495 ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str,
497 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
500 //===----------------------------------------------------------------------===//
502 //===----------------------------------------------------------------------===//
504 static const fltSemantics *TypeToFloatSemantics(Type *Ty) {
506 return &APFloat::IEEEhalf;
508 return &APFloat::IEEEsingle;
509 if (Ty->isDoubleTy())
510 return &APFloat::IEEEdouble;
511 if (Ty->isX86_FP80Ty())
512 return &APFloat::x87DoubleExtended;
513 else if (Ty->isFP128Ty())
514 return &APFloat::IEEEquad;
516 assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
517 return &APFloat::PPCDoubleDouble;
520 void ConstantFP::anchor() { }
522 /// get() - This returns a constant fp for the specified value in the
523 /// specified type. This should only be used for simple constant values like
524 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
525 Constant *ConstantFP::get(Type *Ty, double V) {
526 LLVMContext &Context = Ty->getContext();
530 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
531 APFloat::rmNearestTiesToEven, &ignored);
532 Constant *C = get(Context, FV);
534 // For vectors, broadcast the value.
535 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
536 return ConstantVector::getSplat(VTy->getNumElements(), C);
542 Constant *ConstantFP::get(Type *Ty, StringRef Str) {
543 LLVMContext &Context = Ty->getContext();
545 APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
546 Constant *C = get(Context, FV);
548 // For vectors, broadcast the value.
549 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
550 return ConstantVector::getSplat(VTy->getNumElements(), C);
556 ConstantFP *ConstantFP::getNegativeZero(Type *Ty) {
557 LLVMContext &Context = Ty->getContext();
558 APFloat apf = cast<ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
560 return get(Context, apf);
564 Constant *ConstantFP::getZeroValueForNegation(Type *Ty) {
565 Type *ScalarTy = Ty->getScalarType();
566 if (ScalarTy->isFloatingPointTy()) {
567 Constant *C = getNegativeZero(ScalarTy);
568 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
569 return ConstantVector::getSplat(VTy->getNumElements(), C);
573 return Constant::getNullValue(Ty);
577 // ConstantFP accessors.
578 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
579 DenseMapAPFloatKeyInfo::KeyTy Key(V);
581 LLVMContextImpl* pImpl = Context.pImpl;
583 ConstantFP *&Slot = pImpl->FPConstants[Key];
587 if (&V.getSemantics() == &APFloat::IEEEhalf)
588 Ty = Type::getHalfTy(Context);
589 else if (&V.getSemantics() == &APFloat::IEEEsingle)
590 Ty = Type::getFloatTy(Context);
591 else if (&V.getSemantics() == &APFloat::IEEEdouble)
592 Ty = Type::getDoubleTy(Context);
593 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
594 Ty = Type::getX86_FP80Ty(Context);
595 else if (&V.getSemantics() == &APFloat::IEEEquad)
596 Ty = Type::getFP128Ty(Context);
598 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
599 "Unknown FP format");
600 Ty = Type::getPPC_FP128Ty(Context);
602 Slot = new ConstantFP(Ty, V);
608 ConstantFP *ConstantFP::getInfinity(Type *Ty, bool Negative) {
609 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty);
610 return ConstantFP::get(Ty->getContext(),
611 APFloat::getInf(Semantics, Negative));
614 ConstantFP::ConstantFP(Type *Ty, const APFloat& V)
615 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
616 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
620 bool ConstantFP::isExactlyValue(const APFloat &V) const {
621 return Val.bitwiseIsEqual(V);
624 //===----------------------------------------------------------------------===//
625 // ConstantAggregateZero Implementation
626 //===----------------------------------------------------------------------===//
628 /// getSequentialElement - If this CAZ has array or vector type, return a zero
629 /// with the right element type.
630 Constant *ConstantAggregateZero::getSequentialElement() const {
631 return Constant::getNullValue(getType()->getSequentialElementType());
634 /// getStructElement - If this CAZ has struct type, return a zero with the
635 /// right element type for the specified element.
636 Constant *ConstantAggregateZero::getStructElement(unsigned Elt) const {
637 return Constant::getNullValue(getType()->getStructElementType(Elt));
640 /// getElementValue - Return a zero of the right value for the specified GEP
641 /// index if we can, otherwise return null (e.g. if C is a ConstantExpr).
642 Constant *ConstantAggregateZero::getElementValue(Constant *C) const {
643 if (isa<SequentialType>(getType()))
644 return getSequentialElement();
645 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
648 /// getElementValue - Return a zero of the right value for the specified GEP
650 Constant *ConstantAggregateZero::getElementValue(unsigned Idx) const {
651 if (isa<SequentialType>(getType()))
652 return getSequentialElement();
653 return getStructElement(Idx);
657 //===----------------------------------------------------------------------===//
658 // UndefValue Implementation
659 //===----------------------------------------------------------------------===//
661 /// getSequentialElement - If this undef has array or vector type, return an
662 /// undef with the right element type.
663 UndefValue *UndefValue::getSequentialElement() const {
664 return UndefValue::get(getType()->getSequentialElementType());
667 /// getStructElement - If this undef has struct type, return a zero with the
668 /// right element type for the specified element.
669 UndefValue *UndefValue::getStructElement(unsigned Elt) const {
670 return UndefValue::get(getType()->getStructElementType(Elt));
673 /// getElementValue - Return an undef of the right value for the specified GEP
674 /// index if we can, otherwise return null (e.g. if C is a ConstantExpr).
675 UndefValue *UndefValue::getElementValue(Constant *C) const {
676 if (isa<SequentialType>(getType()))
677 return getSequentialElement();
678 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
681 /// getElementValue - Return an undef of the right value for the specified GEP
683 UndefValue *UndefValue::getElementValue(unsigned Idx) const {
684 if (isa<SequentialType>(getType()))
685 return getSequentialElement();
686 return getStructElement(Idx);
691 //===----------------------------------------------------------------------===//
692 // ConstantXXX Classes
693 //===----------------------------------------------------------------------===//
695 template <typename ItTy, typename EltTy>
696 static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
697 for (; Start != End; ++Start)
703 ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
704 : Constant(T, ConstantArrayVal,
705 OperandTraits<ConstantArray>::op_end(this) - V.size(),
707 assert(V.size() == T->getNumElements() &&
708 "Invalid initializer vector for constant array");
709 for (unsigned i = 0, e = V.size(); i != e; ++i)
710 assert(V[i]->getType() == T->getElementType() &&
711 "Initializer for array element doesn't match array element type!");
712 std::copy(V.begin(), V.end(), op_begin());
715 Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
716 // Empty arrays are canonicalized to ConstantAggregateZero.
718 return ConstantAggregateZero::get(Ty);
720 for (unsigned i = 0, e = V.size(); i != e; ++i) {
721 assert(V[i]->getType() == Ty->getElementType() &&
722 "Wrong type in array element initializer");
724 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
726 // If this is an all-zero array, return a ConstantAggregateZero object. If
727 // all undef, return an UndefValue, if "all simple", then return a
728 // ConstantDataArray.
730 if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
731 return UndefValue::get(Ty);
733 if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
734 return ConstantAggregateZero::get(Ty);
736 // Check to see if all of the elements are ConstantFP or ConstantInt and if
737 // the element type is compatible with ConstantDataVector. If so, use it.
738 if (ConstantDataSequential::isElementTypeCompatible(C->getType())) {
739 // We speculatively build the elements here even if it turns out that there
740 // is a constantexpr or something else weird in the array, since it is so
741 // uncommon for that to happen.
742 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
743 if (CI->getType()->isIntegerTy(8)) {
744 SmallVector<uint8_t, 16> Elts;
745 for (unsigned i = 0, e = V.size(); i != e; ++i)
746 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
747 Elts.push_back(CI->getZExtValue());
750 if (Elts.size() == V.size())
751 return ConstantDataArray::get(C->getContext(), Elts);
752 } else if (CI->getType()->isIntegerTy(16)) {
753 SmallVector<uint16_t, 16> Elts;
754 for (unsigned i = 0, e = V.size(); i != e; ++i)
755 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
756 Elts.push_back(CI->getZExtValue());
759 if (Elts.size() == V.size())
760 return ConstantDataArray::get(C->getContext(), Elts);
761 } else if (CI->getType()->isIntegerTy(32)) {
762 SmallVector<uint32_t, 16> Elts;
763 for (unsigned i = 0, e = V.size(); i != e; ++i)
764 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
765 Elts.push_back(CI->getZExtValue());
768 if (Elts.size() == V.size())
769 return ConstantDataArray::get(C->getContext(), Elts);
770 } else if (CI->getType()->isIntegerTy(64)) {
771 SmallVector<uint64_t, 16> Elts;
772 for (unsigned i = 0, e = V.size(); i != e; ++i)
773 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
774 Elts.push_back(CI->getZExtValue());
777 if (Elts.size() == V.size())
778 return ConstantDataArray::get(C->getContext(), Elts);
782 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
783 if (CFP->getType()->isFloatTy()) {
784 SmallVector<float, 16> Elts;
785 for (unsigned i = 0, e = V.size(); i != e; ++i)
786 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
787 Elts.push_back(CFP->getValueAPF().convertToFloat());
790 if (Elts.size() == V.size())
791 return ConstantDataArray::get(C->getContext(), Elts);
792 } else if (CFP->getType()->isDoubleTy()) {
793 SmallVector<double, 16> Elts;
794 for (unsigned i = 0, e = V.size(); i != e; ++i)
795 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
796 Elts.push_back(CFP->getValueAPF().convertToDouble());
799 if (Elts.size() == V.size())
800 return ConstantDataArray::get(C->getContext(), Elts);
805 // Otherwise, we really do want to create a ConstantArray.
806 return pImpl->ArrayConstants.getOrCreate(Ty, V);
809 /// getTypeForElements - Return an anonymous struct type to use for a constant
810 /// with the specified set of elements. The list must not be empty.
811 StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
812 ArrayRef<Constant*> V,
814 unsigned VecSize = V.size();
815 SmallVector<Type*, 16> EltTypes(VecSize);
816 for (unsigned i = 0; i != VecSize; ++i)
817 EltTypes[i] = V[i]->getType();
819 return StructType::get(Context, EltTypes, Packed);
823 StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
826 "ConstantStruct::getTypeForElements cannot be called on empty list");
827 return getTypeForElements(V[0]->getContext(), V, Packed);
831 ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
832 : Constant(T, ConstantStructVal,
833 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
835 assert(V.size() == T->getNumElements() &&
836 "Invalid initializer vector for constant structure");
837 for (unsigned i = 0, e = V.size(); i != e; ++i)
838 assert((T->isOpaque() || V[i]->getType() == T->getElementType(i)) &&
839 "Initializer for struct element doesn't match struct element type!");
840 std::copy(V.begin(), V.end(), op_begin());
843 // ConstantStruct accessors.
844 Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
845 assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
846 "Incorrect # elements specified to ConstantStruct::get");
848 // Create a ConstantAggregateZero value if all elements are zeros.
850 bool isUndef = false;
853 isUndef = isa<UndefValue>(V[0]);
854 isZero = V[0]->isNullValue();
855 if (isUndef || isZero) {
856 for (unsigned i = 0, e = V.size(); i != e; ++i) {
857 if (!V[i]->isNullValue())
859 if (!isa<UndefValue>(V[i]))
865 return ConstantAggregateZero::get(ST);
867 return UndefValue::get(ST);
869 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
872 Constant *ConstantStruct::get(StructType *T, ...) {
874 SmallVector<Constant*, 8> Values;
876 while (Constant *Val = va_arg(ap, llvm::Constant*))
877 Values.push_back(Val);
879 return get(T, Values);
882 ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
883 : Constant(T, ConstantVectorVal,
884 OperandTraits<ConstantVector>::op_end(this) - V.size(),
886 for (size_t i = 0, e = V.size(); i != e; i++)
887 assert(V[i]->getType() == T->getElementType() &&
888 "Initializer for vector element doesn't match vector element type!");
889 std::copy(V.begin(), V.end(), op_begin());
892 // ConstantVector accessors.
893 Constant *ConstantVector::get(ArrayRef<Constant*> V) {
894 assert(!V.empty() && "Vectors can't be empty");
895 VectorType *T = VectorType::get(V.front()->getType(), V.size());
896 LLVMContextImpl *pImpl = T->getContext().pImpl;
898 // If this is an all-undef or all-zero vector, return a
899 // ConstantAggregateZero or UndefValue.
901 bool isZero = C->isNullValue();
902 bool isUndef = isa<UndefValue>(C);
904 if (isZero || isUndef) {
905 for (unsigned i = 1, e = V.size(); i != e; ++i)
907 isZero = isUndef = false;
913 return ConstantAggregateZero::get(T);
915 return UndefValue::get(T);
917 // Check to see if all of the elements are ConstantFP or ConstantInt and if
918 // the element type is compatible with ConstantDataVector. If so, use it.
919 if (ConstantDataSequential::isElementTypeCompatible(C->getType())) {
920 // We speculatively build the elements here even if it turns out that there
921 // is a constantexpr or something else weird in the array, since it is so
922 // uncommon for that to happen.
923 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
924 if (CI->getType()->isIntegerTy(8)) {
925 SmallVector<uint8_t, 16> Elts;
926 for (unsigned i = 0, e = V.size(); i != e; ++i)
927 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
928 Elts.push_back(CI->getZExtValue());
931 if (Elts.size() == V.size())
932 return ConstantDataVector::get(C->getContext(), Elts);
933 } else if (CI->getType()->isIntegerTy(16)) {
934 SmallVector<uint16_t, 16> Elts;
935 for (unsigned i = 0, e = V.size(); i != e; ++i)
936 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
937 Elts.push_back(CI->getZExtValue());
940 if (Elts.size() == V.size())
941 return ConstantDataVector::get(C->getContext(), Elts);
942 } else if (CI->getType()->isIntegerTy(32)) {
943 SmallVector<uint32_t, 16> Elts;
944 for (unsigned i = 0, e = V.size(); i != e; ++i)
945 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
946 Elts.push_back(CI->getZExtValue());
949 if (Elts.size() == V.size())
950 return ConstantDataVector::get(C->getContext(), Elts);
951 } else if (CI->getType()->isIntegerTy(64)) {
952 SmallVector<uint64_t, 16> Elts;
953 for (unsigned i = 0, e = V.size(); i != e; ++i)
954 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
955 Elts.push_back(CI->getZExtValue());
958 if (Elts.size() == V.size())
959 return ConstantDataVector::get(C->getContext(), Elts);
963 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
964 if (CFP->getType()->isFloatTy()) {
965 SmallVector<float, 16> Elts;
966 for (unsigned i = 0, e = V.size(); i != e; ++i)
967 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
968 Elts.push_back(CFP->getValueAPF().convertToFloat());
971 if (Elts.size() == V.size())
972 return ConstantDataVector::get(C->getContext(), Elts);
973 } else if (CFP->getType()->isDoubleTy()) {
974 SmallVector<double, 16> Elts;
975 for (unsigned i = 0, e = V.size(); i != e; ++i)
976 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
977 Elts.push_back(CFP->getValueAPF().convertToDouble());
980 if (Elts.size() == V.size())
981 return ConstantDataVector::get(C->getContext(), Elts);
986 // Otherwise, the element type isn't compatible with ConstantDataVector, or
987 // the operand list constants a ConstantExpr or something else strange.
988 return pImpl->VectorConstants.getOrCreate(T, V);
991 Constant *ConstantVector::getSplat(unsigned NumElts, Constant *V) {
992 // If this splat is compatible with ConstantDataVector, use it instead of
994 if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&
995 ConstantDataSequential::isElementTypeCompatible(V->getType()))
996 return ConstantDataVector::getSplat(NumElts, V);
998 SmallVector<Constant*, 32> Elts(NumElts, V);
1003 // Utility function for determining if a ConstantExpr is a CastOp or not. This
1004 // can't be inline because we don't want to #include Instruction.h into
1006 bool ConstantExpr::isCast() const {
1007 return Instruction::isCast(getOpcode());
1010 bool ConstantExpr::isCompare() const {
1011 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
1014 bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
1015 if (getOpcode() != Instruction::GetElementPtr) return false;
1017 gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
1018 User::const_op_iterator OI = llvm::next(this->op_begin());
1020 // Skip the first index, as it has no static limit.
1024 // The remaining indices must be compile-time known integers within the
1025 // bounds of the corresponding notional static array types.
1026 for (; GEPI != E; ++GEPI, ++OI) {
1027 ConstantInt *CI = dyn_cast<ConstantInt>(*OI);
1028 if (!CI) return false;
1029 if (ArrayType *ATy = dyn_cast<ArrayType>(*GEPI))
1030 if (CI->getValue().getActiveBits() > 64 ||
1031 CI->getZExtValue() >= ATy->getNumElements())
1035 // All the indices checked out.
1039 bool ConstantExpr::hasIndices() const {
1040 return getOpcode() == Instruction::ExtractValue ||
1041 getOpcode() == Instruction::InsertValue;
1044 ArrayRef<unsigned> ConstantExpr::getIndices() const {
1045 if (const ExtractValueConstantExpr *EVCE =
1046 dyn_cast<ExtractValueConstantExpr>(this))
1047 return EVCE->Indices;
1049 return cast<InsertValueConstantExpr>(this)->Indices;
1052 unsigned ConstantExpr::getPredicate() const {
1053 assert(isCompare());
1054 return ((const CompareConstantExpr*)this)->predicate;
1057 /// getWithOperandReplaced - Return a constant expression identical to this
1058 /// one, but with the specified operand set to the specified value.
1060 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
1061 assert(Op->getType() == getOperand(OpNo)->getType() &&
1062 "Replacing operand with value of different type!");
1063 if (getOperand(OpNo) == Op)
1064 return const_cast<ConstantExpr*>(this);
1066 SmallVector<Constant*, 8> NewOps;
1067 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1068 NewOps.push_back(i == OpNo ? Op : getOperand(i));
1070 return getWithOperands(NewOps);
1073 /// getWithOperands - This returns the current constant expression with the
1074 /// operands replaced with the specified values. The specified array must
1075 /// have the same number of operands as our current one.
1076 Constant *ConstantExpr::
1077 getWithOperands(ArrayRef<Constant*> Ops, Type *Ty) const {
1078 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
1079 bool AnyChange = Ty != getType();
1080 for (unsigned i = 0; i != Ops.size(); ++i)
1081 AnyChange |= Ops[i] != getOperand(i);
1083 if (!AnyChange) // No operands changed, return self.
1084 return const_cast<ConstantExpr*>(this);
1086 switch (getOpcode()) {
1087 case Instruction::Trunc:
1088 case Instruction::ZExt:
1089 case Instruction::SExt:
1090 case Instruction::FPTrunc:
1091 case Instruction::FPExt:
1092 case Instruction::UIToFP:
1093 case Instruction::SIToFP:
1094 case Instruction::FPToUI:
1095 case Instruction::FPToSI:
1096 case Instruction::PtrToInt:
1097 case Instruction::IntToPtr:
1098 case Instruction::BitCast:
1099 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty);
1100 case Instruction::Select:
1101 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
1102 case Instruction::InsertElement:
1103 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
1104 case Instruction::ExtractElement:
1105 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
1106 case Instruction::InsertValue:
1107 return ConstantExpr::getInsertValue(Ops[0], Ops[1], getIndices());
1108 case Instruction::ExtractValue:
1109 return ConstantExpr::getExtractValue(Ops[0], getIndices());
1110 case Instruction::ShuffleVector:
1111 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
1112 case Instruction::GetElementPtr:
1113 return ConstantExpr::getGetElementPtr(Ops[0], Ops.slice(1),
1114 cast<GEPOperator>(this)->isInBounds());
1115 case Instruction::ICmp:
1116 case Instruction::FCmp:
1117 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
1119 assert(getNumOperands() == 2 && "Must be binary operator?");
1120 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData);
1125 //===----------------------------------------------------------------------===//
1126 // isValueValidForType implementations
1128 bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
1129 unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
1130 if (Ty->isIntegerTy(1))
1131 return Val == 0 || Val == 1;
1133 return true; // always true, has to fit in largest type
1134 uint64_t Max = (1ll << NumBits) - 1;
1138 bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
1139 unsigned NumBits = Ty->getIntegerBitWidth();
1140 if (Ty->isIntegerTy(1))
1141 return Val == 0 || Val == 1 || Val == -1;
1143 return true; // always true, has to fit in largest type
1144 int64_t Min = -(1ll << (NumBits-1));
1145 int64_t Max = (1ll << (NumBits-1)) - 1;
1146 return (Val >= Min && Val <= Max);
1149 bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {
1150 // convert modifies in place, so make a copy.
1151 APFloat Val2 = APFloat(Val);
1153 switch (Ty->getTypeID()) {
1155 return false; // These can't be represented as floating point!
1157 // FIXME rounding mode needs to be more flexible
1158 case Type::HalfTyID: {
1159 if (&Val2.getSemantics() == &APFloat::IEEEhalf)
1161 Val2.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &losesInfo);
1164 case Type::FloatTyID: {
1165 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
1167 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
1170 case Type::DoubleTyID: {
1171 if (&Val2.getSemantics() == &APFloat::IEEEhalf ||
1172 &Val2.getSemantics() == &APFloat::IEEEsingle ||
1173 &Val2.getSemantics() == &APFloat::IEEEdouble)
1175 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
1178 case Type::X86_FP80TyID:
1179 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1180 &Val2.getSemantics() == &APFloat::IEEEsingle ||
1181 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1182 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
1183 case Type::FP128TyID:
1184 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1185 &Val2.getSemantics() == &APFloat::IEEEsingle ||
1186 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1187 &Val2.getSemantics() == &APFloat::IEEEquad;
1188 case Type::PPC_FP128TyID:
1189 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1190 &Val2.getSemantics() == &APFloat::IEEEsingle ||
1191 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1192 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
1197 //===----------------------------------------------------------------------===//
1198 // Factory Function Implementation
1200 ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
1201 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
1202 "Cannot create an aggregate zero of non-aggregate type!");
1204 ConstantAggregateZero *&Entry = Ty->getContext().pImpl->CAZConstants[Ty];
1206 Entry = new ConstantAggregateZero(Ty);
1211 /// destroyConstant - Remove the constant from the constant table.
1213 void ConstantAggregateZero::destroyConstant() {
1214 getContext().pImpl->CAZConstants.erase(getType());
1215 destroyConstantImpl();
1218 /// destroyConstant - Remove the constant from the constant table...
1220 void ConstantArray::destroyConstant() {
1221 getType()->getContext().pImpl->ArrayConstants.remove(this);
1222 destroyConstantImpl();
1226 //---- ConstantStruct::get() implementation...
1229 // destroyConstant - Remove the constant from the constant table...
1231 void ConstantStruct::destroyConstant() {
1232 getType()->getContext().pImpl->StructConstants.remove(this);
1233 destroyConstantImpl();
1236 // destroyConstant - Remove the constant from the constant table...
1238 void ConstantVector::destroyConstant() {
1239 getType()->getContext().pImpl->VectorConstants.remove(this);
1240 destroyConstantImpl();
1243 /// getSplatValue - If this is a splat vector constant, meaning that all of
1244 /// the elements have the same value, return that value. Otherwise return 0.
1245 Constant *Constant::getSplatValue() const {
1246 assert(this->getType()->isVectorTy() && "Only valid for vectors!");
1247 if (isa<ConstantAggregateZero>(this))
1248 return getNullValue(this->getType()->getVectorElementType());
1249 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
1250 return CV->getSplatValue();
1251 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
1252 return CV->getSplatValue();
1256 /// getSplatValue - If this is a splat constant, where all of the
1257 /// elements have the same value, return that value. Otherwise return null.
1258 Constant *ConstantVector::getSplatValue() const {
1259 // Check out first element.
1260 Constant *Elt = getOperand(0);
1261 // Then make sure all remaining elements point to the same value.
1262 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1263 if (getOperand(I) != Elt)
1268 /// If C is a constant integer then return its value, otherwise C must be a
1269 /// vector of constant integers, all equal, and the common value is returned.
1270 const APInt &Constant::getUniqueInteger() const {
1271 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
1272 return CI->getValue();
1273 assert(this->getSplatValue() && "Doesn't contain a unique integer!");
1274 const Constant *C = this->getAggregateElement(0U);
1275 assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
1276 return cast<ConstantInt>(C)->getValue();
1280 //---- ConstantPointerNull::get() implementation.
1283 ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
1284 ConstantPointerNull *&Entry = Ty->getContext().pImpl->CPNConstants[Ty];
1286 Entry = new ConstantPointerNull(Ty);
1291 // destroyConstant - Remove the constant from the constant table...
1293 void ConstantPointerNull::destroyConstant() {
1294 getContext().pImpl->CPNConstants.erase(getType());
1295 // Free the constant and any dangling references to it.
1296 destroyConstantImpl();
1300 //---- UndefValue::get() implementation.
1303 UndefValue *UndefValue::get(Type *Ty) {
1304 UndefValue *&Entry = Ty->getContext().pImpl->UVConstants[Ty];
1306 Entry = new UndefValue(Ty);
1311 // destroyConstant - Remove the constant from the constant table.
1313 void UndefValue::destroyConstant() {
1314 // Free the constant and any dangling references to it.
1315 getContext().pImpl->UVConstants.erase(getType());
1316 destroyConstantImpl();
1319 //---- BlockAddress::get() implementation.
1322 BlockAddress *BlockAddress::get(BasicBlock *BB) {
1323 assert(BB->getParent() != 0 && "Block must have a parent");
1324 return get(BB->getParent(), BB);
1327 BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1329 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
1331 BA = new BlockAddress(F, BB);
1333 assert(BA->getFunction() == F && "Basic block moved between functions");
1337 BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1338 : Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1342 BB->AdjustBlockAddressRefCount(1);
1346 // destroyConstant - Remove the constant from the constant table.
1348 void BlockAddress::destroyConstant() {
1349 getFunction()->getType()->getContext().pImpl
1350 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
1351 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1352 destroyConstantImpl();
1355 void BlockAddress::replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U) {
1356 // This could be replacing either the Basic Block or the Function. In either
1357 // case, we have to remove the map entry.
1358 Function *NewF = getFunction();
1359 BasicBlock *NewBB = getBasicBlock();
1362 NewF = cast<Function>(To);
1364 NewBB = cast<BasicBlock>(To);
1366 // See if the 'new' entry already exists, if not, just update this in place
1367 // and return early.
1368 BlockAddress *&NewBA =
1369 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
1371 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1373 // Remove the old entry, this can't cause the map to rehash (just a
1374 // tombstone will get added).
1375 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1378 setOperand(0, NewF);
1379 setOperand(1, NewBB);
1380 getBasicBlock()->AdjustBlockAddressRefCount(1);
1384 // Otherwise, I do need to replace this with an existing value.
1385 assert(NewBA != this && "I didn't contain From!");
1387 // Everyone using this now uses the replacement.
1388 replaceAllUsesWith(NewBA);
1393 //---- ConstantExpr::get() implementations.
1396 /// This is a utility function to handle folding of casts and lookup of the
1397 /// cast in the ExprConstants map. It is used by the various get* methods below.
1398 static inline Constant *getFoldedCast(
1399 Instruction::CastOps opc, Constant *C, Type *Ty) {
1400 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1401 // Fold a few common cases
1402 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1405 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1407 // Look up the constant in the table first to ensure uniqueness
1408 std::vector<Constant*> argVec(1, C);
1409 ExprMapKeyType Key(opc, argVec);
1411 return pImpl->ExprConstants.getOrCreate(Ty, Key);
1414 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty) {
1415 Instruction::CastOps opc = Instruction::CastOps(oc);
1416 assert(Instruction::isCast(opc) && "opcode out of range");
1417 assert(C && Ty && "Null arguments to getCast");
1418 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
1422 llvm_unreachable("Invalid cast opcode");
1423 case Instruction::Trunc: return getTrunc(C, Ty);
1424 case Instruction::ZExt: return getZExt(C, Ty);
1425 case Instruction::SExt: return getSExt(C, Ty);
1426 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1427 case Instruction::FPExt: return getFPExtend(C, Ty);
1428 case Instruction::UIToFP: return getUIToFP(C, Ty);
1429 case Instruction::SIToFP: return getSIToFP(C, Ty);
1430 case Instruction::FPToUI: return getFPToUI(C, Ty);
1431 case Instruction::FPToSI: return getFPToSI(C, Ty);
1432 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1433 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1434 case Instruction::BitCast: return getBitCast(C, Ty);
1438 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) {
1439 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1440 return getBitCast(C, Ty);
1441 return getZExt(C, Ty);
1444 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) {
1445 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1446 return getBitCast(C, Ty);
1447 return getSExt(C, Ty);
1450 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {
1451 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1452 return getBitCast(C, Ty);
1453 return getTrunc(C, Ty);
1456 Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {
1457 assert(S->getType()->isPointerTy() && "Invalid cast");
1458 assert((Ty->isIntegerTy() || Ty->isPointerTy()) && "Invalid cast");
1460 if (Ty->isIntegerTy())
1461 return getPtrToInt(S, Ty);
1462 return getBitCast(S, Ty);
1465 Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty,
1467 assert(C->getType()->isIntOrIntVectorTy() &&
1468 Ty->isIntOrIntVectorTy() && "Invalid cast");
1469 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1470 unsigned DstBits = Ty->getScalarSizeInBits();
1471 Instruction::CastOps opcode =
1472 (SrcBits == DstBits ? Instruction::BitCast :
1473 (SrcBits > DstBits ? Instruction::Trunc :
1474 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1475 return getCast(opcode, C, Ty);
1478 Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) {
1479 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1481 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1482 unsigned DstBits = Ty->getScalarSizeInBits();
1483 if (SrcBits == DstBits)
1484 return C; // Avoid a useless cast
1485 Instruction::CastOps opcode =
1486 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1487 return getCast(opcode, C, Ty);
1490 Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty) {
1492 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1493 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1495 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1496 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
1497 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
1498 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1499 "SrcTy must be larger than DestTy for Trunc!");
1501 return getFoldedCast(Instruction::Trunc, C, Ty);
1504 Constant *ConstantExpr::getSExt(Constant *C, Type *Ty) {
1506 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1507 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1509 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1510 assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
1511 assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
1512 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1513 "SrcTy must be smaller than DestTy for SExt!");
1515 return getFoldedCast(Instruction::SExt, C, Ty);
1518 Constant *ConstantExpr::getZExt(Constant *C, Type *Ty) {
1520 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1521 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1523 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1524 assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
1525 assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
1526 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1527 "SrcTy must be smaller than DestTy for ZExt!");
1529 return getFoldedCast(Instruction::ZExt, C, Ty);
1532 Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty) {
1534 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1535 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1537 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1538 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1539 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1540 "This is an illegal floating point truncation!");
1541 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1544 Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty) {
1546 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1547 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1549 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1550 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1551 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1552 "This is an illegal floating point extension!");
1553 return getFoldedCast(Instruction::FPExt, C, Ty);
1556 Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty) {
1558 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1559 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1561 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1562 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1563 "This is an illegal uint to floating point cast!");
1564 return getFoldedCast(Instruction::UIToFP, C, Ty);
1567 Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty) {
1569 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1570 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1572 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1573 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1574 "This is an illegal sint to floating point cast!");
1575 return getFoldedCast(Instruction::SIToFP, C, Ty);
1578 Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty) {
1580 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1581 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1583 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1584 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1585 "This is an illegal floating point to uint cast!");
1586 return getFoldedCast(Instruction::FPToUI, C, Ty);
1589 Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty) {
1591 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1592 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1594 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1595 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1596 "This is an illegal floating point to sint cast!");
1597 return getFoldedCast(Instruction::FPToSI, C, Ty);
1600 Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy) {
1601 assert(C->getType()->getScalarType()->isPointerTy() &&
1602 "PtrToInt source must be pointer or pointer vector");
1603 assert(DstTy->getScalarType()->isIntegerTy() &&
1604 "PtrToInt destination must be integer or integer vector");
1605 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
1606 if (isa<VectorType>(C->getType()))
1607 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
1608 "Invalid cast between a different number of vector elements");
1609 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1612 Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy) {
1613 assert(C->getType()->getScalarType()->isIntegerTy() &&
1614 "IntToPtr source must be integer or integer vector");
1615 assert(DstTy->getScalarType()->isPointerTy() &&
1616 "IntToPtr destination must be a pointer or pointer vector");
1617 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
1618 if (isa<VectorType>(C->getType()))
1619 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
1620 "Invalid cast between a different number of vector elements");
1621 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1624 Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy) {
1625 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
1626 "Invalid constantexpr bitcast!");
1628 // It is common to ask for a bitcast of a value to its own type, handle this
1630 if (C->getType() == DstTy) return C;
1632 return getFoldedCast(Instruction::BitCast, C, DstTy);
1635 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
1637 // Check the operands for consistency first.
1638 assert(Opcode >= Instruction::BinaryOpsBegin &&
1639 Opcode < Instruction::BinaryOpsEnd &&
1640 "Invalid opcode in binary constant expression");
1641 assert(C1->getType() == C2->getType() &&
1642 "Operand types in binary constant expression should match");
1646 case Instruction::Add:
1647 case Instruction::Sub:
1648 case Instruction::Mul:
1649 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1650 assert(C1->getType()->isIntOrIntVectorTy() &&
1651 "Tried to create an integer operation on a non-integer type!");
1653 case Instruction::FAdd:
1654 case Instruction::FSub:
1655 case Instruction::FMul:
1656 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1657 assert(C1->getType()->isFPOrFPVectorTy() &&
1658 "Tried to create a floating-point operation on a "
1659 "non-floating-point type!");
1661 case Instruction::UDiv:
1662 case Instruction::SDiv:
1663 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1664 assert(C1->getType()->isIntOrIntVectorTy() &&
1665 "Tried to create an arithmetic operation on a non-arithmetic type!");
1667 case Instruction::FDiv:
1668 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1669 assert(C1->getType()->isFPOrFPVectorTy() &&
1670 "Tried to create an arithmetic operation on a non-arithmetic type!");
1672 case Instruction::URem:
1673 case Instruction::SRem:
1674 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1675 assert(C1->getType()->isIntOrIntVectorTy() &&
1676 "Tried to create an arithmetic operation on a non-arithmetic type!");
1678 case Instruction::FRem:
1679 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1680 assert(C1->getType()->isFPOrFPVectorTy() &&
1681 "Tried to create an arithmetic operation on a non-arithmetic type!");
1683 case Instruction::And:
1684 case Instruction::Or:
1685 case Instruction::Xor:
1686 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1687 assert(C1->getType()->isIntOrIntVectorTy() &&
1688 "Tried to create a logical operation on a non-integral type!");
1690 case Instruction::Shl:
1691 case Instruction::LShr:
1692 case Instruction::AShr:
1693 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1694 assert(C1->getType()->isIntOrIntVectorTy() &&
1695 "Tried to create a shift operation on a non-integer type!");
1702 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1703 return FC; // Fold a few common cases.
1705 std::vector<Constant*> argVec(1, C1);
1706 argVec.push_back(C2);
1707 ExprMapKeyType Key(Opcode, argVec, 0, Flags);
1709 LLVMContextImpl *pImpl = C1->getContext().pImpl;
1710 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
1713 Constant *ConstantExpr::getSizeOf(Type* Ty) {
1714 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1715 // Note that a non-inbounds gep is used, as null isn't within any object.
1716 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1717 Constant *GEP = getGetElementPtr(
1718 Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
1719 return getPtrToInt(GEP,
1720 Type::getInt64Ty(Ty->getContext()));
1723 Constant *ConstantExpr::getAlignOf(Type* Ty) {
1724 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
1725 // Note that a non-inbounds gep is used, as null isn't within any object.
1727 StructType::get(Type::getInt1Ty(Ty->getContext()), Ty, NULL);
1728 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo());
1729 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
1730 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1731 Constant *Indices[2] = { Zero, One };
1732 Constant *GEP = getGetElementPtr(NullPtr, Indices);
1733 return getPtrToInt(GEP,
1734 Type::getInt64Ty(Ty->getContext()));
1737 Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) {
1738 return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
1742 Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) {
1743 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1744 // Note that a non-inbounds gep is used, as null isn't within any object.
1745 Constant *GEPIdx[] = {
1746 ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
1749 Constant *GEP = getGetElementPtr(
1750 Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
1751 return getPtrToInt(GEP,
1752 Type::getInt64Ty(Ty->getContext()));
1755 Constant *ConstantExpr::getCompare(unsigned short Predicate,
1756 Constant *C1, Constant *C2) {
1757 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1759 switch (Predicate) {
1760 default: llvm_unreachable("Invalid CmpInst predicate");
1761 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1762 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1763 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1764 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1765 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1766 case CmpInst::FCMP_TRUE:
1767 return getFCmp(Predicate, C1, C2);
1769 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1770 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1771 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1772 case CmpInst::ICMP_SLE:
1773 return getICmp(Predicate, C1, C2);
1777 Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2) {
1778 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1780 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1781 return SC; // Fold common cases
1783 std::vector<Constant*> argVec(3, C);
1786 ExprMapKeyType Key(Instruction::Select, argVec);
1788 LLVMContextImpl *pImpl = C->getContext().pImpl;
1789 return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
1792 Constant *ConstantExpr::getGetElementPtr(Constant *C, ArrayRef<Value *> Idxs,
1794 assert(C->getType()->isPtrOrPtrVectorTy() &&
1795 "Non-pointer type for constant GetElementPtr expression");
1797 if (Constant *FC = ConstantFoldGetElementPtr(C, InBounds, Idxs))
1798 return FC; // Fold a few common cases.
1800 // Get the result type of the getelementptr!
1801 Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), Idxs);
1802 assert(Ty && "GEP indices invalid!");
1803 unsigned AS = C->getType()->getPointerAddressSpace();
1804 Type *ReqTy = Ty->getPointerTo(AS);
1805 if (VectorType *VecTy = dyn_cast<VectorType>(C->getType()))
1806 ReqTy = VectorType::get(ReqTy, VecTy->getNumElements());
1808 // Look up the constant in the table first to ensure uniqueness
1809 std::vector<Constant*> ArgVec;
1810 ArgVec.reserve(1 + Idxs.size());
1811 ArgVec.push_back(C);
1812 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
1813 assert(Idxs[i]->getType()->isVectorTy() == ReqTy->isVectorTy() &&
1814 "getelementptr index type missmatch");
1815 assert((!Idxs[i]->getType()->isVectorTy() ||
1816 ReqTy->getVectorNumElements() ==
1817 Idxs[i]->getType()->getVectorNumElements()) &&
1818 "getelementptr index type missmatch");
1819 ArgVec.push_back(cast<Constant>(Idxs[i]));
1821 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
1822 InBounds ? GEPOperator::IsInBounds : 0);
1824 LLVMContextImpl *pImpl = C->getContext().pImpl;
1825 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1829 ConstantExpr::getICmp(unsigned short pred, Constant *LHS, Constant *RHS) {
1830 assert(LHS->getType() == RHS->getType());
1831 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1832 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1834 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1835 return FC; // Fold a few common cases...
1837 // Look up the constant in the table first to ensure uniqueness
1838 std::vector<Constant*> ArgVec;
1839 ArgVec.push_back(LHS);
1840 ArgVec.push_back(RHS);
1841 // Get the key type with both the opcode and predicate
1842 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1844 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1845 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1846 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1848 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1849 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
1853 ConstantExpr::getFCmp(unsigned short pred, Constant *LHS, Constant *RHS) {
1854 assert(LHS->getType() == RHS->getType());
1855 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1857 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1858 return FC; // Fold a few common cases...
1860 // Look up the constant in the table first to ensure uniqueness
1861 std::vector<Constant*> ArgVec;
1862 ArgVec.push_back(LHS);
1863 ArgVec.push_back(RHS);
1864 // Get the key type with both the opcode and predicate
1865 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1867 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1868 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1869 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1871 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1872 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
1875 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1876 assert(Val->getType()->isVectorTy() &&
1877 "Tried to create extractelement operation on non-vector type!");
1878 assert(Idx->getType()->isIntegerTy(32) &&
1879 "Extractelement index must be i32 type!");
1881 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1882 return FC; // Fold a few common cases.
1884 // Look up the constant in the table first to ensure uniqueness
1885 std::vector<Constant*> ArgVec(1, Val);
1886 ArgVec.push_back(Idx);
1887 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1889 LLVMContextImpl *pImpl = Val->getContext().pImpl;
1890 Type *ReqTy = Val->getType()->getVectorElementType();
1891 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1894 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1896 assert(Val->getType()->isVectorTy() &&
1897 "Tried to create insertelement operation on non-vector type!");
1898 assert(Elt->getType() == Val->getType()->getVectorElementType() &&
1899 "Insertelement types must match!");
1900 assert(Idx->getType()->isIntegerTy(32) &&
1901 "Insertelement index must be i32 type!");
1903 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1904 return FC; // Fold a few common cases.
1905 // Look up the constant in the table first to ensure uniqueness
1906 std::vector<Constant*> ArgVec(1, Val);
1907 ArgVec.push_back(Elt);
1908 ArgVec.push_back(Idx);
1909 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1911 LLVMContextImpl *pImpl = Val->getContext().pImpl;
1912 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
1915 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1917 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1918 "Invalid shuffle vector constant expr operands!");
1920 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1921 return FC; // Fold a few common cases.
1923 unsigned NElts = Mask->getType()->getVectorNumElements();
1924 Type *EltTy = V1->getType()->getVectorElementType();
1925 Type *ShufTy = VectorType::get(EltTy, NElts);
1927 // Look up the constant in the table first to ensure uniqueness
1928 std::vector<Constant*> ArgVec(1, V1);
1929 ArgVec.push_back(V2);
1930 ArgVec.push_back(Mask);
1931 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1933 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
1934 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
1937 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
1938 ArrayRef<unsigned> Idxs) {
1939 assert(ExtractValueInst::getIndexedType(Agg->getType(),
1940 Idxs) == Val->getType() &&
1941 "insertvalue indices invalid!");
1942 assert(Agg->getType()->isFirstClassType() &&
1943 "Non-first-class type for constant insertvalue expression");
1944 Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs);
1945 assert(FC && "insertvalue constant expr couldn't be folded!");
1949 Constant *ConstantExpr::getExtractValue(Constant *Agg,
1950 ArrayRef<unsigned> Idxs) {
1951 assert(Agg->getType()->isFirstClassType() &&
1952 "Tried to create extractelement operation on non-first-class type!");
1954 Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs);
1956 assert(ReqTy && "extractvalue indices invalid!");
1958 assert(Agg->getType()->isFirstClassType() &&
1959 "Non-first-class type for constant extractvalue expression");
1960 Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs);
1961 assert(FC && "ExtractValue constant expr couldn't be folded!");
1965 Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
1966 assert(C->getType()->isIntOrIntVectorTy() &&
1967 "Cannot NEG a nonintegral value!");
1968 return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
1972 Constant *ConstantExpr::getFNeg(Constant *C) {
1973 assert(C->getType()->isFPOrFPVectorTy() &&
1974 "Cannot FNEG a non-floating-point value!");
1975 return getFSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
1978 Constant *ConstantExpr::getNot(Constant *C) {
1979 assert(C->getType()->isIntOrIntVectorTy() &&
1980 "Cannot NOT a nonintegral value!");
1981 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
1984 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
1985 bool HasNUW, bool HasNSW) {
1986 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1987 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
1988 return get(Instruction::Add, C1, C2, Flags);
1991 Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
1992 return get(Instruction::FAdd, C1, C2);
1995 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
1996 bool HasNUW, bool HasNSW) {
1997 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1998 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
1999 return get(Instruction::Sub, C1, C2, Flags);
2002 Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
2003 return get(Instruction::FSub, C1, C2);
2006 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
2007 bool HasNUW, bool HasNSW) {
2008 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2009 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2010 return get(Instruction::Mul, C1, C2, Flags);
2013 Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
2014 return get(Instruction::FMul, C1, C2);
2017 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
2018 return get(Instruction::UDiv, C1, C2,
2019 isExact ? PossiblyExactOperator::IsExact : 0);
2022 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
2023 return get(Instruction::SDiv, C1, C2,
2024 isExact ? PossiblyExactOperator::IsExact : 0);
2027 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
2028 return get(Instruction::FDiv, C1, C2);
2031 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
2032 return get(Instruction::URem, C1, C2);
2035 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
2036 return get(Instruction::SRem, C1, C2);
2039 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
2040 return get(Instruction::FRem, C1, C2);
2043 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
2044 return get(Instruction::And, C1, C2);
2047 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
2048 return get(Instruction::Or, C1, C2);
2051 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
2052 return get(Instruction::Xor, C1, C2);
2055 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
2056 bool HasNUW, bool HasNSW) {
2057 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2058 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2059 return get(Instruction::Shl, C1, C2, Flags);
2062 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
2063 return get(Instruction::LShr, C1, C2,
2064 isExact ? PossiblyExactOperator::IsExact : 0);
2067 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
2068 return get(Instruction::AShr, C1, C2,
2069 isExact ? PossiblyExactOperator::IsExact : 0);
2072 /// getBinOpIdentity - Return the identity for the given binary operation,
2073 /// i.e. a constant C such that X op C = X and C op X = X for every X. It
2074 /// returns null if the operator doesn't have an identity.
2075 Constant *ConstantExpr::getBinOpIdentity(unsigned Opcode, Type *Ty) {
2078 // Doesn't have an identity.
2081 case Instruction::Add:
2082 case Instruction::Or:
2083 case Instruction::Xor:
2084 return Constant::getNullValue(Ty);
2086 case Instruction::Mul:
2087 return ConstantInt::get(Ty, 1);
2089 case Instruction::And:
2090 return Constant::getAllOnesValue(Ty);
2094 /// getBinOpAbsorber - Return the absorbing element for the given binary
2095 /// operation, i.e. a constant C such that X op C = C and C op X = C for
2096 /// every X. For example, this returns zero for integer multiplication.
2097 /// It returns null if the operator doesn't have an absorbing element.
2098 Constant *ConstantExpr::getBinOpAbsorber(unsigned Opcode, Type *Ty) {
2101 // Doesn't have an absorber.
2104 case Instruction::Or:
2105 return Constant::getAllOnesValue(Ty);
2107 case Instruction::And:
2108 case Instruction::Mul:
2109 return Constant::getNullValue(Ty);
2113 // destroyConstant - Remove the constant from the constant table...
2115 void ConstantExpr::destroyConstant() {
2116 getType()->getContext().pImpl->ExprConstants.remove(this);
2117 destroyConstantImpl();
2120 const char *ConstantExpr::getOpcodeName() const {
2121 return Instruction::getOpcodeName(getOpcode());
2126 GetElementPtrConstantExpr::
2127 GetElementPtrConstantExpr(Constant *C, ArrayRef<Constant*> IdxList,
2129 : ConstantExpr(DestTy, Instruction::GetElementPtr,
2130 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
2131 - (IdxList.size()+1), IdxList.size()+1) {
2133 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
2134 OperandList[i+1] = IdxList[i];
2137 //===----------------------------------------------------------------------===//
2138 // ConstantData* implementations
2140 void ConstantDataArray::anchor() {}
2141 void ConstantDataVector::anchor() {}
2143 /// getElementType - Return the element type of the array/vector.
2144 Type *ConstantDataSequential::getElementType() const {
2145 return getType()->getElementType();
2148 StringRef ConstantDataSequential::getRawDataValues() const {
2149 return StringRef(DataElements, getNumElements()*getElementByteSize());
2152 /// isElementTypeCompatible - Return true if a ConstantDataSequential can be
2153 /// formed with a vector or array of the specified element type.
2154 /// ConstantDataArray only works with normal float and int types that are
2155 /// stored densely in memory, not with things like i42 or x86_f80.
2156 bool ConstantDataSequential::isElementTypeCompatible(const Type *Ty) {
2157 if (Ty->isFloatTy() || Ty->isDoubleTy()) return true;
2158 if (const IntegerType *IT = dyn_cast<IntegerType>(Ty)) {
2159 switch (IT->getBitWidth()) {
2171 /// getNumElements - Return the number of elements in the array or vector.
2172 unsigned ConstantDataSequential::getNumElements() const {
2173 if (ArrayType *AT = dyn_cast<ArrayType>(getType()))
2174 return AT->getNumElements();
2175 return getType()->getVectorNumElements();
2179 /// getElementByteSize - Return the size in bytes of the elements in the data.
2180 uint64_t ConstantDataSequential::getElementByteSize() const {
2181 return getElementType()->getPrimitiveSizeInBits()/8;
2184 /// getElementPointer - Return the start of the specified element.
2185 const char *ConstantDataSequential::getElementPointer(unsigned Elt) const {
2186 assert(Elt < getNumElements() && "Invalid Elt");
2187 return DataElements+Elt*getElementByteSize();
2191 /// isAllZeros - return true if the array is empty or all zeros.
2192 static bool isAllZeros(StringRef Arr) {
2193 for (StringRef::iterator I = Arr.begin(), E = Arr.end(); I != E; ++I)
2199 /// getImpl - This is the underlying implementation of all of the
2200 /// ConstantDataSequential::get methods. They all thunk down to here, providing
2201 /// the correct element type. We take the bytes in as a StringRef because
2202 /// we *want* an underlying "char*" to avoid TBAA type punning violations.
2203 Constant *ConstantDataSequential::getImpl(StringRef Elements, Type *Ty) {
2204 assert(isElementTypeCompatible(Ty->getSequentialElementType()));
2205 // If the elements are all zero or there are no elements, return a CAZ, which
2206 // is more dense and canonical.
2207 if (isAllZeros(Elements))
2208 return ConstantAggregateZero::get(Ty);
2210 // Do a lookup to see if we have already formed one of these.
2211 StringMap<ConstantDataSequential*>::MapEntryTy &Slot =
2212 Ty->getContext().pImpl->CDSConstants.GetOrCreateValue(Elements);
2214 // The bucket can point to a linked list of different CDS's that have the same
2215 // body but different types. For example, 0,0,0,1 could be a 4 element array
2216 // of i8, or a 1-element array of i32. They'll both end up in the same
2217 /// StringMap bucket, linked up by their Next pointers. Walk the list.
2218 ConstantDataSequential **Entry = &Slot.getValue();
2219 for (ConstantDataSequential *Node = *Entry; Node != 0;
2220 Entry = &Node->Next, Node = *Entry)
2221 if (Node->getType() == Ty)
2224 // Okay, we didn't get a hit. Create a node of the right class, link it in,
2226 if (isa<ArrayType>(Ty))
2227 return *Entry = new ConstantDataArray(Ty, Slot.getKeyData());
2229 assert(isa<VectorType>(Ty));
2230 return *Entry = new ConstantDataVector(Ty, Slot.getKeyData());
2233 void ConstantDataSequential::destroyConstant() {
2234 // Remove the constant from the StringMap.
2235 StringMap<ConstantDataSequential*> &CDSConstants =
2236 getType()->getContext().pImpl->CDSConstants;
2238 StringMap<ConstantDataSequential*>::iterator Slot =
2239 CDSConstants.find(getRawDataValues());
2241 assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
2243 ConstantDataSequential **Entry = &Slot->getValue();
2245 // Remove the entry from the hash table.
2246 if ((*Entry)->Next == 0) {
2247 // If there is only one value in the bucket (common case) it must be this
2248 // entry, and removing the entry should remove the bucket completely.
2249 assert((*Entry) == this && "Hash mismatch in ConstantDataSequential");
2250 getContext().pImpl->CDSConstants.erase(Slot);
2252 // Otherwise, there are multiple entries linked off the bucket, unlink the
2253 // node we care about but keep the bucket around.
2254 for (ConstantDataSequential *Node = *Entry; ;
2255 Entry = &Node->Next, Node = *Entry) {
2256 assert(Node && "Didn't find entry in its uniquing hash table!");
2257 // If we found our entry, unlink it from the list and we're done.
2259 *Entry = Node->Next;
2265 // If we were part of a list, make sure that we don't delete the list that is
2266 // still owned by the uniquing map.
2269 // Finally, actually delete it.
2270 destroyConstantImpl();
2273 /// get() constructors - Return a constant with array type with an element
2274 /// count and element type matching the ArrayRef passed in. Note that this
2275 /// can return a ConstantAggregateZero object.
2276 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint8_t> Elts) {
2277 Type *Ty = ArrayType::get(Type::getInt8Ty(Context), Elts.size());
2278 const char *Data = reinterpret_cast<const char *>(Elts.data());
2279 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*1), Ty);
2281 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
2282 Type *Ty = ArrayType::get(Type::getInt16Ty(Context), Elts.size());
2283 const char *Data = reinterpret_cast<const char *>(Elts.data());
2284 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*2), Ty);
2286 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
2287 Type *Ty = ArrayType::get(Type::getInt32Ty(Context), Elts.size());
2288 const char *Data = reinterpret_cast<const char *>(Elts.data());
2289 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
2291 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
2292 Type *Ty = ArrayType::get(Type::getInt64Ty(Context), Elts.size());
2293 const char *Data = reinterpret_cast<const char *>(Elts.data());
2294 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
2296 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<float> Elts) {
2297 Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
2298 const char *Data = reinterpret_cast<const char *>(Elts.data());
2299 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
2301 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<double> Elts) {
2302 Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
2303 const char *Data = reinterpret_cast<const char *>(Elts.data());
2304 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
2307 /// getString - This method constructs a CDS and initializes it with a text
2308 /// string. The default behavior (AddNull==true) causes a null terminator to
2309 /// be placed at the end of the array (increasing the length of the string by
2310 /// one more than the StringRef would normally indicate. Pass AddNull=false
2311 /// to disable this behavior.
2312 Constant *ConstantDataArray::getString(LLVMContext &Context,
2313 StringRef Str, bool AddNull) {
2315 const uint8_t *Data = reinterpret_cast<const uint8_t *>(Str.data());
2316 return get(Context, ArrayRef<uint8_t>(const_cast<uint8_t *>(Data),
2320 SmallVector<uint8_t, 64> ElementVals;
2321 ElementVals.append(Str.begin(), Str.end());
2322 ElementVals.push_back(0);
2323 return get(Context, ElementVals);
2326 /// get() constructors - Return a constant with vector type with an element
2327 /// count and element type matching the ArrayRef passed in. Note that this
2328 /// can return a ConstantAggregateZero object.
2329 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> Elts){
2330 Type *Ty = VectorType::get(Type::getInt8Ty(Context), Elts.size());
2331 const char *Data = reinterpret_cast<const char *>(Elts.data());
2332 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*1), Ty);
2334 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
2335 Type *Ty = VectorType::get(Type::getInt16Ty(Context), Elts.size());
2336 const char *Data = reinterpret_cast<const char *>(Elts.data());
2337 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*2), Ty);
2339 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
2340 Type *Ty = VectorType::get(Type::getInt32Ty(Context), Elts.size());
2341 const char *Data = reinterpret_cast<const char *>(Elts.data());
2342 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
2344 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
2345 Type *Ty = VectorType::get(Type::getInt64Ty(Context), Elts.size());
2346 const char *Data = reinterpret_cast<const char *>(Elts.data());
2347 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
2349 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> Elts) {
2350 Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
2351 const char *Data = reinterpret_cast<const char *>(Elts.data());
2352 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
2354 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<double> Elts) {
2355 Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
2356 const char *Data = reinterpret_cast<const char *>(Elts.data());
2357 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
2360 Constant *ConstantDataVector::getSplat(unsigned NumElts, Constant *V) {
2361 assert(isElementTypeCompatible(V->getType()) &&
2362 "Element type not compatible with ConstantData");
2363 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2364 if (CI->getType()->isIntegerTy(8)) {
2365 SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
2366 return get(V->getContext(), Elts);
2368 if (CI->getType()->isIntegerTy(16)) {
2369 SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
2370 return get(V->getContext(), Elts);
2372 if (CI->getType()->isIntegerTy(32)) {
2373 SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
2374 return get(V->getContext(), Elts);
2376 assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
2377 SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
2378 return get(V->getContext(), Elts);
2381 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2382 if (CFP->getType()->isFloatTy()) {
2383 SmallVector<float, 16> Elts(NumElts, CFP->getValueAPF().convertToFloat());
2384 return get(V->getContext(), Elts);
2386 if (CFP->getType()->isDoubleTy()) {
2387 SmallVector<double, 16> Elts(NumElts,
2388 CFP->getValueAPF().convertToDouble());
2389 return get(V->getContext(), Elts);
2392 return ConstantVector::getSplat(NumElts, V);
2396 /// getElementAsInteger - If this is a sequential container of integers (of
2397 /// any size), return the specified element in the low bits of a uint64_t.
2398 uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const {
2399 assert(isa<IntegerType>(getElementType()) &&
2400 "Accessor can only be used when element is an integer");
2401 const char *EltPtr = getElementPointer(Elt);
2403 // The data is stored in host byte order, make sure to cast back to the right
2404 // type to load with the right endianness.
2405 switch (getElementType()->getIntegerBitWidth()) {
2406 default: llvm_unreachable("Invalid bitwidth for CDS");
2408 return *const_cast<uint8_t *>(reinterpret_cast<const uint8_t *>(EltPtr));
2410 return *const_cast<uint16_t *>(reinterpret_cast<const uint16_t *>(EltPtr));
2412 return *const_cast<uint32_t *>(reinterpret_cast<const uint32_t *>(EltPtr));
2414 return *const_cast<uint64_t *>(reinterpret_cast<const uint64_t *>(EltPtr));
2418 /// getElementAsAPFloat - If this is a sequential container of floating point
2419 /// type, return the specified element as an APFloat.
2420 APFloat ConstantDataSequential::getElementAsAPFloat(unsigned Elt) const {
2421 const char *EltPtr = getElementPointer(Elt);
2423 switch (getElementType()->getTypeID()) {
2425 llvm_unreachable("Accessor can only be used when element is float/double!");
2426 case Type::FloatTyID: {
2427 const float *FloatPrt = reinterpret_cast<const float *>(EltPtr);
2428 return APFloat(*const_cast<float *>(FloatPrt));
2430 case Type::DoubleTyID: {
2431 const double *DoublePtr = reinterpret_cast<const double *>(EltPtr);
2432 return APFloat(*const_cast<double *>(DoublePtr));
2437 /// getElementAsFloat - If this is an sequential container of floats, return
2438 /// the specified element as a float.
2439 float ConstantDataSequential::getElementAsFloat(unsigned Elt) const {
2440 assert(getElementType()->isFloatTy() &&
2441 "Accessor can only be used when element is a 'float'");
2442 const float *EltPtr = reinterpret_cast<const float *>(getElementPointer(Elt));
2443 return *const_cast<float *>(EltPtr);
2446 /// getElementAsDouble - If this is an sequential container of doubles, return
2447 /// the specified element as a float.
2448 double ConstantDataSequential::getElementAsDouble(unsigned Elt) const {
2449 assert(getElementType()->isDoubleTy() &&
2450 "Accessor can only be used when element is a 'float'");
2451 const double *EltPtr =
2452 reinterpret_cast<const double *>(getElementPointer(Elt));
2453 return *const_cast<double *>(EltPtr);
2456 /// getElementAsConstant - Return a Constant for a specified index's element.
2457 /// Note that this has to compute a new constant to return, so it isn't as
2458 /// efficient as getElementAsInteger/Float/Double.
2459 Constant *ConstantDataSequential::getElementAsConstant(unsigned Elt) const {
2460 if (getElementType()->isFloatTy() || getElementType()->isDoubleTy())
2461 return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
2463 return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
2466 /// isString - This method returns true if this is an array of i8.
2467 bool ConstantDataSequential::isString() const {
2468 return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(8);
2471 /// isCString - This method returns true if the array "isString", ends with a
2472 /// nul byte, and does not contains any other nul bytes.
2473 bool ConstantDataSequential::isCString() const {
2477 StringRef Str = getAsString();
2479 // The last value must be nul.
2480 if (Str.back() != 0) return false;
2482 // Other elements must be non-nul.
2483 return Str.drop_back().find(0) == StringRef::npos;
2486 /// getSplatValue - If this is a splat constant, meaning that all of the
2487 /// elements have the same value, return that value. Otherwise return NULL.
2488 Constant *ConstantDataVector::getSplatValue() const {
2489 const char *Base = getRawDataValues().data();
2491 // Compare elements 1+ to the 0'th element.
2492 unsigned EltSize = getElementByteSize();
2493 for (unsigned i = 1, e = getNumElements(); i != e; ++i)
2494 if (memcmp(Base, Base+i*EltSize, EltSize))
2497 // If they're all the same, return the 0th one as a representative.
2498 return getElementAsConstant(0);
2501 //===----------------------------------------------------------------------===//
2502 // replaceUsesOfWithOnConstant implementations
2504 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2505 /// 'From' to be uses of 'To'. This must update the uniquing data structures
2508 /// Note that we intentionally replace all uses of From with To here. Consider
2509 /// a large array that uses 'From' 1000 times. By handling this case all here,
2510 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2511 /// single invocation handles all 1000 uses. Handling them one at a time would
2512 /// work, but would be really slow because it would have to unique each updated
2515 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
2517 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2518 Constant *ToC = cast<Constant>(To);
2520 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
2522 SmallVector<Constant*, 8> Values;
2523 LLVMContextImpl::ArrayConstantsTy::LookupKey Lookup;
2524 Lookup.first = cast<ArrayType>(getType());
2525 Values.reserve(getNumOperands()); // Build replacement array.
2527 // Fill values with the modified operands of the constant array. Also,
2528 // compute whether this turns into an all-zeros array.
2529 unsigned NumUpdated = 0;
2531 // Keep track of whether all the values in the array are "ToC".
2532 bool AllSame = true;
2533 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2534 Constant *Val = cast<Constant>(O->get());
2539 Values.push_back(Val);
2540 AllSame &= Val == ToC;
2543 Constant *Replacement = 0;
2544 if (AllSame && ToC->isNullValue()) {
2545 Replacement = ConstantAggregateZero::get(getType());
2546 } else if (AllSame && isa<UndefValue>(ToC)) {
2547 Replacement = UndefValue::get(getType());
2549 // Check to see if we have this array type already.
2550 Lookup.second = makeArrayRef(Values);
2551 LLVMContextImpl::ArrayConstantsTy::MapTy::iterator I =
2552 pImpl->ArrayConstants.find(Lookup);
2554 if (I != pImpl->ArrayConstants.map_end()) {
2555 Replacement = I->first;
2557 // Okay, the new shape doesn't exist in the system yet. Instead of
2558 // creating a new constant array, inserting it, replaceallusesof'ing the
2559 // old with the new, then deleting the old... just update the current one
2561 pImpl->ArrayConstants.remove(this);
2563 // Update to the new value. Optimize for the case when we have a single
2564 // operand that we're changing, but handle bulk updates efficiently.
2565 if (NumUpdated == 1) {
2566 unsigned OperandToUpdate = U - OperandList;
2567 assert(getOperand(OperandToUpdate) == From &&
2568 "ReplaceAllUsesWith broken!");
2569 setOperand(OperandToUpdate, ToC);
2571 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2572 if (getOperand(i) == From)
2575 pImpl->ArrayConstants.insert(this);
2580 // Otherwise, I do need to replace this with an existing value.
2581 assert(Replacement != this && "I didn't contain From!");
2583 // Everyone using this now uses the replacement.
2584 replaceAllUsesWith(Replacement);
2586 // Delete the old constant!
2590 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2592 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2593 Constant *ToC = cast<Constant>(To);
2595 unsigned OperandToUpdate = U-OperandList;
2596 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2598 SmallVector<Constant*, 8> Values;
2599 LLVMContextImpl::StructConstantsTy::LookupKey Lookup;
2600 Lookup.first = cast<StructType>(getType());
2601 Values.reserve(getNumOperands()); // Build replacement struct.
2603 // Fill values with the modified operands of the constant struct. Also,
2604 // compute whether this turns into an all-zeros struct.
2605 bool isAllZeros = false;
2606 bool isAllUndef = false;
2607 if (ToC->isNullValue()) {
2609 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2610 Constant *Val = cast<Constant>(O->get());
2611 Values.push_back(Val);
2612 if (isAllZeros) isAllZeros = Val->isNullValue();
2614 } else if (isa<UndefValue>(ToC)) {
2616 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2617 Constant *Val = cast<Constant>(O->get());
2618 Values.push_back(Val);
2619 if (isAllUndef) isAllUndef = isa<UndefValue>(Val);
2622 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
2623 Values.push_back(cast<Constant>(O->get()));
2625 Values[OperandToUpdate] = ToC;
2627 LLVMContextImpl *pImpl = getContext().pImpl;
2629 Constant *Replacement = 0;
2631 Replacement = ConstantAggregateZero::get(getType());
2632 } else if (isAllUndef) {
2633 Replacement = UndefValue::get(getType());
2635 // Check to see if we have this struct type already.
2636 Lookup.second = makeArrayRef(Values);
2637 LLVMContextImpl::StructConstantsTy::MapTy::iterator I =
2638 pImpl->StructConstants.find(Lookup);
2640 if (I != pImpl->StructConstants.map_end()) {
2641 Replacement = I->first;
2643 // Okay, the new shape doesn't exist in the system yet. Instead of
2644 // creating a new constant struct, inserting it, replaceallusesof'ing the
2645 // old with the new, then deleting the old... just update the current one
2647 pImpl->StructConstants.remove(this);
2649 // Update to the new value.
2650 setOperand(OperandToUpdate, ToC);
2651 pImpl->StructConstants.insert(this);
2656 assert(Replacement != this && "I didn't contain From!");
2658 // Everyone using this now uses the replacement.
2659 replaceAllUsesWith(Replacement);
2661 // Delete the old constant!
2665 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2667 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2669 SmallVector<Constant*, 8> Values;
2670 Values.reserve(getNumOperands()); // Build replacement array...
2671 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2672 Constant *Val = getOperand(i);
2673 if (Val == From) Val = cast<Constant>(To);
2674 Values.push_back(Val);
2677 Constant *Replacement = get(Values);
2678 assert(Replacement != this && "I didn't contain From!");
2680 // Everyone using this now uses the replacement.
2681 replaceAllUsesWith(Replacement);
2683 // Delete the old constant!
2687 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2689 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2690 Constant *To = cast<Constant>(ToV);
2692 SmallVector<Constant*, 8> NewOps;
2693 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2694 Constant *Op = getOperand(i);
2695 NewOps.push_back(Op == From ? To : Op);
2698 Constant *Replacement = getWithOperands(NewOps);
2699 assert(Replacement != this && "I didn't contain From!");
2701 // Everyone using this now uses the replacement.
2702 replaceAllUsesWith(Replacement);
2704 // Delete the old constant!
2708 Instruction *ConstantExpr::getAsInstruction() {
2709 SmallVector<Value*,4> ValueOperands;
2710 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
2711 ValueOperands.push_back(cast<Value>(I));
2713 ArrayRef<Value*> Ops(ValueOperands);
2715 switch (getOpcode()) {
2716 case Instruction::Trunc:
2717 case Instruction::ZExt:
2718 case Instruction::SExt:
2719 case Instruction::FPTrunc:
2720 case Instruction::FPExt:
2721 case Instruction::UIToFP:
2722 case Instruction::SIToFP:
2723 case Instruction::FPToUI:
2724 case Instruction::FPToSI:
2725 case Instruction::PtrToInt:
2726 case Instruction::IntToPtr:
2727 case Instruction::BitCast:
2728 return CastInst::Create((Instruction::CastOps)getOpcode(),
2730 case Instruction::Select:
2731 return SelectInst::Create(Ops[0], Ops[1], Ops[2]);
2732 case Instruction::InsertElement:
2733 return InsertElementInst::Create(Ops[0], Ops[1], Ops[2]);
2734 case Instruction::ExtractElement:
2735 return ExtractElementInst::Create(Ops[0], Ops[1]);
2736 case Instruction::InsertValue:
2737 return InsertValueInst::Create(Ops[0], Ops[1], getIndices());
2738 case Instruction::ExtractValue:
2739 return ExtractValueInst::Create(Ops[0], getIndices());
2740 case Instruction::ShuffleVector:
2741 return new ShuffleVectorInst(Ops[0], Ops[1], Ops[2]);
2743 case Instruction::GetElementPtr:
2744 if (cast<GEPOperator>(this)->isInBounds())
2745 return GetElementPtrInst::CreateInBounds(Ops[0], Ops.slice(1));
2747 return GetElementPtrInst::Create(Ops[0], Ops.slice(1));
2749 case Instruction::ICmp:
2750 case Instruction::FCmp:
2751 return CmpInst::Create((Instruction::OtherOps)getOpcode(),
2752 getPredicate(), Ops[0], Ops[1]);
2755 assert(getNumOperands() == 2 && "Must be binary operator?");
2756 BinaryOperator *BO =
2757 BinaryOperator::Create((Instruction::BinaryOps)getOpcode(),
2759 if (isa<OverflowingBinaryOperator>(BO)) {
2760 BO->setHasNoUnsignedWrap(SubclassOptionalData &
2761 OverflowingBinaryOperator::NoUnsignedWrap);
2762 BO->setHasNoSignedWrap(SubclassOptionalData &
2763 OverflowingBinaryOperator::NoSignedWrap);
2765 if (isa<PossiblyExactOperator>(BO))
2766 BO->setIsExact(SubclassOptionalData & PossiblyExactOperator::IsExact);