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/ErrorHandling.h"
27 #include "llvm/Support/ManagedStatic.h"
28 #include "llvm/Support/MathExtras.h"
29 #include "llvm/System/Mutex.h"
30 #include "llvm/System/RWMutex.h"
31 #include "llvm/System/Threading.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/SmallVector.h"
38 //===----------------------------------------------------------------------===//
40 //===----------------------------------------------------------------------===//
42 // Becomes a no-op when multithreading is disabled.
43 ManagedStatic<sys::SmartRWMutex<true> > ConstantsLock;
45 void Constant::destroyConstantImpl() {
46 // When a Constant is destroyed, there may be lingering
47 // references to the constant by other constants in the constant pool. These
48 // constants are implicitly dependent on the module that is being deleted,
49 // but they don't know that. Because we only find out when the CPV is
50 // deleted, we must now notify all of our users (that should only be
51 // Constants) that they are, in fact, invalid now and should be deleted.
53 while (!use_empty()) {
54 Value *V = use_back();
55 #ifndef NDEBUG // Only in -g mode...
56 if (!isa<Constant>(V))
57 DOUT << "While deleting: " << *this
58 << "\n\nUse still stuck around after Def is destroyed: "
61 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
62 Constant *CV = cast<Constant>(V);
63 CV->destroyConstant();
65 // The constant should remove itself from our use list...
66 assert((use_empty() || use_back() != V) && "Constant not removed!");
69 // Value has no outstanding references it is safe to delete it now...
73 /// canTrap - Return true if evaluation of this constant could trap. This is
74 /// true for things like constant expressions that could divide by zero.
75 bool Constant::canTrap() const {
76 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
77 // The only thing that could possibly trap are constant exprs.
78 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
79 if (!CE) return false;
81 // ConstantExpr traps if any operands can trap.
82 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
83 if (getOperand(i)->canTrap())
86 // Otherwise, only specific operations can trap.
87 switch (CE->getOpcode()) {
90 case Instruction::UDiv:
91 case Instruction::SDiv:
92 case Instruction::FDiv:
93 case Instruction::URem:
94 case Instruction::SRem:
95 case Instruction::FRem:
96 // Div and rem can trap if the RHS is not known to be non-zero.
97 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
103 /// ContainsRelocations - Return true if the constant value contains relocations
104 /// which cannot be resolved at compile time. Kind argument is used to filter
105 /// only 'interesting' sorts of relocations.
106 bool Constant::ContainsRelocations(unsigned Kind) const {
107 if (const GlobalValue* GV = dyn_cast<GlobalValue>(this)) {
108 bool isLocal = GV->hasLocalLinkage();
109 if ((Kind & Reloc::Local) && isLocal) {
110 // Global has local linkage and 'local' kind of relocations are
115 if ((Kind & Reloc::Global) && !isLocal) {
116 // Global has non-local linkage and 'global' kind of relocations are
124 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
125 if (getOperand(i)->ContainsRelocations(Kind))
131 // Static constructor to create a '0' constant of arbitrary type...
132 static const uint64_t zero[2] = {0, 0};
133 Constant *Constant::getNullValue(const Type *Ty) {
134 switch (Ty->getTypeID()) {
135 case Type::IntegerTyID:
136 return ConstantInt::get(Ty, 0);
137 case Type::FloatTyID:
138 return ConstantFP::get(APFloat(APInt(32, 0)));
139 case Type::DoubleTyID:
140 return ConstantFP::get(APFloat(APInt(64, 0)));
141 case Type::X86_FP80TyID:
142 return ConstantFP::get(APFloat(APInt(80, 2, zero)));
143 case Type::FP128TyID:
144 return ConstantFP::get(APFloat(APInt(128, 2, zero), true));
145 case Type::PPC_FP128TyID:
146 return ConstantFP::get(APFloat(APInt(128, 2, zero)));
147 case Type::PointerTyID:
148 return ConstantPointerNull::get(cast<PointerType>(Ty));
149 case Type::StructTyID:
150 case Type::ArrayTyID:
151 case Type::VectorTyID:
152 return ConstantAggregateZero::get(Ty);
154 // Function, Label, or Opaque type?
155 assert(!"Cannot create a null constant of that type!");
160 Constant *Constant::getAllOnesValue(const Type *Ty) {
161 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
162 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
163 return ConstantVector::getAllOnesValue(cast<VectorType>(Ty));
166 // Static constructor to create an integral constant with all bits set
167 ConstantInt *ConstantInt::getAllOnesValue(const Type *Ty) {
168 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
169 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
173 /// @returns the value for a vector integer constant of the given type that
174 /// has all its bits set to true.
175 /// @brief Get the all ones value
176 ConstantVector *ConstantVector::getAllOnesValue(const VectorType *Ty) {
177 std::vector<Constant*> Elts;
178 Elts.resize(Ty->getNumElements(),
179 ConstantInt::getAllOnesValue(Ty->getElementType()));
180 assert(Elts[0] && "Not a vector integer type!");
181 return cast<ConstantVector>(ConstantVector::get(Elts));
185 /// getVectorElements - This method, which is only valid on constant of vector
186 /// type, returns the elements of the vector in the specified smallvector.
187 /// This handles breaking down a vector undef into undef elements, etc. For
188 /// constant exprs and other cases we can't handle, we return an empty vector.
189 void Constant::getVectorElements(SmallVectorImpl<Constant*> &Elts) const {
190 assert(isa<VectorType>(getType()) && "Not a vector constant!");
192 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
193 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
194 Elts.push_back(CV->getOperand(i));
198 const VectorType *VT = cast<VectorType>(getType());
199 if (isa<ConstantAggregateZero>(this)) {
200 Elts.assign(VT->getNumElements(),
201 Constant::getNullValue(VT->getElementType()));
205 if (isa<UndefValue>(this)) {
206 Elts.assign(VT->getNumElements(), UndefValue::get(VT->getElementType()));
210 // Unknown type, must be constant expr etc.
215 //===----------------------------------------------------------------------===//
217 //===----------------------------------------------------------------------===//
219 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
220 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
221 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
224 ConstantInt *ConstantInt::TheTrueVal = 0;
225 ConstantInt *ConstantInt::TheFalseVal = 0;
228 void CleanupTrueFalse(void *) {
229 ConstantInt::ResetTrueFalse();
233 static ManagedCleanup<llvm::CleanupTrueFalse> TrueFalseCleanup;
235 ConstantInt *ConstantInt::CreateTrueFalseVals(bool WhichOne) {
236 assert(TheTrueVal == 0 && TheFalseVal == 0);
237 TheTrueVal = get(Type::Int1Ty, 1);
238 TheFalseVal = get(Type::Int1Ty, 0);
240 // Ensure that llvm_shutdown nulls out TheTrueVal/TheFalseVal.
241 TrueFalseCleanup.Register();
243 return WhichOne ? TheTrueVal : TheFalseVal;
248 struct DenseMapAPIntKeyInfo {
252 KeyTy(const APInt& V, const Type* Ty) : val(V), type(Ty) {}
253 KeyTy(const KeyTy& that) : val(that.val), type(that.type) {}
254 bool operator==(const KeyTy& that) const {
255 return type == that.type && this->val == that.val;
257 bool operator!=(const KeyTy& that) const {
258 return !this->operator==(that);
261 static inline KeyTy getEmptyKey() { return KeyTy(APInt(1,0), 0); }
262 static inline KeyTy getTombstoneKey() { return KeyTy(APInt(1,1), 0); }
263 static unsigned getHashValue(const KeyTy &Key) {
264 return DenseMapInfo<void*>::getHashValue(Key.type) ^
265 Key.val.getHashValue();
267 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
270 static bool isPod() { return false; }
275 typedef DenseMap<DenseMapAPIntKeyInfo::KeyTy, ConstantInt*,
276 DenseMapAPIntKeyInfo> IntMapTy;
277 static ManagedStatic<IntMapTy> IntConstants;
279 ConstantInt *ConstantInt::get(const IntegerType *Ty,
280 uint64_t V, bool isSigned) {
281 return get(APInt(Ty->getBitWidth(), V, isSigned));
284 Constant *ConstantInt::get(const Type *Ty, uint64_t V, bool isSigned) {
285 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
287 // For vectors, broadcast the value.
288 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
290 ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
295 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
296 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
297 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
298 // compare APInt's of different widths, which would violate an APInt class
299 // invariant which generates an assertion.
300 ConstantInt *ConstantInt::get(const APInt& V) {
301 // Get the corresponding integer type for the bit width of the value.
302 const IntegerType *ITy = IntegerType::get(V.getBitWidth());
303 // get an existing value or the insertion position
304 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
306 ConstantsLock->reader_acquire();
307 ConstantInt *&Slot = (*IntConstants)[Key];
308 ConstantsLock->reader_release();
311 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
312 ConstantInt *&NewSlot = (*IntConstants)[Key];
314 NewSlot = new ConstantInt(ITy, V);
323 Constant *ConstantInt::get(const Type *Ty, const APInt &V) {
324 ConstantInt *C = ConstantInt::get(V);
325 assert(C->getType() == Ty->getScalarType() &&
326 "ConstantInt type doesn't match the type implied by its value!");
328 // For vectors, broadcast the value.
329 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
331 ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
336 //===----------------------------------------------------------------------===//
338 //===----------------------------------------------------------------------===//
340 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
341 if (Ty == Type::FloatTy)
342 return &APFloat::IEEEsingle;
343 if (Ty == Type::DoubleTy)
344 return &APFloat::IEEEdouble;
345 if (Ty == Type::X86_FP80Ty)
346 return &APFloat::x87DoubleExtended;
347 else if (Ty == Type::FP128Ty)
348 return &APFloat::IEEEquad;
350 assert(Ty == Type::PPC_FP128Ty && "Unknown FP format");
351 return &APFloat::PPCDoubleDouble;
354 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
355 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
356 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
360 bool ConstantFP::isNullValue() const {
361 return Val.isZero() && !Val.isNegative();
364 ConstantFP *ConstantFP::getNegativeZero(const Type *Ty) {
365 APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
367 return ConstantFP::get(apf);
370 bool ConstantFP::isExactlyValue(const APFloat& V) const {
371 return Val.bitwiseIsEqual(V);
375 struct DenseMapAPFloatKeyInfo {
378 KeyTy(const APFloat& V) : val(V){}
379 KeyTy(const KeyTy& that) : val(that.val) {}
380 bool operator==(const KeyTy& that) const {
381 return this->val.bitwiseIsEqual(that.val);
383 bool operator!=(const KeyTy& that) const {
384 return !this->operator==(that);
387 static inline KeyTy getEmptyKey() {
388 return KeyTy(APFloat(APFloat::Bogus,1));
390 static inline KeyTy getTombstoneKey() {
391 return KeyTy(APFloat(APFloat::Bogus,2));
393 static unsigned getHashValue(const KeyTy &Key) {
394 return Key.val.getHashValue();
396 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
399 static bool isPod() { return false; }
403 //---- ConstantFP::get() implementation...
405 typedef DenseMap<DenseMapAPFloatKeyInfo::KeyTy, ConstantFP*,
406 DenseMapAPFloatKeyInfo> FPMapTy;
408 static ManagedStatic<FPMapTy> FPConstants;
410 ConstantFP *ConstantFP::get(const APFloat &V) {
411 DenseMapAPFloatKeyInfo::KeyTy Key(V);
413 ConstantsLock->reader_acquire();
414 ConstantFP *&Slot = (*FPConstants)[Key];
415 ConstantsLock->reader_release();
418 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
419 ConstantFP *&NewSlot = (*FPConstants)[Key];
422 if (&V.getSemantics() == &APFloat::IEEEsingle)
424 else if (&V.getSemantics() == &APFloat::IEEEdouble)
426 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
427 Ty = Type::X86_FP80Ty;
428 else if (&V.getSemantics() == &APFloat::IEEEquad)
431 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
432 "Unknown FP format");
433 Ty = Type::PPC_FP128Ty;
435 NewSlot = new ConstantFP(Ty, V);
444 /// get() - This returns a constant fp for the specified value in the
445 /// specified type. This should only be used for simple constant values like
446 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
447 Constant *ConstantFP::get(const Type *Ty, double V) {
450 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
451 APFloat::rmNearestTiesToEven, &ignored);
452 Constant *C = get(FV);
454 // For vectors, broadcast the value.
455 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
457 ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
462 //===----------------------------------------------------------------------===//
463 // ConstantXXX Classes
464 //===----------------------------------------------------------------------===//
467 ConstantArray::ConstantArray(const ArrayType *T,
468 const std::vector<Constant*> &V)
469 : Constant(T, ConstantArrayVal,
470 OperandTraits<ConstantArray>::op_end(this) - V.size(),
472 assert(V.size() == T->getNumElements() &&
473 "Invalid initializer vector for constant array");
474 Use *OL = OperandList;
475 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
478 assert((C->getType() == T->getElementType() ||
480 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
481 "Initializer for array element doesn't match array element type!");
487 ConstantStruct::ConstantStruct(const StructType *T,
488 const std::vector<Constant*> &V)
489 : Constant(T, ConstantStructVal,
490 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
492 assert(V.size() == T->getNumElements() &&
493 "Invalid initializer vector for constant structure");
494 Use *OL = OperandList;
495 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
498 assert((C->getType() == T->getElementType(I-V.begin()) ||
499 ((T->getElementType(I-V.begin())->isAbstract() ||
500 C->getType()->isAbstract()) &&
501 T->getElementType(I-V.begin())->getTypeID() ==
502 C->getType()->getTypeID())) &&
503 "Initializer for struct element doesn't match struct element type!");
509 ConstantVector::ConstantVector(const VectorType *T,
510 const std::vector<Constant*> &V)
511 : Constant(T, ConstantVectorVal,
512 OperandTraits<ConstantVector>::op_end(this) - V.size(),
514 Use *OL = OperandList;
515 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
518 assert((C->getType() == T->getElementType() ||
520 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
521 "Initializer for vector element doesn't match vector element type!");
528 // We declare several classes private to this file, so use an anonymous
532 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
533 /// behind the scenes to implement unary constant exprs.
534 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
535 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
537 // allocate space for exactly one operand
538 void *operator new(size_t s) {
539 return User::operator new(s, 1);
541 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
542 : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
545 /// Transparently provide more efficient getOperand methods.
546 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
549 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
550 /// behind the scenes to implement binary constant exprs.
551 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
552 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
554 // allocate space for exactly two operands
555 void *operator new(size_t s) {
556 return User::operator new(s, 2);
558 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
559 : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
563 /// Transparently provide more efficient getOperand methods.
564 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
567 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
568 /// behind the scenes to implement select constant exprs.
569 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
570 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
572 // allocate space for exactly three operands
573 void *operator new(size_t s) {
574 return User::operator new(s, 3);
576 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
577 : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
582 /// Transparently provide more efficient getOperand methods.
583 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
586 /// ExtractElementConstantExpr - This class is private to
587 /// Constants.cpp, and is used behind the scenes to implement
588 /// extractelement constant exprs.
589 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
590 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
592 // allocate space for exactly two operands
593 void *operator new(size_t s) {
594 return User::operator new(s, 2);
596 ExtractElementConstantExpr(Constant *C1, Constant *C2)
597 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
598 Instruction::ExtractElement, &Op<0>(), 2) {
602 /// Transparently provide more efficient getOperand methods.
603 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
606 /// InsertElementConstantExpr - This class is private to
607 /// Constants.cpp, and is used behind the scenes to implement
608 /// insertelement constant exprs.
609 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
610 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
612 // allocate space for exactly three operands
613 void *operator new(size_t s) {
614 return User::operator new(s, 3);
616 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
617 : ConstantExpr(C1->getType(), Instruction::InsertElement,
623 /// Transparently provide more efficient getOperand methods.
624 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
627 /// ShuffleVectorConstantExpr - This class is private to
628 /// Constants.cpp, and is used behind the scenes to implement
629 /// shufflevector constant exprs.
630 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
631 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
633 // allocate space for exactly three operands
634 void *operator new(size_t s) {
635 return User::operator new(s, 3);
637 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
638 : ConstantExpr(VectorType::get(
639 cast<VectorType>(C1->getType())->getElementType(),
640 cast<VectorType>(C3->getType())->getNumElements()),
641 Instruction::ShuffleVector,
647 /// Transparently provide more efficient getOperand methods.
648 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
651 /// ExtractValueConstantExpr - This class is private to
652 /// Constants.cpp, and is used behind the scenes to implement
653 /// extractvalue constant exprs.
654 class VISIBILITY_HIDDEN ExtractValueConstantExpr : public ConstantExpr {
655 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
657 // allocate space for exactly one operand
658 void *operator new(size_t s) {
659 return User::operator new(s, 1);
661 ExtractValueConstantExpr(Constant *Agg,
662 const SmallVector<unsigned, 4> &IdxList,
664 : ConstantExpr(DestTy, Instruction::ExtractValue, &Op<0>(), 1),
669 /// Indices - These identify which value to extract.
670 const SmallVector<unsigned, 4> Indices;
672 /// Transparently provide more efficient getOperand methods.
673 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
676 /// InsertValueConstantExpr - This class is private to
677 /// Constants.cpp, and is used behind the scenes to implement
678 /// insertvalue constant exprs.
679 class VISIBILITY_HIDDEN InsertValueConstantExpr : public ConstantExpr {
680 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
682 // allocate space for exactly one operand
683 void *operator new(size_t s) {
684 return User::operator new(s, 2);
686 InsertValueConstantExpr(Constant *Agg, Constant *Val,
687 const SmallVector<unsigned, 4> &IdxList,
689 : ConstantExpr(DestTy, Instruction::InsertValue, &Op<0>(), 2),
695 /// Indices - These identify the position for the insertion.
696 const SmallVector<unsigned, 4> Indices;
698 /// Transparently provide more efficient getOperand methods.
699 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
703 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
704 /// used behind the scenes to implement getelementpr constant exprs.
705 class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
706 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
709 static GetElementPtrConstantExpr *Create(Constant *C,
710 const std::vector<Constant*>&IdxList,
711 const Type *DestTy) {
712 return new(IdxList.size() + 1)
713 GetElementPtrConstantExpr(C, IdxList, DestTy);
715 /// Transparently provide more efficient getOperand methods.
716 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
719 // CompareConstantExpr - This class is private to Constants.cpp, and is used
720 // behind the scenes to implement ICmp and FCmp constant expressions. This is
721 // needed in order to store the predicate value for these instructions.
722 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
723 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
724 // allocate space for exactly two operands
725 void *operator new(size_t s) {
726 return User::operator new(s, 2);
728 unsigned short predicate;
729 CompareConstantExpr(const Type *ty, Instruction::OtherOps opc,
730 unsigned short pred, Constant* LHS, Constant* RHS)
731 : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
735 /// Transparently provide more efficient getOperand methods.
736 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
739 } // end anonymous namespace
742 struct OperandTraits<UnaryConstantExpr> : FixedNumOperandTraits<1> {
744 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
747 struct OperandTraits<BinaryConstantExpr> : FixedNumOperandTraits<2> {
749 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
752 struct OperandTraits<SelectConstantExpr> : FixedNumOperandTraits<3> {
754 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
757 struct OperandTraits<ExtractElementConstantExpr> : FixedNumOperandTraits<2> {
759 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
762 struct OperandTraits<InsertElementConstantExpr> : FixedNumOperandTraits<3> {
764 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
767 struct OperandTraits<ShuffleVectorConstantExpr> : FixedNumOperandTraits<3> {
769 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
772 struct OperandTraits<ExtractValueConstantExpr> : FixedNumOperandTraits<1> {
774 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractValueConstantExpr, Value)
777 struct OperandTraits<InsertValueConstantExpr> : FixedNumOperandTraits<2> {
779 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueConstantExpr, Value)
782 struct OperandTraits<GetElementPtrConstantExpr> : VariadicOperandTraits<1> {
785 GetElementPtrConstantExpr::GetElementPtrConstantExpr
787 const std::vector<Constant*> &IdxList,
789 : ConstantExpr(DestTy, Instruction::GetElementPtr,
790 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
791 - (IdxList.size()+1),
794 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
795 OperandList[i+1] = IdxList[i];
798 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
802 struct OperandTraits<CompareConstantExpr> : FixedNumOperandTraits<2> {
804 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
807 } // End llvm namespace
810 // Utility function for determining if a ConstantExpr is a CastOp or not. This
811 // can't be inline because we don't want to #include Instruction.h into
813 bool ConstantExpr::isCast() const {
814 return Instruction::isCast(getOpcode());
817 bool ConstantExpr::isCompare() const {
818 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
821 bool ConstantExpr::hasIndices() const {
822 return getOpcode() == Instruction::ExtractValue ||
823 getOpcode() == Instruction::InsertValue;
826 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
827 if (const ExtractValueConstantExpr *EVCE =
828 dyn_cast<ExtractValueConstantExpr>(this))
829 return EVCE->Indices;
831 return cast<InsertValueConstantExpr>(this)->Indices;
834 /// ConstantExpr::get* - Return some common constants without having to
835 /// specify the full Instruction::OPCODE identifier.
837 Constant *ConstantExpr::getNeg(Constant *C) {
838 // API compatibility: Adjust integer opcodes to floating-point opcodes.
839 if (C->getType()->isFPOrFPVector())
841 assert(C->getType()->isIntOrIntVector() &&
842 "Cannot NEG a nonintegral value!");
843 return get(Instruction::Sub,
844 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
847 Constant *ConstantExpr::getFNeg(Constant *C) {
848 assert(C->getType()->isFPOrFPVector() &&
849 "Cannot FNEG a non-floating-point value!");
850 return get(Instruction::FSub,
851 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
854 Constant *ConstantExpr::getNot(Constant *C) {
855 assert(C->getType()->isIntOrIntVector() &&
856 "Cannot NOT a nonintegral value!");
857 return get(Instruction::Xor, C,
858 Constant::getAllOnesValue(C->getType()));
860 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
861 return get(Instruction::Add, C1, C2);
863 Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
864 return get(Instruction::FAdd, C1, C2);
866 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
867 return get(Instruction::Sub, C1, C2);
869 Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
870 return get(Instruction::FSub, C1, C2);
872 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
873 return get(Instruction::Mul, C1, C2);
875 Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
876 return get(Instruction::FMul, C1, C2);
878 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
879 return get(Instruction::UDiv, C1, C2);
881 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
882 return get(Instruction::SDiv, C1, C2);
884 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
885 return get(Instruction::FDiv, C1, C2);
887 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
888 return get(Instruction::URem, C1, C2);
890 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
891 return get(Instruction::SRem, C1, C2);
893 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
894 return get(Instruction::FRem, C1, C2);
896 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
897 return get(Instruction::And, C1, C2);
899 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
900 return get(Instruction::Or, C1, C2);
902 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
903 return get(Instruction::Xor, C1, C2);
905 unsigned ConstantExpr::getPredicate() const {
906 assert(getOpcode() == Instruction::FCmp ||
907 getOpcode() == Instruction::ICmp);
908 return ((const CompareConstantExpr*)this)->predicate;
910 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
911 return get(Instruction::Shl, C1, C2);
913 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
914 return get(Instruction::LShr, C1, C2);
916 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
917 return get(Instruction::AShr, C1, C2);
920 /// getWithOperandReplaced - Return a constant expression identical to this
921 /// one, but with the specified operand set to the specified value.
923 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
924 assert(OpNo < getNumOperands() && "Operand num is out of range!");
925 assert(Op->getType() == getOperand(OpNo)->getType() &&
926 "Replacing operand with value of different type!");
927 if (getOperand(OpNo) == Op)
928 return const_cast<ConstantExpr*>(this);
930 Constant *Op0, *Op1, *Op2;
931 switch (getOpcode()) {
932 case Instruction::Trunc:
933 case Instruction::ZExt:
934 case Instruction::SExt:
935 case Instruction::FPTrunc:
936 case Instruction::FPExt:
937 case Instruction::UIToFP:
938 case Instruction::SIToFP:
939 case Instruction::FPToUI:
940 case Instruction::FPToSI:
941 case Instruction::PtrToInt:
942 case Instruction::IntToPtr:
943 case Instruction::BitCast:
944 return ConstantExpr::getCast(getOpcode(), Op, getType());
945 case Instruction::Select:
946 Op0 = (OpNo == 0) ? Op : getOperand(0);
947 Op1 = (OpNo == 1) ? Op : getOperand(1);
948 Op2 = (OpNo == 2) ? Op : getOperand(2);
949 return ConstantExpr::getSelect(Op0, Op1, Op2);
950 case Instruction::InsertElement:
951 Op0 = (OpNo == 0) ? Op : getOperand(0);
952 Op1 = (OpNo == 1) ? Op : getOperand(1);
953 Op2 = (OpNo == 2) ? Op : getOperand(2);
954 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
955 case Instruction::ExtractElement:
956 Op0 = (OpNo == 0) ? Op : getOperand(0);
957 Op1 = (OpNo == 1) ? Op : getOperand(1);
958 return ConstantExpr::getExtractElement(Op0, Op1);
959 case Instruction::ShuffleVector:
960 Op0 = (OpNo == 0) ? Op : getOperand(0);
961 Op1 = (OpNo == 1) ? Op : getOperand(1);
962 Op2 = (OpNo == 2) ? Op : getOperand(2);
963 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
964 case Instruction::GetElementPtr: {
965 SmallVector<Constant*, 8> Ops;
966 Ops.resize(getNumOperands()-1);
967 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
968 Ops[i-1] = getOperand(i);
970 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
972 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
975 assert(getNumOperands() == 2 && "Must be binary operator?");
976 Op0 = (OpNo == 0) ? Op : getOperand(0);
977 Op1 = (OpNo == 1) ? Op : getOperand(1);
978 return ConstantExpr::get(getOpcode(), Op0, Op1);
982 /// getWithOperands - This returns the current constant expression with the
983 /// operands replaced with the specified values. The specified operands must
984 /// match count and type with the existing ones.
985 Constant *ConstantExpr::
986 getWithOperands(Constant* const *Ops, unsigned NumOps) const {
987 assert(NumOps == getNumOperands() && "Operand count mismatch!");
988 bool AnyChange = false;
989 for (unsigned i = 0; i != NumOps; ++i) {
990 assert(Ops[i]->getType() == getOperand(i)->getType() &&
991 "Operand type mismatch!");
992 AnyChange |= Ops[i] != getOperand(i);
994 if (!AnyChange) // No operands changed, return self.
995 return const_cast<ConstantExpr*>(this);
997 switch (getOpcode()) {
998 case Instruction::Trunc:
999 case Instruction::ZExt:
1000 case Instruction::SExt:
1001 case Instruction::FPTrunc:
1002 case Instruction::FPExt:
1003 case Instruction::UIToFP:
1004 case Instruction::SIToFP:
1005 case Instruction::FPToUI:
1006 case Instruction::FPToSI:
1007 case Instruction::PtrToInt:
1008 case Instruction::IntToPtr:
1009 case Instruction::BitCast:
1010 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
1011 case Instruction::Select:
1012 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
1013 case Instruction::InsertElement:
1014 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
1015 case Instruction::ExtractElement:
1016 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
1017 case Instruction::ShuffleVector:
1018 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
1019 case Instruction::GetElementPtr:
1020 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
1021 case Instruction::ICmp:
1022 case Instruction::FCmp:
1023 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
1025 assert(getNumOperands() == 2 && "Must be binary operator?");
1026 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
1031 //===----------------------------------------------------------------------===//
1032 // isValueValidForType implementations
1034 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
1035 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
1036 if (Ty == Type::Int1Ty)
1037 return Val == 0 || Val == 1;
1039 return true; // always true, has to fit in largest type
1040 uint64_t Max = (1ll << NumBits) - 1;
1044 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
1045 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
1046 if (Ty == Type::Int1Ty)
1047 return Val == 0 || Val == 1 || Val == -1;
1049 return true; // always true, has to fit in largest type
1050 int64_t Min = -(1ll << (NumBits-1));
1051 int64_t Max = (1ll << (NumBits-1)) - 1;
1052 return (Val >= Min && Val <= Max);
1055 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
1056 // convert modifies in place, so make a copy.
1057 APFloat Val2 = APFloat(Val);
1059 switch (Ty->getTypeID()) {
1061 return false; // These can't be represented as floating point!
1063 // FIXME rounding mode needs to be more flexible
1064 case Type::FloatTyID: {
1065 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
1067 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
1070 case Type::DoubleTyID: {
1071 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
1072 &Val2.getSemantics() == &APFloat::IEEEdouble)
1074 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
1077 case Type::X86_FP80TyID:
1078 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1079 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1080 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
1081 case Type::FP128TyID:
1082 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1083 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1084 &Val2.getSemantics() == &APFloat::IEEEquad;
1085 case Type::PPC_FP128TyID:
1086 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1087 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1088 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
1092 //===----------------------------------------------------------------------===//
1093 // Factory Function Implementation
1096 // The number of operands for each ConstantCreator::create method is
1097 // determined by the ConstantTraits template.
1098 // ConstantCreator - A class that is used to create constants by
1099 // ValueMap*. This class should be partially specialized if there is
1100 // something strange that needs to be done to interface to the ctor for the
1104 template<class ValType>
1105 struct ConstantTraits;
1107 template<typename T, typename Alloc>
1108 struct VISIBILITY_HIDDEN ConstantTraits< std::vector<T, Alloc> > {
1109 static unsigned uses(const std::vector<T, Alloc>& v) {
1114 template<class ConstantClass, class TypeClass, class ValType>
1115 struct VISIBILITY_HIDDEN ConstantCreator {
1116 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
1117 return new(ConstantTraits<ValType>::uses(V)) ConstantClass(Ty, V);
1121 template<class ConstantClass, class TypeClass>
1122 struct VISIBILITY_HIDDEN ConvertConstantType {
1123 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
1124 LLVM_UNREACHABLE("This type cannot be converted!");
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 LLVM_UNREACHABLE("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 LLVM_UNREACHABLE("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: LLVM_UNREACHABLE("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 LLVM_UNREACHABLE("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);