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 "LLVMContextImpl.h"
15 #include "llvm/Constants.h"
16 #include "ConstantFold.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/GlobalValue.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Module.h"
21 #include "llvm/Operator.h"
22 #include "llvm/ADT/FoldingSet.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/StringMap.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/MathExtras.h"
30 #include "llvm/System/Mutex.h"
31 #include "llvm/System/RWMutex.h"
32 #include "llvm/System/Threading.h"
33 #include "llvm/ADT/DenseMap.h"
34 #include "llvm/ADT/SmallVector.h"
39 //===----------------------------------------------------------------------===//
41 //===----------------------------------------------------------------------===//
43 // Constructor to create a '0' constant of arbitrary type...
44 static const uint64_t zero[2] = {0, 0};
45 Constant* Constant::getNullValue(const Type* Ty) {
46 switch (Ty->getTypeID()) {
47 case Type::IntegerTyID:
48 return ConstantInt::get(Ty, 0);
50 return ConstantFP::get(Ty->getContext(), APFloat(APInt(32, 0)));
51 case Type::DoubleTyID:
52 return ConstantFP::get(Ty->getContext(), APFloat(APInt(64, 0)));
53 case Type::X86_FP80TyID:
54 return ConstantFP::get(Ty->getContext(), APFloat(APInt(80, 2, zero)));
56 return ConstantFP::get(Ty->getContext(),
57 APFloat(APInt(128, 2, zero), true));
58 case Type::PPC_FP128TyID:
59 return ConstantFP::get(Ty->getContext(), APFloat(APInt(128, 2, zero)));
60 case Type::PointerTyID:
61 return ConstantPointerNull::get(cast<PointerType>(Ty));
62 case Type::StructTyID:
64 case Type::VectorTyID:
65 return ConstantAggregateZero::get(Ty);
67 // Function, Label, or Opaque type?
68 assert(!"Cannot create a null constant of that type!");
73 Constant* Constant::getIntegerValue(const Type* Ty, const APInt &V) {
74 const Type *ScalarTy = Ty->getScalarType();
76 // Create the base integer constant.
77 Constant *C = ConstantInt::get(Ty->getContext(), V);
79 // Convert an integer to a pointer, if necessary.
80 if (const PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
81 C = ConstantExpr::getIntToPtr(C, PTy);
83 // Broadcast a scalar to a vector, if necessary.
84 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
85 C = ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
90 Constant* Constant::getAllOnesValue(const Type* Ty) {
91 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
92 return ConstantInt::get(Ty->getContext(),
93 APInt::getAllOnesValue(ITy->getBitWidth()));
95 std::vector<Constant*> Elts;
96 const VectorType* VTy = cast<VectorType>(Ty);
97 Elts.resize(VTy->getNumElements(), getAllOnesValue(VTy->getElementType()));
98 assert(Elts[0] && "Not a vector integer type!");
99 return cast<ConstantVector>(ConstantVector::get(Elts));
102 void Constant::destroyConstantImpl() {
103 // When a Constant is destroyed, there may be lingering
104 // references to the constant by other constants in the constant pool. These
105 // constants are implicitly dependent on the module that is being deleted,
106 // but they don't know that. Because we only find out when the CPV is
107 // deleted, we must now notify all of our users (that should only be
108 // Constants) that they are, in fact, invalid now and should be deleted.
110 while (!use_empty()) {
111 Value *V = use_back();
112 #ifndef NDEBUG // Only in -g mode...
113 if (!isa<Constant>(V))
114 DOUT << "While deleting: " << *this
115 << "\n\nUse still stuck around after Def is destroyed: "
118 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
119 Constant *CV = cast<Constant>(V);
120 CV->destroyConstant();
122 // The constant should remove itself from our use list...
123 assert((use_empty() || use_back() != V) && "Constant not removed!");
126 // Value has no outstanding references it is safe to delete it now...
130 /// canTrap - Return true if evaluation of this constant could trap. This is
131 /// true for things like constant expressions that could divide by zero.
132 bool Constant::canTrap() const {
133 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
134 // The only thing that could possibly trap are constant exprs.
135 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
136 if (!CE) return false;
138 // ConstantExpr traps if any operands can trap.
139 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
140 if (getOperand(i)->canTrap())
143 // Otherwise, only specific operations can trap.
144 switch (CE->getOpcode()) {
147 case Instruction::UDiv:
148 case Instruction::SDiv:
149 case Instruction::FDiv:
150 case Instruction::URem:
151 case Instruction::SRem:
152 case Instruction::FRem:
153 // Div and rem can trap if the RHS is not known to be non-zero.
154 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
161 /// getRelocationInfo - This method classifies the entry according to
162 /// whether or not it may generate a relocation entry. This must be
163 /// conservative, so if it might codegen to a relocatable entry, it should say
164 /// so. The return values are:
166 /// NoRelocation: This constant pool entry is guaranteed to never have a
167 /// relocation applied to it (because it holds a simple constant like
169 /// LocalRelocation: This entry has relocations, but the entries are
170 /// guaranteed to be resolvable by the static linker, so the dynamic
171 /// linker will never see them.
172 /// GlobalRelocations: This entry may have arbitrary relocations.
174 /// FIXME: This really should not be in VMCore.
175 Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
176 if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
177 if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
178 return LocalRelocation; // Local to this file/library.
179 return GlobalRelocations; // Global reference.
182 PossibleRelocationsTy Result = NoRelocation;
183 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
184 Result = std::max(Result, getOperand(i)->getRelocationInfo());
190 /// getVectorElements - This method, which is only valid on constant of vector
191 /// type, returns the elements of the vector in the specified smallvector.
192 /// This handles breaking down a vector undef into undef elements, etc. For
193 /// constant exprs and other cases we can't handle, we return an empty vector.
194 void Constant::getVectorElements(LLVMContext &Context,
195 SmallVectorImpl<Constant*> &Elts) const {
196 assert(isa<VectorType>(getType()) && "Not a vector constant!");
198 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
199 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
200 Elts.push_back(CV->getOperand(i));
204 const VectorType *VT = cast<VectorType>(getType());
205 if (isa<ConstantAggregateZero>(this)) {
206 Elts.assign(VT->getNumElements(),
207 Constant::getNullValue(VT->getElementType()));
211 if (isa<UndefValue>(this)) {
212 Elts.assign(VT->getNumElements(), UndefValue::get(VT->getElementType()));
216 // Unknown type, must be constant expr etc.
221 //===----------------------------------------------------------------------===//
223 //===----------------------------------------------------------------------===//
225 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
226 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
227 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
230 ConstantInt* ConstantInt::getTrue(LLVMContext &Context) {
231 LLVMContextImpl *pImpl = Context.pImpl;
232 sys::SmartScopedWriter<true>(pImpl->ConstantsLock);
233 if (pImpl->TheTrueVal)
234 return pImpl->TheTrueVal;
236 return (pImpl->TheTrueVal =
237 ConstantInt::get(IntegerType::get(Context, 1), 1));
240 ConstantInt* ConstantInt::getFalse(LLVMContext &Context) {
241 LLVMContextImpl *pImpl = Context.pImpl;
242 sys::SmartScopedWriter<true>(pImpl->ConstantsLock);
243 if (pImpl->TheFalseVal)
244 return pImpl->TheFalseVal;
246 return (pImpl->TheFalseVal =
247 ConstantInt::get(IntegerType::get(Context, 1), 0));
251 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
252 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
253 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
254 // compare APInt's of different widths, which would violate an APInt class
255 // invariant which generates an assertion.
256 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt& V) {
257 // Get the corresponding integer type for the bit width of the value.
258 const IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
259 // get an existing value or the insertion position
260 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
262 Context.pImpl->ConstantsLock.reader_acquire();
263 ConstantInt *&Slot = Context.pImpl->IntConstants[Key];
264 Context.pImpl->ConstantsLock.reader_release();
267 sys::SmartScopedWriter<true> Writer(Context.pImpl->ConstantsLock);
268 ConstantInt *&NewSlot = Context.pImpl->IntConstants[Key];
270 NewSlot = new ConstantInt(ITy, V);
279 Constant* ConstantInt::get(const Type* Ty, uint64_t V, bool isSigned) {
280 Constant *C = get(cast<IntegerType>(Ty->getScalarType()),
283 // For vectors, broadcast the value.
284 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
285 return ConstantVector::get(
286 std::vector<Constant *>(VTy->getNumElements(), C));
291 ConstantInt* ConstantInt::get(const IntegerType* Ty, uint64_t V,
293 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
296 ConstantInt* ConstantInt::getSigned(const IntegerType* Ty, int64_t V) {
297 return get(Ty, V, true);
300 Constant *ConstantInt::getSigned(const Type *Ty, int64_t V) {
301 return get(Ty, V, true);
304 Constant* ConstantInt::get(const Type* Ty, const APInt& V) {
305 ConstantInt *C = get(Ty->getContext(), V);
306 assert(C->getType() == Ty->getScalarType() &&
307 "ConstantInt type doesn't match the type implied by its value!");
309 // For vectors, broadcast the value.
310 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
311 return ConstantVector::get(
312 std::vector<Constant *>(VTy->getNumElements(), C));
317 ConstantInt* ConstantInt::get(const IntegerType* Ty, const StringRef& Str,
319 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
322 //===----------------------------------------------------------------------===//
324 //===----------------------------------------------------------------------===//
326 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
327 if (Ty == Type::getFloatTy(Ty->getContext()))
328 return &APFloat::IEEEsingle;
329 if (Ty == Type::getDoubleTy(Ty->getContext()))
330 return &APFloat::IEEEdouble;
331 if (Ty == Type::getX86_FP80Ty(Ty->getContext()))
332 return &APFloat::x87DoubleExtended;
333 else if (Ty == Type::getFP128Ty(Ty->getContext()))
334 return &APFloat::IEEEquad;
336 assert(Ty == Type::getPPC_FP128Ty(Ty->getContext()) && "Unknown FP format");
337 return &APFloat::PPCDoubleDouble;
340 /// get() - This returns a constant fp for the specified value in the
341 /// specified type. This should only be used for simple constant values like
342 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
343 Constant* ConstantFP::get(const Type* Ty, double V) {
344 LLVMContext &Context = Ty->getContext();
348 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
349 APFloat::rmNearestTiesToEven, &ignored);
350 Constant *C = get(Context, FV);
352 // For vectors, broadcast the value.
353 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
354 return ConstantVector::get(
355 std::vector<Constant *>(VTy->getNumElements(), C));
361 Constant* ConstantFP::get(const Type* Ty, const StringRef& Str) {
362 LLVMContext &Context = Ty->getContext();
364 APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
365 Constant *C = get(Context, FV);
367 // For vectors, broadcast the value.
368 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
369 return ConstantVector::get(
370 std::vector<Constant *>(VTy->getNumElements(), C));
376 ConstantFP* ConstantFP::getNegativeZero(const Type* Ty) {
377 LLVMContext &Context = Ty->getContext();
378 APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
380 return get(Context, apf);
384 Constant* ConstantFP::getZeroValueForNegation(const Type* Ty) {
385 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
386 if (PTy->getElementType()->isFloatingPoint()) {
387 std::vector<Constant*> zeros(PTy->getNumElements(),
388 getNegativeZero(PTy->getElementType()));
389 return ConstantVector::get(PTy, zeros);
392 if (Ty->isFloatingPoint())
393 return getNegativeZero(Ty);
395 return Constant::getNullValue(Ty);
399 // ConstantFP accessors.
400 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
401 DenseMapAPFloatKeyInfo::KeyTy Key(V);
403 LLVMContextImpl* pImpl = Context.pImpl;
405 pImpl->ConstantsLock.reader_acquire();
406 ConstantFP *&Slot = pImpl->FPConstants[Key];
407 pImpl->ConstantsLock.reader_release();
410 sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
411 ConstantFP *&NewSlot = pImpl->FPConstants[Key];
414 if (&V.getSemantics() == &APFloat::IEEEsingle)
415 Ty = Type::getFloatTy(Context);
416 else if (&V.getSemantics() == &APFloat::IEEEdouble)
417 Ty = Type::getDoubleTy(Context);
418 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
419 Ty = Type::getX86_FP80Ty(Context);
420 else if (&V.getSemantics() == &APFloat::IEEEquad)
421 Ty = Type::getFP128Ty(Context);
423 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
424 "Unknown FP format");
425 Ty = Type::getPPC_FP128Ty(Context);
427 NewSlot = new ConstantFP(Ty, V);
436 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
437 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
438 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
442 bool ConstantFP::isNullValue() const {
443 return Val.isZero() && !Val.isNegative();
446 bool ConstantFP::isExactlyValue(const APFloat& V) const {
447 return Val.bitwiseIsEqual(V);
450 //===----------------------------------------------------------------------===//
451 // ConstantXXX Classes
452 //===----------------------------------------------------------------------===//
455 ConstantArray::ConstantArray(const ArrayType *T,
456 const std::vector<Constant*> &V)
457 : Constant(T, ConstantArrayVal,
458 OperandTraits<ConstantArray>::op_end(this) - V.size(),
460 assert(V.size() == T->getNumElements() &&
461 "Invalid initializer vector for constant array");
462 Use *OL = OperandList;
463 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
466 assert((C->getType() == T->getElementType() ||
468 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
469 "Initializer for array element doesn't match array element type!");
474 Constant *ConstantArray::get(const ArrayType *Ty,
475 const std::vector<Constant*> &V) {
476 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
477 // If this is an all-zero array, return a ConstantAggregateZero object
480 if (!C->isNullValue()) {
481 // Implicitly locked.
482 return pImpl->ArrayConstants.getOrCreate(Ty, V);
484 for (unsigned i = 1, e = V.size(); i != e; ++i)
486 // Implicitly locked.
487 return pImpl->ArrayConstants.getOrCreate(Ty, V);
491 return ConstantAggregateZero::get(Ty);
495 Constant* ConstantArray::get(const ArrayType* T, Constant* const* Vals,
497 // FIXME: make this the primary ctor method.
498 return get(T, std::vector<Constant*>(Vals, Vals+NumVals));
501 /// ConstantArray::get(const string&) - Return an array that is initialized to
502 /// contain the specified string. If length is zero then a null terminator is
503 /// added to the specified string so that it may be used in a natural way.
504 /// Otherwise, the length parameter specifies how much of the string to use
505 /// and it won't be null terminated.
507 Constant* ConstantArray::get(LLVMContext &Context, const StringRef &Str,
509 std::vector<Constant*> ElementVals;
510 for (unsigned i = 0; i < Str.size(); ++i)
511 ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), Str[i]));
513 // Add a null terminator to the string...
515 ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), 0));
518 ArrayType *ATy = ArrayType::get(Type::getInt8Ty(Context), ElementVals.size());
519 return get(ATy, ElementVals);
524 ConstantStruct::ConstantStruct(const StructType *T,
525 const std::vector<Constant*> &V)
526 : Constant(T, ConstantStructVal,
527 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
529 assert(V.size() == T->getNumElements() &&
530 "Invalid initializer vector for constant structure");
531 Use *OL = OperandList;
532 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
535 assert((C->getType() == T->getElementType(I-V.begin()) ||
536 ((T->getElementType(I-V.begin())->isAbstract() ||
537 C->getType()->isAbstract()) &&
538 T->getElementType(I-V.begin())->getTypeID() ==
539 C->getType()->getTypeID())) &&
540 "Initializer for struct element doesn't match struct element type!");
545 // ConstantStruct accessors.
546 Constant* ConstantStruct::get(const StructType* T,
547 const std::vector<Constant*>& V) {
548 LLVMContextImpl* pImpl = T->getContext().pImpl;
550 // Create a ConstantAggregateZero value if all elements are zeros...
551 for (unsigned i = 0, e = V.size(); i != e; ++i)
552 if (!V[i]->isNullValue())
553 // Implicitly locked.
554 return pImpl->StructConstants.getOrCreate(T, V);
556 return ConstantAggregateZero::get(T);
559 Constant* ConstantStruct::get(LLVMContext &Context,
560 const std::vector<Constant*>& V, bool packed) {
561 std::vector<const Type*> StructEls;
562 StructEls.reserve(V.size());
563 for (unsigned i = 0, e = V.size(); i != e; ++i)
564 StructEls.push_back(V[i]->getType());
565 return get(StructType::get(Context, StructEls, packed), V);
568 Constant* ConstantStruct::get(LLVMContext &Context,
569 Constant* const *Vals, unsigned NumVals,
571 // FIXME: make this the primary ctor method.
572 return get(Context, std::vector<Constant*>(Vals, Vals+NumVals), Packed);
575 ConstantVector::ConstantVector(const VectorType *T,
576 const std::vector<Constant*> &V)
577 : Constant(T, ConstantVectorVal,
578 OperandTraits<ConstantVector>::op_end(this) - V.size(),
580 Use *OL = OperandList;
581 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
584 assert((C->getType() == T->getElementType() ||
586 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
587 "Initializer for vector element doesn't match vector element type!");
592 // ConstantVector accessors.
593 Constant* ConstantVector::get(const VectorType* T,
594 const std::vector<Constant*>& V) {
595 assert(!V.empty() && "Vectors can't be empty");
596 LLVMContext &Context = T->getContext();
597 LLVMContextImpl *pImpl = Context.pImpl;
599 // If this is an all-undef or alll-zero vector, return a
600 // ConstantAggregateZero or UndefValue.
602 bool isZero = C->isNullValue();
603 bool isUndef = isa<UndefValue>(C);
605 if (isZero || isUndef) {
606 for (unsigned i = 1, e = V.size(); i != e; ++i)
608 isZero = isUndef = false;
614 return ConstantAggregateZero::get(T);
616 return UndefValue::get(T);
618 // Implicitly locked.
619 return pImpl->VectorConstants.getOrCreate(T, V);
622 Constant* ConstantVector::get(const std::vector<Constant*>& V) {
623 assert(!V.empty() && "Cannot infer type if V is empty");
624 return get(VectorType::get(V.front()->getType(),V.size()), V);
627 Constant* ConstantVector::get(Constant* const* Vals, unsigned NumVals) {
628 // FIXME: make this the primary ctor method.
629 return get(std::vector<Constant*>(Vals, Vals+NumVals));
632 Constant* ConstantExpr::getNSWAdd(Constant* C1, Constant* C2) {
633 Constant *C = getAdd(C1, C2);
634 // Set nsw attribute, assuming constant folding didn't eliminate the
636 if (AddOperator *Add = dyn_cast<AddOperator>(C))
637 Add->setHasNoSignedOverflow(true);
641 Constant* ConstantExpr::getExactSDiv(Constant* C1, Constant* C2) {
642 Constant *C = getSDiv(C1, C2);
643 // Set exact attribute, assuming constant folding didn't eliminate the
645 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(C))
646 SDiv->setIsExact(true);
650 // Utility function for determining if a ConstantExpr is a CastOp or not. This
651 // can't be inline because we don't want to #include Instruction.h into
653 bool ConstantExpr::isCast() const {
654 return Instruction::isCast(getOpcode());
657 bool ConstantExpr::isCompare() const {
658 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
661 bool ConstantExpr::hasIndices() const {
662 return getOpcode() == Instruction::ExtractValue ||
663 getOpcode() == Instruction::InsertValue;
666 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
667 if (const ExtractValueConstantExpr *EVCE =
668 dyn_cast<ExtractValueConstantExpr>(this))
669 return EVCE->Indices;
671 return cast<InsertValueConstantExpr>(this)->Indices;
674 unsigned ConstantExpr::getPredicate() const {
675 assert(getOpcode() == Instruction::FCmp ||
676 getOpcode() == Instruction::ICmp);
677 return ((const CompareConstantExpr*)this)->predicate;
680 /// getWithOperandReplaced - Return a constant expression identical to this
681 /// one, but with the specified operand set to the specified value.
683 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
684 assert(OpNo < getNumOperands() && "Operand num is out of range!");
685 assert(Op->getType() == getOperand(OpNo)->getType() &&
686 "Replacing operand with value of different type!");
687 if (getOperand(OpNo) == Op)
688 return const_cast<ConstantExpr*>(this);
690 Constant *Op0, *Op1, *Op2;
691 switch (getOpcode()) {
692 case Instruction::Trunc:
693 case Instruction::ZExt:
694 case Instruction::SExt:
695 case Instruction::FPTrunc:
696 case Instruction::FPExt:
697 case Instruction::UIToFP:
698 case Instruction::SIToFP:
699 case Instruction::FPToUI:
700 case Instruction::FPToSI:
701 case Instruction::PtrToInt:
702 case Instruction::IntToPtr:
703 case Instruction::BitCast:
704 return ConstantExpr::getCast(getOpcode(), Op, getType());
705 case Instruction::Select:
706 Op0 = (OpNo == 0) ? Op : getOperand(0);
707 Op1 = (OpNo == 1) ? Op : getOperand(1);
708 Op2 = (OpNo == 2) ? Op : getOperand(2);
709 return ConstantExpr::getSelect(Op0, Op1, Op2);
710 case Instruction::InsertElement:
711 Op0 = (OpNo == 0) ? Op : getOperand(0);
712 Op1 = (OpNo == 1) ? Op : getOperand(1);
713 Op2 = (OpNo == 2) ? Op : getOperand(2);
714 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
715 case Instruction::ExtractElement:
716 Op0 = (OpNo == 0) ? Op : getOperand(0);
717 Op1 = (OpNo == 1) ? Op : getOperand(1);
718 return ConstantExpr::getExtractElement(Op0, Op1);
719 case Instruction::ShuffleVector:
720 Op0 = (OpNo == 0) ? Op : getOperand(0);
721 Op1 = (OpNo == 1) ? Op : getOperand(1);
722 Op2 = (OpNo == 2) ? Op : getOperand(2);
723 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
724 case Instruction::GetElementPtr: {
725 SmallVector<Constant*, 8> Ops;
726 Ops.resize(getNumOperands()-1);
727 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
728 Ops[i-1] = getOperand(i);
730 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
732 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
735 assert(getNumOperands() == 2 && "Must be binary operator?");
736 Op0 = (OpNo == 0) ? Op : getOperand(0);
737 Op1 = (OpNo == 1) ? Op : getOperand(1);
738 return ConstantExpr::get(getOpcode(), Op0, Op1);
742 /// getWithOperands - This returns the current constant expression with the
743 /// operands replaced with the specified values. The specified operands must
744 /// match count and type with the existing ones.
745 Constant *ConstantExpr::
746 getWithOperands(Constant* const *Ops, unsigned NumOps) const {
747 assert(NumOps == getNumOperands() && "Operand count mismatch!");
748 bool AnyChange = false;
749 for (unsigned i = 0; i != NumOps; ++i) {
750 assert(Ops[i]->getType() == getOperand(i)->getType() &&
751 "Operand type mismatch!");
752 AnyChange |= Ops[i] != getOperand(i);
754 if (!AnyChange) // No operands changed, return self.
755 return const_cast<ConstantExpr*>(this);
757 switch (getOpcode()) {
758 case Instruction::Trunc:
759 case Instruction::ZExt:
760 case Instruction::SExt:
761 case Instruction::FPTrunc:
762 case Instruction::FPExt:
763 case Instruction::UIToFP:
764 case Instruction::SIToFP:
765 case Instruction::FPToUI:
766 case Instruction::FPToSI:
767 case Instruction::PtrToInt:
768 case Instruction::IntToPtr:
769 case Instruction::BitCast:
770 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
771 case Instruction::Select:
772 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
773 case Instruction::InsertElement:
774 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
775 case Instruction::ExtractElement:
776 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
777 case Instruction::ShuffleVector:
778 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
779 case Instruction::GetElementPtr:
780 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
781 case Instruction::ICmp:
782 case Instruction::FCmp:
783 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
785 assert(getNumOperands() == 2 && "Must be binary operator?");
786 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
791 //===----------------------------------------------------------------------===//
792 // isValueValidForType implementations
794 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
795 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
796 if (Ty == Type::getInt1Ty(Ty->getContext()))
797 return Val == 0 || Val == 1;
799 return true; // always true, has to fit in largest type
800 uint64_t Max = (1ll << NumBits) - 1;
804 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
805 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
806 if (Ty == Type::getInt1Ty(Ty->getContext()))
807 return Val == 0 || Val == 1 || Val == -1;
809 return true; // always true, has to fit in largest type
810 int64_t Min = -(1ll << (NumBits-1));
811 int64_t Max = (1ll << (NumBits-1)) - 1;
812 return (Val >= Min && Val <= Max);
815 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
816 // convert modifies in place, so make a copy.
817 APFloat Val2 = APFloat(Val);
819 switch (Ty->getTypeID()) {
821 return false; // These can't be represented as floating point!
823 // FIXME rounding mode needs to be more flexible
824 case Type::FloatTyID: {
825 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
827 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
830 case Type::DoubleTyID: {
831 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
832 &Val2.getSemantics() == &APFloat::IEEEdouble)
834 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
837 case Type::X86_FP80TyID:
838 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
839 &Val2.getSemantics() == &APFloat::IEEEdouble ||
840 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
841 case Type::FP128TyID:
842 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
843 &Val2.getSemantics() == &APFloat::IEEEdouble ||
844 &Val2.getSemantics() == &APFloat::IEEEquad;
845 case Type::PPC_FP128TyID:
846 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
847 &Val2.getSemantics() == &APFloat::IEEEdouble ||
848 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
852 //===----------------------------------------------------------------------===//
853 // Factory Function Implementation
855 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
857 ConstantAggregateZero* ConstantAggregateZero::get(const Type* Ty) {
858 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
859 "Cannot create an aggregate zero of non-aggregate type!");
861 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
862 // Implicitly locked.
863 return pImpl->AggZeroConstants.getOrCreate(Ty, 0);
866 /// destroyConstant - Remove the constant from the constant table...
868 void ConstantAggregateZero::destroyConstant() {
869 // Implicitly locked.
870 getType()->getContext().pImpl->AggZeroConstants.remove(this);
871 destroyConstantImpl();
874 /// destroyConstant - Remove the constant from the constant table...
876 void ConstantArray::destroyConstant() {
877 // Implicitly locked.
878 getType()->getContext().pImpl->ArrayConstants.remove(this);
879 destroyConstantImpl();
882 /// isString - This method returns true if the array is an array of i8, and
883 /// if the elements of the array are all ConstantInt's.
884 bool ConstantArray::isString() const {
885 // Check the element type for i8...
886 if (getType()->getElementType() != Type::getInt8Ty(getContext()))
888 // Check the elements to make sure they are all integers, not constant
890 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
891 if (!isa<ConstantInt>(getOperand(i)))
896 /// isCString - This method returns true if the array is a string (see
897 /// isString) and it ends in a null byte \\0 and does not contains any other
898 /// null bytes except its terminator.
899 bool ConstantArray::isCString() const {
900 // Check the element type for i8...
901 if (getType()->getElementType() != Type::getInt8Ty(getContext()))
904 // Last element must be a null.
905 if (!getOperand(getNumOperands()-1)->isNullValue())
907 // Other elements must be non-null integers.
908 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
909 if (!isa<ConstantInt>(getOperand(i)))
911 if (getOperand(i)->isNullValue())
918 /// getAsString - If the sub-element type of this array is i8
919 /// then this method converts the array to an std::string and returns it.
920 /// Otherwise, it asserts out.
922 std::string ConstantArray::getAsString() const {
923 assert(isString() && "Not a string!");
925 Result.reserve(getNumOperands());
926 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
927 Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
932 //---- ConstantStruct::get() implementation...
939 // destroyConstant - Remove the constant from the constant table...
941 void ConstantStruct::destroyConstant() {
942 // Implicitly locked.
943 getType()->getContext().pImpl->StructConstants.remove(this);
944 destroyConstantImpl();
947 // destroyConstant - Remove the constant from the constant table...
949 void ConstantVector::destroyConstant() {
950 // Implicitly locked.
951 getType()->getContext().pImpl->VectorConstants.remove(this);
952 destroyConstantImpl();
955 /// This function will return true iff every element in this vector constant
956 /// is set to all ones.
957 /// @returns true iff this constant's emements are all set to all ones.
958 /// @brief Determine if the value is all ones.
959 bool ConstantVector::isAllOnesValue() const {
960 // Check out first element.
961 const Constant *Elt = getOperand(0);
962 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
963 if (!CI || !CI->isAllOnesValue()) return false;
964 // Then make sure all remaining elements point to the same value.
965 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
966 if (getOperand(I) != Elt) return false;
971 /// getSplatValue - If this is a splat constant, where all of the
972 /// elements have the same value, return that value. Otherwise return null.
973 Constant *ConstantVector::getSplatValue() {
974 // Check out first element.
975 Constant *Elt = getOperand(0);
976 // Then make sure all remaining elements point to the same value.
977 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
978 if (getOperand(I) != Elt) return 0;
982 //---- ConstantPointerNull::get() implementation...
985 static char getValType(ConstantPointerNull *) {
990 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
991 // Implicitly locked.
992 return Ty->getContext().pImpl->NullPtrConstants.getOrCreate(Ty, 0);
995 // destroyConstant - Remove the constant from the constant table...
997 void ConstantPointerNull::destroyConstant() {
998 // Implicitly locked.
999 getType()->getContext().pImpl->NullPtrConstants.remove(this);
1000 destroyConstantImpl();
1004 //---- UndefValue::get() implementation...
1007 static char getValType(UndefValue *) {
1011 UndefValue *UndefValue::get(const Type *Ty) {
1012 // Implicitly locked.
1013 return Ty->getContext().pImpl->UndefValueConstants.getOrCreate(Ty, 0);
1016 // destroyConstant - Remove the constant from the constant table.
1018 void UndefValue::destroyConstant() {
1019 // Implicitly locked.
1020 getType()->getContext().pImpl->UndefValueConstants.remove(this);
1021 destroyConstantImpl();
1024 //---- ConstantExpr::get() implementations...
1027 static ExprMapKeyType getValType(ConstantExpr *CE) {
1028 std::vector<Constant*> Operands;
1029 Operands.reserve(CE->getNumOperands());
1030 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1031 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1032 return ExprMapKeyType(CE->getOpcode(), Operands,
1033 CE->isCompare() ? CE->getPredicate() : 0,
1035 CE->getIndices() : SmallVector<unsigned, 4>());
1038 /// This is a utility function to handle folding of casts and lookup of the
1039 /// cast in the ExprConstants map. It is used by the various get* methods below.
1040 static inline Constant *getFoldedCast(
1041 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1042 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1043 // Fold a few common cases
1044 if (Constant *FC = ConstantFoldCastInstruction(Ty->getContext(), opc, C, Ty))
1047 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1049 // Look up the constant in the table first to ensure uniqueness
1050 std::vector<Constant*> argVec(1, C);
1051 ExprMapKeyType Key(opc, argVec);
1053 // Implicitly locked.
1054 return pImpl->ExprConstants.getOrCreate(Ty, Key);
1057 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1058 Instruction::CastOps opc = Instruction::CastOps(oc);
1059 assert(Instruction::isCast(opc) && "opcode out of range");
1060 assert(C && Ty && "Null arguments to getCast");
1061 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1065 llvm_unreachable("Invalid cast opcode");
1067 case Instruction::Trunc: return getTrunc(C, Ty);
1068 case Instruction::ZExt: return getZExt(C, Ty);
1069 case Instruction::SExt: return getSExt(C, Ty);
1070 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1071 case Instruction::FPExt: return getFPExtend(C, Ty);
1072 case Instruction::UIToFP: return getUIToFP(C, Ty);
1073 case Instruction::SIToFP: return getSIToFP(C, Ty);
1074 case Instruction::FPToUI: return getFPToUI(C, Ty);
1075 case Instruction::FPToSI: return getFPToSI(C, Ty);
1076 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1077 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1078 case Instruction::BitCast: return getBitCast(C, Ty);
1083 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1084 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1085 return getCast(Instruction::BitCast, C, Ty);
1086 return getCast(Instruction::ZExt, C, Ty);
1089 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1090 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1091 return getCast(Instruction::BitCast, C, Ty);
1092 return getCast(Instruction::SExt, C, Ty);
1095 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1096 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1097 return getCast(Instruction::BitCast, C, Ty);
1098 return getCast(Instruction::Trunc, C, Ty);
1101 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1102 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1103 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1105 if (Ty->isInteger())
1106 return getCast(Instruction::PtrToInt, S, Ty);
1107 return getCast(Instruction::BitCast, S, Ty);
1110 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1112 assert(C->getType()->isIntOrIntVector() &&
1113 Ty->isIntOrIntVector() && "Invalid cast");
1114 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1115 unsigned DstBits = Ty->getScalarSizeInBits();
1116 Instruction::CastOps opcode =
1117 (SrcBits == DstBits ? Instruction::BitCast :
1118 (SrcBits > DstBits ? Instruction::Trunc :
1119 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1120 return getCast(opcode, C, Ty);
1123 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1124 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1126 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1127 unsigned DstBits = Ty->getScalarSizeInBits();
1128 if (SrcBits == DstBits)
1129 return C; // Avoid a useless cast
1130 Instruction::CastOps opcode =
1131 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1132 return getCast(opcode, C, Ty);
1135 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1137 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1138 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1140 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1141 assert(C->getType()->isIntOrIntVector() && "Trunc operand must be integer");
1142 assert(Ty->isIntOrIntVector() && "Trunc produces only integral");
1143 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1144 "SrcTy must be larger than DestTy for Trunc!");
1146 return getFoldedCast(Instruction::Trunc, C, Ty);
1149 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1151 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1152 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1154 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1155 assert(C->getType()->isIntOrIntVector() && "SExt operand must be integral");
1156 assert(Ty->isIntOrIntVector() && "SExt produces only integer");
1157 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1158 "SrcTy must be smaller than DestTy for SExt!");
1160 return getFoldedCast(Instruction::SExt, C, Ty);
1163 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1165 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1166 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1168 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1169 assert(C->getType()->isIntOrIntVector() && "ZEXt operand must be integral");
1170 assert(Ty->isIntOrIntVector() && "ZExt produces only integer");
1171 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1172 "SrcTy must be smaller than DestTy for ZExt!");
1174 return getFoldedCast(Instruction::ZExt, C, Ty);
1177 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1179 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1180 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1182 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1183 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1184 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1185 "This is an illegal floating point truncation!");
1186 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1189 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1191 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1192 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1194 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1195 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1196 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1197 "This is an illegal floating point extension!");
1198 return getFoldedCast(Instruction::FPExt, C, Ty);
1201 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1203 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1204 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1206 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1207 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1208 "This is an illegal uint to floating point cast!");
1209 return getFoldedCast(Instruction::UIToFP, C, Ty);
1212 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1214 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1215 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1217 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1218 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1219 "This is an illegal sint to floating point cast!");
1220 return getFoldedCast(Instruction::SIToFP, C, Ty);
1223 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1225 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1226 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1228 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1229 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1230 "This is an illegal floating point to uint cast!");
1231 return getFoldedCast(Instruction::FPToUI, C, Ty);
1234 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1236 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1237 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1239 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1240 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1241 "This is an illegal floating point to sint cast!");
1242 return getFoldedCast(Instruction::FPToSI, C, Ty);
1245 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1246 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1247 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1248 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1251 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1252 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1253 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1254 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1257 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1258 // BitCast implies a no-op cast of type only. No bits change. However, you
1259 // can't cast pointers to anything but pointers.
1261 const Type *SrcTy = C->getType();
1262 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1263 "BitCast cannot cast pointer to non-pointer and vice versa");
1265 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1266 // or nonptr->ptr). For all the other types, the cast is okay if source and
1267 // destination bit widths are identical.
1268 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1269 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1271 assert(SrcBitSize == DstBitSize && "BitCast requires types of same width");
1273 // It is common to ask for a bitcast of a value to its own type, handle this
1275 if (C->getType() == DstTy) return C;
1277 return getFoldedCast(Instruction::BitCast, C, DstTy);
1280 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1281 Constant *C1, Constant *C2) {
1282 // Check the operands for consistency first
1283 assert(Opcode >= Instruction::BinaryOpsBegin &&
1284 Opcode < Instruction::BinaryOpsEnd &&
1285 "Invalid opcode in binary constant expression");
1286 assert(C1->getType() == C2->getType() &&
1287 "Operand types in binary constant expression should match");
1289 if (ReqTy == C1->getType() || ReqTy == Type::getInt1Ty(ReqTy->getContext()))
1290 if (Constant *FC = ConstantFoldBinaryInstruction(ReqTy->getContext(),
1292 return FC; // Fold a few common cases...
1294 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1295 ExprMapKeyType Key(Opcode, argVec);
1297 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1299 // Implicitly locked.
1300 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1303 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1304 Constant *C1, Constant *C2) {
1305 switch (predicate) {
1306 default: llvm_unreachable("Invalid CmpInst predicate");
1307 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1308 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1309 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1310 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1311 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1312 case CmpInst::FCMP_TRUE:
1313 return getFCmp(predicate, C1, C2);
1315 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1316 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1317 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1318 case CmpInst::ICMP_SLE:
1319 return getICmp(predicate, C1, C2);
1323 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1324 // API compatibility: Adjust integer opcodes to floating-point opcodes.
1325 if (C1->getType()->isFPOrFPVector()) {
1326 if (Opcode == Instruction::Add) Opcode = Instruction::FAdd;
1327 else if (Opcode == Instruction::Sub) Opcode = Instruction::FSub;
1328 else if (Opcode == Instruction::Mul) Opcode = Instruction::FMul;
1332 case Instruction::Add:
1333 case Instruction::Sub:
1334 case Instruction::Mul:
1335 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1336 assert(C1->getType()->isIntOrIntVector() &&
1337 "Tried to create an integer operation on a non-integer type!");
1339 case Instruction::FAdd:
1340 case Instruction::FSub:
1341 case Instruction::FMul:
1342 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1343 assert(C1->getType()->isFPOrFPVector() &&
1344 "Tried to create a floating-point operation on a "
1345 "non-floating-point type!");
1347 case Instruction::UDiv:
1348 case Instruction::SDiv:
1349 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1350 assert(C1->getType()->isIntOrIntVector() &&
1351 "Tried to create an arithmetic operation on a non-arithmetic type!");
1353 case Instruction::FDiv:
1354 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1355 assert(C1->getType()->isFPOrFPVector() &&
1356 "Tried to create an arithmetic operation on a non-arithmetic type!");
1358 case Instruction::URem:
1359 case Instruction::SRem:
1360 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1361 assert(C1->getType()->isIntOrIntVector() &&
1362 "Tried to create an arithmetic operation on a non-arithmetic type!");
1364 case Instruction::FRem:
1365 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1366 assert(C1->getType()->isFPOrFPVector() &&
1367 "Tried to create an arithmetic operation on a non-arithmetic type!");
1369 case Instruction::And:
1370 case Instruction::Or:
1371 case Instruction::Xor:
1372 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1373 assert(C1->getType()->isIntOrIntVector() &&
1374 "Tried to create a logical operation on a non-integral type!");
1376 case Instruction::Shl:
1377 case Instruction::LShr:
1378 case Instruction::AShr:
1379 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1380 assert(C1->getType()->isIntOrIntVector() &&
1381 "Tried to create a shift operation on a non-integer type!");
1388 return getTy(C1->getType(), Opcode, C1, C2);
1391 Constant* ConstantExpr::getSizeOf(const Type* Ty) {
1392 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1393 // Note that a non-inbounds gep is used, as null isn't within any object.
1394 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1395 Constant *GEP = getGetElementPtr(
1396 Constant::getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
1397 return getCast(Instruction::PtrToInt, GEP,
1398 Type::getInt64Ty(Ty->getContext()));
1401 Constant* ConstantExpr::getAlignOf(const Type* Ty) {
1402 // alignof is implemented as: (i64) gep ({i8,Ty}*)null, 0, 1
1403 // Note that a non-inbounds gep is used, as null isn't within any object.
1404 const Type *AligningTy = StructType::get(Ty->getContext(),
1405 Type::getInt8Ty(Ty->getContext()), Ty, NULL);
1406 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo());
1407 Constant *Zero = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 0);
1408 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1409 Constant *Indices[2] = { Zero, One };
1410 Constant *GEP = getGetElementPtr(NullPtr, Indices, 2);
1411 return getCast(Instruction::PtrToInt, GEP,
1412 Type::getInt32Ty(Ty->getContext()));
1415 Constant* ConstantExpr::getOffsetOf(const StructType* STy, unsigned FieldNo) {
1416 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1417 // Note that a non-inbounds gep is used, as null isn't within any object.
1418 Constant *GEPIdx[] = {
1419 ConstantInt::get(Type::getInt64Ty(STy->getContext()), 0),
1420 ConstantInt::get(Type::getInt32Ty(STy->getContext()), FieldNo)
1422 Constant *GEP = getGetElementPtr(
1423 Constant::getNullValue(PointerType::getUnqual(STy)), GEPIdx, 2);
1424 return getCast(Instruction::PtrToInt, GEP,
1425 Type::getInt64Ty(STy->getContext()));
1428 Constant *ConstantExpr::getCompare(unsigned short pred,
1429 Constant *C1, Constant *C2) {
1430 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1431 return getCompareTy(pred, C1, C2);
1434 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1435 Constant *V1, Constant *V2) {
1436 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1438 if (ReqTy == V1->getType())
1439 if (Constant *SC = ConstantFoldSelectInstruction(
1440 ReqTy->getContext(), C, V1, V2))
1441 return SC; // Fold common cases
1443 std::vector<Constant*> argVec(3, C);
1446 ExprMapKeyType Key(Instruction::Select, argVec);
1448 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1450 // Implicitly locked.
1451 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1454 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1457 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
1459 cast<PointerType>(ReqTy)->getElementType() &&
1460 "GEP indices invalid!");
1462 if (Constant *FC = ConstantFoldGetElementPtr(
1463 ReqTy->getContext(), C, (Constant**)Idxs, NumIdx))
1464 return FC; // Fold a few common cases...
1466 assert(isa<PointerType>(C->getType()) &&
1467 "Non-pointer type for constant GetElementPtr expression");
1468 // Look up the constant in the table first to ensure uniqueness
1469 std::vector<Constant*> ArgVec;
1470 ArgVec.reserve(NumIdx+1);
1471 ArgVec.push_back(C);
1472 for (unsigned i = 0; i != NumIdx; ++i)
1473 ArgVec.push_back(cast<Constant>(Idxs[i]));
1474 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
1476 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1478 // Implicitly locked.
1479 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1482 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1484 // Get the result type of the getelementptr!
1486 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
1487 assert(Ty && "GEP indices invalid!");
1488 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
1489 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
1492 Constant *ConstantExpr::getInBoundsGetElementPtr(Constant *C,
1495 Constant *Result = getGetElementPtr(C, Idxs, NumIdx);
1496 // Set in bounds attribute, assuming constant folding didn't eliminate the
1498 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Result))
1499 GEP->setIsInBounds(true);
1503 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1505 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1508 Constant *ConstantExpr::getInBoundsGetElementPtr(Constant *C,
1509 Constant* const *Idxs,
1511 return getInBoundsGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1515 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1516 assert(LHS->getType() == RHS->getType());
1517 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1518 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1520 if (Constant *FC = ConstantFoldCompareInstruction(
1521 LHS->getContext(), pred, LHS, RHS))
1522 return FC; // Fold a few common cases...
1524 // Look up the constant in the table first to ensure uniqueness
1525 std::vector<Constant*> ArgVec;
1526 ArgVec.push_back(LHS);
1527 ArgVec.push_back(RHS);
1528 // Get the key type with both the opcode and predicate
1529 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1531 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1533 // Implicitly locked.
1535 pImpl->ExprConstants.getOrCreate(Type::getInt1Ty(LHS->getContext()), Key);
1539 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1540 assert(LHS->getType() == RHS->getType());
1541 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1543 if (Constant *FC = ConstantFoldCompareInstruction(
1544 LHS->getContext(), pred, LHS, RHS))
1545 return FC; // Fold a few common cases...
1547 // Look up the constant in the table first to ensure uniqueness
1548 std::vector<Constant*> ArgVec;
1549 ArgVec.push_back(LHS);
1550 ArgVec.push_back(RHS);
1551 // Get the key type with both the opcode and predicate
1552 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1554 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1556 // Implicitly locked.
1558 pImpl->ExprConstants.getOrCreate(Type::getInt1Ty(LHS->getContext()), Key);
1561 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1563 if (Constant *FC = ConstantFoldExtractElementInstruction(
1564 ReqTy->getContext(), Val, Idx))
1565 return FC; // Fold a few common cases...
1566 // Look up the constant in the table first to ensure uniqueness
1567 std::vector<Constant*> ArgVec(1, Val);
1568 ArgVec.push_back(Idx);
1569 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1571 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1573 // Implicitly locked.
1574 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1577 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1578 assert(isa<VectorType>(Val->getType()) &&
1579 "Tried to create extractelement operation on non-vector type!");
1580 assert(Idx->getType() == Type::getInt32Ty(Val->getContext()) &&
1581 "Extractelement index must be i32 type!");
1582 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
1586 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1587 Constant *Elt, Constant *Idx) {
1588 if (Constant *FC = ConstantFoldInsertElementInstruction(
1589 ReqTy->getContext(), Val, Elt, Idx))
1590 return FC; // Fold a few common cases...
1591 // Look up the constant in the table first to ensure uniqueness
1592 std::vector<Constant*> ArgVec(1, Val);
1593 ArgVec.push_back(Elt);
1594 ArgVec.push_back(Idx);
1595 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1597 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1599 // Implicitly locked.
1600 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1603 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1605 assert(isa<VectorType>(Val->getType()) &&
1606 "Tried to create insertelement operation on non-vector type!");
1607 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
1608 && "Insertelement types must match!");
1609 assert(Idx->getType() == Type::getInt32Ty(Val->getContext()) &&
1610 "Insertelement index must be i32 type!");
1611 return getInsertElementTy(Val->getType(), Val, Elt, Idx);
1614 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1615 Constant *V2, Constant *Mask) {
1616 if (Constant *FC = ConstantFoldShuffleVectorInstruction(
1617 ReqTy->getContext(), V1, V2, Mask))
1618 return FC; // Fold a few common cases...
1619 // Look up the constant in the table first to ensure uniqueness
1620 std::vector<Constant*> ArgVec(1, V1);
1621 ArgVec.push_back(V2);
1622 ArgVec.push_back(Mask);
1623 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1625 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1627 // Implicitly locked.
1628 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1631 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1633 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1634 "Invalid shuffle vector constant expr operands!");
1636 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
1637 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
1638 const Type *ShufTy = VectorType::get(EltTy, NElts);
1639 return getShuffleVectorTy(ShufTy, V1, V2, Mask);
1642 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
1644 const unsigned *Idxs, unsigned NumIdx) {
1645 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1646 Idxs+NumIdx) == Val->getType() &&
1647 "insertvalue indices invalid!");
1648 assert(Agg->getType() == ReqTy &&
1649 "insertvalue type invalid!");
1650 assert(Agg->getType()->isFirstClassType() &&
1651 "Non-first-class type for constant InsertValue expression");
1652 Constant *FC = ConstantFoldInsertValueInstruction(
1653 ReqTy->getContext(), Agg, Val, Idxs, NumIdx);
1654 assert(FC && "InsertValue constant expr couldn't be folded!");
1658 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
1659 const unsigned *IdxList, unsigned NumIdx) {
1660 assert(Agg->getType()->isFirstClassType() &&
1661 "Tried to create insertelement operation on non-first-class type!");
1663 const Type *ReqTy = Agg->getType();
1666 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1668 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
1669 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
1672 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
1673 const unsigned *Idxs, unsigned NumIdx) {
1674 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1675 Idxs+NumIdx) == ReqTy &&
1676 "extractvalue indices invalid!");
1677 assert(Agg->getType()->isFirstClassType() &&
1678 "Non-first-class type for constant extractvalue expression");
1679 Constant *FC = ConstantFoldExtractValueInstruction(
1680 ReqTy->getContext(), Agg, Idxs, NumIdx);
1681 assert(FC && "ExtractValue constant expr couldn't be folded!");
1685 Constant *ConstantExpr::getExtractValue(Constant *Agg,
1686 const unsigned *IdxList, unsigned NumIdx) {
1687 assert(Agg->getType()->isFirstClassType() &&
1688 "Tried to create extractelement operation on non-first-class type!");
1691 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1692 assert(ReqTy && "extractvalue indices invalid!");
1693 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
1696 Constant* ConstantExpr::getNeg(Constant* C) {
1697 // API compatibility: Adjust integer opcodes to floating-point opcodes.
1698 if (C->getType()->isFPOrFPVector())
1700 assert(C->getType()->isIntOrIntVector() &&
1701 "Cannot NEG a nonintegral value!");
1702 return get(Instruction::Sub,
1703 ConstantFP::getZeroValueForNegation(C->getType()),
1707 Constant* ConstantExpr::getFNeg(Constant* C) {
1708 assert(C->getType()->isFPOrFPVector() &&
1709 "Cannot FNEG a non-floating-point value!");
1710 return get(Instruction::FSub,
1711 ConstantFP::getZeroValueForNegation(C->getType()),
1715 Constant* ConstantExpr::getNot(Constant* C) {
1716 assert(C->getType()->isIntOrIntVector() &&
1717 "Cannot NOT a nonintegral value!");
1718 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
1721 Constant* ConstantExpr::getAdd(Constant* C1, Constant* C2) {
1722 return get(Instruction::Add, C1, C2);
1725 Constant* ConstantExpr::getFAdd(Constant* C1, Constant* C2) {
1726 return get(Instruction::FAdd, C1, C2);
1729 Constant* ConstantExpr::getSub(Constant* C1, Constant* C2) {
1730 return get(Instruction::Sub, C1, C2);
1733 Constant* ConstantExpr::getFSub(Constant* C1, Constant* C2) {
1734 return get(Instruction::FSub, C1, C2);
1737 Constant* ConstantExpr::getMul(Constant* C1, Constant* C2) {
1738 return get(Instruction::Mul, C1, C2);
1741 Constant* ConstantExpr::getFMul(Constant* C1, Constant* C2) {
1742 return get(Instruction::FMul, C1, C2);
1745 Constant* ConstantExpr::getUDiv(Constant* C1, Constant* C2) {
1746 return get(Instruction::UDiv, C1, C2);
1749 Constant* ConstantExpr::getSDiv(Constant* C1, Constant* C2) {
1750 return get(Instruction::SDiv, C1, C2);
1753 Constant* ConstantExpr::getFDiv(Constant* C1, Constant* C2) {
1754 return get(Instruction::FDiv, C1, C2);
1757 Constant* ConstantExpr::getURem(Constant* C1, Constant* C2) {
1758 return get(Instruction::URem, C1, C2);
1761 Constant* ConstantExpr::getSRem(Constant* C1, Constant* C2) {
1762 return get(Instruction::SRem, C1, C2);
1765 Constant* ConstantExpr::getFRem(Constant* C1, Constant* C2) {
1766 return get(Instruction::FRem, C1, C2);
1769 Constant* ConstantExpr::getAnd(Constant* C1, Constant* C2) {
1770 return get(Instruction::And, C1, C2);
1773 Constant* ConstantExpr::getOr(Constant* C1, Constant* C2) {
1774 return get(Instruction::Or, C1, C2);
1777 Constant* ConstantExpr::getXor(Constant* C1, Constant* C2) {
1778 return get(Instruction::Xor, C1, C2);
1781 Constant* ConstantExpr::getShl(Constant* C1, Constant* C2) {
1782 return get(Instruction::Shl, C1, C2);
1785 Constant* ConstantExpr::getLShr(Constant* C1, Constant* C2) {
1786 return get(Instruction::LShr, C1, C2);
1789 Constant* ConstantExpr::getAShr(Constant* C1, Constant* C2) {
1790 return get(Instruction::AShr, C1, C2);
1793 // destroyConstant - Remove the constant from the constant table...
1795 void ConstantExpr::destroyConstant() {
1796 // Implicitly locked.
1797 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
1798 pImpl->ExprConstants.remove(this);
1799 destroyConstantImpl();
1802 const char *ConstantExpr::getOpcodeName() const {
1803 return Instruction::getOpcodeName(getOpcode());
1806 //===----------------------------------------------------------------------===//
1807 // replaceUsesOfWithOnConstant implementations
1809 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
1810 /// 'From' to be uses of 'To'. This must update the uniquing data structures
1813 /// Note that we intentionally replace all uses of From with To here. Consider
1814 /// a large array that uses 'From' 1000 times. By handling this case all here,
1815 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
1816 /// single invocation handles all 1000 uses. Handling them one at a time would
1817 /// work, but would be really slow because it would have to unique each updated
1820 static std::vector<Constant*> getValType(ConstantArray *CA) {
1821 std::vector<Constant*> Elements;
1822 Elements.reserve(CA->getNumOperands());
1823 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1824 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1829 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1831 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1832 Constant *ToC = cast<Constant>(To);
1834 LLVMContext &Context = getType()->getContext();
1835 LLVMContextImpl *pImpl = Context.pImpl;
1837 std::pair<LLVMContextImpl::ArrayConstantsTy::MapKey, Constant*> Lookup;
1838 Lookup.first.first = getType();
1839 Lookup.second = this;
1841 std::vector<Constant*> &Values = Lookup.first.second;
1842 Values.reserve(getNumOperands()); // Build replacement array.
1844 // Fill values with the modified operands of the constant array. Also,
1845 // compute whether this turns into an all-zeros array.
1846 bool isAllZeros = false;
1847 unsigned NumUpdated = 0;
1848 if (!ToC->isNullValue()) {
1849 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1850 Constant *Val = cast<Constant>(O->get());
1855 Values.push_back(Val);
1859 for (Use *O = OperandList, *E = OperandList+getNumOperands();O != E; ++O) {
1860 Constant *Val = cast<Constant>(O->get());
1865 Values.push_back(Val);
1866 if (isAllZeros) isAllZeros = Val->isNullValue();
1870 Constant *Replacement = 0;
1872 Replacement = ConstantAggregateZero::get(getType());
1874 // Check to see if we have this array type already.
1875 sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
1877 LLVMContextImpl::ArrayConstantsTy::MapTy::iterator I =
1878 pImpl->ArrayConstants.InsertOrGetItem(Lookup, Exists);
1881 Replacement = cast<Constant>(I->second);
1883 // Okay, the new shape doesn't exist in the system yet. Instead of
1884 // creating a new constant array, inserting it, replaceallusesof'ing the
1885 // old with the new, then deleting the old... just update the current one
1887 pImpl->ArrayConstants.MoveConstantToNewSlot(this, I);
1889 // Update to the new value. Optimize for the case when we have a single
1890 // operand that we're changing, but handle bulk updates efficiently.
1891 if (NumUpdated == 1) {
1892 unsigned OperandToUpdate = U - OperandList;
1893 assert(getOperand(OperandToUpdate) == From &&
1894 "ReplaceAllUsesWith broken!");
1895 setOperand(OperandToUpdate, ToC);
1897 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1898 if (getOperand(i) == From)
1905 // Otherwise, I do need to replace this with an existing value.
1906 assert(Replacement != this && "I didn't contain From!");
1908 // Everyone using this now uses the replacement.
1909 uncheckedReplaceAllUsesWith(Replacement);
1911 // Delete the old constant!
1915 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1916 std::vector<Constant*> Elements;
1917 Elements.reserve(CS->getNumOperands());
1918 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1919 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1923 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
1925 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1926 Constant *ToC = cast<Constant>(To);
1928 unsigned OperandToUpdate = U-OperandList;
1929 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1931 std::pair<LLVMContextImpl::StructConstantsTy::MapKey, Constant*> Lookup;
1932 Lookup.first.first = getType();
1933 Lookup.second = this;
1934 std::vector<Constant*> &Values = Lookup.first.second;
1935 Values.reserve(getNumOperands()); // Build replacement struct.
1938 // Fill values with the modified operands of the constant struct. Also,
1939 // compute whether this turns into an all-zeros struct.
1940 bool isAllZeros = false;
1941 if (!ToC->isNullValue()) {
1942 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
1943 Values.push_back(cast<Constant>(O->get()));
1946 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1947 Constant *Val = cast<Constant>(O->get());
1948 Values.push_back(Val);
1949 if (isAllZeros) isAllZeros = Val->isNullValue();
1952 Values[OperandToUpdate] = ToC;
1954 LLVMContext &Context = getType()->getContext();
1955 LLVMContextImpl *pImpl = Context.pImpl;
1957 Constant *Replacement = 0;
1959 Replacement = ConstantAggregateZero::get(getType());
1961 // Check to see if we have this array type already.
1962 sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
1964 LLVMContextImpl::StructConstantsTy::MapTy::iterator I =
1965 pImpl->StructConstants.InsertOrGetItem(Lookup, Exists);
1968 Replacement = cast<Constant>(I->second);
1970 // Okay, the new shape doesn't exist in the system yet. Instead of
1971 // creating a new constant struct, inserting it, replaceallusesof'ing the
1972 // old with the new, then deleting the old... just update the current one
1974 pImpl->StructConstants.MoveConstantToNewSlot(this, I);
1976 // Update to the new value.
1977 setOperand(OperandToUpdate, ToC);
1982 assert(Replacement != this && "I didn't contain From!");
1984 // Everyone using this now uses the replacement.
1985 uncheckedReplaceAllUsesWith(Replacement);
1987 // Delete the old constant!
1991 static std::vector<Constant*> getValType(ConstantVector *CP) {
1992 std::vector<Constant*> Elements;
1993 Elements.reserve(CP->getNumOperands());
1994 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1995 Elements.push_back(CP->getOperand(i));
1999 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2001 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2003 std::vector<Constant*> Values;
2004 Values.reserve(getNumOperands()); // Build replacement array...
2005 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2006 Constant *Val = getOperand(i);
2007 if (Val == From) Val = cast<Constant>(To);
2008 Values.push_back(Val);
2011 Constant *Replacement = get(getType(), Values);
2012 assert(Replacement != this && "I didn't contain From!");
2014 // Everyone using this now uses the replacement.
2015 uncheckedReplaceAllUsesWith(Replacement);
2017 // Delete the old constant!
2021 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2023 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2024 Constant *To = cast<Constant>(ToV);
2026 Constant *Replacement = 0;
2027 if (getOpcode() == Instruction::GetElementPtr) {
2028 SmallVector<Constant*, 8> Indices;
2029 Constant *Pointer = getOperand(0);
2030 Indices.reserve(getNumOperands()-1);
2031 if (Pointer == From) Pointer = To;
2033 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2034 Constant *Val = getOperand(i);
2035 if (Val == From) Val = To;
2036 Indices.push_back(Val);
2038 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2039 &Indices[0], Indices.size());
2040 } else if (getOpcode() == Instruction::ExtractValue) {
2041 Constant *Agg = getOperand(0);
2042 if (Agg == From) Agg = To;
2044 const SmallVector<unsigned, 4> &Indices = getIndices();
2045 Replacement = ConstantExpr::getExtractValue(Agg,
2046 &Indices[0], Indices.size());
2047 } else if (getOpcode() == Instruction::InsertValue) {
2048 Constant *Agg = getOperand(0);
2049 Constant *Val = getOperand(1);
2050 if (Agg == From) Agg = To;
2051 if (Val == From) Val = To;
2053 const SmallVector<unsigned, 4> &Indices = getIndices();
2054 Replacement = ConstantExpr::getInsertValue(Agg, Val,
2055 &Indices[0], Indices.size());
2056 } else if (isCast()) {
2057 assert(getOperand(0) == From && "Cast only has one use!");
2058 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2059 } else if (getOpcode() == Instruction::Select) {
2060 Constant *C1 = getOperand(0);
2061 Constant *C2 = getOperand(1);
2062 Constant *C3 = getOperand(2);
2063 if (C1 == From) C1 = To;
2064 if (C2 == From) C2 = To;
2065 if (C3 == From) C3 = To;
2066 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2067 } else if (getOpcode() == Instruction::ExtractElement) {
2068 Constant *C1 = getOperand(0);
2069 Constant *C2 = getOperand(1);
2070 if (C1 == From) C1 = To;
2071 if (C2 == From) C2 = To;
2072 Replacement = ConstantExpr::getExtractElement(C1, C2);
2073 } else if (getOpcode() == Instruction::InsertElement) {
2074 Constant *C1 = getOperand(0);
2075 Constant *C2 = getOperand(1);
2076 Constant *C3 = getOperand(1);
2077 if (C1 == From) C1 = To;
2078 if (C2 == From) C2 = To;
2079 if (C3 == From) C3 = To;
2080 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2081 } else if (getOpcode() == Instruction::ShuffleVector) {
2082 Constant *C1 = getOperand(0);
2083 Constant *C2 = getOperand(1);
2084 Constant *C3 = getOperand(2);
2085 if (C1 == From) C1 = To;
2086 if (C2 == From) C2 = To;
2087 if (C3 == From) C3 = To;
2088 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2089 } else if (isCompare()) {
2090 Constant *C1 = getOperand(0);
2091 Constant *C2 = getOperand(1);
2092 if (C1 == From) C1 = To;
2093 if (C2 == From) C2 = To;
2094 if (getOpcode() == Instruction::ICmp)
2095 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2097 assert(getOpcode() == Instruction::FCmp);
2098 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2100 } else if (getNumOperands() == 2) {
2101 Constant *C1 = getOperand(0);
2102 Constant *C2 = getOperand(1);
2103 if (C1 == From) C1 = To;
2104 if (C2 == From) C2 = To;
2105 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2107 llvm_unreachable("Unknown ConstantExpr type!");
2111 assert(Replacement != this && "I didn't contain From!");
2113 // Everyone using this now uses the replacement.
2114 uncheckedReplaceAllUsesWith(Replacement);
2116 // Delete the old constant!