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/MDNode.h"
21 #include "llvm/Module.h"
22 #include "llvm/Operator.h"
23 #include "llvm/ADT/FoldingSet.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringMap.h"
26 #include "llvm/Support/Compiler.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/ManagedStatic.h"
30 #include "llvm/Support/MathExtras.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 // Becomes a no-op when multithreading is disabled.
45 ManagedStatic<sys::SmartRWMutex<true> > ConstantsLock;
47 void Constant::destroyConstantImpl() {
48 // When a Constant is destroyed, there may be lingering
49 // references to the constant by other constants in the constant pool. These
50 // constants are implicitly dependent on the module that is being deleted,
51 // but they don't know that. Because we only find out when the CPV is
52 // deleted, we must now notify all of our users (that should only be
53 // Constants) that they are, in fact, invalid now and should be deleted.
55 while (!use_empty()) {
56 Value *V = use_back();
57 #ifndef NDEBUG // Only in -g mode...
58 if (!isa<Constant>(V))
59 DOUT << "While deleting: " << *this
60 << "\n\nUse still stuck around after Def is destroyed: "
63 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
64 Constant *CV = cast<Constant>(V);
65 CV->destroyConstant();
67 // The constant should remove itself from our use list...
68 assert((use_empty() || use_back() != V) && "Constant not removed!");
71 // Value has no outstanding references it is safe to delete it now...
75 /// canTrap - Return true if evaluation of this constant could trap. This is
76 /// true for things like constant expressions that could divide by zero.
77 bool Constant::canTrap() const {
78 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
79 // The only thing that could possibly trap are constant exprs.
80 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
81 if (!CE) return false;
83 // ConstantExpr traps if any operands can trap.
84 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
85 if (getOperand(i)->canTrap())
88 // Otherwise, only specific operations can trap.
89 switch (CE->getOpcode()) {
92 case Instruction::UDiv:
93 case Instruction::SDiv:
94 case Instruction::FDiv:
95 case Instruction::URem:
96 case Instruction::SRem:
97 case Instruction::FRem:
98 // Div and rem can trap if the RHS is not known to be non-zero.
99 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
106 /// getRelocationInfo - This method classifies the entry according to
107 /// whether or not it may generate a relocation entry. This must be
108 /// conservative, so if it might codegen to a relocatable entry, it should say
109 /// so. The return values are:
111 /// NoRelocation: This constant pool entry is guaranteed to never have a
112 /// relocation applied to it (because it holds a simple constant like
114 /// LocalRelocation: This entry has relocations, but the entries are
115 /// guaranteed to be resolvable by the static linker, so the dynamic
116 /// linker will never see them.
117 /// GlobalRelocations: This entry may have arbitrary relocations.
119 /// FIXME: This really should not be in VMCore.
120 Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
121 if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
122 if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
123 return LocalRelocation; // Local to this file/library.
124 return GlobalRelocations; // Global reference.
127 PossibleRelocationsTy Result = NoRelocation;
128 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
129 Result = std::max(Result, getOperand(i)->getRelocationInfo());
135 /// getVectorElements - This method, which is only valid on constant of vector
136 /// type, returns the elements of the vector in the specified smallvector.
137 /// This handles breaking down a vector undef into undef elements, etc. For
138 /// constant exprs and other cases we can't handle, we return an empty vector.
139 void Constant::getVectorElements(LLVMContext &Context,
140 SmallVectorImpl<Constant*> &Elts) const {
141 assert(isa<VectorType>(getType()) && "Not a vector constant!");
143 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
144 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
145 Elts.push_back(CV->getOperand(i));
149 const VectorType *VT = cast<VectorType>(getType());
150 if (isa<ConstantAggregateZero>(this)) {
151 Elts.assign(VT->getNumElements(),
152 Context.getNullValue(VT->getElementType()));
156 if (isa<UndefValue>(this)) {
157 Elts.assign(VT->getNumElements(), Context.getUndef(VT->getElementType()));
161 // Unknown type, must be constant expr etc.
166 //===----------------------------------------------------------------------===//
168 //===----------------------------------------------------------------------===//
170 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
171 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
172 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
175 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
176 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
177 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
178 // compare APInt's of different widths, which would violate an APInt class
179 // invariant which generates an assertion.
180 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt& V) {
181 // Get the corresponding integer type for the bit width of the value.
182 const IntegerType *ITy = Context.getIntegerType(V.getBitWidth());
183 // get an existing value or the insertion position
184 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
186 Context.pImpl->ConstantsLock.reader_acquire();
187 ConstantInt *&Slot = Context.pImpl->IntConstants[Key];
188 Context.pImpl->ConstantsLock.reader_release();
191 sys::SmartScopedWriter<true> Writer(Context.pImpl->ConstantsLock);
192 ConstantInt *&NewSlot = Context.pImpl->IntConstants[Key];
194 NewSlot = new ConstantInt(ITy, V);
203 Constant* ConstantInt::get(const Type* Ty, uint64_t V, bool isSigned) {
204 Constant *C = get(cast<IntegerType>(Ty->getScalarType()),
207 // For vectors, broadcast the value.
208 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
209 return ConstantVector::get(
210 std::vector<Constant *>(VTy->getNumElements(), C));
215 ConstantInt* ConstantInt::get(const IntegerType* Ty, uint64_t V,
217 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
220 ConstantInt* ConstantInt::getSigned(const IntegerType* Ty, int64_t V) {
221 return get(Ty, V, true);
224 Constant *ConstantInt::getSigned(const Type *Ty, int64_t V) {
225 return get(Ty, V, true);
228 Constant* ConstantInt::get(const Type* Ty, const APInt& V) {
229 ConstantInt *C = get(Ty->getContext(), V);
230 assert(C->getType() == Ty->getScalarType() &&
231 "ConstantInt type doesn't match the type implied by its value!");
233 // For vectors, broadcast the value.
234 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
235 return ConstantVector::get(
236 std::vector<Constant *>(VTy->getNumElements(), C));
241 //===----------------------------------------------------------------------===//
243 //===----------------------------------------------------------------------===//
245 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
246 if (Ty == Type::FloatTy)
247 return &APFloat::IEEEsingle;
248 if (Ty == Type::DoubleTy)
249 return &APFloat::IEEEdouble;
250 if (Ty == Type::X86_FP80Ty)
251 return &APFloat::x87DoubleExtended;
252 else if (Ty == Type::FP128Ty)
253 return &APFloat::IEEEquad;
255 assert(Ty == Type::PPC_FP128Ty && "Unknown FP format");
256 return &APFloat::PPCDoubleDouble;
259 /// get() - This returns a constant fp for the specified value in the
260 /// specified type. This should only be used for simple constant values like
261 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
262 Constant* ConstantFP::get(const Type* Ty, double V) {
263 LLVMContext &Context = Ty->getContext();
267 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
268 APFloat::rmNearestTiesToEven, &ignored);
269 Constant *C = get(Context, FV);
271 // For vectors, broadcast the value.
272 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
273 return ConstantVector::get(
274 std::vector<Constant *>(VTy->getNumElements(), C));
279 ConstantFP* ConstantFP::getNegativeZero(const Type* Ty) {
280 LLVMContext &Context = Ty->getContext();
281 APFloat apf = cast <ConstantFP>(Context.getNullValue(Ty))->getValueAPF();
283 return get(Context, apf);
287 Constant* ConstantFP::getZeroValueForNegation(const Type* Ty) {
288 LLVMContext &Context = Ty->getContext();
289 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
290 if (PTy->getElementType()->isFloatingPoint()) {
291 std::vector<Constant*> zeros(PTy->getNumElements(),
292 getNegativeZero(PTy->getElementType()));
293 return ConstantVector::get(PTy, zeros);
296 if (Ty->isFloatingPoint())
297 return getNegativeZero(Ty);
299 return Context.getNullValue(Ty);
303 // ConstantFP accessors.
304 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
305 DenseMapAPFloatKeyInfo::KeyTy Key(V);
307 LLVMContextImpl* pImpl = Context.pImpl;
309 pImpl->ConstantsLock.reader_acquire();
310 ConstantFP *&Slot = pImpl->FPConstants[Key];
311 pImpl->ConstantsLock.reader_release();
314 sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
315 ConstantFP *&NewSlot = pImpl->FPConstants[Key];
318 if (&V.getSemantics() == &APFloat::IEEEsingle)
320 else if (&V.getSemantics() == &APFloat::IEEEdouble)
322 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
323 Ty = Type::X86_FP80Ty;
324 else if (&V.getSemantics() == &APFloat::IEEEquad)
327 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
328 "Unknown FP format");
329 Ty = Type::PPC_FP128Ty;
331 NewSlot = new ConstantFP(Ty, V);
340 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
341 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
342 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
346 bool ConstantFP::isNullValue() const {
347 return Val.isZero() && !Val.isNegative();
350 bool ConstantFP::isExactlyValue(const APFloat& V) const {
351 return Val.bitwiseIsEqual(V);
354 //===----------------------------------------------------------------------===//
355 // ConstantXXX Classes
356 //===----------------------------------------------------------------------===//
359 ConstantArray::ConstantArray(const ArrayType *T,
360 const std::vector<Constant*> &V)
361 : Constant(T, ConstantArrayVal,
362 OperandTraits<ConstantArray>::op_end(this) - V.size(),
364 assert(V.size() == T->getNumElements() &&
365 "Invalid initializer vector for constant array");
366 Use *OL = OperandList;
367 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
370 assert((C->getType() == T->getElementType() ||
372 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
373 "Initializer for array element doesn't match array element type!");
378 Constant *ConstantArray::get(const ArrayType *Ty,
379 const std::vector<Constant*> &V) {
380 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
381 // If this is an all-zero array, return a ConstantAggregateZero object
384 if (!C->isNullValue()) {
385 // Implicitly locked.
386 return pImpl->ArrayConstants.getOrCreate(Ty, V);
388 for (unsigned i = 1, e = V.size(); i != e; ++i)
390 // Implicitly locked.
391 return pImpl->ArrayConstants.getOrCreate(Ty, V);
395 return Ty->getContext().getConstantAggregateZero(Ty);
399 Constant* ConstantArray::get(const ArrayType* T, Constant* const* Vals,
401 // FIXME: make this the primary ctor method.
402 return get(T, std::vector<Constant*>(Vals, Vals+NumVals));
405 /// ConstantArray::get(const string&) - Return an array that is initialized to
406 /// contain the specified string. If length is zero then a null terminator is
407 /// added to the specified string so that it may be used in a natural way.
408 /// Otherwise, the length parameter specifies how much of the string to use
409 /// and it won't be null terminated.
411 Constant* ConstantArray::get(const StringRef &Str, bool AddNull) {
412 std::vector<Constant*> ElementVals;
413 for (unsigned i = 0; i < Str.size(); ++i)
414 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
416 // Add a null terminator to the string...
418 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
421 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
422 return get(ATy, ElementVals);
427 ConstantStruct::ConstantStruct(const StructType *T,
428 const std::vector<Constant*> &V)
429 : Constant(T, ConstantStructVal,
430 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
432 assert(V.size() == T->getNumElements() &&
433 "Invalid initializer vector for constant structure");
434 Use *OL = OperandList;
435 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
438 assert((C->getType() == T->getElementType(I-V.begin()) ||
439 ((T->getElementType(I-V.begin())->isAbstract() ||
440 C->getType()->isAbstract()) &&
441 T->getElementType(I-V.begin())->getTypeID() ==
442 C->getType()->getTypeID())) &&
443 "Initializer for struct element doesn't match struct element type!");
448 // ConstantStruct accessors.
449 Constant* ConstantStruct::get(const StructType* T,
450 const std::vector<Constant*>& V) {
451 LLVMContextImpl* pImpl = T->getContext().pImpl;
453 // Create a ConstantAggregateZero value if all elements are zeros...
454 for (unsigned i = 0, e = V.size(); i != e; ++i)
455 if (!V[i]->isNullValue())
456 // Implicitly locked.
457 return pImpl->StructConstants.getOrCreate(T, V);
459 return T->getContext().getConstantAggregateZero(T);
462 Constant* ConstantStruct::get(const std::vector<Constant*>& V, bool packed) {
463 std::vector<const Type*> StructEls;
464 StructEls.reserve(V.size());
465 for (unsigned i = 0, e = V.size(); i != e; ++i)
466 StructEls.push_back(V[i]->getType());
467 return get(StructType::get(StructEls, packed), V);
470 Constant* ConstantStruct::get(Constant* const *Vals, unsigned NumVals,
472 // FIXME: make this the primary ctor method.
473 return get(std::vector<Constant*>(Vals, Vals+NumVals), Packed);
476 ConstantVector::ConstantVector(const VectorType *T,
477 const std::vector<Constant*> &V)
478 : Constant(T, ConstantVectorVal,
479 OperandTraits<ConstantVector>::op_end(this) - V.size(),
481 Use *OL = OperandList;
482 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
485 assert((C->getType() == T->getElementType() ||
487 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
488 "Initializer for vector element doesn't match vector element type!");
493 // ConstantVector accessors.
494 Constant* ConstantVector::get(const VectorType* T,
495 const std::vector<Constant*>& V) {
496 assert(!V.empty() && "Vectors can't be empty");
497 LLVMContext &Context = T->getContext();
498 LLVMContextImpl *pImpl = Context.pImpl;
500 // If this is an all-undef or alll-zero vector, return a
501 // ConstantAggregateZero or UndefValue.
503 bool isZero = C->isNullValue();
504 bool isUndef = isa<UndefValue>(C);
506 if (isZero || isUndef) {
507 for (unsigned i = 1, e = V.size(); i != e; ++i)
509 isZero = isUndef = false;
515 return Context.getConstantAggregateZero(T);
517 return Context.getUndef(T);
519 // Implicitly locked.
520 return pImpl->VectorConstants.getOrCreate(T, V);
523 Constant* ConstantVector::get(const std::vector<Constant*>& V) {
524 assert(!V.empty() && "Cannot infer type if V is empty");
525 return get(VectorType::get(V.front()->getType(),V.size()), V);
528 Constant* ConstantVector::get(Constant* const* Vals, unsigned NumVals) {
529 // FIXME: make this the primary ctor method.
530 return get(std::vector<Constant*>(Vals, Vals+NumVals));
535 // We declare several classes private to this file, so use an anonymous
539 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
540 /// behind the scenes to implement unary constant exprs.
541 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
542 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
544 // allocate space for exactly one operand
545 void *operator new(size_t s) {
546 return User::operator new(s, 1);
548 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
549 : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
552 /// Transparently provide more efficient getOperand methods.
553 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
556 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
557 /// behind the scenes to implement binary constant exprs.
558 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
559 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
561 // allocate space for exactly two operands
562 void *operator new(size_t s) {
563 return User::operator new(s, 2);
565 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
566 : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
570 /// Transparently provide more efficient getOperand methods.
571 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
574 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
575 /// behind the scenes to implement select constant exprs.
576 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
577 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
579 // allocate space for exactly three operands
580 void *operator new(size_t s) {
581 return User::operator new(s, 3);
583 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
584 : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
589 /// Transparently provide more efficient getOperand methods.
590 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
593 /// ExtractElementConstantExpr - This class is private to
594 /// Constants.cpp, and is used behind the scenes to implement
595 /// extractelement constant exprs.
596 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
597 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
599 // allocate space for exactly two operands
600 void *operator new(size_t s) {
601 return User::operator new(s, 2);
603 ExtractElementConstantExpr(Constant *C1, Constant *C2)
604 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
605 Instruction::ExtractElement, &Op<0>(), 2) {
609 /// Transparently provide more efficient getOperand methods.
610 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
613 /// InsertElementConstantExpr - This class is private to
614 /// Constants.cpp, and is used behind the scenes to implement
615 /// insertelement constant exprs.
616 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
617 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
619 // allocate space for exactly three operands
620 void *operator new(size_t s) {
621 return User::operator new(s, 3);
623 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
624 : ConstantExpr(C1->getType(), Instruction::InsertElement,
630 /// Transparently provide more efficient getOperand methods.
631 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
634 /// ShuffleVectorConstantExpr - This class is private to
635 /// Constants.cpp, and is used behind the scenes to implement
636 /// shufflevector constant exprs.
637 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
638 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
640 // allocate space for exactly three operands
641 void *operator new(size_t s) {
642 return User::operator new(s, 3);
644 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
645 : ConstantExpr(VectorType::get(
646 cast<VectorType>(C1->getType())->getElementType(),
647 cast<VectorType>(C3->getType())->getNumElements()),
648 Instruction::ShuffleVector,
654 /// Transparently provide more efficient getOperand methods.
655 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
658 /// ExtractValueConstantExpr - This class is private to
659 /// Constants.cpp, and is used behind the scenes to implement
660 /// extractvalue constant exprs.
661 class VISIBILITY_HIDDEN ExtractValueConstantExpr : public ConstantExpr {
662 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
664 // allocate space for exactly one operand
665 void *operator new(size_t s) {
666 return User::operator new(s, 1);
668 ExtractValueConstantExpr(Constant *Agg,
669 const SmallVector<unsigned, 4> &IdxList,
671 : ConstantExpr(DestTy, Instruction::ExtractValue, &Op<0>(), 1),
676 /// Indices - These identify which value to extract.
677 const SmallVector<unsigned, 4> Indices;
679 /// Transparently provide more efficient getOperand methods.
680 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
683 /// InsertValueConstantExpr - This class is private to
684 /// Constants.cpp, and is used behind the scenes to implement
685 /// insertvalue constant exprs.
686 class VISIBILITY_HIDDEN InsertValueConstantExpr : public ConstantExpr {
687 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
689 // allocate space for exactly one operand
690 void *operator new(size_t s) {
691 return User::operator new(s, 2);
693 InsertValueConstantExpr(Constant *Agg, Constant *Val,
694 const SmallVector<unsigned, 4> &IdxList,
696 : ConstantExpr(DestTy, Instruction::InsertValue, &Op<0>(), 2),
702 /// Indices - These identify the position for the insertion.
703 const SmallVector<unsigned, 4> Indices;
705 /// Transparently provide more efficient getOperand methods.
706 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
710 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
711 /// used behind the scenes to implement getelementpr constant exprs.
712 class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
713 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
716 static GetElementPtrConstantExpr *Create(Constant *C,
717 const std::vector<Constant*>&IdxList,
718 const Type *DestTy) {
720 new(IdxList.size() + 1) GetElementPtrConstantExpr(C, IdxList, DestTy);
722 /// Transparently provide more efficient getOperand methods.
723 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
726 // CompareConstantExpr - This class is private to Constants.cpp, and is used
727 // behind the scenes to implement ICmp and FCmp constant expressions. This is
728 // needed in order to store the predicate value for these instructions.
729 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
730 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
731 // allocate space for exactly two operands
732 void *operator new(size_t s) {
733 return User::operator new(s, 2);
735 unsigned short predicate;
736 CompareConstantExpr(const Type *ty, Instruction::OtherOps opc,
737 unsigned short pred, Constant* LHS, Constant* RHS)
738 : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
742 /// Transparently provide more efficient getOperand methods.
743 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
746 } // end anonymous namespace
749 struct OperandTraits<UnaryConstantExpr> : FixedNumOperandTraits<1> {
751 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
754 struct OperandTraits<BinaryConstantExpr> : FixedNumOperandTraits<2> {
756 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
759 struct OperandTraits<SelectConstantExpr> : FixedNumOperandTraits<3> {
761 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
764 struct OperandTraits<ExtractElementConstantExpr> : FixedNumOperandTraits<2> {
766 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
769 struct OperandTraits<InsertElementConstantExpr> : FixedNumOperandTraits<3> {
771 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
774 struct OperandTraits<ShuffleVectorConstantExpr> : FixedNumOperandTraits<3> {
776 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
779 struct OperandTraits<ExtractValueConstantExpr> : FixedNumOperandTraits<1> {
781 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractValueConstantExpr, Value)
784 struct OperandTraits<InsertValueConstantExpr> : FixedNumOperandTraits<2> {
786 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueConstantExpr, Value)
789 struct OperandTraits<GetElementPtrConstantExpr> : VariadicOperandTraits<1> {
792 GetElementPtrConstantExpr::GetElementPtrConstantExpr
794 const std::vector<Constant*> &IdxList,
796 : ConstantExpr(DestTy, Instruction::GetElementPtr,
797 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
798 - (IdxList.size()+1),
801 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
802 OperandList[i+1] = IdxList[i];
805 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
809 struct OperandTraits<CompareConstantExpr> : FixedNumOperandTraits<2> {
811 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
814 } // End llvm namespace
817 // Utility function for determining if a ConstantExpr is a CastOp or not. This
818 // can't be inline because we don't want to #include Instruction.h into
820 bool ConstantExpr::isCast() const {
821 return Instruction::isCast(getOpcode());
824 bool ConstantExpr::isCompare() const {
825 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
828 bool ConstantExpr::hasIndices() const {
829 return getOpcode() == Instruction::ExtractValue ||
830 getOpcode() == Instruction::InsertValue;
833 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
834 if (const ExtractValueConstantExpr *EVCE =
835 dyn_cast<ExtractValueConstantExpr>(this))
836 return EVCE->Indices;
838 return cast<InsertValueConstantExpr>(this)->Indices;
841 unsigned ConstantExpr::getPredicate() const {
842 assert(getOpcode() == Instruction::FCmp ||
843 getOpcode() == Instruction::ICmp);
844 return ((const CompareConstantExpr*)this)->predicate;
847 /// getWithOperandReplaced - Return a constant expression identical to this
848 /// one, but with the specified operand set to the specified value.
850 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
851 assert(OpNo < getNumOperands() && "Operand num is out of range!");
852 assert(Op->getType() == getOperand(OpNo)->getType() &&
853 "Replacing operand with value of different type!");
854 if (getOperand(OpNo) == Op)
855 return const_cast<ConstantExpr*>(this);
857 Constant *Op0, *Op1, *Op2;
858 switch (getOpcode()) {
859 case Instruction::Trunc:
860 case Instruction::ZExt:
861 case Instruction::SExt:
862 case Instruction::FPTrunc:
863 case Instruction::FPExt:
864 case Instruction::UIToFP:
865 case Instruction::SIToFP:
866 case Instruction::FPToUI:
867 case Instruction::FPToSI:
868 case Instruction::PtrToInt:
869 case Instruction::IntToPtr:
870 case Instruction::BitCast:
871 return ConstantExpr::getCast(getOpcode(), Op, getType());
872 case Instruction::Select:
873 Op0 = (OpNo == 0) ? Op : getOperand(0);
874 Op1 = (OpNo == 1) ? Op : getOperand(1);
875 Op2 = (OpNo == 2) ? Op : getOperand(2);
876 return ConstantExpr::getSelect(Op0, Op1, Op2);
877 case Instruction::InsertElement:
878 Op0 = (OpNo == 0) ? Op : getOperand(0);
879 Op1 = (OpNo == 1) ? Op : getOperand(1);
880 Op2 = (OpNo == 2) ? Op : getOperand(2);
881 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
882 case Instruction::ExtractElement:
883 Op0 = (OpNo == 0) ? Op : getOperand(0);
884 Op1 = (OpNo == 1) ? Op : getOperand(1);
885 return ConstantExpr::getExtractElement(Op0, Op1);
886 case Instruction::ShuffleVector:
887 Op0 = (OpNo == 0) ? Op : getOperand(0);
888 Op1 = (OpNo == 1) ? Op : getOperand(1);
889 Op2 = (OpNo == 2) ? Op : getOperand(2);
890 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
891 case Instruction::GetElementPtr: {
892 SmallVector<Constant*, 8> Ops;
893 Ops.resize(getNumOperands()-1);
894 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
895 Ops[i-1] = getOperand(i);
897 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
899 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
902 assert(getNumOperands() == 2 && "Must be binary operator?");
903 Op0 = (OpNo == 0) ? Op : getOperand(0);
904 Op1 = (OpNo == 1) ? Op : getOperand(1);
905 return ConstantExpr::get(getOpcode(), Op0, Op1);
909 /// getWithOperands - This returns the current constant expression with the
910 /// operands replaced with the specified values. The specified operands must
911 /// match count and type with the existing ones.
912 Constant *ConstantExpr::
913 getWithOperands(Constant* const *Ops, unsigned NumOps) const {
914 assert(NumOps == getNumOperands() && "Operand count mismatch!");
915 bool AnyChange = false;
916 for (unsigned i = 0; i != NumOps; ++i) {
917 assert(Ops[i]->getType() == getOperand(i)->getType() &&
918 "Operand type mismatch!");
919 AnyChange |= Ops[i] != getOperand(i);
921 if (!AnyChange) // No operands changed, return self.
922 return const_cast<ConstantExpr*>(this);
924 switch (getOpcode()) {
925 case Instruction::Trunc:
926 case Instruction::ZExt:
927 case Instruction::SExt:
928 case Instruction::FPTrunc:
929 case Instruction::FPExt:
930 case Instruction::UIToFP:
931 case Instruction::SIToFP:
932 case Instruction::FPToUI:
933 case Instruction::FPToSI:
934 case Instruction::PtrToInt:
935 case Instruction::IntToPtr:
936 case Instruction::BitCast:
937 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
938 case Instruction::Select:
939 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
940 case Instruction::InsertElement:
941 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
942 case Instruction::ExtractElement:
943 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
944 case Instruction::ShuffleVector:
945 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
946 case Instruction::GetElementPtr:
947 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
948 case Instruction::ICmp:
949 case Instruction::FCmp:
950 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
952 assert(getNumOperands() == 2 && "Must be binary operator?");
953 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
958 //===----------------------------------------------------------------------===//
959 // isValueValidForType implementations
961 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
962 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
963 if (Ty == Type::Int1Ty)
964 return Val == 0 || Val == 1;
966 return true; // always true, has to fit in largest type
967 uint64_t Max = (1ll << NumBits) - 1;
971 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
972 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
973 if (Ty == Type::Int1Ty)
974 return Val == 0 || Val == 1 || Val == -1;
976 return true; // always true, has to fit in largest type
977 int64_t Min = -(1ll << (NumBits-1));
978 int64_t Max = (1ll << (NumBits-1)) - 1;
979 return (Val >= Min && Val <= Max);
982 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
983 // convert modifies in place, so make a copy.
984 APFloat Val2 = APFloat(Val);
986 switch (Ty->getTypeID()) {
988 return false; // These can't be represented as floating point!
990 // FIXME rounding mode needs to be more flexible
991 case Type::FloatTyID: {
992 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
994 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
997 case Type::DoubleTyID: {
998 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
999 &Val2.getSemantics() == &APFloat::IEEEdouble)
1001 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
1004 case Type::X86_FP80TyID:
1005 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1006 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1007 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
1008 case Type::FP128TyID:
1009 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1010 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1011 &Val2.getSemantics() == &APFloat::IEEEquad;
1012 case Type::PPC_FP128TyID:
1013 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1014 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1015 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
1019 //===----------------------------------------------------------------------===//
1020 // Factory Function Implementation
1022 /// destroyConstant - Remove the constant from the constant table...
1024 void ConstantAggregateZero::destroyConstant() {
1025 // Implicitly locked.
1026 getType()->getContext().erase(this);
1027 destroyConstantImpl();
1030 /// destroyConstant - Remove the constant from the constant table...
1032 void ConstantArray::destroyConstant() {
1033 // Implicitly locked.
1034 getType()->getContext().pImpl->ArrayConstants.remove(this);
1035 destroyConstantImpl();
1038 /// isString - This method returns true if the array is an array of i8, and
1039 /// if the elements of the array are all ConstantInt's.
1040 bool ConstantArray::isString() const {
1041 // Check the element type for i8...
1042 if (getType()->getElementType() != Type::Int8Ty)
1044 // Check the elements to make sure they are all integers, not constant
1046 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1047 if (!isa<ConstantInt>(getOperand(i)))
1052 /// isCString - This method returns true if the array is a string (see
1053 /// isString) and it ends in a null byte \\0 and does not contains any other
1054 /// null bytes except its terminator.
1055 bool ConstantArray::isCString() const {
1056 // Check the element type for i8...
1057 if (getType()->getElementType() != Type::Int8Ty)
1060 // Last element must be a null.
1061 if (!getOperand(getNumOperands()-1)->isNullValue())
1063 // Other elements must be non-null integers.
1064 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1065 if (!isa<ConstantInt>(getOperand(i)))
1067 if (getOperand(i)->isNullValue())
1074 /// getAsString - If the sub-element type of this array is i8
1075 /// then this method converts the array to an std::string and returns it.
1076 /// Otherwise, it asserts out.
1078 std::string ConstantArray::getAsString() const {
1079 assert(isString() && "Not a string!");
1081 Result.reserve(getNumOperands());
1082 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1083 Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
1088 //---- ConstantStruct::get() implementation...
1095 // destroyConstant - Remove the constant from the constant table...
1097 void ConstantStruct::destroyConstant() {
1098 // Implicitly locked.
1099 getType()->getContext().pImpl->StructConstants.remove(this);
1100 destroyConstantImpl();
1103 // destroyConstant - Remove the constant from the constant table...
1105 void ConstantVector::destroyConstant() {
1106 // Implicitly locked.
1107 getType()->getContext().pImpl->VectorConstants.remove(this);
1108 destroyConstantImpl();
1111 /// This function will return true iff every element in this vector constant
1112 /// is set to all ones.
1113 /// @returns true iff this constant's emements are all set to all ones.
1114 /// @brief Determine if the value is all ones.
1115 bool ConstantVector::isAllOnesValue() const {
1116 // Check out first element.
1117 const Constant *Elt = getOperand(0);
1118 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1119 if (!CI || !CI->isAllOnesValue()) return false;
1120 // Then make sure all remaining elements point to the same value.
1121 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1122 if (getOperand(I) != Elt) return false;
1127 /// getSplatValue - If this is a splat constant, where all of the
1128 /// elements have the same value, return that value. Otherwise return null.
1129 Constant *ConstantVector::getSplatValue() {
1130 // Check out first element.
1131 Constant *Elt = getOperand(0);
1132 // Then make sure all remaining elements point to the same value.
1133 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1134 if (getOperand(I) != Elt) return 0;
1138 //---- ConstantPointerNull::get() implementation...
1142 // ConstantPointerNull does not take extra "value" argument...
1143 template<class ValType>
1144 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1145 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1146 return new ConstantPointerNull(Ty);
1151 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1152 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1153 // Make everyone now use a constant of the new type...
1154 Constant *New = ConstantPointerNull::get(NewTy);
1155 assert(New != OldC && "Didn't replace constant??");
1156 OldC->uncheckedReplaceAllUsesWith(New);
1157 OldC->destroyConstant(); // This constant is now dead, destroy it.
1162 static ManagedStatic<ValueMap<char, PointerType,
1163 ConstantPointerNull> > NullPtrConstants;
1165 static char getValType(ConstantPointerNull *) {
1170 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1171 // Implicitly locked.
1172 return NullPtrConstants->getOrCreate(Ty, 0);
1175 // destroyConstant - Remove the constant from the constant table...
1177 void ConstantPointerNull::destroyConstant() {
1178 // Implicitly locked.
1179 NullPtrConstants->remove(this);
1180 destroyConstantImpl();
1184 //---- UndefValue::get() implementation...
1188 // UndefValue does not take extra "value" argument...
1189 template<class ValType>
1190 struct ConstantCreator<UndefValue, Type, ValType> {
1191 static UndefValue *create(const Type *Ty, const ValType &V) {
1192 return new UndefValue(Ty);
1197 struct ConvertConstantType<UndefValue, Type> {
1198 static void convert(UndefValue *OldC, const Type *NewTy) {
1199 // Make everyone now use a constant of the new type.
1200 Constant *New = UndefValue::get(NewTy);
1201 assert(New != OldC && "Didn't replace constant??");
1202 OldC->uncheckedReplaceAllUsesWith(New);
1203 OldC->destroyConstant(); // This constant is now dead, destroy it.
1208 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1210 static char getValType(UndefValue *) {
1215 UndefValue *UndefValue::get(const Type *Ty) {
1216 // Implicitly locked.
1217 return UndefValueConstants->getOrCreate(Ty, 0);
1220 // destroyConstant - Remove the constant from the constant table.
1222 void UndefValue::destroyConstant() {
1223 // Implicitly locked.
1224 UndefValueConstants->remove(this);
1225 destroyConstantImpl();
1228 //---- MDNode::get() implementation
1231 MDNode::MDNode(Value*const* Vals, unsigned NumVals)
1232 : MetadataBase(Type::MetadataTy, Value::MDNodeVal) {
1233 for (unsigned i = 0; i != NumVals; ++i)
1234 Node.push_back(WeakVH(Vals[i]));
1237 void MDNode::Profile(FoldingSetNodeID &ID) const {
1238 for (const_elem_iterator I = elem_begin(), E = elem_end(); I != E; ++I)
1242 //---- ConstantExpr::get() implementations...
1247 struct ExprMapKeyType {
1248 typedef SmallVector<unsigned, 4> IndexList;
1250 ExprMapKeyType(unsigned opc,
1251 const std::vector<Constant*> &ops,
1252 unsigned short pred = 0,
1253 const IndexList &inds = IndexList())
1254 : opcode(opc), predicate(pred), operands(ops), indices(inds) {}
1257 std::vector<Constant*> operands;
1259 bool operator==(const ExprMapKeyType& that) const {
1260 return this->opcode == that.opcode &&
1261 this->predicate == that.predicate &&
1262 this->operands == that.operands &&
1263 this->indices == that.indices;
1265 bool operator<(const ExprMapKeyType & that) const {
1266 return this->opcode < that.opcode ||
1267 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1268 (this->opcode == that.opcode && this->predicate == that.predicate &&
1269 this->operands < that.operands) ||
1270 (this->opcode == that.opcode && this->predicate == that.predicate &&
1271 this->operands == that.operands && this->indices < that.indices);
1274 bool operator!=(const ExprMapKeyType& that) const {
1275 return !(*this == that);
1283 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1284 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1285 unsigned short pred = 0) {
1286 if (Instruction::isCast(V.opcode))
1287 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1288 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1289 V.opcode < Instruction::BinaryOpsEnd))
1290 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1291 if (V.opcode == Instruction::Select)
1292 return new SelectConstantExpr(V.operands[0], V.operands[1],
1294 if (V.opcode == Instruction::ExtractElement)
1295 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1296 if (V.opcode == Instruction::InsertElement)
1297 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1299 if (V.opcode == Instruction::ShuffleVector)
1300 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1302 if (V.opcode == Instruction::InsertValue)
1303 return new InsertValueConstantExpr(V.operands[0], V.operands[1],
1305 if (V.opcode == Instruction::ExtractValue)
1306 return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
1307 if (V.opcode == Instruction::GetElementPtr) {
1308 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1309 return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
1312 // The compare instructions are weird. We have to encode the predicate
1313 // value and it is combined with the instruction opcode by multiplying
1314 // the opcode by one hundred. We must decode this to get the predicate.
1315 if (V.opcode == Instruction::ICmp)
1316 return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate,
1317 V.operands[0], V.operands[1]);
1318 if (V.opcode == Instruction::FCmp)
1319 return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate,
1320 V.operands[0], V.operands[1]);
1321 llvm_unreachable("Invalid ConstantExpr!");
1327 struct ConvertConstantType<ConstantExpr, Type> {
1328 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1330 switch (OldC->getOpcode()) {
1331 case Instruction::Trunc:
1332 case Instruction::ZExt:
1333 case Instruction::SExt:
1334 case Instruction::FPTrunc:
1335 case Instruction::FPExt:
1336 case Instruction::UIToFP:
1337 case Instruction::SIToFP:
1338 case Instruction::FPToUI:
1339 case Instruction::FPToSI:
1340 case Instruction::PtrToInt:
1341 case Instruction::IntToPtr:
1342 case Instruction::BitCast:
1343 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1346 case Instruction::Select:
1347 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1348 OldC->getOperand(1),
1349 OldC->getOperand(2));
1352 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1353 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1354 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1355 OldC->getOperand(1));
1357 case Instruction::GetElementPtr:
1358 // Make everyone now use a constant of the new type...
1359 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1360 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1361 &Idx[0], Idx.size());
1365 assert(New != OldC && "Didn't replace constant??");
1366 OldC->uncheckedReplaceAllUsesWith(New);
1367 OldC->destroyConstant(); // This constant is now dead, destroy it.
1370 } // end namespace llvm
1373 static ExprMapKeyType getValType(ConstantExpr *CE) {
1374 std::vector<Constant*> Operands;
1375 Operands.reserve(CE->getNumOperands());
1376 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1377 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1378 return ExprMapKeyType(CE->getOpcode(), Operands,
1379 CE->isCompare() ? CE->getPredicate() : 0,
1381 CE->getIndices() : SmallVector<unsigned, 4>());
1384 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1385 ConstantExpr> > ExprConstants;
1387 /// This is a utility function to handle folding of casts and lookup of the
1388 /// cast in the ExprConstants map. It is used by the various get* methods below.
1389 static inline Constant *getFoldedCast(
1390 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1391 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1392 // Fold a few common cases
1394 ConstantFoldCastInstruction(getGlobalContext(), opc, C, Ty))
1397 // Look up the constant in the table first to ensure uniqueness
1398 std::vector<Constant*> argVec(1, C);
1399 ExprMapKeyType Key(opc, argVec);
1401 // Implicitly locked.
1402 return ExprConstants->getOrCreate(Ty, Key);
1405 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1406 Instruction::CastOps opc = Instruction::CastOps(oc);
1407 assert(Instruction::isCast(opc) && "opcode out of range");
1408 assert(C && Ty && "Null arguments to getCast");
1409 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1413 llvm_unreachable("Invalid cast opcode");
1415 case Instruction::Trunc: return getTrunc(C, Ty);
1416 case Instruction::ZExt: return getZExt(C, Ty);
1417 case Instruction::SExt: return getSExt(C, Ty);
1418 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1419 case Instruction::FPExt: return getFPExtend(C, Ty);
1420 case Instruction::UIToFP: return getUIToFP(C, Ty);
1421 case Instruction::SIToFP: return getSIToFP(C, Ty);
1422 case Instruction::FPToUI: return getFPToUI(C, Ty);
1423 case Instruction::FPToSI: return getFPToSI(C, Ty);
1424 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1425 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1426 case Instruction::BitCast: return getBitCast(C, Ty);
1431 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1432 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1433 return getCast(Instruction::BitCast, C, Ty);
1434 return getCast(Instruction::ZExt, C, Ty);
1437 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1438 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1439 return getCast(Instruction::BitCast, C, Ty);
1440 return getCast(Instruction::SExt, C, Ty);
1443 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1444 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1445 return getCast(Instruction::BitCast, C, Ty);
1446 return getCast(Instruction::Trunc, C, Ty);
1449 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1450 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1451 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1453 if (Ty->isInteger())
1454 return getCast(Instruction::PtrToInt, S, Ty);
1455 return getCast(Instruction::BitCast, S, Ty);
1458 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1460 assert(C->getType()->isIntOrIntVector() &&
1461 Ty->isIntOrIntVector() && "Invalid cast");
1462 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1463 unsigned DstBits = Ty->getScalarSizeInBits();
1464 Instruction::CastOps opcode =
1465 (SrcBits == DstBits ? Instruction::BitCast :
1466 (SrcBits > DstBits ? Instruction::Trunc :
1467 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1468 return getCast(opcode, C, Ty);
1471 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1472 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1474 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1475 unsigned DstBits = Ty->getScalarSizeInBits();
1476 if (SrcBits == DstBits)
1477 return C; // Avoid a useless cast
1478 Instruction::CastOps opcode =
1479 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1480 return getCast(opcode, C, Ty);
1483 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1485 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1486 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1488 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1489 assert(C->getType()->isIntOrIntVector() && "Trunc operand must be integer");
1490 assert(Ty->isIntOrIntVector() && "Trunc produces only integral");
1491 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1492 "SrcTy must be larger than DestTy for Trunc!");
1494 return getFoldedCast(Instruction::Trunc, C, Ty);
1497 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1499 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1500 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1502 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1503 assert(C->getType()->isIntOrIntVector() && "SExt operand must be integral");
1504 assert(Ty->isIntOrIntVector() && "SExt produces only integer");
1505 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1506 "SrcTy must be smaller than DestTy for SExt!");
1508 return getFoldedCast(Instruction::SExt, C, Ty);
1511 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1513 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1514 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1516 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1517 assert(C->getType()->isIntOrIntVector() && "ZEXt operand must be integral");
1518 assert(Ty->isIntOrIntVector() && "ZExt produces only integer");
1519 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1520 "SrcTy must be smaller than DestTy for ZExt!");
1522 return getFoldedCast(Instruction::ZExt, C, Ty);
1525 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1527 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1528 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1530 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1531 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1532 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1533 "This is an illegal floating point truncation!");
1534 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1537 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1539 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1540 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1542 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1543 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1544 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1545 "This is an illegal floating point extension!");
1546 return getFoldedCast(Instruction::FPExt, C, Ty);
1549 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1551 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1552 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1554 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1555 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1556 "This is an illegal uint to floating point cast!");
1557 return getFoldedCast(Instruction::UIToFP, C, Ty);
1560 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1562 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1563 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1565 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1566 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1567 "This is an illegal sint to floating point cast!");
1568 return getFoldedCast(Instruction::SIToFP, C, Ty);
1571 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1573 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1574 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1576 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1577 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1578 "This is an illegal floating point to uint cast!");
1579 return getFoldedCast(Instruction::FPToUI, C, Ty);
1582 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1584 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1585 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1587 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1588 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1589 "This is an illegal floating point to sint cast!");
1590 return getFoldedCast(Instruction::FPToSI, C, Ty);
1593 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1594 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1595 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1596 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1599 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1600 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1601 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1602 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1605 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1606 // BitCast implies a no-op cast of type only. No bits change. However, you
1607 // can't cast pointers to anything but pointers.
1609 const Type *SrcTy = C->getType();
1610 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1611 "BitCast cannot cast pointer to non-pointer and vice versa");
1613 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1614 // or nonptr->ptr). For all the other types, the cast is okay if source and
1615 // destination bit widths are identical.
1616 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1617 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1619 assert(SrcBitSize == DstBitSize && "BitCast requires types of same width");
1621 // It is common to ask for a bitcast of a value to its own type, handle this
1623 if (C->getType() == DstTy) return C;
1625 return getFoldedCast(Instruction::BitCast, C, DstTy);
1628 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1629 Constant *C1, Constant *C2) {
1630 // Check the operands for consistency first
1631 assert(Opcode >= Instruction::BinaryOpsBegin &&
1632 Opcode < Instruction::BinaryOpsEnd &&
1633 "Invalid opcode in binary constant expression");
1634 assert(C1->getType() == C2->getType() &&
1635 "Operand types in binary constant expression should match");
1637 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
1638 if (Constant *FC = ConstantFoldBinaryInstruction(
1639 getGlobalContext(), Opcode, C1, C2))
1640 return FC; // Fold a few common cases...
1642 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1643 ExprMapKeyType Key(Opcode, argVec);
1645 // Implicitly locked.
1646 return ExprConstants->getOrCreate(ReqTy, Key);
1649 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1650 Constant *C1, Constant *C2) {
1651 switch (predicate) {
1652 default: llvm_unreachable("Invalid CmpInst predicate");
1653 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1654 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1655 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1656 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1657 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1658 case CmpInst::FCMP_TRUE:
1659 return getFCmp(predicate, C1, C2);
1661 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1662 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1663 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1664 case CmpInst::ICMP_SLE:
1665 return getICmp(predicate, C1, C2);
1669 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1670 // API compatibility: Adjust integer opcodes to floating-point opcodes.
1671 if (C1->getType()->isFPOrFPVector()) {
1672 if (Opcode == Instruction::Add) Opcode = Instruction::FAdd;
1673 else if (Opcode == Instruction::Sub) Opcode = Instruction::FSub;
1674 else if (Opcode == Instruction::Mul) Opcode = Instruction::FMul;
1678 case Instruction::Add:
1679 case Instruction::Sub:
1680 case Instruction::Mul:
1681 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1682 assert(C1->getType()->isIntOrIntVector() &&
1683 "Tried to create an integer operation on a non-integer type!");
1685 case Instruction::FAdd:
1686 case Instruction::FSub:
1687 case Instruction::FMul:
1688 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1689 assert(C1->getType()->isFPOrFPVector() &&
1690 "Tried to create a floating-point operation on a "
1691 "non-floating-point type!");
1693 case Instruction::UDiv:
1694 case Instruction::SDiv:
1695 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1696 assert(C1->getType()->isIntOrIntVector() &&
1697 "Tried to create an arithmetic operation on a non-arithmetic type!");
1699 case Instruction::FDiv:
1700 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1701 assert(C1->getType()->isFPOrFPVector() &&
1702 "Tried to create an arithmetic operation on a non-arithmetic type!");
1704 case Instruction::URem:
1705 case Instruction::SRem:
1706 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1707 assert(C1->getType()->isIntOrIntVector() &&
1708 "Tried to create an arithmetic operation on a non-arithmetic type!");
1710 case Instruction::FRem:
1711 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1712 assert(C1->getType()->isFPOrFPVector() &&
1713 "Tried to create an arithmetic operation on a non-arithmetic type!");
1715 case Instruction::And:
1716 case Instruction::Or:
1717 case Instruction::Xor:
1718 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1719 assert(C1->getType()->isIntOrIntVector() &&
1720 "Tried to create a logical operation on a non-integral type!");
1722 case Instruction::Shl:
1723 case Instruction::LShr:
1724 case Instruction::AShr:
1725 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1726 assert(C1->getType()->isIntOrIntVector() &&
1727 "Tried to create a shift operation on a non-integer type!");
1734 return getTy(C1->getType(), Opcode, C1, C2);
1737 Constant *ConstantExpr::getCompare(unsigned short pred,
1738 Constant *C1, Constant *C2) {
1739 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1740 return getCompareTy(pred, C1, C2);
1743 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1744 Constant *V1, Constant *V2) {
1745 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1747 if (ReqTy == V1->getType())
1748 if (Constant *SC = ConstantFoldSelectInstruction(
1749 getGlobalContext(), C, V1, V2))
1750 return SC; // Fold common cases
1752 std::vector<Constant*> argVec(3, C);
1755 ExprMapKeyType Key(Instruction::Select, argVec);
1757 // Implicitly locked.
1758 return ExprConstants->getOrCreate(ReqTy, Key);
1761 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1764 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
1766 cast<PointerType>(ReqTy)->getElementType() &&
1767 "GEP indices invalid!");
1769 if (Constant *FC = ConstantFoldGetElementPtr(
1770 getGlobalContext(), C, (Constant**)Idxs, NumIdx))
1771 return FC; // Fold a few common cases...
1773 assert(isa<PointerType>(C->getType()) &&
1774 "Non-pointer type for constant GetElementPtr expression");
1775 // Look up the constant in the table first to ensure uniqueness
1776 std::vector<Constant*> ArgVec;
1777 ArgVec.reserve(NumIdx+1);
1778 ArgVec.push_back(C);
1779 for (unsigned i = 0; i != NumIdx; ++i)
1780 ArgVec.push_back(cast<Constant>(Idxs[i]));
1781 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
1783 // Implicitly locked.
1784 return ExprConstants->getOrCreate(ReqTy, Key);
1787 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1789 // Get the result type of the getelementptr!
1791 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
1792 assert(Ty && "GEP indices invalid!");
1793 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
1794 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
1797 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1799 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1804 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1805 assert(LHS->getType() == RHS->getType());
1806 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1807 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1809 if (Constant *FC = ConstantFoldCompareInstruction(
1810 getGlobalContext(),pred, LHS, RHS))
1811 return FC; // Fold a few common cases...
1813 // Look up the constant in the table first to ensure uniqueness
1814 std::vector<Constant*> ArgVec;
1815 ArgVec.push_back(LHS);
1816 ArgVec.push_back(RHS);
1817 // Get the key type with both the opcode and predicate
1818 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1820 // Implicitly locked.
1821 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1825 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1826 assert(LHS->getType() == RHS->getType());
1827 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1829 if (Constant *FC = ConstantFoldCompareInstruction(
1830 getGlobalContext(), pred, LHS, RHS))
1831 return FC; // Fold a few common cases...
1833 // Look up the constant in the table first to ensure uniqueness
1834 std::vector<Constant*> ArgVec;
1835 ArgVec.push_back(LHS);
1836 ArgVec.push_back(RHS);
1837 // Get the key type with both the opcode and predicate
1838 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1840 // Implicitly locked.
1841 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1844 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1846 if (Constant *FC = ConstantFoldExtractElementInstruction(
1847 getGlobalContext(), Val, Idx))
1848 return FC; // Fold a few common cases...
1849 // Look up the constant in the table first to ensure uniqueness
1850 std::vector<Constant*> ArgVec(1, Val);
1851 ArgVec.push_back(Idx);
1852 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1854 // Implicitly locked.
1855 return ExprConstants->getOrCreate(ReqTy, Key);
1858 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1859 assert(isa<VectorType>(Val->getType()) &&
1860 "Tried to create extractelement operation on non-vector type!");
1861 assert(Idx->getType() == Type::Int32Ty &&
1862 "Extractelement index must be i32 type!");
1863 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
1867 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1868 Constant *Elt, Constant *Idx) {
1869 if (Constant *FC = ConstantFoldInsertElementInstruction(
1870 getGlobalContext(), Val, Elt, Idx))
1871 return FC; // Fold a few common cases...
1872 // Look up the constant in the table first to ensure uniqueness
1873 std::vector<Constant*> ArgVec(1, Val);
1874 ArgVec.push_back(Elt);
1875 ArgVec.push_back(Idx);
1876 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1878 // Implicitly locked.
1879 return ExprConstants->getOrCreate(ReqTy, Key);
1882 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1884 assert(isa<VectorType>(Val->getType()) &&
1885 "Tried to create insertelement operation on non-vector type!");
1886 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
1887 && "Insertelement types must match!");
1888 assert(Idx->getType() == Type::Int32Ty &&
1889 "Insertelement index must be i32 type!");
1890 return getInsertElementTy(Val->getType(), Val, Elt, Idx);
1893 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1894 Constant *V2, Constant *Mask) {
1895 if (Constant *FC = ConstantFoldShuffleVectorInstruction(
1896 getGlobalContext(), V1, V2, Mask))
1897 return FC; // Fold a few common cases...
1898 // Look up the constant in the table first to ensure uniqueness
1899 std::vector<Constant*> ArgVec(1, V1);
1900 ArgVec.push_back(V2);
1901 ArgVec.push_back(Mask);
1902 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1904 // Implicitly locked.
1905 return ExprConstants->getOrCreate(ReqTy, Key);
1908 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1910 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1911 "Invalid shuffle vector constant expr operands!");
1913 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
1914 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
1915 const Type *ShufTy = VectorType::get(EltTy, NElts);
1916 return getShuffleVectorTy(ShufTy, V1, V2, Mask);
1919 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
1921 const unsigned *Idxs, unsigned NumIdx) {
1922 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1923 Idxs+NumIdx) == Val->getType() &&
1924 "insertvalue indices invalid!");
1925 assert(Agg->getType() == ReqTy &&
1926 "insertvalue type invalid!");
1927 assert(Agg->getType()->isFirstClassType() &&
1928 "Non-first-class type for constant InsertValue expression");
1929 Constant *FC = ConstantFoldInsertValueInstruction(
1930 getGlobalContext(), Agg, Val, Idxs, NumIdx);
1931 assert(FC && "InsertValue constant expr couldn't be folded!");
1935 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
1936 const unsigned *IdxList, unsigned NumIdx) {
1937 assert(Agg->getType()->isFirstClassType() &&
1938 "Tried to create insertelement operation on non-first-class type!");
1940 const Type *ReqTy = Agg->getType();
1943 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1945 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
1946 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
1949 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
1950 const unsigned *Idxs, unsigned NumIdx) {
1951 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1952 Idxs+NumIdx) == ReqTy &&
1953 "extractvalue indices invalid!");
1954 assert(Agg->getType()->isFirstClassType() &&
1955 "Non-first-class type for constant extractvalue expression");
1956 Constant *FC = ConstantFoldExtractValueInstruction(
1957 getGlobalContext(), Agg, Idxs, NumIdx);
1958 assert(FC && "ExtractValue constant expr couldn't be folded!");
1962 Constant *ConstantExpr::getExtractValue(Constant *Agg,
1963 const unsigned *IdxList, unsigned NumIdx) {
1964 assert(Agg->getType()->isFirstClassType() &&
1965 "Tried to create extractelement operation on non-first-class type!");
1968 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1969 assert(ReqTy && "extractvalue indices invalid!");
1970 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
1973 // destroyConstant - Remove the constant from the constant table...
1975 void ConstantExpr::destroyConstant() {
1976 // Implicitly locked.
1977 ExprConstants->remove(this);
1978 destroyConstantImpl();
1981 const char *ConstantExpr::getOpcodeName() const {
1982 return Instruction::getOpcodeName(getOpcode());
1985 //===----------------------------------------------------------------------===//
1986 // replaceUsesOfWithOnConstant implementations
1988 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
1989 /// 'From' to be uses of 'To'. This must update the uniquing data structures
1992 /// Note that we intentionally replace all uses of From with To here. Consider
1993 /// a large array that uses 'From' 1000 times. By handling this case all here,
1994 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
1995 /// single invocation handles all 1000 uses. Handling them one at a time would
1996 /// work, but would be really slow because it would have to unique each updated
1999 static std::vector<Constant*> getValType(ConstantArray *CA) {
2000 std::vector<Constant*> Elements;
2001 Elements.reserve(CA->getNumOperands());
2002 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
2003 Elements.push_back(cast<Constant>(CA->getOperand(i)));
2008 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
2010 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2011 Constant *ToC = cast<Constant>(To);
2013 LLVMContext &Context = getType()->getContext();
2014 LLVMContextImpl *pImpl = Context.pImpl;
2016 std::pair<LLVMContextImpl::ArrayConstantsTy::MapKey, Constant*> Lookup;
2017 Lookup.first.first = getType();
2018 Lookup.second = this;
2020 std::vector<Constant*> &Values = Lookup.first.second;
2021 Values.reserve(getNumOperands()); // Build replacement array.
2023 // Fill values with the modified operands of the constant array. Also,
2024 // compute whether this turns into an all-zeros array.
2025 bool isAllZeros = false;
2026 unsigned NumUpdated = 0;
2027 if (!ToC->isNullValue()) {
2028 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2029 Constant *Val = cast<Constant>(O->get());
2034 Values.push_back(Val);
2038 for (Use *O = OperandList, *E = OperandList+getNumOperands();O != E; ++O) {
2039 Constant *Val = cast<Constant>(O->get());
2044 Values.push_back(Val);
2045 if (isAllZeros) isAllZeros = Val->isNullValue();
2049 Constant *Replacement = 0;
2051 Replacement = Context.getConstantAggregateZero(getType());
2053 // Check to see if we have this array type already.
2054 sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
2056 LLVMContextImpl::ArrayConstantsTy::MapTy::iterator I =
2057 pImpl->ArrayConstants.InsertOrGetItem(Lookup, Exists);
2060 Replacement = I->second;
2062 // Okay, the new shape doesn't exist in the system yet. Instead of
2063 // creating a new constant array, inserting it, replaceallusesof'ing the
2064 // old with the new, then deleting the old... just update the current one
2066 pImpl->ArrayConstants.MoveConstantToNewSlot(this, I);
2068 // Update to the new value. Optimize for the case when we have a single
2069 // operand that we're changing, but handle bulk updates efficiently.
2070 if (NumUpdated == 1) {
2071 unsigned OperandToUpdate = U - OperandList;
2072 assert(getOperand(OperandToUpdate) == From &&
2073 "ReplaceAllUsesWith broken!");
2074 setOperand(OperandToUpdate, ToC);
2076 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2077 if (getOperand(i) == From)
2084 // Otherwise, I do need to replace this with an existing value.
2085 assert(Replacement != this && "I didn't contain From!");
2087 // Everyone using this now uses the replacement.
2088 uncheckedReplaceAllUsesWith(Replacement);
2090 // Delete the old constant!
2094 static std::vector<Constant*> getValType(ConstantStruct *CS) {
2095 std::vector<Constant*> Elements;
2096 Elements.reserve(CS->getNumOperands());
2097 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
2098 Elements.push_back(cast<Constant>(CS->getOperand(i)));
2102 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2104 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2105 Constant *ToC = cast<Constant>(To);
2107 unsigned OperandToUpdate = U-OperandList;
2108 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2110 std::pair<LLVMContextImpl::StructConstantsTy::MapKey, Constant*> Lookup;
2111 Lookup.first.first = getType();
2112 Lookup.second = this;
2113 std::vector<Constant*> &Values = Lookup.first.second;
2114 Values.reserve(getNumOperands()); // Build replacement struct.
2117 // Fill values with the modified operands of the constant struct. Also,
2118 // compute whether this turns into an all-zeros struct.
2119 bool isAllZeros = false;
2120 if (!ToC->isNullValue()) {
2121 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
2122 Values.push_back(cast<Constant>(O->get()));
2125 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2126 Constant *Val = cast<Constant>(O->get());
2127 Values.push_back(Val);
2128 if (isAllZeros) isAllZeros = Val->isNullValue();
2131 Values[OperandToUpdate] = ToC;
2133 LLVMContext &Context = getType()->getContext();
2134 LLVMContextImpl *pImpl = Context.pImpl;
2136 Constant *Replacement = 0;
2138 Replacement = Context.getConstantAggregateZero(getType());
2140 // Check to see if we have this array type already.
2141 sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
2143 LLVMContextImpl::StructConstantsTy::MapTy::iterator I =
2144 pImpl->StructConstants.InsertOrGetItem(Lookup, Exists);
2147 Replacement = I->second;
2149 // Okay, the new shape doesn't exist in the system yet. Instead of
2150 // creating a new constant struct, inserting it, replaceallusesof'ing the
2151 // old with the new, then deleting the old... just update the current one
2153 pImpl->StructConstants.MoveConstantToNewSlot(this, I);
2155 // Update to the new value.
2156 setOperand(OperandToUpdate, ToC);
2161 assert(Replacement != this && "I didn't contain From!");
2163 // Everyone using this now uses the replacement.
2164 uncheckedReplaceAllUsesWith(Replacement);
2166 // Delete the old constant!
2170 static std::vector<Constant*> getValType(ConstantVector *CP) {
2171 std::vector<Constant*> Elements;
2172 Elements.reserve(CP->getNumOperands());
2173 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
2174 Elements.push_back(CP->getOperand(i));
2178 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2180 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2182 std::vector<Constant*> Values;
2183 Values.reserve(getNumOperands()); // Build replacement array...
2184 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2185 Constant *Val = getOperand(i);
2186 if (Val == From) Val = cast<Constant>(To);
2187 Values.push_back(Val);
2190 Constant *Replacement = get(getType(), Values);
2191 assert(Replacement != this && "I didn't contain From!");
2193 // Everyone using this now uses the replacement.
2194 uncheckedReplaceAllUsesWith(Replacement);
2196 // Delete the old constant!
2200 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2202 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2203 Constant *To = cast<Constant>(ToV);
2205 Constant *Replacement = 0;
2206 if (getOpcode() == Instruction::GetElementPtr) {
2207 SmallVector<Constant*, 8> Indices;
2208 Constant *Pointer = getOperand(0);
2209 Indices.reserve(getNumOperands()-1);
2210 if (Pointer == From) Pointer = To;
2212 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2213 Constant *Val = getOperand(i);
2214 if (Val == From) Val = To;
2215 Indices.push_back(Val);
2217 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2218 &Indices[0], Indices.size());
2219 } else if (getOpcode() == Instruction::ExtractValue) {
2220 Constant *Agg = getOperand(0);
2221 if (Agg == From) Agg = To;
2223 const SmallVector<unsigned, 4> &Indices = getIndices();
2224 Replacement = ConstantExpr::getExtractValue(Agg,
2225 &Indices[0], Indices.size());
2226 } else if (getOpcode() == Instruction::InsertValue) {
2227 Constant *Agg = getOperand(0);
2228 Constant *Val = getOperand(1);
2229 if (Agg == From) Agg = To;
2230 if (Val == From) Val = To;
2232 const SmallVector<unsigned, 4> &Indices = getIndices();
2233 Replacement = ConstantExpr::getInsertValue(Agg, Val,
2234 &Indices[0], Indices.size());
2235 } else if (isCast()) {
2236 assert(getOperand(0) == From && "Cast only has one use!");
2237 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2238 } else if (getOpcode() == Instruction::Select) {
2239 Constant *C1 = getOperand(0);
2240 Constant *C2 = getOperand(1);
2241 Constant *C3 = getOperand(2);
2242 if (C1 == From) C1 = To;
2243 if (C2 == From) C2 = To;
2244 if (C3 == From) C3 = To;
2245 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2246 } else if (getOpcode() == Instruction::ExtractElement) {
2247 Constant *C1 = getOperand(0);
2248 Constant *C2 = getOperand(1);
2249 if (C1 == From) C1 = To;
2250 if (C2 == From) C2 = To;
2251 Replacement = ConstantExpr::getExtractElement(C1, C2);
2252 } else if (getOpcode() == Instruction::InsertElement) {
2253 Constant *C1 = getOperand(0);
2254 Constant *C2 = getOperand(1);
2255 Constant *C3 = getOperand(1);
2256 if (C1 == From) C1 = To;
2257 if (C2 == From) C2 = To;
2258 if (C3 == From) C3 = To;
2259 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2260 } else if (getOpcode() == Instruction::ShuffleVector) {
2261 Constant *C1 = getOperand(0);
2262 Constant *C2 = getOperand(1);
2263 Constant *C3 = getOperand(2);
2264 if (C1 == From) C1 = To;
2265 if (C2 == From) C2 = To;
2266 if (C3 == From) C3 = To;
2267 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2268 } else if (isCompare()) {
2269 Constant *C1 = getOperand(0);
2270 Constant *C2 = getOperand(1);
2271 if (C1 == From) C1 = To;
2272 if (C2 == From) C2 = To;
2273 if (getOpcode() == Instruction::ICmp)
2274 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2276 assert(getOpcode() == Instruction::FCmp);
2277 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2279 } else if (getNumOperands() == 2) {
2280 Constant *C1 = getOperand(0);
2281 Constant *C2 = getOperand(1);
2282 if (C1 == From) C1 = To;
2283 if (C2 == From) C2 = To;
2284 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2286 llvm_unreachable("Unknown ConstantExpr type!");
2290 assert(Replacement != this && "I didn't contain From!");
2292 // Everyone using this now uses the replacement.
2293 uncheckedReplaceAllUsesWith(Replacement);
2295 // Delete the old constant!
2299 void MDNode::replaceElement(Value *From, Value *To) {
2300 SmallVector<Value*, 4> Values;
2301 Values.reserve(getNumElements()); // Build replacement array...
2302 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
2303 Value *Val = getElement(i);
2304 if (Val == From) Val = To;
2305 Values.push_back(Val);
2308 MDNode *Replacement =
2309 getType()->getContext().getMDNode(&Values[0], Values.size());
2310 assert(Replacement != this && "I didn't contain From!");
2312 uncheckedReplaceAllUsesWith(Replacement);