1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Constant* classes...
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Constants.h"
15 #include "ConstantFold.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/GlobalValue.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/MDNode.h"
20 #include "llvm/Module.h"
21 #include "llvm/ADT/FoldingSet.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/StringMap.h"
24 #include "llvm/Support/Compiler.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/ManagedStatic.h"
28 #include "llvm/Support/MathExtras.h"
29 #include "llvm/System/Mutex.h"
30 #include "llvm/System/RWMutex.h"
31 #include "llvm/System/Threading.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/SmallVector.h"
38 //===----------------------------------------------------------------------===//
40 //===----------------------------------------------------------------------===//
42 // Becomes a no-op when multithreading is disabled.
43 ManagedStatic<sys::SmartRWMutex<true> > ConstantsLock;
45 void Constant::destroyConstantImpl() {
46 // When a Constant is destroyed, there may be lingering
47 // references to the constant by other constants in the constant pool. These
48 // constants are implicitly dependent on the module that is being deleted,
49 // but they don't know that. Because we only find out when the CPV is
50 // deleted, we must now notify all of our users (that should only be
51 // Constants) that they are, in fact, invalid now and should be deleted.
53 while (!use_empty()) {
54 Value *V = use_back();
55 #ifndef NDEBUG // Only in -g mode...
56 if (!isa<Constant>(V))
57 DOUT << "While deleting: " << *this
58 << "\n\nUse still stuck around after Def is destroyed: "
61 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
62 Constant *CV = cast<Constant>(V);
63 CV->destroyConstant();
65 // The constant should remove itself from our use list...
66 assert((use_empty() || use_back() != V) && "Constant not removed!");
69 // Value has no outstanding references it is safe to delete it now...
73 /// canTrap - Return true if evaluation of this constant could trap. This is
74 /// true for things like constant expressions that could divide by zero.
75 bool Constant::canTrap() const {
76 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
77 // The only thing that could possibly trap are constant exprs.
78 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
79 if (!CE) return false;
81 // ConstantExpr traps if any operands can trap.
82 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
83 if (getOperand(i)->canTrap())
86 // Otherwise, only specific operations can trap.
87 switch (CE->getOpcode()) {
90 case Instruction::UDiv:
91 case Instruction::SDiv:
92 case Instruction::FDiv:
93 case Instruction::URem:
94 case Instruction::SRem:
95 case Instruction::FRem:
96 // Div and rem can trap if the RHS is not known to be non-zero.
97 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
103 /// ContainsRelocations - Return true if the constant value contains relocations
104 /// which cannot be resolved at compile time. Kind argument is used to filter
105 /// only 'interesting' sorts of relocations.
106 bool Constant::ContainsRelocations(unsigned Kind) const {
107 if (const GlobalValue* GV = dyn_cast<GlobalValue>(this)) {
108 bool isLocal = GV->hasLocalLinkage();
109 if ((Kind & Reloc::Local) && isLocal) {
110 // Global has local linkage and 'local' kind of relocations are
115 if ((Kind & Reloc::Global) && !isLocal) {
116 // Global has non-local linkage and 'global' kind of relocations are
124 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
125 if (getOperand(i)->ContainsRelocations(Kind))
131 /// getVectorElements - This method, which is only valid on constant of vector
132 /// type, returns the elements of the vector in the specified smallvector.
133 /// This handles breaking down a vector undef into undef elements, etc. For
134 /// constant exprs and other cases we can't handle, we return an empty vector.
135 void Constant::getVectorElements(LLVMContext &Context,
136 SmallVectorImpl<Constant*> &Elts) const {
137 assert(isa<VectorType>(getType()) && "Not a vector constant!");
139 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
140 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
141 Elts.push_back(CV->getOperand(i));
145 const VectorType *VT = cast<VectorType>(getType());
146 if (isa<ConstantAggregateZero>(this)) {
147 Elts.assign(VT->getNumElements(),
148 Context.getNullValue(VT->getElementType()));
152 if (isa<UndefValue>(this)) {
153 Elts.assign(VT->getNumElements(), Context.getUndef(VT->getElementType()));
157 // Unknown type, must be constant expr etc.
162 //===----------------------------------------------------------------------===//
164 //===----------------------------------------------------------------------===//
166 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
167 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
168 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
171 ConstantInt *ConstantInt::TheTrueVal = 0;
172 ConstantInt *ConstantInt::TheFalseVal = 0;
175 void CleanupTrueFalse(void *) {
176 ConstantInt::ResetTrueFalse();
180 static ManagedCleanup<llvm::CleanupTrueFalse> TrueFalseCleanup;
182 ConstantInt *ConstantInt::CreateTrueFalseVals(bool WhichOne) {
183 assert(TheTrueVal == 0 && TheFalseVal == 0);
184 TheTrueVal = get(Type::Int1Ty, 1);
185 TheFalseVal = get(Type::Int1Ty, 0);
187 // Ensure that llvm_shutdown nulls out TheTrueVal/TheFalseVal.
188 TrueFalseCleanup.Register();
190 return WhichOne ? TheTrueVal : TheFalseVal;
195 struct DenseMapAPIntKeyInfo {
199 KeyTy(const APInt& V, const Type* Ty) : val(V), type(Ty) {}
200 KeyTy(const KeyTy& that) : val(that.val), type(that.type) {}
201 bool operator==(const KeyTy& that) const {
202 return type == that.type && this->val == that.val;
204 bool operator!=(const KeyTy& that) const {
205 return !this->operator==(that);
208 static inline KeyTy getEmptyKey() { return KeyTy(APInt(1,0), 0); }
209 static inline KeyTy getTombstoneKey() { return KeyTy(APInt(1,1), 0); }
210 static unsigned getHashValue(const KeyTy &Key) {
211 return DenseMapInfo<void*>::getHashValue(Key.type) ^
212 Key.val.getHashValue();
214 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
217 static bool isPod() { return false; }
222 typedef DenseMap<DenseMapAPIntKeyInfo::KeyTy, ConstantInt*,
223 DenseMapAPIntKeyInfo> IntMapTy;
224 static ManagedStatic<IntMapTy> IntConstants;
226 ConstantInt *ConstantInt::get(const IntegerType *Ty,
227 uint64_t V, bool isSigned) {
228 return get(APInt(Ty->getBitWidth(), V, isSigned));
231 Constant *ConstantInt::get(const Type *Ty, uint64_t V, bool isSigned) {
232 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
234 // For vectors, broadcast the value.
235 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
237 ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
242 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
243 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
244 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
245 // compare APInt's of different widths, which would violate an APInt class
246 // invariant which generates an assertion.
247 ConstantInt *ConstantInt::get(const APInt& V) {
248 // Get the corresponding integer type for the bit width of the value.
249 const IntegerType *ITy = IntegerType::get(V.getBitWidth());
250 // get an existing value or the insertion position
251 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
253 ConstantsLock->reader_acquire();
254 ConstantInt *&Slot = (*IntConstants)[Key];
255 ConstantsLock->reader_release();
258 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
259 ConstantInt *&NewSlot = (*IntConstants)[Key];
261 NewSlot = new ConstantInt(ITy, V);
270 Constant *ConstantInt::get(const Type *Ty, const APInt &V) {
271 ConstantInt *C = ConstantInt::get(V);
272 assert(C->getType() == Ty->getScalarType() &&
273 "ConstantInt type doesn't match the type implied by its value!");
275 // For vectors, broadcast the value.
276 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
278 ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
283 //===----------------------------------------------------------------------===//
285 //===----------------------------------------------------------------------===//
287 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
288 if (Ty == Type::FloatTy)
289 return &APFloat::IEEEsingle;
290 if (Ty == Type::DoubleTy)
291 return &APFloat::IEEEdouble;
292 if (Ty == Type::X86_FP80Ty)
293 return &APFloat::x87DoubleExtended;
294 else if (Ty == Type::FP128Ty)
295 return &APFloat::IEEEquad;
297 assert(Ty == Type::PPC_FP128Ty && "Unknown FP format");
298 return &APFloat::PPCDoubleDouble;
301 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
302 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
303 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
307 bool ConstantFP::isNullValue() const {
308 return Val.isZero() && !Val.isNegative();
311 bool ConstantFP::isExactlyValue(const APFloat& V) const {
312 return Val.bitwiseIsEqual(V);
316 struct DenseMapAPFloatKeyInfo {
319 KeyTy(const APFloat& V) : val(V){}
320 KeyTy(const KeyTy& that) : val(that.val) {}
321 bool operator==(const KeyTy& that) const {
322 return this->val.bitwiseIsEqual(that.val);
324 bool operator!=(const KeyTy& that) const {
325 return !this->operator==(that);
328 static inline KeyTy getEmptyKey() {
329 return KeyTy(APFloat(APFloat::Bogus,1));
331 static inline KeyTy getTombstoneKey() {
332 return KeyTy(APFloat(APFloat::Bogus,2));
334 static unsigned getHashValue(const KeyTy &Key) {
335 return Key.val.getHashValue();
337 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
340 static bool isPod() { return false; }
344 //---- ConstantFP::get() implementation...
346 typedef DenseMap<DenseMapAPFloatKeyInfo::KeyTy, ConstantFP*,
347 DenseMapAPFloatKeyInfo> FPMapTy;
349 static ManagedStatic<FPMapTy> FPConstants;
351 ConstantFP *ConstantFP::get(const APFloat &V) {
352 DenseMapAPFloatKeyInfo::KeyTy Key(V);
354 ConstantsLock->reader_acquire();
355 ConstantFP *&Slot = (*FPConstants)[Key];
356 ConstantsLock->reader_release();
359 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
360 ConstantFP *&NewSlot = (*FPConstants)[Key];
363 if (&V.getSemantics() == &APFloat::IEEEsingle)
365 else if (&V.getSemantics() == &APFloat::IEEEdouble)
367 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
368 Ty = Type::X86_FP80Ty;
369 else if (&V.getSemantics() == &APFloat::IEEEquad)
372 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
373 "Unknown FP format");
374 Ty = Type::PPC_FP128Ty;
376 NewSlot = new ConstantFP(Ty, V);
385 //===----------------------------------------------------------------------===//
386 // ConstantXXX Classes
387 //===----------------------------------------------------------------------===//
390 ConstantArray::ConstantArray(const ArrayType *T,
391 const std::vector<Constant*> &V)
392 : Constant(T, ConstantArrayVal,
393 OperandTraits<ConstantArray>::op_end(this) - V.size(),
395 assert(V.size() == T->getNumElements() &&
396 "Invalid initializer vector for constant array");
397 Use *OL = OperandList;
398 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
401 assert((C->getType() == T->getElementType() ||
403 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
404 "Initializer for array element doesn't match array element type!");
410 ConstantStruct::ConstantStruct(const StructType *T,
411 const std::vector<Constant*> &V)
412 : Constant(T, ConstantStructVal,
413 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
415 assert(V.size() == T->getNumElements() &&
416 "Invalid initializer vector for constant structure");
417 Use *OL = OperandList;
418 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
421 assert((C->getType() == T->getElementType(I-V.begin()) ||
422 ((T->getElementType(I-V.begin())->isAbstract() ||
423 C->getType()->isAbstract()) &&
424 T->getElementType(I-V.begin())->getTypeID() ==
425 C->getType()->getTypeID())) &&
426 "Initializer for struct element doesn't match struct element type!");
432 ConstantVector::ConstantVector(const VectorType *T,
433 const std::vector<Constant*> &V)
434 : Constant(T, ConstantVectorVal,
435 OperandTraits<ConstantVector>::op_end(this) - V.size(),
437 Use *OL = OperandList;
438 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
441 assert((C->getType() == T->getElementType() ||
443 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
444 "Initializer for vector element doesn't match vector element type!");
451 // We declare several classes private to this file, so use an anonymous
455 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
456 /// behind the scenes to implement unary constant exprs.
457 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
458 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
460 // allocate space for exactly one operand
461 void *operator new(size_t s) {
462 return User::operator new(s, 1);
464 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
465 : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
468 /// Transparently provide more efficient getOperand methods.
469 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
472 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
473 /// behind the scenes to implement binary constant exprs.
474 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
475 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
477 // allocate space for exactly two operands
478 void *operator new(size_t s) {
479 return User::operator new(s, 2);
481 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
482 : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
486 /// Transparently provide more efficient getOperand methods.
487 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
490 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
491 /// behind the scenes to implement select constant exprs.
492 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
493 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
495 // allocate space for exactly three operands
496 void *operator new(size_t s) {
497 return User::operator new(s, 3);
499 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
500 : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
505 /// Transparently provide more efficient getOperand methods.
506 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
509 /// ExtractElementConstantExpr - This class is private to
510 /// Constants.cpp, and is used behind the scenes to implement
511 /// extractelement constant exprs.
512 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
513 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
515 // allocate space for exactly two operands
516 void *operator new(size_t s) {
517 return User::operator new(s, 2);
519 ExtractElementConstantExpr(Constant *C1, Constant *C2)
520 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
521 Instruction::ExtractElement, &Op<0>(), 2) {
525 /// Transparently provide more efficient getOperand methods.
526 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
529 /// InsertElementConstantExpr - This class is private to
530 /// Constants.cpp, and is used behind the scenes to implement
531 /// insertelement constant exprs.
532 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
533 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
535 // allocate space for exactly three operands
536 void *operator new(size_t s) {
537 return User::operator new(s, 3);
539 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
540 : ConstantExpr(C1->getType(), Instruction::InsertElement,
546 /// Transparently provide more efficient getOperand methods.
547 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
550 /// ShuffleVectorConstantExpr - This class is private to
551 /// Constants.cpp, and is used behind the scenes to implement
552 /// shufflevector constant exprs.
553 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
554 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
556 // allocate space for exactly three operands
557 void *operator new(size_t s) {
558 return User::operator new(s, 3);
560 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
561 : ConstantExpr(VectorType::get(
562 cast<VectorType>(C1->getType())->getElementType(),
563 cast<VectorType>(C3->getType())->getNumElements()),
564 Instruction::ShuffleVector,
570 /// Transparently provide more efficient getOperand methods.
571 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
574 /// ExtractValueConstantExpr - This class is private to
575 /// Constants.cpp, and is used behind the scenes to implement
576 /// extractvalue constant exprs.
577 class VISIBILITY_HIDDEN ExtractValueConstantExpr : public ConstantExpr {
578 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
580 // allocate space for exactly one operand
581 void *operator new(size_t s) {
582 return User::operator new(s, 1);
584 ExtractValueConstantExpr(Constant *Agg,
585 const SmallVector<unsigned, 4> &IdxList,
587 : ConstantExpr(DestTy, Instruction::ExtractValue, &Op<0>(), 1),
592 /// Indices - These identify which value to extract.
593 const SmallVector<unsigned, 4> Indices;
595 /// Transparently provide more efficient getOperand methods.
596 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
599 /// InsertValueConstantExpr - This class is private to
600 /// Constants.cpp, and is used behind the scenes to implement
601 /// insertvalue constant exprs.
602 class VISIBILITY_HIDDEN InsertValueConstantExpr : public ConstantExpr {
603 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
605 // allocate space for exactly one operand
606 void *operator new(size_t s) {
607 return User::operator new(s, 2);
609 InsertValueConstantExpr(Constant *Agg, Constant *Val,
610 const SmallVector<unsigned, 4> &IdxList,
612 : ConstantExpr(DestTy, Instruction::InsertValue, &Op<0>(), 2),
618 /// Indices - These identify the position for the insertion.
619 const SmallVector<unsigned, 4> Indices;
621 /// Transparently provide more efficient getOperand methods.
622 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
626 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
627 /// used behind the scenes to implement getelementpr constant exprs.
628 class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
629 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
632 static GetElementPtrConstantExpr *Create(Constant *C,
633 const std::vector<Constant*>&IdxList,
634 const Type *DestTy) {
635 return new(IdxList.size() + 1)
636 GetElementPtrConstantExpr(C, IdxList, DestTy);
638 /// Transparently provide more efficient getOperand methods.
639 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
642 // CompareConstantExpr - This class is private to Constants.cpp, and is used
643 // behind the scenes to implement ICmp and FCmp constant expressions. This is
644 // needed in order to store the predicate value for these instructions.
645 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
646 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
647 // allocate space for exactly two operands
648 void *operator new(size_t s) {
649 return User::operator new(s, 2);
651 unsigned short predicate;
652 CompareConstantExpr(const Type *ty, Instruction::OtherOps opc,
653 unsigned short pred, Constant* LHS, Constant* RHS)
654 : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
658 /// Transparently provide more efficient getOperand methods.
659 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
662 } // end anonymous namespace
665 struct OperandTraits<UnaryConstantExpr> : FixedNumOperandTraits<1> {
667 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
670 struct OperandTraits<BinaryConstantExpr> : FixedNumOperandTraits<2> {
672 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
675 struct OperandTraits<SelectConstantExpr> : FixedNumOperandTraits<3> {
677 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
680 struct OperandTraits<ExtractElementConstantExpr> : FixedNumOperandTraits<2> {
682 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
685 struct OperandTraits<InsertElementConstantExpr> : FixedNumOperandTraits<3> {
687 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
690 struct OperandTraits<ShuffleVectorConstantExpr> : FixedNumOperandTraits<3> {
692 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
695 struct OperandTraits<ExtractValueConstantExpr> : FixedNumOperandTraits<1> {
697 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractValueConstantExpr, Value)
700 struct OperandTraits<InsertValueConstantExpr> : FixedNumOperandTraits<2> {
702 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueConstantExpr, Value)
705 struct OperandTraits<GetElementPtrConstantExpr> : VariadicOperandTraits<1> {
708 GetElementPtrConstantExpr::GetElementPtrConstantExpr
710 const std::vector<Constant*> &IdxList,
712 : ConstantExpr(DestTy, Instruction::GetElementPtr,
713 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
714 - (IdxList.size()+1),
717 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
718 OperandList[i+1] = IdxList[i];
721 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
725 struct OperandTraits<CompareConstantExpr> : FixedNumOperandTraits<2> {
727 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
730 } // End llvm namespace
733 // Utility function for determining if a ConstantExpr is a CastOp or not. This
734 // can't be inline because we don't want to #include Instruction.h into
736 bool ConstantExpr::isCast() const {
737 return Instruction::isCast(getOpcode());
740 bool ConstantExpr::isCompare() const {
741 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
744 bool ConstantExpr::hasIndices() const {
745 return getOpcode() == Instruction::ExtractValue ||
746 getOpcode() == Instruction::InsertValue;
749 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
750 if (const ExtractValueConstantExpr *EVCE =
751 dyn_cast<ExtractValueConstantExpr>(this))
752 return EVCE->Indices;
754 return cast<InsertValueConstantExpr>(this)->Indices;
757 unsigned ConstantExpr::getPredicate() const {
758 assert(getOpcode() == Instruction::FCmp ||
759 getOpcode() == Instruction::ICmp);
760 return ((const CompareConstantExpr*)this)->predicate;
763 /// getWithOperandReplaced - Return a constant expression identical to this
764 /// one, but with the specified operand set to the specified value.
766 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
767 assert(OpNo < getNumOperands() && "Operand num is out of range!");
768 assert(Op->getType() == getOperand(OpNo)->getType() &&
769 "Replacing operand with value of different type!");
770 if (getOperand(OpNo) == Op)
771 return const_cast<ConstantExpr*>(this);
773 Constant *Op0, *Op1, *Op2;
774 switch (getOpcode()) {
775 case Instruction::Trunc:
776 case Instruction::ZExt:
777 case Instruction::SExt:
778 case Instruction::FPTrunc:
779 case Instruction::FPExt:
780 case Instruction::UIToFP:
781 case Instruction::SIToFP:
782 case Instruction::FPToUI:
783 case Instruction::FPToSI:
784 case Instruction::PtrToInt:
785 case Instruction::IntToPtr:
786 case Instruction::BitCast:
787 return ConstantExpr::getCast(getOpcode(), Op, getType());
788 case Instruction::Select:
789 Op0 = (OpNo == 0) ? Op : getOperand(0);
790 Op1 = (OpNo == 1) ? Op : getOperand(1);
791 Op2 = (OpNo == 2) ? Op : getOperand(2);
792 return ConstantExpr::getSelect(Op0, Op1, Op2);
793 case Instruction::InsertElement:
794 Op0 = (OpNo == 0) ? Op : getOperand(0);
795 Op1 = (OpNo == 1) ? Op : getOperand(1);
796 Op2 = (OpNo == 2) ? Op : getOperand(2);
797 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
798 case Instruction::ExtractElement:
799 Op0 = (OpNo == 0) ? Op : getOperand(0);
800 Op1 = (OpNo == 1) ? Op : getOperand(1);
801 return ConstantExpr::getExtractElement(Op0, Op1);
802 case Instruction::ShuffleVector:
803 Op0 = (OpNo == 0) ? Op : getOperand(0);
804 Op1 = (OpNo == 1) ? Op : getOperand(1);
805 Op2 = (OpNo == 2) ? Op : getOperand(2);
806 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
807 case Instruction::GetElementPtr: {
808 SmallVector<Constant*, 8> Ops;
809 Ops.resize(getNumOperands()-1);
810 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
811 Ops[i-1] = getOperand(i);
813 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
815 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
818 assert(getNumOperands() == 2 && "Must be binary operator?");
819 Op0 = (OpNo == 0) ? Op : getOperand(0);
820 Op1 = (OpNo == 1) ? Op : getOperand(1);
821 return ConstantExpr::get(getOpcode(), Op0, Op1);
825 /// getWithOperands - This returns the current constant expression with the
826 /// operands replaced with the specified values. The specified operands must
827 /// match count and type with the existing ones.
828 Constant *ConstantExpr::
829 getWithOperands(Constant* const *Ops, unsigned NumOps) const {
830 assert(NumOps == getNumOperands() && "Operand count mismatch!");
831 bool AnyChange = false;
832 for (unsigned i = 0; i != NumOps; ++i) {
833 assert(Ops[i]->getType() == getOperand(i)->getType() &&
834 "Operand type mismatch!");
835 AnyChange |= Ops[i] != getOperand(i);
837 if (!AnyChange) // No operands changed, return self.
838 return const_cast<ConstantExpr*>(this);
840 switch (getOpcode()) {
841 case Instruction::Trunc:
842 case Instruction::ZExt:
843 case Instruction::SExt:
844 case Instruction::FPTrunc:
845 case Instruction::FPExt:
846 case Instruction::UIToFP:
847 case Instruction::SIToFP:
848 case Instruction::FPToUI:
849 case Instruction::FPToSI:
850 case Instruction::PtrToInt:
851 case Instruction::IntToPtr:
852 case Instruction::BitCast:
853 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
854 case Instruction::Select:
855 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
856 case Instruction::InsertElement:
857 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
858 case Instruction::ExtractElement:
859 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
860 case Instruction::ShuffleVector:
861 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
862 case Instruction::GetElementPtr:
863 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
864 case Instruction::ICmp:
865 case Instruction::FCmp:
866 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
868 assert(getNumOperands() == 2 && "Must be binary operator?");
869 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
874 //===----------------------------------------------------------------------===//
875 // isValueValidForType implementations
877 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
878 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
879 if (Ty == Type::Int1Ty)
880 return Val == 0 || Val == 1;
882 return true; // always true, has to fit in largest type
883 uint64_t Max = (1ll << NumBits) - 1;
887 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
888 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
889 if (Ty == Type::Int1Ty)
890 return Val == 0 || Val == 1 || Val == -1;
892 return true; // always true, has to fit in largest type
893 int64_t Min = -(1ll << (NumBits-1));
894 int64_t Max = (1ll << (NumBits-1)) - 1;
895 return (Val >= Min && Val <= Max);
898 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
899 // convert modifies in place, so make a copy.
900 APFloat Val2 = APFloat(Val);
902 switch (Ty->getTypeID()) {
904 return false; // These can't be represented as floating point!
906 // FIXME rounding mode needs to be more flexible
907 case Type::FloatTyID: {
908 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
910 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
913 case Type::DoubleTyID: {
914 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
915 &Val2.getSemantics() == &APFloat::IEEEdouble)
917 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
920 case Type::X86_FP80TyID:
921 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
922 &Val2.getSemantics() == &APFloat::IEEEdouble ||
923 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
924 case Type::FP128TyID:
925 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
926 &Val2.getSemantics() == &APFloat::IEEEdouble ||
927 &Val2.getSemantics() == &APFloat::IEEEquad;
928 case Type::PPC_FP128TyID:
929 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
930 &Val2.getSemantics() == &APFloat::IEEEdouble ||
931 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
935 //===----------------------------------------------------------------------===//
936 // Factory Function Implementation
939 // The number of operands for each ConstantCreator::create method is
940 // determined by the ConstantTraits template.
941 // ConstantCreator - A class that is used to create constants by
942 // ValueMap*. This class should be partially specialized if there is
943 // something strange that needs to be done to interface to the ctor for the
947 template<class ValType>
948 struct ConstantTraits;
950 template<typename T, typename Alloc>
951 struct VISIBILITY_HIDDEN ConstantTraits< std::vector<T, Alloc> > {
952 static unsigned uses(const std::vector<T, Alloc>& v) {
957 template<class ConstantClass, class TypeClass, class ValType>
958 struct VISIBILITY_HIDDEN ConstantCreator {
959 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
960 return new(ConstantTraits<ValType>::uses(V)) ConstantClass(Ty, V);
964 template<class ConstantClass, class TypeClass>
965 struct VISIBILITY_HIDDEN ConvertConstantType {
966 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
967 llvm_unreachable("This type cannot be converted!");
971 template<class ValType, class TypeClass, class ConstantClass,
972 bool HasLargeKey = false /*true for arrays and structs*/ >
973 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
975 typedef std::pair<const Type*, ValType> MapKey;
976 typedef std::map<MapKey, Constant *> MapTy;
977 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
978 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
980 /// Map - This is the main map from the element descriptor to the Constants.
981 /// This is the primary way we avoid creating two of the same shape
985 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
986 /// from the constants to their element in Map. This is important for
987 /// removal of constants from the array, which would otherwise have to scan
988 /// through the map with very large keys.
989 InverseMapTy InverseMap;
991 /// AbstractTypeMap - Map for abstract type constants.
993 AbstractTypeMapTy AbstractTypeMap;
995 /// ValueMapLock - Mutex for this map.
996 sys::SmartMutex<true> ValueMapLock;
999 // NOTE: This function is not locked. It is the caller's responsibility
1000 // to enforce proper synchronization.
1001 typename MapTy::iterator map_end() { return Map.end(); }
1003 /// InsertOrGetItem - Return an iterator for the specified element.
1004 /// If the element exists in the map, the returned iterator points to the
1005 /// entry and Exists=true. If not, the iterator points to the newly
1006 /// inserted entry and returns Exists=false. Newly inserted entries have
1007 /// I->second == 0, and should be filled in.
1008 /// NOTE: This function is not locked. It is the caller's responsibility
1009 // to enforce proper synchronization.
1010 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
1013 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
1014 Exists = !IP.second;
1019 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
1021 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
1022 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
1023 IMI->second->second == CP &&
1024 "InverseMap corrupt!");
1028 typename MapTy::iterator I =
1029 Map.find(MapKey(static_cast<const TypeClass*>(CP->getRawType()),
1031 if (I == Map.end() || I->second != CP) {
1032 // FIXME: This should not use a linear scan. If this gets to be a
1033 // performance problem, someone should look at this.
1034 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
1040 ConstantClass* Create(const TypeClass *Ty, const ValType &V,
1041 typename MapTy::iterator I) {
1042 ConstantClass* Result =
1043 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
1045 assert(Result->getType() == Ty && "Type specified is not correct!");
1046 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
1048 if (HasLargeKey) // Remember the reverse mapping if needed.
1049 InverseMap.insert(std::make_pair(Result, I));
1051 // If the type of the constant is abstract, make sure that an entry
1052 // exists for it in the AbstractTypeMap.
1053 if (Ty->isAbstract()) {
1054 typename AbstractTypeMapTy::iterator TI =
1055 AbstractTypeMap.find(Ty);
1057 if (TI == AbstractTypeMap.end()) {
1058 // Add ourselves to the ATU list of the type.
1059 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
1061 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
1069 /// getOrCreate - Return the specified constant from the map, creating it if
1071 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
1072 sys::SmartScopedLock<true> Lock(ValueMapLock);
1073 MapKey Lookup(Ty, V);
1074 ConstantClass* Result = 0;
1076 typename MapTy::iterator I = Map.find(Lookup);
1077 // Is it in the map?
1079 Result = static_cast<ConstantClass *>(I->second);
1082 // If no preexisting value, create one now...
1083 Result = Create(Ty, V, I);
1089 void remove(ConstantClass *CP) {
1090 sys::SmartScopedLock<true> Lock(ValueMapLock);
1091 typename MapTy::iterator I = FindExistingElement(CP);
1092 assert(I != Map.end() && "Constant not found in constant table!");
1093 assert(I->second == CP && "Didn't find correct element?");
1095 if (HasLargeKey) // Remember the reverse mapping if needed.
1096 InverseMap.erase(CP);
1098 // Now that we found the entry, make sure this isn't the entry that
1099 // the AbstractTypeMap points to.
1100 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
1101 if (Ty->isAbstract()) {
1102 assert(AbstractTypeMap.count(Ty) &&
1103 "Abstract type not in AbstractTypeMap?");
1104 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
1105 if (ATMEntryIt == I) {
1106 // Yes, we are removing the representative entry for this type.
1107 // See if there are any other entries of the same type.
1108 typename MapTy::iterator TmpIt = ATMEntryIt;
1110 // First check the entry before this one...
1111 if (TmpIt != Map.begin()) {
1113 if (TmpIt->first.first != Ty) // Not the same type, move back...
1117 // If we didn't find the same type, try to move forward...
1118 if (TmpIt == ATMEntryIt) {
1120 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
1121 --TmpIt; // No entry afterwards with the same type
1124 // If there is another entry in the map of the same abstract type,
1125 // update the AbstractTypeMap entry now.
1126 if (TmpIt != ATMEntryIt) {
1129 // Otherwise, we are removing the last instance of this type
1130 // from the table. Remove from the ATM, and from user list.
1131 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
1132 AbstractTypeMap.erase(Ty);
1141 /// MoveConstantToNewSlot - If we are about to change C to be the element
1142 /// specified by I, update our internal data structures to reflect this
1144 /// NOTE: This function is not locked. It is the responsibility of the
1145 /// caller to enforce proper synchronization if using this method.
1146 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
1147 // First, remove the old location of the specified constant in the map.
1148 typename MapTy::iterator OldI = FindExistingElement(C);
1149 assert(OldI != Map.end() && "Constant not found in constant table!");
1150 assert(OldI->second == C && "Didn't find correct element?");
1152 // If this constant is the representative element for its abstract type,
1153 // update the AbstractTypeMap so that the representative element is I.
1154 if (C->getType()->isAbstract()) {
1155 typename AbstractTypeMapTy::iterator ATI =
1156 AbstractTypeMap.find(C->getType());
1157 assert(ATI != AbstractTypeMap.end() &&
1158 "Abstract type not in AbstractTypeMap?");
1159 if (ATI->second == OldI)
1163 // Remove the old entry from the map.
1166 // Update the inverse map so that we know that this constant is now
1167 // located at descriptor I.
1169 assert(I->second == C && "Bad inversemap entry!");
1174 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
1175 sys::SmartScopedLock<true> Lock(ValueMapLock);
1176 typename AbstractTypeMapTy::iterator I =
1177 AbstractTypeMap.find(cast<Type>(OldTy));
1179 assert(I != AbstractTypeMap.end() &&
1180 "Abstract type not in AbstractTypeMap?");
1182 // Convert a constant at a time until the last one is gone. The last one
1183 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
1184 // eliminated eventually.
1186 ConvertConstantType<ConstantClass,
1187 TypeClass>::convert(
1188 static_cast<ConstantClass *>(I->second->second),
1189 cast<TypeClass>(NewTy));
1191 I = AbstractTypeMap.find(cast<Type>(OldTy));
1192 } while (I != AbstractTypeMap.end());
1195 // If the type became concrete without being refined to any other existing
1196 // type, we just remove ourselves from the ATU list.
1197 void typeBecameConcrete(const DerivedType *AbsTy) {
1198 AbsTy->removeAbstractTypeUser(this);
1202 DOUT << "Constant.cpp: ValueMap\n";
1209 //---- ConstantAggregateZero::get() implementation...
1212 // ConstantAggregateZero does not take extra "value" argument...
1213 template<class ValType>
1214 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
1215 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
1216 return new ConstantAggregateZero(Ty);
1221 struct ConvertConstantType<ConstantAggregateZero, Type> {
1222 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1223 // Make everyone now use a constant of the new type...
1224 Constant *New = ConstantAggregateZero::get(NewTy);
1225 assert(New != OldC && "Didn't replace constant??");
1226 OldC->uncheckedReplaceAllUsesWith(New);
1227 OldC->destroyConstant(); // This constant is now dead, destroy it.
1232 static ManagedStatic<ValueMap<char, Type,
1233 ConstantAggregateZero> > AggZeroConstants;
1235 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1237 ConstantAggregateZero *ConstantAggregateZero::get(const Type *Ty) {
1238 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
1239 "Cannot create an aggregate zero of non-aggregate type!");
1241 // Implicitly locked.
1242 return AggZeroConstants->getOrCreate(Ty, 0);
1245 /// destroyConstant - Remove the constant from the constant table...
1247 void ConstantAggregateZero::destroyConstant() {
1248 // Implicitly locked.
1249 AggZeroConstants->remove(this);
1250 destroyConstantImpl();
1253 //---- ConstantArray::get() implementation...
1257 struct ConvertConstantType<ConstantArray, ArrayType> {
1258 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1259 // Make everyone now use a constant of the new type...
1260 std::vector<Constant*> C;
1261 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1262 C.push_back(cast<Constant>(OldC->getOperand(i)));
1263 Constant *New = ConstantArray::get(NewTy, C);
1264 assert(New != OldC && "Didn't replace constant??");
1265 OldC->uncheckedReplaceAllUsesWith(New);
1266 OldC->destroyConstant(); // This constant is now dead, destroy it.
1271 static std::vector<Constant*> getValType(ConstantArray *CA) {
1272 std::vector<Constant*> Elements;
1273 Elements.reserve(CA->getNumOperands());
1274 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1275 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1279 typedef ValueMap<std::vector<Constant*>, ArrayType,
1280 ConstantArray, true /*largekey*/> ArrayConstantsTy;
1281 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
1283 Constant *ConstantArray::get(const ArrayType *Ty,
1284 const std::vector<Constant*> &V) {
1285 // If this is an all-zero array, return a ConstantAggregateZero object
1288 if (!C->isNullValue()) {
1289 // Implicitly locked.
1290 return ArrayConstants->getOrCreate(Ty, V);
1292 for (unsigned i = 1, e = V.size(); i != e; ++i)
1294 // Implicitly locked.
1295 return ArrayConstants->getOrCreate(Ty, V);
1299 return ConstantAggregateZero::get(Ty);
1302 /// destroyConstant - Remove the constant from the constant table...
1304 void ConstantArray::destroyConstant() {
1305 // Implicitly locked.
1306 ArrayConstants->remove(this);
1307 destroyConstantImpl();
1310 /// ConstantArray::get(const string&) - Return an array that is initialized to
1311 /// contain the specified string. If length is zero then a null terminator is
1312 /// added to the specified string so that it may be used in a natural way.
1313 /// Otherwise, the length parameter specifies how much of the string to use
1314 /// and it won't be null terminated.
1316 Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
1317 std::vector<Constant*> ElementVals;
1318 for (unsigned i = 0; i < Str.length(); ++i)
1319 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
1321 // Add a null terminator to the string...
1323 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
1326 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
1327 return ConstantArray::get(ATy, ElementVals);
1330 /// isString - This method returns true if the array is an array of i8, and
1331 /// if the elements of the array are all ConstantInt's.
1332 bool ConstantArray::isString() const {
1333 // Check the element type for i8...
1334 if (getType()->getElementType() != Type::Int8Ty)
1336 // Check the elements to make sure they are all integers, not constant
1338 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1339 if (!isa<ConstantInt>(getOperand(i)))
1344 /// isCString - This method returns true if the array is a string (see
1345 /// isString) and it ends in a null byte \\0 and does not contains any other
1346 /// null bytes except its terminator.
1347 bool ConstantArray::isCString() const {
1348 // Check the element type for i8...
1349 if (getType()->getElementType() != Type::Int8Ty)
1352 // Last element must be a null.
1353 if (!getOperand(getNumOperands()-1)->isNullValue())
1355 // Other elements must be non-null integers.
1356 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1357 if (!isa<ConstantInt>(getOperand(i)))
1359 if (getOperand(i)->isNullValue())
1366 /// getAsString - If the sub-element type of this array is i8
1367 /// then this method converts the array to an std::string and returns it.
1368 /// Otherwise, it asserts out.
1370 std::string ConstantArray::getAsString() const {
1371 assert(isString() && "Not a string!");
1373 Result.reserve(getNumOperands());
1374 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1375 Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
1380 //---- ConstantStruct::get() implementation...
1385 struct ConvertConstantType<ConstantStruct, StructType> {
1386 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1387 // Make everyone now use a constant of the new type...
1388 std::vector<Constant*> C;
1389 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1390 C.push_back(cast<Constant>(OldC->getOperand(i)));
1391 Constant *New = ConstantStruct::get(NewTy, C);
1392 assert(New != OldC && "Didn't replace constant??");
1394 OldC->uncheckedReplaceAllUsesWith(New);
1395 OldC->destroyConstant(); // This constant is now dead, destroy it.
1400 typedef ValueMap<std::vector<Constant*>, StructType,
1401 ConstantStruct, true /*largekey*/> StructConstantsTy;
1402 static ManagedStatic<StructConstantsTy> StructConstants;
1404 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1405 std::vector<Constant*> Elements;
1406 Elements.reserve(CS->getNumOperands());
1407 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1408 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1412 Constant *ConstantStruct::get(const StructType *Ty,
1413 const std::vector<Constant*> &V) {
1414 // Create a ConstantAggregateZero value if all elements are zeros...
1415 for (unsigned i = 0, e = V.size(); i != e; ++i)
1416 if (!V[i]->isNullValue())
1417 // Implicitly locked.
1418 return StructConstants->getOrCreate(Ty, V);
1420 return ConstantAggregateZero::get(Ty);
1423 Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
1424 std::vector<const Type*> StructEls;
1425 StructEls.reserve(V.size());
1426 for (unsigned i = 0, e = V.size(); i != e; ++i)
1427 StructEls.push_back(V[i]->getType());
1428 return get(StructType::get(StructEls, packed), V);
1431 // destroyConstant - Remove the constant from the constant table...
1433 void ConstantStruct::destroyConstant() {
1434 // Implicitly locked.
1435 StructConstants->remove(this);
1436 destroyConstantImpl();
1439 //---- ConstantVector::get() implementation...
1443 struct ConvertConstantType<ConstantVector, VectorType> {
1444 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
1445 // Make everyone now use a constant of the new type...
1446 std::vector<Constant*> C;
1447 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1448 C.push_back(cast<Constant>(OldC->getOperand(i)));
1449 Constant *New = ConstantVector::get(NewTy, C);
1450 assert(New != OldC && "Didn't replace constant??");
1451 OldC->uncheckedReplaceAllUsesWith(New);
1452 OldC->destroyConstant(); // This constant is now dead, destroy it.
1457 static std::vector<Constant*> getValType(ConstantVector *CP) {
1458 std::vector<Constant*> Elements;
1459 Elements.reserve(CP->getNumOperands());
1460 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1461 Elements.push_back(CP->getOperand(i));
1465 static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
1466 ConstantVector> > VectorConstants;
1468 Constant *ConstantVector::get(const VectorType *Ty,
1469 const std::vector<Constant*> &V) {
1470 assert(!V.empty() && "Vectors can't be empty");
1471 // If this is an all-undef or alll-zero vector, return a
1472 // ConstantAggregateZero or UndefValue.
1474 bool isZero = C->isNullValue();
1475 bool isUndef = isa<UndefValue>(C);
1477 if (isZero || isUndef) {
1478 for (unsigned i = 1, e = V.size(); i != e; ++i)
1480 isZero = isUndef = false;
1486 return ConstantAggregateZero::get(Ty);
1488 return UndefValue::get(Ty);
1490 // Implicitly locked.
1491 return VectorConstants->getOrCreate(Ty, V);
1494 Constant *ConstantVector::get(const std::vector<Constant*> &V) {
1495 assert(!V.empty() && "Cannot infer type if V is empty");
1496 return get(VectorType::get(V.front()->getType(),V.size()), V);
1499 // destroyConstant - Remove the constant from the constant table...
1501 void ConstantVector::destroyConstant() {
1502 // Implicitly locked.
1503 VectorConstants->remove(this);
1504 destroyConstantImpl();
1507 /// This function will return true iff every element in this vector constant
1508 /// is set to all ones.
1509 /// @returns true iff this constant's emements are all set to all ones.
1510 /// @brief Determine if the value is all ones.
1511 bool ConstantVector::isAllOnesValue() const {
1512 // Check out first element.
1513 const Constant *Elt = getOperand(0);
1514 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1515 if (!CI || !CI->isAllOnesValue()) return false;
1516 // Then make sure all remaining elements point to the same value.
1517 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1518 if (getOperand(I) != Elt) return false;
1523 /// getSplatValue - If this is a splat constant, where all of the
1524 /// elements have the same value, return that value. Otherwise return null.
1525 Constant *ConstantVector::getSplatValue() {
1526 // Check out first element.
1527 Constant *Elt = getOperand(0);
1528 // Then make sure all remaining elements point to the same value.
1529 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1530 if (getOperand(I) != Elt) return 0;
1534 //---- ConstantPointerNull::get() implementation...
1538 // ConstantPointerNull does not take extra "value" argument...
1539 template<class ValType>
1540 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1541 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1542 return new ConstantPointerNull(Ty);
1547 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1548 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1549 // Make everyone now use a constant of the new type...
1550 Constant *New = ConstantPointerNull::get(NewTy);
1551 assert(New != OldC && "Didn't replace constant??");
1552 OldC->uncheckedReplaceAllUsesWith(New);
1553 OldC->destroyConstant(); // This constant is now dead, destroy it.
1558 static ManagedStatic<ValueMap<char, PointerType,
1559 ConstantPointerNull> > NullPtrConstants;
1561 static char getValType(ConstantPointerNull *) {
1566 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1567 // Implicitly locked.
1568 return NullPtrConstants->getOrCreate(Ty, 0);
1571 // destroyConstant - Remove the constant from the constant table...
1573 void ConstantPointerNull::destroyConstant() {
1574 // Implicitly locked.
1575 NullPtrConstants->remove(this);
1576 destroyConstantImpl();
1580 //---- UndefValue::get() implementation...
1584 // UndefValue does not take extra "value" argument...
1585 template<class ValType>
1586 struct ConstantCreator<UndefValue, Type, ValType> {
1587 static UndefValue *create(const Type *Ty, const ValType &V) {
1588 return new UndefValue(Ty);
1593 struct ConvertConstantType<UndefValue, Type> {
1594 static void convert(UndefValue *OldC, const Type *NewTy) {
1595 // Make everyone now use a constant of the new type.
1596 Constant *New = UndefValue::get(NewTy);
1597 assert(New != OldC && "Didn't replace constant??");
1598 OldC->uncheckedReplaceAllUsesWith(New);
1599 OldC->destroyConstant(); // This constant is now dead, destroy it.
1604 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1606 static char getValType(UndefValue *) {
1611 UndefValue *UndefValue::get(const Type *Ty) {
1612 // Implicitly locked.
1613 return UndefValueConstants->getOrCreate(Ty, 0);
1616 // destroyConstant - Remove the constant from the constant table.
1618 void UndefValue::destroyConstant() {
1619 // Implicitly locked.
1620 UndefValueConstants->remove(this);
1621 destroyConstantImpl();
1624 //---- MDString::get() implementation
1627 MDString::MDString(const char *begin, const char *end)
1628 : Constant(Type::MetadataTy, MDStringVal, 0, 0),
1629 StrBegin(begin), StrEnd(end) {}
1631 static ManagedStatic<StringMap<MDString*> > MDStringCache;
1633 MDString *MDString::get(const char *StrBegin, const char *StrEnd) {
1634 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
1635 StringMapEntry<MDString *> &Entry = MDStringCache->GetOrCreateValue(
1637 MDString *&S = Entry.getValue();
1638 if (!S) S = new MDString(Entry.getKeyData(),
1639 Entry.getKeyData() + Entry.getKeyLength());
1644 MDString *MDString::get(const std::string &Str) {
1645 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
1646 StringMapEntry<MDString *> &Entry = MDStringCache->GetOrCreateValue(
1647 Str.data(), Str.data() + Str.size());
1648 MDString *&S = Entry.getValue();
1649 if (!S) S = new MDString(Entry.getKeyData(),
1650 Entry.getKeyData() + Entry.getKeyLength());
1655 void MDString::destroyConstant() {
1656 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
1657 MDStringCache->erase(MDStringCache->find(StrBegin, StrEnd));
1658 destroyConstantImpl();
1661 //---- MDNode::get() implementation
1664 static ManagedStatic<FoldingSet<MDNode> > MDNodeSet;
1666 MDNode::MDNode(Value*const* Vals, unsigned NumVals)
1667 : Constant(Type::MetadataTy, MDNodeVal, 0, 0) {
1668 for (unsigned i = 0; i != NumVals; ++i)
1669 Node.push_back(ElementVH(Vals[i], this));
1672 void MDNode::Profile(FoldingSetNodeID &ID) const {
1673 for (const_elem_iterator I = elem_begin(), E = elem_end(); I != E; ++I)
1677 MDNode *MDNode::get(Value*const* Vals, unsigned NumVals) {
1678 FoldingSetNodeID ID;
1679 for (unsigned i = 0; i != NumVals; ++i)
1680 ID.AddPointer(Vals[i]);
1682 ConstantsLock->reader_acquire();
1684 MDNode *N = MDNodeSet->FindNodeOrInsertPos(ID, InsertPoint);
1685 ConstantsLock->reader_release();
1688 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
1689 N = MDNodeSet->FindNodeOrInsertPos(ID, InsertPoint);
1691 // InsertPoint will have been set by the FindNodeOrInsertPos call.
1692 N = new(0) MDNode(Vals, NumVals);
1693 MDNodeSet->InsertNode(N, InsertPoint);
1699 void MDNode::destroyConstant() {
1700 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
1701 MDNodeSet->RemoveNode(this);
1703 destroyConstantImpl();
1706 //---- ConstantExpr::get() implementations...
1711 struct ExprMapKeyType {
1712 typedef SmallVector<unsigned, 4> IndexList;
1714 ExprMapKeyType(unsigned opc,
1715 const std::vector<Constant*> &ops,
1716 unsigned short pred = 0,
1717 const IndexList &inds = IndexList())
1718 : opcode(opc), predicate(pred), operands(ops), indices(inds) {}
1721 std::vector<Constant*> operands;
1723 bool operator==(const ExprMapKeyType& that) const {
1724 return this->opcode == that.opcode &&
1725 this->predicate == that.predicate &&
1726 this->operands == that.operands &&
1727 this->indices == that.indices;
1729 bool operator<(const ExprMapKeyType & that) const {
1730 return this->opcode < that.opcode ||
1731 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1732 (this->opcode == that.opcode && this->predicate == that.predicate &&
1733 this->operands < that.operands) ||
1734 (this->opcode == that.opcode && this->predicate == that.predicate &&
1735 this->operands == that.operands && this->indices < that.indices);
1738 bool operator!=(const ExprMapKeyType& that) const {
1739 return !(*this == that);
1747 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1748 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1749 unsigned short pred = 0) {
1750 if (Instruction::isCast(V.opcode))
1751 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1752 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1753 V.opcode < Instruction::BinaryOpsEnd))
1754 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1755 if (V.opcode == Instruction::Select)
1756 return new SelectConstantExpr(V.operands[0], V.operands[1],
1758 if (V.opcode == Instruction::ExtractElement)
1759 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1760 if (V.opcode == Instruction::InsertElement)
1761 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1763 if (V.opcode == Instruction::ShuffleVector)
1764 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1766 if (V.opcode == Instruction::InsertValue)
1767 return new InsertValueConstantExpr(V.operands[0], V.operands[1],
1769 if (V.opcode == Instruction::ExtractValue)
1770 return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
1771 if (V.opcode == Instruction::GetElementPtr) {
1772 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1773 return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
1776 // The compare instructions are weird. We have to encode the predicate
1777 // value and it is combined with the instruction opcode by multiplying
1778 // the opcode by one hundred. We must decode this to get the predicate.
1779 if (V.opcode == Instruction::ICmp)
1780 return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate,
1781 V.operands[0], V.operands[1]);
1782 if (V.opcode == Instruction::FCmp)
1783 return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate,
1784 V.operands[0], V.operands[1]);
1785 llvm_unreachable("Invalid ConstantExpr!");
1791 struct ConvertConstantType<ConstantExpr, Type> {
1792 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1794 switch (OldC->getOpcode()) {
1795 case Instruction::Trunc:
1796 case Instruction::ZExt:
1797 case Instruction::SExt:
1798 case Instruction::FPTrunc:
1799 case Instruction::FPExt:
1800 case Instruction::UIToFP:
1801 case Instruction::SIToFP:
1802 case Instruction::FPToUI:
1803 case Instruction::FPToSI:
1804 case Instruction::PtrToInt:
1805 case Instruction::IntToPtr:
1806 case Instruction::BitCast:
1807 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1810 case Instruction::Select:
1811 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1812 OldC->getOperand(1),
1813 OldC->getOperand(2));
1816 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1817 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1818 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1819 OldC->getOperand(1));
1821 case Instruction::GetElementPtr:
1822 // Make everyone now use a constant of the new type...
1823 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1824 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1825 &Idx[0], Idx.size());
1829 assert(New != OldC && "Didn't replace constant??");
1830 OldC->uncheckedReplaceAllUsesWith(New);
1831 OldC->destroyConstant(); // This constant is now dead, destroy it.
1834 } // end namespace llvm
1837 static ExprMapKeyType getValType(ConstantExpr *CE) {
1838 std::vector<Constant*> Operands;
1839 Operands.reserve(CE->getNumOperands());
1840 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1841 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1842 return ExprMapKeyType(CE->getOpcode(), Operands,
1843 CE->isCompare() ? CE->getPredicate() : 0,
1845 CE->getIndices() : SmallVector<unsigned, 4>());
1848 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1849 ConstantExpr> > ExprConstants;
1851 /// This is a utility function to handle folding of casts and lookup of the
1852 /// cast in the ExprConstants map. It is used by the various get* methods below.
1853 static inline Constant *getFoldedCast(
1854 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1855 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1856 // Fold a few common cases
1858 ConstantFoldCastInstruction(getGlobalContext(), opc, C, Ty))
1861 // Look up the constant in the table first to ensure uniqueness
1862 std::vector<Constant*> argVec(1, C);
1863 ExprMapKeyType Key(opc, argVec);
1865 // Implicitly locked.
1866 return ExprConstants->getOrCreate(Ty, Key);
1869 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1870 Instruction::CastOps opc = Instruction::CastOps(oc);
1871 assert(Instruction::isCast(opc) && "opcode out of range");
1872 assert(C && Ty && "Null arguments to getCast");
1873 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1877 llvm_unreachable("Invalid cast opcode");
1879 case Instruction::Trunc: return getTrunc(C, Ty);
1880 case Instruction::ZExt: return getZExt(C, Ty);
1881 case Instruction::SExt: return getSExt(C, Ty);
1882 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1883 case Instruction::FPExt: return getFPExtend(C, Ty);
1884 case Instruction::UIToFP: return getUIToFP(C, Ty);
1885 case Instruction::SIToFP: return getSIToFP(C, Ty);
1886 case Instruction::FPToUI: return getFPToUI(C, Ty);
1887 case Instruction::FPToSI: return getFPToSI(C, Ty);
1888 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1889 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1890 case Instruction::BitCast: return getBitCast(C, Ty);
1895 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1896 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1897 return getCast(Instruction::BitCast, C, Ty);
1898 return getCast(Instruction::ZExt, C, Ty);
1901 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1902 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1903 return getCast(Instruction::BitCast, C, Ty);
1904 return getCast(Instruction::SExt, C, Ty);
1907 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1908 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1909 return getCast(Instruction::BitCast, C, Ty);
1910 return getCast(Instruction::Trunc, C, Ty);
1913 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1914 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1915 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1917 if (Ty->isInteger())
1918 return getCast(Instruction::PtrToInt, S, Ty);
1919 return getCast(Instruction::BitCast, S, Ty);
1922 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1924 assert(C->getType()->isIntOrIntVector() &&
1925 Ty->isIntOrIntVector() && "Invalid cast");
1926 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1927 unsigned DstBits = Ty->getScalarSizeInBits();
1928 Instruction::CastOps opcode =
1929 (SrcBits == DstBits ? Instruction::BitCast :
1930 (SrcBits > DstBits ? Instruction::Trunc :
1931 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1932 return getCast(opcode, C, Ty);
1935 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1936 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1938 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1939 unsigned DstBits = Ty->getScalarSizeInBits();
1940 if (SrcBits == DstBits)
1941 return C; // Avoid a useless cast
1942 Instruction::CastOps opcode =
1943 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1944 return getCast(opcode, C, Ty);
1947 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1949 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1950 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1952 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1953 assert(C->getType()->isIntOrIntVector() && "Trunc operand must be integer");
1954 assert(Ty->isIntOrIntVector() && "Trunc produces only integral");
1955 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1956 "SrcTy must be larger than DestTy for Trunc!");
1958 return getFoldedCast(Instruction::Trunc, C, Ty);
1961 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1963 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1964 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1966 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1967 assert(C->getType()->isIntOrIntVector() && "SExt operand must be integral");
1968 assert(Ty->isIntOrIntVector() && "SExt produces only integer");
1969 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1970 "SrcTy must be smaller than DestTy for SExt!");
1972 return getFoldedCast(Instruction::SExt, C, Ty);
1975 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1977 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1978 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1980 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1981 assert(C->getType()->isIntOrIntVector() && "ZEXt operand must be integral");
1982 assert(Ty->isIntOrIntVector() && "ZExt produces only integer");
1983 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1984 "SrcTy must be smaller than DestTy for ZExt!");
1986 return getFoldedCast(Instruction::ZExt, C, Ty);
1989 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1991 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1992 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1994 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1995 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1996 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1997 "This is an illegal floating point truncation!");
1998 return getFoldedCast(Instruction::FPTrunc, C, Ty);
2001 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
2003 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2004 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2006 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2007 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2008 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
2009 "This is an illegal floating point extension!");
2010 return getFoldedCast(Instruction::FPExt, C, Ty);
2013 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
2015 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2016 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2018 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2019 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
2020 "This is an illegal uint to floating point cast!");
2021 return getFoldedCast(Instruction::UIToFP, C, Ty);
2024 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
2026 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2027 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2029 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2030 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
2031 "This is an illegal sint to floating point cast!");
2032 return getFoldedCast(Instruction::SIToFP, C, Ty);
2035 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
2037 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2038 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2040 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2041 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
2042 "This is an illegal floating point to uint cast!");
2043 return getFoldedCast(Instruction::FPToUI, C, Ty);
2046 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
2048 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2049 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2051 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2052 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
2053 "This is an illegal floating point to sint cast!");
2054 return getFoldedCast(Instruction::FPToSI, C, Ty);
2057 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
2058 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
2059 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
2060 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
2063 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
2064 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
2065 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
2066 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
2069 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
2070 // BitCast implies a no-op cast of type only. No bits change. However, you
2071 // can't cast pointers to anything but pointers.
2073 const Type *SrcTy = C->getType();
2074 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
2075 "BitCast cannot cast pointer to non-pointer and vice versa");
2077 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
2078 // or nonptr->ptr). For all the other types, the cast is okay if source and
2079 // destination bit widths are identical.
2080 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
2081 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
2083 assert(SrcBitSize == DstBitSize && "BitCast requires types of same width");
2085 // It is common to ask for a bitcast of a value to its own type, handle this
2087 if (C->getType() == DstTy) return C;
2089 return getFoldedCast(Instruction::BitCast, C, DstTy);
2092 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
2093 Constant *C1, Constant *C2) {
2094 // Check the operands for consistency first
2095 assert(Opcode >= Instruction::BinaryOpsBegin &&
2096 Opcode < Instruction::BinaryOpsEnd &&
2097 "Invalid opcode in binary constant expression");
2098 assert(C1->getType() == C2->getType() &&
2099 "Operand types in binary constant expression should match");
2101 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
2102 if (Constant *FC = ConstantFoldBinaryInstruction(
2103 getGlobalContext(), Opcode, C1, C2))
2104 return FC; // Fold a few common cases...
2106 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
2107 ExprMapKeyType Key(Opcode, argVec);
2109 // Implicitly locked.
2110 return ExprConstants->getOrCreate(ReqTy, Key);
2113 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
2114 Constant *C1, Constant *C2) {
2115 switch (predicate) {
2116 default: llvm_unreachable("Invalid CmpInst predicate");
2117 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
2118 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
2119 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
2120 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
2121 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
2122 case CmpInst::FCMP_TRUE:
2123 return getFCmp(predicate, C1, C2);
2125 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
2126 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
2127 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
2128 case CmpInst::ICMP_SLE:
2129 return getICmp(predicate, C1, C2);
2133 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
2134 // API compatibility: Adjust integer opcodes to floating-point opcodes.
2135 if (C1->getType()->isFPOrFPVector()) {
2136 if (Opcode == Instruction::Add) Opcode = Instruction::FAdd;
2137 else if (Opcode == Instruction::Sub) Opcode = Instruction::FSub;
2138 else if (Opcode == Instruction::Mul) Opcode = Instruction::FMul;
2142 case Instruction::Add:
2143 case Instruction::Sub:
2144 case Instruction::Mul:
2145 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2146 assert(C1->getType()->isIntOrIntVector() &&
2147 "Tried to create an integer operation on a non-integer type!");
2149 case Instruction::FAdd:
2150 case Instruction::FSub:
2151 case Instruction::FMul:
2152 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2153 assert(C1->getType()->isFPOrFPVector() &&
2154 "Tried to create a floating-point operation on a "
2155 "non-floating-point type!");
2157 case Instruction::UDiv:
2158 case Instruction::SDiv:
2159 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2160 assert(C1->getType()->isIntOrIntVector() &&
2161 "Tried to create an arithmetic operation on a non-arithmetic type!");
2163 case Instruction::FDiv:
2164 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2165 assert(C1->getType()->isFPOrFPVector() &&
2166 "Tried to create an arithmetic operation on a non-arithmetic type!");
2168 case Instruction::URem:
2169 case Instruction::SRem:
2170 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2171 assert(C1->getType()->isIntOrIntVector() &&
2172 "Tried to create an arithmetic operation on a non-arithmetic type!");
2174 case Instruction::FRem:
2175 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2176 assert(C1->getType()->isFPOrFPVector() &&
2177 "Tried to create an arithmetic operation on a non-arithmetic type!");
2179 case Instruction::And:
2180 case Instruction::Or:
2181 case Instruction::Xor:
2182 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2183 assert(C1->getType()->isIntOrIntVector() &&
2184 "Tried to create a logical operation on a non-integral type!");
2186 case Instruction::Shl:
2187 case Instruction::LShr:
2188 case Instruction::AShr:
2189 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2190 assert(C1->getType()->isIntOrIntVector() &&
2191 "Tried to create a shift operation on a non-integer type!");
2198 return getTy(C1->getType(), Opcode, C1, C2);
2201 Constant *ConstantExpr::getCompare(unsigned short pred,
2202 Constant *C1, Constant *C2) {
2203 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2204 return getCompareTy(pred, C1, C2);
2207 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
2208 Constant *V1, Constant *V2) {
2209 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
2211 if (ReqTy == V1->getType())
2212 if (Constant *SC = ConstantFoldSelectInstruction(
2213 getGlobalContext(), C, V1, V2))
2214 return SC; // Fold common cases
2216 std::vector<Constant*> argVec(3, C);
2219 ExprMapKeyType Key(Instruction::Select, argVec);
2221 // Implicitly locked.
2222 return ExprConstants->getOrCreate(ReqTy, Key);
2225 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
2228 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
2230 cast<PointerType>(ReqTy)->getElementType() &&
2231 "GEP indices invalid!");
2233 if (Constant *FC = ConstantFoldGetElementPtr(
2234 getGlobalContext(), C, (Constant**)Idxs, NumIdx))
2235 return FC; // Fold a few common cases...
2237 assert(isa<PointerType>(C->getType()) &&
2238 "Non-pointer type for constant GetElementPtr expression");
2239 // Look up the constant in the table first to ensure uniqueness
2240 std::vector<Constant*> ArgVec;
2241 ArgVec.reserve(NumIdx+1);
2242 ArgVec.push_back(C);
2243 for (unsigned i = 0; i != NumIdx; ++i)
2244 ArgVec.push_back(cast<Constant>(Idxs[i]));
2245 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
2247 // Implicitly locked.
2248 return ExprConstants->getOrCreate(ReqTy, Key);
2251 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
2253 // Get the result type of the getelementptr!
2255 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
2256 assert(Ty && "GEP indices invalid!");
2257 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
2258 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
2261 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
2263 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
2268 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2269 assert(LHS->getType() == RHS->getType());
2270 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2271 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
2273 if (Constant *FC = ConstantFoldCompareInstruction(
2274 getGlobalContext(),pred, LHS, RHS))
2275 return FC; // Fold a few common cases...
2277 // Look up the constant in the table first to ensure uniqueness
2278 std::vector<Constant*> ArgVec;
2279 ArgVec.push_back(LHS);
2280 ArgVec.push_back(RHS);
2281 // Get the key type with both the opcode and predicate
2282 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
2284 // Implicitly locked.
2285 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2289 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2290 assert(LHS->getType() == RHS->getType());
2291 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
2293 if (Constant *FC = ConstantFoldCompareInstruction(
2294 getGlobalContext(), pred, LHS, RHS))
2295 return FC; // Fold a few common cases...
2297 // Look up the constant in the table first to ensure uniqueness
2298 std::vector<Constant*> ArgVec;
2299 ArgVec.push_back(LHS);
2300 ArgVec.push_back(RHS);
2301 // Get the key type with both the opcode and predicate
2302 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
2304 // Implicitly locked.
2305 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2308 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
2310 if (Constant *FC = ConstantFoldExtractElementInstruction(
2311 getGlobalContext(), Val, Idx))
2312 return FC; // Fold a few common cases...
2313 // Look up the constant in the table first to ensure uniqueness
2314 std::vector<Constant*> ArgVec(1, Val);
2315 ArgVec.push_back(Idx);
2316 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
2318 // Implicitly locked.
2319 return ExprConstants->getOrCreate(ReqTy, Key);
2322 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
2323 assert(isa<VectorType>(Val->getType()) &&
2324 "Tried to create extractelement operation on non-vector type!");
2325 assert(Idx->getType() == Type::Int32Ty &&
2326 "Extractelement index must be i32 type!");
2327 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
2331 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
2332 Constant *Elt, Constant *Idx) {
2333 if (Constant *FC = ConstantFoldInsertElementInstruction(
2334 getGlobalContext(), Val, Elt, Idx))
2335 return FC; // Fold a few common cases...
2336 // Look up the constant in the table first to ensure uniqueness
2337 std::vector<Constant*> ArgVec(1, Val);
2338 ArgVec.push_back(Elt);
2339 ArgVec.push_back(Idx);
2340 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
2342 // Implicitly locked.
2343 return ExprConstants->getOrCreate(ReqTy, Key);
2346 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2348 assert(isa<VectorType>(Val->getType()) &&
2349 "Tried to create insertelement operation on non-vector type!");
2350 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
2351 && "Insertelement types must match!");
2352 assert(Idx->getType() == Type::Int32Ty &&
2353 "Insertelement index must be i32 type!");
2354 return getInsertElementTy(Val->getType(), Val, Elt, Idx);
2357 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
2358 Constant *V2, Constant *Mask) {
2359 if (Constant *FC = ConstantFoldShuffleVectorInstruction(
2360 getGlobalContext(), V1, V2, Mask))
2361 return FC; // Fold a few common cases...
2362 // Look up the constant in the table first to ensure uniqueness
2363 std::vector<Constant*> ArgVec(1, V1);
2364 ArgVec.push_back(V2);
2365 ArgVec.push_back(Mask);
2366 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
2368 // Implicitly locked.
2369 return ExprConstants->getOrCreate(ReqTy, Key);
2372 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2374 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2375 "Invalid shuffle vector constant expr operands!");
2377 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
2378 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
2379 const Type *ShufTy = VectorType::get(EltTy, NElts);
2380 return getShuffleVectorTy(ShufTy, V1, V2, Mask);
2383 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
2385 const unsigned *Idxs, unsigned NumIdx) {
2386 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2387 Idxs+NumIdx) == Val->getType() &&
2388 "insertvalue indices invalid!");
2389 assert(Agg->getType() == ReqTy &&
2390 "insertvalue type invalid!");
2391 assert(Agg->getType()->isFirstClassType() &&
2392 "Non-first-class type for constant InsertValue expression");
2393 Constant *FC = ConstantFoldInsertValueInstruction(
2394 getGlobalContext(), Agg, Val, Idxs, NumIdx);
2395 assert(FC && "InsertValue constant expr couldn't be folded!");
2399 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
2400 const unsigned *IdxList, unsigned NumIdx) {
2401 assert(Agg->getType()->isFirstClassType() &&
2402 "Tried to create insertelement operation on non-first-class type!");
2404 const Type *ReqTy = Agg->getType();
2407 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2409 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
2410 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
2413 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
2414 const unsigned *Idxs, unsigned NumIdx) {
2415 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2416 Idxs+NumIdx) == ReqTy &&
2417 "extractvalue indices invalid!");
2418 assert(Agg->getType()->isFirstClassType() &&
2419 "Non-first-class type for constant extractvalue expression");
2420 Constant *FC = ConstantFoldExtractValueInstruction(
2421 getGlobalContext(), Agg, Idxs, NumIdx);
2422 assert(FC && "ExtractValue constant expr couldn't be folded!");
2426 Constant *ConstantExpr::getExtractValue(Constant *Agg,
2427 const unsigned *IdxList, unsigned NumIdx) {
2428 assert(Agg->getType()->isFirstClassType() &&
2429 "Tried to create extractelement operation on non-first-class type!");
2432 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2433 assert(ReqTy && "extractvalue indices invalid!");
2434 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
2437 // destroyConstant - Remove the constant from the constant table...
2439 void ConstantExpr::destroyConstant() {
2440 // Implicitly locked.
2441 ExprConstants->remove(this);
2442 destroyConstantImpl();
2445 const char *ConstantExpr::getOpcodeName() const {
2446 return Instruction::getOpcodeName(getOpcode());
2449 //===----------------------------------------------------------------------===//
2450 // replaceUsesOfWithOnConstant implementations
2452 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2453 /// 'From' to be uses of 'To'. This must update the uniquing data structures
2456 /// Note that we intentionally replace all uses of From with To here. Consider
2457 /// a large array that uses 'From' 1000 times. By handling this case all here,
2458 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2459 /// single invocation handles all 1000 uses. Handling them one at a time would
2460 /// work, but would be really slow because it would have to unique each updated
2462 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
2464 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2465 Constant *ToC = cast<Constant>(To);
2467 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
2468 Lookup.first.first = getType();
2469 Lookup.second = this;
2471 std::vector<Constant*> &Values = Lookup.first.second;
2472 Values.reserve(getNumOperands()); // Build replacement array.
2474 // Fill values with the modified operands of the constant array. Also,
2475 // compute whether this turns into an all-zeros array.
2476 bool isAllZeros = false;
2477 unsigned NumUpdated = 0;
2478 if (!ToC->isNullValue()) {
2479 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2480 Constant *Val = cast<Constant>(O->get());
2485 Values.push_back(Val);
2489 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2490 Constant *Val = cast<Constant>(O->get());
2495 Values.push_back(Val);
2496 if (isAllZeros) isAllZeros = Val->isNullValue();
2500 Constant *Replacement = 0;
2502 Replacement = ConstantAggregateZero::get(getType());
2504 // Check to see if we have this array type already.
2505 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
2507 ArrayConstantsTy::MapTy::iterator I =
2508 ArrayConstants->InsertOrGetItem(Lookup, Exists);
2511 Replacement = I->second;
2513 // Okay, the new shape doesn't exist in the system yet. Instead of
2514 // creating a new constant array, inserting it, replaceallusesof'ing the
2515 // old with the new, then deleting the old... just update the current one
2517 ArrayConstants->MoveConstantToNewSlot(this, I);
2519 // Update to the new value. Optimize for the case when we have a single
2520 // operand that we're changing, but handle bulk updates efficiently.
2521 if (NumUpdated == 1) {
2522 unsigned OperandToUpdate = U-OperandList;
2523 assert(getOperand(OperandToUpdate) == From &&
2524 "ReplaceAllUsesWith broken!");
2525 setOperand(OperandToUpdate, ToC);
2527 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2528 if (getOperand(i) == From)
2535 // Otherwise, I do need to replace this with an existing value.
2536 assert(Replacement != this && "I didn't contain From!");
2538 // Everyone using this now uses the replacement.
2539 uncheckedReplaceAllUsesWith(Replacement);
2541 // Delete the old constant!
2545 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2547 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2548 Constant *ToC = cast<Constant>(To);
2550 unsigned OperandToUpdate = U-OperandList;
2551 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2553 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
2554 Lookup.first.first = getType();
2555 Lookup.second = this;
2556 std::vector<Constant*> &Values = Lookup.first.second;
2557 Values.reserve(getNumOperands()); // Build replacement struct.
2560 // Fill values with the modified operands of the constant struct. Also,
2561 // compute whether this turns into an all-zeros struct.
2562 bool isAllZeros = false;
2563 if (!ToC->isNullValue()) {
2564 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2565 Values.push_back(cast<Constant>(O->get()));
2568 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2569 Constant *Val = cast<Constant>(O->get());
2570 Values.push_back(Val);
2571 if (isAllZeros) isAllZeros = Val->isNullValue();
2574 Values[OperandToUpdate] = ToC;
2576 Constant *Replacement = 0;
2578 Replacement = ConstantAggregateZero::get(getType());
2580 // Check to see if we have this array type already.
2581 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
2583 StructConstantsTy::MapTy::iterator I =
2584 StructConstants->InsertOrGetItem(Lookup, Exists);
2587 Replacement = I->second;
2589 // Okay, the new shape doesn't exist in the system yet. Instead of
2590 // creating a new constant struct, inserting it, replaceallusesof'ing the
2591 // old with the new, then deleting the old... just update the current one
2593 StructConstants->MoveConstantToNewSlot(this, I);
2595 // Update to the new value.
2596 setOperand(OperandToUpdate, ToC);
2601 assert(Replacement != this && "I didn't contain From!");
2603 // Everyone using this now uses the replacement.
2604 uncheckedReplaceAllUsesWith(Replacement);
2606 // Delete the old constant!
2610 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2612 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2614 std::vector<Constant*> Values;
2615 Values.reserve(getNumOperands()); // Build replacement array...
2616 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2617 Constant *Val = getOperand(i);
2618 if (Val == From) Val = cast<Constant>(To);
2619 Values.push_back(Val);
2622 Constant *Replacement = ConstantVector::get(getType(), Values);
2623 assert(Replacement != this && "I didn't contain From!");
2625 // Everyone using this now uses the replacement.
2626 uncheckedReplaceAllUsesWith(Replacement);
2628 // Delete the old constant!
2632 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2634 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2635 Constant *To = cast<Constant>(ToV);
2637 Constant *Replacement = 0;
2638 if (getOpcode() == Instruction::GetElementPtr) {
2639 SmallVector<Constant*, 8> Indices;
2640 Constant *Pointer = getOperand(0);
2641 Indices.reserve(getNumOperands()-1);
2642 if (Pointer == From) Pointer = To;
2644 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2645 Constant *Val = getOperand(i);
2646 if (Val == From) Val = To;
2647 Indices.push_back(Val);
2649 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2650 &Indices[0], Indices.size());
2651 } else if (getOpcode() == Instruction::ExtractValue) {
2652 Constant *Agg = getOperand(0);
2653 if (Agg == From) Agg = To;
2655 const SmallVector<unsigned, 4> &Indices = getIndices();
2656 Replacement = ConstantExpr::getExtractValue(Agg,
2657 &Indices[0], Indices.size());
2658 } else if (getOpcode() == Instruction::InsertValue) {
2659 Constant *Agg = getOperand(0);
2660 Constant *Val = getOperand(1);
2661 if (Agg == From) Agg = To;
2662 if (Val == From) Val = To;
2664 const SmallVector<unsigned, 4> &Indices = getIndices();
2665 Replacement = ConstantExpr::getInsertValue(Agg, Val,
2666 &Indices[0], Indices.size());
2667 } else if (isCast()) {
2668 assert(getOperand(0) == From && "Cast only has one use!");
2669 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2670 } else if (getOpcode() == Instruction::Select) {
2671 Constant *C1 = getOperand(0);
2672 Constant *C2 = getOperand(1);
2673 Constant *C3 = getOperand(2);
2674 if (C1 == From) C1 = To;
2675 if (C2 == From) C2 = To;
2676 if (C3 == From) C3 = To;
2677 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2678 } else if (getOpcode() == Instruction::ExtractElement) {
2679 Constant *C1 = getOperand(0);
2680 Constant *C2 = getOperand(1);
2681 if (C1 == From) C1 = To;
2682 if (C2 == From) C2 = To;
2683 Replacement = ConstantExpr::getExtractElement(C1, C2);
2684 } else if (getOpcode() == Instruction::InsertElement) {
2685 Constant *C1 = getOperand(0);
2686 Constant *C2 = getOperand(1);
2687 Constant *C3 = getOperand(1);
2688 if (C1 == From) C1 = To;
2689 if (C2 == From) C2 = To;
2690 if (C3 == From) C3 = To;
2691 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2692 } else if (getOpcode() == Instruction::ShuffleVector) {
2693 Constant *C1 = getOperand(0);
2694 Constant *C2 = getOperand(1);
2695 Constant *C3 = getOperand(2);
2696 if (C1 == From) C1 = To;
2697 if (C2 == From) C2 = To;
2698 if (C3 == From) C3 = To;
2699 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2700 } else if (isCompare()) {
2701 Constant *C1 = getOperand(0);
2702 Constant *C2 = getOperand(1);
2703 if (C1 == From) C1 = To;
2704 if (C2 == From) C2 = To;
2705 if (getOpcode() == Instruction::ICmp)
2706 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2708 assert(getOpcode() == Instruction::FCmp);
2709 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2711 } else if (getNumOperands() == 2) {
2712 Constant *C1 = getOperand(0);
2713 Constant *C2 = getOperand(1);
2714 if (C1 == From) C1 = To;
2715 if (C2 == From) C2 = To;
2716 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2718 llvm_unreachable("Unknown ConstantExpr type!");
2722 assert(Replacement != this && "I didn't contain From!");
2724 // Everyone using this now uses the replacement.
2725 uncheckedReplaceAllUsesWith(Replacement);
2727 // Delete the old constant!
2731 void MDNode::replaceElement(Value *From, Value *To) {
2732 SmallVector<Value*, 4> Values;
2733 Values.reserve(getNumElements()); // Build replacement array...
2734 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
2735 Value *Val = getElement(i);
2736 if (Val == From) Val = To;
2737 Values.push_back(Val);
2740 MDNode *Replacement = MDNode::get(&Values[0], Values.size());
2741 assert(Replacement != this && "I didn't contain From!");
2743 uncheckedReplaceAllUsesWith(Replacement);