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 /// getVectorElements - This method, which is only valid on constant of vector
132 /// type, returns the elements of the vector in the specified smallvector.
133 /// This handles breaking down a vector undef into undef elements, etc. For
134 /// constant exprs and other cases we can't handle, we return an empty vector.
135 void Constant::getVectorElements(LLVMContext &Context,
136 SmallVectorImpl<Constant*> &Elts) const {
137 assert(isa<VectorType>(getType()) && "Not a vector constant!");
139 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
140 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
141 Elts.push_back(CV->getOperand(i));
145 const VectorType *VT = cast<VectorType>(getType());
146 if (isa<ConstantAggregateZero>(this)) {
147 Elts.assign(VT->getNumElements(),
148 Context.getNullValue(VT->getElementType()));
152 if (isa<UndefValue>(this)) {
153 Elts.assign(VT->getNumElements(), Context.getUndef(VT->getElementType()));
157 // Unknown type, must be constant expr etc.
162 //===----------------------------------------------------------------------===//
164 //===----------------------------------------------------------------------===//
166 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
167 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
168 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
171 ConstantInt *ConstantInt::TheTrueVal = 0;
172 ConstantInt *ConstantInt::TheFalseVal = 0;
175 void CleanupTrueFalse(void *) {
176 ConstantInt::ResetTrueFalse();
180 static ManagedCleanup<llvm::CleanupTrueFalse> TrueFalseCleanup;
182 ConstantInt *ConstantInt::CreateTrueFalseVals(bool WhichOne) {
183 assert(TheTrueVal == 0 && TheFalseVal == 0);
184 TheTrueVal = get(Type::Int1Ty, 1);
185 TheFalseVal = get(Type::Int1Ty, 0);
187 // Ensure that llvm_shutdown nulls out TheTrueVal/TheFalseVal.
188 TrueFalseCleanup.Register();
190 return WhichOne ? TheTrueVal : TheFalseVal;
195 struct DenseMapAPIntKeyInfo {
199 KeyTy(const APInt& V, const Type* Ty) : val(V), type(Ty) {}
200 KeyTy(const KeyTy& that) : val(that.val), type(that.type) {}
201 bool operator==(const KeyTy& that) const {
202 return type == that.type && this->val == that.val;
204 bool operator!=(const KeyTy& that) const {
205 return !this->operator==(that);
208 static inline KeyTy getEmptyKey() { return KeyTy(APInt(1,0), 0); }
209 static inline KeyTy getTombstoneKey() { return KeyTy(APInt(1,1), 0); }
210 static unsigned getHashValue(const KeyTy &Key) {
211 return DenseMapInfo<void*>::getHashValue(Key.type) ^
212 Key.val.getHashValue();
214 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
217 static bool isPod() { return false; }
222 typedef DenseMap<DenseMapAPIntKeyInfo::KeyTy, ConstantInt*,
223 DenseMapAPIntKeyInfo> IntMapTy;
224 static ManagedStatic<IntMapTy> IntConstants;
226 ConstantInt *ConstantInt::get(const IntegerType *Ty,
227 uint64_t V, bool isSigned) {
228 return get(APInt(Ty->getBitWidth(), V, isSigned));
231 Constant *ConstantInt::get(const Type *Ty, uint64_t V, bool isSigned) {
232 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
234 // For vectors, broadcast the value.
235 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
237 ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
242 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
243 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
244 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
245 // compare APInt's of different widths, which would violate an APInt class
246 // invariant which generates an assertion.
247 ConstantInt *ConstantInt::get(const APInt& V) {
248 // Get the corresponding integer type for the bit width of the value.
249 const IntegerType *ITy = IntegerType::get(V.getBitWidth());
250 // get an existing value or the insertion position
251 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
253 ConstantsLock->reader_acquire();
254 ConstantInt *&Slot = (*IntConstants)[Key];
255 ConstantsLock->reader_release();
258 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
259 ConstantInt *&NewSlot = (*IntConstants)[Key];
261 NewSlot = new ConstantInt(ITy, V);
270 Constant *ConstantInt::get(const Type *Ty, const APInt &V) {
271 ConstantInt *C = ConstantInt::get(V);
272 assert(C->getType() == Ty->getScalarType() &&
273 "ConstantInt type doesn't match the type implied by its value!");
275 // For vectors, broadcast the value.
276 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
278 ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
283 //===----------------------------------------------------------------------===//
285 //===----------------------------------------------------------------------===//
287 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
288 if (Ty == Type::FloatTy)
289 return &APFloat::IEEEsingle;
290 if (Ty == Type::DoubleTy)
291 return &APFloat::IEEEdouble;
292 if (Ty == Type::X86_FP80Ty)
293 return &APFloat::x87DoubleExtended;
294 else if (Ty == Type::FP128Ty)
295 return &APFloat::IEEEquad;
297 assert(Ty == Type::PPC_FP128Ty && "Unknown FP format");
298 return &APFloat::PPCDoubleDouble;
301 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
302 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
303 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
307 bool ConstantFP::isNullValue() const {
308 return Val.isZero() && !Val.isNegative();
311 bool ConstantFP::isExactlyValue(const APFloat& V) const {
312 return Val.bitwiseIsEqual(V);
316 struct DenseMapAPFloatKeyInfo {
319 KeyTy(const APFloat& V) : val(V){}
320 KeyTy(const KeyTy& that) : val(that.val) {}
321 bool operator==(const KeyTy& that) const {
322 return this->val.bitwiseIsEqual(that.val);
324 bool operator!=(const KeyTy& that) const {
325 return !this->operator==(that);
328 static inline KeyTy getEmptyKey() {
329 return KeyTy(APFloat(APFloat::Bogus,1));
331 static inline KeyTy getTombstoneKey() {
332 return KeyTy(APFloat(APFloat::Bogus,2));
334 static unsigned getHashValue(const KeyTy &Key) {
335 return Key.val.getHashValue();
337 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
340 static bool isPod() { return false; }
344 //---- ConstantFP::get() implementation...
346 typedef DenseMap<DenseMapAPFloatKeyInfo::KeyTy, ConstantFP*,
347 DenseMapAPFloatKeyInfo> FPMapTy;
349 static ManagedStatic<FPMapTy> FPConstants;
351 ConstantFP *ConstantFP::get(const APFloat &V) {
352 DenseMapAPFloatKeyInfo::KeyTy Key(V);
354 ConstantsLock->reader_acquire();
355 ConstantFP *&Slot = (*FPConstants)[Key];
356 ConstantsLock->reader_release();
359 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
360 ConstantFP *&NewSlot = (*FPConstants)[Key];
363 if (&V.getSemantics() == &APFloat::IEEEsingle)
365 else if (&V.getSemantics() == &APFloat::IEEEdouble)
367 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
368 Ty = Type::X86_FP80Ty;
369 else if (&V.getSemantics() == &APFloat::IEEEquad)
372 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
373 "Unknown FP format");
374 Ty = Type::PPC_FP128Ty;
376 NewSlot = new ConstantFP(Ty, V);
385 /// get() - This returns a constant fp for the specified value in the
386 /// specified type. This should only be used for simple constant values like
387 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
388 Constant *ConstantFP::get(const Type *Ty, double V) {
391 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
392 APFloat::rmNearestTiesToEven, &ignored);
393 Constant *C = get(FV);
395 // For vectors, broadcast the value.
396 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
398 ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
403 //===----------------------------------------------------------------------===//
404 // ConstantXXX Classes
405 //===----------------------------------------------------------------------===//
408 ConstantArray::ConstantArray(const ArrayType *T,
409 const std::vector<Constant*> &V)
410 : Constant(T, ConstantArrayVal,
411 OperandTraits<ConstantArray>::op_end(this) - V.size(),
413 assert(V.size() == T->getNumElements() &&
414 "Invalid initializer vector for constant array");
415 Use *OL = OperandList;
416 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
419 assert((C->getType() == T->getElementType() ||
421 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
422 "Initializer for array element doesn't match array element type!");
428 ConstantStruct::ConstantStruct(const StructType *T,
429 const std::vector<Constant*> &V)
430 : Constant(T, ConstantStructVal,
431 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
433 assert(V.size() == T->getNumElements() &&
434 "Invalid initializer vector for constant structure");
435 Use *OL = OperandList;
436 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
439 assert((C->getType() == T->getElementType(I-V.begin()) ||
440 ((T->getElementType(I-V.begin())->isAbstract() ||
441 C->getType()->isAbstract()) &&
442 T->getElementType(I-V.begin())->getTypeID() ==
443 C->getType()->getTypeID())) &&
444 "Initializer for struct element doesn't match struct element type!");
450 ConstantVector::ConstantVector(const VectorType *T,
451 const std::vector<Constant*> &V)
452 : Constant(T, ConstantVectorVal,
453 OperandTraits<ConstantVector>::op_end(this) - V.size(),
455 Use *OL = OperandList;
456 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
459 assert((C->getType() == T->getElementType() ||
461 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
462 "Initializer for vector element doesn't match vector element type!");
469 // We declare several classes private to this file, so use an anonymous
473 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
474 /// behind the scenes to implement unary constant exprs.
475 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
476 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
478 // allocate space for exactly one operand
479 void *operator new(size_t s) {
480 return User::operator new(s, 1);
482 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
483 : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
486 /// Transparently provide more efficient getOperand methods.
487 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
490 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
491 /// behind the scenes to implement binary constant exprs.
492 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
493 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
495 // allocate space for exactly two operands
496 void *operator new(size_t s) {
497 return User::operator new(s, 2);
499 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
500 : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
504 /// Transparently provide more efficient getOperand methods.
505 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
508 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
509 /// behind the scenes to implement select constant exprs.
510 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
511 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
513 // allocate space for exactly three operands
514 void *operator new(size_t s) {
515 return User::operator new(s, 3);
517 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
518 : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
523 /// Transparently provide more efficient getOperand methods.
524 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
527 /// ExtractElementConstantExpr - This class is private to
528 /// Constants.cpp, and is used behind the scenes to implement
529 /// extractelement constant exprs.
530 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
531 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
533 // allocate space for exactly two operands
534 void *operator new(size_t s) {
535 return User::operator new(s, 2);
537 ExtractElementConstantExpr(Constant *C1, Constant *C2)
538 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
539 Instruction::ExtractElement, &Op<0>(), 2) {
543 /// Transparently provide more efficient getOperand methods.
544 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
547 /// InsertElementConstantExpr - This class is private to
548 /// Constants.cpp, and is used behind the scenes to implement
549 /// insertelement constant exprs.
550 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
551 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
553 // allocate space for exactly three operands
554 void *operator new(size_t s) {
555 return User::operator new(s, 3);
557 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
558 : ConstantExpr(C1->getType(), Instruction::InsertElement,
564 /// Transparently provide more efficient getOperand methods.
565 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
568 /// ShuffleVectorConstantExpr - This class is private to
569 /// Constants.cpp, and is used behind the scenes to implement
570 /// shufflevector constant exprs.
571 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
572 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
574 // allocate space for exactly three operands
575 void *operator new(size_t s) {
576 return User::operator new(s, 3);
578 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
579 : ConstantExpr(VectorType::get(
580 cast<VectorType>(C1->getType())->getElementType(),
581 cast<VectorType>(C3->getType())->getNumElements()),
582 Instruction::ShuffleVector,
588 /// Transparently provide more efficient getOperand methods.
589 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
592 /// ExtractValueConstantExpr - This class is private to
593 /// Constants.cpp, and is used behind the scenes to implement
594 /// extractvalue constant exprs.
595 class VISIBILITY_HIDDEN ExtractValueConstantExpr : public ConstantExpr {
596 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
598 // allocate space for exactly one operand
599 void *operator new(size_t s) {
600 return User::operator new(s, 1);
602 ExtractValueConstantExpr(Constant *Agg,
603 const SmallVector<unsigned, 4> &IdxList,
605 : ConstantExpr(DestTy, Instruction::ExtractValue, &Op<0>(), 1),
610 /// Indices - These identify which value to extract.
611 const SmallVector<unsigned, 4> Indices;
613 /// Transparently provide more efficient getOperand methods.
614 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
617 /// InsertValueConstantExpr - This class is private to
618 /// Constants.cpp, and is used behind the scenes to implement
619 /// insertvalue constant exprs.
620 class VISIBILITY_HIDDEN InsertValueConstantExpr : public ConstantExpr {
621 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
623 // allocate space for exactly one operand
624 void *operator new(size_t s) {
625 return User::operator new(s, 2);
627 InsertValueConstantExpr(Constant *Agg, Constant *Val,
628 const SmallVector<unsigned, 4> &IdxList,
630 : ConstantExpr(DestTy, Instruction::InsertValue, &Op<0>(), 2),
636 /// Indices - These identify the position for the insertion.
637 const SmallVector<unsigned, 4> Indices;
639 /// Transparently provide more efficient getOperand methods.
640 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
644 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
645 /// used behind the scenes to implement getelementpr constant exprs.
646 class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
647 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
650 static GetElementPtrConstantExpr *Create(Constant *C,
651 const std::vector<Constant*>&IdxList,
652 const Type *DestTy) {
653 return new(IdxList.size() + 1)
654 GetElementPtrConstantExpr(C, IdxList, DestTy);
656 /// Transparently provide more efficient getOperand methods.
657 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
660 // CompareConstantExpr - This class is private to Constants.cpp, and is used
661 // behind the scenes to implement ICmp and FCmp constant expressions. This is
662 // needed in order to store the predicate value for these instructions.
663 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
664 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
665 // allocate space for exactly two operands
666 void *operator new(size_t s) {
667 return User::operator new(s, 2);
669 unsigned short predicate;
670 CompareConstantExpr(const Type *ty, Instruction::OtherOps opc,
671 unsigned short pred, Constant* LHS, Constant* RHS)
672 : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
676 /// Transparently provide more efficient getOperand methods.
677 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
680 } // end anonymous namespace
683 struct OperandTraits<UnaryConstantExpr> : FixedNumOperandTraits<1> {
685 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
688 struct OperandTraits<BinaryConstantExpr> : FixedNumOperandTraits<2> {
690 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
693 struct OperandTraits<SelectConstantExpr> : FixedNumOperandTraits<3> {
695 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
698 struct OperandTraits<ExtractElementConstantExpr> : FixedNumOperandTraits<2> {
700 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
703 struct OperandTraits<InsertElementConstantExpr> : FixedNumOperandTraits<3> {
705 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
708 struct OperandTraits<ShuffleVectorConstantExpr> : FixedNumOperandTraits<3> {
710 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
713 struct OperandTraits<ExtractValueConstantExpr> : FixedNumOperandTraits<1> {
715 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractValueConstantExpr, Value)
718 struct OperandTraits<InsertValueConstantExpr> : FixedNumOperandTraits<2> {
720 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueConstantExpr, Value)
723 struct OperandTraits<GetElementPtrConstantExpr> : VariadicOperandTraits<1> {
726 GetElementPtrConstantExpr::GetElementPtrConstantExpr
728 const std::vector<Constant*> &IdxList,
730 : ConstantExpr(DestTy, Instruction::GetElementPtr,
731 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
732 - (IdxList.size()+1),
735 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
736 OperandList[i+1] = IdxList[i];
739 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
743 struct OperandTraits<CompareConstantExpr> : FixedNumOperandTraits<2> {
745 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
748 } // End llvm namespace
751 // Utility function for determining if a ConstantExpr is a CastOp or not. This
752 // can't be inline because we don't want to #include Instruction.h into
754 bool ConstantExpr::isCast() const {
755 return Instruction::isCast(getOpcode());
758 bool ConstantExpr::isCompare() const {
759 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
762 bool ConstantExpr::hasIndices() const {
763 return getOpcode() == Instruction::ExtractValue ||
764 getOpcode() == Instruction::InsertValue;
767 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
768 if (const ExtractValueConstantExpr *EVCE =
769 dyn_cast<ExtractValueConstantExpr>(this))
770 return EVCE->Indices;
772 return cast<InsertValueConstantExpr>(this)->Indices;
775 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
776 return get(Instruction::Add, C1, C2);
778 Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
779 return get(Instruction::FAdd, C1, C2);
781 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
782 return get(Instruction::Sub, C1, C2);
784 Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
785 return get(Instruction::FSub, C1, C2);
787 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
788 return get(Instruction::Mul, C1, C2);
790 Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
791 return get(Instruction::FMul, C1, C2);
793 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
794 return get(Instruction::UDiv, C1, C2);
796 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
797 return get(Instruction::SDiv, C1, C2);
799 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
800 return get(Instruction::FDiv, C1, C2);
802 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
803 return get(Instruction::URem, C1, C2);
805 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
806 return get(Instruction::SRem, C1, C2);
808 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
809 return get(Instruction::FRem, C1, C2);
811 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
812 return get(Instruction::And, C1, C2);
814 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
815 return get(Instruction::Or, C1, C2);
817 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
818 return get(Instruction::Xor, C1, C2);
820 unsigned ConstantExpr::getPredicate() const {
821 assert(getOpcode() == Instruction::FCmp ||
822 getOpcode() == Instruction::ICmp);
823 return ((const CompareConstantExpr*)this)->predicate;
825 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
826 return get(Instruction::Shl, C1, C2);
828 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
829 return get(Instruction::LShr, C1, C2);
831 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
832 return get(Instruction::AShr, C1, C2);
835 /// getWithOperandReplaced - Return a constant expression identical to this
836 /// one, but with the specified operand set to the specified value.
838 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
839 assert(OpNo < getNumOperands() && "Operand num is out of range!");
840 assert(Op->getType() == getOperand(OpNo)->getType() &&
841 "Replacing operand with value of different type!");
842 if (getOperand(OpNo) == Op)
843 return const_cast<ConstantExpr*>(this);
845 Constant *Op0, *Op1, *Op2;
846 switch (getOpcode()) {
847 case Instruction::Trunc:
848 case Instruction::ZExt:
849 case Instruction::SExt:
850 case Instruction::FPTrunc:
851 case Instruction::FPExt:
852 case Instruction::UIToFP:
853 case Instruction::SIToFP:
854 case Instruction::FPToUI:
855 case Instruction::FPToSI:
856 case Instruction::PtrToInt:
857 case Instruction::IntToPtr:
858 case Instruction::BitCast:
859 return ConstantExpr::getCast(getOpcode(), Op, getType());
860 case Instruction::Select:
861 Op0 = (OpNo == 0) ? Op : getOperand(0);
862 Op1 = (OpNo == 1) ? Op : getOperand(1);
863 Op2 = (OpNo == 2) ? Op : getOperand(2);
864 return ConstantExpr::getSelect(Op0, Op1, Op2);
865 case Instruction::InsertElement:
866 Op0 = (OpNo == 0) ? Op : getOperand(0);
867 Op1 = (OpNo == 1) ? Op : getOperand(1);
868 Op2 = (OpNo == 2) ? Op : getOperand(2);
869 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
870 case Instruction::ExtractElement:
871 Op0 = (OpNo == 0) ? Op : getOperand(0);
872 Op1 = (OpNo == 1) ? Op : getOperand(1);
873 return ConstantExpr::getExtractElement(Op0, Op1);
874 case Instruction::ShuffleVector:
875 Op0 = (OpNo == 0) ? Op : getOperand(0);
876 Op1 = (OpNo == 1) ? Op : getOperand(1);
877 Op2 = (OpNo == 2) ? Op : getOperand(2);
878 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
879 case Instruction::GetElementPtr: {
880 SmallVector<Constant*, 8> Ops;
881 Ops.resize(getNumOperands()-1);
882 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
883 Ops[i-1] = getOperand(i);
885 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
887 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
890 assert(getNumOperands() == 2 && "Must be binary operator?");
891 Op0 = (OpNo == 0) ? Op : getOperand(0);
892 Op1 = (OpNo == 1) ? Op : getOperand(1);
893 return ConstantExpr::get(getOpcode(), Op0, Op1);
897 /// getWithOperands - This returns the current constant expression with the
898 /// operands replaced with the specified values. The specified operands must
899 /// match count and type with the existing ones.
900 Constant *ConstantExpr::
901 getWithOperands(Constant* const *Ops, unsigned NumOps) const {
902 assert(NumOps == getNumOperands() && "Operand count mismatch!");
903 bool AnyChange = false;
904 for (unsigned i = 0; i != NumOps; ++i) {
905 assert(Ops[i]->getType() == getOperand(i)->getType() &&
906 "Operand type mismatch!");
907 AnyChange |= Ops[i] != getOperand(i);
909 if (!AnyChange) // No operands changed, return self.
910 return const_cast<ConstantExpr*>(this);
912 switch (getOpcode()) {
913 case Instruction::Trunc:
914 case Instruction::ZExt:
915 case Instruction::SExt:
916 case Instruction::FPTrunc:
917 case Instruction::FPExt:
918 case Instruction::UIToFP:
919 case Instruction::SIToFP:
920 case Instruction::FPToUI:
921 case Instruction::FPToSI:
922 case Instruction::PtrToInt:
923 case Instruction::IntToPtr:
924 case Instruction::BitCast:
925 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
926 case Instruction::Select:
927 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
928 case Instruction::InsertElement:
929 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
930 case Instruction::ExtractElement:
931 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
932 case Instruction::ShuffleVector:
933 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
934 case Instruction::GetElementPtr:
935 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
936 case Instruction::ICmp:
937 case Instruction::FCmp:
938 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
940 assert(getNumOperands() == 2 && "Must be binary operator?");
941 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
946 //===----------------------------------------------------------------------===//
947 // isValueValidForType implementations
949 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
950 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
951 if (Ty == Type::Int1Ty)
952 return Val == 0 || Val == 1;
954 return true; // always true, has to fit in largest type
955 uint64_t Max = (1ll << NumBits) - 1;
959 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
960 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
961 if (Ty == Type::Int1Ty)
962 return Val == 0 || Val == 1 || Val == -1;
964 return true; // always true, has to fit in largest type
965 int64_t Min = -(1ll << (NumBits-1));
966 int64_t Max = (1ll << (NumBits-1)) - 1;
967 return (Val >= Min && Val <= Max);
970 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
971 // convert modifies in place, so make a copy.
972 APFloat Val2 = APFloat(Val);
974 switch (Ty->getTypeID()) {
976 return false; // These can't be represented as floating point!
978 // FIXME rounding mode needs to be more flexible
979 case Type::FloatTyID: {
980 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
982 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
985 case Type::DoubleTyID: {
986 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
987 &Val2.getSemantics() == &APFloat::IEEEdouble)
989 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
992 case Type::X86_FP80TyID:
993 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
994 &Val2.getSemantics() == &APFloat::IEEEdouble ||
995 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
996 case Type::FP128TyID:
997 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
998 &Val2.getSemantics() == &APFloat::IEEEdouble ||
999 &Val2.getSemantics() == &APFloat::IEEEquad;
1000 case Type::PPC_FP128TyID:
1001 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1002 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1003 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
1007 //===----------------------------------------------------------------------===//
1008 // Factory Function Implementation
1011 // The number of operands for each ConstantCreator::create method is
1012 // determined by the ConstantTraits template.
1013 // ConstantCreator - A class that is used to create constants by
1014 // ValueMap*. This class should be partially specialized if there is
1015 // something strange that needs to be done to interface to the ctor for the
1019 template<class ValType>
1020 struct ConstantTraits;
1022 template<typename T, typename Alloc>
1023 struct VISIBILITY_HIDDEN ConstantTraits< std::vector<T, Alloc> > {
1024 static unsigned uses(const std::vector<T, Alloc>& v) {
1029 template<class ConstantClass, class TypeClass, class ValType>
1030 struct VISIBILITY_HIDDEN ConstantCreator {
1031 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
1032 return new(ConstantTraits<ValType>::uses(V)) ConstantClass(Ty, V);
1036 template<class ConstantClass, class TypeClass>
1037 struct VISIBILITY_HIDDEN ConvertConstantType {
1038 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
1039 LLVM_UNREACHABLE("This type cannot be converted!");
1043 template<class ValType, class TypeClass, class ConstantClass,
1044 bool HasLargeKey = false /*true for arrays and structs*/ >
1045 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
1047 typedef std::pair<const Type*, ValType> MapKey;
1048 typedef std::map<MapKey, Constant *> MapTy;
1049 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
1050 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
1052 /// Map - This is the main map from the element descriptor to the Constants.
1053 /// This is the primary way we avoid creating two of the same shape
1057 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
1058 /// from the constants to their element in Map. This is important for
1059 /// removal of constants from the array, which would otherwise have to scan
1060 /// through the map with very large keys.
1061 InverseMapTy InverseMap;
1063 /// AbstractTypeMap - Map for abstract type constants.
1065 AbstractTypeMapTy AbstractTypeMap;
1067 /// ValueMapLock - Mutex for this map.
1068 sys::SmartMutex<true> ValueMapLock;
1071 // NOTE: This function is not locked. It is the caller's responsibility
1072 // to enforce proper synchronization.
1073 typename MapTy::iterator map_end() { return Map.end(); }
1075 /// InsertOrGetItem - Return an iterator for the specified element.
1076 /// If the element exists in the map, the returned iterator points to the
1077 /// entry and Exists=true. If not, the iterator points to the newly
1078 /// inserted entry and returns Exists=false. Newly inserted entries have
1079 /// I->second == 0, and should be filled in.
1080 /// NOTE: This function is not locked. It is the caller's responsibility
1081 // to enforce proper synchronization.
1082 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
1085 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
1086 Exists = !IP.second;
1091 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
1093 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
1094 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
1095 IMI->second->second == CP &&
1096 "InverseMap corrupt!");
1100 typename MapTy::iterator I =
1101 Map.find(MapKey(static_cast<const TypeClass*>(CP->getRawType()),
1103 if (I == Map.end() || I->second != CP) {
1104 // FIXME: This should not use a linear scan. If this gets to be a
1105 // performance problem, someone should look at this.
1106 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
1112 ConstantClass* Create(const TypeClass *Ty, const ValType &V,
1113 typename MapTy::iterator I) {
1114 ConstantClass* Result =
1115 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
1117 assert(Result->getType() == Ty && "Type specified is not correct!");
1118 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
1120 if (HasLargeKey) // Remember the reverse mapping if needed.
1121 InverseMap.insert(std::make_pair(Result, I));
1123 // If the type of the constant is abstract, make sure that an entry
1124 // exists for it in the AbstractTypeMap.
1125 if (Ty->isAbstract()) {
1126 typename AbstractTypeMapTy::iterator TI =
1127 AbstractTypeMap.find(Ty);
1129 if (TI == AbstractTypeMap.end()) {
1130 // Add ourselves to the ATU list of the type.
1131 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
1133 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
1141 /// getOrCreate - Return the specified constant from the map, creating it if
1143 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
1144 sys::SmartScopedLock<true> Lock(ValueMapLock);
1145 MapKey Lookup(Ty, V);
1146 ConstantClass* Result = 0;
1148 typename MapTy::iterator I = Map.find(Lookup);
1149 // Is it in the map?
1151 Result = static_cast<ConstantClass *>(I->second);
1154 // If no preexisting value, create one now...
1155 Result = Create(Ty, V, I);
1161 void remove(ConstantClass *CP) {
1162 sys::SmartScopedLock<true> Lock(ValueMapLock);
1163 typename MapTy::iterator I = FindExistingElement(CP);
1164 assert(I != Map.end() && "Constant not found in constant table!");
1165 assert(I->second == CP && "Didn't find correct element?");
1167 if (HasLargeKey) // Remember the reverse mapping if needed.
1168 InverseMap.erase(CP);
1170 // Now that we found the entry, make sure this isn't the entry that
1171 // the AbstractTypeMap points to.
1172 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
1173 if (Ty->isAbstract()) {
1174 assert(AbstractTypeMap.count(Ty) &&
1175 "Abstract type not in AbstractTypeMap?");
1176 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
1177 if (ATMEntryIt == I) {
1178 // Yes, we are removing the representative entry for this type.
1179 // See if there are any other entries of the same type.
1180 typename MapTy::iterator TmpIt = ATMEntryIt;
1182 // First check the entry before this one...
1183 if (TmpIt != Map.begin()) {
1185 if (TmpIt->first.first != Ty) // Not the same type, move back...
1189 // If we didn't find the same type, try to move forward...
1190 if (TmpIt == ATMEntryIt) {
1192 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
1193 --TmpIt; // No entry afterwards with the same type
1196 // If there is another entry in the map of the same abstract type,
1197 // update the AbstractTypeMap entry now.
1198 if (TmpIt != ATMEntryIt) {
1201 // Otherwise, we are removing the last instance of this type
1202 // from the table. Remove from the ATM, and from user list.
1203 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
1204 AbstractTypeMap.erase(Ty);
1213 /// MoveConstantToNewSlot - If we are about to change C to be the element
1214 /// specified by I, update our internal data structures to reflect this
1216 /// NOTE: This function is not locked. It is the responsibility of the
1217 /// caller to enforce proper synchronization if using this method.
1218 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
1219 // First, remove the old location of the specified constant in the map.
1220 typename MapTy::iterator OldI = FindExistingElement(C);
1221 assert(OldI != Map.end() && "Constant not found in constant table!");
1222 assert(OldI->second == C && "Didn't find correct element?");
1224 // If this constant is the representative element for its abstract type,
1225 // update the AbstractTypeMap so that the representative element is I.
1226 if (C->getType()->isAbstract()) {
1227 typename AbstractTypeMapTy::iterator ATI =
1228 AbstractTypeMap.find(C->getType());
1229 assert(ATI != AbstractTypeMap.end() &&
1230 "Abstract type not in AbstractTypeMap?");
1231 if (ATI->second == OldI)
1235 // Remove the old entry from the map.
1238 // Update the inverse map so that we know that this constant is now
1239 // located at descriptor I.
1241 assert(I->second == C && "Bad inversemap entry!");
1246 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
1247 sys::SmartScopedLock<true> Lock(ValueMapLock);
1248 typename AbstractTypeMapTy::iterator I =
1249 AbstractTypeMap.find(cast<Type>(OldTy));
1251 assert(I != AbstractTypeMap.end() &&
1252 "Abstract type not in AbstractTypeMap?");
1254 // Convert a constant at a time until the last one is gone. The last one
1255 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
1256 // eliminated eventually.
1258 ConvertConstantType<ConstantClass,
1259 TypeClass>::convert(
1260 static_cast<ConstantClass *>(I->second->second),
1261 cast<TypeClass>(NewTy));
1263 I = AbstractTypeMap.find(cast<Type>(OldTy));
1264 } while (I != AbstractTypeMap.end());
1267 // If the type became concrete without being refined to any other existing
1268 // type, we just remove ourselves from the ATU list.
1269 void typeBecameConcrete(const DerivedType *AbsTy) {
1270 AbsTy->removeAbstractTypeUser(this);
1274 DOUT << "Constant.cpp: ValueMap\n";
1281 //---- ConstantAggregateZero::get() implementation...
1284 // ConstantAggregateZero does not take extra "value" argument...
1285 template<class ValType>
1286 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
1287 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
1288 return new ConstantAggregateZero(Ty);
1293 struct ConvertConstantType<ConstantAggregateZero, Type> {
1294 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1295 // Make everyone now use a constant of the new type...
1296 Constant *New = ConstantAggregateZero::get(NewTy);
1297 assert(New != OldC && "Didn't replace constant??");
1298 OldC->uncheckedReplaceAllUsesWith(New);
1299 OldC->destroyConstant(); // This constant is now dead, destroy it.
1304 static ManagedStatic<ValueMap<char, Type,
1305 ConstantAggregateZero> > AggZeroConstants;
1307 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1309 ConstantAggregateZero *ConstantAggregateZero::get(const Type *Ty) {
1310 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
1311 "Cannot create an aggregate zero of non-aggregate type!");
1313 // Implicitly locked.
1314 return AggZeroConstants->getOrCreate(Ty, 0);
1317 /// destroyConstant - Remove the constant from the constant table...
1319 void ConstantAggregateZero::destroyConstant() {
1320 // Implicitly locked.
1321 AggZeroConstants->remove(this);
1322 destroyConstantImpl();
1325 //---- ConstantArray::get() implementation...
1329 struct ConvertConstantType<ConstantArray, ArrayType> {
1330 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1331 // Make everyone now use a constant of the new type...
1332 std::vector<Constant*> C;
1333 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1334 C.push_back(cast<Constant>(OldC->getOperand(i)));
1335 Constant *New = ConstantArray::get(NewTy, C);
1336 assert(New != OldC && "Didn't replace constant??");
1337 OldC->uncheckedReplaceAllUsesWith(New);
1338 OldC->destroyConstant(); // This constant is now dead, destroy it.
1343 static std::vector<Constant*> getValType(ConstantArray *CA) {
1344 std::vector<Constant*> Elements;
1345 Elements.reserve(CA->getNumOperands());
1346 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1347 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1351 typedef ValueMap<std::vector<Constant*>, ArrayType,
1352 ConstantArray, true /*largekey*/> ArrayConstantsTy;
1353 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
1355 Constant *ConstantArray::get(const ArrayType *Ty,
1356 const std::vector<Constant*> &V) {
1357 // If this is an all-zero array, return a ConstantAggregateZero object
1360 if (!C->isNullValue()) {
1361 // Implicitly locked.
1362 return ArrayConstants->getOrCreate(Ty, V);
1364 for (unsigned i = 1, e = V.size(); i != e; ++i)
1366 // Implicitly locked.
1367 return ArrayConstants->getOrCreate(Ty, V);
1371 return ConstantAggregateZero::get(Ty);
1374 /// destroyConstant - Remove the constant from the constant table...
1376 void ConstantArray::destroyConstant() {
1377 // Implicitly locked.
1378 ArrayConstants->remove(this);
1379 destroyConstantImpl();
1382 /// ConstantArray::get(const string&) - Return an array that is initialized to
1383 /// contain the specified string. If length is zero then a null terminator is
1384 /// added to the specified string so that it may be used in a natural way.
1385 /// Otherwise, the length parameter specifies how much of the string to use
1386 /// and it won't be null terminated.
1388 Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
1389 std::vector<Constant*> ElementVals;
1390 for (unsigned i = 0; i < Str.length(); ++i)
1391 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
1393 // Add a null terminator to the string...
1395 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
1398 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
1399 return ConstantArray::get(ATy, ElementVals);
1402 /// isString - This method returns true if the array is an array of i8, and
1403 /// if the elements of the array are all ConstantInt's.
1404 bool ConstantArray::isString() const {
1405 // Check the element type for i8...
1406 if (getType()->getElementType() != Type::Int8Ty)
1408 // Check the elements to make sure they are all integers, not constant
1410 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1411 if (!isa<ConstantInt>(getOperand(i)))
1416 /// isCString - This method returns true if the array is a string (see
1417 /// isString) and it ends in a null byte \\0 and does not contains any other
1418 /// null bytes except its terminator.
1419 bool ConstantArray::isCString() const {
1420 // Check the element type for i8...
1421 if (getType()->getElementType() != Type::Int8Ty)
1424 // Last element must be a null.
1425 if (!getOperand(getNumOperands()-1)->isNullValue())
1427 // Other elements must be non-null integers.
1428 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1429 if (!isa<ConstantInt>(getOperand(i)))
1431 if (getOperand(i)->isNullValue())
1438 /// getAsString - If the sub-element type of this array is i8
1439 /// then this method converts the array to an std::string and returns it.
1440 /// Otherwise, it asserts out.
1442 std::string ConstantArray::getAsString() const {
1443 assert(isString() && "Not a string!");
1445 Result.reserve(getNumOperands());
1446 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1447 Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
1452 //---- ConstantStruct::get() implementation...
1457 struct ConvertConstantType<ConstantStruct, StructType> {
1458 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1459 // Make everyone now use a constant of the new type...
1460 std::vector<Constant*> C;
1461 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1462 C.push_back(cast<Constant>(OldC->getOperand(i)));
1463 Constant *New = ConstantStruct::get(NewTy, C);
1464 assert(New != OldC && "Didn't replace constant??");
1466 OldC->uncheckedReplaceAllUsesWith(New);
1467 OldC->destroyConstant(); // This constant is now dead, destroy it.
1472 typedef ValueMap<std::vector<Constant*>, StructType,
1473 ConstantStruct, true /*largekey*/> StructConstantsTy;
1474 static ManagedStatic<StructConstantsTy> StructConstants;
1476 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1477 std::vector<Constant*> Elements;
1478 Elements.reserve(CS->getNumOperands());
1479 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1480 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1484 Constant *ConstantStruct::get(const StructType *Ty,
1485 const std::vector<Constant*> &V) {
1486 // Create a ConstantAggregateZero value if all elements are zeros...
1487 for (unsigned i = 0, e = V.size(); i != e; ++i)
1488 if (!V[i]->isNullValue())
1489 // Implicitly locked.
1490 return StructConstants->getOrCreate(Ty, V);
1492 return ConstantAggregateZero::get(Ty);
1495 Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
1496 std::vector<const Type*> StructEls;
1497 StructEls.reserve(V.size());
1498 for (unsigned i = 0, e = V.size(); i != e; ++i)
1499 StructEls.push_back(V[i]->getType());
1500 return get(StructType::get(StructEls, packed), V);
1503 // destroyConstant - Remove the constant from the constant table...
1505 void ConstantStruct::destroyConstant() {
1506 // Implicitly locked.
1507 StructConstants->remove(this);
1508 destroyConstantImpl();
1511 //---- ConstantVector::get() implementation...
1515 struct ConvertConstantType<ConstantVector, VectorType> {
1516 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
1517 // Make everyone now use a constant of the new type...
1518 std::vector<Constant*> C;
1519 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1520 C.push_back(cast<Constant>(OldC->getOperand(i)));
1521 Constant *New = ConstantVector::get(NewTy, C);
1522 assert(New != OldC && "Didn't replace constant??");
1523 OldC->uncheckedReplaceAllUsesWith(New);
1524 OldC->destroyConstant(); // This constant is now dead, destroy it.
1529 static std::vector<Constant*> getValType(ConstantVector *CP) {
1530 std::vector<Constant*> Elements;
1531 Elements.reserve(CP->getNumOperands());
1532 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1533 Elements.push_back(CP->getOperand(i));
1537 static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
1538 ConstantVector> > VectorConstants;
1540 Constant *ConstantVector::get(const VectorType *Ty,
1541 const std::vector<Constant*> &V) {
1542 assert(!V.empty() && "Vectors can't be empty");
1543 // If this is an all-undef or alll-zero vector, return a
1544 // ConstantAggregateZero or UndefValue.
1546 bool isZero = C->isNullValue();
1547 bool isUndef = isa<UndefValue>(C);
1549 if (isZero || isUndef) {
1550 for (unsigned i = 1, e = V.size(); i != e; ++i)
1552 isZero = isUndef = false;
1558 return ConstantAggregateZero::get(Ty);
1560 return UndefValue::get(Ty);
1562 // Implicitly locked.
1563 return VectorConstants->getOrCreate(Ty, V);
1566 Constant *ConstantVector::get(const std::vector<Constant*> &V) {
1567 assert(!V.empty() && "Cannot infer type if V is empty");
1568 return get(VectorType::get(V.front()->getType(),V.size()), V);
1571 // destroyConstant - Remove the constant from the constant table...
1573 void ConstantVector::destroyConstant() {
1574 // Implicitly locked.
1575 VectorConstants->remove(this);
1576 destroyConstantImpl();
1579 /// This function will return true iff every element in this vector constant
1580 /// is set to all ones.
1581 /// @returns true iff this constant's emements are all set to all ones.
1582 /// @brief Determine if the value is all ones.
1583 bool ConstantVector::isAllOnesValue() const {
1584 // Check out first element.
1585 const Constant *Elt = getOperand(0);
1586 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1587 if (!CI || !CI->isAllOnesValue()) return false;
1588 // Then make sure all remaining elements point to the same value.
1589 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1590 if (getOperand(I) != Elt) return false;
1595 /// getSplatValue - If this is a splat constant, where all of the
1596 /// elements have the same value, return that value. Otherwise return null.
1597 Constant *ConstantVector::getSplatValue() {
1598 // Check out first element.
1599 Constant *Elt = getOperand(0);
1600 // Then make sure all remaining elements point to the same value.
1601 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1602 if (getOperand(I) != Elt) return 0;
1606 //---- ConstantPointerNull::get() implementation...
1610 // ConstantPointerNull does not take extra "value" argument...
1611 template<class ValType>
1612 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1613 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1614 return new ConstantPointerNull(Ty);
1619 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1620 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1621 // Make everyone now use a constant of the new type...
1622 Constant *New = ConstantPointerNull::get(NewTy);
1623 assert(New != OldC && "Didn't replace constant??");
1624 OldC->uncheckedReplaceAllUsesWith(New);
1625 OldC->destroyConstant(); // This constant is now dead, destroy it.
1630 static ManagedStatic<ValueMap<char, PointerType,
1631 ConstantPointerNull> > NullPtrConstants;
1633 static char getValType(ConstantPointerNull *) {
1638 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1639 // Implicitly locked.
1640 return NullPtrConstants->getOrCreate(Ty, 0);
1643 // destroyConstant - Remove the constant from the constant table...
1645 void ConstantPointerNull::destroyConstant() {
1646 // Implicitly locked.
1647 NullPtrConstants->remove(this);
1648 destroyConstantImpl();
1652 //---- UndefValue::get() implementation...
1656 // UndefValue does not take extra "value" argument...
1657 template<class ValType>
1658 struct ConstantCreator<UndefValue, Type, ValType> {
1659 static UndefValue *create(const Type *Ty, const ValType &V) {
1660 return new UndefValue(Ty);
1665 struct ConvertConstantType<UndefValue, Type> {
1666 static void convert(UndefValue *OldC, const Type *NewTy) {
1667 // Make everyone now use a constant of the new type.
1668 Constant *New = UndefValue::get(NewTy);
1669 assert(New != OldC && "Didn't replace constant??");
1670 OldC->uncheckedReplaceAllUsesWith(New);
1671 OldC->destroyConstant(); // This constant is now dead, destroy it.
1676 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1678 static char getValType(UndefValue *) {
1683 UndefValue *UndefValue::get(const Type *Ty) {
1684 // Implicitly locked.
1685 return UndefValueConstants->getOrCreate(Ty, 0);
1688 // destroyConstant - Remove the constant from the constant table.
1690 void UndefValue::destroyConstant() {
1691 // Implicitly locked.
1692 UndefValueConstants->remove(this);
1693 destroyConstantImpl();
1696 //---- MDString::get() implementation
1699 MDString::MDString(const char *begin, const char *end)
1700 : Constant(Type::MetadataTy, MDStringVal, 0, 0),
1701 StrBegin(begin), StrEnd(end) {}
1703 static ManagedStatic<StringMap<MDString*> > MDStringCache;
1705 MDString *MDString::get(const char *StrBegin, const char *StrEnd) {
1706 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
1707 StringMapEntry<MDString *> &Entry = MDStringCache->GetOrCreateValue(
1709 MDString *&S = Entry.getValue();
1710 if (!S) S = new MDString(Entry.getKeyData(),
1711 Entry.getKeyData() + Entry.getKeyLength());
1716 MDString *MDString::get(const std::string &Str) {
1717 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
1718 StringMapEntry<MDString *> &Entry = MDStringCache->GetOrCreateValue(
1719 Str.data(), Str.data() + Str.size());
1720 MDString *&S = Entry.getValue();
1721 if (!S) S = new MDString(Entry.getKeyData(),
1722 Entry.getKeyData() + Entry.getKeyLength());
1727 void MDString::destroyConstant() {
1728 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
1729 MDStringCache->erase(MDStringCache->find(StrBegin, StrEnd));
1730 destroyConstantImpl();
1733 //---- MDNode::get() implementation
1736 static ManagedStatic<FoldingSet<MDNode> > MDNodeSet;
1738 MDNode::MDNode(Value*const* Vals, unsigned NumVals)
1739 : Constant(Type::MetadataTy, MDNodeVal, 0, 0) {
1740 for (unsigned i = 0; i != NumVals; ++i)
1741 Node.push_back(ElementVH(Vals[i], this));
1744 void MDNode::Profile(FoldingSetNodeID &ID) const {
1745 for (const_elem_iterator I = elem_begin(), E = elem_end(); I != E; ++I)
1749 MDNode *MDNode::get(Value*const* Vals, unsigned NumVals) {
1750 FoldingSetNodeID ID;
1751 for (unsigned i = 0; i != NumVals; ++i)
1752 ID.AddPointer(Vals[i]);
1754 ConstantsLock->reader_acquire();
1756 MDNode *N = MDNodeSet->FindNodeOrInsertPos(ID, InsertPoint);
1757 ConstantsLock->reader_release();
1760 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
1761 N = MDNodeSet->FindNodeOrInsertPos(ID, InsertPoint);
1763 // InsertPoint will have been set by the FindNodeOrInsertPos call.
1764 N = new(0) MDNode(Vals, NumVals);
1765 MDNodeSet->InsertNode(N, InsertPoint);
1771 void MDNode::destroyConstant() {
1772 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
1773 MDNodeSet->RemoveNode(this);
1775 destroyConstantImpl();
1778 //---- ConstantExpr::get() implementations...
1783 struct ExprMapKeyType {
1784 typedef SmallVector<unsigned, 4> IndexList;
1786 ExprMapKeyType(unsigned opc,
1787 const std::vector<Constant*> &ops,
1788 unsigned short pred = 0,
1789 const IndexList &inds = IndexList())
1790 : opcode(opc), predicate(pred), operands(ops), indices(inds) {}
1793 std::vector<Constant*> operands;
1795 bool operator==(const ExprMapKeyType& that) const {
1796 return this->opcode == that.opcode &&
1797 this->predicate == that.predicate &&
1798 this->operands == that.operands &&
1799 this->indices == that.indices;
1801 bool operator<(const ExprMapKeyType & that) const {
1802 return this->opcode < that.opcode ||
1803 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1804 (this->opcode == that.opcode && this->predicate == that.predicate &&
1805 this->operands < that.operands) ||
1806 (this->opcode == that.opcode && this->predicate == that.predicate &&
1807 this->operands == that.operands && this->indices < that.indices);
1810 bool operator!=(const ExprMapKeyType& that) const {
1811 return !(*this == that);
1819 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1820 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1821 unsigned short pred = 0) {
1822 if (Instruction::isCast(V.opcode))
1823 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1824 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1825 V.opcode < Instruction::BinaryOpsEnd))
1826 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1827 if (V.opcode == Instruction::Select)
1828 return new SelectConstantExpr(V.operands[0], V.operands[1],
1830 if (V.opcode == Instruction::ExtractElement)
1831 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1832 if (V.opcode == Instruction::InsertElement)
1833 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1835 if (V.opcode == Instruction::ShuffleVector)
1836 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1838 if (V.opcode == Instruction::InsertValue)
1839 return new InsertValueConstantExpr(V.operands[0], V.operands[1],
1841 if (V.opcode == Instruction::ExtractValue)
1842 return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
1843 if (V.opcode == Instruction::GetElementPtr) {
1844 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1845 return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
1848 // The compare instructions are weird. We have to encode the predicate
1849 // value and it is combined with the instruction opcode by multiplying
1850 // the opcode by one hundred. We must decode this to get the predicate.
1851 if (V.opcode == Instruction::ICmp)
1852 return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate,
1853 V.operands[0], V.operands[1]);
1854 if (V.opcode == Instruction::FCmp)
1855 return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate,
1856 V.operands[0], V.operands[1]);
1857 LLVM_UNREACHABLE("Invalid ConstantExpr!");
1863 struct ConvertConstantType<ConstantExpr, Type> {
1864 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1866 switch (OldC->getOpcode()) {
1867 case Instruction::Trunc:
1868 case Instruction::ZExt:
1869 case Instruction::SExt:
1870 case Instruction::FPTrunc:
1871 case Instruction::FPExt:
1872 case Instruction::UIToFP:
1873 case Instruction::SIToFP:
1874 case Instruction::FPToUI:
1875 case Instruction::FPToSI:
1876 case Instruction::PtrToInt:
1877 case Instruction::IntToPtr:
1878 case Instruction::BitCast:
1879 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1882 case Instruction::Select:
1883 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1884 OldC->getOperand(1),
1885 OldC->getOperand(2));
1888 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1889 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1890 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1891 OldC->getOperand(1));
1893 case Instruction::GetElementPtr:
1894 // Make everyone now use a constant of the new type...
1895 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1896 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1897 &Idx[0], Idx.size());
1901 assert(New != OldC && "Didn't replace constant??");
1902 OldC->uncheckedReplaceAllUsesWith(New);
1903 OldC->destroyConstant(); // This constant is now dead, destroy it.
1906 } // end namespace llvm
1909 static ExprMapKeyType getValType(ConstantExpr *CE) {
1910 std::vector<Constant*> Operands;
1911 Operands.reserve(CE->getNumOperands());
1912 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1913 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1914 return ExprMapKeyType(CE->getOpcode(), Operands,
1915 CE->isCompare() ? CE->getPredicate() : 0,
1917 CE->getIndices() : SmallVector<unsigned, 4>());
1920 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1921 ConstantExpr> > ExprConstants;
1923 /// This is a utility function to handle folding of casts and lookup of the
1924 /// cast in the ExprConstants map. It is used by the various get* methods below.
1925 static inline Constant *getFoldedCast(
1926 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1927 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1928 // Fold a few common cases
1930 ConstantFoldCastInstruction(getGlobalContext(), opc, C, Ty))
1933 // Look up the constant in the table first to ensure uniqueness
1934 std::vector<Constant*> argVec(1, C);
1935 ExprMapKeyType Key(opc, argVec);
1937 // Implicitly locked.
1938 return ExprConstants->getOrCreate(Ty, Key);
1941 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1942 Instruction::CastOps opc = Instruction::CastOps(oc);
1943 assert(Instruction::isCast(opc) && "opcode out of range");
1944 assert(C && Ty && "Null arguments to getCast");
1945 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1949 LLVM_UNREACHABLE("Invalid cast opcode");
1951 case Instruction::Trunc: return getTrunc(C, Ty);
1952 case Instruction::ZExt: return getZExt(C, Ty);
1953 case Instruction::SExt: return getSExt(C, Ty);
1954 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1955 case Instruction::FPExt: return getFPExtend(C, Ty);
1956 case Instruction::UIToFP: return getUIToFP(C, Ty);
1957 case Instruction::SIToFP: return getSIToFP(C, Ty);
1958 case Instruction::FPToUI: return getFPToUI(C, Ty);
1959 case Instruction::FPToSI: return getFPToSI(C, Ty);
1960 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1961 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1962 case Instruction::BitCast: return getBitCast(C, Ty);
1967 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1968 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1969 return getCast(Instruction::BitCast, C, Ty);
1970 return getCast(Instruction::ZExt, C, Ty);
1973 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1974 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1975 return getCast(Instruction::BitCast, C, Ty);
1976 return getCast(Instruction::SExt, C, Ty);
1979 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1980 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1981 return getCast(Instruction::BitCast, C, Ty);
1982 return getCast(Instruction::Trunc, C, Ty);
1985 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1986 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1987 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1989 if (Ty->isInteger())
1990 return getCast(Instruction::PtrToInt, S, Ty);
1991 return getCast(Instruction::BitCast, S, Ty);
1994 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1996 assert(C->getType()->isIntOrIntVector() &&
1997 Ty->isIntOrIntVector() && "Invalid cast");
1998 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1999 unsigned DstBits = Ty->getScalarSizeInBits();
2000 Instruction::CastOps opcode =
2001 (SrcBits == DstBits ? Instruction::BitCast :
2002 (SrcBits > DstBits ? Instruction::Trunc :
2003 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2004 return getCast(opcode, C, Ty);
2007 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
2008 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2010 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2011 unsigned DstBits = Ty->getScalarSizeInBits();
2012 if (SrcBits == DstBits)
2013 return C; // Avoid a useless cast
2014 Instruction::CastOps opcode =
2015 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
2016 return getCast(opcode, C, Ty);
2019 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
2021 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2022 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2024 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2025 assert(C->getType()->isIntOrIntVector() && "Trunc operand must be integer");
2026 assert(Ty->isIntOrIntVector() && "Trunc produces only integral");
2027 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
2028 "SrcTy must be larger than DestTy for Trunc!");
2030 return getFoldedCast(Instruction::Trunc, C, Ty);
2033 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
2035 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2036 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2038 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2039 assert(C->getType()->isIntOrIntVector() && "SExt operand must be integral");
2040 assert(Ty->isIntOrIntVector() && "SExt produces only integer");
2041 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
2042 "SrcTy must be smaller than DestTy for SExt!");
2044 return getFoldedCast(Instruction::SExt, C, Ty);
2047 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
2049 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2050 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2052 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2053 assert(C->getType()->isIntOrIntVector() && "ZEXt operand must be integral");
2054 assert(Ty->isIntOrIntVector() && "ZExt produces only integer");
2055 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
2056 "SrcTy must be smaller than DestTy for ZExt!");
2058 return getFoldedCast(Instruction::ZExt, C, Ty);
2061 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
2063 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2064 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2066 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2067 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2068 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
2069 "This is an illegal floating point truncation!");
2070 return getFoldedCast(Instruction::FPTrunc, C, Ty);
2073 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
2075 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2076 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2078 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2079 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2080 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
2081 "This is an illegal floating point extension!");
2082 return getFoldedCast(Instruction::FPExt, C, Ty);
2085 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
2087 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2088 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2090 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2091 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
2092 "This is an illegal uint to floating point cast!");
2093 return getFoldedCast(Instruction::UIToFP, C, Ty);
2096 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
2098 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2099 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2101 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2102 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
2103 "This is an illegal sint to floating point cast!");
2104 return getFoldedCast(Instruction::SIToFP, C, Ty);
2107 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
2109 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2110 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2112 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2113 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
2114 "This is an illegal floating point to uint cast!");
2115 return getFoldedCast(Instruction::FPToUI, C, Ty);
2118 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
2120 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2121 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2123 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2124 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
2125 "This is an illegal floating point to sint cast!");
2126 return getFoldedCast(Instruction::FPToSI, C, Ty);
2129 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
2130 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
2131 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
2132 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
2135 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
2136 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
2137 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
2138 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
2141 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
2142 // BitCast implies a no-op cast of type only. No bits change. However, you
2143 // can't cast pointers to anything but pointers.
2145 const Type *SrcTy = C->getType();
2146 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
2147 "BitCast cannot cast pointer to non-pointer and vice versa");
2149 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
2150 // or nonptr->ptr). For all the other types, the cast is okay if source and
2151 // destination bit widths are identical.
2152 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
2153 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
2155 assert(SrcBitSize == DstBitSize && "BitCast requires types of same width");
2157 // It is common to ask for a bitcast of a value to its own type, handle this
2159 if (C->getType() == DstTy) return C;
2161 return getFoldedCast(Instruction::BitCast, C, DstTy);
2164 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
2165 Constant *C1, Constant *C2) {
2166 // Check the operands for consistency first
2167 assert(Opcode >= Instruction::BinaryOpsBegin &&
2168 Opcode < Instruction::BinaryOpsEnd &&
2169 "Invalid opcode in binary constant expression");
2170 assert(C1->getType() == C2->getType() &&
2171 "Operand types in binary constant expression should match");
2173 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
2174 if (Constant *FC = ConstantFoldBinaryInstruction(
2175 getGlobalContext(), Opcode, C1, C2))
2176 return FC; // Fold a few common cases...
2178 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
2179 ExprMapKeyType Key(Opcode, argVec);
2181 // Implicitly locked.
2182 return ExprConstants->getOrCreate(ReqTy, Key);
2185 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
2186 Constant *C1, Constant *C2) {
2187 switch (predicate) {
2188 default: LLVM_UNREACHABLE("Invalid CmpInst predicate");
2189 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
2190 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
2191 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
2192 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
2193 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
2194 case CmpInst::FCMP_TRUE:
2195 return getFCmp(predicate, C1, C2);
2197 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
2198 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
2199 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
2200 case CmpInst::ICMP_SLE:
2201 return getICmp(predicate, C1, C2);
2205 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
2206 // API compatibility: Adjust integer opcodes to floating-point opcodes.
2207 if (C1->getType()->isFPOrFPVector()) {
2208 if (Opcode == Instruction::Add) Opcode = Instruction::FAdd;
2209 else if (Opcode == Instruction::Sub) Opcode = Instruction::FSub;
2210 else if (Opcode == Instruction::Mul) Opcode = Instruction::FMul;
2214 case Instruction::Add:
2215 case Instruction::Sub:
2216 case Instruction::Mul:
2217 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2218 assert(C1->getType()->isIntOrIntVector() &&
2219 "Tried to create an integer operation on a non-integer type!");
2221 case Instruction::FAdd:
2222 case Instruction::FSub:
2223 case Instruction::FMul:
2224 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2225 assert(C1->getType()->isFPOrFPVector() &&
2226 "Tried to create a floating-point operation on a "
2227 "non-floating-point type!");
2229 case Instruction::UDiv:
2230 case Instruction::SDiv:
2231 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2232 assert(C1->getType()->isIntOrIntVector() &&
2233 "Tried to create an arithmetic operation on a non-arithmetic type!");
2235 case Instruction::FDiv:
2236 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2237 assert(C1->getType()->isFPOrFPVector() &&
2238 "Tried to create an arithmetic operation on a non-arithmetic type!");
2240 case Instruction::URem:
2241 case Instruction::SRem:
2242 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2243 assert(C1->getType()->isIntOrIntVector() &&
2244 "Tried to create an arithmetic operation on a non-arithmetic type!");
2246 case Instruction::FRem:
2247 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2248 assert(C1->getType()->isFPOrFPVector() &&
2249 "Tried to create an arithmetic operation on a non-arithmetic type!");
2251 case Instruction::And:
2252 case Instruction::Or:
2253 case Instruction::Xor:
2254 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2255 assert(C1->getType()->isIntOrIntVector() &&
2256 "Tried to create a logical operation on a non-integral type!");
2258 case Instruction::Shl:
2259 case Instruction::LShr:
2260 case Instruction::AShr:
2261 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2262 assert(C1->getType()->isIntOrIntVector() &&
2263 "Tried to create a shift operation on a non-integer type!");
2270 return getTy(C1->getType(), Opcode, C1, C2);
2273 Constant *ConstantExpr::getCompare(unsigned short pred,
2274 Constant *C1, Constant *C2) {
2275 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2276 return getCompareTy(pred, C1, C2);
2279 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
2280 Constant *V1, Constant *V2) {
2281 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
2283 if (ReqTy == V1->getType())
2284 if (Constant *SC = ConstantFoldSelectInstruction(
2285 getGlobalContext(), C, V1, V2))
2286 return SC; // Fold common cases
2288 std::vector<Constant*> argVec(3, C);
2291 ExprMapKeyType Key(Instruction::Select, argVec);
2293 // Implicitly locked.
2294 return ExprConstants->getOrCreate(ReqTy, Key);
2297 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
2300 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
2302 cast<PointerType>(ReqTy)->getElementType() &&
2303 "GEP indices invalid!");
2305 if (Constant *FC = ConstantFoldGetElementPtr(
2306 getGlobalContext(), C, (Constant**)Idxs, NumIdx))
2307 return FC; // Fold a few common cases...
2309 assert(isa<PointerType>(C->getType()) &&
2310 "Non-pointer type for constant GetElementPtr expression");
2311 // Look up the constant in the table first to ensure uniqueness
2312 std::vector<Constant*> ArgVec;
2313 ArgVec.reserve(NumIdx+1);
2314 ArgVec.push_back(C);
2315 for (unsigned i = 0; i != NumIdx; ++i)
2316 ArgVec.push_back(cast<Constant>(Idxs[i]));
2317 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
2319 // Implicitly locked.
2320 return ExprConstants->getOrCreate(ReqTy, Key);
2323 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
2325 // Get the result type of the getelementptr!
2327 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
2328 assert(Ty && "GEP indices invalid!");
2329 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
2330 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
2333 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
2335 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
2340 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2341 assert(LHS->getType() == RHS->getType());
2342 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2343 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
2345 if (Constant *FC = ConstantFoldCompareInstruction(
2346 getGlobalContext(),pred, LHS, RHS))
2347 return FC; // Fold a few common cases...
2349 // Look up the constant in the table first to ensure uniqueness
2350 std::vector<Constant*> ArgVec;
2351 ArgVec.push_back(LHS);
2352 ArgVec.push_back(RHS);
2353 // Get the key type with both the opcode and predicate
2354 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
2356 // Implicitly locked.
2357 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2361 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2362 assert(LHS->getType() == RHS->getType());
2363 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
2365 if (Constant *FC = ConstantFoldCompareInstruction(
2366 getGlobalContext(), pred, LHS, RHS))
2367 return FC; // Fold a few common cases...
2369 // Look up the constant in the table first to ensure uniqueness
2370 std::vector<Constant*> ArgVec;
2371 ArgVec.push_back(LHS);
2372 ArgVec.push_back(RHS);
2373 // Get the key type with both the opcode and predicate
2374 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
2376 // Implicitly locked.
2377 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2380 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
2382 if (Constant *FC = ConstantFoldExtractElementInstruction(
2383 getGlobalContext(), Val, Idx))
2384 return FC; // Fold a few common cases...
2385 // Look up the constant in the table first to ensure uniqueness
2386 std::vector<Constant*> ArgVec(1, Val);
2387 ArgVec.push_back(Idx);
2388 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
2390 // Implicitly locked.
2391 return ExprConstants->getOrCreate(ReqTy, Key);
2394 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
2395 assert(isa<VectorType>(Val->getType()) &&
2396 "Tried to create extractelement operation on non-vector type!");
2397 assert(Idx->getType() == Type::Int32Ty &&
2398 "Extractelement index must be i32 type!");
2399 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
2403 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
2404 Constant *Elt, Constant *Idx) {
2405 if (Constant *FC = ConstantFoldInsertElementInstruction(
2406 getGlobalContext(), Val, Elt, Idx))
2407 return FC; // Fold a few common cases...
2408 // Look up the constant in the table first to ensure uniqueness
2409 std::vector<Constant*> ArgVec(1, Val);
2410 ArgVec.push_back(Elt);
2411 ArgVec.push_back(Idx);
2412 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
2414 // Implicitly locked.
2415 return ExprConstants->getOrCreate(ReqTy, Key);
2418 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2420 assert(isa<VectorType>(Val->getType()) &&
2421 "Tried to create insertelement operation on non-vector type!");
2422 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
2423 && "Insertelement types must match!");
2424 assert(Idx->getType() == Type::Int32Ty &&
2425 "Insertelement index must be i32 type!");
2426 return getInsertElementTy(Val->getType(), Val, Elt, Idx);
2429 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
2430 Constant *V2, Constant *Mask) {
2431 if (Constant *FC = ConstantFoldShuffleVectorInstruction(
2432 getGlobalContext(), V1, V2, Mask))
2433 return FC; // Fold a few common cases...
2434 // Look up the constant in the table first to ensure uniqueness
2435 std::vector<Constant*> ArgVec(1, V1);
2436 ArgVec.push_back(V2);
2437 ArgVec.push_back(Mask);
2438 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
2440 // Implicitly locked.
2441 return ExprConstants->getOrCreate(ReqTy, Key);
2444 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2446 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2447 "Invalid shuffle vector constant expr operands!");
2449 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
2450 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
2451 const Type *ShufTy = VectorType::get(EltTy, NElts);
2452 return getShuffleVectorTy(ShufTy, V1, V2, Mask);
2455 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
2457 const unsigned *Idxs, unsigned NumIdx) {
2458 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2459 Idxs+NumIdx) == Val->getType() &&
2460 "insertvalue indices invalid!");
2461 assert(Agg->getType() == ReqTy &&
2462 "insertvalue type invalid!");
2463 assert(Agg->getType()->isFirstClassType() &&
2464 "Non-first-class type for constant InsertValue expression");
2465 Constant *FC = ConstantFoldInsertValueInstruction(
2466 getGlobalContext(), Agg, Val, Idxs, NumIdx);
2467 assert(FC && "InsertValue constant expr couldn't be folded!");
2471 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
2472 const unsigned *IdxList, unsigned NumIdx) {
2473 assert(Agg->getType()->isFirstClassType() &&
2474 "Tried to create insertelement operation on non-first-class type!");
2476 const Type *ReqTy = Agg->getType();
2479 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2481 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
2482 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
2485 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
2486 const unsigned *Idxs, unsigned NumIdx) {
2487 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2488 Idxs+NumIdx) == ReqTy &&
2489 "extractvalue indices invalid!");
2490 assert(Agg->getType()->isFirstClassType() &&
2491 "Non-first-class type for constant extractvalue expression");
2492 Constant *FC = ConstantFoldExtractValueInstruction(
2493 getGlobalContext(), Agg, Idxs, NumIdx);
2494 assert(FC && "ExtractValue constant expr couldn't be folded!");
2498 Constant *ConstantExpr::getExtractValue(Constant *Agg,
2499 const unsigned *IdxList, unsigned NumIdx) {
2500 assert(Agg->getType()->isFirstClassType() &&
2501 "Tried to create extractelement operation on non-first-class type!");
2504 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2505 assert(ReqTy && "extractvalue indices invalid!");
2506 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
2509 // destroyConstant - Remove the constant from the constant table...
2511 void ConstantExpr::destroyConstant() {
2512 // Implicitly locked.
2513 ExprConstants->remove(this);
2514 destroyConstantImpl();
2517 const char *ConstantExpr::getOpcodeName() const {
2518 return Instruction::getOpcodeName(getOpcode());
2521 //===----------------------------------------------------------------------===//
2522 // replaceUsesOfWithOnConstant implementations
2524 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2525 /// 'From' to be uses of 'To'. This must update the uniquing data structures
2528 /// Note that we intentionally replace all uses of From with To here. Consider
2529 /// a large array that uses 'From' 1000 times. By handling this case all here,
2530 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2531 /// single invocation handles all 1000 uses. Handling them one at a time would
2532 /// work, but would be really slow because it would have to unique each updated
2534 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
2536 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2537 Constant *ToC = cast<Constant>(To);
2539 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
2540 Lookup.first.first = getType();
2541 Lookup.second = this;
2543 std::vector<Constant*> &Values = Lookup.first.second;
2544 Values.reserve(getNumOperands()); // Build replacement array.
2546 // Fill values with the modified operands of the constant array. Also,
2547 // compute whether this turns into an all-zeros array.
2548 bool isAllZeros = false;
2549 unsigned NumUpdated = 0;
2550 if (!ToC->isNullValue()) {
2551 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2552 Constant *Val = cast<Constant>(O->get());
2557 Values.push_back(Val);
2561 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2562 Constant *Val = cast<Constant>(O->get());
2567 Values.push_back(Val);
2568 if (isAllZeros) isAllZeros = Val->isNullValue();
2572 Constant *Replacement = 0;
2574 Replacement = ConstantAggregateZero::get(getType());
2576 // Check to see if we have this array type already.
2577 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
2579 ArrayConstantsTy::MapTy::iterator I =
2580 ArrayConstants->InsertOrGetItem(Lookup, Exists);
2583 Replacement = I->second;
2585 // Okay, the new shape doesn't exist in the system yet. Instead of
2586 // creating a new constant array, inserting it, replaceallusesof'ing the
2587 // old with the new, then deleting the old... just update the current one
2589 ArrayConstants->MoveConstantToNewSlot(this, I);
2591 // Update to the new value. Optimize for the case when we have a single
2592 // operand that we're changing, but handle bulk updates efficiently.
2593 if (NumUpdated == 1) {
2594 unsigned OperandToUpdate = U-OperandList;
2595 assert(getOperand(OperandToUpdate) == From &&
2596 "ReplaceAllUsesWith broken!");
2597 setOperand(OperandToUpdate, ToC);
2599 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2600 if (getOperand(i) == From)
2607 // Otherwise, I do need to replace this with an existing value.
2608 assert(Replacement != this && "I didn't contain From!");
2610 // Everyone using this now uses the replacement.
2611 uncheckedReplaceAllUsesWith(Replacement);
2613 // Delete the old constant!
2617 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2619 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2620 Constant *ToC = cast<Constant>(To);
2622 unsigned OperandToUpdate = U-OperandList;
2623 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2625 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
2626 Lookup.first.first = getType();
2627 Lookup.second = this;
2628 std::vector<Constant*> &Values = Lookup.first.second;
2629 Values.reserve(getNumOperands()); // Build replacement struct.
2632 // Fill values with the modified operands of the constant struct. Also,
2633 // compute whether this turns into an all-zeros struct.
2634 bool isAllZeros = false;
2635 if (!ToC->isNullValue()) {
2636 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2637 Values.push_back(cast<Constant>(O->get()));
2640 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2641 Constant *Val = cast<Constant>(O->get());
2642 Values.push_back(Val);
2643 if (isAllZeros) isAllZeros = Val->isNullValue();
2646 Values[OperandToUpdate] = ToC;
2648 Constant *Replacement = 0;
2650 Replacement = ConstantAggregateZero::get(getType());
2652 // Check to see if we have this array type already.
2653 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
2655 StructConstantsTy::MapTy::iterator I =
2656 StructConstants->InsertOrGetItem(Lookup, Exists);
2659 Replacement = I->second;
2661 // Okay, the new shape doesn't exist in the system yet. Instead of
2662 // creating a new constant struct, inserting it, replaceallusesof'ing the
2663 // old with the new, then deleting the old... just update the current one
2665 StructConstants->MoveConstantToNewSlot(this, I);
2667 // Update to the new value.
2668 setOperand(OperandToUpdate, ToC);
2673 assert(Replacement != this && "I didn't contain From!");
2675 // Everyone using this now uses the replacement.
2676 uncheckedReplaceAllUsesWith(Replacement);
2678 // Delete the old constant!
2682 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2684 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2686 std::vector<Constant*> Values;
2687 Values.reserve(getNumOperands()); // Build replacement array...
2688 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2689 Constant *Val = getOperand(i);
2690 if (Val == From) Val = cast<Constant>(To);
2691 Values.push_back(Val);
2694 Constant *Replacement = ConstantVector::get(getType(), Values);
2695 assert(Replacement != this && "I didn't contain From!");
2697 // Everyone using this now uses the replacement.
2698 uncheckedReplaceAllUsesWith(Replacement);
2700 // Delete the old constant!
2704 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2706 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2707 Constant *To = cast<Constant>(ToV);
2709 Constant *Replacement = 0;
2710 if (getOpcode() == Instruction::GetElementPtr) {
2711 SmallVector<Constant*, 8> Indices;
2712 Constant *Pointer = getOperand(0);
2713 Indices.reserve(getNumOperands()-1);
2714 if (Pointer == From) Pointer = To;
2716 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2717 Constant *Val = getOperand(i);
2718 if (Val == From) Val = To;
2719 Indices.push_back(Val);
2721 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2722 &Indices[0], Indices.size());
2723 } else if (getOpcode() == Instruction::ExtractValue) {
2724 Constant *Agg = getOperand(0);
2725 if (Agg == From) Agg = To;
2727 const SmallVector<unsigned, 4> &Indices = getIndices();
2728 Replacement = ConstantExpr::getExtractValue(Agg,
2729 &Indices[0], Indices.size());
2730 } else if (getOpcode() == Instruction::InsertValue) {
2731 Constant *Agg = getOperand(0);
2732 Constant *Val = getOperand(1);
2733 if (Agg == From) Agg = To;
2734 if (Val == From) Val = To;
2736 const SmallVector<unsigned, 4> &Indices = getIndices();
2737 Replacement = ConstantExpr::getInsertValue(Agg, Val,
2738 &Indices[0], Indices.size());
2739 } else if (isCast()) {
2740 assert(getOperand(0) == From && "Cast only has one use!");
2741 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2742 } else if (getOpcode() == Instruction::Select) {
2743 Constant *C1 = getOperand(0);
2744 Constant *C2 = getOperand(1);
2745 Constant *C3 = getOperand(2);
2746 if (C1 == From) C1 = To;
2747 if (C2 == From) C2 = To;
2748 if (C3 == From) C3 = To;
2749 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2750 } else if (getOpcode() == Instruction::ExtractElement) {
2751 Constant *C1 = getOperand(0);
2752 Constant *C2 = getOperand(1);
2753 if (C1 == From) C1 = To;
2754 if (C2 == From) C2 = To;
2755 Replacement = ConstantExpr::getExtractElement(C1, C2);
2756 } else if (getOpcode() == Instruction::InsertElement) {
2757 Constant *C1 = getOperand(0);
2758 Constant *C2 = getOperand(1);
2759 Constant *C3 = getOperand(1);
2760 if (C1 == From) C1 = To;
2761 if (C2 == From) C2 = To;
2762 if (C3 == From) C3 = To;
2763 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2764 } else if (getOpcode() == Instruction::ShuffleVector) {
2765 Constant *C1 = getOperand(0);
2766 Constant *C2 = getOperand(1);
2767 Constant *C3 = getOperand(2);
2768 if (C1 == From) C1 = To;
2769 if (C2 == From) C2 = To;
2770 if (C3 == From) C3 = To;
2771 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2772 } else if (isCompare()) {
2773 Constant *C1 = getOperand(0);
2774 Constant *C2 = getOperand(1);
2775 if (C1 == From) C1 = To;
2776 if (C2 == From) C2 = To;
2777 if (getOpcode() == Instruction::ICmp)
2778 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2780 assert(getOpcode() == Instruction::FCmp);
2781 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2783 } else if (getNumOperands() == 2) {
2784 Constant *C1 = getOperand(0);
2785 Constant *C2 = getOperand(1);
2786 if (C1 == From) C1 = To;
2787 if (C2 == From) C2 = To;
2788 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2790 LLVM_UNREACHABLE("Unknown ConstantExpr type!");
2794 assert(Replacement != this && "I didn't contain From!");
2796 // Everyone using this now uses the replacement.
2797 uncheckedReplaceAllUsesWith(Replacement);
2799 // Delete the old constant!
2803 void MDNode::replaceElement(Value *From, Value *To) {
2804 SmallVector<Value*, 4> Values;
2805 Values.reserve(getNumElements()); // Build replacement array...
2806 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
2807 Value *Val = getElement(i);
2808 if (Val == From) Val = To;
2809 Values.push_back(Val);
2812 MDNode *Replacement = MDNode::get(&Values[0], Values.size());
2813 assert(Replacement != this && "I didn't contain From!");
2815 uncheckedReplaceAllUsesWith(Replacement);