1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Constant* classes.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Constants.h"
15 #include "LLVMContextImpl.h"
16 #include "ConstantFold.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/GlobalValue.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Module.h"
21 #include "llvm/Operator.h"
22 #include "llvm/ADT/FoldingSet.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/StringMap.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/MathExtras.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Support/GetElementPtrTypeIterator.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/STLExtras.h"
39 //===----------------------------------------------------------------------===//
41 //===----------------------------------------------------------------------===//
43 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 assert(0 && "Cannot create a null constant of that type!");
125 Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) {
126 Type *ScalarTy = Ty->getScalarType();
128 // Create the base integer constant.
129 Constant *C = ConstantInt::get(Ty->getContext(), V);
131 // Convert an integer to a pointer, if necessary.
132 if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
133 C = ConstantExpr::getIntToPtr(C, PTy);
135 // Broadcast a scalar to a vector, if necessary.
136 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
137 C = ConstantVector::getSplat(VTy->getNumElements(), C);
142 Constant *Constant::getAllOnesValue(Type *Ty) {
143 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
144 return ConstantInt::get(Ty->getContext(),
145 APInt::getAllOnesValue(ITy->getBitWidth()));
147 if (Ty->isFloatingPointTy()) {
148 APFloat FL = APFloat::getAllOnesValue(Ty->getPrimitiveSizeInBits(),
149 !Ty->isPPC_FP128Ty());
150 return ConstantFP::get(Ty->getContext(), FL);
153 VectorType *VTy = cast<VectorType>(Ty);
154 return ConstantVector::getSplat(VTy->getNumElements(),
155 getAllOnesValue(VTy->getElementType()));
158 /// getAggregateElement - For aggregates (struct/array/vector) return the
159 /// constant that corresponds to the specified element if possible, or null if
160 /// not. This can return null if the element index is a ConstantExpr, or if
161 /// 'this' is a constant expr.
162 Constant *Constant::getAggregateElement(unsigned Elt) const {
163 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(this))
164 return Elt < CS->getNumOperands() ? CS->getOperand(Elt) : 0;
166 if (const ConstantArray *CA = dyn_cast<ConstantArray>(this))
167 return Elt < CA->getNumOperands() ? CA->getOperand(Elt) : 0;
169 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
170 return Elt < CV->getNumOperands() ? CV->getOperand(Elt) : 0;
172 if (const ConstantAggregateZero *CAZ =dyn_cast<ConstantAggregateZero>(this))
173 return CAZ->getElementValue(Elt);
175 if (const UndefValue *UV = dyn_cast<UndefValue>(this))
176 return UV->getElementValue(Elt);
178 if (const ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(this))
179 return CDS->getElementAsConstant(Elt);
183 Constant *Constant::getAggregateElement(Constant *Elt) const {
184 assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
185 if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt))
186 return getAggregateElement(CI->getZExtValue());
191 void Constant::destroyConstantImpl() {
192 // When a Constant is destroyed, there may be lingering
193 // references to the constant by other constants in the constant pool. These
194 // constants are implicitly dependent on the module that is being deleted,
195 // but they don't know that. Because we only find out when the CPV is
196 // deleted, we must now notify all of our users (that should only be
197 // Constants) that they are, in fact, invalid now and should be deleted.
199 while (!use_empty()) {
200 Value *V = use_back();
201 #ifndef NDEBUG // Only in -g mode...
202 if (!isa<Constant>(V)) {
203 dbgs() << "While deleting: " << *this
204 << "\n\nUse still stuck around after Def is destroyed: "
208 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
209 cast<Constant>(V)->destroyConstant();
211 // The constant should remove itself from our use list...
212 assert((use_empty() || use_back() != V) && "Constant not removed!");
215 // Value has no outstanding references it is safe to delete it now...
219 /// canTrap - Return true if evaluation of this constant could trap. This is
220 /// true for things like constant expressions that could divide by zero.
221 bool Constant::canTrap() const {
222 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
223 // The only thing that could possibly trap are constant exprs.
224 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
225 if (!CE) return false;
227 // ConstantExpr traps if any operands can trap.
228 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
229 if (CE->getOperand(i)->canTrap())
232 // Otherwise, only specific operations can trap.
233 switch (CE->getOpcode()) {
236 case Instruction::UDiv:
237 case Instruction::SDiv:
238 case Instruction::FDiv:
239 case Instruction::URem:
240 case Instruction::SRem:
241 case Instruction::FRem:
242 // Div and rem can trap if the RHS is not known to be non-zero.
243 if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
249 /// isConstantUsed - Return true if the constant has users other than constant
250 /// exprs and other dangling things.
251 bool Constant::isConstantUsed() const {
252 for (const_use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
253 const Constant *UC = dyn_cast<Constant>(*UI);
254 if (UC == 0 || isa<GlobalValue>(UC))
257 if (UC->isConstantUsed())
265 /// getRelocationInfo - This method classifies the entry according to
266 /// whether or not it may generate a relocation entry. This must be
267 /// conservative, so if it might codegen to a relocatable entry, it should say
268 /// so. The return values are:
270 /// NoRelocation: This constant pool entry is guaranteed to never have a
271 /// relocation applied to it (because it holds a simple constant like
273 /// LocalRelocation: This entry has relocations, but the entries are
274 /// guaranteed to be resolvable by the static linker, so the dynamic
275 /// linker will never see them.
276 /// GlobalRelocations: This entry may have arbitrary relocations.
278 /// FIXME: This really should not be in VMCore.
279 Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
280 if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
281 if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
282 return LocalRelocation; // Local to this file/library.
283 return GlobalRelocations; // Global reference.
286 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
287 return BA->getFunction()->getRelocationInfo();
289 // While raw uses of blockaddress need to be relocated, differences between
290 // two of them don't when they are for labels in the same function. This is a
291 // common idiom when creating a table for the indirect goto extension, so we
292 // handle it efficiently here.
293 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this))
294 if (CE->getOpcode() == Instruction::Sub) {
295 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
296 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
298 LHS->getOpcode() == Instruction::PtrToInt &&
299 RHS->getOpcode() == Instruction::PtrToInt &&
300 isa<BlockAddress>(LHS->getOperand(0)) &&
301 isa<BlockAddress>(RHS->getOperand(0)) &&
302 cast<BlockAddress>(LHS->getOperand(0))->getFunction() ==
303 cast<BlockAddress>(RHS->getOperand(0))->getFunction())
307 PossibleRelocationsTy Result = NoRelocation;
308 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
309 Result = std::max(Result,
310 cast<Constant>(getOperand(i))->getRelocationInfo());
315 /// removeDeadUsersOfConstant - If the specified constantexpr is dead, remove
316 /// it. This involves recursively eliminating any dead users of the
318 static bool removeDeadUsersOfConstant(const Constant *C) {
319 if (isa<GlobalValue>(C)) return false; // Cannot remove this
321 while (!C->use_empty()) {
322 const Constant *User = dyn_cast<Constant>(C->use_back());
323 if (!User) return false; // Non-constant usage;
324 if (!removeDeadUsersOfConstant(User))
325 return false; // Constant wasn't dead
328 const_cast<Constant*>(C)->destroyConstant();
333 /// removeDeadConstantUsers - If there are any dead constant users dangling
334 /// off of this constant, remove them. This method is useful for clients
335 /// that want to check to see if a global is unused, but don't want to deal
336 /// with potentially dead constants hanging off of the globals.
337 void Constant::removeDeadConstantUsers() const {
338 Value::const_use_iterator I = use_begin(), E = use_end();
339 Value::const_use_iterator LastNonDeadUser = E;
341 const Constant *User = dyn_cast<Constant>(*I);
348 if (!removeDeadUsersOfConstant(User)) {
349 // If the constant wasn't dead, remember that this was the last live use
350 // and move on to the next constant.
356 // If the constant was dead, then the iterator is invalidated.
357 if (LastNonDeadUser == E) {
369 //===----------------------------------------------------------------------===//
371 //===----------------------------------------------------------------------===//
373 void ConstantInt::anchor() { }
375 ConstantInt::ConstantInt(IntegerType *Ty, const APInt& V)
376 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
377 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
380 ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
381 LLVMContextImpl *pImpl = Context.pImpl;
382 if (!pImpl->TheTrueVal)
383 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
384 return pImpl->TheTrueVal;
387 ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
388 LLVMContextImpl *pImpl = Context.pImpl;
389 if (!pImpl->TheFalseVal)
390 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
391 return pImpl->TheFalseVal;
394 Constant *ConstantInt::getTrue(Type *Ty) {
395 VectorType *VTy = dyn_cast<VectorType>(Ty);
397 assert(Ty->isIntegerTy(1) && "True must be i1 or vector of i1.");
398 return ConstantInt::getTrue(Ty->getContext());
400 assert(VTy->getElementType()->isIntegerTy(1) &&
401 "True must be vector of i1 or i1.");
402 return ConstantVector::getSplat(VTy->getNumElements(),
403 ConstantInt::getTrue(Ty->getContext()));
406 Constant *ConstantInt::getFalse(Type *Ty) {
407 VectorType *VTy = dyn_cast<VectorType>(Ty);
409 assert(Ty->isIntegerTy(1) && "False must be i1 or vector of i1.");
410 return ConstantInt::getFalse(Ty->getContext());
412 assert(VTy->getElementType()->isIntegerTy(1) &&
413 "False must be vector of i1 or i1.");
414 return ConstantVector::getSplat(VTy->getNumElements(),
415 ConstantInt::getFalse(Ty->getContext()));
419 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
420 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
421 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
422 // compare APInt's of different widths, which would violate an APInt class
423 // invariant which generates an assertion.
424 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
425 // Get the corresponding integer type for the bit width of the value.
426 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
427 // get an existing value or the insertion position
428 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
429 ConstantInt *&Slot = Context.pImpl->IntConstants[Key];
430 if (!Slot) Slot = new ConstantInt(ITy, V);
434 Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
435 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
437 // For vectors, broadcast the value.
438 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
439 return ConstantVector::getSplat(VTy->getNumElements(), C);
444 ConstantInt* ConstantInt::get(IntegerType* Ty, uint64_t V,
446 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
449 ConstantInt* ConstantInt::getSigned(IntegerType* Ty, int64_t V) {
450 return get(Ty, V, true);
453 Constant *ConstantInt::getSigned(Type *Ty, int64_t V) {
454 return get(Ty, V, true);
457 Constant *ConstantInt::get(Type* Ty, const APInt& V) {
458 ConstantInt *C = get(Ty->getContext(), V);
459 assert(C->getType() == Ty->getScalarType() &&
460 "ConstantInt type doesn't match the type implied by its value!");
462 // For vectors, broadcast the value.
463 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
464 return ConstantVector::getSplat(VTy->getNumElements(), C);
469 ConstantInt* ConstantInt::get(IntegerType* Ty, StringRef Str,
471 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
474 //===----------------------------------------------------------------------===//
476 //===----------------------------------------------------------------------===//
478 static const fltSemantics *TypeToFloatSemantics(Type *Ty) {
480 return &APFloat::IEEEhalf;
482 return &APFloat::IEEEsingle;
483 if (Ty->isDoubleTy())
484 return &APFloat::IEEEdouble;
485 if (Ty->isX86_FP80Ty())
486 return &APFloat::x87DoubleExtended;
487 else if (Ty->isFP128Ty())
488 return &APFloat::IEEEquad;
490 assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
491 return &APFloat::PPCDoubleDouble;
494 void ConstantFP::anchor() { }
496 /// get() - This returns a constant fp for the specified value in the
497 /// specified type. This should only be used for simple constant values like
498 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
499 Constant *ConstantFP::get(Type* Ty, double V) {
500 LLVMContext &Context = Ty->getContext();
504 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
505 APFloat::rmNearestTiesToEven, &ignored);
506 Constant *C = get(Context, FV);
508 // For vectors, broadcast the value.
509 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
510 return ConstantVector::getSplat(VTy->getNumElements(), C);
516 Constant *ConstantFP::get(Type* Ty, StringRef Str) {
517 LLVMContext &Context = Ty->getContext();
519 APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
520 Constant *C = get(Context, FV);
522 // For vectors, broadcast the value.
523 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
524 return ConstantVector::getSplat(VTy->getNumElements(), C);
530 ConstantFP *ConstantFP::getNegativeZero(Type *Ty) {
531 LLVMContext &Context = Ty->getContext();
532 APFloat apf = cast<ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
534 return get(Context, apf);
538 Constant *ConstantFP::getZeroValueForNegation(Type *Ty) {
539 Type *ScalarTy = Ty->getScalarType();
540 if (ScalarTy->isFloatingPointTy()) {
541 Constant *C = getNegativeZero(ScalarTy);
542 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
543 return ConstantVector::getSplat(VTy->getNumElements(), C);
547 return Constant::getNullValue(Ty);
551 // ConstantFP accessors.
552 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
553 DenseMapAPFloatKeyInfo::KeyTy Key(V);
555 LLVMContextImpl* pImpl = Context.pImpl;
557 ConstantFP *&Slot = pImpl->FPConstants[Key];
561 if (&V.getSemantics() == &APFloat::IEEEhalf)
562 Ty = Type::getHalfTy(Context);
563 else if (&V.getSemantics() == &APFloat::IEEEsingle)
564 Ty = Type::getFloatTy(Context);
565 else if (&V.getSemantics() == &APFloat::IEEEdouble)
566 Ty = Type::getDoubleTy(Context);
567 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
568 Ty = Type::getX86_FP80Ty(Context);
569 else if (&V.getSemantics() == &APFloat::IEEEquad)
570 Ty = Type::getFP128Ty(Context);
572 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
573 "Unknown FP format");
574 Ty = Type::getPPC_FP128Ty(Context);
576 Slot = new ConstantFP(Ty, V);
582 ConstantFP *ConstantFP::getInfinity(Type *Ty, bool Negative) {
583 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty);
584 return ConstantFP::get(Ty->getContext(),
585 APFloat::getInf(Semantics, Negative));
588 ConstantFP::ConstantFP(Type *Ty, const APFloat& V)
589 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
590 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
594 bool ConstantFP::isExactlyValue(const APFloat &V) const {
595 return Val.bitwiseIsEqual(V);
598 //===----------------------------------------------------------------------===//
599 // ConstantAggregateZero Implementation
600 //===----------------------------------------------------------------------===//
602 /// getSequentialElement - If this CAZ has array or vector type, return a zero
603 /// with the right element type.
604 Constant *ConstantAggregateZero::getSequentialElement() const {
605 return Constant::getNullValue(getType()->getSequentialElementType());
608 /// getStructElement - If this CAZ has struct type, return a zero with the
609 /// right element type for the specified element.
610 Constant *ConstantAggregateZero::getStructElement(unsigned Elt) const {
611 return Constant::getNullValue(getType()->getStructElementType(Elt));
614 /// getElementValue - Return a zero of the right value for the specified GEP
615 /// index if we can, otherwise return null (e.g. if C is a ConstantExpr).
616 Constant *ConstantAggregateZero::getElementValue(Constant *C) const {
617 if (isa<SequentialType>(getType()))
618 return getSequentialElement();
619 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
622 /// getElementValue - Return a zero of the right value for the specified GEP
624 Constant *ConstantAggregateZero::getElementValue(unsigned Idx) const {
625 if (isa<SequentialType>(getType()))
626 return getSequentialElement();
627 return getStructElement(Idx);
631 //===----------------------------------------------------------------------===//
632 // UndefValue Implementation
633 //===----------------------------------------------------------------------===//
635 /// getSequentialElement - If this undef has array or vector type, return an
636 /// undef with the right element type.
637 UndefValue *UndefValue::getSequentialElement() const {
638 return UndefValue::get(getType()->getSequentialElementType());
641 /// getStructElement - If this undef has struct type, return a zero with the
642 /// right element type for the specified element.
643 UndefValue *UndefValue::getStructElement(unsigned Elt) const {
644 return UndefValue::get(getType()->getStructElementType(Elt));
647 /// getElementValue - Return an undef of the right value for the specified GEP
648 /// index if we can, otherwise return null (e.g. if C is a ConstantExpr).
649 UndefValue *UndefValue::getElementValue(Constant *C) const {
650 if (isa<SequentialType>(getType()))
651 return getSequentialElement();
652 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
655 /// getElementValue - Return an undef of the right value for the specified GEP
657 UndefValue *UndefValue::getElementValue(unsigned Idx) const {
658 if (isa<SequentialType>(getType()))
659 return getSequentialElement();
660 return getStructElement(Idx);
665 //===----------------------------------------------------------------------===//
666 // ConstantXXX Classes
667 //===----------------------------------------------------------------------===//
670 ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
671 : Constant(T, ConstantArrayVal,
672 OperandTraits<ConstantArray>::op_end(this) - V.size(),
674 assert(V.size() == T->getNumElements() &&
675 "Invalid initializer vector for constant array");
676 for (unsigned i = 0, e = V.size(); i != e; ++i)
677 assert(V[i]->getType() == T->getElementType() &&
678 "Initializer for array element doesn't match array element type!");
679 std::copy(V.begin(), V.end(), op_begin());
682 Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
683 for (unsigned i = 0, e = V.size(); i != e; ++i) {
684 assert(V[i]->getType() == Ty->getElementType() &&
685 "Wrong type in array element initializer");
687 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
688 // If this is an all-zero array, return a ConstantAggregateZero object
689 bool isAllZero = true;
690 bool isUndef = false;
693 isAllZero = C->isNullValue();
694 isUndef = isa<UndefValue>(C);
696 if (isAllZero || isUndef)
697 for (unsigned i = 1, e = V.size(); i != e; ++i)
706 return ConstantAggregateZero::get(Ty);
708 return UndefValue::get(Ty);
709 return pImpl->ArrayConstants.getOrCreate(Ty, V);
712 /// ConstantArray::get(const string&) - Return an array that is initialized to
713 /// contain the specified string. If length is zero then a null terminator is
714 /// added to the specified string so that it may be used in a natural way.
715 /// Otherwise, the length parameter specifies how much of the string to use
716 /// and it won't be null terminated.
718 Constant *ConstantArray::get(LLVMContext &Context, StringRef Str,
720 std::vector<Constant*> ElementVals;
721 ElementVals.reserve(Str.size() + size_t(AddNull));
722 for (unsigned i = 0; i < Str.size(); ++i)
723 ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), Str[i]));
725 // Add a null terminator to the string...
727 ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), 0));
729 ArrayType *ATy = ArrayType::get(Type::getInt8Ty(Context), ElementVals.size());
730 return get(ATy, ElementVals);
733 /// getTypeForElements - Return an anonymous struct type to use for a constant
734 /// with the specified set of elements. The list must not be empty.
735 StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
736 ArrayRef<Constant*> V,
738 SmallVector<Type*, 16> EltTypes;
739 for (unsigned i = 0, e = V.size(); i != e; ++i)
740 EltTypes.push_back(V[i]->getType());
742 return StructType::get(Context, EltTypes, Packed);
746 StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
749 "ConstantStruct::getTypeForElements cannot be called on empty list");
750 return getTypeForElements(V[0]->getContext(), V, Packed);
754 ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
755 : Constant(T, ConstantStructVal,
756 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
758 assert(V.size() == T->getNumElements() &&
759 "Invalid initializer vector for constant structure");
760 for (unsigned i = 0, e = V.size(); i != e; ++i)
761 assert((T->isOpaque() || V[i]->getType() == T->getElementType(i)) &&
762 "Initializer for struct element doesn't match struct element type!");
763 std::copy(V.begin(), V.end(), op_begin());
766 // ConstantStruct accessors.
767 Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
768 assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
769 "Incorrect # elements specified to ConstantStruct::get");
771 // Create a ConstantAggregateZero value if all elements are zeros.
773 bool isUndef = false;
776 isUndef = isa<UndefValue>(V[0]);
777 isZero = V[0]->isNullValue();
778 if (isUndef || isZero) {
779 for (unsigned i = 0, e = V.size(); i != e; ++i) {
780 if (!V[i]->isNullValue())
782 if (!isa<UndefValue>(V[i]))
788 return ConstantAggregateZero::get(ST);
790 return UndefValue::get(ST);
792 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
795 Constant *ConstantStruct::get(StructType *T, ...) {
797 SmallVector<Constant*, 8> Values;
799 while (Constant *Val = va_arg(ap, llvm::Constant*))
800 Values.push_back(Val);
802 return get(T, Values);
805 ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
806 : Constant(T, ConstantVectorVal,
807 OperandTraits<ConstantVector>::op_end(this) - V.size(),
809 for (size_t i = 0, e = V.size(); i != e; i++)
810 assert(V[i]->getType() == T->getElementType() &&
811 "Initializer for vector element doesn't match vector element type!");
812 std::copy(V.begin(), V.end(), op_begin());
815 // ConstantVector accessors.
816 Constant *ConstantVector::get(ArrayRef<Constant*> V) {
817 assert(!V.empty() && "Vectors can't be empty");
818 VectorType *T = VectorType::get(V.front()->getType(), V.size());
819 LLVMContextImpl *pImpl = T->getContext().pImpl;
821 // If this is an all-undef or all-zero vector, return a
822 // ConstantAggregateZero or UndefValue.
824 bool isZero = C->isNullValue();
825 bool isUndef = isa<UndefValue>(C);
827 if (isZero || isUndef) {
828 for (unsigned i = 1, e = V.size(); i != e; ++i)
830 isZero = isUndef = false;
836 return ConstantAggregateZero::get(T);
838 return UndefValue::get(T);
840 return pImpl->VectorConstants.getOrCreate(T, V);
843 Constant *ConstantVector::getSplat(unsigned NumElts, Constant *V) {
844 SmallVector<Constant*, 32> Elts(NumElts, V);
849 // Utility function for determining if a ConstantExpr is a CastOp or not. This
850 // can't be inline because we don't want to #include Instruction.h into
852 bool ConstantExpr::isCast() const {
853 return Instruction::isCast(getOpcode());
856 bool ConstantExpr::isCompare() const {
857 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
860 bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
861 if (getOpcode() != Instruction::GetElementPtr) return false;
863 gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
864 User::const_op_iterator OI = llvm::next(this->op_begin());
866 // Skip the first index, as it has no static limit.
870 // The remaining indices must be compile-time known integers within the
871 // bounds of the corresponding notional static array types.
872 for (; GEPI != E; ++GEPI, ++OI) {
873 ConstantInt *CI = dyn_cast<ConstantInt>(*OI);
874 if (!CI) return false;
875 if (ArrayType *ATy = dyn_cast<ArrayType>(*GEPI))
876 if (CI->getValue().getActiveBits() > 64 ||
877 CI->getZExtValue() >= ATy->getNumElements())
881 // All the indices checked out.
885 bool ConstantExpr::hasIndices() const {
886 return getOpcode() == Instruction::ExtractValue ||
887 getOpcode() == Instruction::InsertValue;
890 ArrayRef<unsigned> ConstantExpr::getIndices() const {
891 if (const ExtractValueConstantExpr *EVCE =
892 dyn_cast<ExtractValueConstantExpr>(this))
893 return EVCE->Indices;
895 return cast<InsertValueConstantExpr>(this)->Indices;
898 unsigned ConstantExpr::getPredicate() const {
900 return ((const CompareConstantExpr*)this)->predicate;
903 /// getWithOperandReplaced - Return a constant expression identical to this
904 /// one, but with the specified operand set to the specified value.
906 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
907 assert(OpNo < getNumOperands() && "Operand num is out of range!");
908 assert(Op->getType() == getOperand(OpNo)->getType() &&
909 "Replacing operand with value of different type!");
910 if (getOperand(OpNo) == Op)
911 return const_cast<ConstantExpr*>(this);
913 Constant *Op0, *Op1, *Op2;
914 switch (getOpcode()) {
915 case Instruction::Trunc:
916 case Instruction::ZExt:
917 case Instruction::SExt:
918 case Instruction::FPTrunc:
919 case Instruction::FPExt:
920 case Instruction::UIToFP:
921 case Instruction::SIToFP:
922 case Instruction::FPToUI:
923 case Instruction::FPToSI:
924 case Instruction::PtrToInt:
925 case Instruction::IntToPtr:
926 case Instruction::BitCast:
927 return ConstantExpr::getCast(getOpcode(), Op, getType());
928 case Instruction::Select:
929 Op0 = (OpNo == 0) ? Op : getOperand(0);
930 Op1 = (OpNo == 1) ? Op : getOperand(1);
931 Op2 = (OpNo == 2) ? Op : getOperand(2);
932 return ConstantExpr::getSelect(Op0, Op1, Op2);
933 case Instruction::InsertElement:
934 Op0 = (OpNo == 0) ? Op : getOperand(0);
935 Op1 = (OpNo == 1) ? Op : getOperand(1);
936 Op2 = (OpNo == 2) ? Op : getOperand(2);
937 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
938 case Instruction::ExtractElement:
939 Op0 = (OpNo == 0) ? Op : getOperand(0);
940 Op1 = (OpNo == 1) ? Op : getOperand(1);
941 return ConstantExpr::getExtractElement(Op0, Op1);
942 case Instruction::ShuffleVector:
943 Op0 = (OpNo == 0) ? Op : getOperand(0);
944 Op1 = (OpNo == 1) ? Op : getOperand(1);
945 Op2 = (OpNo == 2) ? Op : getOperand(2);
946 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
947 case Instruction::GetElementPtr: {
948 SmallVector<Constant*, 8> Ops;
949 Ops.resize(getNumOperands()-1);
950 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
951 Ops[i-1] = getOperand(i);
954 ConstantExpr::getGetElementPtr(Op, Ops,
955 cast<GEPOperator>(this)->isInBounds());
958 ConstantExpr::getGetElementPtr(getOperand(0), Ops,
959 cast<GEPOperator>(this)->isInBounds());
962 assert(getNumOperands() == 2 && "Must be binary operator?");
963 Op0 = (OpNo == 0) ? Op : getOperand(0);
964 Op1 = (OpNo == 1) ? Op : getOperand(1);
965 return ConstantExpr::get(getOpcode(), Op0, Op1, SubclassOptionalData);
969 /// getWithOperands - This returns the current constant expression with the
970 /// operands replaced with the specified values. The specified array must
971 /// have the same number of operands as our current one.
972 Constant *ConstantExpr::
973 getWithOperands(ArrayRef<Constant*> Ops, Type *Ty) const {
974 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
975 bool AnyChange = Ty != getType();
976 for (unsigned i = 0; i != Ops.size(); ++i)
977 AnyChange |= Ops[i] != getOperand(i);
979 if (!AnyChange) // No operands changed, return self.
980 return const_cast<ConstantExpr*>(this);
982 switch (getOpcode()) {
983 case Instruction::Trunc:
984 case Instruction::ZExt:
985 case Instruction::SExt:
986 case Instruction::FPTrunc:
987 case Instruction::FPExt:
988 case Instruction::UIToFP:
989 case Instruction::SIToFP:
990 case Instruction::FPToUI:
991 case Instruction::FPToSI:
992 case Instruction::PtrToInt:
993 case Instruction::IntToPtr:
994 case Instruction::BitCast:
995 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty);
996 case Instruction::Select:
997 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
998 case Instruction::InsertElement:
999 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
1000 case Instruction::ExtractElement:
1001 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
1002 case Instruction::ShuffleVector:
1003 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
1004 case Instruction::GetElementPtr:
1006 ConstantExpr::getGetElementPtr(Ops[0], Ops.slice(1),
1007 cast<GEPOperator>(this)->isInBounds());
1008 case Instruction::ICmp:
1009 case Instruction::FCmp:
1010 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
1012 assert(getNumOperands() == 2 && "Must be binary operator?");
1013 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData);
1018 //===----------------------------------------------------------------------===//
1019 // isValueValidForType implementations
1021 bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
1022 unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
1023 if (Ty->isIntegerTy(1))
1024 return Val == 0 || Val == 1;
1026 return true; // always true, has to fit in largest type
1027 uint64_t Max = (1ll << NumBits) - 1;
1031 bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
1032 unsigned NumBits = Ty->getIntegerBitWidth();
1033 if (Ty->isIntegerTy(1))
1034 return Val == 0 || Val == 1 || Val == -1;
1036 return true; // always true, has to fit in largest type
1037 int64_t Min = -(1ll << (NumBits-1));
1038 int64_t Max = (1ll << (NumBits-1)) - 1;
1039 return (Val >= Min && Val <= Max);
1042 bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {
1043 // convert modifies in place, so make a copy.
1044 APFloat Val2 = APFloat(Val);
1046 switch (Ty->getTypeID()) {
1048 return false; // These can't be represented as floating point!
1050 // FIXME rounding mode needs to be more flexible
1051 case Type::HalfTyID: {
1052 if (&Val2.getSemantics() == &APFloat::IEEEhalf)
1054 Val2.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &losesInfo);
1057 case Type::FloatTyID: {
1058 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
1060 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
1063 case Type::DoubleTyID: {
1064 if (&Val2.getSemantics() == &APFloat::IEEEhalf ||
1065 &Val2.getSemantics() == &APFloat::IEEEsingle ||
1066 &Val2.getSemantics() == &APFloat::IEEEdouble)
1068 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
1071 case Type::X86_FP80TyID:
1072 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1073 &Val2.getSemantics() == &APFloat::IEEEsingle ||
1074 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1075 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
1076 case Type::FP128TyID:
1077 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1078 &Val2.getSemantics() == &APFloat::IEEEsingle ||
1079 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1080 &Val2.getSemantics() == &APFloat::IEEEquad;
1081 case Type::PPC_FP128TyID:
1082 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1083 &Val2.getSemantics() == &APFloat::IEEEsingle ||
1084 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1085 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
1090 //===----------------------------------------------------------------------===//
1091 // Factory Function Implementation
1093 ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
1094 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
1095 "Cannot create an aggregate zero of non-aggregate type!");
1097 ConstantAggregateZero *&Entry = Ty->getContext().pImpl->CAZConstants[Ty];
1099 Entry = new ConstantAggregateZero(Ty);
1104 /// destroyConstant - Remove the constant from the constant table.
1106 void ConstantAggregateZero::destroyConstant() {
1107 getContext().pImpl->CAZConstants.erase(getType());
1108 destroyConstantImpl();
1111 /// destroyConstant - Remove the constant from the constant table...
1113 void ConstantArray::destroyConstant() {
1114 getType()->getContext().pImpl->ArrayConstants.remove(this);
1115 destroyConstantImpl();
1118 /// isString - This method returns true if the array is an array of i8, and
1119 /// if the elements of the array are all ConstantInt's.
1120 bool ConstantArray::isString() const {
1121 // Check the element type for i8...
1122 if (!getType()->getElementType()->isIntegerTy(8))
1124 // Check the elements to make sure they are all integers, not constant
1126 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1127 if (!isa<ConstantInt>(getOperand(i)))
1132 /// isCString - This method returns true if the array is a string (see
1133 /// isString) and it ends in a null byte \\0 and does not contains any other
1134 /// null bytes except its terminator.
1135 bool ConstantArray::isCString() const {
1136 // Check the element type for i8...
1137 if (!getType()->getElementType()->isIntegerTy(8))
1140 // Last element must be a null.
1141 if (!getOperand(getNumOperands()-1)->isNullValue())
1143 // Other elements must be non-null integers.
1144 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1145 if (!isa<ConstantInt>(getOperand(i)))
1147 if (getOperand(i)->isNullValue())
1154 /// convertToString - Helper function for getAsString() and getAsCString().
1155 static std::string convertToString(const User *U, unsigned len) {
1157 Result.reserve(len);
1158 for (unsigned i = 0; i != len; ++i)
1159 Result.push_back((char)cast<ConstantInt>(U->getOperand(i))->getZExtValue());
1163 /// getAsString - If this array is isString(), then this method converts the
1164 /// array to an std::string and returns it. Otherwise, it asserts out.
1166 std::string ConstantArray::getAsString() const {
1167 assert(isString() && "Not a string!");
1168 return convertToString(this, getNumOperands());
1172 /// getAsCString - If this array is isCString(), then this method converts the
1173 /// array (without the trailing null byte) to an std::string and returns it.
1174 /// Otherwise, it asserts out.
1176 std::string ConstantArray::getAsCString() const {
1177 assert(isCString() && "Not a string!");
1178 return convertToString(this, getNumOperands() - 1);
1182 //---- ConstantStruct::get() implementation...
1185 // destroyConstant - Remove the constant from the constant table...
1187 void ConstantStruct::destroyConstant() {
1188 getType()->getContext().pImpl->StructConstants.remove(this);
1189 destroyConstantImpl();
1192 // destroyConstant - Remove the constant from the constant table...
1194 void ConstantVector::destroyConstant() {
1195 getType()->getContext().pImpl->VectorConstants.remove(this);
1196 destroyConstantImpl();
1199 /// getSplatValue - If this is a splat constant, where all of the
1200 /// elements have the same value, return that value. Otherwise return null.
1201 Constant *ConstantVector::getSplatValue() const {
1202 // Check out first element.
1203 Constant *Elt = getOperand(0);
1204 // Then make sure all remaining elements point to the same value.
1205 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1206 if (getOperand(I) != Elt)
1211 //---- ConstantPointerNull::get() implementation.
1214 ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
1215 ConstantPointerNull *&Entry = Ty->getContext().pImpl->CPNConstants[Ty];
1217 Entry = new ConstantPointerNull(Ty);
1222 // destroyConstant - Remove the constant from the constant table...
1224 void ConstantPointerNull::destroyConstant() {
1225 getContext().pImpl->CPNConstants.erase(getType());
1226 // Free the constant and any dangling references to it.
1227 destroyConstantImpl();
1231 //---- UndefValue::get() implementation.
1234 UndefValue *UndefValue::get(Type *Ty) {
1235 UndefValue *&Entry = Ty->getContext().pImpl->UVConstants[Ty];
1237 Entry = new UndefValue(Ty);
1242 // destroyConstant - Remove the constant from the constant table.
1244 void UndefValue::destroyConstant() {
1245 // Free the constant and any dangling references to it.
1246 getContext().pImpl->UVConstants.erase(getType());
1247 destroyConstantImpl();
1250 //---- BlockAddress::get() implementation.
1253 BlockAddress *BlockAddress::get(BasicBlock *BB) {
1254 assert(BB->getParent() != 0 && "Block must have a parent");
1255 return get(BB->getParent(), BB);
1258 BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1260 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
1262 BA = new BlockAddress(F, BB);
1264 assert(BA->getFunction() == F && "Basic block moved between functions");
1268 BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1269 : Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1273 BB->AdjustBlockAddressRefCount(1);
1277 // destroyConstant - Remove the constant from the constant table.
1279 void BlockAddress::destroyConstant() {
1280 getFunction()->getType()->getContext().pImpl
1281 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
1282 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1283 destroyConstantImpl();
1286 void BlockAddress::replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U) {
1287 // This could be replacing either the Basic Block or the Function. In either
1288 // case, we have to remove the map entry.
1289 Function *NewF = getFunction();
1290 BasicBlock *NewBB = getBasicBlock();
1293 NewF = cast<Function>(To);
1295 NewBB = cast<BasicBlock>(To);
1297 // See if the 'new' entry already exists, if not, just update this in place
1298 // and return early.
1299 BlockAddress *&NewBA =
1300 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
1302 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1304 // Remove the old entry, this can't cause the map to rehash (just a
1305 // tombstone will get added).
1306 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1309 setOperand(0, NewF);
1310 setOperand(1, NewBB);
1311 getBasicBlock()->AdjustBlockAddressRefCount(1);
1315 // Otherwise, I do need to replace this with an existing value.
1316 assert(NewBA != this && "I didn't contain From!");
1318 // Everyone using this now uses the replacement.
1319 replaceAllUsesWith(NewBA);
1324 //---- ConstantExpr::get() implementations.
1327 /// This is a utility function to handle folding of casts and lookup of the
1328 /// cast in the ExprConstants map. It is used by the various get* methods below.
1329 static inline Constant *getFoldedCast(
1330 Instruction::CastOps opc, Constant *C, Type *Ty) {
1331 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1332 // Fold a few common cases
1333 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1336 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1338 // Look up the constant in the table first to ensure uniqueness
1339 std::vector<Constant*> argVec(1, C);
1340 ExprMapKeyType Key(opc, argVec);
1342 return pImpl->ExprConstants.getOrCreate(Ty, Key);
1345 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty) {
1346 Instruction::CastOps opc = Instruction::CastOps(oc);
1347 assert(Instruction::isCast(opc) && "opcode out of range");
1348 assert(C && Ty && "Null arguments to getCast");
1349 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
1353 llvm_unreachable("Invalid cast opcode");
1354 case Instruction::Trunc: return getTrunc(C, Ty);
1355 case Instruction::ZExt: return getZExt(C, Ty);
1356 case Instruction::SExt: return getSExt(C, Ty);
1357 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1358 case Instruction::FPExt: return getFPExtend(C, Ty);
1359 case Instruction::UIToFP: return getUIToFP(C, Ty);
1360 case Instruction::SIToFP: return getSIToFP(C, Ty);
1361 case Instruction::FPToUI: return getFPToUI(C, Ty);
1362 case Instruction::FPToSI: return getFPToSI(C, Ty);
1363 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1364 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1365 case Instruction::BitCast: return getBitCast(C, Ty);
1369 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) {
1370 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1371 return getBitCast(C, Ty);
1372 return getZExt(C, Ty);
1375 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) {
1376 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1377 return getBitCast(C, Ty);
1378 return getSExt(C, Ty);
1381 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {
1382 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1383 return getBitCast(C, Ty);
1384 return getTrunc(C, Ty);
1387 Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {
1388 assert(S->getType()->isPointerTy() && "Invalid cast");
1389 assert((Ty->isIntegerTy() || Ty->isPointerTy()) && "Invalid cast");
1391 if (Ty->isIntegerTy())
1392 return getPtrToInt(S, Ty);
1393 return getBitCast(S, Ty);
1396 Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty,
1398 assert(C->getType()->isIntOrIntVectorTy() &&
1399 Ty->isIntOrIntVectorTy() && "Invalid cast");
1400 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1401 unsigned DstBits = Ty->getScalarSizeInBits();
1402 Instruction::CastOps opcode =
1403 (SrcBits == DstBits ? Instruction::BitCast :
1404 (SrcBits > DstBits ? Instruction::Trunc :
1405 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1406 return getCast(opcode, C, Ty);
1409 Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) {
1410 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1412 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1413 unsigned DstBits = Ty->getScalarSizeInBits();
1414 if (SrcBits == DstBits)
1415 return C; // Avoid a useless cast
1416 Instruction::CastOps opcode =
1417 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1418 return getCast(opcode, C, Ty);
1421 Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty) {
1423 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1424 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1426 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1427 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
1428 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
1429 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1430 "SrcTy must be larger than DestTy for Trunc!");
1432 return getFoldedCast(Instruction::Trunc, C, Ty);
1435 Constant *ConstantExpr::getSExt(Constant *C, Type *Ty) {
1437 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1438 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1440 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1441 assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
1442 assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
1443 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1444 "SrcTy must be smaller than DestTy for SExt!");
1446 return getFoldedCast(Instruction::SExt, C, Ty);
1449 Constant *ConstantExpr::getZExt(Constant *C, Type *Ty) {
1451 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1452 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1454 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1455 assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
1456 assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
1457 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1458 "SrcTy must be smaller than DestTy for ZExt!");
1460 return getFoldedCast(Instruction::ZExt, C, Ty);
1463 Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty) {
1465 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1466 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1468 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1469 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1470 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1471 "This is an illegal floating point truncation!");
1472 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1475 Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty) {
1477 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1478 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1480 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1481 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1482 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1483 "This is an illegal floating point extension!");
1484 return getFoldedCast(Instruction::FPExt, C, Ty);
1487 Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty) {
1489 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1490 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1492 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1493 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1494 "This is an illegal uint to floating point cast!");
1495 return getFoldedCast(Instruction::UIToFP, C, Ty);
1498 Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty) {
1500 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1501 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1503 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1504 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1505 "This is an illegal sint to floating point cast!");
1506 return getFoldedCast(Instruction::SIToFP, C, Ty);
1509 Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty) {
1511 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1512 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1514 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1515 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1516 "This is an illegal floating point to uint cast!");
1517 return getFoldedCast(Instruction::FPToUI, C, Ty);
1520 Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty) {
1522 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1523 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1525 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1526 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1527 "This is an illegal floating point to sint cast!");
1528 return getFoldedCast(Instruction::FPToSI, C, Ty);
1531 Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy) {
1532 assert(C->getType()->getScalarType()->isPointerTy() &&
1533 "PtrToInt source must be pointer or pointer vector");
1534 assert(DstTy->getScalarType()->isIntegerTy() &&
1535 "PtrToInt destination must be integer or integer vector");
1536 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
1537 if (isa<VectorType>(C->getType()))
1538 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
1539 "Invalid cast between a different number of vector elements");
1540 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1543 Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy) {
1544 assert(C->getType()->getScalarType()->isIntegerTy() &&
1545 "IntToPtr source must be integer or integer vector");
1546 assert(DstTy->getScalarType()->isPointerTy() &&
1547 "IntToPtr destination must be a pointer or pointer vector");
1548 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
1549 if (isa<VectorType>(C->getType()))
1550 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
1551 "Invalid cast between a different number of vector elements");
1552 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1555 Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy) {
1556 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
1557 "Invalid constantexpr bitcast!");
1559 // It is common to ask for a bitcast of a value to its own type, handle this
1561 if (C->getType() == DstTy) return C;
1563 return getFoldedCast(Instruction::BitCast, C, DstTy);
1566 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
1568 // Check the operands for consistency first.
1569 assert(Opcode >= Instruction::BinaryOpsBegin &&
1570 Opcode < Instruction::BinaryOpsEnd &&
1571 "Invalid opcode in binary constant expression");
1572 assert(C1->getType() == C2->getType() &&
1573 "Operand types in binary constant expression should match");
1577 case Instruction::Add:
1578 case Instruction::Sub:
1579 case Instruction::Mul:
1580 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1581 assert(C1->getType()->isIntOrIntVectorTy() &&
1582 "Tried to create an integer operation on a non-integer type!");
1584 case Instruction::FAdd:
1585 case Instruction::FSub:
1586 case Instruction::FMul:
1587 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1588 assert(C1->getType()->isFPOrFPVectorTy() &&
1589 "Tried to create a floating-point operation on a "
1590 "non-floating-point type!");
1592 case Instruction::UDiv:
1593 case Instruction::SDiv:
1594 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1595 assert(C1->getType()->isIntOrIntVectorTy() &&
1596 "Tried to create an arithmetic operation on a non-arithmetic type!");
1598 case Instruction::FDiv:
1599 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1600 assert(C1->getType()->isFPOrFPVectorTy() &&
1601 "Tried to create an arithmetic operation on a non-arithmetic type!");
1603 case Instruction::URem:
1604 case Instruction::SRem:
1605 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1606 assert(C1->getType()->isIntOrIntVectorTy() &&
1607 "Tried to create an arithmetic operation on a non-arithmetic type!");
1609 case Instruction::FRem:
1610 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1611 assert(C1->getType()->isFPOrFPVectorTy() &&
1612 "Tried to create an arithmetic operation on a non-arithmetic type!");
1614 case Instruction::And:
1615 case Instruction::Or:
1616 case Instruction::Xor:
1617 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1618 assert(C1->getType()->isIntOrIntVectorTy() &&
1619 "Tried to create a logical operation on a non-integral type!");
1621 case Instruction::Shl:
1622 case Instruction::LShr:
1623 case Instruction::AShr:
1624 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1625 assert(C1->getType()->isIntOrIntVectorTy() &&
1626 "Tried to create a shift operation on a non-integer type!");
1633 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1634 return FC; // Fold a few common cases.
1636 std::vector<Constant*> argVec(1, C1);
1637 argVec.push_back(C2);
1638 ExprMapKeyType Key(Opcode, argVec, 0, Flags);
1640 LLVMContextImpl *pImpl = C1->getContext().pImpl;
1641 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
1644 Constant *ConstantExpr::getSizeOf(Type* Ty) {
1645 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1646 // Note that a non-inbounds gep is used, as null isn't within any object.
1647 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1648 Constant *GEP = getGetElementPtr(
1649 Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
1650 return getPtrToInt(GEP,
1651 Type::getInt64Ty(Ty->getContext()));
1654 Constant *ConstantExpr::getAlignOf(Type* Ty) {
1655 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
1656 // Note that a non-inbounds gep is used, as null isn't within any object.
1658 StructType::get(Type::getInt1Ty(Ty->getContext()), Ty, NULL);
1659 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo());
1660 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
1661 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1662 Constant *Indices[2] = { Zero, One };
1663 Constant *GEP = getGetElementPtr(NullPtr, Indices);
1664 return getPtrToInt(GEP,
1665 Type::getInt64Ty(Ty->getContext()));
1668 Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) {
1669 return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
1673 Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) {
1674 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1675 // Note that a non-inbounds gep is used, as null isn't within any object.
1676 Constant *GEPIdx[] = {
1677 ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
1680 Constant *GEP = getGetElementPtr(
1681 Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
1682 return getPtrToInt(GEP,
1683 Type::getInt64Ty(Ty->getContext()));
1686 Constant *ConstantExpr::getCompare(unsigned short Predicate,
1687 Constant *C1, Constant *C2) {
1688 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1690 switch (Predicate) {
1691 default: llvm_unreachable("Invalid CmpInst predicate");
1692 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1693 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1694 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1695 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1696 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1697 case CmpInst::FCMP_TRUE:
1698 return getFCmp(Predicate, C1, C2);
1700 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1701 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1702 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1703 case CmpInst::ICMP_SLE:
1704 return getICmp(Predicate, C1, C2);
1708 Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2) {
1709 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1711 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1712 return SC; // Fold common cases
1714 std::vector<Constant*> argVec(3, C);
1717 ExprMapKeyType Key(Instruction::Select, argVec);
1719 LLVMContextImpl *pImpl = C->getContext().pImpl;
1720 return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
1723 Constant *ConstantExpr::getGetElementPtr(Constant *C, ArrayRef<Value *> Idxs,
1725 if (Constant *FC = ConstantFoldGetElementPtr(C, InBounds, Idxs))
1726 return FC; // Fold a few common cases.
1728 // Get the result type of the getelementptr!
1729 Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), Idxs);
1730 assert(Ty && "GEP indices invalid!");
1731 unsigned AS = C->getType()->getPointerAddressSpace();
1732 Type *ReqTy = Ty->getPointerTo(AS);
1734 assert(C->getType()->isPointerTy() &&
1735 "Non-pointer type for constant GetElementPtr expression");
1736 // Look up the constant in the table first to ensure uniqueness
1737 std::vector<Constant*> ArgVec;
1738 ArgVec.reserve(1 + Idxs.size());
1739 ArgVec.push_back(C);
1740 for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
1741 ArgVec.push_back(cast<Constant>(Idxs[i]));
1742 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
1743 InBounds ? GEPOperator::IsInBounds : 0);
1745 LLVMContextImpl *pImpl = C->getContext().pImpl;
1746 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1750 ConstantExpr::getICmp(unsigned short pred, Constant *LHS, Constant *RHS) {
1751 assert(LHS->getType() == RHS->getType());
1752 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1753 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1755 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1756 return FC; // Fold a few common cases...
1758 // Look up the constant in the table first to ensure uniqueness
1759 std::vector<Constant*> ArgVec;
1760 ArgVec.push_back(LHS);
1761 ArgVec.push_back(RHS);
1762 // Get the key type with both the opcode and predicate
1763 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1765 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1766 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1767 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1769 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1770 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
1774 ConstantExpr::getFCmp(unsigned short pred, Constant *LHS, Constant *RHS) {
1775 assert(LHS->getType() == RHS->getType());
1776 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1778 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1779 return FC; // Fold a few common cases...
1781 // Look up the constant in the table first to ensure uniqueness
1782 std::vector<Constant*> ArgVec;
1783 ArgVec.push_back(LHS);
1784 ArgVec.push_back(RHS);
1785 // Get the key type with both the opcode and predicate
1786 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1788 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1789 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1790 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1792 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1793 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
1796 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1797 assert(Val->getType()->isVectorTy() &&
1798 "Tried to create extractelement operation on non-vector type!");
1799 assert(Idx->getType()->isIntegerTy(32) &&
1800 "Extractelement index must be i32 type!");
1802 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1803 return FC; // Fold a few common cases.
1805 // Look up the constant in the table first to ensure uniqueness
1806 std::vector<Constant*> ArgVec(1, Val);
1807 ArgVec.push_back(Idx);
1808 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1810 LLVMContextImpl *pImpl = Val->getContext().pImpl;
1811 Type *ReqTy = Val->getType()->getVectorElementType();
1812 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1815 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1817 assert(Val->getType()->isVectorTy() &&
1818 "Tried to create insertelement operation on non-vector type!");
1819 assert(Elt->getType() == Val->getType()->getVectorElementType() &&
1820 "Insertelement types must match!");
1821 assert(Idx->getType()->isIntegerTy(32) &&
1822 "Insertelement index must be i32 type!");
1824 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1825 return FC; // Fold a few common cases.
1826 // Look up the constant in the table first to ensure uniqueness
1827 std::vector<Constant*> ArgVec(1, Val);
1828 ArgVec.push_back(Elt);
1829 ArgVec.push_back(Idx);
1830 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1832 LLVMContextImpl *pImpl = Val->getContext().pImpl;
1833 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
1836 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1838 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1839 "Invalid shuffle vector constant expr operands!");
1841 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1842 return FC; // Fold a few common cases.
1844 unsigned NElts = Mask->getType()->getVectorNumElements();
1845 Type *EltTy = V1->getType()->getVectorElementType();
1846 Type *ShufTy = VectorType::get(EltTy, NElts);
1848 // Look up the constant in the table first to ensure uniqueness
1849 std::vector<Constant*> ArgVec(1, V1);
1850 ArgVec.push_back(V2);
1851 ArgVec.push_back(Mask);
1852 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1854 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
1855 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
1858 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
1859 ArrayRef<unsigned> Idxs) {
1860 assert(ExtractValueInst::getIndexedType(Agg->getType(),
1861 Idxs) == Val->getType() &&
1862 "insertvalue indices invalid!");
1863 assert(Agg->getType()->isFirstClassType() &&
1864 "Non-first-class type for constant insertvalue expression");
1865 Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs);
1866 assert(FC && "insertvalue constant expr couldn't be folded!");
1870 Constant *ConstantExpr::getExtractValue(Constant *Agg,
1871 ArrayRef<unsigned> Idxs) {
1872 assert(Agg->getType()->isFirstClassType() &&
1873 "Tried to create extractelement operation on non-first-class type!");
1875 Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs);
1877 assert(ReqTy && "extractvalue indices invalid!");
1879 assert(Agg->getType()->isFirstClassType() &&
1880 "Non-first-class type for constant extractvalue expression");
1881 Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs);
1882 assert(FC && "ExtractValue constant expr couldn't be folded!");
1886 Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
1887 assert(C->getType()->isIntOrIntVectorTy() &&
1888 "Cannot NEG a nonintegral value!");
1889 return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
1893 Constant *ConstantExpr::getFNeg(Constant *C) {
1894 assert(C->getType()->isFPOrFPVectorTy() &&
1895 "Cannot FNEG a non-floating-point value!");
1896 return getFSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
1899 Constant *ConstantExpr::getNot(Constant *C) {
1900 assert(C->getType()->isIntOrIntVectorTy() &&
1901 "Cannot NOT a nonintegral value!");
1902 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
1905 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
1906 bool HasNUW, bool HasNSW) {
1907 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1908 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
1909 return get(Instruction::Add, C1, C2, Flags);
1912 Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
1913 return get(Instruction::FAdd, C1, C2);
1916 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
1917 bool HasNUW, bool HasNSW) {
1918 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1919 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
1920 return get(Instruction::Sub, C1, C2, Flags);
1923 Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
1924 return get(Instruction::FSub, C1, C2);
1927 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
1928 bool HasNUW, bool HasNSW) {
1929 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1930 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
1931 return get(Instruction::Mul, C1, C2, Flags);
1934 Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
1935 return get(Instruction::FMul, C1, C2);
1938 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
1939 return get(Instruction::UDiv, C1, C2,
1940 isExact ? PossiblyExactOperator::IsExact : 0);
1943 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
1944 return get(Instruction::SDiv, C1, C2,
1945 isExact ? PossiblyExactOperator::IsExact : 0);
1948 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
1949 return get(Instruction::FDiv, C1, C2);
1952 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
1953 return get(Instruction::URem, C1, C2);
1956 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
1957 return get(Instruction::SRem, C1, C2);
1960 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
1961 return get(Instruction::FRem, C1, C2);
1964 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
1965 return get(Instruction::And, C1, C2);
1968 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
1969 return get(Instruction::Or, C1, C2);
1972 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
1973 return get(Instruction::Xor, C1, C2);
1976 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
1977 bool HasNUW, bool HasNSW) {
1978 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1979 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
1980 return get(Instruction::Shl, C1, C2, Flags);
1983 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
1984 return get(Instruction::LShr, C1, C2,
1985 isExact ? PossiblyExactOperator::IsExact : 0);
1988 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
1989 return get(Instruction::AShr, C1, C2,
1990 isExact ? PossiblyExactOperator::IsExact : 0);
1993 // destroyConstant - Remove the constant from the constant table...
1995 void ConstantExpr::destroyConstant() {
1996 getType()->getContext().pImpl->ExprConstants.remove(this);
1997 destroyConstantImpl();
2000 const char *ConstantExpr::getOpcodeName() const {
2001 return Instruction::getOpcodeName(getOpcode());
2006 GetElementPtrConstantExpr::
2007 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
2009 : ConstantExpr(DestTy, Instruction::GetElementPtr,
2010 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
2011 - (IdxList.size()+1), IdxList.size()+1) {
2013 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
2014 OperandList[i+1] = IdxList[i];
2017 //===----------------------------------------------------------------------===//
2018 // ConstantData* implementations
2020 void ConstantDataArray::anchor() {}
2021 void ConstantDataVector::anchor() {}
2023 /// getElementType - Return the element type of the array/vector.
2024 Type *ConstantDataSequential::getElementType() const {
2025 return getType()->getElementType();
2028 StringRef ConstantDataSequential::getRawDataValues() const {
2029 return StringRef(DataElements, getNumElements()*getElementByteSize());
2032 /// isElementTypeCompatible - Return true if a ConstantDataSequential can be
2033 /// formed with a vector or array of the specified element type.
2034 /// ConstantDataArray only works with normal float and int types that are
2035 /// stored densely in memory, not with things like i42 or x86_f80.
2036 bool ConstantDataSequential::isElementTypeCompatible(const Type *Ty) {
2037 if (Ty->isFloatTy() || Ty->isDoubleTy()) return true;
2038 if (const IntegerType *IT = dyn_cast<IntegerType>(Ty)) {
2039 switch (IT->getBitWidth()) {
2051 /// getNumElements - Return the number of elements in the array or vector.
2052 unsigned ConstantDataSequential::getNumElements() const {
2053 if (ArrayType *AT = dyn_cast<ArrayType>(getType()))
2054 return AT->getNumElements();
2055 return getType()->getVectorNumElements();
2059 /// getElementByteSize - Return the size in bytes of the elements in the data.
2060 uint64_t ConstantDataSequential::getElementByteSize() const {
2061 return getElementType()->getPrimitiveSizeInBits()/8;
2064 /// getElementPointer - Return the start of the specified element.
2065 const char *ConstantDataSequential::getElementPointer(unsigned Elt) const {
2066 assert(Elt < getNumElements() && "Invalid Elt");
2067 return DataElements+Elt*getElementByteSize();
2071 /// isAllZeros - return true if the array is empty or all zeros.
2072 static bool isAllZeros(StringRef Arr) {
2073 for (StringRef::iterator I = Arr.begin(), E = Arr.end(); I != E; ++I)
2079 /// getImpl - This is the underlying implementation of all of the
2080 /// ConstantDataSequential::get methods. They all thunk down to here, providing
2081 /// the correct element type. We take the bytes in as an StringRef because
2082 /// we *want* an underlying "char*" to avoid TBAA type punning violations.
2083 Constant *ConstantDataSequential::getImpl(StringRef Elements, Type *Ty) {
2084 assert(isElementTypeCompatible(Ty->getSequentialElementType()));
2085 // If the elements are all zero or there are no elements, return a CAZ, which
2086 // is more dense and canonical.
2087 if (isAllZeros(Elements))
2088 return ConstantAggregateZero::get(Ty);
2090 // Do a lookup to see if we have already formed one of these.
2091 StringMap<ConstantDataSequential*>::MapEntryTy &Slot =
2092 Ty->getContext().pImpl->CDSConstants.GetOrCreateValue(Elements);
2094 // The bucket can point to a linked list of different CDS's that have the same
2095 // body but different types. For example, 0,0,0,1 could be a 4 element array
2096 // of i8, or a 1-element array of i32. They'll both end up in the same
2097 /// StringMap bucket, linked up by their Next pointers. Walk the list.
2098 ConstantDataSequential **Entry = &Slot.getValue();
2099 for (ConstantDataSequential *Node = *Entry; Node != 0;
2100 Entry = &Node->Next, Node = *Entry)
2101 if (Node->getType() == Ty)
2104 // Okay, we didn't get a hit. Create a node of the right class, link it in,
2106 if (isa<ArrayType>(Ty))
2107 return *Entry = new ConstantDataArray(Ty, Slot.getKeyData());
2109 assert(isa<VectorType>(Ty));
2110 return *Entry = new ConstantDataVector(Ty, Slot.getKeyData());
2113 void ConstantDataSequential::destroyConstant() {
2114 // Remove the constant from the StringMap.
2115 StringMap<ConstantDataSequential*> &CDSConstants =
2116 getType()->getContext().pImpl->CDSConstants;
2118 StringMap<ConstantDataSequential*>::iterator Slot =
2119 CDSConstants.find(getRawDataValues());
2121 assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
2123 ConstantDataSequential **Entry = &Slot->getValue();
2125 // Remove the entry from the hash table.
2126 if ((*Entry)->Next == 0) {
2127 // If there is only one value in the bucket (common case) it must be this
2128 // entry, and removing the entry should remove the bucket completely.
2129 assert((*Entry) == this && "Hash mismatch in ConstantDataSequential");
2130 getContext().pImpl->CDSConstants.erase(Slot);
2132 // Otherwise, there are multiple entries linked off the bucket, unlink the
2133 // node we care about but keep the bucket around.
2134 for (ConstantDataSequential *Node = *Entry; ;
2135 Entry = &Node->Next, Node = *Entry) {
2136 assert(Node && "Didn't find entry in its uniquing hash table!");
2137 // If we found our entry, unlink it from the list and we're done.
2139 *Entry = Node->Next;
2145 // If we were part of a list, make sure that we don't delete the list that is
2146 // still owned by the uniquing map.
2149 // Finally, actually delete it.
2150 destroyConstantImpl();
2153 /// get() constructors - Return a constant with array type with an element
2154 /// count and element type matching the ArrayRef passed in. Note that this
2155 /// can return a ConstantAggregateZero object.
2156 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint8_t> Elts) {
2157 Type *Ty = ArrayType::get(Type::getInt8Ty(Context), Elts.size());
2158 return getImpl(StringRef((char*)Elts.data(), Elts.size()*1), Ty);
2160 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
2161 Type *Ty = ArrayType::get(Type::getInt16Ty(Context), Elts.size());
2162 return getImpl(StringRef((char*)Elts.data(), Elts.size()*2), Ty);
2164 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
2165 Type *Ty = ArrayType::get(Type::getInt32Ty(Context), Elts.size());
2166 return getImpl(StringRef((char*)Elts.data(), Elts.size()*4), Ty);
2168 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
2169 Type *Ty = ArrayType::get(Type::getInt64Ty(Context), Elts.size());
2170 return getImpl(StringRef((char*)Elts.data(), Elts.size()*8), Ty);
2172 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<float> Elts) {
2173 Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
2174 return getImpl(StringRef((char*)Elts.data(), Elts.size()*4), Ty);
2176 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<double> Elts) {
2177 Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
2178 return getImpl(StringRef((char*)Elts.data(), Elts.size()*8), Ty);
2181 /// getString - This method constructs a CDS and initializes it with a text
2182 /// string. The default behavior (AddNull==true) causes a null terminator to
2183 /// be placed at the end of the array (increasing the length of the string by
2184 /// one more than the StringRef would normally indicate. Pass AddNull=false
2185 /// to disable this behavior.
2186 Constant *ConstantDataArray::getString(LLVMContext &Context,
2187 StringRef Str, bool AddNull) {
2189 return get(Context, ArrayRef<uint8_t>((uint8_t*)Str.data(), Str.size()));
2191 SmallVector<uint8_t, 64> ElementVals;
2192 ElementVals.append(Str.begin(), Str.end());
2193 ElementVals.push_back(0);
2194 return get(Context, ElementVals);
2197 /// get() constructors - Return a constant with vector type with an element
2198 /// count and element type matching the ArrayRef passed in. Note that this
2199 /// can return a ConstantAggregateZero object.
2200 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> Elts){
2201 Type *Ty = VectorType::get(Type::getInt8Ty(Context), Elts.size());
2202 return getImpl(StringRef((char*)Elts.data(), Elts.size()*1), Ty);
2204 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
2205 Type *Ty = VectorType::get(Type::getInt16Ty(Context), Elts.size());
2206 return getImpl(StringRef((char*)Elts.data(), Elts.size()*2), Ty);
2208 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
2209 Type *Ty = VectorType::get(Type::getInt32Ty(Context), Elts.size());
2210 return getImpl(StringRef((char*)Elts.data(), Elts.size()*4), Ty);
2212 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
2213 Type *Ty = VectorType::get(Type::getInt64Ty(Context), Elts.size());
2214 return getImpl(StringRef((char*)Elts.data(), Elts.size()*8), Ty);
2216 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> Elts) {
2217 Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
2218 return getImpl(StringRef((char*)Elts.data(), Elts.size()*4), Ty);
2220 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<double> Elts) {
2221 Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
2222 return getImpl(StringRef((char*)Elts.data(), Elts.size()*8), Ty);
2225 Constant *ConstantDataVector::getSplat(unsigned NumElts, Constant *V) {
2226 assert(isElementTypeCompatible(V->getType()) &&
2227 "Element type not compatible with ConstantData");
2228 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2229 if (CI->getType()->isIntegerTy(8)) {
2230 SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
2231 return get(V->getContext(), Elts);
2233 if (CI->getType()->isIntegerTy(16)) {
2234 SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
2235 return get(V->getContext(), Elts);
2237 if (CI->getType()->isIntegerTy(32)) {
2238 SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
2239 return get(V->getContext(), Elts);
2241 assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
2242 SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
2243 return get(V->getContext(), Elts);
2246 ConstantFP *CFP = cast<ConstantFP>(V);
2247 if (CFP->getType()->isFloatTy()) {
2248 SmallVector<float, 16> Elts(NumElts, CFP->getValueAPF().convertToFloat());
2249 return get(V->getContext(), Elts);
2251 assert(CFP->getType()->isDoubleTy() && "Unsupported ConstantData type");
2252 SmallVector<double, 16> Elts(NumElts, CFP->getValueAPF().convertToDouble());
2253 return get(V->getContext(), Elts);
2257 /// getElementAsInteger - If this is a sequential container of integers (of
2258 /// any size), return the specified element in the low bits of a uint64_t.
2259 uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const {
2260 assert(isa<IntegerType>(getElementType()) &&
2261 "Accessor can only be used when element is an integer");
2262 const char *EltPtr = getElementPointer(Elt);
2264 // The data is stored in host byte order, make sure to cast back to the right
2265 // type to load with the right endianness.
2266 switch (getElementType()->getIntegerBitWidth()) {
2267 default: assert(0 && "Invalid bitwidth for CDS");
2268 case 8: return *(uint8_t*)EltPtr;
2269 case 16: return *(uint16_t*)EltPtr;
2270 case 32: return *(uint32_t*)EltPtr;
2271 case 64: return *(uint64_t*)EltPtr;
2275 /// getElementAsAPFloat - If this is a sequential container of floating point
2276 /// type, return the specified element as an APFloat.
2277 APFloat ConstantDataSequential::getElementAsAPFloat(unsigned Elt) const {
2278 const char *EltPtr = getElementPointer(Elt);
2280 switch (getElementType()->getTypeID()) {
2282 assert(0 && "Accessor can only be used when element is float/double!");
2283 case Type::FloatTyID: return APFloat(*(float*)EltPtr);
2284 case Type::DoubleTyID: return APFloat(*(double*)EltPtr);
2288 /// getElementAsFloat - If this is an sequential container of floats, return
2289 /// the specified element as a float.
2290 float ConstantDataSequential::getElementAsFloat(unsigned Elt) const {
2291 assert(getElementType()->isFloatTy() &&
2292 "Accessor can only be used when element is a 'float'");
2293 return *(float*)getElementPointer(Elt);
2296 /// getElementAsDouble - If this is an sequential container of doubles, return
2297 /// the specified element as a float.
2298 double ConstantDataSequential::getElementAsDouble(unsigned Elt) const {
2299 assert(getElementType()->isDoubleTy() &&
2300 "Accessor can only be used when element is a 'float'");
2301 return *(double*)getElementPointer(Elt);
2304 /// getElementAsConstant - Return a Constant for a specified index's element.
2305 /// Note that this has to compute a new constant to return, so it isn't as
2306 /// efficient as getElementAsInteger/Float/Double.
2307 Constant *ConstantDataSequential::getElementAsConstant(unsigned Elt) const {
2308 if (getElementType()->isFloatTy() || getElementType()->isDoubleTy())
2309 return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
2311 return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
2314 /// isString - This method returns true if this is an array of i8.
2315 bool ConstantDataSequential::isString() const {
2316 return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(8);
2319 /// isCString - This method returns true if the array "isString", ends with a
2320 /// nul byte, and does not contains any other nul bytes.
2321 bool ConstantDataSequential::isCString() const {
2325 StringRef Str = getAsString();
2327 // The last value must be nul.
2328 if (Str.back() != 0) return false;
2330 // Other elements must be non-nul.
2331 return Str.drop_back().find(0) == StringRef::npos;
2334 /// getSplatValue - If this is a splat constant, meaning that all of the
2335 /// elements have the same value, return that value. Otherwise return NULL.
2336 Constant *ConstantDataVector::getSplatValue() const {
2337 const char *Base = getRawDataValues().data();
2339 // Compare elements 1+ to the 0'th element.
2340 unsigned EltSize = getElementByteSize();
2341 for (unsigned i = 1, e = getNumElements(); i != e; ++i)
2342 if (memcmp(Base, Base+i*EltSize, EltSize))
2345 // If they're all the same, return the 0th one as a representative.
2346 return getElementAsConstant(0);
2349 //===----------------------------------------------------------------------===//
2350 // replaceUsesOfWithOnConstant implementations
2352 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2353 /// 'From' to be uses of 'To'. This must update the uniquing data structures
2356 /// Note that we intentionally replace all uses of From with To here. Consider
2357 /// a large array that uses 'From' 1000 times. By handling this case all here,
2358 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2359 /// single invocation handles all 1000 uses. Handling them one at a time would
2360 /// work, but would be really slow because it would have to unique each updated
2363 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
2365 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2366 Constant *ToC = cast<Constant>(To);
2368 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
2370 std::pair<LLVMContextImpl::ArrayConstantsTy::MapKey, ConstantArray*> Lookup;
2371 Lookup.first.first = cast<ArrayType>(getType());
2372 Lookup.second = this;
2374 std::vector<Constant*> &Values = Lookup.first.second;
2375 Values.reserve(getNumOperands()); // Build replacement array.
2377 // Fill values with the modified operands of the constant array. Also,
2378 // compute whether this turns into an all-zeros array.
2379 unsigned NumUpdated = 0;
2381 // Keep track of whether all the values in the array are "ToC".
2382 bool AllSame = true;
2383 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2384 Constant *Val = cast<Constant>(O->get());
2389 Values.push_back(Val);
2390 AllSame = Val == ToC;
2393 Constant *Replacement = 0;
2394 if (AllSame && ToC->isNullValue()) {
2395 Replacement = ConstantAggregateZero::get(getType());
2396 } else if (AllSame && isa<UndefValue>(ToC)) {
2397 Replacement = UndefValue::get(getType());
2399 // Check to see if we have this array type already.
2401 LLVMContextImpl::ArrayConstantsTy::MapTy::iterator I =
2402 pImpl->ArrayConstants.InsertOrGetItem(Lookup, Exists);
2405 Replacement = I->second;
2407 // Okay, the new shape doesn't exist in the system yet. Instead of
2408 // creating a new constant array, inserting it, replaceallusesof'ing the
2409 // old with the new, then deleting the old... just update the current one
2411 pImpl->ArrayConstants.MoveConstantToNewSlot(this, I);
2413 // Update to the new value. Optimize for the case when we have a single
2414 // operand that we're changing, but handle bulk updates efficiently.
2415 if (NumUpdated == 1) {
2416 unsigned OperandToUpdate = U - OperandList;
2417 assert(getOperand(OperandToUpdate) == From &&
2418 "ReplaceAllUsesWith broken!");
2419 setOperand(OperandToUpdate, ToC);
2421 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2422 if (getOperand(i) == From)
2429 // Otherwise, I do need to replace this with an existing value.
2430 assert(Replacement != this && "I didn't contain From!");
2432 // Everyone using this now uses the replacement.
2433 replaceAllUsesWith(Replacement);
2435 // Delete the old constant!
2439 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2441 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2442 Constant *ToC = cast<Constant>(To);
2444 unsigned OperandToUpdate = U-OperandList;
2445 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2447 std::pair<LLVMContextImpl::StructConstantsTy::MapKey, ConstantStruct*> Lookup;
2448 Lookup.first.first = cast<StructType>(getType());
2449 Lookup.second = this;
2450 std::vector<Constant*> &Values = Lookup.first.second;
2451 Values.reserve(getNumOperands()); // Build replacement struct.
2454 // Fill values with the modified operands of the constant struct. Also,
2455 // compute whether this turns into an all-zeros struct.
2456 bool isAllZeros = false;
2457 bool isAllUndef = false;
2458 if (ToC->isNullValue()) {
2460 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2461 Constant *Val = cast<Constant>(O->get());
2462 Values.push_back(Val);
2463 if (isAllZeros) isAllZeros = Val->isNullValue();
2465 } else if (isa<UndefValue>(ToC)) {
2467 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2468 Constant *Val = cast<Constant>(O->get());
2469 Values.push_back(Val);
2470 if (isAllUndef) isAllUndef = isa<UndefValue>(Val);
2473 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
2474 Values.push_back(cast<Constant>(O->get()));
2476 Values[OperandToUpdate] = ToC;
2478 LLVMContextImpl *pImpl = getContext().pImpl;
2480 Constant *Replacement = 0;
2482 Replacement = ConstantAggregateZero::get(getType());
2483 } else if (isAllUndef) {
2484 Replacement = UndefValue::get(getType());
2486 // Check to see if we have this struct type already.
2488 LLVMContextImpl::StructConstantsTy::MapTy::iterator I =
2489 pImpl->StructConstants.InsertOrGetItem(Lookup, Exists);
2492 Replacement = I->second;
2494 // Okay, the new shape doesn't exist in the system yet. Instead of
2495 // creating a new constant struct, inserting it, replaceallusesof'ing the
2496 // old with the new, then deleting the old... just update the current one
2498 pImpl->StructConstants.MoveConstantToNewSlot(this, I);
2500 // Update to the new value.
2501 setOperand(OperandToUpdate, ToC);
2506 assert(Replacement != this && "I didn't contain From!");
2508 // Everyone using this now uses the replacement.
2509 replaceAllUsesWith(Replacement);
2511 // Delete the old constant!
2515 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2517 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2519 std::vector<Constant*> Values;
2520 Values.reserve(getNumOperands()); // Build replacement array...
2521 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2522 Constant *Val = getOperand(i);
2523 if (Val == From) Val = cast<Constant>(To);
2524 Values.push_back(Val);
2527 Constant *Replacement = get(Values);
2528 assert(Replacement != this && "I didn't contain From!");
2530 // Everyone using this now uses the replacement.
2531 replaceAllUsesWith(Replacement);
2533 // Delete the old constant!
2537 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2539 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2540 Constant *To = cast<Constant>(ToV);
2542 Constant *Replacement = 0;
2543 if (getOpcode() == Instruction::GetElementPtr) {
2544 SmallVector<Constant*, 8> Indices;
2545 Constant *Pointer = getOperand(0);
2546 Indices.reserve(getNumOperands()-1);
2547 if (Pointer == From) Pointer = To;
2549 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2550 Constant *Val = getOperand(i);
2551 if (Val == From) Val = To;
2552 Indices.push_back(Val);
2554 Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices,
2555 cast<GEPOperator>(this)->isInBounds());
2556 } else if (getOpcode() == Instruction::ExtractValue) {
2557 Constant *Agg = getOperand(0);
2558 if (Agg == From) Agg = To;
2560 ArrayRef<unsigned> Indices = getIndices();
2561 Replacement = ConstantExpr::getExtractValue(Agg, Indices);
2562 } else if (getOpcode() == Instruction::InsertValue) {
2563 Constant *Agg = getOperand(0);
2564 Constant *Val = getOperand(1);
2565 if (Agg == From) Agg = To;
2566 if (Val == From) Val = To;
2568 ArrayRef<unsigned> Indices = getIndices();
2569 Replacement = ConstantExpr::getInsertValue(Agg, Val, Indices);
2570 } else if (isCast()) {
2571 assert(getOperand(0) == From && "Cast only has one use!");
2572 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2573 } else if (getOpcode() == Instruction::Select) {
2574 Constant *C1 = getOperand(0);
2575 Constant *C2 = getOperand(1);
2576 Constant *C3 = getOperand(2);
2577 if (C1 == From) C1 = To;
2578 if (C2 == From) C2 = To;
2579 if (C3 == From) C3 = To;
2580 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2581 } else if (getOpcode() == Instruction::ExtractElement) {
2582 Constant *C1 = getOperand(0);
2583 Constant *C2 = getOperand(1);
2584 if (C1 == From) C1 = To;
2585 if (C2 == From) C2 = To;
2586 Replacement = ConstantExpr::getExtractElement(C1, C2);
2587 } else if (getOpcode() == Instruction::InsertElement) {
2588 Constant *C1 = getOperand(0);
2589 Constant *C2 = getOperand(1);
2590 Constant *C3 = getOperand(1);
2591 if (C1 == From) C1 = To;
2592 if (C2 == From) C2 = To;
2593 if (C3 == From) C3 = To;
2594 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2595 } else if (getOpcode() == Instruction::ShuffleVector) {
2596 Constant *C1 = getOperand(0);
2597 Constant *C2 = getOperand(1);
2598 Constant *C3 = getOperand(2);
2599 if (C1 == From) C1 = To;
2600 if (C2 == From) C2 = To;
2601 if (C3 == From) C3 = To;
2602 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2603 } else if (isCompare()) {
2604 Constant *C1 = getOperand(0);
2605 Constant *C2 = getOperand(1);
2606 if (C1 == From) C1 = To;
2607 if (C2 == From) C2 = To;
2608 if (getOpcode() == Instruction::ICmp)
2609 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2611 assert(getOpcode() == Instruction::FCmp);
2612 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2614 } else if (getNumOperands() == 2) {
2615 Constant *C1 = getOperand(0);
2616 Constant *C2 = getOperand(1);
2617 if (C1 == From) C1 = To;
2618 if (C2 == From) C2 = To;
2619 Replacement = ConstantExpr::get(getOpcode(), C1, C2, SubclassOptionalData);
2621 llvm_unreachable("Unknown ConstantExpr type!");
2624 assert(Replacement != this && "I didn't contain From!");
2626 // Everyone using this now uses the replacement.
2627 replaceAllUsesWith(Replacement);
2629 // Delete the old constant!