1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Constant* classes.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/IR/Constants.h"
15 #include "ConstantFold.h"
16 #include "LLVMContextImpl.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/FoldingSet.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/StringMap.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/GetElementPtrTypeIterator.h"
25 #include "llvm/IR/GlobalValue.h"
26 #include "llvm/IR/Instructions.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/Operator.h"
29 #include "llvm/Support/Compiler.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/ManagedStatic.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
39 //===----------------------------------------------------------------------===//
41 //===----------------------------------------------------------------------===//
43 void Constant::anchor() { }
45 bool Constant::isNegativeZeroValue() const {
46 // Floating point values have an explicit -0.0 value.
47 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
48 return CFP->isZero() && CFP->isNegative();
50 // Equivalent for a vector of -0.0's.
51 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
52 if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
53 if (SplatCFP && SplatCFP->isZero() && SplatCFP->isNegative())
56 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
57 if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
58 if (SplatCFP && SplatCFP->isZero() && SplatCFP->isNegative())
61 // We've already handled true FP case; any other FP vectors can't represent -0.0.
62 if (getType()->isFPOrFPVectorTy())
65 // Otherwise, just use +0.0.
69 // Return true iff this constant is positive zero (floating point), negative
70 // zero (floating point), or a null value.
71 bool Constant::isZeroValue() const {
72 // Floating point values have an explicit -0.0 value.
73 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
76 // Equivalent for a vector of -0.0's.
77 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
78 if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
79 if (SplatCFP && SplatCFP->isZero())
82 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
83 if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
84 if (SplatCFP && SplatCFP->isZero())
87 // Otherwise, just use +0.0.
91 bool Constant::isNullValue() const {
93 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
97 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
98 return CFP->isZero() && !CFP->isNegative();
100 // constant zero is zero for aggregates, cpnull is null for pointers, none for
102 return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this) ||
103 isa<ConstantTokenNone>(this);
106 bool Constant::isAllOnesValue() const {
107 // Check for -1 integers
108 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
109 return CI->isMinusOne();
111 // Check for FP which are bitcasted from -1 integers
112 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
113 return CFP->getValueAPF().bitcastToAPInt().isAllOnesValue();
115 // Check for constant vectors which are splats of -1 values.
116 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
117 if (Constant *Splat = CV->getSplatValue())
118 return Splat->isAllOnesValue();
120 // Check for constant vectors which are splats of -1 values.
121 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
122 if (Constant *Splat = CV->getSplatValue())
123 return Splat->isAllOnesValue();
128 bool Constant::isOneValue() const {
129 // Check for 1 integers
130 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
133 // Check for FP which are bitcasted from 1 integers
134 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
135 return CFP->getValueAPF().bitcastToAPInt() == 1;
137 // Check for constant vectors which are splats of 1 values.
138 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
139 if (Constant *Splat = CV->getSplatValue())
140 return Splat->isOneValue();
142 // Check for constant vectors which are splats of 1 values.
143 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
144 if (Constant *Splat = CV->getSplatValue())
145 return Splat->isOneValue();
150 bool Constant::isMinSignedValue() const {
151 // Check for INT_MIN integers
152 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
153 return CI->isMinValue(/*isSigned=*/true);
155 // Check for FP which are bitcasted from INT_MIN integers
156 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
157 return CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
159 // Check for constant vectors which are splats of INT_MIN values.
160 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
161 if (Constant *Splat = CV->getSplatValue())
162 return Splat->isMinSignedValue();
164 // Check for constant vectors which are splats of INT_MIN values.
165 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
166 if (Constant *Splat = CV->getSplatValue())
167 return Splat->isMinSignedValue();
172 bool Constant::isNotMinSignedValue() const {
173 // Check for INT_MIN integers
174 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
175 return !CI->isMinValue(/*isSigned=*/true);
177 // Check for FP which are bitcasted from INT_MIN integers
178 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
179 return !CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
181 // Check for constant vectors which are splats of INT_MIN values.
182 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
183 if (Constant *Splat = CV->getSplatValue())
184 return Splat->isNotMinSignedValue();
186 // Check for constant vectors which are splats of INT_MIN values.
187 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
188 if (Constant *Splat = CV->getSplatValue())
189 return Splat->isNotMinSignedValue();
191 // It *may* contain INT_MIN, we can't tell.
195 // Constructor to create a '0' constant of arbitrary type...
196 Constant *Constant::getNullValue(Type *Ty) {
197 switch (Ty->getTypeID()) {
198 case Type::IntegerTyID:
199 return ConstantInt::get(Ty, 0);
201 return ConstantFP::get(Ty->getContext(),
202 APFloat::getZero(APFloat::IEEEhalf));
203 case Type::FloatTyID:
204 return ConstantFP::get(Ty->getContext(),
205 APFloat::getZero(APFloat::IEEEsingle));
206 case Type::DoubleTyID:
207 return ConstantFP::get(Ty->getContext(),
208 APFloat::getZero(APFloat::IEEEdouble));
209 case Type::X86_FP80TyID:
210 return ConstantFP::get(Ty->getContext(),
211 APFloat::getZero(APFloat::x87DoubleExtended));
212 case Type::FP128TyID:
213 return ConstantFP::get(Ty->getContext(),
214 APFloat::getZero(APFloat::IEEEquad));
215 case Type::PPC_FP128TyID:
216 return ConstantFP::get(Ty->getContext(),
217 APFloat(APFloat::PPCDoubleDouble,
218 APInt::getNullValue(128)));
219 case Type::PointerTyID:
220 return ConstantPointerNull::get(cast<PointerType>(Ty));
221 case Type::StructTyID:
222 case Type::ArrayTyID:
223 case Type::VectorTyID:
224 return ConstantAggregateZero::get(Ty);
225 case Type::TokenTyID:
226 return ConstantTokenNone::get(Ty->getContext());
228 // Function, Label, or Opaque type?
229 llvm_unreachable("Cannot create a null constant of that type!");
233 Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) {
234 Type *ScalarTy = Ty->getScalarType();
236 // Create the base integer constant.
237 Constant *C = ConstantInt::get(Ty->getContext(), V);
239 // Convert an integer to a pointer, if necessary.
240 if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
241 C = ConstantExpr::getIntToPtr(C, PTy);
243 // Broadcast a scalar to a vector, if necessary.
244 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
245 C = ConstantVector::getSplat(VTy->getNumElements(), C);
250 Constant *Constant::getAllOnesValue(Type *Ty) {
251 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
252 return ConstantInt::get(Ty->getContext(),
253 APInt::getAllOnesValue(ITy->getBitWidth()));
255 if (Ty->isFloatingPointTy()) {
256 APFloat FL = APFloat::getAllOnesValue(Ty->getPrimitiveSizeInBits(),
257 !Ty->isPPC_FP128Ty());
258 return ConstantFP::get(Ty->getContext(), FL);
261 VectorType *VTy = cast<VectorType>(Ty);
262 return ConstantVector::getSplat(VTy->getNumElements(),
263 getAllOnesValue(VTy->getElementType()));
266 /// getAggregateElement - For aggregates (struct/array/vector) return the
267 /// constant that corresponds to the specified element if possible, or null if
268 /// not. This can return null if the element index is a ConstantExpr, or if
269 /// 'this' is a constant expr.
270 Constant *Constant::getAggregateElement(unsigned Elt) const {
271 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(this))
272 return Elt < CS->getNumOperands() ? CS->getOperand(Elt) : nullptr;
274 if (const ConstantArray *CA = dyn_cast<ConstantArray>(this))
275 return Elt < CA->getNumOperands() ? CA->getOperand(Elt) : nullptr;
277 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
278 return Elt < CV->getNumOperands() ? CV->getOperand(Elt) : nullptr;
280 if (const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(this))
281 return Elt < CAZ->getNumElements() ? CAZ->getElementValue(Elt) : nullptr;
283 if (const UndefValue *UV = dyn_cast<UndefValue>(this))
284 return Elt < UV->getNumElements() ? UV->getElementValue(Elt) : nullptr;
286 if (const ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(this))
287 return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt)
292 Constant *Constant::getAggregateElement(Constant *Elt) const {
293 assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
294 if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt))
295 return getAggregateElement(CI->getZExtValue());
299 void Constant::destroyConstant() {
300 /// First call destroyConstantImpl on the subclass. This gives the subclass
301 /// a chance to remove the constant from any maps/pools it's contained in.
302 switch (getValueID()) {
304 llvm_unreachable("Not a constant!");
305 #define HANDLE_CONSTANT(Name) \
306 case Value::Name##Val: \
307 cast<Name>(this)->destroyConstantImpl(); \
309 #include "llvm/IR/Value.def"
312 // When a Constant is destroyed, there may be lingering
313 // references to the constant by other constants in the constant pool. These
314 // constants are implicitly dependent on the module that is being deleted,
315 // but they don't know that. Because we only find out when the CPV is
316 // deleted, we must now notify all of our users (that should only be
317 // Constants) that they are, in fact, invalid now and should be deleted.
319 while (!use_empty()) {
320 Value *V = user_back();
321 #ifndef NDEBUG // Only in -g mode...
322 if (!isa<Constant>(V)) {
323 dbgs() << "While deleting: " << *this
324 << "\n\nUse still stuck around after Def is destroyed: " << *V
328 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
329 cast<Constant>(V)->destroyConstant();
331 // The constant should remove itself from our use list...
332 assert((use_empty() || user_back() != V) && "Constant not removed!");
335 // Value has no outstanding references it is safe to delete it now...
339 static bool canTrapImpl(const Constant *C,
340 SmallPtrSetImpl<const ConstantExpr *> &NonTrappingOps) {
341 assert(C->getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
342 // The only thing that could possibly trap are constant exprs.
343 const ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
347 // ConstantExpr traps if any operands can trap.
348 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
349 if (ConstantExpr *Op = dyn_cast<ConstantExpr>(CE->getOperand(i))) {
350 if (NonTrappingOps.insert(Op).second && canTrapImpl(Op, NonTrappingOps))
355 // Otherwise, only specific operations can trap.
356 switch (CE->getOpcode()) {
359 case Instruction::UDiv:
360 case Instruction::SDiv:
361 case Instruction::FDiv:
362 case Instruction::URem:
363 case Instruction::SRem:
364 case Instruction::FRem:
365 // Div and rem can trap if the RHS is not known to be non-zero.
366 if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
372 /// canTrap - Return true if evaluation of this constant could trap. This is
373 /// true for things like constant expressions that could divide by zero.
374 bool Constant::canTrap() const {
375 SmallPtrSet<const ConstantExpr *, 4> NonTrappingOps;
376 return canTrapImpl(this, NonTrappingOps);
379 /// Check if C contains a GlobalValue for which Predicate is true.
381 ConstHasGlobalValuePredicate(const Constant *C,
382 bool (*Predicate)(const GlobalValue *)) {
383 SmallPtrSet<const Constant *, 8> Visited;
384 SmallVector<const Constant *, 8> WorkList;
385 WorkList.push_back(C);
388 while (!WorkList.empty()) {
389 const Constant *WorkItem = WorkList.pop_back_val();
390 if (const auto *GV = dyn_cast<GlobalValue>(WorkItem))
393 for (const Value *Op : WorkItem->operands()) {
394 const Constant *ConstOp = dyn_cast<Constant>(Op);
397 if (Visited.insert(ConstOp).second)
398 WorkList.push_back(ConstOp);
404 /// Return true if the value can vary between threads.
405 bool Constant::isThreadDependent() const {
406 auto DLLImportPredicate = [](const GlobalValue *GV) {
407 return GV->isThreadLocal();
409 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
412 bool Constant::isDLLImportDependent() const {
413 auto DLLImportPredicate = [](const GlobalValue *GV) {
414 return GV->hasDLLImportStorageClass();
416 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
419 /// Return true if the constant has users other than constant exprs and other
421 bool Constant::isConstantUsed() const {
422 for (const User *U : users()) {
423 const Constant *UC = dyn_cast<Constant>(U);
424 if (!UC || isa<GlobalValue>(UC))
427 if (UC->isConstantUsed())
433 bool Constant::needsRelocation() const {
434 if (isa<GlobalValue>(this))
435 return true; // Global reference.
437 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
438 return BA->getFunction()->needsRelocation();
440 // While raw uses of blockaddress need to be relocated, differences between
441 // two of them don't when they are for labels in the same function. This is a
442 // common idiom when creating a table for the indirect goto extension, so we
443 // handle it efficiently here.
444 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this))
445 if (CE->getOpcode() == Instruction::Sub) {
446 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
447 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
448 if (LHS && RHS && LHS->getOpcode() == Instruction::PtrToInt &&
449 RHS->getOpcode() == Instruction::PtrToInt &&
450 isa<BlockAddress>(LHS->getOperand(0)) &&
451 isa<BlockAddress>(RHS->getOperand(0)) &&
452 cast<BlockAddress>(LHS->getOperand(0))->getFunction() ==
453 cast<BlockAddress>(RHS->getOperand(0))->getFunction())
458 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
459 Result |= cast<Constant>(getOperand(i))->needsRelocation();
464 /// removeDeadUsersOfConstant - If the specified constantexpr is dead, remove
465 /// it. This involves recursively eliminating any dead users of the
467 static bool removeDeadUsersOfConstant(const Constant *C) {
468 if (isa<GlobalValue>(C)) return false; // Cannot remove this
470 while (!C->use_empty()) {
471 const Constant *User = dyn_cast<Constant>(C->user_back());
472 if (!User) return false; // Non-constant usage;
473 if (!removeDeadUsersOfConstant(User))
474 return false; // Constant wasn't dead
477 const_cast<Constant*>(C)->destroyConstant();
482 /// removeDeadConstantUsers - If there are any dead constant users dangling
483 /// off of this constant, remove them. This method is useful for clients
484 /// that want to check to see if a global is unused, but don't want to deal
485 /// with potentially dead constants hanging off of the globals.
486 void Constant::removeDeadConstantUsers() const {
487 Value::const_user_iterator I = user_begin(), E = user_end();
488 Value::const_user_iterator LastNonDeadUser = E;
490 const Constant *User = dyn_cast<Constant>(*I);
497 if (!removeDeadUsersOfConstant(User)) {
498 // If the constant wasn't dead, remember that this was the last live use
499 // and move on to the next constant.
505 // If the constant was dead, then the iterator is invalidated.
506 if (LastNonDeadUser == E) {
518 //===----------------------------------------------------------------------===//
520 //===----------------------------------------------------------------------===//
522 void ConstantInt::anchor() { }
524 ConstantInt::ConstantInt(IntegerType *Ty, const APInt& V)
525 : Constant(Ty, ConstantIntVal, nullptr, 0), Val(V) {
526 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
529 ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
530 LLVMContextImpl *pImpl = Context.pImpl;
531 if (!pImpl->TheTrueVal)
532 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
533 return pImpl->TheTrueVal;
536 ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
537 LLVMContextImpl *pImpl = Context.pImpl;
538 if (!pImpl->TheFalseVal)
539 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
540 return pImpl->TheFalseVal;
543 Constant *ConstantInt::getTrue(Type *Ty) {
544 VectorType *VTy = dyn_cast<VectorType>(Ty);
546 assert(Ty->isIntegerTy(1) && "True must be i1 or vector of i1.");
547 return ConstantInt::getTrue(Ty->getContext());
549 assert(VTy->getElementType()->isIntegerTy(1) &&
550 "True must be vector of i1 or i1.");
551 return ConstantVector::getSplat(VTy->getNumElements(),
552 ConstantInt::getTrue(Ty->getContext()));
555 Constant *ConstantInt::getFalse(Type *Ty) {
556 VectorType *VTy = dyn_cast<VectorType>(Ty);
558 assert(Ty->isIntegerTy(1) && "False must be i1 or vector of i1.");
559 return ConstantInt::getFalse(Ty->getContext());
561 assert(VTy->getElementType()->isIntegerTy(1) &&
562 "False must be vector of i1 or i1.");
563 return ConstantVector::getSplat(VTy->getNumElements(),
564 ConstantInt::getFalse(Ty->getContext()));
567 // Get a ConstantInt from an APInt.
568 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
569 // get an existing value or the insertion position
570 LLVMContextImpl *pImpl = Context.pImpl;
571 ConstantInt *&Slot = pImpl->IntConstants[V];
573 // Get the corresponding integer type for the bit width of the value.
574 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
575 Slot = new ConstantInt(ITy, V);
577 assert(Slot->getType() == IntegerType::get(Context, V.getBitWidth()));
581 Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
582 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
584 // For vectors, broadcast the value.
585 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
586 return ConstantVector::getSplat(VTy->getNumElements(), C);
591 ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V,
593 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
596 ConstantInt *ConstantInt::getSigned(IntegerType *Ty, int64_t V) {
597 return get(Ty, V, true);
600 Constant *ConstantInt::getSigned(Type *Ty, int64_t V) {
601 return get(Ty, V, true);
604 Constant *ConstantInt::get(Type *Ty, const APInt& V) {
605 ConstantInt *C = get(Ty->getContext(), V);
606 assert(C->getType() == Ty->getScalarType() &&
607 "ConstantInt type doesn't match the type implied by its value!");
609 // For vectors, broadcast the value.
610 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
611 return ConstantVector::getSplat(VTy->getNumElements(), C);
616 ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str,
618 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
621 /// Remove the constant from the constant table.
622 void ConstantInt::destroyConstantImpl() {
623 llvm_unreachable("You can't ConstantInt->destroyConstantImpl()!");
626 //===----------------------------------------------------------------------===//
628 //===----------------------------------------------------------------------===//
630 static const fltSemantics *TypeToFloatSemantics(Type *Ty) {
632 return &APFloat::IEEEhalf;
634 return &APFloat::IEEEsingle;
635 if (Ty->isDoubleTy())
636 return &APFloat::IEEEdouble;
637 if (Ty->isX86_FP80Ty())
638 return &APFloat::x87DoubleExtended;
639 else if (Ty->isFP128Ty())
640 return &APFloat::IEEEquad;
642 assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
643 return &APFloat::PPCDoubleDouble;
646 void ConstantFP::anchor() { }
648 /// get() - This returns a constant fp for the specified value in the
649 /// specified type. This should only be used for simple constant values like
650 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
651 Constant *ConstantFP::get(Type *Ty, double V) {
652 LLVMContext &Context = Ty->getContext();
656 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
657 APFloat::rmNearestTiesToEven, &ignored);
658 Constant *C = get(Context, FV);
660 // For vectors, broadcast the value.
661 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
662 return ConstantVector::getSplat(VTy->getNumElements(), C);
668 Constant *ConstantFP::get(Type *Ty, StringRef Str) {
669 LLVMContext &Context = Ty->getContext();
671 APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
672 Constant *C = get(Context, FV);
674 // For vectors, broadcast the value.
675 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
676 return ConstantVector::getSplat(VTy->getNumElements(), C);
681 Constant *ConstantFP::getNaN(Type *Ty, bool Negative, unsigned Type) {
682 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
683 APFloat NaN = APFloat::getNaN(Semantics, Negative, Type);
684 Constant *C = get(Ty->getContext(), NaN);
686 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
687 return ConstantVector::getSplat(VTy->getNumElements(), C);
692 Constant *ConstantFP::getNegativeZero(Type *Ty) {
693 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
694 APFloat NegZero = APFloat::getZero(Semantics, /*Negative=*/true);
695 Constant *C = get(Ty->getContext(), NegZero);
697 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
698 return ConstantVector::getSplat(VTy->getNumElements(), C);
704 Constant *ConstantFP::getZeroValueForNegation(Type *Ty) {
705 if (Ty->isFPOrFPVectorTy())
706 return getNegativeZero(Ty);
708 return Constant::getNullValue(Ty);
712 // ConstantFP accessors.
713 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
714 LLVMContextImpl* pImpl = Context.pImpl;
716 ConstantFP *&Slot = pImpl->FPConstants[V];
720 if (&V.getSemantics() == &APFloat::IEEEhalf)
721 Ty = Type::getHalfTy(Context);
722 else if (&V.getSemantics() == &APFloat::IEEEsingle)
723 Ty = Type::getFloatTy(Context);
724 else if (&V.getSemantics() == &APFloat::IEEEdouble)
725 Ty = Type::getDoubleTy(Context);
726 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
727 Ty = Type::getX86_FP80Ty(Context);
728 else if (&V.getSemantics() == &APFloat::IEEEquad)
729 Ty = Type::getFP128Ty(Context);
731 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
732 "Unknown FP format");
733 Ty = Type::getPPC_FP128Ty(Context);
735 Slot = new ConstantFP(Ty, V);
741 Constant *ConstantFP::getInfinity(Type *Ty, bool Negative) {
742 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
743 Constant *C = get(Ty->getContext(), APFloat::getInf(Semantics, Negative));
745 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
746 return ConstantVector::getSplat(VTy->getNumElements(), C);
751 ConstantFP::ConstantFP(Type *Ty, const APFloat& V)
752 : Constant(Ty, ConstantFPVal, nullptr, 0), Val(V) {
753 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
757 bool ConstantFP::isExactlyValue(const APFloat &V) const {
758 return Val.bitwiseIsEqual(V);
761 /// Remove the constant from the constant table.
762 void ConstantFP::destroyConstantImpl() {
763 llvm_unreachable("You can't ConstantInt->destroyConstantImpl()!");
766 //===----------------------------------------------------------------------===//
767 // ConstantAggregateZero Implementation
768 //===----------------------------------------------------------------------===//
770 /// getSequentialElement - If this CAZ has array or vector type, return a zero
771 /// with the right element type.
772 Constant *ConstantAggregateZero::getSequentialElement() const {
773 return Constant::getNullValue(getType()->getSequentialElementType());
776 /// getStructElement - If this CAZ has struct type, return a zero with the
777 /// right element type for the specified element.
778 Constant *ConstantAggregateZero::getStructElement(unsigned Elt) const {
779 return Constant::getNullValue(getType()->getStructElementType(Elt));
782 /// getElementValue - Return a zero of the right value for the specified GEP
783 /// index if we can, otherwise return null (e.g. if C is a ConstantExpr).
784 Constant *ConstantAggregateZero::getElementValue(Constant *C) const {
785 if (isa<SequentialType>(getType()))
786 return getSequentialElement();
787 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
790 /// getElementValue - Return a zero of the right value for the specified GEP
792 Constant *ConstantAggregateZero::getElementValue(unsigned Idx) const {
793 if (isa<SequentialType>(getType()))
794 return getSequentialElement();
795 return getStructElement(Idx);
798 unsigned ConstantAggregateZero::getNumElements() const {
799 Type *Ty = getType();
800 if (auto *AT = dyn_cast<ArrayType>(Ty))
801 return AT->getNumElements();
802 if (auto *VT = dyn_cast<VectorType>(Ty))
803 return VT->getNumElements();
804 return Ty->getStructNumElements();
807 //===----------------------------------------------------------------------===//
808 // UndefValue Implementation
809 //===----------------------------------------------------------------------===//
811 /// getSequentialElement - If this undef has array or vector type, return an
812 /// undef with the right element type.
813 UndefValue *UndefValue::getSequentialElement() const {
814 return UndefValue::get(getType()->getSequentialElementType());
817 /// getStructElement - If this undef has struct type, return a zero with the
818 /// right element type for the specified element.
819 UndefValue *UndefValue::getStructElement(unsigned Elt) const {
820 return UndefValue::get(getType()->getStructElementType(Elt));
823 /// getElementValue - Return an undef of the right value for the specified GEP
824 /// index if we can, otherwise return null (e.g. if C is a ConstantExpr).
825 UndefValue *UndefValue::getElementValue(Constant *C) const {
826 if (isa<SequentialType>(getType()))
827 return getSequentialElement();
828 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
831 /// getElementValue - Return an undef of the right value for the specified GEP
833 UndefValue *UndefValue::getElementValue(unsigned Idx) const {
834 if (isa<SequentialType>(getType()))
835 return getSequentialElement();
836 return getStructElement(Idx);
839 unsigned UndefValue::getNumElements() const {
840 Type *Ty = getType();
841 if (auto *AT = dyn_cast<ArrayType>(Ty))
842 return AT->getNumElements();
843 if (auto *VT = dyn_cast<VectorType>(Ty))
844 return VT->getNumElements();
845 return Ty->getStructNumElements();
848 //===----------------------------------------------------------------------===//
849 // ConstantXXX Classes
850 //===----------------------------------------------------------------------===//
852 template <typename ItTy, typename EltTy>
853 static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
854 for (; Start != End; ++Start)
860 template <typename SequentialTy, typename ElementTy>
861 static Constant *getIntSequenceIfElementsMatch(ArrayRef<Constant *> V) {
862 assert(!V.empty() && "Cannot get empty int sequence.");
864 SmallVector<ElementTy, 16> Elts;
865 for (Constant *C : V)
866 if (auto *CI = dyn_cast<ConstantInt>(C))
867 Elts.push_back(CI->getZExtValue());
870 return SequentialTy::get(V[0]->getContext(), Elts);
873 template <typename SequentialTy, typename ElementTy>
874 static Constant *getFPSequenceIfElementsMatch(ArrayRef<Constant *> V) {
875 assert(!V.empty() && "Cannot get empty FP sequence.");
877 SmallVector<ElementTy, 16> Elts;
878 for (Constant *C : V)
879 if (auto *CFP = dyn_cast<ConstantFP>(C))
880 Elts.push_back(CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
883 return SequentialTy::getFP(V[0]->getContext(), Elts);
886 template <typename SequenceTy>
887 static Constant *getSequenceIfElementsMatch(Constant *C,
888 ArrayRef<Constant *> V) {
889 // We speculatively build the elements here even if it turns out that there is
890 // a constantexpr or something else weird, since it is so uncommon for that to
892 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
893 if (CI->getType()->isIntegerTy(8))
894 return getIntSequenceIfElementsMatch<SequenceTy, uint8_t>(V);
895 else if (CI->getType()->isIntegerTy(16))
896 return getIntSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
897 else if (CI->getType()->isIntegerTy(32))
898 return getIntSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
899 else if (CI->getType()->isIntegerTy(64))
900 return getIntSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
901 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
902 if (CFP->getType()->isHalfTy())
903 return getFPSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
904 else if (CFP->getType()->isFloatTy())
905 return getFPSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
906 else if (CFP->getType()->isDoubleTy())
907 return getFPSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
913 ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
914 : Constant(T, ConstantArrayVal,
915 OperandTraits<ConstantArray>::op_end(this) - V.size(),
917 assert(V.size() == T->getNumElements() &&
918 "Invalid initializer vector for constant array");
919 for (unsigned i = 0, e = V.size(); i != e; ++i)
920 assert(V[i]->getType() == T->getElementType() &&
921 "Initializer for array element doesn't match array element type!");
922 std::copy(V.begin(), V.end(), op_begin());
925 Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
926 if (Constant *C = getImpl(Ty, V))
928 return Ty->getContext().pImpl->ArrayConstants.getOrCreate(Ty, V);
931 Constant *ConstantArray::getImpl(ArrayType *Ty, ArrayRef<Constant*> V) {
932 // Empty arrays are canonicalized to ConstantAggregateZero.
934 return ConstantAggregateZero::get(Ty);
936 for (unsigned i = 0, e = V.size(); i != e; ++i) {
937 assert(V[i]->getType() == Ty->getElementType() &&
938 "Wrong type in array element initializer");
941 // If this is an all-zero array, return a ConstantAggregateZero object. If
942 // all undef, return an UndefValue, if "all simple", then return a
943 // ConstantDataArray.
945 if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
946 return UndefValue::get(Ty);
948 if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
949 return ConstantAggregateZero::get(Ty);
951 // Check to see if all of the elements are ConstantFP or ConstantInt and if
952 // the element type is compatible with ConstantDataVector. If so, use it.
953 if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
954 return getSequenceIfElementsMatch<ConstantDataArray>(C, V);
956 // Otherwise, we really do want to create a ConstantArray.
960 /// getTypeForElements - Return an anonymous struct type to use for a constant
961 /// with the specified set of elements. The list must not be empty.
962 StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
963 ArrayRef<Constant*> V,
965 unsigned VecSize = V.size();
966 SmallVector<Type*, 16> EltTypes(VecSize);
967 for (unsigned i = 0; i != VecSize; ++i)
968 EltTypes[i] = V[i]->getType();
970 return StructType::get(Context, EltTypes, Packed);
974 StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
977 "ConstantStruct::getTypeForElements cannot be called on empty list");
978 return getTypeForElements(V[0]->getContext(), V, Packed);
982 ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
983 : Constant(T, ConstantStructVal,
984 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
986 assert(V.size() == T->getNumElements() &&
987 "Invalid initializer vector for constant structure");
988 for (unsigned i = 0, e = V.size(); i != e; ++i)
989 assert((T->isOpaque() || V[i]->getType() == T->getElementType(i)) &&
990 "Initializer for struct element doesn't match struct element type!");
991 std::copy(V.begin(), V.end(), op_begin());
994 // ConstantStruct accessors.
995 Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
996 assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
997 "Incorrect # elements specified to ConstantStruct::get");
999 // Create a ConstantAggregateZero value if all elements are zeros.
1001 bool isUndef = false;
1004 isUndef = isa<UndefValue>(V[0]);
1005 isZero = V[0]->isNullValue();
1006 if (isUndef || isZero) {
1007 for (unsigned i = 0, e = V.size(); i != e; ++i) {
1008 if (!V[i]->isNullValue())
1010 if (!isa<UndefValue>(V[i]))
1016 return ConstantAggregateZero::get(ST);
1018 return UndefValue::get(ST);
1020 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
1023 Constant *ConstantStruct::get(StructType *T, ...) {
1025 SmallVector<Constant*, 8> Values;
1027 while (Constant *Val = va_arg(ap, llvm::Constant*))
1028 Values.push_back(Val);
1030 return get(T, Values);
1033 ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
1034 : Constant(T, ConstantVectorVal,
1035 OperandTraits<ConstantVector>::op_end(this) - V.size(),
1037 for (size_t i = 0, e = V.size(); i != e; i++)
1038 assert(V[i]->getType() == T->getElementType() &&
1039 "Initializer for vector element doesn't match vector element type!");
1040 std::copy(V.begin(), V.end(), op_begin());
1043 // ConstantVector accessors.
1044 Constant *ConstantVector::get(ArrayRef<Constant*> V) {
1045 if (Constant *C = getImpl(V))
1047 VectorType *Ty = VectorType::get(V.front()->getType(), V.size());
1048 return Ty->getContext().pImpl->VectorConstants.getOrCreate(Ty, V);
1051 Constant *ConstantVector::getImpl(ArrayRef<Constant*> V) {
1052 assert(!V.empty() && "Vectors can't be empty");
1053 VectorType *T = VectorType::get(V.front()->getType(), V.size());
1055 // If this is an all-undef or all-zero vector, return a
1056 // ConstantAggregateZero or UndefValue.
1058 bool isZero = C->isNullValue();
1059 bool isUndef = isa<UndefValue>(C);
1061 if (isZero || isUndef) {
1062 for (unsigned i = 1, e = V.size(); i != e; ++i)
1064 isZero = isUndef = false;
1070 return ConstantAggregateZero::get(T);
1072 return UndefValue::get(T);
1074 // Check to see if all of the elements are ConstantFP or ConstantInt and if
1075 // the element type is compatible with ConstantDataVector. If so, use it.
1076 if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
1077 return getSequenceIfElementsMatch<ConstantDataVector>(C, V);
1079 // Otherwise, the element type isn't compatible with ConstantDataVector, or
1080 // the operand list constants a ConstantExpr or something else strange.
1084 Constant *ConstantVector::getSplat(unsigned NumElts, Constant *V) {
1085 // If this splat is compatible with ConstantDataVector, use it instead of
1087 if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&
1088 ConstantDataSequential::isElementTypeCompatible(V->getType()))
1089 return ConstantDataVector::getSplat(NumElts, V);
1091 SmallVector<Constant*, 32> Elts(NumElts, V);
1095 ConstantTokenNone *ConstantTokenNone::get(LLVMContext &Context) {
1096 LLVMContextImpl *pImpl = Context.pImpl;
1097 if (!pImpl->TheNoneToken)
1098 pImpl->TheNoneToken.reset(new ConstantTokenNone(Context));
1099 return pImpl->TheNoneToken.get();
1102 /// Remove the constant from the constant table.
1103 void ConstantTokenNone::destroyConstantImpl() {
1104 llvm_unreachable("You can't ConstantTokenNone->destroyConstantImpl()!");
1107 // Utility function for determining if a ConstantExpr is a CastOp or not. This
1108 // can't be inline because we don't want to #include Instruction.h into
1110 bool ConstantExpr::isCast() const {
1111 return Instruction::isCast(getOpcode());
1114 bool ConstantExpr::isCompare() const {
1115 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
1118 bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
1119 if (getOpcode() != Instruction::GetElementPtr) return false;
1121 gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
1122 User::const_op_iterator OI = std::next(this->op_begin());
1124 // Skip the first index, as it has no static limit.
1128 // The remaining indices must be compile-time known integers within the
1129 // bounds of the corresponding notional static array types.
1130 for (; GEPI != E; ++GEPI, ++OI) {
1131 ConstantInt *CI = dyn_cast<ConstantInt>(*OI);
1132 if (!CI) return false;
1133 if (ArrayType *ATy = dyn_cast<ArrayType>(*GEPI))
1134 if (CI->getValue().getActiveBits() > 64 ||
1135 CI->getZExtValue() >= ATy->getNumElements())
1139 // All the indices checked out.
1143 bool ConstantExpr::hasIndices() const {
1144 return getOpcode() == Instruction::ExtractValue ||
1145 getOpcode() == Instruction::InsertValue;
1148 ArrayRef<unsigned> ConstantExpr::getIndices() const {
1149 if (const ExtractValueConstantExpr *EVCE =
1150 dyn_cast<ExtractValueConstantExpr>(this))
1151 return EVCE->Indices;
1153 return cast<InsertValueConstantExpr>(this)->Indices;
1156 unsigned ConstantExpr::getPredicate() const {
1157 return cast<CompareConstantExpr>(this)->predicate;
1160 /// getWithOperandReplaced - Return a constant expression identical to this
1161 /// one, but with the specified operand set to the specified value.
1163 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
1164 assert(Op->getType() == getOperand(OpNo)->getType() &&
1165 "Replacing operand with value of different type!");
1166 if (getOperand(OpNo) == Op)
1167 return const_cast<ConstantExpr*>(this);
1169 SmallVector<Constant*, 8> NewOps;
1170 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1171 NewOps.push_back(i == OpNo ? Op : getOperand(i));
1173 return getWithOperands(NewOps);
1176 /// getWithOperands - This returns the current constant expression with the
1177 /// operands replaced with the specified values. The specified array must
1178 /// have the same number of operands as our current one.
1179 Constant *ConstantExpr::getWithOperands(ArrayRef<Constant *> Ops, Type *Ty,
1180 bool OnlyIfReduced, Type *SrcTy) const {
1181 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
1183 // If no operands changed return self.
1184 if (Ty == getType() && std::equal(Ops.begin(), Ops.end(), op_begin()))
1185 return const_cast<ConstantExpr*>(this);
1187 Type *OnlyIfReducedTy = OnlyIfReduced ? Ty : nullptr;
1188 switch (getOpcode()) {
1189 case Instruction::Trunc:
1190 case Instruction::ZExt:
1191 case Instruction::SExt:
1192 case Instruction::FPTrunc:
1193 case Instruction::FPExt:
1194 case Instruction::UIToFP:
1195 case Instruction::SIToFP:
1196 case Instruction::FPToUI:
1197 case Instruction::FPToSI:
1198 case Instruction::PtrToInt:
1199 case Instruction::IntToPtr:
1200 case Instruction::BitCast:
1201 case Instruction::AddrSpaceCast:
1202 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty, OnlyIfReduced);
1203 case Instruction::Select:
1204 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2], OnlyIfReducedTy);
1205 case Instruction::InsertElement:
1206 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2],
1208 case Instruction::ExtractElement:
1209 return ConstantExpr::getExtractElement(Ops[0], Ops[1], OnlyIfReducedTy);
1210 case Instruction::InsertValue:
1211 return ConstantExpr::getInsertValue(Ops[0], Ops[1], getIndices(),
1213 case Instruction::ExtractValue:
1214 return ConstantExpr::getExtractValue(Ops[0], getIndices(), OnlyIfReducedTy);
1215 case Instruction::ShuffleVector:
1216 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2],
1218 case Instruction::GetElementPtr: {
1219 auto *GEPO = cast<GEPOperator>(this);
1220 assert(SrcTy || (Ops[0]->getType() == getOperand(0)->getType()));
1221 return ConstantExpr::getGetElementPtr(
1222 SrcTy ? SrcTy : GEPO->getSourceElementType(), Ops[0], Ops.slice(1),
1223 GEPO->isInBounds(), OnlyIfReducedTy);
1225 case Instruction::ICmp:
1226 case Instruction::FCmp:
1227 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1],
1230 assert(getNumOperands() == 2 && "Must be binary operator?");
1231 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData,
1237 //===----------------------------------------------------------------------===//
1238 // isValueValidForType implementations
1240 bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
1241 unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
1242 if (Ty->isIntegerTy(1))
1243 return Val == 0 || Val == 1;
1245 return true; // always true, has to fit in largest type
1246 uint64_t Max = (1ll << NumBits) - 1;
1250 bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
1251 unsigned NumBits = Ty->getIntegerBitWidth();
1252 if (Ty->isIntegerTy(1))
1253 return Val == 0 || Val == 1 || Val == -1;
1255 return true; // always true, has to fit in largest type
1256 int64_t Min = -(1ll << (NumBits-1));
1257 int64_t Max = (1ll << (NumBits-1)) - 1;
1258 return (Val >= Min && Val <= Max);
1261 bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {
1262 // convert modifies in place, so make a copy.
1263 APFloat Val2 = APFloat(Val);
1265 switch (Ty->getTypeID()) {
1267 return false; // These can't be represented as floating point!
1269 // FIXME rounding mode needs to be more flexible
1270 case Type::HalfTyID: {
1271 if (&Val2.getSemantics() == &APFloat::IEEEhalf)
1273 Val2.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &losesInfo);
1276 case Type::FloatTyID: {
1277 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
1279 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
1282 case Type::DoubleTyID: {
1283 if (&Val2.getSemantics() == &APFloat::IEEEhalf ||
1284 &Val2.getSemantics() == &APFloat::IEEEsingle ||
1285 &Val2.getSemantics() == &APFloat::IEEEdouble)
1287 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
1290 case Type::X86_FP80TyID:
1291 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1292 &Val2.getSemantics() == &APFloat::IEEEsingle ||
1293 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1294 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
1295 case Type::FP128TyID:
1296 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1297 &Val2.getSemantics() == &APFloat::IEEEsingle ||
1298 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1299 &Val2.getSemantics() == &APFloat::IEEEquad;
1300 case Type::PPC_FP128TyID:
1301 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1302 &Val2.getSemantics() == &APFloat::IEEEsingle ||
1303 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1304 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
1309 //===----------------------------------------------------------------------===//
1310 // Factory Function Implementation
1312 ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
1313 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
1314 "Cannot create an aggregate zero of non-aggregate type!");
1316 ConstantAggregateZero *&Entry = Ty->getContext().pImpl->CAZConstants[Ty];
1318 Entry = new ConstantAggregateZero(Ty);
1323 /// destroyConstant - Remove the constant from the constant table.
1325 void ConstantAggregateZero::destroyConstantImpl() {
1326 getContext().pImpl->CAZConstants.erase(getType());
1329 /// destroyConstant - Remove the constant from the constant table...
1331 void ConstantArray::destroyConstantImpl() {
1332 getType()->getContext().pImpl->ArrayConstants.remove(this);
1336 //---- ConstantStruct::get() implementation...
1339 // destroyConstant - Remove the constant from the constant table...
1341 void ConstantStruct::destroyConstantImpl() {
1342 getType()->getContext().pImpl->StructConstants.remove(this);
1345 // destroyConstant - Remove the constant from the constant table...
1347 void ConstantVector::destroyConstantImpl() {
1348 getType()->getContext().pImpl->VectorConstants.remove(this);
1351 /// getSplatValue - If this is a splat vector constant, meaning that all of
1352 /// the elements have the same value, return that value. Otherwise return 0.
1353 Constant *Constant::getSplatValue() const {
1354 assert(this->getType()->isVectorTy() && "Only valid for vectors!");
1355 if (isa<ConstantAggregateZero>(this))
1356 return getNullValue(this->getType()->getVectorElementType());
1357 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
1358 return CV->getSplatValue();
1359 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
1360 return CV->getSplatValue();
1364 /// getSplatValue - If this is a splat constant, where all of the
1365 /// elements have the same value, return that value. Otherwise return null.
1366 Constant *ConstantVector::getSplatValue() const {
1367 // Check out first element.
1368 Constant *Elt = getOperand(0);
1369 // Then make sure all remaining elements point to the same value.
1370 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1371 if (getOperand(I) != Elt)
1376 /// If C is a constant integer then return its value, otherwise C must be a
1377 /// vector of constant integers, all equal, and the common value is returned.
1378 const APInt &Constant::getUniqueInteger() const {
1379 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
1380 return CI->getValue();
1381 assert(this->getSplatValue() && "Doesn't contain a unique integer!");
1382 const Constant *C = this->getAggregateElement(0U);
1383 assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
1384 return cast<ConstantInt>(C)->getValue();
1387 //---- ConstantPointerNull::get() implementation.
1390 ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
1391 ConstantPointerNull *&Entry = Ty->getContext().pImpl->CPNConstants[Ty];
1393 Entry = new ConstantPointerNull(Ty);
1398 // destroyConstant - Remove the constant from the constant table...
1400 void ConstantPointerNull::destroyConstantImpl() {
1401 getContext().pImpl->CPNConstants.erase(getType());
1405 //---- UndefValue::get() implementation.
1408 UndefValue *UndefValue::get(Type *Ty) {
1409 UndefValue *&Entry = Ty->getContext().pImpl->UVConstants[Ty];
1411 Entry = new UndefValue(Ty);
1416 // destroyConstant - Remove the constant from the constant table.
1418 void UndefValue::destroyConstantImpl() {
1419 // Free the constant and any dangling references to it.
1420 getContext().pImpl->UVConstants.erase(getType());
1423 //---- BlockAddress::get() implementation.
1426 BlockAddress *BlockAddress::get(BasicBlock *BB) {
1427 assert(BB->getParent() && "Block must have a parent");
1428 return get(BB->getParent(), BB);
1431 BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1433 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
1435 BA = new BlockAddress(F, BB);
1437 assert(BA->getFunction() == F && "Basic block moved between functions");
1441 BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1442 : Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1446 BB->AdjustBlockAddressRefCount(1);
1449 BlockAddress *BlockAddress::lookup(const BasicBlock *BB) {
1450 if (!BB->hasAddressTaken())
1453 const Function *F = BB->getParent();
1454 assert(F && "Block must have a parent");
1456 F->getContext().pImpl->BlockAddresses.lookup(std::make_pair(F, BB));
1457 assert(BA && "Refcount and block address map disagree!");
1461 // destroyConstant - Remove the constant from the constant table.
1463 void BlockAddress::destroyConstantImpl() {
1464 getFunction()->getType()->getContext().pImpl
1465 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
1466 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1469 Value *BlockAddress::handleOperandChangeImpl(Value *From, Value *To, Use *U) {
1470 // This could be replacing either the Basic Block or the Function. In either
1471 // case, we have to remove the map entry.
1472 Function *NewF = getFunction();
1473 BasicBlock *NewBB = getBasicBlock();
1476 NewF = cast<Function>(To->stripPointerCasts());
1478 NewBB = cast<BasicBlock>(To);
1480 // See if the 'new' entry already exists, if not, just update this in place
1481 // and return early.
1482 BlockAddress *&NewBA =
1483 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
1487 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1489 // Remove the old entry, this can't cause the map to rehash (just a
1490 // tombstone will get added).
1491 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1494 setOperand(0, NewF);
1495 setOperand(1, NewBB);
1496 getBasicBlock()->AdjustBlockAddressRefCount(1);
1498 // If we just want to keep the existing value, then return null.
1499 // Callers know that this means we shouldn't delete this value.
1503 //---- ConstantExpr::get() implementations.
1506 /// This is a utility function to handle folding of casts and lookup of the
1507 /// cast in the ExprConstants map. It is used by the various get* methods below.
1508 static Constant *getFoldedCast(Instruction::CastOps opc, Constant *C, Type *Ty,
1509 bool OnlyIfReduced = false) {
1510 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1511 // Fold a few common cases
1512 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1518 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1520 // Look up the constant in the table first to ensure uniqueness.
1521 ConstantExprKeyType Key(opc, C);
1523 return pImpl->ExprConstants.getOrCreate(Ty, Key);
1526 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty,
1527 bool OnlyIfReduced) {
1528 Instruction::CastOps opc = Instruction::CastOps(oc);
1529 assert(Instruction::isCast(opc) && "opcode out of range");
1530 assert(C && Ty && "Null arguments to getCast");
1531 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
1535 llvm_unreachable("Invalid cast opcode");
1536 case Instruction::Trunc:
1537 return getTrunc(C, Ty, OnlyIfReduced);
1538 case Instruction::ZExt:
1539 return getZExt(C, Ty, OnlyIfReduced);
1540 case Instruction::SExt:
1541 return getSExt(C, Ty, OnlyIfReduced);
1542 case Instruction::FPTrunc:
1543 return getFPTrunc(C, Ty, OnlyIfReduced);
1544 case Instruction::FPExt:
1545 return getFPExtend(C, Ty, OnlyIfReduced);
1546 case Instruction::UIToFP:
1547 return getUIToFP(C, Ty, OnlyIfReduced);
1548 case Instruction::SIToFP:
1549 return getSIToFP(C, Ty, OnlyIfReduced);
1550 case Instruction::FPToUI:
1551 return getFPToUI(C, Ty, OnlyIfReduced);
1552 case Instruction::FPToSI:
1553 return getFPToSI(C, Ty, OnlyIfReduced);
1554 case Instruction::PtrToInt:
1555 return getPtrToInt(C, Ty, OnlyIfReduced);
1556 case Instruction::IntToPtr:
1557 return getIntToPtr(C, Ty, OnlyIfReduced);
1558 case Instruction::BitCast:
1559 return getBitCast(C, Ty, OnlyIfReduced);
1560 case Instruction::AddrSpaceCast:
1561 return getAddrSpaceCast(C, Ty, OnlyIfReduced);
1565 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) {
1566 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1567 return getBitCast(C, Ty);
1568 return getZExt(C, Ty);
1571 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) {
1572 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1573 return getBitCast(C, Ty);
1574 return getSExt(C, Ty);
1577 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {
1578 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1579 return getBitCast(C, Ty);
1580 return getTrunc(C, Ty);
1583 Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {
1584 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1585 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
1588 if (Ty->isIntOrIntVectorTy())
1589 return getPtrToInt(S, Ty);
1591 unsigned SrcAS = S->getType()->getPointerAddressSpace();
1592 if (Ty->isPtrOrPtrVectorTy() && SrcAS != Ty->getPointerAddressSpace())
1593 return getAddrSpaceCast(S, Ty);
1595 return getBitCast(S, Ty);
1598 Constant *ConstantExpr::getPointerBitCastOrAddrSpaceCast(Constant *S,
1600 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1601 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
1603 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
1604 return getAddrSpaceCast(S, Ty);
1606 return getBitCast(S, Ty);
1609 Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty,
1611 assert(C->getType()->isIntOrIntVectorTy() &&
1612 Ty->isIntOrIntVectorTy() && "Invalid cast");
1613 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1614 unsigned DstBits = Ty->getScalarSizeInBits();
1615 Instruction::CastOps opcode =
1616 (SrcBits == DstBits ? Instruction::BitCast :
1617 (SrcBits > DstBits ? Instruction::Trunc :
1618 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1619 return getCast(opcode, C, Ty);
1622 Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) {
1623 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1625 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1626 unsigned DstBits = Ty->getScalarSizeInBits();
1627 if (SrcBits == DstBits)
1628 return C; // Avoid a useless cast
1629 Instruction::CastOps opcode =
1630 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1631 return getCast(opcode, C, Ty);
1634 Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
1636 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1637 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1639 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1640 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
1641 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
1642 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1643 "SrcTy must be larger than DestTy for Trunc!");
1645 return getFoldedCast(Instruction::Trunc, C, Ty, OnlyIfReduced);
1648 Constant *ConstantExpr::getSExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
1650 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1651 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1653 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1654 assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
1655 assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
1656 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1657 "SrcTy must be smaller than DestTy for SExt!");
1659 return getFoldedCast(Instruction::SExt, C, Ty, OnlyIfReduced);
1662 Constant *ConstantExpr::getZExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
1664 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1665 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1667 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1668 assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
1669 assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
1670 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1671 "SrcTy must be smaller than DestTy for ZExt!");
1673 return getFoldedCast(Instruction::ZExt, C, Ty, OnlyIfReduced);
1676 Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
1678 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1679 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1681 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1682 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1683 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1684 "This is an illegal floating point truncation!");
1685 return getFoldedCast(Instruction::FPTrunc, C, Ty, OnlyIfReduced);
1688 Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty, bool OnlyIfReduced) {
1690 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1691 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1693 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1694 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1695 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1696 "This is an illegal floating point extension!");
1697 return getFoldedCast(Instruction::FPExt, C, Ty, OnlyIfReduced);
1700 Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
1702 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1703 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1705 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1706 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1707 "This is an illegal uint to floating point cast!");
1708 return getFoldedCast(Instruction::UIToFP, C, Ty, OnlyIfReduced);
1711 Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
1713 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1714 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1716 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1717 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1718 "This is an illegal sint to floating point cast!");
1719 return getFoldedCast(Instruction::SIToFP, C, Ty, OnlyIfReduced);
1722 Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty, bool OnlyIfReduced) {
1724 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1725 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1727 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1728 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1729 "This is an illegal floating point to uint cast!");
1730 return getFoldedCast(Instruction::FPToUI, C, Ty, OnlyIfReduced);
1733 Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty, bool OnlyIfReduced) {
1735 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1736 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1738 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1739 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1740 "This is an illegal floating point to sint cast!");
1741 return getFoldedCast(Instruction::FPToSI, C, Ty, OnlyIfReduced);
1744 Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy,
1745 bool OnlyIfReduced) {
1746 assert(C->getType()->getScalarType()->isPointerTy() &&
1747 "PtrToInt source must be pointer or pointer vector");
1748 assert(DstTy->getScalarType()->isIntegerTy() &&
1749 "PtrToInt destination must be integer or integer vector");
1750 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
1751 if (isa<VectorType>(C->getType()))
1752 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
1753 "Invalid cast between a different number of vector elements");
1754 return getFoldedCast(Instruction::PtrToInt, C, DstTy, OnlyIfReduced);
1757 Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy,
1758 bool OnlyIfReduced) {
1759 assert(C->getType()->getScalarType()->isIntegerTy() &&
1760 "IntToPtr source must be integer or integer vector");
1761 assert(DstTy->getScalarType()->isPointerTy() &&
1762 "IntToPtr destination must be a pointer or pointer vector");
1763 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
1764 if (isa<VectorType>(C->getType()))
1765 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
1766 "Invalid cast between a different number of vector elements");
1767 return getFoldedCast(Instruction::IntToPtr, C, DstTy, OnlyIfReduced);
1770 Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy,
1771 bool OnlyIfReduced) {
1772 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
1773 "Invalid constantexpr bitcast!");
1775 // It is common to ask for a bitcast of a value to its own type, handle this
1777 if (C->getType() == DstTy) return C;
1779 return getFoldedCast(Instruction::BitCast, C, DstTy, OnlyIfReduced);
1782 Constant *ConstantExpr::getAddrSpaceCast(Constant *C, Type *DstTy,
1783 bool OnlyIfReduced) {
1784 assert(CastInst::castIsValid(Instruction::AddrSpaceCast, C, DstTy) &&
1785 "Invalid constantexpr addrspacecast!");
1787 // Canonicalize addrspacecasts between different pointer types by first
1788 // bitcasting the pointer type and then converting the address space.
1789 PointerType *SrcScalarTy = cast<PointerType>(C->getType()->getScalarType());
1790 PointerType *DstScalarTy = cast<PointerType>(DstTy->getScalarType());
1791 Type *DstElemTy = DstScalarTy->getElementType();
1792 if (SrcScalarTy->getElementType() != DstElemTy) {
1793 Type *MidTy = PointerType::get(DstElemTy, SrcScalarTy->getAddressSpace());
1794 if (VectorType *VT = dyn_cast<VectorType>(DstTy)) {
1795 // Handle vectors of pointers.
1796 MidTy = VectorType::get(MidTy, VT->getNumElements());
1798 C = getBitCast(C, MidTy);
1800 return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced);
1803 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
1804 unsigned Flags, Type *OnlyIfReducedTy) {
1805 // Check the operands for consistency first.
1806 assert(Opcode >= Instruction::BinaryOpsBegin &&
1807 Opcode < Instruction::BinaryOpsEnd &&
1808 "Invalid opcode in binary constant expression");
1809 assert(C1->getType() == C2->getType() &&
1810 "Operand types in binary constant expression should match");
1814 case Instruction::Add:
1815 case Instruction::Sub:
1816 case Instruction::Mul:
1817 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1818 assert(C1->getType()->isIntOrIntVectorTy() &&
1819 "Tried to create an integer operation on a non-integer type!");
1821 case Instruction::FAdd:
1822 case Instruction::FSub:
1823 case Instruction::FMul:
1824 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1825 assert(C1->getType()->isFPOrFPVectorTy() &&
1826 "Tried to create a floating-point operation on a "
1827 "non-floating-point type!");
1829 case Instruction::UDiv:
1830 case Instruction::SDiv:
1831 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1832 assert(C1->getType()->isIntOrIntVectorTy() &&
1833 "Tried to create an arithmetic operation on a non-arithmetic type!");
1835 case Instruction::FDiv:
1836 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1837 assert(C1->getType()->isFPOrFPVectorTy() &&
1838 "Tried to create an arithmetic operation on a non-arithmetic type!");
1840 case Instruction::URem:
1841 case Instruction::SRem:
1842 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1843 assert(C1->getType()->isIntOrIntVectorTy() &&
1844 "Tried to create an arithmetic operation on a non-arithmetic type!");
1846 case Instruction::FRem:
1847 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1848 assert(C1->getType()->isFPOrFPVectorTy() &&
1849 "Tried to create an arithmetic operation on a non-arithmetic type!");
1851 case Instruction::And:
1852 case Instruction::Or:
1853 case Instruction::Xor:
1854 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1855 assert(C1->getType()->isIntOrIntVectorTy() &&
1856 "Tried to create a logical operation on a non-integral type!");
1858 case Instruction::Shl:
1859 case Instruction::LShr:
1860 case Instruction::AShr:
1861 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1862 assert(C1->getType()->isIntOrIntVectorTy() &&
1863 "Tried to create a shift operation on a non-integer type!");
1870 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1871 return FC; // Fold a few common cases.
1873 if (OnlyIfReducedTy == C1->getType())
1876 Constant *ArgVec[] = { C1, C2 };
1877 ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
1879 LLVMContextImpl *pImpl = C1->getContext().pImpl;
1880 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
1883 Constant *ConstantExpr::getSizeOf(Type* Ty) {
1884 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1885 // Note that a non-inbounds gep is used, as null isn't within any object.
1886 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1887 Constant *GEP = getGetElementPtr(
1888 Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
1889 return getPtrToInt(GEP,
1890 Type::getInt64Ty(Ty->getContext()));
1893 Constant *ConstantExpr::getAlignOf(Type* Ty) {
1894 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
1895 // Note that a non-inbounds gep is used, as null isn't within any object.
1897 StructType::get(Type::getInt1Ty(Ty->getContext()), Ty, nullptr);
1898 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo(0));
1899 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
1900 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1901 Constant *Indices[2] = { Zero, One };
1902 Constant *GEP = getGetElementPtr(AligningTy, NullPtr, Indices);
1903 return getPtrToInt(GEP,
1904 Type::getInt64Ty(Ty->getContext()));
1907 Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) {
1908 return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
1912 Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) {
1913 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1914 // Note that a non-inbounds gep is used, as null isn't within any object.
1915 Constant *GEPIdx[] = {
1916 ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
1919 Constant *GEP = getGetElementPtr(
1920 Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
1921 return getPtrToInt(GEP,
1922 Type::getInt64Ty(Ty->getContext()));
1925 Constant *ConstantExpr::getCompare(unsigned short Predicate, Constant *C1,
1926 Constant *C2, bool OnlyIfReduced) {
1927 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1929 switch (Predicate) {
1930 default: llvm_unreachable("Invalid CmpInst predicate");
1931 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1932 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1933 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1934 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1935 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1936 case CmpInst::FCMP_TRUE:
1937 return getFCmp(Predicate, C1, C2, OnlyIfReduced);
1939 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1940 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1941 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1942 case CmpInst::ICMP_SLE:
1943 return getICmp(Predicate, C1, C2, OnlyIfReduced);
1947 Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2,
1948 Type *OnlyIfReducedTy) {
1949 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1951 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1952 return SC; // Fold common cases
1954 if (OnlyIfReducedTy == V1->getType())
1957 Constant *ArgVec[] = { C, V1, V2 };
1958 ConstantExprKeyType Key(Instruction::Select, ArgVec);
1960 LLVMContextImpl *pImpl = C->getContext().pImpl;
1961 return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
1964 Constant *ConstantExpr::getGetElementPtr(Type *Ty, Constant *C,
1965 ArrayRef<Value *> Idxs, bool InBounds,
1966 Type *OnlyIfReducedTy) {
1968 Ty = cast<PointerType>(C->getType()->getScalarType())->getElementType();
1972 cast<PointerType>(C->getType()->getScalarType())->getContainedType(0u));
1974 if (Constant *FC = ConstantFoldGetElementPtr(Ty, C, InBounds, Idxs))
1975 return FC; // Fold a few common cases.
1977 // Get the result type of the getelementptr!
1978 Type *DestTy = GetElementPtrInst::getIndexedType(Ty, Idxs);
1979 assert(DestTy && "GEP indices invalid!");
1980 unsigned AS = C->getType()->getPointerAddressSpace();
1981 Type *ReqTy = DestTy->getPointerTo(AS);
1982 if (VectorType *VecTy = dyn_cast<VectorType>(C->getType()))
1983 ReqTy = VectorType::get(ReqTy, VecTy->getNumElements());
1985 if (OnlyIfReducedTy == ReqTy)
1988 // Look up the constant in the table first to ensure uniqueness
1989 std::vector<Constant*> ArgVec;
1990 ArgVec.reserve(1 + Idxs.size());
1991 ArgVec.push_back(C);
1992 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
1993 assert(Idxs[i]->getType()->isVectorTy() == ReqTy->isVectorTy() &&
1994 "getelementptr index type missmatch");
1995 assert((!Idxs[i]->getType()->isVectorTy() ||
1996 ReqTy->getVectorNumElements() ==
1997 Idxs[i]->getType()->getVectorNumElements()) &&
1998 "getelementptr index type missmatch");
1999 ArgVec.push_back(cast<Constant>(Idxs[i]));
2001 const ConstantExprKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
2002 InBounds ? GEPOperator::IsInBounds : 0, None,
2005 LLVMContextImpl *pImpl = C->getContext().pImpl;
2006 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2009 Constant *ConstantExpr::getICmp(unsigned short pred, Constant *LHS,
2010 Constant *RHS, bool OnlyIfReduced) {
2011 assert(LHS->getType() == RHS->getType());
2012 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2013 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
2015 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2016 return FC; // Fold a few common cases...
2021 // Look up the constant in the table first to ensure uniqueness
2022 Constant *ArgVec[] = { LHS, RHS };
2023 // Get the key type with both the opcode and predicate
2024 const ConstantExprKeyType Key(Instruction::ICmp, ArgVec, pred);
2026 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
2027 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
2028 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
2030 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
2031 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
2034 Constant *ConstantExpr::getFCmp(unsigned short pred, Constant *LHS,
2035 Constant *RHS, bool OnlyIfReduced) {
2036 assert(LHS->getType() == RHS->getType());
2037 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
2039 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2040 return FC; // Fold a few common cases...
2045 // Look up the constant in the table first to ensure uniqueness
2046 Constant *ArgVec[] = { LHS, RHS };
2047 // Get the key type with both the opcode and predicate
2048 const ConstantExprKeyType Key(Instruction::FCmp, ArgVec, pred);
2050 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
2051 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
2052 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
2054 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
2055 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
2058 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx,
2059 Type *OnlyIfReducedTy) {
2060 assert(Val->getType()->isVectorTy() &&
2061 "Tried to create extractelement operation on non-vector type!");
2062 assert(Idx->getType()->isIntegerTy() &&
2063 "Extractelement index must be an integer type!");
2065 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
2066 return FC; // Fold a few common cases.
2068 Type *ReqTy = Val->getType()->getVectorElementType();
2069 if (OnlyIfReducedTy == ReqTy)
2072 // Look up the constant in the table first to ensure uniqueness
2073 Constant *ArgVec[] = { Val, Idx };
2074 const ConstantExprKeyType Key(Instruction::ExtractElement, ArgVec);
2076 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2077 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2080 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2081 Constant *Idx, Type *OnlyIfReducedTy) {
2082 assert(Val->getType()->isVectorTy() &&
2083 "Tried to create insertelement operation on non-vector type!");
2084 assert(Elt->getType() == Val->getType()->getVectorElementType() &&
2085 "Insertelement types must match!");
2086 assert(Idx->getType()->isIntegerTy() &&
2087 "Insertelement index must be i32 type!");
2089 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2090 return FC; // Fold a few common cases.
2092 if (OnlyIfReducedTy == Val->getType())
2095 // Look up the constant in the table first to ensure uniqueness
2096 Constant *ArgVec[] = { Val, Elt, Idx };
2097 const ConstantExprKeyType Key(Instruction::InsertElement, ArgVec);
2099 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2100 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
2103 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2104 Constant *Mask, Type *OnlyIfReducedTy) {
2105 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2106 "Invalid shuffle vector constant expr operands!");
2108 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2109 return FC; // Fold a few common cases.
2111 unsigned NElts = Mask->getType()->getVectorNumElements();
2112 Type *EltTy = V1->getType()->getVectorElementType();
2113 Type *ShufTy = VectorType::get(EltTy, NElts);
2115 if (OnlyIfReducedTy == ShufTy)
2118 // Look up the constant in the table first to ensure uniqueness
2119 Constant *ArgVec[] = { V1, V2, Mask };
2120 const ConstantExprKeyType Key(Instruction::ShuffleVector, ArgVec);
2122 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
2123 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
2126 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
2127 ArrayRef<unsigned> Idxs,
2128 Type *OnlyIfReducedTy) {
2129 assert(Agg->getType()->isFirstClassType() &&
2130 "Non-first-class type for constant insertvalue expression");
2132 assert(ExtractValueInst::getIndexedType(Agg->getType(),
2133 Idxs) == Val->getType() &&
2134 "insertvalue indices invalid!");
2135 Type *ReqTy = Val->getType();
2137 if (Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs))
2140 if (OnlyIfReducedTy == ReqTy)
2143 Constant *ArgVec[] = { Agg, Val };
2144 const ConstantExprKeyType Key(Instruction::InsertValue, ArgVec, 0, 0, Idxs);
2146 LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2147 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2150 Constant *ConstantExpr::getExtractValue(Constant *Agg, ArrayRef<unsigned> Idxs,
2151 Type *OnlyIfReducedTy) {
2152 assert(Agg->getType()->isFirstClassType() &&
2153 "Tried to create extractelement operation on non-first-class type!");
2155 Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs);
2157 assert(ReqTy && "extractvalue indices invalid!");
2159 assert(Agg->getType()->isFirstClassType() &&
2160 "Non-first-class type for constant extractvalue expression");
2161 if (Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs))
2164 if (OnlyIfReducedTy == ReqTy)
2167 Constant *ArgVec[] = { Agg };
2168 const ConstantExprKeyType Key(Instruction::ExtractValue, ArgVec, 0, 0, Idxs);
2170 LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2171 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2174 Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
2175 assert(C->getType()->isIntOrIntVectorTy() &&
2176 "Cannot NEG a nonintegral value!");
2177 return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
2181 Constant *ConstantExpr::getFNeg(Constant *C) {
2182 assert(C->getType()->isFPOrFPVectorTy() &&
2183 "Cannot FNEG a non-floating-point value!");
2184 return getFSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
2187 Constant *ConstantExpr::getNot(Constant *C) {
2188 assert(C->getType()->isIntOrIntVectorTy() &&
2189 "Cannot NOT a nonintegral value!");
2190 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
2193 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
2194 bool HasNUW, bool HasNSW) {
2195 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2196 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2197 return get(Instruction::Add, C1, C2, Flags);
2200 Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
2201 return get(Instruction::FAdd, C1, C2);
2204 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
2205 bool HasNUW, bool HasNSW) {
2206 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2207 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2208 return get(Instruction::Sub, C1, C2, Flags);
2211 Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
2212 return get(Instruction::FSub, C1, C2);
2215 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
2216 bool HasNUW, bool HasNSW) {
2217 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2218 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2219 return get(Instruction::Mul, C1, C2, Flags);
2222 Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
2223 return get(Instruction::FMul, C1, C2);
2226 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
2227 return get(Instruction::UDiv, C1, C2,
2228 isExact ? PossiblyExactOperator::IsExact : 0);
2231 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
2232 return get(Instruction::SDiv, C1, C2,
2233 isExact ? PossiblyExactOperator::IsExact : 0);
2236 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
2237 return get(Instruction::FDiv, C1, C2);
2240 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
2241 return get(Instruction::URem, C1, C2);
2244 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
2245 return get(Instruction::SRem, C1, C2);
2248 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
2249 return get(Instruction::FRem, C1, C2);
2252 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
2253 return get(Instruction::And, C1, C2);
2256 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
2257 return get(Instruction::Or, C1, C2);
2260 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
2261 return get(Instruction::Xor, C1, C2);
2264 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
2265 bool HasNUW, bool HasNSW) {
2266 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2267 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2268 return get(Instruction::Shl, C1, C2, Flags);
2271 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
2272 return get(Instruction::LShr, C1, C2,
2273 isExact ? PossiblyExactOperator::IsExact : 0);
2276 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
2277 return get(Instruction::AShr, C1, C2,
2278 isExact ? PossiblyExactOperator::IsExact : 0);
2281 /// getBinOpIdentity - Return the identity for the given binary operation,
2282 /// i.e. a constant C such that X op C = X and C op X = X for every X. It
2283 /// returns null if the operator doesn't have an identity.
2284 Constant *ConstantExpr::getBinOpIdentity(unsigned Opcode, Type *Ty) {
2287 // Doesn't have an identity.
2290 case Instruction::Add:
2291 case Instruction::Or:
2292 case Instruction::Xor:
2293 return Constant::getNullValue(Ty);
2295 case Instruction::Mul:
2296 return ConstantInt::get(Ty, 1);
2298 case Instruction::And:
2299 return Constant::getAllOnesValue(Ty);
2303 /// getBinOpAbsorber - Return the absorbing element for the given binary
2304 /// operation, i.e. a constant C such that X op C = C and C op X = C for
2305 /// every X. For example, this returns zero for integer multiplication.
2306 /// It returns null if the operator doesn't have an absorbing element.
2307 Constant *ConstantExpr::getBinOpAbsorber(unsigned Opcode, Type *Ty) {
2310 // Doesn't have an absorber.
2313 case Instruction::Or:
2314 return Constant::getAllOnesValue(Ty);
2316 case Instruction::And:
2317 case Instruction::Mul:
2318 return Constant::getNullValue(Ty);
2322 // destroyConstant - Remove the constant from the constant table...
2324 void ConstantExpr::destroyConstantImpl() {
2325 getType()->getContext().pImpl->ExprConstants.remove(this);
2328 const char *ConstantExpr::getOpcodeName() const {
2329 return Instruction::getOpcodeName(getOpcode());
2332 GetElementPtrConstantExpr::GetElementPtrConstantExpr(
2333 Type *SrcElementTy, Constant *C, ArrayRef<Constant *> IdxList, Type *DestTy)
2334 : ConstantExpr(DestTy, Instruction::GetElementPtr,
2335 OperandTraits<GetElementPtrConstantExpr>::op_end(this) -
2336 (IdxList.size() + 1),
2337 IdxList.size() + 1),
2338 SrcElementTy(SrcElementTy) {
2340 Use *OperandList = getOperandList();
2341 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
2342 OperandList[i+1] = IdxList[i];
2345 Type *GetElementPtrConstantExpr::getSourceElementType() const {
2346 return SrcElementTy;
2349 //===----------------------------------------------------------------------===//
2350 // ConstantData* implementations
2352 void ConstantDataArray::anchor() {}
2353 void ConstantDataVector::anchor() {}
2355 /// getElementType - Return the element type of the array/vector.
2356 Type *ConstantDataSequential::getElementType() const {
2357 return getType()->getElementType();
2360 StringRef ConstantDataSequential::getRawDataValues() const {
2361 return StringRef(DataElements, getNumElements()*getElementByteSize());
2364 /// isElementTypeCompatible - Return true if a ConstantDataSequential can be
2365 /// formed with a vector or array of the specified element type.
2366 /// ConstantDataArray only works with normal float and int types that are
2367 /// stored densely in memory, not with things like i42 or x86_f80.
2368 bool ConstantDataSequential::isElementTypeCompatible(Type *Ty) {
2369 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) return true;
2370 if (auto *IT = dyn_cast<IntegerType>(Ty)) {
2371 switch (IT->getBitWidth()) {
2383 /// getNumElements - Return the number of elements in the array or vector.
2384 unsigned ConstantDataSequential::getNumElements() const {
2385 if (ArrayType *AT = dyn_cast<ArrayType>(getType()))
2386 return AT->getNumElements();
2387 return getType()->getVectorNumElements();
2391 /// getElementByteSize - Return the size in bytes of the elements in the data.
2392 uint64_t ConstantDataSequential::getElementByteSize() const {
2393 return getElementType()->getPrimitiveSizeInBits()/8;
2396 /// getElementPointer - Return the start of the specified element.
2397 const char *ConstantDataSequential::getElementPointer(unsigned Elt) const {
2398 assert(Elt < getNumElements() && "Invalid Elt");
2399 return DataElements+Elt*getElementByteSize();
2403 /// isAllZeros - return true if the array is empty or all zeros.
2404 static bool isAllZeros(StringRef Arr) {
2405 for (StringRef::iterator I = Arr.begin(), E = Arr.end(); I != E; ++I)
2411 /// getImpl - This is the underlying implementation of all of the
2412 /// ConstantDataSequential::get methods. They all thunk down to here, providing
2413 /// the correct element type. We take the bytes in as a StringRef because
2414 /// we *want* an underlying "char*" to avoid TBAA type punning violations.
2415 Constant *ConstantDataSequential::getImpl(StringRef Elements, Type *Ty) {
2416 assert(isElementTypeCompatible(Ty->getSequentialElementType()));
2417 // If the elements are all zero or there are no elements, return a CAZ, which
2418 // is more dense and canonical.
2419 if (isAllZeros(Elements))
2420 return ConstantAggregateZero::get(Ty);
2422 // Do a lookup to see if we have already formed one of these.
2425 .pImpl->CDSConstants.insert(std::make_pair(Elements, nullptr))
2428 // The bucket can point to a linked list of different CDS's that have the same
2429 // body but different types. For example, 0,0,0,1 could be a 4 element array
2430 // of i8, or a 1-element array of i32. They'll both end up in the same
2431 /// StringMap bucket, linked up by their Next pointers. Walk the list.
2432 ConstantDataSequential **Entry = &Slot.second;
2433 for (ConstantDataSequential *Node = *Entry; Node;
2434 Entry = &Node->Next, Node = *Entry)
2435 if (Node->getType() == Ty)
2438 // Okay, we didn't get a hit. Create a node of the right class, link it in,
2440 if (isa<ArrayType>(Ty))
2441 return *Entry = new ConstantDataArray(Ty, Slot.first().data());
2443 assert(isa<VectorType>(Ty));
2444 return *Entry = new ConstantDataVector(Ty, Slot.first().data());
2447 void ConstantDataSequential::destroyConstantImpl() {
2448 // Remove the constant from the StringMap.
2449 StringMap<ConstantDataSequential*> &CDSConstants =
2450 getType()->getContext().pImpl->CDSConstants;
2452 StringMap<ConstantDataSequential*>::iterator Slot =
2453 CDSConstants.find(getRawDataValues());
2455 assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
2457 ConstantDataSequential **Entry = &Slot->getValue();
2459 // Remove the entry from the hash table.
2460 if (!(*Entry)->Next) {
2461 // If there is only one value in the bucket (common case) it must be this
2462 // entry, and removing the entry should remove the bucket completely.
2463 assert((*Entry) == this && "Hash mismatch in ConstantDataSequential");
2464 getContext().pImpl->CDSConstants.erase(Slot);
2466 // Otherwise, there are multiple entries linked off the bucket, unlink the
2467 // node we care about but keep the bucket around.
2468 for (ConstantDataSequential *Node = *Entry; ;
2469 Entry = &Node->Next, Node = *Entry) {
2470 assert(Node && "Didn't find entry in its uniquing hash table!");
2471 // If we found our entry, unlink it from the list and we're done.
2473 *Entry = Node->Next;
2479 // If we were part of a list, make sure that we don't delete the list that is
2480 // still owned by the uniquing map.
2484 /// get() constructors - Return a constant with array type with an element
2485 /// count and element type matching the ArrayRef passed in. Note that this
2486 /// can return a ConstantAggregateZero object.
2487 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint8_t> Elts) {
2488 Type *Ty = ArrayType::get(Type::getInt8Ty(Context), Elts.size());
2489 const char *Data = reinterpret_cast<const char *>(Elts.data());
2490 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*1), Ty);
2492 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
2493 Type *Ty = ArrayType::get(Type::getInt16Ty(Context), Elts.size());
2494 const char *Data = reinterpret_cast<const char *>(Elts.data());
2495 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*2), Ty);
2497 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
2498 Type *Ty = ArrayType::get(Type::getInt32Ty(Context), Elts.size());
2499 const char *Data = reinterpret_cast<const char *>(Elts.data());
2500 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
2502 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
2503 Type *Ty = ArrayType::get(Type::getInt64Ty(Context), Elts.size());
2504 const char *Data = reinterpret_cast<const char *>(Elts.data());
2505 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
2507 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<float> Elts) {
2508 Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
2509 const char *Data = reinterpret_cast<const char *>(Elts.data());
2510 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
2512 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<double> Elts) {
2513 Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
2514 const char *Data = reinterpret_cast<const char *>(Elts.data());
2515 return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 8), Ty);
2518 /// getFP() constructors - Return a constant with array type with an element
2519 /// count and element type of float with precision matching the number of
2520 /// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits,
2521 /// double for 64bits) Note that this can return a ConstantAggregateZero
2523 Constant *ConstantDataArray::getFP(LLVMContext &Context,
2524 ArrayRef<uint16_t> Elts) {
2525 Type *Ty = ArrayType::get(Type::getHalfTy(Context), Elts.size());
2526 const char *Data = reinterpret_cast<const char *>(Elts.data());
2527 return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 2), Ty);
2529 Constant *ConstantDataArray::getFP(LLVMContext &Context,
2530 ArrayRef<uint32_t> Elts) {
2531 Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
2532 const char *Data = reinterpret_cast<const char *>(Elts.data());
2533 return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 4), Ty);
2535 Constant *ConstantDataArray::getFP(LLVMContext &Context,
2536 ArrayRef<uint64_t> Elts) {
2537 Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
2538 const char *Data = reinterpret_cast<const char *>(Elts.data());
2539 return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 8), Ty);
2542 /// getString - This method constructs a CDS and initializes it with a text
2543 /// string. The default behavior (AddNull==true) causes a null terminator to
2544 /// be placed at the end of the array (increasing the length of the string by
2545 /// one more than the StringRef would normally indicate. Pass AddNull=false
2546 /// to disable this behavior.
2547 Constant *ConstantDataArray::getString(LLVMContext &Context,
2548 StringRef Str, bool AddNull) {
2550 const uint8_t *Data = reinterpret_cast<const uint8_t *>(Str.data());
2551 return get(Context, makeArrayRef(const_cast<uint8_t *>(Data),
2555 SmallVector<uint8_t, 64> ElementVals;
2556 ElementVals.append(Str.begin(), Str.end());
2557 ElementVals.push_back(0);
2558 return get(Context, ElementVals);
2561 /// get() constructors - Return a constant with vector type with an element
2562 /// count and element type matching the ArrayRef passed in. Note that this
2563 /// can return a ConstantAggregateZero object.
2564 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> Elts){
2565 Type *Ty = VectorType::get(Type::getInt8Ty(Context), Elts.size());
2566 const char *Data = reinterpret_cast<const char *>(Elts.data());
2567 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*1), Ty);
2569 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
2570 Type *Ty = VectorType::get(Type::getInt16Ty(Context), Elts.size());
2571 const char *Data = reinterpret_cast<const char *>(Elts.data());
2572 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*2), Ty);
2574 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
2575 Type *Ty = VectorType::get(Type::getInt32Ty(Context), Elts.size());
2576 const char *Data = reinterpret_cast<const char *>(Elts.data());
2577 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
2579 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
2580 Type *Ty = VectorType::get(Type::getInt64Ty(Context), Elts.size());
2581 const char *Data = reinterpret_cast<const char *>(Elts.data());
2582 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
2584 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> Elts) {
2585 Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
2586 const char *Data = reinterpret_cast<const char *>(Elts.data());
2587 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
2589 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<double> Elts) {
2590 Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
2591 const char *Data = reinterpret_cast<const char *>(Elts.data());
2592 return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 8), Ty);
2595 /// getFP() constructors - Return a constant with vector type with an element
2596 /// count and element type of float with the precision matching the number of
2597 /// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits,
2598 /// double for 64bits) Note that this can return a ConstantAggregateZero
2600 Constant *ConstantDataVector::getFP(LLVMContext &Context,
2601 ArrayRef<uint16_t> Elts) {
2602 Type *Ty = VectorType::get(Type::getHalfTy(Context), Elts.size());
2603 const char *Data = reinterpret_cast<const char *>(Elts.data());
2604 return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 2), Ty);
2606 Constant *ConstantDataVector::getFP(LLVMContext &Context,
2607 ArrayRef<uint32_t> Elts) {
2608 Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
2609 const char *Data = reinterpret_cast<const char *>(Elts.data());
2610 return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 4), Ty);
2612 Constant *ConstantDataVector::getFP(LLVMContext &Context,
2613 ArrayRef<uint64_t> Elts) {
2614 Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
2615 const char *Data = reinterpret_cast<const char *>(Elts.data());
2616 return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 8), Ty);
2619 Constant *ConstantDataVector::getSplat(unsigned NumElts, Constant *V) {
2620 assert(isElementTypeCompatible(V->getType()) &&
2621 "Element type not compatible with ConstantData");
2622 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2623 if (CI->getType()->isIntegerTy(8)) {
2624 SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
2625 return get(V->getContext(), Elts);
2627 if (CI->getType()->isIntegerTy(16)) {
2628 SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
2629 return get(V->getContext(), Elts);
2631 if (CI->getType()->isIntegerTy(32)) {
2632 SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
2633 return get(V->getContext(), Elts);
2635 assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
2636 SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
2637 return get(V->getContext(), Elts);
2640 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2641 if (CFP->getType()->isHalfTy()) {
2642 SmallVector<uint16_t, 16> Elts(
2643 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2644 return getFP(V->getContext(), Elts);
2646 if (CFP->getType()->isFloatTy()) {
2647 SmallVector<uint32_t, 16> Elts(
2648 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2649 return getFP(V->getContext(), Elts);
2651 if (CFP->getType()->isDoubleTy()) {
2652 SmallVector<uint64_t, 16> Elts(
2653 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2654 return getFP(V->getContext(), Elts);
2657 return ConstantVector::getSplat(NumElts, V);
2661 /// getElementAsInteger - If this is a sequential container of integers (of
2662 /// any size), return the specified element in the low bits of a uint64_t.
2663 uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const {
2664 assert(isa<IntegerType>(getElementType()) &&
2665 "Accessor can only be used when element is an integer");
2666 const char *EltPtr = getElementPointer(Elt);
2668 // The data is stored in host byte order, make sure to cast back to the right
2669 // type to load with the right endianness.
2670 switch (getElementType()->getIntegerBitWidth()) {
2671 default: llvm_unreachable("Invalid bitwidth for CDS");
2673 return *const_cast<uint8_t *>(reinterpret_cast<const uint8_t *>(EltPtr));
2675 return *const_cast<uint16_t *>(reinterpret_cast<const uint16_t *>(EltPtr));
2677 return *const_cast<uint32_t *>(reinterpret_cast<const uint32_t *>(EltPtr));
2679 return *const_cast<uint64_t *>(reinterpret_cast<const uint64_t *>(EltPtr));
2683 /// getElementAsAPFloat - If this is a sequential container of floating point
2684 /// type, return the specified element as an APFloat.
2685 APFloat ConstantDataSequential::getElementAsAPFloat(unsigned Elt) const {
2686 const char *EltPtr = getElementPointer(Elt);
2688 switch (getElementType()->getTypeID()) {
2690 llvm_unreachable("Accessor can only be used when element is float/double!");
2691 case Type::HalfTyID: {
2692 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
2693 return APFloat(APFloat::IEEEhalf, APInt(16, EltVal));
2695 case Type::FloatTyID: {
2696 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
2697 return APFloat(APFloat::IEEEsingle, APInt(32, EltVal));
2699 case Type::DoubleTyID: {
2700 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
2701 return APFloat(APFloat::IEEEdouble, APInt(64, EltVal));
2706 /// getElementAsFloat - If this is an sequential container of floats, return
2707 /// the specified element as a float.
2708 float ConstantDataSequential::getElementAsFloat(unsigned Elt) const {
2709 assert(getElementType()->isFloatTy() &&
2710 "Accessor can only be used when element is a 'float'");
2711 const float *EltPtr = reinterpret_cast<const float *>(getElementPointer(Elt));
2712 return *const_cast<float *>(EltPtr);
2715 /// getElementAsDouble - If this is an sequential container of doubles, return
2716 /// the specified element as a float.
2717 double ConstantDataSequential::getElementAsDouble(unsigned Elt) const {
2718 assert(getElementType()->isDoubleTy() &&
2719 "Accessor can only be used when element is a 'float'");
2720 const double *EltPtr =
2721 reinterpret_cast<const double *>(getElementPointer(Elt));
2722 return *const_cast<double *>(EltPtr);
2725 /// getElementAsConstant - Return a Constant for a specified index's element.
2726 /// Note that this has to compute a new constant to return, so it isn't as
2727 /// efficient as getElementAsInteger/Float/Double.
2728 Constant *ConstantDataSequential::getElementAsConstant(unsigned Elt) const {
2729 if (getElementType()->isHalfTy() || getElementType()->isFloatTy() ||
2730 getElementType()->isDoubleTy())
2731 return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
2733 return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
2736 /// isString - This method returns true if this is an array of i8.
2737 bool ConstantDataSequential::isString() const {
2738 return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(8);
2741 /// isCString - This method returns true if the array "isString", ends with a
2742 /// nul byte, and does not contains any other nul bytes.
2743 bool ConstantDataSequential::isCString() const {
2747 StringRef Str = getAsString();
2749 // The last value must be nul.
2750 if (Str.back() != 0) return false;
2752 // Other elements must be non-nul.
2753 return Str.drop_back().find(0) == StringRef::npos;
2756 /// getSplatValue - If this is a splat constant, meaning that all of the
2757 /// elements have the same value, return that value. Otherwise return nullptr.
2758 Constant *ConstantDataVector::getSplatValue() const {
2759 const char *Base = getRawDataValues().data();
2761 // Compare elements 1+ to the 0'th element.
2762 unsigned EltSize = getElementByteSize();
2763 for (unsigned i = 1, e = getNumElements(); i != e; ++i)
2764 if (memcmp(Base, Base+i*EltSize, EltSize))
2767 // If they're all the same, return the 0th one as a representative.
2768 return getElementAsConstant(0);
2771 //===----------------------------------------------------------------------===//
2772 // handleOperandChange implementations
2774 /// Update this constant array to change uses of
2775 /// 'From' to be uses of 'To'. This must update the uniquing data structures
2778 /// Note that we intentionally replace all uses of From with To here. Consider
2779 /// a large array that uses 'From' 1000 times. By handling this case all here,
2780 /// ConstantArray::handleOperandChange is only invoked once, and that
2781 /// single invocation handles all 1000 uses. Handling them one at a time would
2782 /// work, but would be really slow because it would have to unique each updated
2785 void Constant::handleOperandChange(Value *From, Value *To, Use *U) {
2786 Value *Replacement = nullptr;
2787 switch (getValueID()) {
2789 llvm_unreachable("Not a constant!");
2790 #define HANDLE_CONSTANT(Name) \
2791 case Value::Name##Val: \
2792 Replacement = cast<Name>(this)->handleOperandChangeImpl(From, To, U); \
2794 #include "llvm/IR/Value.def"
2797 // If handleOperandChangeImpl returned nullptr, then it handled
2798 // replacing itself and we don't want to delete or replace anything else here.
2802 // I do need to replace this with an existing value.
2803 assert(Replacement != this && "I didn't contain From!");
2805 // Everyone using this now uses the replacement.
2806 replaceAllUsesWith(Replacement);
2808 // Delete the old constant!
2812 Value *ConstantInt::handleOperandChangeImpl(Value *From, Value *To, Use *U) {
2813 llvm_unreachable("Unsupported class for handleOperandChange()!");
2816 Value *ConstantFP::handleOperandChangeImpl(Value *From, Value *To, Use *U) {
2817 llvm_unreachable("Unsupported class for handleOperandChange()!");
2820 Value *ConstantTokenNone::handleOperandChangeImpl(Value *From, Value *To,
2822 llvm_unreachable("Unsupported class for handleOperandChange()!");
2825 Value *UndefValue::handleOperandChangeImpl(Value *From, Value *To, Use *U) {
2826 llvm_unreachable("Unsupported class for handleOperandChange()!");
2829 Value *ConstantPointerNull::handleOperandChangeImpl(Value *From, Value *To,
2831 llvm_unreachable("Unsupported class for handleOperandChange()!");
2834 Value *ConstantAggregateZero::handleOperandChangeImpl(Value *From, Value *To,
2836 llvm_unreachable("Unsupported class for handleOperandChange()!");
2839 Value *ConstantDataSequential::handleOperandChangeImpl(Value *From, Value *To,
2841 llvm_unreachable("Unsupported class for handleOperandChange()!");
2844 Value *ConstantArray::handleOperandChangeImpl(Value *From, Value *To, Use *U) {
2845 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2846 Constant *ToC = cast<Constant>(To);
2848 SmallVector<Constant*, 8> Values;
2849 Values.reserve(getNumOperands()); // Build replacement array.
2851 // Fill values with the modified operands of the constant array. Also,
2852 // compute whether this turns into an all-zeros array.
2853 unsigned NumUpdated = 0;
2855 // Keep track of whether all the values in the array are "ToC".
2856 bool AllSame = true;
2857 Use *OperandList = getOperandList();
2858 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2859 Constant *Val = cast<Constant>(O->get());
2864 Values.push_back(Val);
2865 AllSame &= Val == ToC;
2868 if (AllSame && ToC->isNullValue())
2869 return ConstantAggregateZero::get(getType());
2871 if (AllSame && isa<UndefValue>(ToC))
2872 return UndefValue::get(getType());
2874 // Check for any other type of constant-folding.
2875 if (Constant *C = getImpl(getType(), Values))
2878 // Update to the new value.
2879 return getContext().pImpl->ArrayConstants.replaceOperandsInPlace(
2880 Values, this, From, ToC, NumUpdated, U - OperandList);
2883 Value *ConstantStruct::handleOperandChangeImpl(Value *From, Value *To, Use *U) {
2884 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2885 Constant *ToC = cast<Constant>(To);
2887 Use *OperandList = getOperandList();
2888 unsigned OperandToUpdate = U-OperandList;
2889 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2891 SmallVector<Constant*, 8> Values;
2892 Values.reserve(getNumOperands()); // Build replacement struct.
2894 // Fill values with the modified operands of the constant struct. Also,
2895 // compute whether this turns into an all-zeros struct.
2896 bool isAllZeros = false;
2897 bool isAllUndef = false;
2898 if (ToC->isNullValue()) {
2900 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2901 Constant *Val = cast<Constant>(O->get());
2902 Values.push_back(Val);
2903 if (isAllZeros) isAllZeros = Val->isNullValue();
2905 } else if (isa<UndefValue>(ToC)) {
2907 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2908 Constant *Val = cast<Constant>(O->get());
2909 Values.push_back(Val);
2910 if (isAllUndef) isAllUndef = isa<UndefValue>(Val);
2913 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
2914 Values.push_back(cast<Constant>(O->get()));
2916 Values[OperandToUpdate] = ToC;
2919 return ConstantAggregateZero::get(getType());
2922 return UndefValue::get(getType());
2924 // Update to the new value.
2925 return getContext().pImpl->StructConstants.replaceOperandsInPlace(
2926 Values, this, From, ToC);
2929 Value *ConstantVector::handleOperandChangeImpl(Value *From, Value *To, Use *U) {
2930 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2931 Constant *ToC = cast<Constant>(To);
2933 SmallVector<Constant*, 8> Values;
2934 Values.reserve(getNumOperands()); // Build replacement array...
2935 unsigned NumUpdated = 0;
2936 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2937 Constant *Val = getOperand(i);
2942 Values.push_back(Val);
2945 if (Constant *C = getImpl(Values))
2948 // Update to the new value.
2949 Use *OperandList = getOperandList();
2950 return getContext().pImpl->VectorConstants.replaceOperandsInPlace(
2951 Values, this, From, ToC, NumUpdated, U - OperandList);
2954 Value *ConstantExpr::handleOperandChangeImpl(Value *From, Value *ToV, Use *U) {
2955 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2956 Constant *To = cast<Constant>(ToV);
2958 SmallVector<Constant*, 8> NewOps;
2959 unsigned NumUpdated = 0;
2960 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2961 Constant *Op = getOperand(i);
2966 NewOps.push_back(Op);
2968 assert(NumUpdated && "I didn't contain From!");
2970 if (Constant *C = getWithOperands(NewOps, getType(), true))
2973 // Update to the new value.
2974 Use *OperandList = getOperandList();
2975 return getContext().pImpl->ExprConstants.replaceOperandsInPlace(
2976 NewOps, this, From, To, NumUpdated, U - OperandList);
2979 Instruction *ConstantExpr::getAsInstruction() {
2980 SmallVector<Value *, 4> ValueOperands(op_begin(), op_end());
2981 ArrayRef<Value*> Ops(ValueOperands);
2983 switch (getOpcode()) {
2984 case Instruction::Trunc:
2985 case Instruction::ZExt:
2986 case Instruction::SExt:
2987 case Instruction::FPTrunc:
2988 case Instruction::FPExt:
2989 case Instruction::UIToFP:
2990 case Instruction::SIToFP:
2991 case Instruction::FPToUI:
2992 case Instruction::FPToSI:
2993 case Instruction::PtrToInt:
2994 case Instruction::IntToPtr:
2995 case Instruction::BitCast:
2996 case Instruction::AddrSpaceCast:
2997 return CastInst::Create((Instruction::CastOps)getOpcode(),
2999 case Instruction::Select:
3000 return SelectInst::Create(Ops[0], Ops[1], Ops[2]);
3001 case Instruction::InsertElement:
3002 return InsertElementInst::Create(Ops[0], Ops[1], Ops[2]);
3003 case Instruction::ExtractElement:
3004 return ExtractElementInst::Create(Ops[0], Ops[1]);
3005 case Instruction::InsertValue:
3006 return InsertValueInst::Create(Ops[0], Ops[1], getIndices());
3007 case Instruction::ExtractValue:
3008 return ExtractValueInst::Create(Ops[0], getIndices());
3009 case Instruction::ShuffleVector:
3010 return new ShuffleVectorInst(Ops[0], Ops[1], Ops[2]);
3012 case Instruction::GetElementPtr: {
3013 const auto *GO = cast<GEPOperator>(this);
3014 if (GO->isInBounds())
3015 return GetElementPtrInst::CreateInBounds(GO->getSourceElementType(),
3016 Ops[0], Ops.slice(1));
3017 return GetElementPtrInst::Create(GO->getSourceElementType(), Ops[0],
3020 case Instruction::ICmp:
3021 case Instruction::FCmp:
3022 return CmpInst::Create((Instruction::OtherOps)getOpcode(),
3023 (CmpInst::Predicate)getPredicate(), Ops[0], Ops[1]);
3026 assert(getNumOperands() == 2 && "Must be binary operator?");
3027 BinaryOperator *BO =
3028 BinaryOperator::Create((Instruction::BinaryOps)getOpcode(),
3030 if (isa<OverflowingBinaryOperator>(BO)) {
3031 BO->setHasNoUnsignedWrap(SubclassOptionalData &
3032 OverflowingBinaryOperator::NoUnsignedWrap);
3033 BO->setHasNoSignedWrap(SubclassOptionalData &
3034 OverflowingBinaryOperator::NoSignedWrap);
3036 if (isa<PossiblyExactOperator>(BO))
3037 BO->setIsExact(SubclassOptionalData & PossiblyExactOperator::IsExact);