1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Constant* classes...
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Constants.h"
15 #include "ConstantFold.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/GlobalValue.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/MDNode.h"
20 #include "llvm/Module.h"
21 #include "llvm/ADT/FoldingSet.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/StringMap.h"
24 #include "llvm/Support/Compiler.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/ManagedStatic.h"
27 #include "llvm/Support/MathExtras.h"
28 #include "llvm/System/RWMutex.h"
29 #include "llvm/System/Threading.h"
30 #include "llvm/ADT/DenseMap.h"
31 #include "llvm/ADT/SmallVector.h"
36 //===----------------------------------------------------------------------===//
38 //===----------------------------------------------------------------------===//
40 // Becomes a no-op when multithreading is disabled.
41 ManagedStatic<sys::SmartRWMutex<true> > ConstantsLock;
43 void Constant::destroyConstantImpl() {
44 // When a Constant is destroyed, there may be lingering
45 // references to the constant by other constants in the constant pool. These
46 // constants are implicitly dependent on the module that is being deleted,
47 // but they don't know that. Because we only find out when the CPV is
48 // deleted, we must now notify all of our users (that should only be
49 // Constants) that they are, in fact, invalid now and should be deleted.
51 while (!use_empty()) {
52 Value *V = use_back();
53 #ifndef NDEBUG // Only in -g mode...
54 if (!isa<Constant>(V))
55 DOUT << "While deleting: " << *this
56 << "\n\nUse still stuck around after Def is destroyed: "
59 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
60 Constant *CV = cast<Constant>(V);
61 CV->destroyConstant();
63 // The constant should remove itself from our use list...
64 assert((use_empty() || use_back() != V) && "Constant not removed!");
67 // Value has no outstanding references it is safe to delete it now...
71 /// canTrap - Return true if evaluation of this constant could trap. This is
72 /// true for things like constant expressions that could divide by zero.
73 bool Constant::canTrap() const {
74 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
75 // The only thing that could possibly trap are constant exprs.
76 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
77 if (!CE) return false;
79 // ConstantExpr traps if any operands can trap.
80 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
81 if (getOperand(i)->canTrap())
84 // Otherwise, only specific operations can trap.
85 switch (CE->getOpcode()) {
88 case Instruction::UDiv:
89 case Instruction::SDiv:
90 case Instruction::FDiv:
91 case Instruction::URem:
92 case Instruction::SRem:
93 case Instruction::FRem:
94 // Div and rem can trap if the RHS is not known to be non-zero.
95 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
101 /// ContainsRelocations - Return true if the constant value contains relocations
102 /// which cannot be resolved at compile time. Kind argument is used to filter
103 /// only 'interesting' sorts of relocations.
104 bool Constant::ContainsRelocations(unsigned Kind) const {
105 if (const GlobalValue* GV = dyn_cast<GlobalValue>(this)) {
106 bool isLocal = GV->hasLocalLinkage();
107 if ((Kind & Reloc::Local) && isLocal) {
108 // Global has local linkage and 'local' kind of relocations are
113 if ((Kind & Reloc::Global) && !isLocal) {
114 // Global has non-local linkage and 'global' kind of relocations are
122 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
123 if (getOperand(i)->ContainsRelocations(Kind))
129 // Static constructor to create a '0' constant of arbitrary type...
130 Constant *Constant::getNullValue(const Type *Ty, bool locked) {
131 static uint64_t zero[2] = {0, 0};
132 switch (Ty->getTypeID()) {
133 case Type::IntegerTyID:
134 return ConstantInt::get(Ty, 0, locked);
135 case Type::FloatTyID:
136 return ConstantFP::get(APFloat(APInt(32, 0)), locked);
137 case Type::DoubleTyID:
138 return ConstantFP::get(APFloat(APInt(64, 0)), locked);
139 case Type::X86_FP80TyID:
140 return ConstantFP::get(APFloat(APInt(80, 2, zero)), locked);
141 case Type::FP128TyID:
142 return ConstantFP::get(APFloat(APInt(128, 2, zero), true), locked);
143 case Type::PPC_FP128TyID:
144 return ConstantFP::get(APFloat(APInt(128, 2, zero)), locked);
145 case Type::PointerTyID:
146 return ConstantPointerNull::get(cast<PointerType>(Ty), locked);
147 case Type::StructTyID:
148 case Type::ArrayTyID:
149 case Type::VectorTyID:
150 return ConstantAggregateZero::get(Ty, locked);
152 // Function, Label, or Opaque type?
153 assert(!"Cannot create a null constant of that type!");
158 Constant *Constant::getAllOnesValue(const Type *Ty) {
159 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
160 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
161 return ConstantVector::getAllOnesValue(cast<VectorType>(Ty));
164 // Static constructor to create an integral constant with all bits set
165 ConstantInt *ConstantInt::getAllOnesValue(const Type *Ty, bool locked) {
166 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
167 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()), locked);
171 /// @returns the value for a vector integer constant of the given type that
172 /// has all its bits set to true.
173 /// @brief Get the all ones value
174 ConstantVector *ConstantVector::getAllOnesValue(const VectorType *Ty,
176 std::vector<Constant*> Elts;
177 Elts.resize(Ty->getNumElements(),
178 ConstantInt::getAllOnesValue(Ty->getElementType(), locked));
179 assert(Elts[0] && "Not a vector integer type!");
180 return cast<ConstantVector>(ConstantVector::get(Elts, locked));
184 /// getVectorElements - This method, which is only valid on constant of vector
185 /// type, returns the elements of the vector in the specified smallvector.
186 /// This handles breaking down a vector undef into undef elements, etc. For
187 /// constant exprs and other cases we can't handle, we return an empty vector.
188 void Constant::getVectorElements(SmallVectorImpl<Constant*> &Elts) const {
189 assert(isa<VectorType>(getType()) && "Not a vector constant!");
191 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
192 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
193 Elts.push_back(CV->getOperand(i));
197 const VectorType *VT = cast<VectorType>(getType());
198 if (isa<ConstantAggregateZero>(this)) {
199 Elts.assign(VT->getNumElements(),
200 Constant::getNullValue(VT->getElementType()));
204 if (isa<UndefValue>(this)) {
205 Elts.assign(VT->getNumElements(), UndefValue::get(VT->getElementType()));
209 // Unknown type, must be constant expr etc.
214 //===----------------------------------------------------------------------===//
216 //===----------------------------------------------------------------------===//
218 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
219 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
220 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
223 ConstantInt *ConstantInt::TheTrueVal = 0;
224 ConstantInt *ConstantInt::TheFalseVal = 0;
227 void CleanupTrueFalse(void *) {
228 ConstantInt::ResetTrueFalse();
232 static ManagedCleanup<llvm::CleanupTrueFalse> TrueFalseCleanup;
234 ConstantInt *ConstantInt::CreateTrueFalseVals(bool WhichOne) {
235 assert(TheTrueVal == 0 && TheFalseVal == 0);
236 TheTrueVal = get(Type::Int1Ty, 1);
237 TheFalseVal = get(Type::Int1Ty, 0);
239 // Ensure that llvm_shutdown nulls out TheTrueVal/TheFalseVal.
240 TrueFalseCleanup.Register();
242 return WhichOne ? TheTrueVal : TheFalseVal;
247 struct DenseMapAPIntKeyInfo {
251 KeyTy(const APInt& V, const Type* Ty) : val(V), type(Ty) {}
252 KeyTy(const KeyTy& that) : val(that.val), type(that.type) {}
253 bool operator==(const KeyTy& that) const {
254 return type == that.type && this->val == that.val;
256 bool operator!=(const KeyTy& that) const {
257 return !this->operator==(that);
260 static inline KeyTy getEmptyKey() { return KeyTy(APInt(1,0), 0); }
261 static inline KeyTy getTombstoneKey() { return KeyTy(APInt(1,1), 0); }
262 static unsigned getHashValue(const KeyTy &Key) {
263 return DenseMapInfo<void*>::getHashValue(Key.type) ^
264 Key.val.getHashValue();
266 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
269 static bool isPod() { return false; }
274 typedef DenseMap<DenseMapAPIntKeyInfo::KeyTy, ConstantInt*,
275 DenseMapAPIntKeyInfo> IntMapTy;
276 static ManagedStatic<IntMapTy> IntConstants;
278 ConstantInt *ConstantInt::get(const IntegerType *Ty,
279 uint64_t V, bool isSigned, bool locked) {
280 return get(APInt(Ty->getBitWidth(), V, isSigned), locked);
283 Constant *ConstantInt::get(const Type *Ty, uint64_t V,
284 bool isSigned, bool locked) {
285 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
287 // For vectors, broadcast the value.
288 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
290 ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C),
296 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
297 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
298 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
299 // compare APInt's of different widths, which would violate an APInt class
300 // invariant which generates an assertion.
301 ConstantInt *ConstantInt::get(const APInt& V, bool locked) {
302 // Get the corresponding integer type for the bit width of the value.
303 const IntegerType *ITy = IntegerType::get(V.getBitWidth());
304 // get an existing value or the insertion position
305 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
307 if (locked) ConstantsLock->reader_acquire();
308 ConstantInt *&Slot = (*IntConstants)[Key];
309 if (locked) ConstantsLock->reader_release();
313 sys::SmartScopedWriter<true> Writer(&*ConstantsLock);
314 ConstantInt *&NewSlot = (*IntConstants)[Key];
316 NewSlot = new ConstantInt(ITy, V);
320 Slot = new ConstantInt(ITy, V);
327 Constant *ConstantInt::get(const Type *Ty, const APInt &V, bool locked) {
328 ConstantInt *C = ConstantInt::get(V, locked);
329 assert(C->getType() == Ty->getScalarType() &&
330 "ConstantInt type doesn't match the type implied by its value!");
332 // For vectors, broadcast the value.
333 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
335 ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C),
341 //===----------------------------------------------------------------------===//
343 //===----------------------------------------------------------------------===//
345 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
346 if (Ty == Type::FloatTy)
347 return &APFloat::IEEEsingle;
348 if (Ty == Type::DoubleTy)
349 return &APFloat::IEEEdouble;
350 if (Ty == Type::X86_FP80Ty)
351 return &APFloat::x87DoubleExtended;
352 else if (Ty == Type::FP128Ty)
353 return &APFloat::IEEEquad;
355 assert(Ty == Type::PPC_FP128Ty && "Unknown FP format");
356 return &APFloat::PPCDoubleDouble;
359 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
360 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
361 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
365 bool ConstantFP::isNullValue() const {
366 return Val.isZero() && !Val.isNegative();
369 ConstantFP *ConstantFP::getNegativeZero(const Type *Ty) {
370 APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
372 return ConstantFP::get(apf);
375 bool ConstantFP::isExactlyValue(const APFloat& V) const {
376 return Val.bitwiseIsEqual(V);
380 struct DenseMapAPFloatKeyInfo {
383 KeyTy(const APFloat& V) : val(V){}
384 KeyTy(const KeyTy& that) : val(that.val) {}
385 bool operator==(const KeyTy& that) const {
386 return this->val.bitwiseIsEqual(that.val);
388 bool operator!=(const KeyTy& that) const {
389 return !this->operator==(that);
392 static inline KeyTy getEmptyKey() {
393 return KeyTy(APFloat(APFloat::Bogus,1));
395 static inline KeyTy getTombstoneKey() {
396 return KeyTy(APFloat(APFloat::Bogus,2));
398 static unsigned getHashValue(const KeyTy &Key) {
399 return Key.val.getHashValue();
401 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
404 static bool isPod() { return false; }
408 //---- ConstantFP::get() implementation...
410 typedef DenseMap<DenseMapAPFloatKeyInfo::KeyTy, ConstantFP*,
411 DenseMapAPFloatKeyInfo> FPMapTy;
413 static ManagedStatic<FPMapTy> FPConstants;
415 ConstantFP *ConstantFP::get(const APFloat &V, bool locked) {
416 DenseMapAPFloatKeyInfo::KeyTy Key(V);
418 if (locked) ConstantsLock->reader_acquire();
419 ConstantFP *&Slot = (*FPConstants)[Key];
420 if (locked) ConstantsLock->reader_release();
424 sys::SmartScopedWriter<true> Writer(&*ConstantsLock);
425 ConstantFP *&NewSlot = (*FPConstants)[Key];
428 if (&V.getSemantics() == &APFloat::IEEEsingle)
430 else if (&V.getSemantics() == &APFloat::IEEEdouble)
432 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
433 Ty = Type::X86_FP80Ty;
434 else if (&V.getSemantics() == &APFloat::IEEEquad)
437 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
438 "Unknown FP format");
439 Ty = Type::PPC_FP128Ty;
441 NewSlot = new ConstantFP(Ty, V);
447 if (&V.getSemantics() == &APFloat::IEEEsingle)
449 else if (&V.getSemantics() == &APFloat::IEEEdouble)
451 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
452 Ty = Type::X86_FP80Ty;
453 else if (&V.getSemantics() == &APFloat::IEEEquad)
456 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
457 "Unknown FP format");
458 Ty = Type::PPC_FP128Ty;
460 Slot = new ConstantFP(Ty, V);
467 /// get() - This returns a constant fp for the specified value in the
468 /// specified type. This should only be used for simple constant values like
469 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
470 Constant *ConstantFP::get(const Type *Ty, double V, bool locked) {
473 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
474 APFloat::rmNearestTiesToEven, &ignored);
475 Constant *C = get(FV, locked);
477 // For vectors, broadcast the value.
478 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
480 ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C),
486 //===----------------------------------------------------------------------===//
487 // ConstantXXX Classes
488 //===----------------------------------------------------------------------===//
491 ConstantArray::ConstantArray(const ArrayType *T,
492 const std::vector<Constant*> &V)
493 : Constant(T, ConstantArrayVal,
494 OperandTraits<ConstantArray>::op_end(this) - V.size(),
496 assert(V.size() == T->getNumElements() &&
497 "Invalid initializer vector for constant array");
498 Use *OL = OperandList;
499 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
502 assert((C->getType() == T->getElementType() ||
504 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
505 "Initializer for array element doesn't match array element type!");
511 ConstantStruct::ConstantStruct(const StructType *T,
512 const std::vector<Constant*> &V)
513 : Constant(T, ConstantStructVal,
514 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
516 assert(V.size() == T->getNumElements() &&
517 "Invalid initializer vector for constant structure");
518 Use *OL = OperandList;
519 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
522 assert((C->getType() == T->getElementType(I-V.begin()) ||
523 ((T->getElementType(I-V.begin())->isAbstract() ||
524 C->getType()->isAbstract()) &&
525 T->getElementType(I-V.begin())->getTypeID() ==
526 C->getType()->getTypeID())) &&
527 "Initializer for struct element doesn't match struct element type!");
533 ConstantVector::ConstantVector(const VectorType *T,
534 const std::vector<Constant*> &V)
535 : Constant(T, ConstantVectorVal,
536 OperandTraits<ConstantVector>::op_end(this) - V.size(),
538 Use *OL = OperandList;
539 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
542 assert((C->getType() == T->getElementType() ||
544 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
545 "Initializer for vector element doesn't match vector element type!");
552 // We declare several classes private to this file, so use an anonymous
556 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
557 /// behind the scenes to implement unary constant exprs.
558 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
559 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
561 // allocate space for exactly one operand
562 void *operator new(size_t s) {
563 return User::operator new(s, 1);
565 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
566 : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
569 /// Transparently provide more efficient getOperand methods.
570 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
573 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
574 /// behind the scenes to implement binary constant exprs.
575 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
576 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
578 // allocate space for exactly two operands
579 void *operator new(size_t s) {
580 return User::operator new(s, 2);
582 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
583 : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
587 /// Transparently provide more efficient getOperand methods.
588 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
591 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
592 /// behind the scenes to implement select constant exprs.
593 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
594 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
596 // allocate space for exactly three operands
597 void *operator new(size_t s) {
598 return User::operator new(s, 3);
600 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
601 : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
606 /// Transparently provide more efficient getOperand methods.
607 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
610 /// ExtractElementConstantExpr - This class is private to
611 /// Constants.cpp, and is used behind the scenes to implement
612 /// extractelement constant exprs.
613 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
614 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
616 // allocate space for exactly two operands
617 void *operator new(size_t s) {
618 return User::operator new(s, 2);
620 ExtractElementConstantExpr(Constant *C1, Constant *C2)
621 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
622 Instruction::ExtractElement, &Op<0>(), 2) {
626 /// Transparently provide more efficient getOperand methods.
627 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
630 /// InsertElementConstantExpr - This class is private to
631 /// Constants.cpp, and is used behind the scenes to implement
632 /// insertelement constant exprs.
633 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
634 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
636 // allocate space for exactly three operands
637 void *operator new(size_t s) {
638 return User::operator new(s, 3);
640 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
641 : ConstantExpr(C1->getType(), Instruction::InsertElement,
647 /// Transparently provide more efficient getOperand methods.
648 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
651 /// ShuffleVectorConstantExpr - This class is private to
652 /// Constants.cpp, and is used behind the scenes to implement
653 /// shufflevector constant exprs.
654 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
655 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
657 // allocate space for exactly three operands
658 void *operator new(size_t s) {
659 return User::operator new(s, 3);
661 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
662 : ConstantExpr(VectorType::get(
663 cast<VectorType>(C1->getType())->getElementType(),
664 cast<VectorType>(C3->getType())->getNumElements()),
665 Instruction::ShuffleVector,
671 /// Transparently provide more efficient getOperand methods.
672 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
675 /// ExtractValueConstantExpr - This class is private to
676 /// Constants.cpp, and is used behind the scenes to implement
677 /// extractvalue constant exprs.
678 class VISIBILITY_HIDDEN ExtractValueConstantExpr : public ConstantExpr {
679 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
681 // allocate space for exactly one operand
682 void *operator new(size_t s) {
683 return User::operator new(s, 1);
685 ExtractValueConstantExpr(Constant *Agg,
686 const SmallVector<unsigned, 4> &IdxList,
688 : ConstantExpr(DestTy, Instruction::ExtractValue, &Op<0>(), 1),
693 /// Indices - These identify which value to extract.
694 const SmallVector<unsigned, 4> Indices;
696 /// Transparently provide more efficient getOperand methods.
697 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
700 /// InsertValueConstantExpr - This class is private to
701 /// Constants.cpp, and is used behind the scenes to implement
702 /// insertvalue constant exprs.
703 class VISIBILITY_HIDDEN InsertValueConstantExpr : public ConstantExpr {
704 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
706 // allocate space for exactly one operand
707 void *operator new(size_t s) {
708 return User::operator new(s, 2);
710 InsertValueConstantExpr(Constant *Agg, Constant *Val,
711 const SmallVector<unsigned, 4> &IdxList,
713 : ConstantExpr(DestTy, Instruction::InsertValue, &Op<0>(), 2),
719 /// Indices - These identify the position for the insertion.
720 const SmallVector<unsigned, 4> Indices;
722 /// Transparently provide more efficient getOperand methods.
723 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
727 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
728 /// used behind the scenes to implement getelementpr constant exprs.
729 class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
730 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
733 static GetElementPtrConstantExpr *Create(Constant *C,
734 const std::vector<Constant*>&IdxList,
735 const Type *DestTy) {
736 return new(IdxList.size() + 1)
737 GetElementPtrConstantExpr(C, IdxList, DestTy);
739 /// Transparently provide more efficient getOperand methods.
740 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
743 // CompareConstantExpr - This class is private to Constants.cpp, and is used
744 // behind the scenes to implement ICmp and FCmp constant expressions. This is
745 // needed in order to store the predicate value for these instructions.
746 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
747 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
748 // allocate space for exactly two operands
749 void *operator new(size_t s) {
750 return User::operator new(s, 2);
752 unsigned short predicate;
753 CompareConstantExpr(const Type *ty, Instruction::OtherOps opc,
754 unsigned short pred, Constant* LHS, Constant* RHS)
755 : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
759 /// Transparently provide more efficient getOperand methods.
760 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
763 } // end anonymous namespace
766 struct OperandTraits<UnaryConstantExpr> : FixedNumOperandTraits<1> {
768 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
771 struct OperandTraits<BinaryConstantExpr> : FixedNumOperandTraits<2> {
773 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
776 struct OperandTraits<SelectConstantExpr> : FixedNumOperandTraits<3> {
778 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
781 struct OperandTraits<ExtractElementConstantExpr> : FixedNumOperandTraits<2> {
783 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
786 struct OperandTraits<InsertElementConstantExpr> : FixedNumOperandTraits<3> {
788 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
791 struct OperandTraits<ShuffleVectorConstantExpr> : FixedNumOperandTraits<3> {
793 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
796 struct OperandTraits<ExtractValueConstantExpr> : FixedNumOperandTraits<1> {
798 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractValueConstantExpr, Value)
801 struct OperandTraits<InsertValueConstantExpr> : FixedNumOperandTraits<2> {
803 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueConstantExpr, Value)
806 struct OperandTraits<GetElementPtrConstantExpr> : VariadicOperandTraits<1> {
809 GetElementPtrConstantExpr::GetElementPtrConstantExpr
811 const std::vector<Constant*> &IdxList,
813 : ConstantExpr(DestTy, Instruction::GetElementPtr,
814 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
815 - (IdxList.size()+1),
818 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
819 OperandList[i+1] = IdxList[i];
822 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
826 struct OperandTraits<CompareConstantExpr> : FixedNumOperandTraits<2> {
828 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
831 } // End llvm namespace
834 // Utility function for determining if a ConstantExpr is a CastOp or not. This
835 // can't be inline because we don't want to #include Instruction.h into
837 bool ConstantExpr::isCast() const {
838 return Instruction::isCast(getOpcode());
841 bool ConstantExpr::isCompare() const {
842 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp ||
843 getOpcode() == Instruction::VICmp || getOpcode() == Instruction::VFCmp;
846 bool ConstantExpr::hasIndices() const {
847 return getOpcode() == Instruction::ExtractValue ||
848 getOpcode() == Instruction::InsertValue;
851 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
852 if (const ExtractValueConstantExpr *EVCE =
853 dyn_cast<ExtractValueConstantExpr>(this))
854 return EVCE->Indices;
856 return cast<InsertValueConstantExpr>(this)->Indices;
859 /// ConstantExpr::get* - Return some common constants without having to
860 /// specify the full Instruction::OPCODE identifier.
862 Constant *ConstantExpr::getNeg(Constant *C) {
863 // API compatibility: Adjust integer opcodes to floating-point opcodes.
864 if (C->getType()->isFPOrFPVector())
866 assert(C->getType()->isIntOrIntVector() &&
867 "Cannot NEG a nonintegral value!");
868 return get(Instruction::Sub,
869 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
872 Constant *ConstantExpr::getFNeg(Constant *C) {
873 assert(C->getType()->isFPOrFPVector() &&
874 "Cannot FNEG a non-floating-point value!");
875 return get(Instruction::FSub,
876 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
879 Constant *ConstantExpr::getNot(Constant *C) {
880 assert(C->getType()->isIntOrIntVector() &&
881 "Cannot NOT a nonintegral value!");
882 return get(Instruction::Xor, C,
883 Constant::getAllOnesValue(C->getType()));
885 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2, bool locked) {
886 return get(Instruction::Add, C1, C2, locked);
888 Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2, bool locked) {
889 return get(Instruction::FAdd, C1, C2, locked);
891 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2, bool locked) {
892 return get(Instruction::Sub, C1, C2, locked);
894 Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2, bool locked) {
895 return get(Instruction::FSub, C1, C2, locked);
897 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2, bool locked) {
898 return get(Instruction::Mul, C1, C2, locked);
900 Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2, bool locked) {
901 return get(Instruction::FMul, C1, C2, locked);
903 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool locked) {
904 return get(Instruction::UDiv, C1, C2, locked);
906 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool locked) {
907 return get(Instruction::SDiv, C1, C2, locked);
909 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2, bool locked) {
910 return get(Instruction::FDiv, C1, C2, locked);
912 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2, bool locked) {
913 return get(Instruction::URem, C1, C2, locked);
915 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2, bool locked) {
916 return get(Instruction::SRem, C1, C2, locked);
918 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2, bool locked) {
919 return get(Instruction::FRem, C1, C2, locked);
921 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2, bool locked) {
922 return get(Instruction::And, C1, C2, locked);
924 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2, bool locked) {
925 return get(Instruction::Or, C1, C2, locked);
927 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2, bool locked) {
928 return get(Instruction::Xor, C1, C2, locked);
930 unsigned ConstantExpr::getPredicate() const {
931 assert(getOpcode() == Instruction::FCmp ||
932 getOpcode() == Instruction::ICmp ||
933 getOpcode() == Instruction::VFCmp ||
934 getOpcode() == Instruction::VICmp);
935 return ((const CompareConstantExpr*)this)->predicate;
937 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2, bool locked) {
938 return get(Instruction::Shl, C1, C2, locked);
940 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool locked) {
941 return get(Instruction::LShr, C1, C2, locked);
943 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool locked) {
944 return get(Instruction::AShr, C1, C2, locked);
947 /// getWithOperandReplaced - Return a constant expression identical to this
948 /// one, but with the specified operand set to the specified value.
950 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
951 assert(OpNo < getNumOperands() && "Operand num is out of range!");
952 assert(Op->getType() == getOperand(OpNo)->getType() &&
953 "Replacing operand with value of different type!");
954 if (getOperand(OpNo) == Op)
955 return const_cast<ConstantExpr*>(this);
957 Constant *Op0, *Op1, *Op2;
958 switch (getOpcode()) {
959 case Instruction::Trunc:
960 case Instruction::ZExt:
961 case Instruction::SExt:
962 case Instruction::FPTrunc:
963 case Instruction::FPExt:
964 case Instruction::UIToFP:
965 case Instruction::SIToFP:
966 case Instruction::FPToUI:
967 case Instruction::FPToSI:
968 case Instruction::PtrToInt:
969 case Instruction::IntToPtr:
970 case Instruction::BitCast:
971 return ConstantExpr::getCast(getOpcode(), Op, getType());
972 case Instruction::Select:
973 Op0 = (OpNo == 0) ? Op : getOperand(0);
974 Op1 = (OpNo == 1) ? Op : getOperand(1);
975 Op2 = (OpNo == 2) ? Op : getOperand(2);
976 return ConstantExpr::getSelect(Op0, Op1, Op2);
977 case Instruction::InsertElement:
978 Op0 = (OpNo == 0) ? Op : getOperand(0);
979 Op1 = (OpNo == 1) ? Op : getOperand(1);
980 Op2 = (OpNo == 2) ? Op : getOperand(2);
981 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
982 case Instruction::ExtractElement:
983 Op0 = (OpNo == 0) ? Op : getOperand(0);
984 Op1 = (OpNo == 1) ? Op : getOperand(1);
985 return ConstantExpr::getExtractElement(Op0, Op1);
986 case Instruction::ShuffleVector:
987 Op0 = (OpNo == 0) ? Op : getOperand(0);
988 Op1 = (OpNo == 1) ? Op : getOperand(1);
989 Op2 = (OpNo == 2) ? Op : getOperand(2);
990 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
991 case Instruction::GetElementPtr: {
992 SmallVector<Constant*, 8> Ops;
993 Ops.resize(getNumOperands()-1);
994 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
995 Ops[i-1] = getOperand(i);
997 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
999 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
1002 assert(getNumOperands() == 2 && "Must be binary operator?");
1003 Op0 = (OpNo == 0) ? Op : getOperand(0);
1004 Op1 = (OpNo == 1) ? Op : getOperand(1);
1005 return ConstantExpr::get(getOpcode(), Op0, Op1);
1009 /// getWithOperands - This returns the current constant expression with the
1010 /// operands replaced with the specified values. The specified operands must
1011 /// match count and type with the existing ones.
1012 Constant *ConstantExpr::
1013 getWithOperands(Constant* const *Ops, unsigned NumOps) const {
1014 assert(NumOps == getNumOperands() && "Operand count mismatch!");
1015 bool AnyChange = false;
1016 for (unsigned i = 0; i != NumOps; ++i) {
1017 assert(Ops[i]->getType() == getOperand(i)->getType() &&
1018 "Operand type mismatch!");
1019 AnyChange |= Ops[i] != getOperand(i);
1021 if (!AnyChange) // No operands changed, return self.
1022 return const_cast<ConstantExpr*>(this);
1024 switch (getOpcode()) {
1025 case Instruction::Trunc:
1026 case Instruction::ZExt:
1027 case Instruction::SExt:
1028 case Instruction::FPTrunc:
1029 case Instruction::FPExt:
1030 case Instruction::UIToFP:
1031 case Instruction::SIToFP:
1032 case Instruction::FPToUI:
1033 case Instruction::FPToSI:
1034 case Instruction::PtrToInt:
1035 case Instruction::IntToPtr:
1036 case Instruction::BitCast:
1037 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
1038 case Instruction::Select:
1039 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
1040 case Instruction::InsertElement:
1041 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
1042 case Instruction::ExtractElement:
1043 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
1044 case Instruction::ShuffleVector:
1045 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
1046 case Instruction::GetElementPtr:
1047 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
1048 case Instruction::ICmp:
1049 case Instruction::FCmp:
1050 case Instruction::VICmp:
1051 case Instruction::VFCmp:
1052 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
1054 assert(getNumOperands() == 2 && "Must be binary operator?");
1055 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
1060 //===----------------------------------------------------------------------===//
1061 // isValueValidForType implementations
1063 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
1064 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
1065 if (Ty == Type::Int1Ty)
1066 return Val == 0 || Val == 1;
1068 return true; // always true, has to fit in largest type
1069 uint64_t Max = (1ll << NumBits) - 1;
1073 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
1074 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
1075 if (Ty == Type::Int1Ty)
1076 return Val == 0 || Val == 1 || Val == -1;
1078 return true; // always true, has to fit in largest type
1079 int64_t Min = -(1ll << (NumBits-1));
1080 int64_t Max = (1ll << (NumBits-1)) - 1;
1081 return (Val >= Min && Val <= Max);
1084 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
1085 // convert modifies in place, so make a copy.
1086 APFloat Val2 = APFloat(Val);
1088 switch (Ty->getTypeID()) {
1090 return false; // These can't be represented as floating point!
1092 // FIXME rounding mode needs to be more flexible
1093 case Type::FloatTyID: {
1094 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
1096 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
1099 case Type::DoubleTyID: {
1100 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
1101 &Val2.getSemantics() == &APFloat::IEEEdouble)
1103 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
1106 case Type::X86_FP80TyID:
1107 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1108 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1109 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
1110 case Type::FP128TyID:
1111 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1112 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1113 &Val2.getSemantics() == &APFloat::IEEEquad;
1114 case Type::PPC_FP128TyID:
1115 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1116 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1117 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
1121 //===----------------------------------------------------------------------===//
1122 // Factory Function Implementation
1125 // The number of operands for each ConstantCreator::create method is
1126 // determined by the ConstantTraits template.
1127 // ConstantCreator - A class that is used to create constants by
1128 // ValueMap*. This class should be partially specialized if there is
1129 // something strange that needs to be done to interface to the ctor for the
1133 template<class ValType>
1134 struct ConstantTraits;
1136 template<typename T, typename Alloc>
1137 struct VISIBILITY_HIDDEN ConstantTraits< std::vector<T, Alloc> > {
1138 static unsigned uses(const std::vector<T, Alloc>& v) {
1143 template<class ConstantClass, class TypeClass, class ValType>
1144 struct VISIBILITY_HIDDEN ConstantCreator {
1145 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
1146 return new(ConstantTraits<ValType>::uses(V)) ConstantClass(Ty, V);
1150 template<class ConstantClass, class TypeClass>
1151 struct VISIBILITY_HIDDEN ConvertConstantType {
1152 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
1153 assert(0 && "This type cannot be converted!\n");
1158 template<class ValType, class TypeClass, class ConstantClass,
1159 bool HasLargeKey = false /*true for arrays and structs*/ >
1160 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
1162 typedef std::pair<const Type*, ValType> MapKey;
1163 typedef std::map<MapKey, Constant *> MapTy;
1164 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
1165 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
1167 /// Map - This is the main map from the element descriptor to the Constants.
1168 /// This is the primary way we avoid creating two of the same shape
1172 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
1173 /// from the constants to their element in Map. This is important for
1174 /// removal of constants from the array, which would otherwise have to scan
1175 /// through the map with very large keys.
1176 InverseMapTy InverseMap;
1178 /// AbstractTypeMap - Map for abstract type constants.
1180 AbstractTypeMapTy AbstractTypeMap;
1183 // NOTE: This function is not locked. It is the caller's responsibility
1184 // to enforce proper synchronization.
1185 typename MapTy::iterator map_end() { return Map.end(); }
1187 /// InsertOrGetItem - Return an iterator for the specified element.
1188 /// If the element exists in the map, the returned iterator points to the
1189 /// entry and Exists=true. If not, the iterator points to the newly
1190 /// inserted entry and returns Exists=false. Newly inserted entries have
1191 /// I->second == 0, and should be filled in.
1192 /// NOTE: This function is not locked. It is the caller's responsibility
1193 // to enforce proper synchronization.
1194 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
1197 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
1198 Exists = !IP.second;
1203 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
1205 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
1206 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
1207 IMI->second->second == CP &&
1208 "InverseMap corrupt!");
1212 typename MapTy::iterator I =
1213 Map.find(MapKey(static_cast<const TypeClass*>(CP->getRawType()),
1215 if (I == Map.end() || I->second != CP) {
1216 // FIXME: This should not use a linear scan. If this gets to be a
1217 // performance problem, someone should look at this.
1218 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
1224 ConstantClass* Create(const TypeClass *Ty, const ValType &V,
1225 typename MapTy::iterator I) {
1226 ConstantClass* Result =
1227 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
1229 assert(Result->getType() == Ty && "Type specified is not correct!");
1230 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
1232 if (HasLargeKey) // Remember the reverse mapping if needed.
1233 InverseMap.insert(std::make_pair(Result, I));
1235 // If the type of the constant is abstract, make sure that an entry
1236 // exists for it in the AbstractTypeMap.
1237 if (Ty->isAbstract()) {
1238 typename AbstractTypeMapTy::iterator TI =
1239 AbstractTypeMap.find(Ty);
1241 if (TI == AbstractTypeMap.end()) {
1242 // Add ourselves to the ATU list of the type.
1243 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
1245 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
1253 /// getOrCreate - Return the specified constant from the map, creating it if
1255 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
1256 MapKey Lookup(Ty, V);
1257 ConstantClass* Result = 0;
1259 ConstantsLock->reader_acquire();
1260 typename MapTy::iterator I = Map.find(Lookup);
1261 // Is it in the map?
1263 Result = static_cast<ConstantClass *>(I->second);
1264 ConstantsLock->reader_release();
1267 sys::SmartScopedWriter<true> Writer(&*ConstantsLock);
1268 I = Map.find(Lookup);
1269 // Is it in the map?
1271 Result = static_cast<ConstantClass *>(I->second);
1273 // If no preexisting value, create one now...
1274 Result = Create(Ty, V, I);
1281 /// unlockedGetOrCreate - Return the specified constant from the map,
1282 /// creating it if necessary. This version performs no locking, and should
1283 /// only be used during recursive type refinement, when the locks are
1285 ConstantClass *unlockedGetOrCreate(const TypeClass *Ty, const ValType &V) {
1286 MapKey Lookup(Ty, V);
1287 ConstantClass* Result = 0;
1289 typename MapTy::iterator I = Map.find(Lookup);
1290 // Is it in the map?
1292 Result = static_cast<ConstantClass *>(I->second);
1295 // If no preexisting value, create one now...
1296 Result = Create(Ty, V, I);
1302 void remove(ConstantClass *CP, bool locked = true) {
1303 if (locked) ConstantsLock->writer_acquire();
1304 typename MapTy::iterator I = FindExistingElement(CP);
1305 assert(I != Map.end() && "Constant not found in constant table!");
1306 assert(I->second == CP && "Didn't find correct element?");
1308 if (HasLargeKey) // Remember the reverse mapping if needed.
1309 InverseMap.erase(CP);
1311 // Now that we found the entry, make sure this isn't the entry that
1312 // the AbstractTypeMap points to.
1313 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
1314 if (Ty->isAbstract()) {
1315 assert(AbstractTypeMap.count(Ty) &&
1316 "Abstract type not in AbstractTypeMap?");
1317 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
1318 if (ATMEntryIt == I) {
1319 // Yes, we are removing the representative entry for this type.
1320 // See if there are any other entries of the same type.
1321 typename MapTy::iterator TmpIt = ATMEntryIt;
1323 // First check the entry before this one...
1324 if (TmpIt != Map.begin()) {
1326 if (TmpIt->first.first != Ty) // Not the same type, move back...
1330 // If we didn't find the same type, try to move forward...
1331 if (TmpIt == ATMEntryIt) {
1333 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
1334 --TmpIt; // No entry afterwards with the same type
1337 // If there is another entry in the map of the same abstract type,
1338 // update the AbstractTypeMap entry now.
1339 if (TmpIt != ATMEntryIt) {
1342 // Otherwise, we are removing the last instance of this type
1343 // from the table. Remove from the ATM, and from user list.
1344 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
1345 AbstractTypeMap.erase(Ty);
1352 if (locked) ConstantsLock->writer_release();
1356 /// MoveConstantToNewSlot - If we are about to change C to be the element
1357 /// specified by I, update our internal data structures to reflect this
1359 /// NOTE: This function is not locked. It is the responsibility of the
1360 /// caller to enforce proper synchronization if using this method.
1361 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
1362 // First, remove the old location of the specified constant in the map.
1363 typename MapTy::iterator OldI = FindExistingElement(C);
1364 assert(OldI != Map.end() && "Constant not found in constant table!");
1365 assert(OldI->second == C && "Didn't find correct element?");
1367 // If this constant is the representative element for its abstract type,
1368 // update the AbstractTypeMap so that the representative element is I.
1369 if (C->getType()->isAbstract()) {
1370 typename AbstractTypeMapTy::iterator ATI =
1371 AbstractTypeMap.find(C->getType());
1372 assert(ATI != AbstractTypeMap.end() &&
1373 "Abstract type not in AbstractTypeMap?");
1374 if (ATI->second == OldI)
1378 // Remove the old entry from the map.
1381 // Update the inverse map so that we know that this constant is now
1382 // located at descriptor I.
1384 assert(I->second == C && "Bad inversemap entry!");
1389 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
1390 ConstantsLock->writer_acquire();
1391 typename AbstractTypeMapTy::iterator I =
1392 AbstractTypeMap.find(cast<Type>(OldTy));
1394 assert(I != AbstractTypeMap.end() &&
1395 "Abstract type not in AbstractTypeMap?");
1397 // Convert a constant at a time until the last one is gone. The last one
1398 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
1399 // eliminated eventually.
1401 ConvertConstantType<ConstantClass,
1402 TypeClass>::convert(
1403 static_cast<ConstantClass *>(I->second->second),
1404 cast<TypeClass>(NewTy));
1406 I = AbstractTypeMap.find(cast<Type>(OldTy));
1407 } while (I != AbstractTypeMap.end());
1409 ConstantsLock->writer_release();
1412 // If the type became concrete without being refined to any other existing
1413 // type, we just remove ourselves from the ATU list.
1414 void typeBecameConcrete(const DerivedType *AbsTy) {
1415 sys::SmartScopedWriter<true> Writer(&*ConstantsLock);
1416 AbsTy->removeAbstractTypeUser(this);
1420 DOUT << "Constant.cpp: ValueMap\n";
1427 //---- ConstantAggregateZero::get() implementation...
1430 // ConstantAggregateZero does not take extra "value" argument...
1431 template<class ValType>
1432 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
1433 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
1434 return new ConstantAggregateZero(Ty);
1439 struct ConvertConstantType<ConstantAggregateZero, Type> {
1440 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1441 // Make everyone now use a constant of the new type...
1442 Constant *New = ConstantAggregateZero::get(NewTy, false);
1443 assert(New != OldC && "Didn't replace constant??");
1444 OldC->uncheckedReplaceAllUsesWith(New);
1445 OldC->destroyConstant(false); // This constant is now dead, destroy it.
1450 static ManagedStatic<ValueMap<char, Type,
1451 ConstantAggregateZero> > AggZeroConstants;
1453 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1455 ConstantAggregateZero *ConstantAggregateZero::get(const Type *Ty, bool locked) {
1456 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
1457 "Cannot create an aggregate zero of non-aggregate type!");
1459 return locked ? AggZeroConstants->getOrCreate(Ty, 0) :
1460 AggZeroConstants->unlockedGetOrCreate(Ty, 0);
1463 /// destroyConstant - Remove the constant from the constant table...
1465 void ConstantAggregateZero::destroyConstant(bool locked) {
1466 // Implicitly locked.
1467 AggZeroConstants->remove(this, locked);
1468 destroyConstantImpl();
1471 //---- ConstantArray::get() implementation...
1475 struct ConvertConstantType<ConstantArray, ArrayType> {
1476 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1477 // Make everyone now use a constant of the new type...
1478 std::vector<Constant*> C;
1479 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1480 C.push_back(cast<Constant>(OldC->getOperand(i)));
1481 Constant *New = ConstantArray::get(NewTy, C, false);
1482 assert(New != OldC && "Didn't replace constant??");
1483 OldC->uncheckedReplaceAllUsesWith(New);
1484 OldC->destroyConstant(false); // This constant is now dead, destroy it.
1489 static std::vector<Constant*> getValType(ConstantArray *CA) {
1490 std::vector<Constant*> Elements;
1491 Elements.reserve(CA->getNumOperands());
1492 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1493 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1497 typedef ValueMap<std::vector<Constant*>, ArrayType,
1498 ConstantArray, true /*largekey*/> ArrayConstantsTy;
1499 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
1501 Constant *ConstantArray::get(const ArrayType *Ty,
1502 const std::vector<Constant*> &V,
1504 // If this is an all-zero array, return a ConstantAggregateZero object
1507 if (!C->isNullValue()) {
1509 // Implicitly locked.
1510 return ArrayConstants->getOrCreate(Ty, V);
1512 return ArrayConstants->unlockedGetOrCreate(Ty, V);
1514 for (unsigned i = 1, e = V.size(); i != e; ++i)
1517 // Implicitly locked.
1518 return ArrayConstants->getOrCreate(Ty, V);
1520 return ArrayConstants->unlockedGetOrCreate(Ty, V);
1524 return ConstantAggregateZero::get(Ty, locked);
1527 /// destroyConstant - Remove the constant from the constant table...
1529 void ConstantArray::destroyConstant(bool locked) {
1530 // Implicitly locked.
1531 ArrayConstants->remove(this, locked);
1532 destroyConstantImpl();
1535 /// ConstantArray::get(const string&) - Return an array that is initialized to
1536 /// contain the specified string. If length is zero then a null terminator is
1537 /// added to the specified string so that it may be used in a natural way.
1538 /// Otherwise, the length parameter specifies how much of the string to use
1539 /// and it won't be null terminated.
1541 Constant *ConstantArray::get(const std::string &Str,
1542 bool AddNull, bool locked) {
1543 std::vector<Constant*> ElementVals;
1544 for (unsigned i = 0; i < Str.length(); ++i)
1545 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
1547 // Add a null terminator to the string...
1549 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
1552 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
1553 return ConstantArray::get(ATy, ElementVals, locked);
1556 /// isString - This method returns true if the array is an array of i8, and
1557 /// if the elements of the array are all ConstantInt's.
1558 bool ConstantArray::isString() const {
1559 // Check the element type for i8...
1560 if (getType()->getElementType() != Type::Int8Ty)
1562 // Check the elements to make sure they are all integers, not constant
1564 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1565 if (!isa<ConstantInt>(getOperand(i)))
1570 /// isCString - This method returns true if the array is a string (see
1571 /// isString) and it ends in a null byte \\0 and does not contains any other
1572 /// null bytes except its terminator.
1573 bool ConstantArray::isCString() const {
1574 // Check the element type for i8...
1575 if (getType()->getElementType() != Type::Int8Ty)
1577 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1578 // Last element must be a null.
1579 if (getOperand(getNumOperands()-1) != Zero)
1581 // Other elements must be non-null integers.
1582 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1583 if (!isa<ConstantInt>(getOperand(i)))
1585 if (getOperand(i) == Zero)
1592 /// getAsString - If the sub-element type of this array is i8
1593 /// then this method converts the array to an std::string and returns it.
1594 /// Otherwise, it asserts out.
1596 std::string ConstantArray::getAsString() const {
1597 assert(isString() && "Not a string!");
1599 Result.reserve(getNumOperands());
1600 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1601 Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
1606 //---- ConstantStruct::get() implementation...
1611 struct ConvertConstantType<ConstantStruct, StructType> {
1612 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1613 // Make everyone now use a constant of the new type...
1614 std::vector<Constant*> C;
1615 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1616 C.push_back(cast<Constant>(OldC->getOperand(i)));
1617 Constant *New = ConstantStruct::get(NewTy, C, false);
1618 assert(New != OldC && "Didn't replace constant??");
1620 OldC->uncheckedReplaceAllUsesWith(New);
1621 OldC->destroyConstant(false); // This constant is now dead, destroy it.
1626 typedef ValueMap<std::vector<Constant*>, StructType,
1627 ConstantStruct, true /*largekey*/> StructConstantsTy;
1628 static ManagedStatic<StructConstantsTy> StructConstants;
1630 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1631 std::vector<Constant*> Elements;
1632 Elements.reserve(CS->getNumOperands());
1633 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1634 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1638 Constant *ConstantStruct::get(const StructType *Ty,
1639 const std::vector<Constant*> &V,
1641 // Create a ConstantAggregateZero value if all elements are zeros...
1642 for (unsigned i = 0, e = V.size(); i != e; ++i)
1643 if (!V[i]->isNullValue())
1644 return locked ? StructConstants->getOrCreate(Ty, V) :
1645 StructConstants->unlockedGetOrCreate(Ty, V);
1647 return ConstantAggregateZero::get(Ty, locked);
1650 Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed,
1652 std::vector<const Type*> StructEls;
1653 StructEls.reserve(V.size());
1654 for (unsigned i = 0, e = V.size(); i != e; ++i)
1655 StructEls.push_back(V[i]->getType());
1656 return get(StructType::get(StructEls, packed), V, locked);
1659 // destroyConstant - Remove the constant from the constant table...
1661 void ConstantStruct::destroyConstant(bool locked) {
1662 // Implicitly locked.
1663 StructConstants->remove(this, locked);
1664 destroyConstantImpl();
1667 //---- ConstantVector::get() implementation...
1671 struct ConvertConstantType<ConstantVector, VectorType> {
1672 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
1673 // Make everyone now use a constant of the new type...
1674 std::vector<Constant*> C;
1675 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1676 C.push_back(cast<Constant>(OldC->getOperand(i)));
1677 Constant *New = ConstantVector::get(NewTy, C, false);
1678 assert(New != OldC && "Didn't replace constant??");
1679 OldC->uncheckedReplaceAllUsesWith(New);
1680 OldC->destroyConstant(false); // This constant is now dead, destroy it.
1685 static std::vector<Constant*> getValType(ConstantVector *CP) {
1686 std::vector<Constant*> Elements;
1687 Elements.reserve(CP->getNumOperands());
1688 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1689 Elements.push_back(CP->getOperand(i));
1693 static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
1694 ConstantVector> > VectorConstants;
1696 Constant *ConstantVector::get(const VectorType *Ty,
1697 const std::vector<Constant*> &V,
1699 assert(!V.empty() && "Vectors can't be empty");
1700 // If this is an all-undef or alll-zero vector, return a
1701 // ConstantAggregateZero or UndefValue.
1703 bool isZero = C->isNullValue();
1704 bool isUndef = isa<UndefValue>(C);
1706 if (isZero || isUndef) {
1707 for (unsigned i = 1, e = V.size(); i != e; ++i)
1709 isZero = isUndef = false;
1715 return ConstantAggregateZero::get(Ty, locked);
1717 return UndefValue::get(Ty, locked);
1719 return locked ? VectorConstants->getOrCreate(Ty, V) :
1720 VectorConstants->unlockedGetOrCreate(Ty, V);
1723 Constant *ConstantVector::get(const std::vector<Constant*> &V, bool locked) {
1724 assert(!V.empty() && "Cannot infer type if V is empty");
1725 return get(VectorType::get(V.front()->getType(),V.size()), V, locked);
1728 // destroyConstant - Remove the constant from the constant table...
1730 void ConstantVector::destroyConstant(bool locked) {
1731 // Implicitly locked.
1732 VectorConstants->remove(this, locked);
1733 destroyConstantImpl();
1736 /// This function will return true iff every element in this vector constant
1737 /// is set to all ones.
1738 /// @returns true iff this constant's emements are all set to all ones.
1739 /// @brief Determine if the value is all ones.
1740 bool ConstantVector::isAllOnesValue() const {
1741 // Check out first element.
1742 const Constant *Elt = getOperand(0);
1743 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1744 if (!CI || !CI->isAllOnesValue()) return false;
1745 // Then make sure all remaining elements point to the same value.
1746 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1747 if (getOperand(I) != Elt) return false;
1752 /// getSplatValue - If this is a splat constant, where all of the
1753 /// elements have the same value, return that value. Otherwise return null.
1754 Constant *ConstantVector::getSplatValue() {
1755 // Check out first element.
1756 Constant *Elt = getOperand(0);
1757 // Then make sure all remaining elements point to the same value.
1758 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1759 if (getOperand(I) != Elt) return 0;
1763 //---- ConstantPointerNull::get() implementation...
1767 // ConstantPointerNull does not take extra "value" argument...
1768 template<class ValType>
1769 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1770 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1771 return new ConstantPointerNull(Ty);
1776 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1777 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1778 // Make everyone now use a constant of the new type...
1779 Constant *New = ConstantPointerNull::get(NewTy, false);
1780 assert(New != OldC && "Didn't replace constant??");
1781 OldC->uncheckedReplaceAllUsesWith(New);
1782 OldC->destroyConstant(false); // This constant is now dead, destroy it.
1787 static ManagedStatic<ValueMap<char, PointerType,
1788 ConstantPointerNull> > NullPtrConstants;
1790 static char getValType(ConstantPointerNull *) {
1795 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty,
1797 // Implicitly locked.
1798 return locked ? NullPtrConstants->getOrCreate(Ty, 0) :
1799 NullPtrConstants->unlockedGetOrCreate(Ty, 0);
1802 // destroyConstant - Remove the constant from the constant table...
1804 void ConstantPointerNull::destroyConstant(bool locked) {
1805 // Implicitly locked.
1806 NullPtrConstants->remove(this, locked);
1807 destroyConstantImpl();
1811 //---- UndefValue::get() implementation...
1815 // UndefValue does not take extra "value" argument...
1816 template<class ValType>
1817 struct ConstantCreator<UndefValue, Type, ValType> {
1818 static UndefValue *create(const Type *Ty, const ValType &V) {
1819 return new UndefValue(Ty);
1824 struct ConvertConstantType<UndefValue, Type> {
1825 static void convert(UndefValue *OldC, const Type *NewTy) {
1826 // Make everyone now use a constant of the new type.
1827 Constant *New = UndefValue::get(NewTy, false);
1828 assert(New != OldC && "Didn't replace constant??");
1829 OldC->uncheckedReplaceAllUsesWith(New);
1830 OldC->destroyConstant(false); // This constant is now dead, destroy it.
1835 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1837 static char getValType(UndefValue *) {
1842 UndefValue *UndefValue::get(const Type *Ty, bool locked) {
1843 return locked ? UndefValueConstants->getOrCreate(Ty, 0) :
1844 UndefValueConstants->unlockedGetOrCreate(Ty, 0);
1847 // destroyConstant - Remove the constant from the constant table.
1849 void UndefValue::destroyConstant(bool locked) {
1850 // Implicitly locked.
1851 UndefValueConstants->remove(this, locked);
1852 destroyConstantImpl();
1855 //---- MDString::get() implementation
1858 MDString::MDString(const char *begin, const char *end)
1859 : Constant(Type::MetadataTy, MDStringVal, 0, 0),
1860 StrBegin(begin), StrEnd(end) {}
1862 static ManagedStatic<StringMap<MDString*> > MDStringCache;
1864 MDString *MDString::get(const char *StrBegin, const char *StrEnd, bool locked) {
1865 if (locked) ConstantsLock->writer_acquire();
1867 StringMapEntry<MDString *> &Entry = MDStringCache->GetOrCreateValue(
1869 MDString *&S = Entry.getValue();
1870 if (!S) S = new MDString(Entry.getKeyData(),
1871 Entry.getKeyData() + Entry.getKeyLength());
1873 if (locked) ConstantsLock->writer_release();
1878 void MDString::destroyConstant(bool locked) {
1879 if (locked) ConstantsLock->writer_acquire();
1880 MDStringCache->erase(MDStringCache->find(StrBegin, StrEnd));
1881 destroyConstantImpl();
1882 if (locked) ConstantsLock->writer_release();
1885 //---- MDNode::get() implementation
1888 static ManagedStatic<FoldingSet<MDNode> > MDNodeSet;
1890 MDNode::MDNode(Value*const* Vals, unsigned NumVals)
1891 : Constant(Type::MetadataTy, MDNodeVal, 0, 0) {
1892 for (unsigned i = 0; i != NumVals; ++i)
1893 Node.push_back(ElementVH(Vals[i], this));
1896 void MDNode::Profile(FoldingSetNodeID &ID) const {
1897 for (const_elem_iterator I = elem_begin(), E = elem_end(); I != E; ++I)
1901 MDNode *MDNode::get(Value*const* Vals, unsigned NumVals, bool locked) {
1902 FoldingSetNodeID ID;
1903 for (unsigned i = 0; i != NumVals; ++i)
1904 ID.AddPointer(Vals[i]);
1906 if (locked) ConstantsLock->reader_acquire();
1908 MDNode *N = MDNodeSet->FindNodeOrInsertPos(ID, InsertPoint);
1909 if (locked) ConstantsLock->reader_release();
1913 sys::SmartScopedWriter<true> Writer(&*ConstantsLock);
1914 N = MDNodeSet->FindNodeOrInsertPos(ID, InsertPoint);
1916 // InsertPoint will have been set by the FindNodeOrInsertPos call.
1917 N = new(0) MDNode(Vals, NumVals);
1918 MDNodeSet->InsertNode(N, InsertPoint);
1921 // InsertPoint will have been set by the FindNodeOrInsertPos call.
1922 N = new(0) MDNode(Vals, NumVals);
1923 MDNodeSet->InsertNode(N, InsertPoint);
1929 void MDNode::destroyConstant(bool locked) {
1930 if (locked) ConstantsLock->writer_acquire();
1931 MDNodeSet->RemoveNode(this);
1932 destroyConstantImpl();
1933 if (locked) ConstantsLock->writer_release();
1936 //---- ConstantExpr::get() implementations...
1941 struct ExprMapKeyType {
1942 typedef SmallVector<unsigned, 4> IndexList;
1944 ExprMapKeyType(unsigned opc,
1945 const std::vector<Constant*> &ops,
1946 unsigned short pred = 0,
1947 const IndexList &inds = IndexList())
1948 : opcode(opc), predicate(pred), operands(ops), indices(inds) {}
1951 std::vector<Constant*> operands;
1953 bool operator==(const ExprMapKeyType& that) const {
1954 return this->opcode == that.opcode &&
1955 this->predicate == that.predicate &&
1956 this->operands == that.operands &&
1957 this->indices == that.indices;
1959 bool operator<(const ExprMapKeyType & that) const {
1960 return this->opcode < that.opcode ||
1961 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1962 (this->opcode == that.opcode && this->predicate == that.predicate &&
1963 this->operands < that.operands) ||
1964 (this->opcode == that.opcode && this->predicate == that.predicate &&
1965 this->operands == that.operands && this->indices < that.indices);
1968 bool operator!=(const ExprMapKeyType& that) const {
1969 return !(*this == that);
1977 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1978 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1979 unsigned short pred = 0) {
1980 if (Instruction::isCast(V.opcode))
1981 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1982 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1983 V.opcode < Instruction::BinaryOpsEnd))
1984 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1985 if (V.opcode == Instruction::Select)
1986 return new SelectConstantExpr(V.operands[0], V.operands[1],
1988 if (V.opcode == Instruction::ExtractElement)
1989 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1990 if (V.opcode == Instruction::InsertElement)
1991 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1993 if (V.opcode == Instruction::ShuffleVector)
1994 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1996 if (V.opcode == Instruction::InsertValue)
1997 return new InsertValueConstantExpr(V.operands[0], V.operands[1],
1999 if (V.opcode == Instruction::ExtractValue)
2000 return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
2001 if (V.opcode == Instruction::GetElementPtr) {
2002 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
2003 return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
2006 // The compare instructions are weird. We have to encode the predicate
2007 // value and it is combined with the instruction opcode by multiplying
2008 // the opcode by one hundred. We must decode this to get the predicate.
2009 if (V.opcode == Instruction::ICmp)
2010 return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate,
2011 V.operands[0], V.operands[1]);
2012 if (V.opcode == Instruction::FCmp)
2013 return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate,
2014 V.operands[0], V.operands[1]);
2015 if (V.opcode == Instruction::VICmp)
2016 return new CompareConstantExpr(Ty, Instruction::VICmp, V.predicate,
2017 V.operands[0], V.operands[1]);
2018 if (V.opcode == Instruction::VFCmp)
2019 return new CompareConstantExpr(Ty, Instruction::VFCmp, V.predicate,
2020 V.operands[0], V.operands[1]);
2021 assert(0 && "Invalid ConstantExpr!");
2027 struct ConvertConstantType<ConstantExpr, Type> {
2028 static void convert(ConstantExpr *OldC, const Type *NewTy) {
2030 switch (OldC->getOpcode()) {
2031 case Instruction::Trunc:
2032 case Instruction::ZExt:
2033 case Instruction::SExt:
2034 case Instruction::FPTrunc:
2035 case Instruction::FPExt:
2036 case Instruction::UIToFP:
2037 case Instruction::SIToFP:
2038 case Instruction::FPToUI:
2039 case Instruction::FPToSI:
2040 case Instruction::PtrToInt:
2041 case Instruction::IntToPtr:
2042 case Instruction::BitCast:
2043 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
2046 case Instruction::Select:
2047 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
2048 OldC->getOperand(1),
2049 OldC->getOperand(2), false);
2052 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
2053 OldC->getOpcode() < Instruction::BinaryOpsEnd);
2054 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
2055 OldC->getOperand(1), false);
2057 case Instruction::GetElementPtr:
2058 // Make everyone now use a constant of the new type...
2059 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
2060 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
2061 &Idx[0], Idx.size(), false);
2065 assert(New != OldC && "Didn't replace constant??");
2066 OldC->uncheckedReplaceAllUsesWith(New);
2067 OldC->destroyConstant(false); // This constant is now dead, destroy it.
2070 } // end namespace llvm
2073 static ExprMapKeyType getValType(ConstantExpr *CE) {
2074 std::vector<Constant*> Operands;
2075 Operands.reserve(CE->getNumOperands());
2076 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
2077 Operands.push_back(cast<Constant>(CE->getOperand(i)));
2078 return ExprMapKeyType(CE->getOpcode(), Operands,
2079 CE->isCompare() ? CE->getPredicate() : 0,
2081 CE->getIndices() : SmallVector<unsigned, 4>());
2084 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
2085 ConstantExpr> > ExprConstants;
2087 /// This is a utility function to handle folding of casts and lookup of the
2088 /// cast in the ExprConstants map. It is used by the various get* methods below.
2089 static inline Constant *getFoldedCast(
2090 Instruction::CastOps opc, Constant *C, const Type *Ty, bool locked) {
2091 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
2092 // Fold a few common cases
2093 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty, locked))
2096 // Look up the constant in the table first to ensure uniqueness
2097 std::vector<Constant*> argVec(1, C);
2098 ExprMapKeyType Key(opc, argVec);
2100 // Implicitly locked.
2101 return locked ? ExprConstants->getOrCreate(Ty, Key) :
2102 ExprConstants->unlockedGetOrCreate(Ty, Key);
2105 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty,
2107 Instruction::CastOps opc = Instruction::CastOps(oc);
2108 assert(Instruction::isCast(opc) && "opcode out of range");
2109 assert(C && Ty && "Null arguments to getCast");
2110 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
2114 assert(0 && "Invalid cast opcode");
2116 case Instruction::Trunc: return getTrunc(C, Ty, locked);
2117 case Instruction::ZExt: return getZExt(C, Ty, locked);
2118 case Instruction::SExt: return getSExt(C, Ty, locked);
2119 case Instruction::FPTrunc: return getFPTrunc(C, Ty, locked);
2120 case Instruction::FPExt: return getFPExtend(C, Ty, locked);
2121 case Instruction::UIToFP: return getUIToFP(C, Ty, locked);
2122 case Instruction::SIToFP: return getSIToFP(C, Ty, locked);
2123 case Instruction::FPToUI: return getFPToUI(C, Ty, locked);
2124 case Instruction::FPToSI: return getFPToSI(C, Ty, locked);
2125 case Instruction::PtrToInt: return getPtrToInt(C, Ty, locked);
2126 case Instruction::IntToPtr: return getIntToPtr(C, Ty, locked);
2127 case Instruction::BitCast: return getBitCast(C, Ty, locked);
2132 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
2133 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2134 return getCast(Instruction::BitCast, C, Ty);
2135 return getCast(Instruction::ZExt, C, Ty);
2138 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty,
2140 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2141 return getCast(Instruction::BitCast, C, Ty, locked);
2142 return getCast(Instruction::SExt, C, Ty, locked);
2145 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
2146 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2147 return getCast(Instruction::BitCast, C, Ty);
2148 return getCast(Instruction::Trunc, C, Ty);
2151 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty,
2153 assert(isa<PointerType>(S->getType()) && "Invalid cast");
2154 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
2156 if (Ty->isInteger())
2157 return getCast(Instruction::PtrToInt, S, Ty, locked);
2158 return getCast(Instruction::BitCast, S, Ty, locked);
2161 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
2163 assert(C->getType()->isIntOrIntVector() &&
2164 Ty->isIntOrIntVector() && "Invalid cast");
2165 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2166 unsigned DstBits = Ty->getScalarSizeInBits();
2167 Instruction::CastOps opcode =
2168 (SrcBits == DstBits ? Instruction::BitCast :
2169 (SrcBits > DstBits ? Instruction::Trunc :
2170 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2171 return getCast(opcode, C, Ty);
2174 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
2175 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2177 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2178 unsigned DstBits = Ty->getScalarSizeInBits();
2179 if (SrcBits == DstBits)
2180 return C; // Avoid a useless cast
2181 Instruction::CastOps opcode =
2182 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
2183 return getCast(opcode, C, Ty);
2186 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty, bool locked) {
2188 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2189 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2191 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2192 assert(C->getType()->isIntOrIntVector() && "Trunc operand must be integer");
2193 assert(Ty->isIntOrIntVector() && "Trunc produces only integral");
2194 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
2195 "SrcTy must be larger than DestTy for Trunc!");
2197 return getFoldedCast(Instruction::Trunc, C, Ty, locked);
2200 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty, bool locked) {
2202 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2203 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2205 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2206 assert(C->getType()->isIntOrIntVector() && "SExt operand must be integral");
2207 assert(Ty->isIntOrIntVector() && "SExt produces only integer");
2208 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
2209 "SrcTy must be smaller than DestTy for SExt!");
2211 return getFoldedCast(Instruction::SExt, C, Ty, locked);
2214 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty, bool locked) {
2216 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2217 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2219 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2220 assert(C->getType()->isIntOrIntVector() && "ZEXt operand must be integral");
2221 assert(Ty->isIntOrIntVector() && "ZExt produces only integer");
2222 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
2223 "SrcTy must be smaller than DestTy for ZExt!");
2225 return getFoldedCast(Instruction::ZExt, C, Ty, locked);
2228 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty, bool locked) {
2230 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2231 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2233 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2234 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2235 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
2236 "This is an illegal floating point truncation!");
2237 return getFoldedCast(Instruction::FPTrunc, C, Ty, locked);
2240 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty, bool locked) {
2242 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2243 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2245 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2246 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2247 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
2248 "This is an illegal floating point extension!");
2249 return getFoldedCast(Instruction::FPExt, C, Ty, locked);
2252 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty, bool locked) {
2254 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2255 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2257 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2258 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
2259 "This is an illegal uint to floating point cast!");
2260 return getFoldedCast(Instruction::UIToFP, C, Ty, locked);
2263 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty, bool locked) {
2265 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2266 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2268 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2269 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
2270 "This is an illegal sint to floating point cast!");
2271 return getFoldedCast(Instruction::SIToFP, C, Ty, locked);
2274 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty, bool locked) {
2276 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2277 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2279 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2280 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
2281 "This is an illegal floating point to uint cast!");
2282 return getFoldedCast(Instruction::FPToUI, C, Ty, locked);
2285 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty, bool locked) {
2287 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2288 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2290 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2291 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
2292 "This is an illegal floating point to sint cast!");
2293 return getFoldedCast(Instruction::FPToSI, C, Ty, locked);
2296 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy,
2298 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
2299 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
2300 return getFoldedCast(Instruction::PtrToInt, C, DstTy, locked);
2303 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy,
2305 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
2306 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
2307 return getFoldedCast(Instruction::IntToPtr, C, DstTy, locked);
2310 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy,
2312 // BitCast implies a no-op cast of type only. No bits change. However, you
2313 // can't cast pointers to anything but pointers.
2315 const Type *SrcTy = C->getType();
2316 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
2317 "BitCast cannot cast pointer to non-pointer and vice versa");
2319 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
2320 // or nonptr->ptr). For all the other types, the cast is okay if source and
2321 // destination bit widths are identical.
2322 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
2323 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
2325 assert(SrcBitSize == DstBitSize && "BitCast requires types of same width");
2327 // It is common to ask for a bitcast of a value to its own type, handle this
2329 if (C->getType() == DstTy) return C;
2331 return getFoldedCast(Instruction::BitCast, C, DstTy, locked);
2334 Constant *ConstantExpr::getAlignOf(const Type *Ty) {
2335 // alignof is implemented as: (i64) gep ({i8,Ty}*)null, 0, 1
2336 const Type *AligningTy = StructType::get(Type::Int8Ty, Ty, NULL);
2337 Constant *NullPtr = getNullValue(AligningTy->getPointerTo());
2338 Constant *Zero = ConstantInt::get(Type::Int32Ty, 0);
2339 Constant *One = ConstantInt::get(Type::Int32Ty, 1);
2340 Constant *Indices[2] = { Zero, One };
2341 Constant *GEP = getGetElementPtr(NullPtr, Indices, 2);
2342 return getCast(Instruction::PtrToInt, GEP, Type::Int32Ty);
2345 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
2346 // sizeof is implemented as: (i64) gep (Ty*)null, 1
2347 Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
2349 getGetElementPtr(getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
2350 return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
2353 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
2354 Constant *C1, Constant *C2, bool locked) {
2355 // Check the operands for consistency first
2356 assert(Opcode >= Instruction::BinaryOpsBegin &&
2357 Opcode < Instruction::BinaryOpsEnd &&
2358 "Invalid opcode in binary constant expression");
2359 assert(C1->getType() == C2->getType() &&
2360 "Operand types in binary constant expression should match");
2362 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
2363 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2, locked))
2364 return FC; // Fold a few common cases...
2366 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
2367 ExprMapKeyType Key(Opcode, argVec);
2369 return locked ? ExprConstants->getOrCreate(ReqTy, Key) :
2370 ExprConstants->unlockedGetOrCreate(ReqTy, Key);
2373 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
2374 Constant *C1, Constant *C2) {
2375 bool isVectorType = C1->getType()->getTypeID() == Type::VectorTyID;
2376 switch (predicate) {
2377 default: assert(0 && "Invalid CmpInst predicate");
2378 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
2379 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
2380 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
2381 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
2382 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
2383 case CmpInst::FCMP_TRUE:
2384 return isVectorType ? getVFCmp(predicate, C1, C2)
2385 : getFCmp(predicate, C1, C2);
2386 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
2387 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
2388 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
2389 case CmpInst::ICMP_SLE:
2390 return isVectorType ? getVICmp(predicate, C1, C2)
2391 : getICmp(predicate, C1, C2);
2395 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
2397 // API compatibility: Adjust integer opcodes to floating-point opcodes.
2398 if (C1->getType()->isFPOrFPVector()) {
2399 if (Opcode == Instruction::Add) Opcode = Instruction::FAdd;
2400 else if (Opcode == Instruction::Sub) Opcode = Instruction::FSub;
2401 else if (Opcode == Instruction::Mul) Opcode = Instruction::FMul;
2405 case Instruction::Add:
2406 case Instruction::Sub:
2407 case Instruction::Mul:
2408 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2409 assert(C1->getType()->isIntOrIntVector() &&
2410 "Tried to create an integer operation on a non-integer type!");
2412 case Instruction::FAdd:
2413 case Instruction::FSub:
2414 case Instruction::FMul:
2415 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2416 assert(C1->getType()->isFPOrFPVector() &&
2417 "Tried to create a floating-point operation on a "
2418 "non-floating-point type!");
2420 case Instruction::UDiv:
2421 case Instruction::SDiv:
2422 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2423 assert(C1->getType()->isIntOrIntVector() &&
2424 "Tried to create an arithmetic operation on a non-arithmetic type!");
2426 case Instruction::FDiv:
2427 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2428 assert(C1->getType()->isFPOrFPVector() &&
2429 "Tried to create an arithmetic operation on a non-arithmetic type!");
2431 case Instruction::URem:
2432 case Instruction::SRem:
2433 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2434 assert(C1->getType()->isIntOrIntVector() &&
2435 "Tried to create an arithmetic operation on a non-arithmetic type!");
2437 case Instruction::FRem:
2438 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2439 assert(C1->getType()->isFPOrFPVector() &&
2440 "Tried to create an arithmetic operation on a non-arithmetic type!");
2442 case Instruction::And:
2443 case Instruction::Or:
2444 case Instruction::Xor:
2445 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2446 assert(C1->getType()->isIntOrIntVector() &&
2447 "Tried to create a logical operation on a non-integral type!");
2449 case Instruction::Shl:
2450 case Instruction::LShr:
2451 case Instruction::AShr:
2452 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2453 assert(C1->getType()->isIntOrIntVector() &&
2454 "Tried to create a shift operation on a non-integer type!");
2461 return getTy(C1->getType(), Opcode, C1, C2, locked);
2464 Constant *ConstantExpr::getCompare(unsigned short pred,
2465 Constant *C1, Constant *C2) {
2466 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2467 return getCompareTy(pred, C1, C2);
2470 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
2471 Constant *V1, Constant *V2, bool locked) {
2472 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
2474 if (ReqTy == V1->getType())
2475 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2, locked))
2476 return SC; // Fold common cases
2478 std::vector<Constant*> argVec(3, C);
2481 ExprMapKeyType Key(Instruction::Select, argVec);
2483 return locked ? ExprConstants->getOrCreate(ReqTy, Key) :
2484 ExprConstants->unlockedGetOrCreate(ReqTy, Key);
2487 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
2489 unsigned NumIdx, bool locked) {
2490 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
2492 cast<PointerType>(ReqTy)->getElementType() &&
2493 "GEP indices invalid!");
2495 if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs,
2497 return FC; // Fold a few common cases...
2499 assert(isa<PointerType>(C->getType()) &&
2500 "Non-pointer type for constant GetElementPtr expression");
2501 // Look up the constant in the table first to ensure uniqueness
2502 std::vector<Constant*> ArgVec;
2503 ArgVec.reserve(NumIdx+1);
2504 ArgVec.push_back(C);
2505 for (unsigned i = 0; i != NumIdx; ++i)
2506 ArgVec.push_back(cast<Constant>(Idxs[i]));
2507 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
2509 // Implicitly locked.
2510 return locked ? ExprConstants->getOrCreate(ReqTy, Key) :
2511 ExprConstants->unlockedGetOrCreate(ReqTy, Key);
2514 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
2515 unsigned NumIdx, bool locked) {
2516 // Get the result type of the getelementptr!
2518 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
2519 assert(Ty && "GEP indices invalid!");
2520 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
2521 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs,
2525 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
2526 unsigned NumIdx, bool locked) {
2527 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx, locked);
2532 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2533 assert(LHS->getType() == RHS->getType());
2534 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2535 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
2537 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2538 return FC; // Fold a few common cases...
2540 // Look up the constant in the table first to ensure uniqueness
2541 std::vector<Constant*> ArgVec;
2542 ArgVec.push_back(LHS);
2543 ArgVec.push_back(RHS);
2544 // Get the key type with both the opcode and predicate
2545 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
2547 // Implicitly locked.
2548 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2552 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2553 assert(LHS->getType() == RHS->getType());
2554 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
2556 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2557 return FC; // Fold a few common cases...
2559 // Look up the constant in the table first to ensure uniqueness
2560 std::vector<Constant*> ArgVec;
2561 ArgVec.push_back(LHS);
2562 ArgVec.push_back(RHS);
2563 // Get the key type with both the opcode and predicate
2564 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
2566 // Implicitly locked.
2567 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2571 ConstantExpr::getVICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2572 assert(isa<VectorType>(LHS->getType()) && LHS->getType() == RHS->getType() &&
2573 "Tried to create vicmp operation on non-vector type!");
2574 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2575 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid VICmp Predicate");
2577 const VectorType *VTy = cast<VectorType>(LHS->getType());
2578 const Type *EltTy = VTy->getElementType();
2579 unsigned NumElts = VTy->getNumElements();
2581 // See if we can fold the element-wise comparison of the LHS and RHS.
2582 SmallVector<Constant *, 16> LHSElts, RHSElts;
2583 LHS->getVectorElements(LHSElts);
2584 RHS->getVectorElements(RHSElts);
2586 if (!LHSElts.empty() && !RHSElts.empty()) {
2587 SmallVector<Constant *, 16> Elts;
2588 for (unsigned i = 0; i != NumElts; ++i) {
2589 Constant *FC = ConstantFoldCompareInstruction(pred, LHSElts[i],
2591 if (ConstantInt *FCI = dyn_cast_or_null<ConstantInt>(FC)) {
2592 if (FCI->getZExtValue())
2593 Elts.push_back(ConstantInt::getAllOnesValue(EltTy));
2595 Elts.push_back(ConstantInt::get(EltTy, 0ULL));
2596 } else if (FC && isa<UndefValue>(FC)) {
2597 Elts.push_back(UndefValue::get(EltTy));
2602 if (Elts.size() == NumElts)
2603 return ConstantVector::get(&Elts[0], Elts.size());
2606 // Look up the constant in the table first to ensure uniqueness
2607 std::vector<Constant*> ArgVec;
2608 ArgVec.push_back(LHS);
2609 ArgVec.push_back(RHS);
2610 // Get the key type with both the opcode and predicate
2611 const ExprMapKeyType Key(Instruction::VICmp, ArgVec, pred);
2613 // Implicitly locked.
2614 return ExprConstants->getOrCreate(LHS->getType(), Key);
2618 ConstantExpr::getVFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2619 assert(isa<VectorType>(LHS->getType()) &&
2620 "Tried to create vfcmp operation on non-vector type!");
2621 assert(LHS->getType() == RHS->getType());
2622 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid VFCmp Predicate");
2624 const VectorType *VTy = cast<VectorType>(LHS->getType());
2625 unsigned NumElts = VTy->getNumElements();
2626 const Type *EltTy = VTy->getElementType();
2627 const Type *REltTy = IntegerType::get(EltTy->getPrimitiveSizeInBits());
2628 const Type *ResultTy = VectorType::get(REltTy, NumElts);
2630 // See if we can fold the element-wise comparison of the LHS and RHS.
2631 SmallVector<Constant *, 16> LHSElts, RHSElts;
2632 LHS->getVectorElements(LHSElts);
2633 RHS->getVectorElements(RHSElts);
2635 if (!LHSElts.empty() && !RHSElts.empty()) {
2636 SmallVector<Constant *, 16> Elts;
2637 for (unsigned i = 0; i != NumElts; ++i) {
2638 Constant *FC = ConstantFoldCompareInstruction(pred, LHSElts[i],
2640 if (ConstantInt *FCI = dyn_cast_or_null<ConstantInt>(FC)) {
2641 if (FCI->getZExtValue())
2642 Elts.push_back(ConstantInt::getAllOnesValue(REltTy));
2644 Elts.push_back(ConstantInt::get(REltTy, 0ULL));
2645 } else if (FC && isa<UndefValue>(FC)) {
2646 Elts.push_back(UndefValue::get(REltTy));
2651 if (Elts.size() == NumElts)
2652 return ConstantVector::get(&Elts[0], Elts.size());
2655 // Look up the constant in the table first to ensure uniqueness
2656 std::vector<Constant*> ArgVec;
2657 ArgVec.push_back(LHS);
2658 ArgVec.push_back(RHS);
2659 // Get the key type with both the opcode and predicate
2660 const ExprMapKeyType Key(Instruction::VFCmp, ArgVec, pred);
2662 // Implicitly locked.
2663 return ExprConstants->getOrCreate(ResultTy, Key);
2666 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
2668 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
2669 return FC; // Fold a few common cases...
2670 // Look up the constant in the table first to ensure uniqueness
2671 std::vector<Constant*> ArgVec(1, Val);
2672 ArgVec.push_back(Idx);
2673 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
2675 // Implicitly locked.
2676 return ExprConstants->getOrCreate(ReqTy, Key);
2679 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
2680 assert(isa<VectorType>(Val->getType()) &&
2681 "Tried to create extractelement operation on non-vector type!");
2682 assert(Idx->getType() == Type::Int32Ty &&
2683 "Extractelement index must be i32 type!");
2684 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
2688 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
2689 Constant *Elt, Constant *Idx) {
2690 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2691 return FC; // Fold a few common cases...
2692 // Look up the constant in the table first to ensure uniqueness
2693 std::vector<Constant*> ArgVec(1, Val);
2694 ArgVec.push_back(Elt);
2695 ArgVec.push_back(Idx);
2696 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
2698 // Implicitly locked.
2699 return ExprConstants->getOrCreate(ReqTy, Key);
2702 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2704 assert(isa<VectorType>(Val->getType()) &&
2705 "Tried to create insertelement operation on non-vector type!");
2706 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
2707 && "Insertelement types must match!");
2708 assert(Idx->getType() == Type::Int32Ty &&
2709 "Insertelement index must be i32 type!");
2710 return getInsertElementTy(Val->getType(), Val, Elt, Idx);
2713 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
2714 Constant *V2, Constant *Mask) {
2715 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2716 return FC; // Fold a few common cases...
2717 // Look up the constant in the table first to ensure uniqueness
2718 std::vector<Constant*> ArgVec(1, V1);
2719 ArgVec.push_back(V2);
2720 ArgVec.push_back(Mask);
2721 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
2723 // Implicitly locked.
2724 return ExprConstants->getOrCreate(ReqTy, Key);
2727 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2729 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2730 "Invalid shuffle vector constant expr operands!");
2732 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
2733 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
2734 const Type *ShufTy = VectorType::get(EltTy, NElts);
2735 return getShuffleVectorTy(ShufTy, V1, V2, Mask);
2738 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
2740 const unsigned *Idxs, unsigned NumIdx) {
2741 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2742 Idxs+NumIdx) == Val->getType() &&
2743 "insertvalue indices invalid!");
2744 assert(Agg->getType() == ReqTy &&
2745 "insertvalue type invalid!");
2746 assert(Agg->getType()->isFirstClassType() &&
2747 "Non-first-class type for constant InsertValue expression");
2748 Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs, NumIdx);
2749 assert(FC && "InsertValue constant expr couldn't be folded!");
2753 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
2754 const unsigned *IdxList, unsigned NumIdx) {
2755 assert(Agg->getType()->isFirstClassType() &&
2756 "Tried to create insertelement operation on non-first-class type!");
2758 const Type *ReqTy = Agg->getType();
2761 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2763 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
2764 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
2767 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
2768 const unsigned *Idxs, unsigned NumIdx) {
2769 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2770 Idxs+NumIdx) == ReqTy &&
2771 "extractvalue indices invalid!");
2772 assert(Agg->getType()->isFirstClassType() &&
2773 "Non-first-class type for constant extractvalue expression");
2774 Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs, NumIdx);
2775 assert(FC && "ExtractValue constant expr couldn't be folded!");
2779 Constant *ConstantExpr::getExtractValue(Constant *Agg,
2780 const unsigned *IdxList, unsigned NumIdx) {
2781 assert(Agg->getType()->isFirstClassType() &&
2782 "Tried to create extractelement operation on non-first-class type!");
2785 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2786 assert(ReqTy && "extractvalue indices invalid!");
2787 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
2790 Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
2791 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
2792 if (PTy->getElementType()->isFloatingPoint()) {
2793 std::vector<Constant*> zeros(PTy->getNumElements(),
2794 ConstantFP::getNegativeZero(PTy->getElementType()));
2795 return ConstantVector::get(PTy, zeros);
2798 if (Ty->isFloatingPoint())
2799 return ConstantFP::getNegativeZero(Ty);
2801 return Constant::getNullValue(Ty);
2804 // destroyConstant - Remove the constant from the constant table...
2806 void ConstantExpr::destroyConstant(bool locked) {
2807 ExprConstants->remove(this, locked);
2808 destroyConstantImpl();
2811 const char *ConstantExpr::getOpcodeName() const {
2812 return Instruction::getOpcodeName(getOpcode());
2815 //===----------------------------------------------------------------------===//
2816 // replaceUsesOfWithOnConstant implementations
2818 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2819 /// 'From' to be uses of 'To'. This must update the uniquing data structures
2822 /// Note that we intentionally replace all uses of From with To here. Consider
2823 /// a large array that uses 'From' 1000 times. By handling this case all here,
2824 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2825 /// single invocation handles all 1000 uses. Handling them one at a time would
2826 /// work, but would be really slow because it would have to unique each updated
2828 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
2830 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2831 Constant *ToC = cast<Constant>(To);
2833 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
2834 Lookup.first.first = getType();
2835 Lookup.second = this;
2837 std::vector<Constant*> &Values = Lookup.first.second;
2838 Values.reserve(getNumOperands()); // Build replacement array.
2840 // Fill values with the modified operands of the constant array. Also,
2841 // compute whether this turns into an all-zeros array.
2842 bool isAllZeros = false;
2843 unsigned NumUpdated = 0;
2844 if (!ToC->isNullValue()) {
2845 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2846 Constant *Val = cast<Constant>(O->get());
2851 Values.push_back(Val);
2855 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2856 Constant *Val = cast<Constant>(O->get());
2861 Values.push_back(Val);
2862 if (isAllZeros) isAllZeros = Val->isNullValue();
2866 Constant *Replacement = 0;
2868 Replacement = ConstantAggregateZero::get(getType());
2870 // Check to see if we have this array type already.
2871 sys::SmartScopedWriter<true> Writer(&*ConstantsLock);
2873 ArrayConstantsTy::MapTy::iterator I =
2874 ArrayConstants->InsertOrGetItem(Lookup, Exists);
2877 Replacement = I->second;
2879 // Okay, the new shape doesn't exist in the system yet. Instead of
2880 // creating a new constant array, inserting it, replaceallusesof'ing the
2881 // old with the new, then deleting the old... just update the current one
2883 ArrayConstants->MoveConstantToNewSlot(this, I);
2885 // Update to the new value. Optimize for the case when we have a single
2886 // operand that we're changing, but handle bulk updates efficiently.
2887 if (NumUpdated == 1) {
2888 unsigned OperandToUpdate = U-OperandList;
2889 assert(getOperand(OperandToUpdate) == From &&
2890 "ReplaceAllUsesWith broken!");
2891 setOperand(OperandToUpdate, ToC);
2893 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2894 if (getOperand(i) == From)
2901 // Otherwise, I do need to replace this with an existing value.
2902 assert(Replacement != this && "I didn't contain From!");
2904 // Everyone using this now uses the replacement.
2905 uncheckedReplaceAllUsesWith(Replacement);
2907 // Delete the old constant!
2911 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2913 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2914 Constant *ToC = cast<Constant>(To);
2916 unsigned OperandToUpdate = U-OperandList;
2917 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2919 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
2920 Lookup.first.first = getType();
2921 Lookup.second = this;
2922 std::vector<Constant*> &Values = Lookup.first.second;
2923 Values.reserve(getNumOperands()); // Build replacement struct.
2926 // Fill values with the modified operands of the constant struct. Also,
2927 // compute whether this turns into an all-zeros struct.
2928 bool isAllZeros = false;
2929 if (!ToC->isNullValue()) {
2930 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2931 Values.push_back(cast<Constant>(O->get()));
2934 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2935 Constant *Val = cast<Constant>(O->get());
2936 Values.push_back(Val);
2937 if (isAllZeros) isAllZeros = Val->isNullValue();
2940 Values[OperandToUpdate] = ToC;
2942 Constant *Replacement = 0;
2945 Replacement = ConstantAggregateZero::get(getType());
2947 // Check to see if we have this array type already.
2948 sys::SmartScopedWriter<true> Writer(&*ConstantsLock);
2950 StructConstantsTy::MapTy::iterator I =
2951 StructConstants->InsertOrGetItem(Lookup, Exists);
2954 Replacement = I->second;
2956 // Okay, the new shape doesn't exist in the system yet. Instead of
2957 // creating a new constant struct, inserting it, replaceallusesof'ing the
2958 // old with the new, then deleting the old... just update the current one
2960 StructConstants->MoveConstantToNewSlot(this, I);
2962 // Update to the new value.
2963 setOperand(OperandToUpdate, ToC);
2968 assert(Replacement != this && "I didn't contain From!");
2970 // Everyone using this now uses the replacement.
2971 uncheckedReplaceAllUsesWith(Replacement);
2973 // Delete the old constant!
2977 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2979 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2981 std::vector<Constant*> Values;
2982 Values.reserve(getNumOperands()); // Build replacement array...
2983 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2984 Constant *Val = getOperand(i);
2985 if (Val == From) Val = cast<Constant>(To);
2986 Values.push_back(Val);
2989 Constant *Replacement = ConstantVector::get(getType(), Values);
2990 assert(Replacement != this && "I didn't contain From!");
2992 // Everyone using this now uses the replacement.
2993 uncheckedReplaceAllUsesWith(Replacement);
2995 // Delete the old constant!
2999 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
3001 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
3002 Constant *To = cast<Constant>(ToV);
3004 Constant *Replacement = 0;
3005 if (getOpcode() == Instruction::GetElementPtr) {
3006 SmallVector<Constant*, 8> Indices;
3007 Constant *Pointer = getOperand(0);
3008 Indices.reserve(getNumOperands()-1);
3009 if (Pointer == From) Pointer = To;
3011 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
3012 Constant *Val = getOperand(i);
3013 if (Val == From) Val = To;
3014 Indices.push_back(Val);
3016 Replacement = ConstantExpr::getGetElementPtr(Pointer,
3017 &Indices[0], Indices.size());
3018 } else if (getOpcode() == Instruction::ExtractValue) {
3019 Constant *Agg = getOperand(0);
3020 if (Agg == From) Agg = To;
3022 const SmallVector<unsigned, 4> &Indices = getIndices();
3023 Replacement = ConstantExpr::getExtractValue(Agg,
3024 &Indices[0], Indices.size());
3025 } else if (getOpcode() == Instruction::InsertValue) {
3026 Constant *Agg = getOperand(0);
3027 Constant *Val = getOperand(1);
3028 if (Agg == From) Agg = To;
3029 if (Val == From) Val = To;
3031 const SmallVector<unsigned, 4> &Indices = getIndices();
3032 Replacement = ConstantExpr::getInsertValue(Agg, Val,
3033 &Indices[0], Indices.size());
3034 } else if (isCast()) {
3035 assert(getOperand(0) == From && "Cast only has one use!");
3036 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
3037 } else if (getOpcode() == Instruction::Select) {
3038 Constant *C1 = getOperand(0);
3039 Constant *C2 = getOperand(1);
3040 Constant *C3 = getOperand(2);
3041 if (C1 == From) C1 = To;
3042 if (C2 == From) C2 = To;
3043 if (C3 == From) C3 = To;
3044 Replacement = ConstantExpr::getSelect(C1, C2, C3);
3045 } else if (getOpcode() == Instruction::ExtractElement) {
3046 Constant *C1 = getOperand(0);
3047 Constant *C2 = getOperand(1);
3048 if (C1 == From) C1 = To;
3049 if (C2 == From) C2 = To;
3050 Replacement = ConstantExpr::getExtractElement(C1, C2);
3051 } else if (getOpcode() == Instruction::InsertElement) {
3052 Constant *C1 = getOperand(0);
3053 Constant *C2 = getOperand(1);
3054 Constant *C3 = getOperand(1);
3055 if (C1 == From) C1 = To;
3056 if (C2 == From) C2 = To;
3057 if (C3 == From) C3 = To;
3058 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
3059 } else if (getOpcode() == Instruction::ShuffleVector) {
3060 Constant *C1 = getOperand(0);
3061 Constant *C2 = getOperand(1);
3062 Constant *C3 = getOperand(2);
3063 if (C1 == From) C1 = To;
3064 if (C2 == From) C2 = To;
3065 if (C3 == From) C3 = To;
3066 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
3067 } else if (isCompare()) {
3068 Constant *C1 = getOperand(0);
3069 Constant *C2 = getOperand(1);
3070 if (C1 == From) C1 = To;
3071 if (C2 == From) C2 = To;
3072 if (getOpcode() == Instruction::ICmp)
3073 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
3074 else if (getOpcode() == Instruction::FCmp)
3075 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
3076 else if (getOpcode() == Instruction::VICmp)
3077 Replacement = ConstantExpr::getVICmp(getPredicate(), C1, C2);
3079 assert(getOpcode() == Instruction::VFCmp);
3080 Replacement = ConstantExpr::getVFCmp(getPredicate(), C1, C2);
3082 } else if (getNumOperands() == 2) {
3083 Constant *C1 = getOperand(0);
3084 Constant *C2 = getOperand(1);
3085 if (C1 == From) C1 = To;
3086 if (C2 == From) C2 = To;
3087 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
3089 assert(0 && "Unknown ConstantExpr type!");
3093 assert(Replacement != this && "I didn't contain From!");
3095 // Everyone using this now uses the replacement.
3096 uncheckedReplaceAllUsesWith(Replacement);
3098 // Delete the old constant!
3102 void MDNode::replaceElement(Value *From, Value *To) {
3103 SmallVector<Value*, 4> Values;
3104 Values.reserve(getNumElements()); // Build replacement array...
3105 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
3106 Value *Val = getElement(i);
3107 if (Val == From) Val = To;
3108 Values.push_back(Val);
3111 MDNode *Replacement = MDNode::get(&Values[0], Values.size());
3112 assert(Replacement != this && "I didn't contain From!");
3114 uncheckedReplaceAllUsesWith(Replacement);