1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Constant* classes...
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Constants.h"
15 #include "LLVMContextImpl.h"
16 #include "ConstantFold.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/GlobalValue.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Module.h"
21 #include "llvm/Operator.h"
22 #include "llvm/ADT/FoldingSet.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/StringMap.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/MathExtras.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/System/Mutex.h"
32 #include "llvm/System/RWMutex.h"
33 #include "llvm/System/Threading.h"
34 #include "llvm/ADT/DenseMap.h"
35 #include "llvm/ADT/SmallVector.h"
40 //===----------------------------------------------------------------------===//
42 //===----------------------------------------------------------------------===//
44 // Constructor to create a '0' constant of arbitrary type...
45 static const uint64_t zero[2] = {0, 0};
46 Constant* Constant::getNullValue(const Type* Ty) {
47 switch (Ty->getTypeID()) {
48 case Type::IntegerTyID:
49 return ConstantInt::get(Ty, 0);
51 return ConstantFP::get(Ty->getContext(), APFloat(APInt(32, 0)));
52 case Type::DoubleTyID:
53 return ConstantFP::get(Ty->getContext(), APFloat(APInt(64, 0)));
54 case Type::X86_FP80TyID:
55 return ConstantFP::get(Ty->getContext(), APFloat(APInt(80, 2, zero)));
57 return ConstantFP::get(Ty->getContext(),
58 APFloat(APInt(128, 2, zero), true));
59 case Type::PPC_FP128TyID:
60 return ConstantFP::get(Ty->getContext(), APFloat(APInt(128, 2, zero)));
61 case Type::PointerTyID:
62 return ConstantPointerNull::get(cast<PointerType>(Ty));
63 case Type::StructTyID:
65 case Type::VectorTyID:
66 return ConstantAggregateZero::get(Ty);
68 // Function, Label, or Opaque type?
69 assert(!"Cannot create a null constant of that type!");
74 Constant* Constant::getIntegerValue(const Type* Ty, const APInt &V) {
75 const Type *ScalarTy = Ty->getScalarType();
77 // Create the base integer constant.
78 Constant *C = ConstantInt::get(Ty->getContext(), V);
80 // Convert an integer to a pointer, if necessary.
81 if (const PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
82 C = ConstantExpr::getIntToPtr(C, PTy);
84 // Broadcast a scalar to a vector, if necessary.
85 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
86 C = ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
91 Constant* Constant::getAllOnesValue(const Type* Ty) {
92 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
93 return ConstantInt::get(Ty->getContext(),
94 APInt::getAllOnesValue(ITy->getBitWidth()));
96 std::vector<Constant*> Elts;
97 const VectorType* VTy = cast<VectorType>(Ty);
98 Elts.resize(VTy->getNumElements(), getAllOnesValue(VTy->getElementType()));
99 assert(Elts[0] && "Not a vector integer type!");
100 return cast<ConstantVector>(ConstantVector::get(Elts));
103 void Constant::destroyConstantImpl() {
104 // When a Constant is destroyed, there may be lingering
105 // references to the constant by other constants in the constant pool. These
106 // constants are implicitly dependent on the module that is being deleted,
107 // but they don't know that. Because we only find out when the CPV is
108 // deleted, we must now notify all of our users (that should only be
109 // Constants) that they are, in fact, invalid now and should be deleted.
111 while (!use_empty()) {
112 Value *V = use_back();
113 #ifndef NDEBUG // Only in -g mode...
114 if (!isa<Constant>(V)) {
115 errs() << "While deleting: " << *this
116 << "\n\nUse still stuck around after Def is destroyed: "
120 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
121 Constant *CV = cast<Constant>(V);
122 CV->destroyConstant();
124 // The constant should remove itself from our use list...
125 assert((use_empty() || use_back() != V) && "Constant not removed!");
128 // Value has no outstanding references it is safe to delete it now...
132 /// canTrap - Return true if evaluation of this constant could trap. This is
133 /// true for things like constant expressions that could divide by zero.
134 bool Constant::canTrap() const {
135 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
136 // The only thing that could possibly trap are constant exprs.
137 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
138 if (!CE) return false;
140 // ConstantExpr traps if any operands can trap.
141 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
142 if (getOperand(i)->canTrap())
145 // Otherwise, only specific operations can trap.
146 switch (CE->getOpcode()) {
149 case Instruction::UDiv:
150 case Instruction::SDiv:
151 case Instruction::FDiv:
152 case Instruction::URem:
153 case Instruction::SRem:
154 case Instruction::FRem:
155 // Div and rem can trap if the RHS is not known to be non-zero.
156 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
163 /// getRelocationInfo - This method classifies the entry according to
164 /// whether or not it may generate a relocation entry. This must be
165 /// conservative, so if it might codegen to a relocatable entry, it should say
166 /// so. The return values are:
168 /// NoRelocation: This constant pool entry is guaranteed to never have a
169 /// relocation applied to it (because it holds a simple constant like
171 /// LocalRelocation: This entry has relocations, but the entries are
172 /// guaranteed to be resolvable by the static linker, so the dynamic
173 /// linker will never see them.
174 /// GlobalRelocations: This entry may have arbitrary relocations.
176 /// FIXME: This really should not be in VMCore.
177 Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
178 if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
179 if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
180 return LocalRelocation; // Local to this file/library.
181 return GlobalRelocations; // Global reference.
184 PossibleRelocationsTy Result = NoRelocation;
185 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
186 Result = std::max(Result, getOperand(i)->getRelocationInfo());
192 /// getVectorElements - This method, which is only valid on constant of vector
193 /// type, returns the elements of the vector in the specified smallvector.
194 /// This handles breaking down a vector undef into undef elements, etc. For
195 /// constant exprs and other cases we can't handle, we return an empty vector.
196 void Constant::getVectorElements(LLVMContext &Context,
197 SmallVectorImpl<Constant*> &Elts) const {
198 assert(isa<VectorType>(getType()) && "Not a vector constant!");
200 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
201 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
202 Elts.push_back(CV->getOperand(i));
206 const VectorType *VT = cast<VectorType>(getType());
207 if (isa<ConstantAggregateZero>(this)) {
208 Elts.assign(VT->getNumElements(),
209 Constant::getNullValue(VT->getElementType()));
213 if (isa<UndefValue>(this)) {
214 Elts.assign(VT->getNumElements(), UndefValue::get(VT->getElementType()));
218 // Unknown type, must be constant expr etc.
223 //===----------------------------------------------------------------------===//
225 //===----------------------------------------------------------------------===//
227 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
228 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
229 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
232 ConstantInt* ConstantInt::getTrue(LLVMContext &Context) {
233 LLVMContextImpl *pImpl = Context.pImpl;
234 sys::SmartScopedWriter<true>(pImpl->ConstantsLock);
235 if (pImpl->TheTrueVal)
236 return pImpl->TheTrueVal;
238 return (pImpl->TheTrueVal =
239 ConstantInt::get(IntegerType::get(Context, 1), 1));
242 ConstantInt* ConstantInt::getFalse(LLVMContext &Context) {
243 LLVMContextImpl *pImpl = Context.pImpl;
244 sys::SmartScopedWriter<true>(pImpl->ConstantsLock);
245 if (pImpl->TheFalseVal)
246 return pImpl->TheFalseVal;
248 return (pImpl->TheFalseVal =
249 ConstantInt::get(IntegerType::get(Context, 1), 0));
253 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
254 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
255 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
256 // compare APInt's of different widths, which would violate an APInt class
257 // invariant which generates an assertion.
258 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt& V) {
259 // Get the corresponding integer type for the bit width of the value.
260 const IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
261 // get an existing value or the insertion position
262 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
264 Context.pImpl->ConstantsLock.reader_acquire();
265 ConstantInt *&Slot = Context.pImpl->IntConstants[Key];
266 Context.pImpl->ConstantsLock.reader_release();
269 sys::SmartScopedWriter<true> Writer(Context.pImpl->ConstantsLock);
270 ConstantInt *&NewSlot = Context.pImpl->IntConstants[Key];
272 NewSlot = new ConstantInt(ITy, V);
281 Constant* ConstantInt::get(const Type* Ty, uint64_t V, bool isSigned) {
282 Constant *C = get(cast<IntegerType>(Ty->getScalarType()),
285 // For vectors, broadcast the value.
286 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
287 return ConstantVector::get(
288 std::vector<Constant *>(VTy->getNumElements(), C));
293 ConstantInt* ConstantInt::get(const IntegerType* Ty, uint64_t V,
295 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
298 ConstantInt* ConstantInt::getSigned(const IntegerType* Ty, int64_t V) {
299 return get(Ty, V, true);
302 Constant *ConstantInt::getSigned(const Type *Ty, int64_t V) {
303 return get(Ty, V, true);
306 Constant* ConstantInt::get(const Type* Ty, const APInt& V) {
307 ConstantInt *C = get(Ty->getContext(), V);
308 assert(C->getType() == Ty->getScalarType() &&
309 "ConstantInt type doesn't match the type implied by its value!");
311 // For vectors, broadcast the value.
312 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
313 return ConstantVector::get(
314 std::vector<Constant *>(VTy->getNumElements(), C));
319 ConstantInt* ConstantInt::get(const IntegerType* Ty, const StringRef& Str,
321 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
324 //===----------------------------------------------------------------------===//
326 //===----------------------------------------------------------------------===//
328 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
329 if (Ty == Type::getFloatTy(Ty->getContext()))
330 return &APFloat::IEEEsingle;
331 if (Ty == Type::getDoubleTy(Ty->getContext()))
332 return &APFloat::IEEEdouble;
333 if (Ty == Type::getX86_FP80Ty(Ty->getContext()))
334 return &APFloat::x87DoubleExtended;
335 else if (Ty == Type::getFP128Ty(Ty->getContext()))
336 return &APFloat::IEEEquad;
338 assert(Ty == Type::getPPC_FP128Ty(Ty->getContext()) && "Unknown FP format");
339 return &APFloat::PPCDoubleDouble;
342 /// get() - This returns a constant fp for the specified value in the
343 /// specified type. This should only be used for simple constant values like
344 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
345 Constant* ConstantFP::get(const Type* Ty, double V) {
346 LLVMContext &Context = Ty->getContext();
350 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
351 APFloat::rmNearestTiesToEven, &ignored);
352 Constant *C = get(Context, FV);
354 // For vectors, broadcast the value.
355 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
356 return ConstantVector::get(
357 std::vector<Constant *>(VTy->getNumElements(), C));
363 Constant* ConstantFP::get(const Type* Ty, const StringRef& Str) {
364 LLVMContext &Context = Ty->getContext();
366 APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
367 Constant *C = get(Context, FV);
369 // For vectors, broadcast the value.
370 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
371 return ConstantVector::get(
372 std::vector<Constant *>(VTy->getNumElements(), C));
378 ConstantFP* ConstantFP::getNegativeZero(const Type* Ty) {
379 LLVMContext &Context = Ty->getContext();
380 APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
382 return get(Context, apf);
386 Constant* ConstantFP::getZeroValueForNegation(const Type* Ty) {
387 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
388 if (PTy->getElementType()->isFloatingPoint()) {
389 std::vector<Constant*> zeros(PTy->getNumElements(),
390 getNegativeZero(PTy->getElementType()));
391 return ConstantVector::get(PTy, zeros);
394 if (Ty->isFloatingPoint())
395 return getNegativeZero(Ty);
397 return Constant::getNullValue(Ty);
401 // ConstantFP accessors.
402 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
403 DenseMapAPFloatKeyInfo::KeyTy Key(V);
405 LLVMContextImpl* pImpl = Context.pImpl;
407 pImpl->ConstantsLock.reader_acquire();
408 ConstantFP *&Slot = pImpl->FPConstants[Key];
409 pImpl->ConstantsLock.reader_release();
412 sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
413 ConstantFP *&NewSlot = pImpl->FPConstants[Key];
416 if (&V.getSemantics() == &APFloat::IEEEsingle)
417 Ty = Type::getFloatTy(Context);
418 else if (&V.getSemantics() == &APFloat::IEEEdouble)
419 Ty = Type::getDoubleTy(Context);
420 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
421 Ty = Type::getX86_FP80Ty(Context);
422 else if (&V.getSemantics() == &APFloat::IEEEquad)
423 Ty = Type::getFP128Ty(Context);
425 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
426 "Unknown FP format");
427 Ty = Type::getPPC_FP128Ty(Context);
429 NewSlot = new ConstantFP(Ty, V);
438 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
439 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
440 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
444 bool ConstantFP::isNullValue() const {
445 return Val.isZero() && !Val.isNegative();
448 bool ConstantFP::isExactlyValue(const APFloat& V) const {
449 return Val.bitwiseIsEqual(V);
452 //===----------------------------------------------------------------------===//
453 // ConstantXXX Classes
454 //===----------------------------------------------------------------------===//
457 ConstantArray::ConstantArray(const ArrayType *T,
458 const std::vector<Constant*> &V)
459 : Constant(T, ConstantArrayVal,
460 OperandTraits<ConstantArray>::op_end(this) - V.size(),
462 assert(V.size() == T->getNumElements() &&
463 "Invalid initializer vector for constant array");
464 Use *OL = OperandList;
465 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
468 assert((C->getType() == T->getElementType() ||
470 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
471 "Initializer for array element doesn't match array element type!");
476 Constant *ConstantArray::get(const ArrayType *Ty,
477 const std::vector<Constant*> &V) {
478 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
479 // If this is an all-zero array, return a ConstantAggregateZero object
482 if (!C->isNullValue()) {
483 // Implicitly locked.
484 return pImpl->ArrayConstants.getOrCreate(Ty, V);
486 for (unsigned i = 1, e = V.size(); i != e; ++i)
488 // Implicitly locked.
489 return pImpl->ArrayConstants.getOrCreate(Ty, V);
493 return ConstantAggregateZero::get(Ty);
497 Constant* ConstantArray::get(const ArrayType* T, Constant* const* Vals,
499 // FIXME: make this the primary ctor method.
500 return get(T, std::vector<Constant*>(Vals, Vals+NumVals));
503 /// ConstantArray::get(const string&) - Return an array that is initialized to
504 /// contain the specified string. If length is zero then a null terminator is
505 /// added to the specified string so that it may be used in a natural way.
506 /// Otherwise, the length parameter specifies how much of the string to use
507 /// and it won't be null terminated.
509 Constant* ConstantArray::get(LLVMContext &Context, const StringRef &Str,
511 std::vector<Constant*> ElementVals;
512 for (unsigned i = 0; i < Str.size(); ++i)
513 ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), Str[i]));
515 // Add a null terminator to the string...
517 ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), 0));
520 ArrayType *ATy = ArrayType::get(Type::getInt8Ty(Context), ElementVals.size());
521 return get(ATy, ElementVals);
526 ConstantStruct::ConstantStruct(const StructType *T,
527 const std::vector<Constant*> &V)
528 : Constant(T, ConstantStructVal,
529 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
531 assert(V.size() == T->getNumElements() &&
532 "Invalid initializer vector for constant structure");
533 Use *OL = OperandList;
534 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
537 assert((C->getType() == T->getElementType(I-V.begin()) ||
538 ((T->getElementType(I-V.begin())->isAbstract() ||
539 C->getType()->isAbstract()) &&
540 T->getElementType(I-V.begin())->getTypeID() ==
541 C->getType()->getTypeID())) &&
542 "Initializer for struct element doesn't match struct element type!");
547 // ConstantStruct accessors.
548 Constant* ConstantStruct::get(const StructType* T,
549 const std::vector<Constant*>& V) {
550 LLVMContextImpl* pImpl = T->getContext().pImpl;
552 // Create a ConstantAggregateZero value if all elements are zeros...
553 for (unsigned i = 0, e = V.size(); i != e; ++i)
554 if (!V[i]->isNullValue())
555 // Implicitly locked.
556 return pImpl->StructConstants.getOrCreate(T, V);
558 return ConstantAggregateZero::get(T);
561 Constant* ConstantStruct::get(LLVMContext &Context,
562 const std::vector<Constant*>& V, bool packed) {
563 std::vector<const Type*> StructEls;
564 StructEls.reserve(V.size());
565 for (unsigned i = 0, e = V.size(); i != e; ++i)
566 StructEls.push_back(V[i]->getType());
567 return get(StructType::get(Context, StructEls, packed), V);
570 Constant* ConstantStruct::get(LLVMContext &Context,
571 Constant* const *Vals, unsigned NumVals,
573 // FIXME: make this the primary ctor method.
574 return get(Context, std::vector<Constant*>(Vals, Vals+NumVals), Packed);
577 ConstantVector::ConstantVector(const VectorType *T,
578 const std::vector<Constant*> &V)
579 : Constant(T, ConstantVectorVal,
580 OperandTraits<ConstantVector>::op_end(this) - V.size(),
582 Use *OL = OperandList;
583 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
586 assert((C->getType() == T->getElementType() ||
588 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
589 "Initializer for vector element doesn't match vector element type!");
594 // ConstantVector accessors.
595 Constant* ConstantVector::get(const VectorType* T,
596 const std::vector<Constant*>& V) {
597 assert(!V.empty() && "Vectors can't be empty");
598 LLVMContext &Context = T->getContext();
599 LLVMContextImpl *pImpl = Context.pImpl;
601 // If this is an all-undef or alll-zero vector, return a
602 // ConstantAggregateZero or UndefValue.
604 bool isZero = C->isNullValue();
605 bool isUndef = isa<UndefValue>(C);
607 if (isZero || isUndef) {
608 for (unsigned i = 1, e = V.size(); i != e; ++i)
610 isZero = isUndef = false;
616 return ConstantAggregateZero::get(T);
618 return UndefValue::get(T);
620 // Implicitly locked.
621 return pImpl->VectorConstants.getOrCreate(T, V);
624 Constant* ConstantVector::get(const std::vector<Constant*>& V) {
625 assert(!V.empty() && "Cannot infer type if V is empty");
626 return get(VectorType::get(V.front()->getType(),V.size()), V);
629 Constant* ConstantVector::get(Constant* const* Vals, unsigned NumVals) {
630 // FIXME: make this the primary ctor method.
631 return get(std::vector<Constant*>(Vals, Vals+NumVals));
634 // Utility function for determining if a ConstantExpr is a CastOp or not. This
635 // can't be inline because we don't want to #include Instruction.h into
637 bool ConstantExpr::isCast() const {
638 return Instruction::isCast(getOpcode());
641 bool ConstantExpr::isCompare() const {
642 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
645 bool ConstantExpr::hasIndices() const {
646 return getOpcode() == Instruction::ExtractValue ||
647 getOpcode() == Instruction::InsertValue;
650 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
651 if (const ExtractValueConstantExpr *EVCE =
652 dyn_cast<ExtractValueConstantExpr>(this))
653 return EVCE->Indices;
655 return cast<InsertValueConstantExpr>(this)->Indices;
658 unsigned ConstantExpr::getPredicate() const {
659 assert(getOpcode() == Instruction::FCmp ||
660 getOpcode() == Instruction::ICmp);
661 return ((const CompareConstantExpr*)this)->predicate;
664 /// getWithOperandReplaced - Return a constant expression identical to this
665 /// one, but with the specified operand set to the specified value.
667 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
668 assert(OpNo < getNumOperands() && "Operand num is out of range!");
669 assert(Op->getType() == getOperand(OpNo)->getType() &&
670 "Replacing operand with value of different type!");
671 if (getOperand(OpNo) == Op)
672 return const_cast<ConstantExpr*>(this);
674 Constant *Op0, *Op1, *Op2;
675 switch (getOpcode()) {
676 case Instruction::Trunc:
677 case Instruction::ZExt:
678 case Instruction::SExt:
679 case Instruction::FPTrunc:
680 case Instruction::FPExt:
681 case Instruction::UIToFP:
682 case Instruction::SIToFP:
683 case Instruction::FPToUI:
684 case Instruction::FPToSI:
685 case Instruction::PtrToInt:
686 case Instruction::IntToPtr:
687 case Instruction::BitCast:
688 return ConstantExpr::getCast(getOpcode(), Op, getType());
689 case Instruction::Select:
690 Op0 = (OpNo == 0) ? Op : getOperand(0);
691 Op1 = (OpNo == 1) ? Op : getOperand(1);
692 Op2 = (OpNo == 2) ? Op : getOperand(2);
693 return ConstantExpr::getSelect(Op0, Op1, Op2);
694 case Instruction::InsertElement:
695 Op0 = (OpNo == 0) ? Op : getOperand(0);
696 Op1 = (OpNo == 1) ? Op : getOperand(1);
697 Op2 = (OpNo == 2) ? Op : getOperand(2);
698 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
699 case Instruction::ExtractElement:
700 Op0 = (OpNo == 0) ? Op : getOperand(0);
701 Op1 = (OpNo == 1) ? Op : getOperand(1);
702 return ConstantExpr::getExtractElement(Op0, Op1);
703 case Instruction::ShuffleVector:
704 Op0 = (OpNo == 0) ? Op : getOperand(0);
705 Op1 = (OpNo == 1) ? Op : getOperand(1);
706 Op2 = (OpNo == 2) ? Op : getOperand(2);
707 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
708 case Instruction::GetElementPtr: {
709 SmallVector<Constant*, 8> Ops;
710 Ops.resize(getNumOperands()-1);
711 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
712 Ops[i-1] = getOperand(i);
714 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
716 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
719 assert(getNumOperands() == 2 && "Must be binary operator?");
720 Op0 = (OpNo == 0) ? Op : getOperand(0);
721 Op1 = (OpNo == 1) ? Op : getOperand(1);
722 return ConstantExpr::get(getOpcode(), Op0, Op1);
726 /// getWithOperands - This returns the current constant expression with the
727 /// operands replaced with the specified values. The specified operands must
728 /// match count and type with the existing ones.
729 Constant *ConstantExpr::
730 getWithOperands(Constant* const *Ops, unsigned NumOps) const {
731 assert(NumOps == getNumOperands() && "Operand count mismatch!");
732 bool AnyChange = false;
733 for (unsigned i = 0; i != NumOps; ++i) {
734 assert(Ops[i]->getType() == getOperand(i)->getType() &&
735 "Operand type mismatch!");
736 AnyChange |= Ops[i] != getOperand(i);
738 if (!AnyChange) // No operands changed, return self.
739 return const_cast<ConstantExpr*>(this);
741 switch (getOpcode()) {
742 case Instruction::Trunc:
743 case Instruction::ZExt:
744 case Instruction::SExt:
745 case Instruction::FPTrunc:
746 case Instruction::FPExt:
747 case Instruction::UIToFP:
748 case Instruction::SIToFP:
749 case Instruction::FPToUI:
750 case Instruction::FPToSI:
751 case Instruction::PtrToInt:
752 case Instruction::IntToPtr:
753 case Instruction::BitCast:
754 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
755 case Instruction::Select:
756 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
757 case Instruction::InsertElement:
758 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
759 case Instruction::ExtractElement:
760 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
761 case Instruction::ShuffleVector:
762 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
763 case Instruction::GetElementPtr:
764 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
765 case Instruction::ICmp:
766 case Instruction::FCmp:
767 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
769 assert(getNumOperands() == 2 && "Must be binary operator?");
770 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
775 //===----------------------------------------------------------------------===//
776 // isValueValidForType implementations
778 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
779 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
780 if (Ty == Type::getInt1Ty(Ty->getContext()))
781 return Val == 0 || Val == 1;
783 return true; // always true, has to fit in largest type
784 uint64_t Max = (1ll << NumBits) - 1;
788 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
789 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
790 if (Ty == Type::getInt1Ty(Ty->getContext()))
791 return Val == 0 || Val == 1 || Val == -1;
793 return true; // always true, has to fit in largest type
794 int64_t Min = -(1ll << (NumBits-1));
795 int64_t Max = (1ll << (NumBits-1)) - 1;
796 return (Val >= Min && Val <= Max);
799 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
800 // convert modifies in place, so make a copy.
801 APFloat Val2 = APFloat(Val);
803 switch (Ty->getTypeID()) {
805 return false; // These can't be represented as floating point!
807 // FIXME rounding mode needs to be more flexible
808 case Type::FloatTyID: {
809 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
811 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
814 case Type::DoubleTyID: {
815 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
816 &Val2.getSemantics() == &APFloat::IEEEdouble)
818 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
821 case Type::X86_FP80TyID:
822 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
823 &Val2.getSemantics() == &APFloat::IEEEdouble ||
824 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
825 case Type::FP128TyID:
826 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
827 &Val2.getSemantics() == &APFloat::IEEEdouble ||
828 &Val2.getSemantics() == &APFloat::IEEEquad;
829 case Type::PPC_FP128TyID:
830 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
831 &Val2.getSemantics() == &APFloat::IEEEdouble ||
832 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
836 //===----------------------------------------------------------------------===//
837 // Factory Function Implementation
839 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
841 ConstantAggregateZero* ConstantAggregateZero::get(const Type* Ty) {
842 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
843 "Cannot create an aggregate zero of non-aggregate type!");
845 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
846 // Implicitly locked.
847 return pImpl->AggZeroConstants.getOrCreate(Ty, 0);
850 /// destroyConstant - Remove the constant from the constant table...
852 void ConstantAggregateZero::destroyConstant() {
853 // Implicitly locked.
854 getType()->getContext().pImpl->AggZeroConstants.remove(this);
855 destroyConstantImpl();
858 /// destroyConstant - Remove the constant from the constant table...
860 void ConstantArray::destroyConstant() {
861 // Implicitly locked.
862 getType()->getContext().pImpl->ArrayConstants.remove(this);
863 destroyConstantImpl();
866 /// isString - This method returns true if the array is an array of i8, and
867 /// if the elements of the array are all ConstantInt's.
868 bool ConstantArray::isString() const {
869 // Check the element type for i8...
870 if (getType()->getElementType() != Type::getInt8Ty(getContext()))
872 // Check the elements to make sure they are all integers, not constant
874 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
875 if (!isa<ConstantInt>(getOperand(i)))
880 /// isCString - This method returns true if the array is a string (see
881 /// isString) and it ends in a null byte \\0 and does not contains any other
882 /// null bytes except its terminator.
883 bool ConstantArray::isCString() const {
884 // Check the element type for i8...
885 if (getType()->getElementType() != Type::getInt8Ty(getContext()))
888 // Last element must be a null.
889 if (!getOperand(getNumOperands()-1)->isNullValue())
891 // Other elements must be non-null integers.
892 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
893 if (!isa<ConstantInt>(getOperand(i)))
895 if (getOperand(i)->isNullValue())
902 /// getAsString - If the sub-element type of this array is i8
903 /// then this method converts the array to an std::string and returns it.
904 /// Otherwise, it asserts out.
906 std::string ConstantArray::getAsString() const {
907 assert(isString() && "Not a string!");
909 Result.reserve(getNumOperands());
910 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
911 Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
916 //---- ConstantStruct::get() implementation...
923 // destroyConstant - Remove the constant from the constant table...
925 void ConstantStruct::destroyConstant() {
926 // Implicitly locked.
927 getType()->getContext().pImpl->StructConstants.remove(this);
928 destroyConstantImpl();
931 // destroyConstant - Remove the constant from the constant table...
933 void ConstantVector::destroyConstant() {
934 // Implicitly locked.
935 getType()->getContext().pImpl->VectorConstants.remove(this);
936 destroyConstantImpl();
939 /// This function will return true iff every element in this vector constant
940 /// is set to all ones.
941 /// @returns true iff this constant's emements are all set to all ones.
942 /// @brief Determine if the value is all ones.
943 bool ConstantVector::isAllOnesValue() const {
944 // Check out first element.
945 const Constant *Elt = getOperand(0);
946 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
947 if (!CI || !CI->isAllOnesValue()) return false;
948 // Then make sure all remaining elements point to the same value.
949 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
950 if (getOperand(I) != Elt) return false;
955 /// getSplatValue - If this is a splat constant, where all of the
956 /// elements have the same value, return that value. Otherwise return null.
957 Constant *ConstantVector::getSplatValue() {
958 // Check out first element.
959 Constant *Elt = getOperand(0);
960 // Then make sure all remaining elements point to the same value.
961 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
962 if (getOperand(I) != Elt) return 0;
966 //---- ConstantPointerNull::get() implementation...
969 static char getValType(ConstantPointerNull *) {
974 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
975 // Implicitly locked.
976 return Ty->getContext().pImpl->NullPtrConstants.getOrCreate(Ty, 0);
979 // destroyConstant - Remove the constant from the constant table...
981 void ConstantPointerNull::destroyConstant() {
982 // Implicitly locked.
983 getType()->getContext().pImpl->NullPtrConstants.remove(this);
984 destroyConstantImpl();
988 //---- UndefValue::get() implementation...
991 static char getValType(UndefValue *) {
995 UndefValue *UndefValue::get(const Type *Ty) {
996 // Implicitly locked.
997 return Ty->getContext().pImpl->UndefValueConstants.getOrCreate(Ty, 0);
1000 // destroyConstant - Remove the constant from the constant table.
1002 void UndefValue::destroyConstant() {
1003 // Implicitly locked.
1004 getType()->getContext().pImpl->UndefValueConstants.remove(this);
1005 destroyConstantImpl();
1008 //---- ConstantExpr::get() implementations...
1011 static ExprMapKeyType getValType(ConstantExpr *CE) {
1012 std::vector<Constant*> Operands;
1013 Operands.reserve(CE->getNumOperands());
1014 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1015 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1016 return ExprMapKeyType(CE->getOpcode(), Operands,
1017 CE->isCompare() ? CE->getPredicate() : 0,
1019 CE->getIndices() : SmallVector<unsigned, 4>());
1022 /// This is a utility function to handle folding of casts and lookup of the
1023 /// cast in the ExprConstants map. It is used by the various get* methods below.
1024 static inline Constant *getFoldedCast(
1025 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1026 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1027 // Fold a few common cases
1028 if (Constant *FC = ConstantFoldCastInstruction(Ty->getContext(), opc, C, Ty))
1031 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1033 // Look up the constant in the table first to ensure uniqueness
1034 std::vector<Constant*> argVec(1, C);
1035 ExprMapKeyType Key(opc, argVec);
1037 // Implicitly locked.
1038 return pImpl->ExprConstants.getOrCreate(Ty, Key);
1041 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1042 Instruction::CastOps opc = Instruction::CastOps(oc);
1043 assert(Instruction::isCast(opc) && "opcode out of range");
1044 assert(C && Ty && "Null arguments to getCast");
1045 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1049 llvm_unreachable("Invalid cast opcode");
1051 case Instruction::Trunc: return getTrunc(C, Ty);
1052 case Instruction::ZExt: return getZExt(C, Ty);
1053 case Instruction::SExt: return getSExt(C, Ty);
1054 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1055 case Instruction::FPExt: return getFPExtend(C, Ty);
1056 case Instruction::UIToFP: return getUIToFP(C, Ty);
1057 case Instruction::SIToFP: return getSIToFP(C, Ty);
1058 case Instruction::FPToUI: return getFPToUI(C, Ty);
1059 case Instruction::FPToSI: return getFPToSI(C, Ty);
1060 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1061 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1062 case Instruction::BitCast: return getBitCast(C, Ty);
1067 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1068 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1069 return getCast(Instruction::BitCast, C, Ty);
1070 return getCast(Instruction::ZExt, C, Ty);
1073 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1074 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1075 return getCast(Instruction::BitCast, C, Ty);
1076 return getCast(Instruction::SExt, C, Ty);
1079 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1080 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1081 return getCast(Instruction::BitCast, C, Ty);
1082 return getCast(Instruction::Trunc, C, Ty);
1085 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1086 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1087 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1089 if (Ty->isInteger())
1090 return getCast(Instruction::PtrToInt, S, Ty);
1091 return getCast(Instruction::BitCast, S, Ty);
1094 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1096 assert(C->getType()->isIntOrIntVector() &&
1097 Ty->isIntOrIntVector() && "Invalid cast");
1098 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1099 unsigned DstBits = Ty->getScalarSizeInBits();
1100 Instruction::CastOps opcode =
1101 (SrcBits == DstBits ? Instruction::BitCast :
1102 (SrcBits > DstBits ? Instruction::Trunc :
1103 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1104 return getCast(opcode, C, Ty);
1107 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1108 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1110 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1111 unsigned DstBits = Ty->getScalarSizeInBits();
1112 if (SrcBits == DstBits)
1113 return C; // Avoid a useless cast
1114 Instruction::CastOps opcode =
1115 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1116 return getCast(opcode, C, Ty);
1119 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1121 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1122 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1124 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1125 assert(C->getType()->isIntOrIntVector() && "Trunc operand must be integer");
1126 assert(Ty->isIntOrIntVector() && "Trunc produces only integral");
1127 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1128 "SrcTy must be larger than DestTy for Trunc!");
1130 return getFoldedCast(Instruction::Trunc, C, Ty);
1133 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1135 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1136 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1138 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1139 assert(C->getType()->isIntOrIntVector() && "SExt operand must be integral");
1140 assert(Ty->isIntOrIntVector() && "SExt produces only integer");
1141 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1142 "SrcTy must be smaller than DestTy for SExt!");
1144 return getFoldedCast(Instruction::SExt, C, Ty);
1147 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1149 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1150 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1152 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1153 assert(C->getType()->isIntOrIntVector() && "ZEXt operand must be integral");
1154 assert(Ty->isIntOrIntVector() && "ZExt produces only integer");
1155 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1156 "SrcTy must be smaller than DestTy for ZExt!");
1158 return getFoldedCast(Instruction::ZExt, C, Ty);
1161 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1163 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1164 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1166 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1167 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1168 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1169 "This is an illegal floating point truncation!");
1170 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1173 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1175 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1176 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1178 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1179 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1180 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1181 "This is an illegal floating point extension!");
1182 return getFoldedCast(Instruction::FPExt, C, Ty);
1185 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1187 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1188 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1190 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1191 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1192 "This is an illegal uint to floating point cast!");
1193 return getFoldedCast(Instruction::UIToFP, C, Ty);
1196 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1198 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1199 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1201 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1202 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1203 "This is an illegal sint to floating point cast!");
1204 return getFoldedCast(Instruction::SIToFP, C, Ty);
1207 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1209 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1210 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1212 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1213 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1214 "This is an illegal floating point to uint cast!");
1215 return getFoldedCast(Instruction::FPToUI, C, Ty);
1218 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1220 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1221 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1223 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1224 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1225 "This is an illegal floating point to sint cast!");
1226 return getFoldedCast(Instruction::FPToSI, C, Ty);
1229 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1230 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1231 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1232 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1235 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1236 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1237 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1238 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1241 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1242 // BitCast implies a no-op cast of type only. No bits change. However, you
1243 // can't cast pointers to anything but pointers.
1245 const Type *SrcTy = C->getType();
1246 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1247 "BitCast cannot cast pointer to non-pointer and vice versa");
1249 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1250 // or nonptr->ptr). For all the other types, the cast is okay if source and
1251 // destination bit widths are identical.
1252 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1253 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1255 assert(SrcBitSize == DstBitSize && "BitCast requires types of same width");
1257 // It is common to ask for a bitcast of a value to its own type, handle this
1259 if (C->getType() == DstTy) return C;
1261 return getFoldedCast(Instruction::BitCast, C, DstTy);
1264 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1265 Constant *C1, Constant *C2) {
1266 // Check the operands for consistency first
1267 assert(Opcode >= Instruction::BinaryOpsBegin &&
1268 Opcode < Instruction::BinaryOpsEnd &&
1269 "Invalid opcode in binary constant expression");
1270 assert(C1->getType() == C2->getType() &&
1271 "Operand types in binary constant expression should match");
1273 if (ReqTy == C1->getType() || ReqTy == Type::getInt1Ty(ReqTy->getContext()))
1274 if (Constant *FC = ConstantFoldBinaryInstruction(ReqTy->getContext(),
1276 return FC; // Fold a few common cases...
1278 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1279 ExprMapKeyType Key(Opcode, argVec);
1281 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1283 // Implicitly locked.
1284 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1287 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1288 Constant *C1, Constant *C2) {
1289 switch (predicate) {
1290 default: llvm_unreachable("Invalid CmpInst predicate");
1291 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1292 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1293 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1294 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1295 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1296 case CmpInst::FCMP_TRUE:
1297 return getFCmp(predicate, C1, C2);
1299 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1300 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1301 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1302 case CmpInst::ICMP_SLE:
1303 return getICmp(predicate, C1, C2);
1307 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1308 // API compatibility: Adjust integer opcodes to floating-point opcodes.
1309 if (C1->getType()->isFPOrFPVector()) {
1310 if (Opcode == Instruction::Add) Opcode = Instruction::FAdd;
1311 else if (Opcode == Instruction::Sub) Opcode = Instruction::FSub;
1312 else if (Opcode == Instruction::Mul) Opcode = Instruction::FMul;
1316 case Instruction::Add:
1317 case Instruction::Sub:
1318 case Instruction::Mul:
1319 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1320 assert(C1->getType()->isIntOrIntVector() &&
1321 "Tried to create an integer operation on a non-integer type!");
1323 case Instruction::FAdd:
1324 case Instruction::FSub:
1325 case Instruction::FMul:
1326 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1327 assert(C1->getType()->isFPOrFPVector() &&
1328 "Tried to create a floating-point operation on a "
1329 "non-floating-point type!");
1331 case Instruction::UDiv:
1332 case Instruction::SDiv:
1333 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1334 assert(C1->getType()->isIntOrIntVector() &&
1335 "Tried to create an arithmetic operation on a non-arithmetic type!");
1337 case Instruction::FDiv:
1338 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1339 assert(C1->getType()->isFPOrFPVector() &&
1340 "Tried to create an arithmetic operation on a non-arithmetic type!");
1342 case Instruction::URem:
1343 case Instruction::SRem:
1344 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1345 assert(C1->getType()->isIntOrIntVector() &&
1346 "Tried to create an arithmetic operation on a non-arithmetic type!");
1348 case Instruction::FRem:
1349 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1350 assert(C1->getType()->isFPOrFPVector() &&
1351 "Tried to create an arithmetic operation on a non-arithmetic type!");
1353 case Instruction::And:
1354 case Instruction::Or:
1355 case Instruction::Xor:
1356 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1357 assert(C1->getType()->isIntOrIntVector() &&
1358 "Tried to create a logical operation on a non-integral type!");
1360 case Instruction::Shl:
1361 case Instruction::LShr:
1362 case Instruction::AShr:
1363 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1364 assert(C1->getType()->isIntOrIntVector() &&
1365 "Tried to create a shift operation on a non-integer type!");
1372 return getTy(C1->getType(), Opcode, C1, C2);
1375 Constant* ConstantExpr::getSizeOf(const Type* Ty) {
1376 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1377 // Note that a non-inbounds gep is used, as null isn't within any object.
1378 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1379 Constant *GEP = getGetElementPtr(
1380 Constant::getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
1381 return getCast(Instruction::PtrToInt, GEP,
1382 Type::getInt64Ty(Ty->getContext()));
1385 Constant* ConstantExpr::getAlignOf(const Type* Ty) {
1386 // alignof is implemented as: (i64) gep ({i8,Ty}*)null, 0, 1
1387 // Note that a non-inbounds gep is used, as null isn't within any object.
1388 const Type *AligningTy = StructType::get(Ty->getContext(),
1389 Type::getInt8Ty(Ty->getContext()), Ty, NULL);
1390 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo());
1391 Constant *Zero = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 0);
1392 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1393 Constant *Indices[2] = { Zero, One };
1394 Constant *GEP = getGetElementPtr(NullPtr, Indices, 2);
1395 return getCast(Instruction::PtrToInt, GEP,
1396 Type::getInt32Ty(Ty->getContext()));
1399 Constant* ConstantExpr::getOffsetOf(const StructType* STy, unsigned FieldNo) {
1400 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1401 // Note that a non-inbounds gep is used, as null isn't within any object.
1402 Constant *GEPIdx[] = {
1403 ConstantInt::get(Type::getInt64Ty(STy->getContext()), 0),
1404 ConstantInt::get(Type::getInt32Ty(STy->getContext()), FieldNo)
1406 Constant *GEP = getGetElementPtr(
1407 Constant::getNullValue(PointerType::getUnqual(STy)), GEPIdx, 2);
1408 return getCast(Instruction::PtrToInt, GEP,
1409 Type::getInt64Ty(STy->getContext()));
1412 Constant *ConstantExpr::getCompare(unsigned short pred,
1413 Constant *C1, Constant *C2) {
1414 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1415 return getCompareTy(pred, C1, C2);
1418 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1419 Constant *V1, Constant *V2) {
1420 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1422 if (ReqTy == V1->getType())
1423 if (Constant *SC = ConstantFoldSelectInstruction(
1424 ReqTy->getContext(), C, V1, V2))
1425 return SC; // Fold common cases
1427 std::vector<Constant*> argVec(3, C);
1430 ExprMapKeyType Key(Instruction::Select, argVec);
1432 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1434 // Implicitly locked.
1435 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1438 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1441 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
1443 cast<PointerType>(ReqTy)->getElementType() &&
1444 "GEP indices invalid!");
1446 if (Constant *FC = ConstantFoldGetElementPtr(
1447 ReqTy->getContext(), C, (Constant**)Idxs, NumIdx))
1448 return FC; // Fold a few common cases...
1450 assert(isa<PointerType>(C->getType()) &&
1451 "Non-pointer type for constant GetElementPtr expression");
1452 // Look up the constant in the table first to ensure uniqueness
1453 std::vector<Constant*> ArgVec;
1454 ArgVec.reserve(NumIdx+1);
1455 ArgVec.push_back(C);
1456 for (unsigned i = 0; i != NumIdx; ++i)
1457 ArgVec.push_back(cast<Constant>(Idxs[i]));
1458 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
1460 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1462 // Implicitly locked.
1463 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1466 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1468 // Get the result type of the getelementptr!
1470 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
1471 assert(Ty && "GEP indices invalid!");
1472 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
1473 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
1476 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1478 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1482 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1483 assert(LHS->getType() == RHS->getType());
1484 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1485 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1487 if (Constant *FC = ConstantFoldCompareInstruction(
1488 LHS->getContext(), pred, LHS, RHS))
1489 return FC; // Fold a few common cases...
1491 // Look up the constant in the table first to ensure uniqueness
1492 std::vector<Constant*> ArgVec;
1493 ArgVec.push_back(LHS);
1494 ArgVec.push_back(RHS);
1495 // Get the key type with both the opcode and predicate
1496 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1498 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1500 // Implicitly locked.
1502 pImpl->ExprConstants.getOrCreate(Type::getInt1Ty(LHS->getContext()), Key);
1506 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1507 assert(LHS->getType() == RHS->getType());
1508 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1510 if (Constant *FC = ConstantFoldCompareInstruction(
1511 LHS->getContext(), pred, LHS, RHS))
1512 return FC; // Fold a few common cases...
1514 // Look up the constant in the table first to ensure uniqueness
1515 std::vector<Constant*> ArgVec;
1516 ArgVec.push_back(LHS);
1517 ArgVec.push_back(RHS);
1518 // Get the key type with both the opcode and predicate
1519 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1521 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1523 // Implicitly locked.
1525 pImpl->ExprConstants.getOrCreate(Type::getInt1Ty(LHS->getContext()), Key);
1528 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1530 if (Constant *FC = ConstantFoldExtractElementInstruction(
1531 ReqTy->getContext(), Val, Idx))
1532 return FC; // Fold a few common cases...
1533 // Look up the constant in the table first to ensure uniqueness
1534 std::vector<Constant*> ArgVec(1, Val);
1535 ArgVec.push_back(Idx);
1536 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1538 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1540 // Implicitly locked.
1541 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1544 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1545 assert(isa<VectorType>(Val->getType()) &&
1546 "Tried to create extractelement operation on non-vector type!");
1547 assert(Idx->getType() == Type::getInt32Ty(Val->getContext()) &&
1548 "Extractelement index must be i32 type!");
1549 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
1553 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1554 Constant *Elt, Constant *Idx) {
1555 if (Constant *FC = ConstantFoldInsertElementInstruction(
1556 ReqTy->getContext(), Val, Elt, Idx))
1557 return FC; // Fold a few common cases...
1558 // Look up the constant in the table first to ensure uniqueness
1559 std::vector<Constant*> ArgVec(1, Val);
1560 ArgVec.push_back(Elt);
1561 ArgVec.push_back(Idx);
1562 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1564 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1566 // Implicitly locked.
1567 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1570 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1572 assert(isa<VectorType>(Val->getType()) &&
1573 "Tried to create insertelement operation on non-vector type!");
1574 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
1575 && "Insertelement types must match!");
1576 assert(Idx->getType() == Type::getInt32Ty(Val->getContext()) &&
1577 "Insertelement index must be i32 type!");
1578 return getInsertElementTy(Val->getType(), Val, Elt, Idx);
1581 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1582 Constant *V2, Constant *Mask) {
1583 if (Constant *FC = ConstantFoldShuffleVectorInstruction(
1584 ReqTy->getContext(), V1, V2, Mask))
1585 return FC; // Fold a few common cases...
1586 // Look up the constant in the table first to ensure uniqueness
1587 std::vector<Constant*> ArgVec(1, V1);
1588 ArgVec.push_back(V2);
1589 ArgVec.push_back(Mask);
1590 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1592 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1594 // Implicitly locked.
1595 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1598 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1600 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1601 "Invalid shuffle vector constant expr operands!");
1603 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
1604 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
1605 const Type *ShufTy = VectorType::get(EltTy, NElts);
1606 return getShuffleVectorTy(ShufTy, V1, V2, Mask);
1609 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
1611 const unsigned *Idxs, unsigned NumIdx) {
1612 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1613 Idxs+NumIdx) == Val->getType() &&
1614 "insertvalue indices invalid!");
1615 assert(Agg->getType() == ReqTy &&
1616 "insertvalue type invalid!");
1617 assert(Agg->getType()->isFirstClassType() &&
1618 "Non-first-class type for constant InsertValue expression");
1619 Constant *FC = ConstantFoldInsertValueInstruction(
1620 ReqTy->getContext(), Agg, Val, Idxs, NumIdx);
1621 assert(FC && "InsertValue constant expr couldn't be folded!");
1625 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
1626 const unsigned *IdxList, unsigned NumIdx) {
1627 assert(Agg->getType()->isFirstClassType() &&
1628 "Tried to create insertelement operation on non-first-class type!");
1630 const Type *ReqTy = Agg->getType();
1633 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1635 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
1636 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
1639 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
1640 const unsigned *Idxs, unsigned NumIdx) {
1641 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1642 Idxs+NumIdx) == ReqTy &&
1643 "extractvalue indices invalid!");
1644 assert(Agg->getType()->isFirstClassType() &&
1645 "Non-first-class type for constant extractvalue expression");
1646 Constant *FC = ConstantFoldExtractValueInstruction(
1647 ReqTy->getContext(), Agg, Idxs, NumIdx);
1648 assert(FC && "ExtractValue constant expr couldn't be folded!");
1652 Constant *ConstantExpr::getExtractValue(Constant *Agg,
1653 const unsigned *IdxList, unsigned NumIdx) {
1654 assert(Agg->getType()->isFirstClassType() &&
1655 "Tried to create extractelement operation on non-first-class type!");
1658 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1659 assert(ReqTy && "extractvalue indices invalid!");
1660 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
1663 Constant* ConstantExpr::getNeg(Constant* C) {
1664 // API compatibility: Adjust integer opcodes to floating-point opcodes.
1665 if (C->getType()->isFPOrFPVector())
1667 assert(C->getType()->isIntOrIntVector() &&
1668 "Cannot NEG a nonintegral value!");
1669 return get(Instruction::Sub,
1670 ConstantFP::getZeroValueForNegation(C->getType()),
1674 Constant* ConstantExpr::getFNeg(Constant* C) {
1675 assert(C->getType()->isFPOrFPVector() &&
1676 "Cannot FNEG a non-floating-point value!");
1677 return get(Instruction::FSub,
1678 ConstantFP::getZeroValueForNegation(C->getType()),
1682 Constant* ConstantExpr::getNot(Constant* C) {
1683 assert(C->getType()->isIntOrIntVector() &&
1684 "Cannot NOT a nonintegral value!");
1685 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
1688 Constant* ConstantExpr::getAdd(Constant* C1, Constant* C2) {
1689 return get(Instruction::Add, C1, C2);
1692 Constant* ConstantExpr::getFAdd(Constant* C1, Constant* C2) {
1693 return get(Instruction::FAdd, C1, C2);
1696 Constant* ConstantExpr::getSub(Constant* C1, Constant* C2) {
1697 return get(Instruction::Sub, C1, C2);
1700 Constant* ConstantExpr::getFSub(Constant* C1, Constant* C2) {
1701 return get(Instruction::FSub, C1, C2);
1704 Constant* ConstantExpr::getMul(Constant* C1, Constant* C2) {
1705 return get(Instruction::Mul, C1, C2);
1708 Constant* ConstantExpr::getFMul(Constant* C1, Constant* C2) {
1709 return get(Instruction::FMul, C1, C2);
1712 Constant* ConstantExpr::getUDiv(Constant* C1, Constant* C2) {
1713 return get(Instruction::UDiv, C1, C2);
1716 Constant* ConstantExpr::getSDiv(Constant* C1, Constant* C2) {
1717 return get(Instruction::SDiv, C1, C2);
1720 Constant* ConstantExpr::getFDiv(Constant* C1, Constant* C2) {
1721 return get(Instruction::FDiv, C1, C2);
1724 Constant* ConstantExpr::getURem(Constant* C1, Constant* C2) {
1725 return get(Instruction::URem, C1, C2);
1728 Constant* ConstantExpr::getSRem(Constant* C1, Constant* C2) {
1729 return get(Instruction::SRem, C1, C2);
1732 Constant* ConstantExpr::getFRem(Constant* C1, Constant* C2) {
1733 return get(Instruction::FRem, C1, C2);
1736 Constant* ConstantExpr::getAnd(Constant* C1, Constant* C2) {
1737 return get(Instruction::And, C1, C2);
1740 Constant* ConstantExpr::getOr(Constant* C1, Constant* C2) {
1741 return get(Instruction::Or, C1, C2);
1744 Constant* ConstantExpr::getXor(Constant* C1, Constant* C2) {
1745 return get(Instruction::Xor, C1, C2);
1748 Constant* ConstantExpr::getShl(Constant* C1, Constant* C2) {
1749 return get(Instruction::Shl, C1, C2);
1752 Constant* ConstantExpr::getLShr(Constant* C1, Constant* C2) {
1753 return get(Instruction::LShr, C1, C2);
1756 Constant* ConstantExpr::getAShr(Constant* C1, Constant* C2) {
1757 return get(Instruction::AShr, C1, C2);
1760 // destroyConstant - Remove the constant from the constant table...
1762 void ConstantExpr::destroyConstant() {
1763 // Implicitly locked.
1764 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
1765 pImpl->ExprConstants.remove(this);
1766 destroyConstantImpl();
1769 const char *ConstantExpr::getOpcodeName() const {
1770 return Instruction::getOpcodeName(getOpcode());
1773 //===----------------------------------------------------------------------===//
1774 // replaceUsesOfWithOnConstant implementations
1776 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
1777 /// 'From' to be uses of 'To'. This must update the uniquing data structures
1780 /// Note that we intentionally replace all uses of From with To here. Consider
1781 /// a large array that uses 'From' 1000 times. By handling this case all here,
1782 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
1783 /// single invocation handles all 1000 uses. Handling them one at a time would
1784 /// work, but would be really slow because it would have to unique each updated
1787 static std::vector<Constant*> getValType(ConstantArray *CA) {
1788 std::vector<Constant*> Elements;
1789 Elements.reserve(CA->getNumOperands());
1790 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1791 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1796 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1798 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1799 Constant *ToC = cast<Constant>(To);
1801 LLVMContext &Context = getType()->getContext();
1802 LLVMContextImpl *pImpl = Context.pImpl;
1804 std::pair<LLVMContextImpl::ArrayConstantsTy::MapKey, Constant*> Lookup;
1805 Lookup.first.first = getType();
1806 Lookup.second = this;
1808 std::vector<Constant*> &Values = Lookup.first.second;
1809 Values.reserve(getNumOperands()); // Build replacement array.
1811 // Fill values with the modified operands of the constant array. Also,
1812 // compute whether this turns into an all-zeros array.
1813 bool isAllZeros = false;
1814 unsigned NumUpdated = 0;
1815 if (!ToC->isNullValue()) {
1816 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1817 Constant *Val = cast<Constant>(O->get());
1822 Values.push_back(Val);
1826 for (Use *O = OperandList, *E = OperandList+getNumOperands();O != E; ++O) {
1827 Constant *Val = cast<Constant>(O->get());
1832 Values.push_back(Val);
1833 if (isAllZeros) isAllZeros = Val->isNullValue();
1837 Constant *Replacement = 0;
1839 Replacement = ConstantAggregateZero::get(getType());
1841 // Check to see if we have this array type already.
1842 sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
1844 LLVMContextImpl::ArrayConstantsTy::MapTy::iterator I =
1845 pImpl->ArrayConstants.InsertOrGetItem(Lookup, Exists);
1848 Replacement = I->second;
1850 // Okay, the new shape doesn't exist in the system yet. Instead of
1851 // creating a new constant array, inserting it, replaceallusesof'ing the
1852 // old with the new, then deleting the old... just update the current one
1854 pImpl->ArrayConstants.MoveConstantToNewSlot(this, I);
1856 // Update to the new value. Optimize for the case when we have a single
1857 // operand that we're changing, but handle bulk updates efficiently.
1858 if (NumUpdated == 1) {
1859 unsigned OperandToUpdate = U - OperandList;
1860 assert(getOperand(OperandToUpdate) == From &&
1861 "ReplaceAllUsesWith broken!");
1862 setOperand(OperandToUpdate, ToC);
1864 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1865 if (getOperand(i) == From)
1872 // Otherwise, I do need to replace this with an existing value.
1873 assert(Replacement != this && "I didn't contain From!");
1875 // Everyone using this now uses the replacement.
1876 uncheckedReplaceAllUsesWith(Replacement);
1878 // Delete the old constant!
1882 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1883 std::vector<Constant*> Elements;
1884 Elements.reserve(CS->getNumOperands());
1885 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1886 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1890 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
1892 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1893 Constant *ToC = cast<Constant>(To);
1895 unsigned OperandToUpdate = U-OperandList;
1896 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1898 std::pair<LLVMContextImpl::StructConstantsTy::MapKey, Constant*> Lookup;
1899 Lookup.first.first = getType();
1900 Lookup.second = this;
1901 std::vector<Constant*> &Values = Lookup.first.second;
1902 Values.reserve(getNumOperands()); // Build replacement struct.
1905 // Fill values with the modified operands of the constant struct. Also,
1906 // compute whether this turns into an all-zeros struct.
1907 bool isAllZeros = false;
1908 if (!ToC->isNullValue()) {
1909 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
1910 Values.push_back(cast<Constant>(O->get()));
1913 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1914 Constant *Val = cast<Constant>(O->get());
1915 Values.push_back(Val);
1916 if (isAllZeros) isAllZeros = Val->isNullValue();
1919 Values[OperandToUpdate] = ToC;
1921 LLVMContext &Context = getType()->getContext();
1922 LLVMContextImpl *pImpl = Context.pImpl;
1924 Constant *Replacement = 0;
1926 Replacement = ConstantAggregateZero::get(getType());
1928 // Check to see if we have this array type already.
1929 sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
1931 LLVMContextImpl::StructConstantsTy::MapTy::iterator I =
1932 pImpl->StructConstants.InsertOrGetItem(Lookup, Exists);
1935 Replacement = I->second;
1937 // Okay, the new shape doesn't exist in the system yet. Instead of
1938 // creating a new constant struct, inserting it, replaceallusesof'ing the
1939 // old with the new, then deleting the old... just update the current one
1941 pImpl->StructConstants.MoveConstantToNewSlot(this, I);
1943 // Update to the new value.
1944 setOperand(OperandToUpdate, ToC);
1949 assert(Replacement != this && "I didn't contain From!");
1951 // Everyone using this now uses the replacement.
1952 uncheckedReplaceAllUsesWith(Replacement);
1954 // Delete the old constant!
1958 static std::vector<Constant*> getValType(ConstantVector *CP) {
1959 std::vector<Constant*> Elements;
1960 Elements.reserve(CP->getNumOperands());
1961 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1962 Elements.push_back(CP->getOperand(i));
1966 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
1968 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1970 std::vector<Constant*> Values;
1971 Values.reserve(getNumOperands()); // Build replacement array...
1972 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1973 Constant *Val = getOperand(i);
1974 if (Val == From) Val = cast<Constant>(To);
1975 Values.push_back(Val);
1978 Constant *Replacement = get(getType(), Values);
1979 assert(Replacement != this && "I didn't contain From!");
1981 // Everyone using this now uses the replacement.
1982 uncheckedReplaceAllUsesWith(Replacement);
1984 // Delete the old constant!
1988 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
1990 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
1991 Constant *To = cast<Constant>(ToV);
1993 Constant *Replacement = 0;
1994 if (getOpcode() == Instruction::GetElementPtr) {
1995 SmallVector<Constant*, 8> Indices;
1996 Constant *Pointer = getOperand(0);
1997 Indices.reserve(getNumOperands()-1);
1998 if (Pointer == From) Pointer = To;
2000 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2001 Constant *Val = getOperand(i);
2002 if (Val == From) Val = To;
2003 Indices.push_back(Val);
2005 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2006 &Indices[0], Indices.size());
2007 } else if (getOpcode() == Instruction::ExtractValue) {
2008 Constant *Agg = getOperand(0);
2009 if (Agg == From) Agg = To;
2011 const SmallVector<unsigned, 4> &Indices = getIndices();
2012 Replacement = ConstantExpr::getExtractValue(Agg,
2013 &Indices[0], Indices.size());
2014 } else if (getOpcode() == Instruction::InsertValue) {
2015 Constant *Agg = getOperand(0);
2016 Constant *Val = getOperand(1);
2017 if (Agg == From) Agg = To;
2018 if (Val == From) Val = To;
2020 const SmallVector<unsigned, 4> &Indices = getIndices();
2021 Replacement = ConstantExpr::getInsertValue(Agg, Val,
2022 &Indices[0], Indices.size());
2023 } else if (isCast()) {
2024 assert(getOperand(0) == From && "Cast only has one use!");
2025 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2026 } else if (getOpcode() == Instruction::Select) {
2027 Constant *C1 = getOperand(0);
2028 Constant *C2 = getOperand(1);
2029 Constant *C3 = getOperand(2);
2030 if (C1 == From) C1 = To;
2031 if (C2 == From) C2 = To;
2032 if (C3 == From) C3 = To;
2033 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2034 } else if (getOpcode() == Instruction::ExtractElement) {
2035 Constant *C1 = getOperand(0);
2036 Constant *C2 = getOperand(1);
2037 if (C1 == From) C1 = To;
2038 if (C2 == From) C2 = To;
2039 Replacement = ConstantExpr::getExtractElement(C1, C2);
2040 } else if (getOpcode() == Instruction::InsertElement) {
2041 Constant *C1 = getOperand(0);
2042 Constant *C2 = getOperand(1);
2043 Constant *C3 = getOperand(1);
2044 if (C1 == From) C1 = To;
2045 if (C2 == From) C2 = To;
2046 if (C3 == From) C3 = To;
2047 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2048 } else if (getOpcode() == Instruction::ShuffleVector) {
2049 Constant *C1 = getOperand(0);
2050 Constant *C2 = getOperand(1);
2051 Constant *C3 = getOperand(2);
2052 if (C1 == From) C1 = To;
2053 if (C2 == From) C2 = To;
2054 if (C3 == From) C3 = To;
2055 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2056 } else if (isCompare()) {
2057 Constant *C1 = getOperand(0);
2058 Constant *C2 = getOperand(1);
2059 if (C1 == From) C1 = To;
2060 if (C2 == From) C2 = To;
2061 if (getOpcode() == Instruction::ICmp)
2062 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2064 assert(getOpcode() == Instruction::FCmp);
2065 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2067 } else if (getNumOperands() == 2) {
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::get(getOpcode(), C1, C2);
2074 llvm_unreachable("Unknown ConstantExpr type!");
2078 assert(Replacement != this && "I didn't contain From!");
2080 // Everyone using this now uses the replacement.
2081 uncheckedReplaceAllUsesWith(Replacement);
2083 // Delete the old constant!