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 "ConstantFold.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/GlobalValue.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/MDNode.h"
20 #include "llvm/Module.h"
21 #include "llvm/ADT/FoldingSet.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/StringMap.h"
24 #include "llvm/Support/Compiler.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/ManagedStatic.h"
27 #include "llvm/Support/MathExtras.h"
28 #include "llvm/System/Mutex.h"
29 #include "llvm/System/RWMutex.h"
30 #include "llvm/System/Threading.h"
31 #include "llvm/ADT/DenseMap.h"
32 #include "llvm/ADT/SmallVector.h"
37 //===----------------------------------------------------------------------===//
39 //===----------------------------------------------------------------------===//
41 // Becomes a no-op when multithreading is disabled.
42 ManagedStatic<sys::SmartRWMutex<true> > ConstantsLock;
44 void Constant::destroyConstantImpl() {
45 // When a Constant is destroyed, there may be lingering
46 // references to the constant by other constants in the constant pool. These
47 // constants are implicitly dependent on the module that is being deleted,
48 // but they don't know that. Because we only find out when the CPV is
49 // deleted, we must now notify all of our users (that should only be
50 // Constants) that they are, in fact, invalid now and should be deleted.
52 while (!use_empty()) {
53 Value *V = use_back();
54 #ifndef NDEBUG // Only in -g mode...
55 if (!isa<Constant>(V))
56 DOUT << "While deleting: " << *this
57 << "\n\nUse still stuck around after Def is destroyed: "
60 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
61 Constant *CV = cast<Constant>(V);
62 CV->destroyConstant();
64 // The constant should remove itself from our use list...
65 assert((use_empty() || use_back() != V) && "Constant not removed!");
68 // Value has no outstanding references it is safe to delete it now...
72 /// canTrap - Return true if evaluation of this constant could trap. This is
73 /// true for things like constant expressions that could divide by zero.
74 bool Constant::canTrap() const {
75 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
76 // The only thing that could possibly trap are constant exprs.
77 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
78 if (!CE) return false;
80 // ConstantExpr traps if any operands can trap.
81 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
82 if (getOperand(i)->canTrap())
85 // Otherwise, only specific operations can trap.
86 switch (CE->getOpcode()) {
89 case Instruction::UDiv:
90 case Instruction::SDiv:
91 case Instruction::FDiv:
92 case Instruction::URem:
93 case Instruction::SRem:
94 case Instruction::FRem:
95 // Div and rem can trap if the RHS is not known to be non-zero.
96 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
102 /// ContainsRelocations - Return true if the constant value contains relocations
103 /// which cannot be resolved at compile time. Kind argument is used to filter
104 /// only 'interesting' sorts of relocations.
105 bool Constant::ContainsRelocations(unsigned Kind) const {
106 if (const GlobalValue* GV = dyn_cast<GlobalValue>(this)) {
107 bool isLocal = GV->hasLocalLinkage();
108 if ((Kind & Reloc::Local) && isLocal) {
109 // Global has local linkage and 'local' kind of relocations are
114 if ((Kind & Reloc::Global) && !isLocal) {
115 // Global has non-local linkage and 'global' kind of relocations are
123 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
124 if (getOperand(i)->ContainsRelocations(Kind))
130 // Static constructor to create a '0' constant of arbitrary type...
131 static const uint64_t zero[2] = {0, 0};
132 Constant *Constant::getNullValue(const Type *Ty) {
133 switch (Ty->getTypeID()) {
134 case Type::IntegerTyID:
135 return ConstantInt::get(Ty, 0);
136 case Type::FloatTyID:
137 return ConstantFP::get(APFloat(APInt(32, 0)));
138 case Type::DoubleTyID:
139 return ConstantFP::get(APFloat(APInt(64, 0)));
140 case Type::X86_FP80TyID:
141 return ConstantFP::get(APFloat(APInt(80, 2, zero)));
142 case Type::FP128TyID:
143 return ConstantFP::get(APFloat(APInt(128, 2, zero), true));
144 case Type::PPC_FP128TyID:
145 return ConstantFP::get(APFloat(APInt(128, 2, zero)));
146 case Type::PointerTyID:
147 return ConstantPointerNull::get(cast<PointerType>(Ty));
148 case Type::StructTyID:
149 case Type::ArrayTyID:
150 case Type::VectorTyID:
151 return ConstantAggregateZero::get(Ty);
153 // Function, Label, or Opaque type?
154 assert(!"Cannot create a null constant of that type!");
159 Constant *Constant::getAllOnesValue(const Type *Ty) {
160 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
161 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
162 return ConstantVector::getAllOnesValue(cast<VectorType>(Ty));
165 // Static constructor to create an integral constant with all bits set
166 ConstantInt *ConstantInt::getAllOnesValue(const Type *Ty) {
167 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
168 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
172 /// @returns the value for a vector integer constant of the given type that
173 /// has all its bits set to true.
174 /// @brief Get the all ones value
175 ConstantVector *ConstantVector::getAllOnesValue(const VectorType *Ty) {
176 std::vector<Constant*> Elts;
177 Elts.resize(Ty->getNumElements(),
178 ConstantInt::getAllOnesValue(Ty->getElementType()));
179 assert(Elts[0] && "Not a vector integer type!");
180 return cast<ConstantVector>(ConstantVector::get(Elts));
184 /// getVectorElements - This method, which is only valid on constant of vector
185 /// type, returns the elements of the vector in the specified smallvector.
186 /// This handles breaking down a vector undef into undef elements, etc. For
187 /// constant exprs and other cases we can't handle, we return an empty vector.
188 void Constant::getVectorElements(SmallVectorImpl<Constant*> &Elts) const {
189 assert(isa<VectorType>(getType()) && "Not a vector constant!");
191 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
192 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
193 Elts.push_back(CV->getOperand(i));
197 const VectorType *VT = cast<VectorType>(getType());
198 if (isa<ConstantAggregateZero>(this)) {
199 Elts.assign(VT->getNumElements(),
200 Constant::getNullValue(VT->getElementType()));
204 if (isa<UndefValue>(this)) {
205 Elts.assign(VT->getNumElements(), UndefValue::get(VT->getElementType()));
209 // Unknown type, must be constant expr etc.
214 //===----------------------------------------------------------------------===//
216 //===----------------------------------------------------------------------===//
218 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
219 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
220 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
223 ConstantInt *ConstantInt::TheTrueVal = 0;
224 ConstantInt *ConstantInt::TheFalseVal = 0;
227 void CleanupTrueFalse(void *) {
228 ConstantInt::ResetTrueFalse();
232 static ManagedCleanup<llvm::CleanupTrueFalse> TrueFalseCleanup;
234 ConstantInt *ConstantInt::CreateTrueFalseVals(bool WhichOne) {
235 assert(TheTrueVal == 0 && TheFalseVal == 0);
236 TheTrueVal = get(Type::Int1Ty, 1);
237 TheFalseVal = get(Type::Int1Ty, 0);
239 // Ensure that llvm_shutdown nulls out TheTrueVal/TheFalseVal.
240 TrueFalseCleanup.Register();
242 return WhichOne ? TheTrueVal : TheFalseVal;
247 struct DenseMapAPIntKeyInfo {
251 KeyTy(const APInt& V, const Type* Ty) : val(V), type(Ty) {}
252 KeyTy(const KeyTy& that) : val(that.val), type(that.type) {}
253 bool operator==(const KeyTy& that) const {
254 return type == that.type && this->val == that.val;
256 bool operator!=(const KeyTy& that) const {
257 return !this->operator==(that);
260 static inline KeyTy getEmptyKey() { return KeyTy(APInt(1,0), 0); }
261 static inline KeyTy getTombstoneKey() { return KeyTy(APInt(1,1), 0); }
262 static unsigned getHashValue(const KeyTy &Key) {
263 return DenseMapInfo<void*>::getHashValue(Key.type) ^
264 Key.val.getHashValue();
266 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
269 static bool isPod() { return false; }
274 typedef DenseMap<DenseMapAPIntKeyInfo::KeyTy, ConstantInt*,
275 DenseMapAPIntKeyInfo> IntMapTy;
276 static ManagedStatic<IntMapTy> IntConstants;
278 ConstantInt *ConstantInt::get(const IntegerType *Ty,
279 uint64_t V, bool isSigned) {
280 return get(APInt(Ty->getBitWidth(), V, isSigned));
283 Constant *ConstantInt::get(const Type *Ty, uint64_t V, bool isSigned) {
284 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
286 // For vectors, broadcast the value.
287 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
289 ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
294 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
295 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
296 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
297 // compare APInt's of different widths, which would violate an APInt class
298 // invariant which generates an assertion.
299 ConstantInt *ConstantInt::get(const APInt& V) {
300 // Get the corresponding integer type for the bit width of the value.
301 const IntegerType *ITy = IntegerType::get(V.getBitWidth());
302 // get an existing value or the insertion position
303 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
305 ConstantsLock->reader_acquire();
306 ConstantInt *&Slot = (*IntConstants)[Key];
307 ConstantsLock->reader_release();
310 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
311 ConstantInt *&NewSlot = (*IntConstants)[Key];
313 NewSlot = new ConstantInt(ITy, V);
322 Constant *ConstantInt::get(const Type *Ty, const APInt &V) {
323 ConstantInt *C = ConstantInt::get(V);
324 assert(C->getType() == Ty->getScalarType() &&
325 "ConstantInt type doesn't match the type implied by its value!");
327 // For vectors, broadcast the value.
328 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
330 ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
335 //===----------------------------------------------------------------------===//
337 //===----------------------------------------------------------------------===//
339 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
340 if (Ty == Type::FloatTy)
341 return &APFloat::IEEEsingle;
342 if (Ty == Type::DoubleTy)
343 return &APFloat::IEEEdouble;
344 if (Ty == Type::X86_FP80Ty)
345 return &APFloat::x87DoubleExtended;
346 else if (Ty == Type::FP128Ty)
347 return &APFloat::IEEEquad;
349 assert(Ty == Type::PPC_FP128Ty && "Unknown FP format");
350 return &APFloat::PPCDoubleDouble;
353 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
354 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
355 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
359 bool ConstantFP::isNullValue() const {
360 return Val.isZero() && !Val.isNegative();
363 ConstantFP *ConstantFP::getNegativeZero(const Type *Ty) {
364 APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
366 return ConstantFP::get(apf);
369 bool ConstantFP::isExactlyValue(const APFloat& V) const {
370 return Val.bitwiseIsEqual(V);
374 struct DenseMapAPFloatKeyInfo {
377 KeyTy(const APFloat& V) : val(V){}
378 KeyTy(const KeyTy& that) : val(that.val) {}
379 bool operator==(const KeyTy& that) const {
380 return this->val.bitwiseIsEqual(that.val);
382 bool operator!=(const KeyTy& that) const {
383 return !this->operator==(that);
386 static inline KeyTy getEmptyKey() {
387 return KeyTy(APFloat(APFloat::Bogus,1));
389 static inline KeyTy getTombstoneKey() {
390 return KeyTy(APFloat(APFloat::Bogus,2));
392 static unsigned getHashValue(const KeyTy &Key) {
393 return Key.val.getHashValue();
395 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
398 static bool isPod() { return false; }
402 //---- ConstantFP::get() implementation...
404 typedef DenseMap<DenseMapAPFloatKeyInfo::KeyTy, ConstantFP*,
405 DenseMapAPFloatKeyInfo> FPMapTy;
407 static ManagedStatic<FPMapTy> FPConstants;
409 ConstantFP *ConstantFP::get(const APFloat &V) {
410 DenseMapAPFloatKeyInfo::KeyTy Key(V);
412 ConstantsLock->reader_acquire();
413 ConstantFP *&Slot = (*FPConstants)[Key];
414 ConstantsLock->reader_release();
417 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
418 ConstantFP *&NewSlot = (*FPConstants)[Key];
421 if (&V.getSemantics() == &APFloat::IEEEsingle)
423 else if (&V.getSemantics() == &APFloat::IEEEdouble)
425 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
426 Ty = Type::X86_FP80Ty;
427 else if (&V.getSemantics() == &APFloat::IEEEquad)
430 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
431 "Unknown FP format");
432 Ty = Type::PPC_FP128Ty;
434 NewSlot = new ConstantFP(Ty, V);
443 /// get() - This returns a constant fp for the specified value in the
444 /// specified type. This should only be used for simple constant values like
445 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
446 Constant *ConstantFP::get(const Type *Ty, double V) {
449 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
450 APFloat::rmNearestTiesToEven, &ignored);
451 Constant *C = get(FV);
453 // For vectors, broadcast the value.
454 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
456 ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
461 //===----------------------------------------------------------------------===//
462 // ConstantXXX Classes
463 //===----------------------------------------------------------------------===//
466 ConstantArray::ConstantArray(const ArrayType *T,
467 const std::vector<Constant*> &V)
468 : Constant(T, ConstantArrayVal,
469 OperandTraits<ConstantArray>::op_end(this) - V.size(),
471 assert(V.size() == T->getNumElements() &&
472 "Invalid initializer vector for constant array");
473 Use *OL = OperandList;
474 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
477 assert((C->getType() == T->getElementType() ||
479 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
480 "Initializer for array element doesn't match array element type!");
486 ConstantStruct::ConstantStruct(const StructType *T,
487 const std::vector<Constant*> &V)
488 : Constant(T, ConstantStructVal,
489 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
491 assert(V.size() == T->getNumElements() &&
492 "Invalid initializer vector for constant structure");
493 Use *OL = OperandList;
494 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
497 assert((C->getType() == T->getElementType(I-V.begin()) ||
498 ((T->getElementType(I-V.begin())->isAbstract() ||
499 C->getType()->isAbstract()) &&
500 T->getElementType(I-V.begin())->getTypeID() ==
501 C->getType()->getTypeID())) &&
502 "Initializer for struct element doesn't match struct element type!");
508 ConstantVector::ConstantVector(const VectorType *T,
509 const std::vector<Constant*> &V)
510 : Constant(T, ConstantVectorVal,
511 OperandTraits<ConstantVector>::op_end(this) - V.size(),
513 Use *OL = OperandList;
514 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
517 assert((C->getType() == T->getElementType() ||
519 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
520 "Initializer for vector element doesn't match vector element type!");
527 // We declare several classes private to this file, so use an anonymous
531 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
532 /// behind the scenes to implement unary constant exprs.
533 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
534 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
536 // allocate space for exactly one operand
537 void *operator new(size_t s) {
538 return User::operator new(s, 1);
540 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
541 : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
544 /// Transparently provide more efficient getOperand methods.
545 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
548 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
549 /// behind the scenes to implement binary constant exprs.
550 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
551 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
553 // allocate space for exactly two operands
554 void *operator new(size_t s) {
555 return User::operator new(s, 2);
557 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
558 : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
562 /// Transparently provide more efficient getOperand methods.
563 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
566 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
567 /// behind the scenes to implement select constant exprs.
568 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
569 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
571 // allocate space for exactly three operands
572 void *operator new(size_t s) {
573 return User::operator new(s, 3);
575 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
576 : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
581 /// Transparently provide more efficient getOperand methods.
582 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
585 /// ExtractElementConstantExpr - This class is private to
586 /// Constants.cpp, and is used behind the scenes to implement
587 /// extractelement constant exprs.
588 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
589 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
591 // allocate space for exactly two operands
592 void *operator new(size_t s) {
593 return User::operator new(s, 2);
595 ExtractElementConstantExpr(Constant *C1, Constant *C2)
596 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
597 Instruction::ExtractElement, &Op<0>(), 2) {
601 /// Transparently provide more efficient getOperand methods.
602 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
605 /// InsertElementConstantExpr - This class is private to
606 /// Constants.cpp, and is used behind the scenes to implement
607 /// insertelement constant exprs.
608 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
609 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
611 // allocate space for exactly three operands
612 void *operator new(size_t s) {
613 return User::operator new(s, 3);
615 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
616 : ConstantExpr(C1->getType(), Instruction::InsertElement,
622 /// Transparently provide more efficient getOperand methods.
623 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
626 /// ShuffleVectorConstantExpr - This class is private to
627 /// Constants.cpp, and is used behind the scenes to implement
628 /// shufflevector constant exprs.
629 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
630 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
632 // allocate space for exactly three operands
633 void *operator new(size_t s) {
634 return User::operator new(s, 3);
636 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
637 : ConstantExpr(VectorType::get(
638 cast<VectorType>(C1->getType())->getElementType(),
639 cast<VectorType>(C3->getType())->getNumElements()),
640 Instruction::ShuffleVector,
646 /// Transparently provide more efficient getOperand methods.
647 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
650 /// ExtractValueConstantExpr - This class is private to
651 /// Constants.cpp, and is used behind the scenes to implement
652 /// extractvalue constant exprs.
653 class VISIBILITY_HIDDEN ExtractValueConstantExpr : public ConstantExpr {
654 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
656 // allocate space for exactly one operand
657 void *operator new(size_t s) {
658 return User::operator new(s, 1);
660 ExtractValueConstantExpr(Constant *Agg,
661 const SmallVector<unsigned, 4> &IdxList,
663 : ConstantExpr(DestTy, Instruction::ExtractValue, &Op<0>(), 1),
668 /// Indices - These identify which value to extract.
669 const SmallVector<unsigned, 4> Indices;
671 /// Transparently provide more efficient getOperand methods.
672 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
675 /// InsertValueConstantExpr - This class is private to
676 /// Constants.cpp, and is used behind the scenes to implement
677 /// insertvalue constant exprs.
678 class VISIBILITY_HIDDEN InsertValueConstantExpr : public ConstantExpr {
679 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
681 // allocate space for exactly one operand
682 void *operator new(size_t s) {
683 return User::operator new(s, 2);
685 InsertValueConstantExpr(Constant *Agg, Constant *Val,
686 const SmallVector<unsigned, 4> &IdxList,
688 : ConstantExpr(DestTy, Instruction::InsertValue, &Op<0>(), 2),
694 /// Indices - These identify the position for the insertion.
695 const SmallVector<unsigned, 4> Indices;
697 /// Transparently provide more efficient getOperand methods.
698 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
702 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
703 /// used behind the scenes to implement getelementpr constant exprs.
704 class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
705 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
708 static GetElementPtrConstantExpr *Create(Constant *C,
709 const std::vector<Constant*>&IdxList,
710 const Type *DestTy) {
711 return new(IdxList.size() + 1)
712 GetElementPtrConstantExpr(C, IdxList, DestTy);
714 /// Transparently provide more efficient getOperand methods.
715 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
718 // CompareConstantExpr - This class is private to Constants.cpp, and is used
719 // behind the scenes to implement ICmp and FCmp constant expressions. This is
720 // needed in order to store the predicate value for these instructions.
721 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
722 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
723 // allocate space for exactly two operands
724 void *operator new(size_t s) {
725 return User::operator new(s, 2);
727 unsigned short predicate;
728 CompareConstantExpr(const Type *ty, Instruction::OtherOps opc,
729 unsigned short pred, Constant* LHS, Constant* RHS)
730 : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
734 /// Transparently provide more efficient getOperand methods.
735 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
738 } // end anonymous namespace
741 struct OperandTraits<UnaryConstantExpr> : FixedNumOperandTraits<1> {
743 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
746 struct OperandTraits<BinaryConstantExpr> : FixedNumOperandTraits<2> {
748 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
751 struct OperandTraits<SelectConstantExpr> : FixedNumOperandTraits<3> {
753 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
756 struct OperandTraits<ExtractElementConstantExpr> : FixedNumOperandTraits<2> {
758 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
761 struct OperandTraits<InsertElementConstantExpr> : FixedNumOperandTraits<3> {
763 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
766 struct OperandTraits<ShuffleVectorConstantExpr> : FixedNumOperandTraits<3> {
768 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
771 struct OperandTraits<ExtractValueConstantExpr> : FixedNumOperandTraits<1> {
773 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractValueConstantExpr, Value)
776 struct OperandTraits<InsertValueConstantExpr> : FixedNumOperandTraits<2> {
778 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueConstantExpr, Value)
781 struct OperandTraits<GetElementPtrConstantExpr> : VariadicOperandTraits<1> {
784 GetElementPtrConstantExpr::GetElementPtrConstantExpr
786 const std::vector<Constant*> &IdxList,
788 : ConstantExpr(DestTy, Instruction::GetElementPtr,
789 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
790 - (IdxList.size()+1),
793 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
794 OperandList[i+1] = IdxList[i];
797 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
801 struct OperandTraits<CompareConstantExpr> : FixedNumOperandTraits<2> {
803 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
806 } // End llvm namespace
809 // Utility function for determining if a ConstantExpr is a CastOp or not. This
810 // can't be inline because we don't want to #include Instruction.h into
812 bool ConstantExpr::isCast() const {
813 return Instruction::isCast(getOpcode());
816 bool ConstantExpr::isCompare() const {
817 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
820 bool ConstantExpr::hasIndices() const {
821 return getOpcode() == Instruction::ExtractValue ||
822 getOpcode() == Instruction::InsertValue;
825 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
826 if (const ExtractValueConstantExpr *EVCE =
827 dyn_cast<ExtractValueConstantExpr>(this))
828 return EVCE->Indices;
830 return cast<InsertValueConstantExpr>(this)->Indices;
833 /// ConstantExpr::get* - Return some common constants without having to
834 /// specify the full Instruction::OPCODE identifier.
836 Constant *ConstantExpr::getNeg(Constant *C) {
837 // API compatibility: Adjust integer opcodes to floating-point opcodes.
838 if (C->getType()->isFPOrFPVector())
840 assert(C->getType()->isIntOrIntVector() &&
841 "Cannot NEG a nonintegral value!");
842 return get(Instruction::Sub,
843 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
846 Constant *ConstantExpr::getFNeg(Constant *C) {
847 assert(C->getType()->isFPOrFPVector() &&
848 "Cannot FNEG a non-floating-point value!");
849 return get(Instruction::FSub,
850 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
853 Constant *ConstantExpr::getNot(Constant *C) {
854 assert(C->getType()->isIntOrIntVector() &&
855 "Cannot NOT a nonintegral value!");
856 return get(Instruction::Xor, C,
857 Constant::getAllOnesValue(C->getType()));
859 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
860 return get(Instruction::Add, C1, C2);
862 Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
863 return get(Instruction::FAdd, C1, C2);
865 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
866 return get(Instruction::Sub, C1, C2);
868 Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
869 return get(Instruction::FSub, C1, C2);
871 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
872 return get(Instruction::Mul, C1, C2);
874 Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
875 return get(Instruction::FMul, C1, C2);
877 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
878 return get(Instruction::UDiv, C1, C2);
880 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
881 return get(Instruction::SDiv, C1, C2);
883 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
884 return get(Instruction::FDiv, C1, C2);
886 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
887 return get(Instruction::URem, C1, C2);
889 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
890 return get(Instruction::SRem, C1, C2);
892 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
893 return get(Instruction::FRem, C1, C2);
895 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
896 return get(Instruction::And, C1, C2);
898 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
899 return get(Instruction::Or, C1, C2);
901 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
902 return get(Instruction::Xor, C1, C2);
904 unsigned ConstantExpr::getPredicate() const {
905 assert(getOpcode() == Instruction::FCmp ||
906 getOpcode() == Instruction::ICmp);
907 return ((const CompareConstantExpr*)this)->predicate;
909 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
910 return get(Instruction::Shl, C1, C2);
912 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
913 return get(Instruction::LShr, C1, C2);
915 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
916 return get(Instruction::AShr, C1, C2);
919 /// getWithOperandReplaced - Return a constant expression identical to this
920 /// one, but with the specified operand set to the specified value.
922 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
923 assert(OpNo < getNumOperands() && "Operand num is out of range!");
924 assert(Op->getType() == getOperand(OpNo)->getType() &&
925 "Replacing operand with value of different type!");
926 if (getOperand(OpNo) == Op)
927 return const_cast<ConstantExpr*>(this);
929 Constant *Op0, *Op1, *Op2;
930 switch (getOpcode()) {
931 case Instruction::Trunc:
932 case Instruction::ZExt:
933 case Instruction::SExt:
934 case Instruction::FPTrunc:
935 case Instruction::FPExt:
936 case Instruction::UIToFP:
937 case Instruction::SIToFP:
938 case Instruction::FPToUI:
939 case Instruction::FPToSI:
940 case Instruction::PtrToInt:
941 case Instruction::IntToPtr:
942 case Instruction::BitCast:
943 return ConstantExpr::getCast(getOpcode(), Op, getType());
944 case Instruction::Select:
945 Op0 = (OpNo == 0) ? Op : getOperand(0);
946 Op1 = (OpNo == 1) ? Op : getOperand(1);
947 Op2 = (OpNo == 2) ? Op : getOperand(2);
948 return ConstantExpr::getSelect(Op0, Op1, Op2);
949 case Instruction::InsertElement:
950 Op0 = (OpNo == 0) ? Op : getOperand(0);
951 Op1 = (OpNo == 1) ? Op : getOperand(1);
952 Op2 = (OpNo == 2) ? Op : getOperand(2);
953 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
954 case Instruction::ExtractElement:
955 Op0 = (OpNo == 0) ? Op : getOperand(0);
956 Op1 = (OpNo == 1) ? Op : getOperand(1);
957 return ConstantExpr::getExtractElement(Op0, Op1);
958 case Instruction::ShuffleVector:
959 Op0 = (OpNo == 0) ? Op : getOperand(0);
960 Op1 = (OpNo == 1) ? Op : getOperand(1);
961 Op2 = (OpNo == 2) ? Op : getOperand(2);
962 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
963 case Instruction::GetElementPtr: {
964 SmallVector<Constant*, 8> Ops;
965 Ops.resize(getNumOperands()-1);
966 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
967 Ops[i-1] = getOperand(i);
969 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
971 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
974 assert(getNumOperands() == 2 && "Must be binary operator?");
975 Op0 = (OpNo == 0) ? Op : getOperand(0);
976 Op1 = (OpNo == 1) ? Op : getOperand(1);
977 return ConstantExpr::get(getOpcode(), Op0, Op1);
981 /// getWithOperands - This returns the current constant expression with the
982 /// operands replaced with the specified values. The specified operands must
983 /// match count and type with the existing ones.
984 Constant *ConstantExpr::
985 getWithOperands(Constant* const *Ops, unsigned NumOps) const {
986 assert(NumOps == getNumOperands() && "Operand count mismatch!");
987 bool AnyChange = false;
988 for (unsigned i = 0; i != NumOps; ++i) {
989 assert(Ops[i]->getType() == getOperand(i)->getType() &&
990 "Operand type mismatch!");
991 AnyChange |= Ops[i] != getOperand(i);
993 if (!AnyChange) // No operands changed, return self.
994 return const_cast<ConstantExpr*>(this);
996 switch (getOpcode()) {
997 case Instruction::Trunc:
998 case Instruction::ZExt:
999 case Instruction::SExt:
1000 case Instruction::FPTrunc:
1001 case Instruction::FPExt:
1002 case Instruction::UIToFP:
1003 case Instruction::SIToFP:
1004 case Instruction::FPToUI:
1005 case Instruction::FPToSI:
1006 case Instruction::PtrToInt:
1007 case Instruction::IntToPtr:
1008 case Instruction::BitCast:
1009 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
1010 case Instruction::Select:
1011 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
1012 case Instruction::InsertElement:
1013 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
1014 case Instruction::ExtractElement:
1015 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
1016 case Instruction::ShuffleVector:
1017 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
1018 case Instruction::GetElementPtr:
1019 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
1020 case Instruction::ICmp:
1021 case Instruction::FCmp:
1022 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
1024 assert(getNumOperands() == 2 && "Must be binary operator?");
1025 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
1030 //===----------------------------------------------------------------------===//
1031 // isValueValidForType implementations
1033 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
1034 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
1035 if (Ty == Type::Int1Ty)
1036 return Val == 0 || Val == 1;
1038 return true; // always true, has to fit in largest type
1039 uint64_t Max = (1ll << NumBits) - 1;
1043 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
1044 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
1045 if (Ty == Type::Int1Ty)
1046 return Val == 0 || Val == 1 || Val == -1;
1048 return true; // always true, has to fit in largest type
1049 int64_t Min = -(1ll << (NumBits-1));
1050 int64_t Max = (1ll << (NumBits-1)) - 1;
1051 return (Val >= Min && Val <= Max);
1054 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
1055 // convert modifies in place, so make a copy.
1056 APFloat Val2 = APFloat(Val);
1058 switch (Ty->getTypeID()) {
1060 return false; // These can't be represented as floating point!
1062 // FIXME rounding mode needs to be more flexible
1063 case Type::FloatTyID: {
1064 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
1066 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
1069 case Type::DoubleTyID: {
1070 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
1071 &Val2.getSemantics() == &APFloat::IEEEdouble)
1073 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
1076 case Type::X86_FP80TyID:
1077 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1078 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1079 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
1080 case Type::FP128TyID:
1081 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1082 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1083 &Val2.getSemantics() == &APFloat::IEEEquad;
1084 case Type::PPC_FP128TyID:
1085 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1086 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1087 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
1091 //===----------------------------------------------------------------------===//
1092 // Factory Function Implementation
1095 // The number of operands for each ConstantCreator::create method is
1096 // determined by the ConstantTraits template.
1097 // ConstantCreator - A class that is used to create constants by
1098 // ValueMap*. This class should be partially specialized if there is
1099 // something strange that needs to be done to interface to the ctor for the
1103 template<class ValType>
1104 struct ConstantTraits;
1106 template<typename T, typename Alloc>
1107 struct VISIBILITY_HIDDEN ConstantTraits< std::vector<T, Alloc> > {
1108 static unsigned uses(const std::vector<T, Alloc>& v) {
1113 template<class ConstantClass, class TypeClass, class ValType>
1114 struct VISIBILITY_HIDDEN ConstantCreator {
1115 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
1116 return new(ConstantTraits<ValType>::uses(V)) ConstantClass(Ty, V);
1120 template<class ConstantClass, class TypeClass>
1121 struct VISIBILITY_HIDDEN ConvertConstantType {
1122 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
1123 assert(0 && "This type cannot be converted!\n");
1128 template<class ValType, class TypeClass, class ConstantClass,
1129 bool HasLargeKey = false /*true for arrays and structs*/ >
1130 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
1132 typedef std::pair<const Type*, ValType> MapKey;
1133 typedef std::map<MapKey, Constant *> MapTy;
1134 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
1135 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
1137 /// Map - This is the main map from the element descriptor to the Constants.
1138 /// This is the primary way we avoid creating two of the same shape
1142 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
1143 /// from the constants to their element in Map. This is important for
1144 /// removal of constants from the array, which would otherwise have to scan
1145 /// through the map with very large keys.
1146 InverseMapTy InverseMap;
1148 /// AbstractTypeMap - Map for abstract type constants.
1150 AbstractTypeMapTy AbstractTypeMap;
1152 /// ValueMapLock - Mutex for this map.
1153 sys::SmartMutex<true> ValueMapLock;
1156 // NOTE: This function is not locked. It is the caller's responsibility
1157 // to enforce proper synchronization.
1158 typename MapTy::iterator map_end() { return Map.end(); }
1160 /// InsertOrGetItem - Return an iterator for the specified element.
1161 /// If the element exists in the map, the returned iterator points to the
1162 /// entry and Exists=true. If not, the iterator points to the newly
1163 /// inserted entry and returns Exists=false. Newly inserted entries have
1164 /// I->second == 0, and should be filled in.
1165 /// NOTE: This function is not locked. It is the caller's responsibility
1166 // to enforce proper synchronization.
1167 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
1170 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
1171 Exists = !IP.second;
1176 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
1178 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
1179 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
1180 IMI->second->second == CP &&
1181 "InverseMap corrupt!");
1185 typename MapTy::iterator I =
1186 Map.find(MapKey(static_cast<const TypeClass*>(CP->getRawType()),
1188 if (I == Map.end() || I->second != CP) {
1189 // FIXME: This should not use a linear scan. If this gets to be a
1190 // performance problem, someone should look at this.
1191 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
1197 ConstantClass* Create(const TypeClass *Ty, const ValType &V,
1198 typename MapTy::iterator I) {
1199 ConstantClass* Result =
1200 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
1202 assert(Result->getType() == Ty && "Type specified is not correct!");
1203 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
1205 if (HasLargeKey) // Remember the reverse mapping if needed.
1206 InverseMap.insert(std::make_pair(Result, I));
1208 // If the type of the constant is abstract, make sure that an entry
1209 // exists for it in the AbstractTypeMap.
1210 if (Ty->isAbstract()) {
1211 typename AbstractTypeMapTy::iterator TI =
1212 AbstractTypeMap.find(Ty);
1214 if (TI == AbstractTypeMap.end()) {
1215 // Add ourselves to the ATU list of the type.
1216 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
1218 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
1226 /// getOrCreate - Return the specified constant from the map, creating it if
1228 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
1229 sys::SmartScopedLock<true> Lock(ValueMapLock);
1230 MapKey Lookup(Ty, V);
1231 ConstantClass* Result = 0;
1233 typename MapTy::iterator I = Map.find(Lookup);
1234 // Is it in the map?
1236 Result = static_cast<ConstantClass *>(I->second);
1239 // If no preexisting value, create one now...
1240 Result = Create(Ty, V, I);
1246 void remove(ConstantClass *CP) {
1247 sys::SmartScopedLock<true> Lock(ValueMapLock);
1248 typename MapTy::iterator I = FindExistingElement(CP);
1249 assert(I != Map.end() && "Constant not found in constant table!");
1250 assert(I->second == CP && "Didn't find correct element?");
1252 if (HasLargeKey) // Remember the reverse mapping if needed.
1253 InverseMap.erase(CP);
1255 // Now that we found the entry, make sure this isn't the entry that
1256 // the AbstractTypeMap points to.
1257 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
1258 if (Ty->isAbstract()) {
1259 assert(AbstractTypeMap.count(Ty) &&
1260 "Abstract type not in AbstractTypeMap?");
1261 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
1262 if (ATMEntryIt == I) {
1263 // Yes, we are removing the representative entry for this type.
1264 // See if there are any other entries of the same type.
1265 typename MapTy::iterator TmpIt = ATMEntryIt;
1267 // First check the entry before this one...
1268 if (TmpIt != Map.begin()) {
1270 if (TmpIt->first.first != Ty) // Not the same type, move back...
1274 // If we didn't find the same type, try to move forward...
1275 if (TmpIt == ATMEntryIt) {
1277 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
1278 --TmpIt; // No entry afterwards with the same type
1281 // If there is another entry in the map of the same abstract type,
1282 // update the AbstractTypeMap entry now.
1283 if (TmpIt != ATMEntryIt) {
1286 // Otherwise, we are removing the last instance of this type
1287 // from the table. Remove from the ATM, and from user list.
1288 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
1289 AbstractTypeMap.erase(Ty);
1298 /// MoveConstantToNewSlot - If we are about to change C to be the element
1299 /// specified by I, update our internal data structures to reflect this
1301 /// NOTE: This function is not locked. It is the responsibility of the
1302 /// caller to enforce proper synchronization if using this method.
1303 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
1304 // First, remove the old location of the specified constant in the map.
1305 typename MapTy::iterator OldI = FindExistingElement(C);
1306 assert(OldI != Map.end() && "Constant not found in constant table!");
1307 assert(OldI->second == C && "Didn't find correct element?");
1309 // If this constant is the representative element for its abstract type,
1310 // update the AbstractTypeMap so that the representative element is I.
1311 if (C->getType()->isAbstract()) {
1312 typename AbstractTypeMapTy::iterator ATI =
1313 AbstractTypeMap.find(C->getType());
1314 assert(ATI != AbstractTypeMap.end() &&
1315 "Abstract type not in AbstractTypeMap?");
1316 if (ATI->second == OldI)
1320 // Remove the old entry from the map.
1323 // Update the inverse map so that we know that this constant is now
1324 // located at descriptor I.
1326 assert(I->second == C && "Bad inversemap entry!");
1331 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
1332 sys::SmartScopedLock<true> Lock(ValueMapLock);
1333 typename AbstractTypeMapTy::iterator I =
1334 AbstractTypeMap.find(cast<Type>(OldTy));
1336 assert(I != AbstractTypeMap.end() &&
1337 "Abstract type not in AbstractTypeMap?");
1339 // Convert a constant at a time until the last one is gone. The last one
1340 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
1341 // eliminated eventually.
1343 ConvertConstantType<ConstantClass,
1344 TypeClass>::convert(
1345 static_cast<ConstantClass *>(I->second->second),
1346 cast<TypeClass>(NewTy));
1348 I = AbstractTypeMap.find(cast<Type>(OldTy));
1349 } while (I != AbstractTypeMap.end());
1352 // If the type became concrete without being refined to any other existing
1353 // type, we just remove ourselves from the ATU list.
1354 void typeBecameConcrete(const DerivedType *AbsTy) {
1355 AbsTy->removeAbstractTypeUser(this);
1359 DOUT << "Constant.cpp: ValueMap\n";
1366 //---- ConstantAggregateZero::get() implementation...
1369 // ConstantAggregateZero does not take extra "value" argument...
1370 template<class ValType>
1371 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
1372 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
1373 return new ConstantAggregateZero(Ty);
1378 struct ConvertConstantType<ConstantAggregateZero, Type> {
1379 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1380 // Make everyone now use a constant of the new type...
1381 Constant *New = ConstantAggregateZero::get(NewTy);
1382 assert(New != OldC && "Didn't replace constant??");
1383 OldC->uncheckedReplaceAllUsesWith(New);
1384 OldC->destroyConstant(); // This constant is now dead, destroy it.
1389 static ManagedStatic<ValueMap<char, Type,
1390 ConstantAggregateZero> > AggZeroConstants;
1392 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1394 ConstantAggregateZero *ConstantAggregateZero::get(const Type *Ty) {
1395 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
1396 "Cannot create an aggregate zero of non-aggregate type!");
1398 // Implicitly locked.
1399 return AggZeroConstants->getOrCreate(Ty, 0);
1402 /// destroyConstant - Remove the constant from the constant table...
1404 void ConstantAggregateZero::destroyConstant() {
1405 // Implicitly locked.
1406 AggZeroConstants->remove(this);
1407 destroyConstantImpl();
1410 //---- ConstantArray::get() implementation...
1414 struct ConvertConstantType<ConstantArray, ArrayType> {
1415 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1416 // Make everyone now use a constant of the new type...
1417 std::vector<Constant*> C;
1418 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1419 C.push_back(cast<Constant>(OldC->getOperand(i)));
1420 Constant *New = ConstantArray::get(NewTy, C);
1421 assert(New != OldC && "Didn't replace constant??");
1422 OldC->uncheckedReplaceAllUsesWith(New);
1423 OldC->destroyConstant(); // This constant is now dead, destroy it.
1428 static std::vector<Constant*> getValType(ConstantArray *CA) {
1429 std::vector<Constant*> Elements;
1430 Elements.reserve(CA->getNumOperands());
1431 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1432 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1436 typedef ValueMap<std::vector<Constant*>, ArrayType,
1437 ConstantArray, true /*largekey*/> ArrayConstantsTy;
1438 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
1440 Constant *ConstantArray::get(const ArrayType *Ty,
1441 const std::vector<Constant*> &V) {
1442 // If this is an all-zero array, return a ConstantAggregateZero object
1445 if (!C->isNullValue()) {
1446 // Implicitly locked.
1447 return ArrayConstants->getOrCreate(Ty, V);
1449 for (unsigned i = 1, e = V.size(); i != e; ++i)
1451 // Implicitly locked.
1452 return ArrayConstants->getOrCreate(Ty, V);
1456 return ConstantAggregateZero::get(Ty);
1459 /// destroyConstant - Remove the constant from the constant table...
1461 void ConstantArray::destroyConstant() {
1462 // Implicitly locked.
1463 ArrayConstants->remove(this);
1464 destroyConstantImpl();
1467 /// ConstantArray::get(const string&) - Return an array that is initialized to
1468 /// contain the specified string. If length is zero then a null terminator is
1469 /// added to the specified string so that it may be used in a natural way.
1470 /// Otherwise, the length parameter specifies how much of the string to use
1471 /// and it won't be null terminated.
1473 Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
1474 std::vector<Constant*> ElementVals;
1475 for (unsigned i = 0; i < Str.length(); ++i)
1476 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
1478 // Add a null terminator to the string...
1480 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
1483 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
1484 return ConstantArray::get(ATy, ElementVals);
1487 /// isString - This method returns true if the array is an array of i8, and
1488 /// if the elements of the array are all ConstantInt's.
1489 bool ConstantArray::isString() const {
1490 // Check the element type for i8...
1491 if (getType()->getElementType() != Type::Int8Ty)
1493 // Check the elements to make sure they are all integers, not constant
1495 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1496 if (!isa<ConstantInt>(getOperand(i)))
1501 /// isCString - This method returns true if the array is a string (see
1502 /// isString) and it ends in a null byte \\0 and does not contains any other
1503 /// null bytes except its terminator.
1504 bool ConstantArray::isCString() const {
1505 // Check the element type for i8...
1506 if (getType()->getElementType() != Type::Int8Ty)
1508 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1509 // Last element must be a null.
1510 if (getOperand(getNumOperands()-1) != Zero)
1512 // Other elements must be non-null integers.
1513 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1514 if (!isa<ConstantInt>(getOperand(i)))
1516 if (getOperand(i) == Zero)
1523 /// getAsString - If the sub-element type of this array is i8
1524 /// then this method converts the array to an std::string and returns it.
1525 /// Otherwise, it asserts out.
1527 std::string ConstantArray::getAsString() const {
1528 assert(isString() && "Not a string!");
1530 Result.reserve(getNumOperands());
1531 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1532 Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
1537 //---- ConstantStruct::get() implementation...
1542 struct ConvertConstantType<ConstantStruct, StructType> {
1543 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1544 // Make everyone now use a constant of the new type...
1545 std::vector<Constant*> C;
1546 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1547 C.push_back(cast<Constant>(OldC->getOperand(i)));
1548 Constant *New = ConstantStruct::get(NewTy, C);
1549 assert(New != OldC && "Didn't replace constant??");
1551 OldC->uncheckedReplaceAllUsesWith(New);
1552 OldC->destroyConstant(); // This constant is now dead, destroy it.
1557 typedef ValueMap<std::vector<Constant*>, StructType,
1558 ConstantStruct, true /*largekey*/> StructConstantsTy;
1559 static ManagedStatic<StructConstantsTy> StructConstants;
1561 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1562 std::vector<Constant*> Elements;
1563 Elements.reserve(CS->getNumOperands());
1564 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1565 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1569 Constant *ConstantStruct::get(const StructType *Ty,
1570 const std::vector<Constant*> &V) {
1571 // Create a ConstantAggregateZero value if all elements are zeros...
1572 for (unsigned i = 0, e = V.size(); i != e; ++i)
1573 if (!V[i]->isNullValue())
1574 // Implicitly locked.
1575 return StructConstants->getOrCreate(Ty, V);
1577 return ConstantAggregateZero::get(Ty);
1580 Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
1581 std::vector<const Type*> StructEls;
1582 StructEls.reserve(V.size());
1583 for (unsigned i = 0, e = V.size(); i != e; ++i)
1584 StructEls.push_back(V[i]->getType());
1585 return get(StructType::get(StructEls, packed), V);
1588 // destroyConstant - Remove the constant from the constant table...
1590 void ConstantStruct::destroyConstant() {
1591 // Implicitly locked.
1592 StructConstants->remove(this);
1593 destroyConstantImpl();
1596 //---- ConstantVector::get() implementation...
1600 struct ConvertConstantType<ConstantVector, VectorType> {
1601 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
1602 // Make everyone now use a constant of the new type...
1603 std::vector<Constant*> C;
1604 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1605 C.push_back(cast<Constant>(OldC->getOperand(i)));
1606 Constant *New = ConstantVector::get(NewTy, C);
1607 assert(New != OldC && "Didn't replace constant??");
1608 OldC->uncheckedReplaceAllUsesWith(New);
1609 OldC->destroyConstant(); // This constant is now dead, destroy it.
1614 static std::vector<Constant*> getValType(ConstantVector *CP) {
1615 std::vector<Constant*> Elements;
1616 Elements.reserve(CP->getNumOperands());
1617 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1618 Elements.push_back(CP->getOperand(i));
1622 static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
1623 ConstantVector> > VectorConstants;
1625 Constant *ConstantVector::get(const VectorType *Ty,
1626 const std::vector<Constant*> &V) {
1627 assert(!V.empty() && "Vectors can't be empty");
1628 // If this is an all-undef or alll-zero vector, return a
1629 // ConstantAggregateZero or UndefValue.
1631 bool isZero = C->isNullValue();
1632 bool isUndef = isa<UndefValue>(C);
1634 if (isZero || isUndef) {
1635 for (unsigned i = 1, e = V.size(); i != e; ++i)
1637 isZero = isUndef = false;
1643 return ConstantAggregateZero::get(Ty);
1645 return UndefValue::get(Ty);
1647 // Implicitly locked.
1648 return VectorConstants->getOrCreate(Ty, V);
1651 Constant *ConstantVector::get(const std::vector<Constant*> &V) {
1652 assert(!V.empty() && "Cannot infer type if V is empty");
1653 return get(VectorType::get(V.front()->getType(),V.size()), V);
1656 // destroyConstant - Remove the constant from the constant table...
1658 void ConstantVector::destroyConstant() {
1659 // Implicitly locked.
1660 VectorConstants->remove(this);
1661 destroyConstantImpl();
1664 /// This function will return true iff every element in this vector constant
1665 /// is set to all ones.
1666 /// @returns true iff this constant's emements are all set to all ones.
1667 /// @brief Determine if the value is all ones.
1668 bool ConstantVector::isAllOnesValue() const {
1669 // Check out first element.
1670 const Constant *Elt = getOperand(0);
1671 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1672 if (!CI || !CI->isAllOnesValue()) return false;
1673 // Then make sure all remaining elements point to the same value.
1674 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1675 if (getOperand(I) != Elt) return false;
1680 /// getSplatValue - If this is a splat constant, where all of the
1681 /// elements have the same value, return that value. Otherwise return null.
1682 Constant *ConstantVector::getSplatValue() {
1683 // Check out first element.
1684 Constant *Elt = getOperand(0);
1685 // Then make sure all remaining elements point to the same value.
1686 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1687 if (getOperand(I) != Elt) return 0;
1691 //---- ConstantPointerNull::get() implementation...
1695 // ConstantPointerNull does not take extra "value" argument...
1696 template<class ValType>
1697 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1698 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1699 return new ConstantPointerNull(Ty);
1704 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1705 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1706 // Make everyone now use a constant of the new type...
1707 Constant *New = ConstantPointerNull::get(NewTy);
1708 assert(New != OldC && "Didn't replace constant??");
1709 OldC->uncheckedReplaceAllUsesWith(New);
1710 OldC->destroyConstant(); // This constant is now dead, destroy it.
1715 static ManagedStatic<ValueMap<char, PointerType,
1716 ConstantPointerNull> > NullPtrConstants;
1718 static char getValType(ConstantPointerNull *) {
1723 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1724 // Implicitly locked.
1725 return NullPtrConstants->getOrCreate(Ty, 0);
1728 // destroyConstant - Remove the constant from the constant table...
1730 void ConstantPointerNull::destroyConstant() {
1731 // Implicitly locked.
1732 NullPtrConstants->remove(this);
1733 destroyConstantImpl();
1737 //---- UndefValue::get() implementation...
1741 // UndefValue does not take extra "value" argument...
1742 template<class ValType>
1743 struct ConstantCreator<UndefValue, Type, ValType> {
1744 static UndefValue *create(const Type *Ty, const ValType &V) {
1745 return new UndefValue(Ty);
1750 struct ConvertConstantType<UndefValue, Type> {
1751 static void convert(UndefValue *OldC, const Type *NewTy) {
1752 // Make everyone now use a constant of the new type.
1753 Constant *New = UndefValue::get(NewTy);
1754 assert(New != OldC && "Didn't replace constant??");
1755 OldC->uncheckedReplaceAllUsesWith(New);
1756 OldC->destroyConstant(); // This constant is now dead, destroy it.
1761 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1763 static char getValType(UndefValue *) {
1768 UndefValue *UndefValue::get(const Type *Ty) {
1769 // Implicitly locked.
1770 return UndefValueConstants->getOrCreate(Ty, 0);
1773 // destroyConstant - Remove the constant from the constant table.
1775 void UndefValue::destroyConstant() {
1776 // Implicitly locked.
1777 UndefValueConstants->remove(this);
1778 destroyConstantImpl();
1781 //---- MDString::get() implementation
1784 MDString::MDString(const char *begin, const char *end)
1785 : Constant(Type::MetadataTy, MDStringVal, 0, 0),
1786 StrBegin(begin), StrEnd(end) {}
1788 static ManagedStatic<StringMap<MDString*> > MDStringCache;
1790 MDString *MDString::get(const char *StrBegin, const char *StrEnd) {
1791 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
1792 StringMapEntry<MDString *> &Entry = MDStringCache->GetOrCreateValue(
1794 MDString *&S = Entry.getValue();
1795 if (!S) S = new MDString(Entry.getKeyData(),
1796 Entry.getKeyData() + Entry.getKeyLength());
1801 MDString *MDString::get(const std::string &Str) {
1802 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
1803 StringMapEntry<MDString *> &Entry = MDStringCache->GetOrCreateValue(
1804 Str.data(), Str.data() + Str.size());
1805 MDString *&S = Entry.getValue();
1806 if (!S) S = new MDString(Entry.getKeyData(),
1807 Entry.getKeyData() + Entry.getKeyLength());
1812 void MDString::destroyConstant() {
1813 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
1814 MDStringCache->erase(MDStringCache->find(StrBegin, StrEnd));
1815 destroyConstantImpl();
1818 //---- MDNode::get() implementation
1821 static ManagedStatic<FoldingSet<MDNode> > MDNodeSet;
1823 MDNode::MDNode(Value*const* Vals, unsigned NumVals)
1824 : Constant(Type::MetadataTy, MDNodeVal, 0, 0) {
1825 for (unsigned i = 0; i != NumVals; ++i)
1826 Node.push_back(ElementVH(Vals[i], this));
1829 void MDNode::Profile(FoldingSetNodeID &ID) const {
1830 for (const_elem_iterator I = elem_begin(), E = elem_end(); I != E; ++I)
1834 MDNode *MDNode::get(Value*const* Vals, unsigned NumVals) {
1835 FoldingSetNodeID ID;
1836 for (unsigned i = 0; i != NumVals; ++i)
1837 ID.AddPointer(Vals[i]);
1839 ConstantsLock->reader_acquire();
1841 MDNode *N = MDNodeSet->FindNodeOrInsertPos(ID, InsertPoint);
1842 ConstantsLock->reader_release();
1845 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
1846 N = MDNodeSet->FindNodeOrInsertPos(ID, InsertPoint);
1848 // InsertPoint will have been set by the FindNodeOrInsertPos call.
1849 N = new(0) MDNode(Vals, NumVals);
1850 MDNodeSet->InsertNode(N, InsertPoint);
1856 void MDNode::destroyConstant() {
1857 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
1858 MDNodeSet->RemoveNode(this);
1860 destroyConstantImpl();
1863 //---- ConstantExpr::get() implementations...
1868 struct ExprMapKeyType {
1869 typedef SmallVector<unsigned, 4> IndexList;
1871 ExprMapKeyType(unsigned opc,
1872 const std::vector<Constant*> &ops,
1873 unsigned short pred = 0,
1874 const IndexList &inds = IndexList())
1875 : opcode(opc), predicate(pred), operands(ops), indices(inds) {}
1878 std::vector<Constant*> operands;
1880 bool operator==(const ExprMapKeyType& that) const {
1881 return this->opcode == that.opcode &&
1882 this->predicate == that.predicate &&
1883 this->operands == that.operands &&
1884 this->indices == that.indices;
1886 bool operator<(const ExprMapKeyType & that) const {
1887 return this->opcode < that.opcode ||
1888 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1889 (this->opcode == that.opcode && this->predicate == that.predicate &&
1890 this->operands < that.operands) ||
1891 (this->opcode == that.opcode && this->predicate == that.predicate &&
1892 this->operands == that.operands && this->indices < that.indices);
1895 bool operator!=(const ExprMapKeyType& that) const {
1896 return !(*this == that);
1904 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1905 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1906 unsigned short pred = 0) {
1907 if (Instruction::isCast(V.opcode))
1908 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1909 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1910 V.opcode < Instruction::BinaryOpsEnd))
1911 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1912 if (V.opcode == Instruction::Select)
1913 return new SelectConstantExpr(V.operands[0], V.operands[1],
1915 if (V.opcode == Instruction::ExtractElement)
1916 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1917 if (V.opcode == Instruction::InsertElement)
1918 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1920 if (V.opcode == Instruction::ShuffleVector)
1921 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1923 if (V.opcode == Instruction::InsertValue)
1924 return new InsertValueConstantExpr(V.operands[0], V.operands[1],
1926 if (V.opcode == Instruction::ExtractValue)
1927 return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
1928 if (V.opcode == Instruction::GetElementPtr) {
1929 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1930 return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
1933 // The compare instructions are weird. We have to encode the predicate
1934 // value and it is combined with the instruction opcode by multiplying
1935 // the opcode by one hundred. We must decode this to get the predicate.
1936 if (V.opcode == Instruction::ICmp)
1937 return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate,
1938 V.operands[0], V.operands[1]);
1939 if (V.opcode == Instruction::FCmp)
1940 return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate,
1941 V.operands[0], V.operands[1]);
1942 assert(0 && "Invalid ConstantExpr!");
1948 struct ConvertConstantType<ConstantExpr, Type> {
1949 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1951 switch (OldC->getOpcode()) {
1952 case Instruction::Trunc:
1953 case Instruction::ZExt:
1954 case Instruction::SExt:
1955 case Instruction::FPTrunc:
1956 case Instruction::FPExt:
1957 case Instruction::UIToFP:
1958 case Instruction::SIToFP:
1959 case Instruction::FPToUI:
1960 case Instruction::FPToSI:
1961 case Instruction::PtrToInt:
1962 case Instruction::IntToPtr:
1963 case Instruction::BitCast:
1964 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1967 case Instruction::Select:
1968 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1969 OldC->getOperand(1),
1970 OldC->getOperand(2));
1973 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1974 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1975 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1976 OldC->getOperand(1));
1978 case Instruction::GetElementPtr:
1979 // Make everyone now use a constant of the new type...
1980 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1981 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1982 &Idx[0], Idx.size());
1986 assert(New != OldC && "Didn't replace constant??");
1987 OldC->uncheckedReplaceAllUsesWith(New);
1988 OldC->destroyConstant(); // This constant is now dead, destroy it.
1991 } // end namespace llvm
1994 static ExprMapKeyType getValType(ConstantExpr *CE) {
1995 std::vector<Constant*> Operands;
1996 Operands.reserve(CE->getNumOperands());
1997 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1998 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1999 return ExprMapKeyType(CE->getOpcode(), Operands,
2000 CE->isCompare() ? CE->getPredicate() : 0,
2002 CE->getIndices() : SmallVector<unsigned, 4>());
2005 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
2006 ConstantExpr> > ExprConstants;
2008 /// This is a utility function to handle folding of casts and lookup of the
2009 /// cast in the ExprConstants map. It is used by the various get* methods below.
2010 static inline Constant *getFoldedCast(
2011 Instruction::CastOps opc, Constant *C, const Type *Ty) {
2012 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
2013 // Fold a few common cases
2014 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
2017 // Look up the constant in the table first to ensure uniqueness
2018 std::vector<Constant*> argVec(1, C);
2019 ExprMapKeyType Key(opc, argVec);
2021 // Implicitly locked.
2022 return ExprConstants->getOrCreate(Ty, Key);
2025 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
2026 Instruction::CastOps opc = Instruction::CastOps(oc);
2027 assert(Instruction::isCast(opc) && "opcode out of range");
2028 assert(C && Ty && "Null arguments to getCast");
2029 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
2033 assert(0 && "Invalid cast opcode");
2035 case Instruction::Trunc: return getTrunc(C, Ty);
2036 case Instruction::ZExt: return getZExt(C, Ty);
2037 case Instruction::SExt: return getSExt(C, Ty);
2038 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
2039 case Instruction::FPExt: return getFPExtend(C, Ty);
2040 case Instruction::UIToFP: return getUIToFP(C, Ty);
2041 case Instruction::SIToFP: return getSIToFP(C, Ty);
2042 case Instruction::FPToUI: return getFPToUI(C, Ty);
2043 case Instruction::FPToSI: return getFPToSI(C, Ty);
2044 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
2045 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
2046 case Instruction::BitCast: return getBitCast(C, Ty);
2051 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
2052 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2053 return getCast(Instruction::BitCast, C, Ty);
2054 return getCast(Instruction::ZExt, C, Ty);
2057 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
2058 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2059 return getCast(Instruction::BitCast, C, Ty);
2060 return getCast(Instruction::SExt, C, Ty);
2063 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
2064 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2065 return getCast(Instruction::BitCast, C, Ty);
2066 return getCast(Instruction::Trunc, C, Ty);
2069 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
2070 assert(isa<PointerType>(S->getType()) && "Invalid cast");
2071 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
2073 if (Ty->isInteger())
2074 return getCast(Instruction::PtrToInt, S, Ty);
2075 return getCast(Instruction::BitCast, S, Ty);
2078 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
2080 assert(C->getType()->isIntOrIntVector() &&
2081 Ty->isIntOrIntVector() && "Invalid cast");
2082 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2083 unsigned DstBits = Ty->getScalarSizeInBits();
2084 Instruction::CastOps opcode =
2085 (SrcBits == DstBits ? Instruction::BitCast :
2086 (SrcBits > DstBits ? Instruction::Trunc :
2087 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2088 return getCast(opcode, C, Ty);
2091 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
2092 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2094 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2095 unsigned DstBits = Ty->getScalarSizeInBits();
2096 if (SrcBits == DstBits)
2097 return C; // Avoid a useless cast
2098 Instruction::CastOps opcode =
2099 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
2100 return getCast(opcode, C, Ty);
2103 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
2105 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2106 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2108 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2109 assert(C->getType()->isIntOrIntVector() && "Trunc operand must be integer");
2110 assert(Ty->isIntOrIntVector() && "Trunc produces only integral");
2111 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
2112 "SrcTy must be larger than DestTy for Trunc!");
2114 return getFoldedCast(Instruction::Trunc, C, Ty);
2117 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
2119 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2120 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2122 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2123 assert(C->getType()->isIntOrIntVector() && "SExt operand must be integral");
2124 assert(Ty->isIntOrIntVector() && "SExt produces only integer");
2125 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
2126 "SrcTy must be smaller than DestTy for SExt!");
2128 return getFoldedCast(Instruction::SExt, C, Ty);
2131 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
2133 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2134 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2136 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2137 assert(C->getType()->isIntOrIntVector() && "ZEXt operand must be integral");
2138 assert(Ty->isIntOrIntVector() && "ZExt produces only integer");
2139 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
2140 "SrcTy must be smaller than DestTy for ZExt!");
2142 return getFoldedCast(Instruction::ZExt, C, Ty);
2145 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
2147 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2148 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2150 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2151 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2152 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
2153 "This is an illegal floating point truncation!");
2154 return getFoldedCast(Instruction::FPTrunc, C, Ty);
2157 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
2159 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2160 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2162 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2163 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2164 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
2165 "This is an illegal floating point extension!");
2166 return getFoldedCast(Instruction::FPExt, C, Ty);
2169 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
2171 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2172 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2174 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2175 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
2176 "This is an illegal uint to floating point cast!");
2177 return getFoldedCast(Instruction::UIToFP, C, Ty);
2180 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
2182 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2183 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2185 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2186 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
2187 "This is an illegal sint to floating point cast!");
2188 return getFoldedCast(Instruction::SIToFP, C, Ty);
2191 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
2193 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2194 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2196 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2197 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
2198 "This is an illegal floating point to uint cast!");
2199 return getFoldedCast(Instruction::FPToUI, C, Ty);
2202 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
2204 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2205 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2207 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2208 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
2209 "This is an illegal floating point to sint cast!");
2210 return getFoldedCast(Instruction::FPToSI, C, Ty);
2213 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
2214 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
2215 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
2216 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
2219 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
2220 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
2221 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
2222 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
2225 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
2226 // BitCast implies a no-op cast of type only. No bits change. However, you
2227 // can't cast pointers to anything but pointers.
2229 const Type *SrcTy = C->getType();
2230 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
2231 "BitCast cannot cast pointer to non-pointer and vice versa");
2233 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
2234 // or nonptr->ptr). For all the other types, the cast is okay if source and
2235 // destination bit widths are identical.
2236 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
2237 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
2239 assert(SrcBitSize == DstBitSize && "BitCast requires types of same width");
2241 // It is common to ask for a bitcast of a value to its own type, handle this
2243 if (C->getType() == DstTy) return C;
2245 return getFoldedCast(Instruction::BitCast, C, DstTy);
2248 Constant *ConstantExpr::getAlignOf(const Type *Ty) {
2249 // alignof is implemented as: (i64) gep ({i8,Ty}*)null, 0, 1
2250 const Type *AligningTy = StructType::get(Type::Int8Ty, Ty, NULL);
2251 Constant *NullPtr = getNullValue(AligningTy->getPointerTo());
2252 Constant *Zero = ConstantInt::get(Type::Int32Ty, 0);
2253 Constant *One = ConstantInt::get(Type::Int32Ty, 1);
2254 Constant *Indices[2] = { Zero, One };
2255 Constant *GEP = getGetElementPtr(NullPtr, Indices, 2);
2256 return getCast(Instruction::PtrToInt, GEP, Type::Int32Ty);
2259 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
2260 // sizeof is implemented as: (i64) gep (Ty*)null, 1
2261 Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
2263 getGetElementPtr(getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
2264 return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
2267 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
2268 Constant *C1, Constant *C2) {
2269 // Check the operands for consistency first
2270 assert(Opcode >= Instruction::BinaryOpsBegin &&
2271 Opcode < Instruction::BinaryOpsEnd &&
2272 "Invalid opcode in binary constant expression");
2273 assert(C1->getType() == C2->getType() &&
2274 "Operand types in binary constant expression should match");
2276 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
2277 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
2278 return FC; // Fold a few common cases...
2280 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
2281 ExprMapKeyType Key(Opcode, argVec);
2283 // Implicitly locked.
2284 return ExprConstants->getOrCreate(ReqTy, Key);
2287 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
2288 Constant *C1, Constant *C2) {
2289 switch (predicate) {
2290 default: assert(0 && "Invalid CmpInst predicate");
2291 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
2292 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
2293 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
2294 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
2295 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
2296 case CmpInst::FCMP_TRUE:
2297 return getFCmp(predicate, C1, C2);
2299 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
2300 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
2301 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
2302 case CmpInst::ICMP_SLE:
2303 return getICmp(predicate, C1, C2);
2307 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
2308 // API compatibility: Adjust integer opcodes to floating-point opcodes.
2309 if (C1->getType()->isFPOrFPVector()) {
2310 if (Opcode == Instruction::Add) Opcode = Instruction::FAdd;
2311 else if (Opcode == Instruction::Sub) Opcode = Instruction::FSub;
2312 else if (Opcode == Instruction::Mul) Opcode = Instruction::FMul;
2316 case Instruction::Add:
2317 case Instruction::Sub:
2318 case Instruction::Mul:
2319 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2320 assert(C1->getType()->isIntOrIntVector() &&
2321 "Tried to create an integer operation on a non-integer type!");
2323 case Instruction::FAdd:
2324 case Instruction::FSub:
2325 case Instruction::FMul:
2326 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2327 assert(C1->getType()->isFPOrFPVector() &&
2328 "Tried to create a floating-point operation on a "
2329 "non-floating-point type!");
2331 case Instruction::UDiv:
2332 case Instruction::SDiv:
2333 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2334 assert(C1->getType()->isIntOrIntVector() &&
2335 "Tried to create an arithmetic operation on a non-arithmetic type!");
2337 case Instruction::FDiv:
2338 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2339 assert(C1->getType()->isFPOrFPVector() &&
2340 "Tried to create an arithmetic operation on a non-arithmetic type!");
2342 case Instruction::URem:
2343 case Instruction::SRem:
2344 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2345 assert(C1->getType()->isIntOrIntVector() &&
2346 "Tried to create an arithmetic operation on a non-arithmetic type!");
2348 case Instruction::FRem:
2349 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2350 assert(C1->getType()->isFPOrFPVector() &&
2351 "Tried to create an arithmetic operation on a non-arithmetic type!");
2353 case Instruction::And:
2354 case Instruction::Or:
2355 case Instruction::Xor:
2356 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2357 assert(C1->getType()->isIntOrIntVector() &&
2358 "Tried to create a logical operation on a non-integral type!");
2360 case Instruction::Shl:
2361 case Instruction::LShr:
2362 case Instruction::AShr:
2363 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2364 assert(C1->getType()->isIntOrIntVector() &&
2365 "Tried to create a shift operation on a non-integer type!");
2372 return getTy(C1->getType(), Opcode, C1, C2);
2375 Constant *ConstantExpr::getCompare(unsigned short pred,
2376 Constant *C1, Constant *C2) {
2377 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2378 return getCompareTy(pred, C1, C2);
2381 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
2382 Constant *V1, Constant *V2) {
2383 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
2385 if (ReqTy == V1->getType())
2386 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
2387 return SC; // Fold common cases
2389 std::vector<Constant*> argVec(3, C);
2392 ExprMapKeyType Key(Instruction::Select, argVec);
2394 // Implicitly locked.
2395 return ExprConstants->getOrCreate(ReqTy, Key);
2398 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
2401 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
2403 cast<PointerType>(ReqTy)->getElementType() &&
2404 "GEP indices invalid!");
2406 if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs, NumIdx))
2407 return FC; // Fold a few common cases...
2409 assert(isa<PointerType>(C->getType()) &&
2410 "Non-pointer type for constant GetElementPtr expression");
2411 // Look up the constant in the table first to ensure uniqueness
2412 std::vector<Constant*> ArgVec;
2413 ArgVec.reserve(NumIdx+1);
2414 ArgVec.push_back(C);
2415 for (unsigned i = 0; i != NumIdx; ++i)
2416 ArgVec.push_back(cast<Constant>(Idxs[i]));
2417 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
2419 // Implicitly locked.
2420 return ExprConstants->getOrCreate(ReqTy, Key);
2423 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
2425 // Get the result type of the getelementptr!
2427 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
2428 assert(Ty && "GEP indices invalid!");
2429 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
2430 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
2433 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
2435 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
2440 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2441 assert(LHS->getType() == RHS->getType());
2442 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2443 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
2445 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2446 return FC; // Fold a few common cases...
2448 // Look up the constant in the table first to ensure uniqueness
2449 std::vector<Constant*> ArgVec;
2450 ArgVec.push_back(LHS);
2451 ArgVec.push_back(RHS);
2452 // Get the key type with both the opcode and predicate
2453 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
2455 // Implicitly locked.
2456 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2460 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2461 assert(LHS->getType() == RHS->getType());
2462 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
2464 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2465 return FC; // Fold a few common cases...
2467 // Look up the constant in the table first to ensure uniqueness
2468 std::vector<Constant*> ArgVec;
2469 ArgVec.push_back(LHS);
2470 ArgVec.push_back(RHS);
2471 // Get the key type with both the opcode and predicate
2472 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
2474 // Implicitly locked.
2475 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2478 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
2480 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
2481 return FC; // Fold a few common cases...
2482 // Look up the constant in the table first to ensure uniqueness
2483 std::vector<Constant*> ArgVec(1, Val);
2484 ArgVec.push_back(Idx);
2485 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
2487 // Implicitly locked.
2488 return ExprConstants->getOrCreate(ReqTy, Key);
2491 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
2492 assert(isa<VectorType>(Val->getType()) &&
2493 "Tried to create extractelement operation on non-vector type!");
2494 assert(Idx->getType() == Type::Int32Ty &&
2495 "Extractelement index must be i32 type!");
2496 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
2500 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
2501 Constant *Elt, Constant *Idx) {
2502 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2503 return FC; // Fold a few common cases...
2504 // Look up the constant in the table first to ensure uniqueness
2505 std::vector<Constant*> ArgVec(1, Val);
2506 ArgVec.push_back(Elt);
2507 ArgVec.push_back(Idx);
2508 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
2510 // Implicitly locked.
2511 return ExprConstants->getOrCreate(ReqTy, Key);
2514 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2516 assert(isa<VectorType>(Val->getType()) &&
2517 "Tried to create insertelement operation on non-vector type!");
2518 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
2519 && "Insertelement types must match!");
2520 assert(Idx->getType() == Type::Int32Ty &&
2521 "Insertelement index must be i32 type!");
2522 return getInsertElementTy(Val->getType(), Val, Elt, Idx);
2525 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
2526 Constant *V2, Constant *Mask) {
2527 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2528 return FC; // Fold a few common cases...
2529 // Look up the constant in the table first to ensure uniqueness
2530 std::vector<Constant*> ArgVec(1, V1);
2531 ArgVec.push_back(V2);
2532 ArgVec.push_back(Mask);
2533 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
2535 // Implicitly locked.
2536 return ExprConstants->getOrCreate(ReqTy, Key);
2539 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2541 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2542 "Invalid shuffle vector constant expr operands!");
2544 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
2545 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
2546 const Type *ShufTy = VectorType::get(EltTy, NElts);
2547 return getShuffleVectorTy(ShufTy, V1, V2, Mask);
2550 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
2552 const unsigned *Idxs, unsigned NumIdx) {
2553 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2554 Idxs+NumIdx) == Val->getType() &&
2555 "insertvalue indices invalid!");
2556 assert(Agg->getType() == ReqTy &&
2557 "insertvalue type invalid!");
2558 assert(Agg->getType()->isFirstClassType() &&
2559 "Non-first-class type for constant InsertValue expression");
2560 Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs, NumIdx);
2561 assert(FC && "InsertValue constant expr couldn't be folded!");
2565 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
2566 const unsigned *IdxList, unsigned NumIdx) {
2567 assert(Agg->getType()->isFirstClassType() &&
2568 "Tried to create insertelement operation on non-first-class type!");
2570 const Type *ReqTy = Agg->getType();
2573 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2575 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
2576 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
2579 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
2580 const unsigned *Idxs, unsigned NumIdx) {
2581 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2582 Idxs+NumIdx) == ReqTy &&
2583 "extractvalue indices invalid!");
2584 assert(Agg->getType()->isFirstClassType() &&
2585 "Non-first-class type for constant extractvalue expression");
2586 Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs, NumIdx);
2587 assert(FC && "ExtractValue constant expr couldn't be folded!");
2591 Constant *ConstantExpr::getExtractValue(Constant *Agg,
2592 const unsigned *IdxList, unsigned NumIdx) {
2593 assert(Agg->getType()->isFirstClassType() &&
2594 "Tried to create extractelement operation on non-first-class type!");
2597 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2598 assert(ReqTy && "extractvalue indices invalid!");
2599 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
2602 Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
2603 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
2604 if (PTy->getElementType()->isFloatingPoint()) {
2605 std::vector<Constant*> zeros(PTy->getNumElements(),
2606 ConstantFP::getNegativeZero(PTy->getElementType()));
2607 return ConstantVector::get(PTy, zeros);
2610 if (Ty->isFloatingPoint())
2611 return ConstantFP::getNegativeZero(Ty);
2613 return Constant::getNullValue(Ty);
2616 // destroyConstant - Remove the constant from the constant table...
2618 void ConstantExpr::destroyConstant() {
2619 // Implicitly locked.
2620 ExprConstants->remove(this);
2621 destroyConstantImpl();
2624 const char *ConstantExpr::getOpcodeName() const {
2625 return Instruction::getOpcodeName(getOpcode());
2628 //===----------------------------------------------------------------------===//
2629 // replaceUsesOfWithOnConstant implementations
2631 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2632 /// 'From' to be uses of 'To'. This must update the uniquing data structures
2635 /// Note that we intentionally replace all uses of From with To here. Consider
2636 /// a large array that uses 'From' 1000 times. By handling this case all here,
2637 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2638 /// single invocation handles all 1000 uses. Handling them one at a time would
2639 /// work, but would be really slow because it would have to unique each updated
2641 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
2643 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2644 Constant *ToC = cast<Constant>(To);
2646 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
2647 Lookup.first.first = getType();
2648 Lookup.second = this;
2650 std::vector<Constant*> &Values = Lookup.first.second;
2651 Values.reserve(getNumOperands()); // Build replacement array.
2653 // Fill values with the modified operands of the constant array. Also,
2654 // compute whether this turns into an all-zeros array.
2655 bool isAllZeros = false;
2656 unsigned NumUpdated = 0;
2657 if (!ToC->isNullValue()) {
2658 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2659 Constant *Val = cast<Constant>(O->get());
2664 Values.push_back(Val);
2668 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2669 Constant *Val = cast<Constant>(O->get());
2674 Values.push_back(Val);
2675 if (isAllZeros) isAllZeros = Val->isNullValue();
2679 Constant *Replacement = 0;
2681 Replacement = ConstantAggregateZero::get(getType());
2683 // Check to see if we have this array type already.
2684 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
2686 ArrayConstantsTy::MapTy::iterator I =
2687 ArrayConstants->InsertOrGetItem(Lookup, Exists);
2690 Replacement = I->second;
2692 // Okay, the new shape doesn't exist in the system yet. Instead of
2693 // creating a new constant array, inserting it, replaceallusesof'ing the
2694 // old with the new, then deleting the old... just update the current one
2696 ArrayConstants->MoveConstantToNewSlot(this, I);
2698 // Update to the new value. Optimize for the case when we have a single
2699 // operand that we're changing, but handle bulk updates efficiently.
2700 if (NumUpdated == 1) {
2701 unsigned OperandToUpdate = U-OperandList;
2702 assert(getOperand(OperandToUpdate) == From &&
2703 "ReplaceAllUsesWith broken!");
2704 setOperand(OperandToUpdate, ToC);
2706 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2707 if (getOperand(i) == From)
2714 // Otherwise, I do need to replace this with an existing value.
2715 assert(Replacement != this && "I didn't contain From!");
2717 // Everyone using this now uses the replacement.
2718 uncheckedReplaceAllUsesWith(Replacement);
2720 // Delete the old constant!
2724 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2726 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2727 Constant *ToC = cast<Constant>(To);
2729 unsigned OperandToUpdate = U-OperandList;
2730 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2732 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
2733 Lookup.first.first = getType();
2734 Lookup.second = this;
2735 std::vector<Constant*> &Values = Lookup.first.second;
2736 Values.reserve(getNumOperands()); // Build replacement struct.
2739 // Fill values with the modified operands of the constant struct. Also,
2740 // compute whether this turns into an all-zeros struct.
2741 bool isAllZeros = false;
2742 if (!ToC->isNullValue()) {
2743 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2744 Values.push_back(cast<Constant>(O->get()));
2747 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2748 Constant *Val = cast<Constant>(O->get());
2749 Values.push_back(Val);
2750 if (isAllZeros) isAllZeros = Val->isNullValue();
2753 Values[OperandToUpdate] = ToC;
2755 Constant *Replacement = 0;
2757 Replacement = ConstantAggregateZero::get(getType());
2759 // Check to see if we have this array type already.
2760 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
2762 StructConstantsTy::MapTy::iterator I =
2763 StructConstants->InsertOrGetItem(Lookup, Exists);
2766 Replacement = I->second;
2768 // Okay, the new shape doesn't exist in the system yet. Instead of
2769 // creating a new constant struct, inserting it, replaceallusesof'ing the
2770 // old with the new, then deleting the old... just update the current one
2772 StructConstants->MoveConstantToNewSlot(this, I);
2774 // Update to the new value.
2775 setOperand(OperandToUpdate, ToC);
2780 assert(Replacement != this && "I didn't contain From!");
2782 // Everyone using this now uses the replacement.
2783 uncheckedReplaceAllUsesWith(Replacement);
2785 // Delete the old constant!
2789 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2791 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2793 std::vector<Constant*> Values;
2794 Values.reserve(getNumOperands()); // Build replacement array...
2795 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2796 Constant *Val = getOperand(i);
2797 if (Val == From) Val = cast<Constant>(To);
2798 Values.push_back(Val);
2801 Constant *Replacement = ConstantVector::get(getType(), Values);
2802 assert(Replacement != this && "I didn't contain From!");
2804 // Everyone using this now uses the replacement.
2805 uncheckedReplaceAllUsesWith(Replacement);
2807 // Delete the old constant!
2811 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2813 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2814 Constant *To = cast<Constant>(ToV);
2816 Constant *Replacement = 0;
2817 if (getOpcode() == Instruction::GetElementPtr) {
2818 SmallVector<Constant*, 8> Indices;
2819 Constant *Pointer = getOperand(0);
2820 Indices.reserve(getNumOperands()-1);
2821 if (Pointer == From) Pointer = To;
2823 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2824 Constant *Val = getOperand(i);
2825 if (Val == From) Val = To;
2826 Indices.push_back(Val);
2828 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2829 &Indices[0], Indices.size());
2830 } else if (getOpcode() == Instruction::ExtractValue) {
2831 Constant *Agg = getOperand(0);
2832 if (Agg == From) Agg = To;
2834 const SmallVector<unsigned, 4> &Indices = getIndices();
2835 Replacement = ConstantExpr::getExtractValue(Agg,
2836 &Indices[0], Indices.size());
2837 } else if (getOpcode() == Instruction::InsertValue) {
2838 Constant *Agg = getOperand(0);
2839 Constant *Val = getOperand(1);
2840 if (Agg == From) Agg = To;
2841 if (Val == From) Val = To;
2843 const SmallVector<unsigned, 4> &Indices = getIndices();
2844 Replacement = ConstantExpr::getInsertValue(Agg, Val,
2845 &Indices[0], Indices.size());
2846 } else if (isCast()) {
2847 assert(getOperand(0) == From && "Cast only has one use!");
2848 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2849 } else if (getOpcode() == Instruction::Select) {
2850 Constant *C1 = getOperand(0);
2851 Constant *C2 = getOperand(1);
2852 Constant *C3 = getOperand(2);
2853 if (C1 == From) C1 = To;
2854 if (C2 == From) C2 = To;
2855 if (C3 == From) C3 = To;
2856 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2857 } else if (getOpcode() == Instruction::ExtractElement) {
2858 Constant *C1 = getOperand(0);
2859 Constant *C2 = getOperand(1);
2860 if (C1 == From) C1 = To;
2861 if (C2 == From) C2 = To;
2862 Replacement = ConstantExpr::getExtractElement(C1, C2);
2863 } else if (getOpcode() == Instruction::InsertElement) {
2864 Constant *C1 = getOperand(0);
2865 Constant *C2 = getOperand(1);
2866 Constant *C3 = getOperand(1);
2867 if (C1 == From) C1 = To;
2868 if (C2 == From) C2 = To;
2869 if (C3 == From) C3 = To;
2870 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2871 } else if (getOpcode() == Instruction::ShuffleVector) {
2872 Constant *C1 = getOperand(0);
2873 Constant *C2 = getOperand(1);
2874 Constant *C3 = getOperand(2);
2875 if (C1 == From) C1 = To;
2876 if (C2 == From) C2 = To;
2877 if (C3 == From) C3 = To;
2878 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2879 } else if (isCompare()) {
2880 Constant *C1 = getOperand(0);
2881 Constant *C2 = getOperand(1);
2882 if (C1 == From) C1 = To;
2883 if (C2 == From) C2 = To;
2884 if (getOpcode() == Instruction::ICmp)
2885 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2887 assert(getOpcode() == Instruction::FCmp);
2888 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2890 } else if (getNumOperands() == 2) {
2891 Constant *C1 = getOperand(0);
2892 Constant *C2 = getOperand(1);
2893 if (C1 == From) C1 = To;
2894 if (C2 == From) C2 = To;
2895 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2897 assert(0 && "Unknown ConstantExpr type!");
2901 assert(Replacement != this && "I didn't contain From!");
2903 // Everyone using this now uses the replacement.
2904 uncheckedReplaceAllUsesWith(Replacement);
2906 // Delete the old constant!
2910 void MDNode::replaceElement(Value *From, Value *To) {
2911 SmallVector<Value*, 4> Values;
2912 Values.reserve(getNumElements()); // Build replacement array...
2913 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
2914 Value *Val = getElement(i);
2915 if (Val == From) Val = To;
2916 Values.push_back(Val);
2919 MDNode *Replacement = MDNode::get(&Values[0], Values.size());
2920 assert(Replacement != this && "I didn't contain From!");
2922 uncheckedReplaceAllUsesWith(Replacement);