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 = ConstantInt::get(IntegerType::get(1), 1));
239 ConstantInt* ConstantInt::getFalse(LLVMContext &Context) {
240 LLVMContextImpl *pImpl = Context.pImpl;
241 sys::SmartScopedWriter<true>(pImpl->ConstantsLock);
242 if (pImpl->TheFalseVal)
243 return pImpl->TheFalseVal;
245 return (pImpl->TheFalseVal = ConstantInt::get(IntegerType::get(1), 0));
249 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
250 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
251 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
252 // compare APInt's of different widths, which would violate an APInt class
253 // invariant which generates an assertion.
254 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt& V) {
255 // Get the corresponding integer type for the bit width of the value.
256 const IntegerType *ITy = IntegerType::get(V.getBitWidth());
257 // get an existing value or the insertion position
258 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
260 Context.pImpl->ConstantsLock.reader_acquire();
261 ConstantInt *&Slot = Context.pImpl->IntConstants[Key];
262 Context.pImpl->ConstantsLock.reader_release();
265 sys::SmartScopedWriter<true> Writer(Context.pImpl->ConstantsLock);
266 ConstantInt *&NewSlot = Context.pImpl->IntConstants[Key];
268 NewSlot = new ConstantInt(ITy, V);
277 Constant* ConstantInt::get(const Type* Ty, uint64_t V, bool isSigned) {
278 Constant *C = get(cast<IntegerType>(Ty->getScalarType()),
281 // For vectors, broadcast the value.
282 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
283 return ConstantVector::get(
284 std::vector<Constant *>(VTy->getNumElements(), C));
289 ConstantInt* ConstantInt::get(const IntegerType* Ty, uint64_t V,
291 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
294 ConstantInt* ConstantInt::getSigned(const IntegerType* Ty, int64_t V) {
295 return get(Ty, V, true);
298 Constant *ConstantInt::getSigned(const Type *Ty, int64_t V) {
299 return get(Ty, V, true);
302 Constant* ConstantInt::get(const Type* Ty, const APInt& V) {
303 ConstantInt *C = get(Ty->getContext(), V);
304 assert(C->getType() == Ty->getScalarType() &&
305 "ConstantInt type doesn't match the type implied by its value!");
307 // For vectors, broadcast the value.
308 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
309 return ConstantVector::get(
310 std::vector<Constant *>(VTy->getNumElements(), C));
315 //===----------------------------------------------------------------------===//
317 //===----------------------------------------------------------------------===//
319 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
320 if (Ty == Type::FloatTy)
321 return &APFloat::IEEEsingle;
322 if (Ty == Type::DoubleTy)
323 return &APFloat::IEEEdouble;
324 if (Ty == Type::X86_FP80Ty)
325 return &APFloat::x87DoubleExtended;
326 else if (Ty == Type::FP128Ty)
327 return &APFloat::IEEEquad;
329 assert(Ty == Type::PPC_FP128Ty && "Unknown FP format");
330 return &APFloat::PPCDoubleDouble;
333 /// get() - This returns a constant fp for the specified value in the
334 /// specified type. This should only be used for simple constant values like
335 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
336 Constant* ConstantFP::get(const Type* Ty, double V) {
337 LLVMContext &Context = Ty->getContext();
341 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
342 APFloat::rmNearestTiesToEven, &ignored);
343 Constant *C = get(Context, FV);
345 // For vectors, broadcast the value.
346 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
347 return ConstantVector::get(
348 std::vector<Constant *>(VTy->getNumElements(), C));
353 ConstantFP* ConstantFP::getNegativeZero(const Type* Ty) {
354 LLVMContext &Context = Ty->getContext();
355 APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
357 return get(Context, apf);
361 Constant* ConstantFP::getZeroValueForNegation(const Type* Ty) {
362 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
363 if (PTy->getElementType()->isFloatingPoint()) {
364 std::vector<Constant*> zeros(PTy->getNumElements(),
365 getNegativeZero(PTy->getElementType()));
366 return ConstantVector::get(PTy, zeros);
369 if (Ty->isFloatingPoint())
370 return getNegativeZero(Ty);
372 return Constant::getNullValue(Ty);
376 // ConstantFP accessors.
377 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
378 DenseMapAPFloatKeyInfo::KeyTy Key(V);
380 LLVMContextImpl* pImpl = Context.pImpl;
382 pImpl->ConstantsLock.reader_acquire();
383 ConstantFP *&Slot = pImpl->FPConstants[Key];
384 pImpl->ConstantsLock.reader_release();
387 sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
388 ConstantFP *&NewSlot = pImpl->FPConstants[Key];
391 if (&V.getSemantics() == &APFloat::IEEEsingle)
393 else if (&V.getSemantics() == &APFloat::IEEEdouble)
395 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
396 Ty = Type::X86_FP80Ty;
397 else if (&V.getSemantics() == &APFloat::IEEEquad)
400 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
401 "Unknown FP format");
402 Ty = Type::PPC_FP128Ty;
404 NewSlot = new ConstantFP(Ty, V);
413 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
414 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
415 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
419 bool ConstantFP::isNullValue() const {
420 return Val.isZero() && !Val.isNegative();
423 bool ConstantFP::isExactlyValue(const APFloat& V) const {
424 return Val.bitwiseIsEqual(V);
427 //===----------------------------------------------------------------------===//
428 // ConstantXXX Classes
429 //===----------------------------------------------------------------------===//
432 ConstantArray::ConstantArray(const ArrayType *T,
433 const std::vector<Constant*> &V)
434 : Constant(T, ConstantArrayVal,
435 OperandTraits<ConstantArray>::op_end(this) - V.size(),
437 assert(V.size() == T->getNumElements() &&
438 "Invalid initializer vector for constant array");
439 Use *OL = OperandList;
440 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
443 assert((C->getType() == T->getElementType() ||
445 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
446 "Initializer for array element doesn't match array element type!");
451 Constant *ConstantArray::get(const ArrayType *Ty,
452 const std::vector<Constant*> &V) {
453 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
454 // If this is an all-zero array, return a ConstantAggregateZero object
457 if (!C->isNullValue()) {
458 // Implicitly locked.
459 return pImpl->ArrayConstants.getOrCreate(Ty, V);
461 for (unsigned i = 1, e = V.size(); i != e; ++i)
463 // Implicitly locked.
464 return pImpl->ArrayConstants.getOrCreate(Ty, V);
468 return ConstantAggregateZero::get(Ty);
472 Constant* ConstantArray::get(const ArrayType* T, Constant* const* Vals,
474 // FIXME: make this the primary ctor method.
475 return get(T, std::vector<Constant*>(Vals, Vals+NumVals));
478 /// ConstantArray::get(const string&) - Return an array that is initialized to
479 /// contain the specified string. If length is zero then a null terminator is
480 /// added to the specified string so that it may be used in a natural way.
481 /// Otherwise, the length parameter specifies how much of the string to use
482 /// and it won't be null terminated.
484 Constant* ConstantArray::get(const StringRef &Str, bool AddNull) {
485 std::vector<Constant*> ElementVals;
486 for (unsigned i = 0; i < Str.size(); ++i)
487 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
489 // Add a null terminator to the string...
491 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
494 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
495 return get(ATy, ElementVals);
500 ConstantStruct::ConstantStruct(const StructType *T,
501 const std::vector<Constant*> &V)
502 : Constant(T, ConstantStructVal,
503 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
505 assert(V.size() == T->getNumElements() &&
506 "Invalid initializer vector for constant structure");
507 Use *OL = OperandList;
508 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
511 assert((C->getType() == T->getElementType(I-V.begin()) ||
512 ((T->getElementType(I-V.begin())->isAbstract() ||
513 C->getType()->isAbstract()) &&
514 T->getElementType(I-V.begin())->getTypeID() ==
515 C->getType()->getTypeID())) &&
516 "Initializer for struct element doesn't match struct element type!");
521 // ConstantStruct accessors.
522 Constant* ConstantStruct::get(const StructType* T,
523 const std::vector<Constant*>& V) {
524 LLVMContextImpl* pImpl = T->getContext().pImpl;
526 // Create a ConstantAggregateZero value if all elements are zeros...
527 for (unsigned i = 0, e = V.size(); i != e; ++i)
528 if (!V[i]->isNullValue())
529 // Implicitly locked.
530 return pImpl->StructConstants.getOrCreate(T, V);
532 return ConstantAggregateZero::get(T);
535 Constant* ConstantStruct::get(LLVMContext &Context,
536 const std::vector<Constant*>& V, bool packed) {
537 std::vector<const Type*> StructEls;
538 StructEls.reserve(V.size());
539 for (unsigned i = 0, e = V.size(); i != e; ++i)
540 StructEls.push_back(V[i]->getType());
541 return get(StructType::get(Context, StructEls, packed), V);
544 Constant* ConstantStruct::get(LLVMContext &Context,
545 Constant* const *Vals, unsigned NumVals,
547 // FIXME: make this the primary ctor method.
548 return get(Context, std::vector<Constant*>(Vals, Vals+NumVals), Packed);
551 ConstantVector::ConstantVector(const VectorType *T,
552 const std::vector<Constant*> &V)
553 : Constant(T, ConstantVectorVal,
554 OperandTraits<ConstantVector>::op_end(this) - V.size(),
556 Use *OL = OperandList;
557 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
560 assert((C->getType() == T->getElementType() ||
562 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
563 "Initializer for vector element doesn't match vector element type!");
568 // ConstantVector accessors.
569 Constant* ConstantVector::get(const VectorType* T,
570 const std::vector<Constant*>& V) {
571 assert(!V.empty() && "Vectors can't be empty");
572 LLVMContext &Context = T->getContext();
573 LLVMContextImpl *pImpl = Context.pImpl;
575 // If this is an all-undef or alll-zero vector, return a
576 // ConstantAggregateZero or UndefValue.
578 bool isZero = C->isNullValue();
579 bool isUndef = isa<UndefValue>(C);
581 if (isZero || isUndef) {
582 for (unsigned i = 1, e = V.size(); i != e; ++i)
584 isZero = isUndef = false;
590 return ConstantAggregateZero::get(T);
592 return UndefValue::get(T);
594 // Implicitly locked.
595 return pImpl->VectorConstants.getOrCreate(T, V);
598 Constant* ConstantVector::get(const std::vector<Constant*>& V) {
599 assert(!V.empty() && "Cannot infer type if V is empty");
600 return get(VectorType::get(V.front()->getType(),V.size()), V);
603 Constant* ConstantVector::get(Constant* const* Vals, unsigned NumVals) {
604 // FIXME: make this the primary ctor method.
605 return get(std::vector<Constant*>(Vals, Vals+NumVals));
608 Constant* ConstantExpr::getExactSDiv(Constant* C1, Constant* C2) {
609 Constant *C = getSDiv(C1, C2);
610 cast<SDivOperator>(C)->setIsExact(true);
614 // Utility function for determining if a ConstantExpr is a CastOp or not. This
615 // can't be inline because we don't want to #include Instruction.h into
617 bool ConstantExpr::isCast() const {
618 return Instruction::isCast(getOpcode());
621 bool ConstantExpr::isCompare() const {
622 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
625 bool ConstantExpr::hasIndices() const {
626 return getOpcode() == Instruction::ExtractValue ||
627 getOpcode() == Instruction::InsertValue;
630 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
631 if (const ExtractValueConstantExpr *EVCE =
632 dyn_cast<ExtractValueConstantExpr>(this))
633 return EVCE->Indices;
635 return cast<InsertValueConstantExpr>(this)->Indices;
638 unsigned ConstantExpr::getPredicate() const {
639 assert(getOpcode() == Instruction::FCmp ||
640 getOpcode() == Instruction::ICmp);
641 return ((const CompareConstantExpr*)this)->predicate;
644 /// getWithOperandReplaced - Return a constant expression identical to this
645 /// one, but with the specified operand set to the specified value.
647 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
648 assert(OpNo < getNumOperands() && "Operand num is out of range!");
649 assert(Op->getType() == getOperand(OpNo)->getType() &&
650 "Replacing operand with value of different type!");
651 if (getOperand(OpNo) == Op)
652 return const_cast<ConstantExpr*>(this);
654 Constant *Op0, *Op1, *Op2;
655 switch (getOpcode()) {
656 case Instruction::Trunc:
657 case Instruction::ZExt:
658 case Instruction::SExt:
659 case Instruction::FPTrunc:
660 case Instruction::FPExt:
661 case Instruction::UIToFP:
662 case Instruction::SIToFP:
663 case Instruction::FPToUI:
664 case Instruction::FPToSI:
665 case Instruction::PtrToInt:
666 case Instruction::IntToPtr:
667 case Instruction::BitCast:
668 return ConstantExpr::getCast(getOpcode(), Op, getType());
669 case Instruction::Select:
670 Op0 = (OpNo == 0) ? Op : getOperand(0);
671 Op1 = (OpNo == 1) ? Op : getOperand(1);
672 Op2 = (OpNo == 2) ? Op : getOperand(2);
673 return ConstantExpr::getSelect(Op0, Op1, Op2);
674 case Instruction::InsertElement:
675 Op0 = (OpNo == 0) ? Op : getOperand(0);
676 Op1 = (OpNo == 1) ? Op : getOperand(1);
677 Op2 = (OpNo == 2) ? Op : getOperand(2);
678 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
679 case Instruction::ExtractElement:
680 Op0 = (OpNo == 0) ? Op : getOperand(0);
681 Op1 = (OpNo == 1) ? Op : getOperand(1);
682 return ConstantExpr::getExtractElement(Op0, Op1);
683 case Instruction::ShuffleVector:
684 Op0 = (OpNo == 0) ? Op : getOperand(0);
685 Op1 = (OpNo == 1) ? Op : getOperand(1);
686 Op2 = (OpNo == 2) ? Op : getOperand(2);
687 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
688 case Instruction::GetElementPtr: {
689 SmallVector<Constant*, 8> Ops;
690 Ops.resize(getNumOperands()-1);
691 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
692 Ops[i-1] = getOperand(i);
694 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
696 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
699 assert(getNumOperands() == 2 && "Must be binary operator?");
700 Op0 = (OpNo == 0) ? Op : getOperand(0);
701 Op1 = (OpNo == 1) ? Op : getOperand(1);
702 return ConstantExpr::get(getOpcode(), Op0, Op1);
706 /// getWithOperands - This returns the current constant expression with the
707 /// operands replaced with the specified values. The specified operands must
708 /// match count and type with the existing ones.
709 Constant *ConstantExpr::
710 getWithOperands(Constant* const *Ops, unsigned NumOps) const {
711 assert(NumOps == getNumOperands() && "Operand count mismatch!");
712 bool AnyChange = false;
713 for (unsigned i = 0; i != NumOps; ++i) {
714 assert(Ops[i]->getType() == getOperand(i)->getType() &&
715 "Operand type mismatch!");
716 AnyChange |= Ops[i] != getOperand(i);
718 if (!AnyChange) // No operands changed, return self.
719 return const_cast<ConstantExpr*>(this);
721 switch (getOpcode()) {
722 case Instruction::Trunc:
723 case Instruction::ZExt:
724 case Instruction::SExt:
725 case Instruction::FPTrunc:
726 case Instruction::FPExt:
727 case Instruction::UIToFP:
728 case Instruction::SIToFP:
729 case Instruction::FPToUI:
730 case Instruction::FPToSI:
731 case Instruction::PtrToInt:
732 case Instruction::IntToPtr:
733 case Instruction::BitCast:
734 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
735 case Instruction::Select:
736 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
737 case Instruction::InsertElement:
738 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
739 case Instruction::ExtractElement:
740 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
741 case Instruction::ShuffleVector:
742 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
743 case Instruction::GetElementPtr:
744 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
745 case Instruction::ICmp:
746 case Instruction::FCmp:
747 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
749 assert(getNumOperands() == 2 && "Must be binary operator?");
750 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
755 //===----------------------------------------------------------------------===//
756 // isValueValidForType implementations
758 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
759 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
760 if (Ty == Type::Int1Ty)
761 return Val == 0 || Val == 1;
763 return true; // always true, has to fit in largest type
764 uint64_t Max = (1ll << NumBits) - 1;
768 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
769 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
770 if (Ty == Type::Int1Ty)
771 return Val == 0 || Val == 1 || Val == -1;
773 return true; // always true, has to fit in largest type
774 int64_t Min = -(1ll << (NumBits-1));
775 int64_t Max = (1ll << (NumBits-1)) - 1;
776 return (Val >= Min && Val <= Max);
779 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
780 // convert modifies in place, so make a copy.
781 APFloat Val2 = APFloat(Val);
783 switch (Ty->getTypeID()) {
785 return false; // These can't be represented as floating point!
787 // FIXME rounding mode needs to be more flexible
788 case Type::FloatTyID: {
789 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
791 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
794 case Type::DoubleTyID: {
795 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
796 &Val2.getSemantics() == &APFloat::IEEEdouble)
798 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
801 case Type::X86_FP80TyID:
802 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
803 &Val2.getSemantics() == &APFloat::IEEEdouble ||
804 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
805 case Type::FP128TyID:
806 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
807 &Val2.getSemantics() == &APFloat::IEEEdouble ||
808 &Val2.getSemantics() == &APFloat::IEEEquad;
809 case Type::PPC_FP128TyID:
810 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
811 &Val2.getSemantics() == &APFloat::IEEEdouble ||
812 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
816 //===----------------------------------------------------------------------===//
817 // Factory Function Implementation
819 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
821 ConstantAggregateZero* ConstantAggregateZero::get(const Type* Ty) {
822 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
823 "Cannot create an aggregate zero of non-aggregate type!");
825 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
826 // Implicitly locked.
827 return pImpl->AggZeroConstants.getOrCreate(Ty, 0);
830 /// destroyConstant - Remove the constant from the constant table...
832 void ConstantAggregateZero::destroyConstant() {
833 // Implicitly locked.
834 getType()->getContext().pImpl->AggZeroConstants.remove(this);
835 destroyConstantImpl();
838 /// destroyConstant - Remove the constant from the constant table...
840 void ConstantArray::destroyConstant() {
841 // Implicitly locked.
842 getType()->getContext().pImpl->ArrayConstants.remove(this);
843 destroyConstantImpl();
846 /// isString - This method returns true if the array is an array of i8, and
847 /// if the elements of the array are all ConstantInt's.
848 bool ConstantArray::isString() const {
849 // Check the element type for i8...
850 if (getType()->getElementType() != Type::Int8Ty)
852 // Check the elements to make sure they are all integers, not constant
854 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
855 if (!isa<ConstantInt>(getOperand(i)))
860 /// isCString - This method returns true if the array is a string (see
861 /// isString) and it ends in a null byte \\0 and does not contains any other
862 /// null bytes except its terminator.
863 bool ConstantArray::isCString() const {
864 // Check the element type for i8...
865 if (getType()->getElementType() != Type::Int8Ty)
868 // Last element must be a null.
869 if (!getOperand(getNumOperands()-1)->isNullValue())
871 // Other elements must be non-null integers.
872 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
873 if (!isa<ConstantInt>(getOperand(i)))
875 if (getOperand(i)->isNullValue())
882 /// getAsString - If the sub-element type of this array is i8
883 /// then this method converts the array to an std::string and returns it.
884 /// Otherwise, it asserts out.
886 std::string ConstantArray::getAsString() const {
887 assert(isString() && "Not a string!");
889 Result.reserve(getNumOperands());
890 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
891 Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
896 //---- ConstantStruct::get() implementation...
903 // destroyConstant - Remove the constant from the constant table...
905 void ConstantStruct::destroyConstant() {
906 // Implicitly locked.
907 getType()->getContext().pImpl->StructConstants.remove(this);
908 destroyConstantImpl();
911 // destroyConstant - Remove the constant from the constant table...
913 void ConstantVector::destroyConstant() {
914 // Implicitly locked.
915 getType()->getContext().pImpl->VectorConstants.remove(this);
916 destroyConstantImpl();
919 /// This function will return true iff every element in this vector constant
920 /// is set to all ones.
921 /// @returns true iff this constant's emements are all set to all ones.
922 /// @brief Determine if the value is all ones.
923 bool ConstantVector::isAllOnesValue() const {
924 // Check out first element.
925 const Constant *Elt = getOperand(0);
926 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
927 if (!CI || !CI->isAllOnesValue()) return false;
928 // Then make sure all remaining elements point to the same value.
929 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
930 if (getOperand(I) != Elt) return false;
935 /// getSplatValue - If this is a splat constant, where all of the
936 /// elements have the same value, return that value. Otherwise return null.
937 Constant *ConstantVector::getSplatValue() {
938 // Check out first element.
939 Constant *Elt = getOperand(0);
940 // Then make sure all remaining elements point to the same value.
941 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
942 if (getOperand(I) != Elt) return 0;
946 //---- ConstantPointerNull::get() implementation...
949 static char getValType(ConstantPointerNull *) {
954 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
955 // Implicitly locked.
956 return Ty->getContext().pImpl->NullPtrConstants.getOrCreate(Ty, 0);
959 // destroyConstant - Remove the constant from the constant table...
961 void ConstantPointerNull::destroyConstant() {
962 // Implicitly locked.
963 getType()->getContext().pImpl->NullPtrConstants.remove(this);
964 destroyConstantImpl();
968 //---- UndefValue::get() implementation...
971 static char getValType(UndefValue *) {
975 UndefValue *UndefValue::get(const Type *Ty) {
976 // Implicitly locked.
977 return Ty->getContext().pImpl->UndefValueConstants.getOrCreate(Ty, 0);
980 // destroyConstant - Remove the constant from the constant table.
982 void UndefValue::destroyConstant() {
983 // Implicitly locked.
984 getType()->getContext().pImpl->UndefValueConstants.remove(this);
985 destroyConstantImpl();
988 //---- ConstantExpr::get() implementations...
991 static ExprMapKeyType getValType(ConstantExpr *CE) {
992 std::vector<Constant*> Operands;
993 Operands.reserve(CE->getNumOperands());
994 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
995 Operands.push_back(cast<Constant>(CE->getOperand(i)));
996 return ExprMapKeyType(CE->getOpcode(), Operands,
997 CE->isCompare() ? CE->getPredicate() : 0,
999 CE->getIndices() : SmallVector<unsigned, 4>());
1002 /// This is a utility function to handle folding of casts and lookup of the
1003 /// cast in the ExprConstants map. It is used by the various get* methods below.
1004 static inline Constant *getFoldedCast(
1005 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1006 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1007 // Fold a few common cases
1008 if (Constant *FC = ConstantFoldCastInstruction(Ty->getContext(), opc, C, Ty))
1011 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1013 // Look up the constant in the table first to ensure uniqueness
1014 std::vector<Constant*> argVec(1, C);
1015 ExprMapKeyType Key(opc, argVec);
1017 // Implicitly locked.
1018 return pImpl->ExprConstants.getOrCreate(Ty, Key);
1021 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1022 Instruction::CastOps opc = Instruction::CastOps(oc);
1023 assert(Instruction::isCast(opc) && "opcode out of range");
1024 assert(C && Ty && "Null arguments to getCast");
1025 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1029 llvm_unreachable("Invalid cast opcode");
1031 case Instruction::Trunc: return getTrunc(C, Ty);
1032 case Instruction::ZExt: return getZExt(C, Ty);
1033 case Instruction::SExt: return getSExt(C, Ty);
1034 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1035 case Instruction::FPExt: return getFPExtend(C, Ty);
1036 case Instruction::UIToFP: return getUIToFP(C, Ty);
1037 case Instruction::SIToFP: return getSIToFP(C, Ty);
1038 case Instruction::FPToUI: return getFPToUI(C, Ty);
1039 case Instruction::FPToSI: return getFPToSI(C, Ty);
1040 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1041 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1042 case Instruction::BitCast: return getBitCast(C, Ty);
1047 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1048 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1049 return getCast(Instruction::BitCast, C, Ty);
1050 return getCast(Instruction::ZExt, C, Ty);
1053 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1054 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1055 return getCast(Instruction::BitCast, C, Ty);
1056 return getCast(Instruction::SExt, C, Ty);
1059 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1060 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1061 return getCast(Instruction::BitCast, C, Ty);
1062 return getCast(Instruction::Trunc, C, Ty);
1065 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1066 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1067 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1069 if (Ty->isInteger())
1070 return getCast(Instruction::PtrToInt, S, Ty);
1071 return getCast(Instruction::BitCast, S, Ty);
1074 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1076 assert(C->getType()->isIntOrIntVector() &&
1077 Ty->isIntOrIntVector() && "Invalid cast");
1078 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1079 unsigned DstBits = Ty->getScalarSizeInBits();
1080 Instruction::CastOps opcode =
1081 (SrcBits == DstBits ? Instruction::BitCast :
1082 (SrcBits > DstBits ? Instruction::Trunc :
1083 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1084 return getCast(opcode, C, Ty);
1087 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1088 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1090 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1091 unsigned DstBits = Ty->getScalarSizeInBits();
1092 if (SrcBits == DstBits)
1093 return C; // Avoid a useless cast
1094 Instruction::CastOps opcode =
1095 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1096 return getCast(opcode, C, Ty);
1099 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1101 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1102 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1104 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1105 assert(C->getType()->isIntOrIntVector() && "Trunc operand must be integer");
1106 assert(Ty->isIntOrIntVector() && "Trunc produces only integral");
1107 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1108 "SrcTy must be larger than DestTy for Trunc!");
1110 return getFoldedCast(Instruction::Trunc, C, Ty);
1113 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1115 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1116 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1118 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1119 assert(C->getType()->isIntOrIntVector() && "SExt operand must be integral");
1120 assert(Ty->isIntOrIntVector() && "SExt produces only integer");
1121 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1122 "SrcTy must be smaller than DestTy for SExt!");
1124 return getFoldedCast(Instruction::SExt, C, Ty);
1127 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1129 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1130 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1132 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1133 assert(C->getType()->isIntOrIntVector() && "ZEXt operand must be integral");
1134 assert(Ty->isIntOrIntVector() && "ZExt produces only integer");
1135 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1136 "SrcTy must be smaller than DestTy for ZExt!");
1138 return getFoldedCast(Instruction::ZExt, C, Ty);
1141 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1143 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1144 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1146 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1147 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1148 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1149 "This is an illegal floating point truncation!");
1150 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1153 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1155 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1156 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1158 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1159 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1160 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1161 "This is an illegal floating point extension!");
1162 return getFoldedCast(Instruction::FPExt, C, Ty);
1165 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1167 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1168 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1170 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1171 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1172 "This is an illegal uint to floating point cast!");
1173 return getFoldedCast(Instruction::UIToFP, C, Ty);
1176 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1178 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1179 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1181 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1182 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1183 "This is an illegal sint to floating point cast!");
1184 return getFoldedCast(Instruction::SIToFP, C, Ty);
1187 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1189 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1190 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1192 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1193 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1194 "This is an illegal floating point to uint cast!");
1195 return getFoldedCast(Instruction::FPToUI, C, Ty);
1198 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1200 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1201 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1203 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1204 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1205 "This is an illegal floating point to sint cast!");
1206 return getFoldedCast(Instruction::FPToSI, C, Ty);
1209 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1210 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1211 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1212 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1215 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1216 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1217 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1218 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1221 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1222 // BitCast implies a no-op cast of type only. No bits change. However, you
1223 // can't cast pointers to anything but pointers.
1225 const Type *SrcTy = C->getType();
1226 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1227 "BitCast cannot cast pointer to non-pointer and vice versa");
1229 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1230 // or nonptr->ptr). For all the other types, the cast is okay if source and
1231 // destination bit widths are identical.
1232 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1233 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1235 assert(SrcBitSize == DstBitSize && "BitCast requires types of same width");
1237 // It is common to ask for a bitcast of a value to its own type, handle this
1239 if (C->getType() == DstTy) return C;
1241 return getFoldedCast(Instruction::BitCast, C, DstTy);
1244 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1245 Constant *C1, Constant *C2) {
1246 // Check the operands for consistency first
1247 assert(Opcode >= Instruction::BinaryOpsBegin &&
1248 Opcode < Instruction::BinaryOpsEnd &&
1249 "Invalid opcode in binary constant expression");
1250 assert(C1->getType() == C2->getType() &&
1251 "Operand types in binary constant expression should match");
1253 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
1254 if (Constant *FC = ConstantFoldBinaryInstruction(ReqTy->getContext(),
1256 return FC; // Fold a few common cases...
1258 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1259 ExprMapKeyType Key(Opcode, argVec);
1261 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1263 // Implicitly locked.
1264 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1267 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1268 Constant *C1, Constant *C2) {
1269 switch (predicate) {
1270 default: llvm_unreachable("Invalid CmpInst predicate");
1271 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1272 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1273 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1274 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1275 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1276 case CmpInst::FCMP_TRUE:
1277 return getFCmp(predicate, C1, C2);
1279 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1280 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1281 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1282 case CmpInst::ICMP_SLE:
1283 return getICmp(predicate, C1, C2);
1287 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1288 // API compatibility: Adjust integer opcodes to floating-point opcodes.
1289 if (C1->getType()->isFPOrFPVector()) {
1290 if (Opcode == Instruction::Add) Opcode = Instruction::FAdd;
1291 else if (Opcode == Instruction::Sub) Opcode = Instruction::FSub;
1292 else if (Opcode == Instruction::Mul) Opcode = Instruction::FMul;
1296 case Instruction::Add:
1297 case Instruction::Sub:
1298 case Instruction::Mul:
1299 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1300 assert(C1->getType()->isIntOrIntVector() &&
1301 "Tried to create an integer operation on a non-integer type!");
1303 case Instruction::FAdd:
1304 case Instruction::FSub:
1305 case Instruction::FMul:
1306 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1307 assert(C1->getType()->isFPOrFPVector() &&
1308 "Tried to create a floating-point operation on a "
1309 "non-floating-point type!");
1311 case Instruction::UDiv:
1312 case Instruction::SDiv:
1313 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1314 assert(C1->getType()->isIntOrIntVector() &&
1315 "Tried to create an arithmetic operation on a non-arithmetic type!");
1317 case Instruction::FDiv:
1318 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1319 assert(C1->getType()->isFPOrFPVector() &&
1320 "Tried to create an arithmetic operation on a non-arithmetic type!");
1322 case Instruction::URem:
1323 case Instruction::SRem:
1324 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1325 assert(C1->getType()->isIntOrIntVector() &&
1326 "Tried to create an arithmetic operation on a non-arithmetic type!");
1328 case Instruction::FRem:
1329 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1330 assert(C1->getType()->isFPOrFPVector() &&
1331 "Tried to create an arithmetic operation on a non-arithmetic type!");
1333 case Instruction::And:
1334 case Instruction::Or:
1335 case Instruction::Xor:
1336 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1337 assert(C1->getType()->isIntOrIntVector() &&
1338 "Tried to create a logical operation on a non-integral type!");
1340 case Instruction::Shl:
1341 case Instruction::LShr:
1342 case Instruction::AShr:
1343 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1344 assert(C1->getType()->isIntOrIntVector() &&
1345 "Tried to create a shift operation on a non-integer type!");
1352 return getTy(C1->getType(), Opcode, C1, C2);
1355 Constant* ConstantExpr::getSizeOf(const Type* Ty) {
1356 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1357 // Note that a non-inbounds gep is used, as null isn't within any object.
1358 Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
1359 Constant *GEP = getGetElementPtr(
1360 Constant::getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
1361 return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
1364 Constant* ConstantExpr::getAlignOf(const Type* Ty) {
1365 // alignof is implemented as: (i64) gep ({i8,Ty}*)null, 0, 1
1366 const Type *AligningTy = StructType::get(Ty->getContext(),
1367 Type::Int8Ty, Ty, NULL);
1368 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo());
1369 Constant *Zero = ConstantInt::get(Type::Int32Ty, 0);
1370 Constant *One = ConstantInt::get(Type::Int32Ty, 1);
1371 Constant *Indices[2] = { Zero, One };
1372 Constant *GEP = getGetElementPtr(NullPtr, Indices, 2);
1373 return getCast(Instruction::PtrToInt, GEP, Type::Int32Ty);
1377 Constant *ConstantExpr::getCompare(unsigned short pred,
1378 Constant *C1, Constant *C2) {
1379 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1380 return getCompareTy(pred, C1, C2);
1383 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1384 Constant *V1, Constant *V2) {
1385 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1387 if (ReqTy == V1->getType())
1388 if (Constant *SC = ConstantFoldSelectInstruction(
1389 ReqTy->getContext(), C, V1, V2))
1390 return SC; // Fold common cases
1392 std::vector<Constant*> argVec(3, C);
1395 ExprMapKeyType Key(Instruction::Select, argVec);
1397 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1399 // Implicitly locked.
1400 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1403 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1406 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
1408 cast<PointerType>(ReqTy)->getElementType() &&
1409 "GEP indices invalid!");
1411 if (Constant *FC = ConstantFoldGetElementPtr(
1412 ReqTy->getContext(), C, (Constant**)Idxs, NumIdx))
1413 return FC; // Fold a few common cases...
1415 assert(isa<PointerType>(C->getType()) &&
1416 "Non-pointer type for constant GetElementPtr expression");
1417 // Look up the constant in the table first to ensure uniqueness
1418 std::vector<Constant*> ArgVec;
1419 ArgVec.reserve(NumIdx+1);
1420 ArgVec.push_back(C);
1421 for (unsigned i = 0; i != NumIdx; ++i)
1422 ArgVec.push_back(cast<Constant>(Idxs[i]));
1423 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
1425 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1427 // Implicitly locked.
1428 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1431 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1433 // Get the result type of the getelementptr!
1435 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
1436 assert(Ty && "GEP indices invalid!");
1437 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
1438 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
1441 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1443 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1448 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1449 assert(LHS->getType() == RHS->getType());
1450 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1451 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1453 if (Constant *FC = ConstantFoldCompareInstruction(
1454 LHS->getContext(), pred, LHS, RHS))
1455 return FC; // Fold a few common cases...
1457 // Look up the constant in the table first to ensure uniqueness
1458 std::vector<Constant*> ArgVec;
1459 ArgVec.push_back(LHS);
1460 ArgVec.push_back(RHS);
1461 // Get the key type with both the opcode and predicate
1462 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1464 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1466 // Implicitly locked.
1467 return pImpl->ExprConstants.getOrCreate(Type::Int1Ty, Key);
1471 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1472 assert(LHS->getType() == RHS->getType());
1473 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1475 if (Constant *FC = ConstantFoldCompareInstruction(
1476 LHS->getContext(), pred, LHS, RHS))
1477 return FC; // Fold a few common cases...
1479 // Look up the constant in the table first to ensure uniqueness
1480 std::vector<Constant*> ArgVec;
1481 ArgVec.push_back(LHS);
1482 ArgVec.push_back(RHS);
1483 // Get the key type with both the opcode and predicate
1484 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1486 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1488 // Implicitly locked.
1489 return pImpl->ExprConstants.getOrCreate(Type::Int1Ty, Key);
1492 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1494 if (Constant *FC = ConstantFoldExtractElementInstruction(
1495 ReqTy->getContext(), Val, Idx))
1496 return FC; // Fold a few common cases...
1497 // Look up the constant in the table first to ensure uniqueness
1498 std::vector<Constant*> ArgVec(1, Val);
1499 ArgVec.push_back(Idx);
1500 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1502 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1504 // Implicitly locked.
1505 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1508 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1509 assert(isa<VectorType>(Val->getType()) &&
1510 "Tried to create extractelement operation on non-vector type!");
1511 assert(Idx->getType() == Type::Int32Ty &&
1512 "Extractelement index must be i32 type!");
1513 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
1517 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1518 Constant *Elt, Constant *Idx) {
1519 if (Constant *FC = ConstantFoldInsertElementInstruction(
1520 ReqTy->getContext(), Val, Elt, Idx))
1521 return FC; // Fold a few common cases...
1522 // Look up the constant in the table first to ensure uniqueness
1523 std::vector<Constant*> ArgVec(1, Val);
1524 ArgVec.push_back(Elt);
1525 ArgVec.push_back(Idx);
1526 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1528 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1530 // Implicitly locked.
1531 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1534 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1536 assert(isa<VectorType>(Val->getType()) &&
1537 "Tried to create insertelement operation on non-vector type!");
1538 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
1539 && "Insertelement types must match!");
1540 assert(Idx->getType() == Type::Int32Ty &&
1541 "Insertelement index must be i32 type!");
1542 return getInsertElementTy(Val->getType(), Val, Elt, Idx);
1545 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1546 Constant *V2, Constant *Mask) {
1547 if (Constant *FC = ConstantFoldShuffleVectorInstruction(
1548 ReqTy->getContext(), V1, V2, Mask))
1549 return FC; // Fold a few common cases...
1550 // Look up the constant in the table first to ensure uniqueness
1551 std::vector<Constant*> ArgVec(1, V1);
1552 ArgVec.push_back(V2);
1553 ArgVec.push_back(Mask);
1554 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1556 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1558 // Implicitly locked.
1559 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1562 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1564 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1565 "Invalid shuffle vector constant expr operands!");
1567 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
1568 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
1569 const Type *ShufTy = VectorType::get(EltTy, NElts);
1570 return getShuffleVectorTy(ShufTy, V1, V2, Mask);
1573 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
1575 const unsigned *Idxs, unsigned NumIdx) {
1576 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1577 Idxs+NumIdx) == Val->getType() &&
1578 "insertvalue indices invalid!");
1579 assert(Agg->getType() == ReqTy &&
1580 "insertvalue type invalid!");
1581 assert(Agg->getType()->isFirstClassType() &&
1582 "Non-first-class type for constant InsertValue expression");
1583 Constant *FC = ConstantFoldInsertValueInstruction(
1584 ReqTy->getContext(), Agg, Val, Idxs, NumIdx);
1585 assert(FC && "InsertValue constant expr couldn't be folded!");
1589 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
1590 const unsigned *IdxList, unsigned NumIdx) {
1591 assert(Agg->getType()->isFirstClassType() &&
1592 "Tried to create insertelement operation on non-first-class type!");
1594 const Type *ReqTy = Agg->getType();
1597 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1599 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
1600 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
1603 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
1604 const unsigned *Idxs, unsigned NumIdx) {
1605 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1606 Idxs+NumIdx) == ReqTy &&
1607 "extractvalue indices invalid!");
1608 assert(Agg->getType()->isFirstClassType() &&
1609 "Non-first-class type for constant extractvalue expression");
1610 Constant *FC = ConstantFoldExtractValueInstruction(
1611 ReqTy->getContext(), Agg, Idxs, NumIdx);
1612 assert(FC && "ExtractValue constant expr couldn't be folded!");
1616 Constant *ConstantExpr::getExtractValue(Constant *Agg,
1617 const unsigned *IdxList, unsigned NumIdx) {
1618 assert(Agg->getType()->isFirstClassType() &&
1619 "Tried to create extractelement operation on non-first-class type!");
1622 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1623 assert(ReqTy && "extractvalue indices invalid!");
1624 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
1627 Constant* ConstantExpr::getNeg(Constant* C) {
1628 // API compatibility: Adjust integer opcodes to floating-point opcodes.
1629 if (C->getType()->isFPOrFPVector())
1631 assert(C->getType()->isIntOrIntVector() &&
1632 "Cannot NEG a nonintegral value!");
1633 return get(Instruction::Sub,
1634 ConstantFP::getZeroValueForNegation(C->getType()),
1638 Constant* ConstantExpr::getFNeg(Constant* C) {
1639 assert(C->getType()->isFPOrFPVector() &&
1640 "Cannot FNEG a non-floating-point value!");
1641 return get(Instruction::FSub,
1642 ConstantFP::getZeroValueForNegation(C->getType()),
1646 Constant* ConstantExpr::getNot(Constant* C) {
1647 assert(C->getType()->isIntOrIntVector() &&
1648 "Cannot NOT a nonintegral value!");
1649 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
1652 Constant* ConstantExpr::getAdd(Constant* C1, Constant* C2) {
1653 return get(Instruction::Add, C1, C2);
1656 Constant* ConstantExpr::getFAdd(Constant* C1, Constant* C2) {
1657 return get(Instruction::FAdd, C1, C2);
1660 Constant* ConstantExpr::getSub(Constant* C1, Constant* C2) {
1661 return get(Instruction::Sub, C1, C2);
1664 Constant* ConstantExpr::getFSub(Constant* C1, Constant* C2) {
1665 return get(Instruction::FSub, C1, C2);
1668 Constant* ConstantExpr::getMul(Constant* C1, Constant* C2) {
1669 return get(Instruction::Mul, C1, C2);
1672 Constant* ConstantExpr::getFMul(Constant* C1, Constant* C2) {
1673 return get(Instruction::FMul, C1, C2);
1676 Constant* ConstantExpr::getUDiv(Constant* C1, Constant* C2) {
1677 return get(Instruction::UDiv, C1, C2);
1680 Constant* ConstantExpr::getSDiv(Constant* C1, Constant* C2) {
1681 return get(Instruction::SDiv, C1, C2);
1684 Constant* ConstantExpr::getFDiv(Constant* C1, Constant* C2) {
1685 return get(Instruction::FDiv, C1, C2);
1688 Constant* ConstantExpr::getURem(Constant* C1, Constant* C2) {
1689 return get(Instruction::URem, C1, C2);
1692 Constant* ConstantExpr::getSRem(Constant* C1, Constant* C2) {
1693 return get(Instruction::SRem, C1, C2);
1696 Constant* ConstantExpr::getFRem(Constant* C1, Constant* C2) {
1697 return get(Instruction::FRem, C1, C2);
1700 Constant* ConstantExpr::getAnd(Constant* C1, Constant* C2) {
1701 return get(Instruction::And, C1, C2);
1704 Constant* ConstantExpr::getOr(Constant* C1, Constant* C2) {
1705 return get(Instruction::Or, C1, C2);
1708 Constant* ConstantExpr::getXor(Constant* C1, Constant* C2) {
1709 return get(Instruction::Xor, C1, C2);
1712 Constant* ConstantExpr::getShl(Constant* C1, Constant* C2) {
1713 return get(Instruction::Shl, C1, C2);
1716 Constant* ConstantExpr::getLShr(Constant* C1, Constant* C2) {
1717 return get(Instruction::LShr, C1, C2);
1720 Constant* ConstantExpr::getAShr(Constant* C1, Constant* C2) {
1721 return get(Instruction::AShr, C1, C2);
1724 // destroyConstant - Remove the constant from the constant table...
1726 void ConstantExpr::destroyConstant() {
1727 // Implicitly locked.
1728 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
1729 pImpl->ExprConstants.remove(this);
1730 destroyConstantImpl();
1733 const char *ConstantExpr::getOpcodeName() const {
1734 return Instruction::getOpcodeName(getOpcode());
1737 //===----------------------------------------------------------------------===//
1738 // replaceUsesOfWithOnConstant implementations
1740 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
1741 /// 'From' to be uses of 'To'. This must update the uniquing data structures
1744 /// Note that we intentionally replace all uses of From with To here. Consider
1745 /// a large array that uses 'From' 1000 times. By handling this case all here,
1746 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
1747 /// single invocation handles all 1000 uses. Handling them one at a time would
1748 /// work, but would be really slow because it would have to unique each updated
1751 static std::vector<Constant*> getValType(ConstantArray *CA) {
1752 std::vector<Constant*> Elements;
1753 Elements.reserve(CA->getNumOperands());
1754 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1755 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1760 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1762 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1763 Constant *ToC = cast<Constant>(To);
1765 LLVMContext &Context = getType()->getContext();
1766 LLVMContextImpl *pImpl = Context.pImpl;
1768 std::pair<LLVMContextImpl::ArrayConstantsTy::MapKey, Constant*> Lookup;
1769 Lookup.first.first = getType();
1770 Lookup.second = this;
1772 std::vector<Constant*> &Values = Lookup.first.second;
1773 Values.reserve(getNumOperands()); // Build replacement array.
1775 // Fill values with the modified operands of the constant array. Also,
1776 // compute whether this turns into an all-zeros array.
1777 bool isAllZeros = false;
1778 unsigned NumUpdated = 0;
1779 if (!ToC->isNullValue()) {
1780 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1781 Constant *Val = cast<Constant>(O->get());
1786 Values.push_back(Val);
1790 for (Use *O = OperandList, *E = OperandList+getNumOperands();O != E; ++O) {
1791 Constant *Val = cast<Constant>(O->get());
1796 Values.push_back(Val);
1797 if (isAllZeros) isAllZeros = Val->isNullValue();
1801 Constant *Replacement = 0;
1803 Replacement = ConstantAggregateZero::get(getType());
1805 // Check to see if we have this array type already.
1806 sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
1808 LLVMContextImpl::ArrayConstantsTy::MapTy::iterator I =
1809 pImpl->ArrayConstants.InsertOrGetItem(Lookup, Exists);
1812 Replacement = cast<Constant>(I->second);
1814 // Okay, the new shape doesn't exist in the system yet. Instead of
1815 // creating a new constant array, inserting it, replaceallusesof'ing the
1816 // old with the new, then deleting the old... just update the current one
1818 pImpl->ArrayConstants.MoveConstantToNewSlot(this, I);
1820 // Update to the new value. Optimize for the case when we have a single
1821 // operand that we're changing, but handle bulk updates efficiently.
1822 if (NumUpdated == 1) {
1823 unsigned OperandToUpdate = U - OperandList;
1824 assert(getOperand(OperandToUpdate) == From &&
1825 "ReplaceAllUsesWith broken!");
1826 setOperand(OperandToUpdate, ToC);
1828 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1829 if (getOperand(i) == From)
1836 // Otherwise, I do need to replace this with an existing value.
1837 assert(Replacement != this && "I didn't contain From!");
1839 // Everyone using this now uses the replacement.
1840 uncheckedReplaceAllUsesWith(Replacement);
1842 // Delete the old constant!
1846 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1847 std::vector<Constant*> Elements;
1848 Elements.reserve(CS->getNumOperands());
1849 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1850 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1854 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
1856 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1857 Constant *ToC = cast<Constant>(To);
1859 unsigned OperandToUpdate = U-OperandList;
1860 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1862 std::pair<LLVMContextImpl::StructConstantsTy::MapKey, Constant*> Lookup;
1863 Lookup.first.first = getType();
1864 Lookup.second = this;
1865 std::vector<Constant*> &Values = Lookup.first.second;
1866 Values.reserve(getNumOperands()); // Build replacement struct.
1869 // Fill values with the modified operands of the constant struct. Also,
1870 // compute whether this turns into an all-zeros struct.
1871 bool isAllZeros = false;
1872 if (!ToC->isNullValue()) {
1873 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
1874 Values.push_back(cast<Constant>(O->get()));
1877 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1878 Constant *Val = cast<Constant>(O->get());
1879 Values.push_back(Val);
1880 if (isAllZeros) isAllZeros = Val->isNullValue();
1883 Values[OperandToUpdate] = ToC;
1885 LLVMContext &Context = getType()->getContext();
1886 LLVMContextImpl *pImpl = Context.pImpl;
1888 Constant *Replacement = 0;
1890 Replacement = ConstantAggregateZero::get(getType());
1892 // Check to see if we have this array type already.
1893 sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
1895 LLVMContextImpl::StructConstantsTy::MapTy::iterator I =
1896 pImpl->StructConstants.InsertOrGetItem(Lookup, Exists);
1899 Replacement = cast<Constant>(I->second);
1901 // Okay, the new shape doesn't exist in the system yet. Instead of
1902 // creating a new constant struct, inserting it, replaceallusesof'ing the
1903 // old with the new, then deleting the old... just update the current one
1905 pImpl->StructConstants.MoveConstantToNewSlot(this, I);
1907 // Update to the new value.
1908 setOperand(OperandToUpdate, ToC);
1913 assert(Replacement != this && "I didn't contain From!");
1915 // Everyone using this now uses the replacement.
1916 uncheckedReplaceAllUsesWith(Replacement);
1918 // Delete the old constant!
1922 static std::vector<Constant*> getValType(ConstantVector *CP) {
1923 std::vector<Constant*> Elements;
1924 Elements.reserve(CP->getNumOperands());
1925 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1926 Elements.push_back(CP->getOperand(i));
1930 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
1932 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1934 std::vector<Constant*> Values;
1935 Values.reserve(getNumOperands()); // Build replacement array...
1936 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1937 Constant *Val = getOperand(i);
1938 if (Val == From) Val = cast<Constant>(To);
1939 Values.push_back(Val);
1942 Constant *Replacement = get(getType(), Values);
1943 assert(Replacement != this && "I didn't contain From!");
1945 // Everyone using this now uses the replacement.
1946 uncheckedReplaceAllUsesWith(Replacement);
1948 // Delete the old constant!
1952 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
1954 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
1955 Constant *To = cast<Constant>(ToV);
1957 Constant *Replacement = 0;
1958 if (getOpcode() == Instruction::GetElementPtr) {
1959 SmallVector<Constant*, 8> Indices;
1960 Constant *Pointer = getOperand(0);
1961 Indices.reserve(getNumOperands()-1);
1962 if (Pointer == From) Pointer = To;
1964 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1965 Constant *Val = getOperand(i);
1966 if (Val == From) Val = To;
1967 Indices.push_back(Val);
1969 Replacement = ConstantExpr::getGetElementPtr(Pointer,
1970 &Indices[0], Indices.size());
1971 } else if (getOpcode() == Instruction::ExtractValue) {
1972 Constant *Agg = getOperand(0);
1973 if (Agg == From) Agg = To;
1975 const SmallVector<unsigned, 4> &Indices = getIndices();
1976 Replacement = ConstantExpr::getExtractValue(Agg,
1977 &Indices[0], Indices.size());
1978 } else if (getOpcode() == Instruction::InsertValue) {
1979 Constant *Agg = getOperand(0);
1980 Constant *Val = getOperand(1);
1981 if (Agg == From) Agg = To;
1982 if (Val == From) Val = To;
1984 const SmallVector<unsigned, 4> &Indices = getIndices();
1985 Replacement = ConstantExpr::getInsertValue(Agg, Val,
1986 &Indices[0], Indices.size());
1987 } else if (isCast()) {
1988 assert(getOperand(0) == From && "Cast only has one use!");
1989 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
1990 } else if (getOpcode() == Instruction::Select) {
1991 Constant *C1 = getOperand(0);
1992 Constant *C2 = getOperand(1);
1993 Constant *C3 = getOperand(2);
1994 if (C1 == From) C1 = To;
1995 if (C2 == From) C2 = To;
1996 if (C3 == From) C3 = To;
1997 Replacement = ConstantExpr::getSelect(C1, C2, C3);
1998 } else if (getOpcode() == Instruction::ExtractElement) {
1999 Constant *C1 = getOperand(0);
2000 Constant *C2 = getOperand(1);
2001 if (C1 == From) C1 = To;
2002 if (C2 == From) C2 = To;
2003 Replacement = ConstantExpr::getExtractElement(C1, C2);
2004 } else if (getOpcode() == Instruction::InsertElement) {
2005 Constant *C1 = getOperand(0);
2006 Constant *C2 = getOperand(1);
2007 Constant *C3 = getOperand(1);
2008 if (C1 == From) C1 = To;
2009 if (C2 == From) C2 = To;
2010 if (C3 == From) C3 = To;
2011 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2012 } else if (getOpcode() == Instruction::ShuffleVector) {
2013 Constant *C1 = getOperand(0);
2014 Constant *C2 = getOperand(1);
2015 Constant *C3 = getOperand(2);
2016 if (C1 == From) C1 = To;
2017 if (C2 == From) C2 = To;
2018 if (C3 == From) C3 = To;
2019 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2020 } else if (isCompare()) {
2021 Constant *C1 = getOperand(0);
2022 Constant *C2 = getOperand(1);
2023 if (C1 == From) C1 = To;
2024 if (C2 == From) C2 = To;
2025 if (getOpcode() == Instruction::ICmp)
2026 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2028 assert(getOpcode() == Instruction::FCmp);
2029 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2031 } else if (getNumOperands() == 2) {
2032 Constant *C1 = getOperand(0);
2033 Constant *C2 = getOperand(1);
2034 if (C1 == From) C1 = To;
2035 if (C2 == From) C2 = To;
2036 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2038 llvm_unreachable("Unknown ConstantExpr type!");
2042 assert(Replacement != this && "I didn't contain From!");
2044 // Everyone using this now uses the replacement.
2045 uncheckedReplaceAllUsesWith(Replacement);
2047 // Delete the old constant!