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/Module.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/Support/Compiler.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/ManagedStatic.h"
24 #include "llvm/Support/MathExtras.h"
25 #include "llvm/ADT/DenseMap.h"
26 #include "llvm/ADT/SmallVector.h"
31 //===----------------------------------------------------------------------===//
33 //===----------------------------------------------------------------------===//
35 void Constant::destroyConstantImpl() {
36 // When a Constant is destroyed, there may be lingering
37 // references to the constant by other constants in the constant pool. These
38 // constants are implicitly dependent on the module that is being deleted,
39 // but they don't know that. Because we only find out when the CPV is
40 // deleted, we must now notify all of our users (that should only be
41 // Constants) that they are, in fact, invalid now and should be deleted.
43 while (!use_empty()) {
44 Value *V = use_back();
45 #ifndef NDEBUG // Only in -g mode...
46 if (!isa<Constant>(V))
47 DOUT << "While deleting: " << *this
48 << "\n\nUse still stuck around after Def is destroyed: "
51 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
52 Constant *CV = cast<Constant>(V);
53 CV->destroyConstant();
55 // The constant should remove itself from our use list...
56 assert((use_empty() || use_back() != V) && "Constant not removed!");
59 // Value has no outstanding references it is safe to delete it now...
63 /// canTrap - Return true if evaluation of this constant could trap. This is
64 /// true for things like constant expressions that could divide by zero.
65 bool Constant::canTrap() const {
66 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
67 // The only thing that could possibly trap are constant exprs.
68 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
69 if (!CE) return false;
71 // ConstantExpr traps if any operands can trap.
72 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
73 if (getOperand(i)->canTrap())
76 // Otherwise, only specific operations can trap.
77 switch (CE->getOpcode()) {
80 case Instruction::UDiv:
81 case Instruction::SDiv:
82 case Instruction::FDiv:
83 case Instruction::URem:
84 case Instruction::SRem:
85 case Instruction::FRem:
86 // Div and rem can trap if the RHS is not known to be non-zero.
87 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
93 /// ContaintsRelocations - Return true if the constant value contains
94 /// relocations which cannot be resolved at compile time.
95 bool Constant::ContainsRelocations() const {
96 if (isa<GlobalValue>(this))
98 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
99 if (getOperand(i)->ContainsRelocations())
104 // Static constructor to create a '0' constant of arbitrary type...
105 Constant *Constant::getNullValue(const Type *Ty) {
106 static uint64_t zero[2] = {0, 0};
107 switch (Ty->getTypeID()) {
108 case Type::IntegerTyID:
109 return ConstantInt::get(Ty, 0);
110 case Type::FloatTyID:
111 return ConstantFP::get(APFloat(APInt(32, 0)));
112 case Type::DoubleTyID:
113 return ConstantFP::get(APFloat(APInt(64, 0)));
114 case Type::X86_FP80TyID:
115 return ConstantFP::get(APFloat(APInt(80, 2, zero)));
116 case Type::FP128TyID:
117 return ConstantFP::get(APFloat(APInt(128, 2, zero), true));
118 case Type::PPC_FP128TyID:
119 return ConstantFP::get(APFloat(APInt(128, 2, zero)));
120 case Type::PointerTyID:
121 return ConstantPointerNull::get(cast<PointerType>(Ty));
122 case Type::StructTyID:
123 case Type::ArrayTyID:
124 case Type::VectorTyID:
125 return ConstantAggregateZero::get(Ty);
127 // Function, Label, or Opaque type?
128 assert(!"Cannot create a null constant of that type!");
133 Constant *Constant::getAllOnesValue(const Type *Ty) {
134 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
135 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
136 return ConstantVector::getAllOnesValue(cast<VectorType>(Ty));
139 // Static constructor to create an integral constant with all bits set
140 ConstantInt *ConstantInt::getAllOnesValue(const Type *Ty) {
141 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
142 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
146 /// @returns the value for a vector integer constant of the given type that
147 /// has all its bits set to true.
148 /// @brief Get the all ones value
149 ConstantVector *ConstantVector::getAllOnesValue(const VectorType *Ty) {
150 std::vector<Constant*> Elts;
151 Elts.resize(Ty->getNumElements(),
152 ConstantInt::getAllOnesValue(Ty->getElementType()));
153 assert(Elts[0] && "Not a vector integer type!");
154 return cast<ConstantVector>(ConstantVector::get(Elts));
158 /// getVectorElements - This method, which is only valid on constant of vector
159 /// type, returns the elements of the vector in the specified smallvector.
160 /// This handles breaking down a vector undef into undef elements, etc.
161 void Constant::getVectorElements(SmallVectorImpl<Constant*> &Elts) const {
162 assert(isa<VectorType>(getType()) && "Not a vector constant!");
164 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
165 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
166 Elts.push_back(CV->getOperand(i));
170 const VectorType *VT = cast<VectorType>(getType());
171 if (isa<ConstantAggregateZero>(this)) {
172 Elts.assign(VT->getNumElements(),
173 Constant::getNullValue(VT->getElementType()));
177 assert(isa<UndefValue>(this) && "Unknown vector constant type!");
178 Elts.assign(VT->getNumElements(), UndefValue::get(VT->getElementType()));
183 //===----------------------------------------------------------------------===//
185 //===----------------------------------------------------------------------===//
187 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
188 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
189 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
192 ConstantInt *ConstantInt::TheTrueVal = 0;
193 ConstantInt *ConstantInt::TheFalseVal = 0;
196 void CleanupTrueFalse(void *) {
197 ConstantInt::ResetTrueFalse();
201 static ManagedCleanup<llvm::CleanupTrueFalse> TrueFalseCleanup;
203 ConstantInt *ConstantInt::CreateTrueFalseVals(bool WhichOne) {
204 assert(TheTrueVal == 0 && TheFalseVal == 0);
205 TheTrueVal = get(Type::Int1Ty, 1);
206 TheFalseVal = get(Type::Int1Ty, 0);
208 // Ensure that llvm_shutdown nulls out TheTrueVal/TheFalseVal.
209 TrueFalseCleanup.Register();
211 return WhichOne ? TheTrueVal : TheFalseVal;
216 struct DenseMapAPIntKeyInfo {
220 KeyTy(const APInt& V, const Type* Ty) : val(V), type(Ty) {}
221 KeyTy(const KeyTy& that) : val(that.val), type(that.type) {}
222 bool operator==(const KeyTy& that) const {
223 return type == that.type && this->val == that.val;
225 bool operator!=(const KeyTy& that) const {
226 return !this->operator==(that);
229 static inline KeyTy getEmptyKey() { return KeyTy(APInt(1,0), 0); }
230 static inline KeyTy getTombstoneKey() { return KeyTy(APInt(1,1), 0); }
231 static unsigned getHashValue(const KeyTy &Key) {
232 return DenseMapInfo<void*>::getHashValue(Key.type) ^
233 Key.val.getHashValue();
235 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
238 static bool isPod() { return false; }
243 typedef DenseMap<DenseMapAPIntKeyInfo::KeyTy, ConstantInt*,
244 DenseMapAPIntKeyInfo> IntMapTy;
245 static ManagedStatic<IntMapTy> IntConstants;
247 ConstantInt *ConstantInt::get(const Type *Ty, uint64_t V, bool isSigned) {
248 const IntegerType *ITy = cast<IntegerType>(Ty);
249 return get(APInt(ITy->getBitWidth(), V, isSigned));
252 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
253 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
254 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
255 // compare APInt's of different widths, which would violate an APInt class
256 // invariant which generates an assertion.
257 ConstantInt *ConstantInt::get(const APInt& V) {
258 // Get the corresponding integer type for the bit width of the value.
259 const IntegerType *ITy = IntegerType::get(V.getBitWidth());
260 // get an existing value or the insertion position
261 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
262 ConstantInt *&Slot = (*IntConstants)[Key];
263 // if it exists, return it.
266 // otherwise create a new one, insert it, and return it.
267 return Slot = new ConstantInt(ITy, V);
270 //===----------------------------------------------------------------------===//
272 //===----------------------------------------------------------------------===//
274 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
275 if (Ty == Type::FloatTy)
276 return &APFloat::IEEEsingle;
277 if (Ty == Type::DoubleTy)
278 return &APFloat::IEEEdouble;
279 if (Ty == Type::X86_FP80Ty)
280 return &APFloat::x87DoubleExtended;
281 else if (Ty == Type::FP128Ty)
282 return &APFloat::IEEEquad;
284 assert(Ty == Type::PPC_FP128Ty && "Unknown FP format");
285 return &APFloat::PPCDoubleDouble;
288 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
289 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
290 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
294 bool ConstantFP::isNullValue() const {
295 return Val.isZero() && !Val.isNegative();
298 ConstantFP *ConstantFP::getNegativeZero(const Type *Ty) {
299 APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
301 return ConstantFP::get(apf);
304 bool ConstantFP::isExactlyValue(const APFloat& V) const {
305 return Val.bitwiseIsEqual(V);
309 struct DenseMapAPFloatKeyInfo {
312 KeyTy(const APFloat& V) : val(V){}
313 KeyTy(const KeyTy& that) : val(that.val) {}
314 bool operator==(const KeyTy& that) const {
315 return this->val.bitwiseIsEqual(that.val);
317 bool operator!=(const KeyTy& that) const {
318 return !this->operator==(that);
321 static inline KeyTy getEmptyKey() {
322 return KeyTy(APFloat(APFloat::Bogus,1));
324 static inline KeyTy getTombstoneKey() {
325 return KeyTy(APFloat(APFloat::Bogus,2));
327 static unsigned getHashValue(const KeyTy &Key) {
328 return Key.val.getHashValue();
330 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
333 static bool isPod() { return false; }
337 //---- ConstantFP::get() implementation...
339 typedef DenseMap<DenseMapAPFloatKeyInfo::KeyTy, ConstantFP*,
340 DenseMapAPFloatKeyInfo> FPMapTy;
342 static ManagedStatic<FPMapTy> FPConstants;
344 ConstantFP *ConstantFP::get(const APFloat &V) {
345 DenseMapAPFloatKeyInfo::KeyTy Key(V);
346 ConstantFP *&Slot = (*FPConstants)[Key];
347 if (Slot) return Slot;
350 if (&V.getSemantics() == &APFloat::IEEEsingle)
352 else if (&V.getSemantics() == &APFloat::IEEEdouble)
354 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
355 Ty = Type::X86_FP80Ty;
356 else if (&V.getSemantics() == &APFloat::IEEEquad)
359 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble&&"Unknown FP format");
360 Ty = Type::PPC_FP128Ty;
363 return Slot = new ConstantFP(Ty, V);
366 /// get() - This returns a constant fp for the specified value in the
367 /// specified type. This should only be used for simple constant values like
368 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
369 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
371 FV.convert(*TypeToFloatSemantics(Ty), APFloat::rmNearestTiesToEven);
375 //===----------------------------------------------------------------------===//
376 // ConstantXXX Classes
377 //===----------------------------------------------------------------------===//
380 ConstantArray::ConstantArray(const ArrayType *T,
381 const std::vector<Constant*> &V)
382 : Constant(T, ConstantArrayVal,
383 OperandTraits<ConstantArray>::op_end(this) - V.size(),
385 assert(V.size() == T->getNumElements() &&
386 "Invalid initializer vector for constant array");
387 Use *OL = OperandList;
388 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
391 assert((C->getType() == T->getElementType() ||
393 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
394 "Initializer for array element doesn't match array element type!");
400 ConstantStruct::ConstantStruct(const StructType *T,
401 const std::vector<Constant*> &V)
402 : Constant(T, ConstantStructVal,
403 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
405 assert(V.size() == T->getNumElements() &&
406 "Invalid initializer vector for constant structure");
407 Use *OL = OperandList;
408 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
411 assert((C->getType() == T->getElementType(I-V.begin()) ||
412 ((T->getElementType(I-V.begin())->isAbstract() ||
413 C->getType()->isAbstract()) &&
414 T->getElementType(I-V.begin())->getTypeID() ==
415 C->getType()->getTypeID())) &&
416 "Initializer for struct element doesn't match struct element type!");
422 ConstantVector::ConstantVector(const VectorType *T,
423 const std::vector<Constant*> &V)
424 : Constant(T, ConstantVectorVal,
425 OperandTraits<ConstantVector>::op_end(this) - V.size(),
427 Use *OL = OperandList;
428 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
431 assert((C->getType() == T->getElementType() ||
433 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
434 "Initializer for vector element doesn't match vector element type!");
441 // We declare several classes private to this file, so use an anonymous
445 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
446 /// behind the scenes to implement unary constant exprs.
447 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
448 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
450 // allocate space for exactly one operand
451 void *operator new(size_t s) {
452 return User::operator new(s, 1);
454 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
455 : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
458 /// Transparently provide more efficient getOperand methods.
459 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
462 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
463 /// behind the scenes to implement binary constant exprs.
464 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
465 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
467 // allocate space for exactly two operands
468 void *operator new(size_t s) {
469 return User::operator new(s, 2);
471 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
472 : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
476 /// Transparently provide more efficient getOperand methods.
477 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
480 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
481 /// behind the scenes to implement select constant exprs.
482 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
483 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
485 // allocate space for exactly three operands
486 void *operator new(size_t s) {
487 return User::operator new(s, 3);
489 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
490 : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
495 /// Transparently provide more efficient getOperand methods.
496 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
499 /// ExtractElementConstantExpr - This class is private to
500 /// Constants.cpp, and is used behind the scenes to implement
501 /// extractelement constant exprs.
502 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
503 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
505 // allocate space for exactly two operands
506 void *operator new(size_t s) {
507 return User::operator new(s, 2);
509 ExtractElementConstantExpr(Constant *C1, Constant *C2)
510 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
511 Instruction::ExtractElement, &Op<0>(), 2) {
515 /// Transparently provide more efficient getOperand methods.
516 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
519 /// InsertElementConstantExpr - This class is private to
520 /// Constants.cpp, and is used behind the scenes to implement
521 /// insertelement constant exprs.
522 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
523 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
525 // allocate space for exactly three operands
526 void *operator new(size_t s) {
527 return User::operator new(s, 3);
529 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
530 : ConstantExpr(C1->getType(), Instruction::InsertElement,
536 /// Transparently provide more efficient getOperand methods.
537 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
540 /// ShuffleVectorConstantExpr - This class is private to
541 /// Constants.cpp, and is used behind the scenes to implement
542 /// shufflevector constant exprs.
543 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
544 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
546 // allocate space for exactly three operands
547 void *operator new(size_t s) {
548 return User::operator new(s, 3);
550 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
551 : ConstantExpr(C1->getType(), Instruction::ShuffleVector,
557 /// Transparently provide more efficient getOperand methods.
558 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
561 /// ExtractValueConstantExpr - This class is private to
562 /// Constants.cpp, and is used behind the scenes to implement
563 /// extractvalue constant exprs.
564 class VISIBILITY_HIDDEN ExtractValueConstantExpr : public ConstantExpr {
565 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
567 // allocate space for exactly one operand
568 void *operator new(size_t s) {
569 return User::operator new(s, 1);
571 ExtractValueConstantExpr(Constant *Agg,
572 const SmallVector<unsigned, 4> &IdxList,
574 : ConstantExpr(DestTy, Instruction::ExtractValue, &Op<0>(), 1),
579 /// Indices - These identify which value to extract.
580 const SmallVector<unsigned, 4> Indices;
582 /// Transparently provide more efficient getOperand methods.
583 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
586 /// InsertValueConstantExpr - This class is private to
587 /// Constants.cpp, and is used behind the scenes to implement
588 /// insertvalue constant exprs.
589 class VISIBILITY_HIDDEN InsertValueConstantExpr : public ConstantExpr {
590 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
592 // allocate space for exactly one operand
593 void *operator new(size_t s) {
594 return User::operator new(s, 2);
596 InsertValueConstantExpr(Constant *Agg, Constant *Val,
597 const SmallVector<unsigned, 4> &IdxList,
599 : ConstantExpr(DestTy, Instruction::InsertValue, &Op<0>(), 2),
605 /// Indices - These identify the position for the insertion.
606 const SmallVector<unsigned, 4> Indices;
608 /// Transparently provide more efficient getOperand methods.
609 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
613 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
614 /// used behind the scenes to implement getelementpr constant exprs.
615 class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
616 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
619 static GetElementPtrConstantExpr *Create(Constant *C,
620 const std::vector<Constant*>&IdxList,
621 const Type *DestTy) {
622 return new(IdxList.size() + 1)
623 GetElementPtrConstantExpr(C, IdxList, DestTy);
625 /// Transparently provide more efficient getOperand methods.
626 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
629 // CompareConstantExpr - This class is private to Constants.cpp, and is used
630 // behind the scenes to implement ICmp and FCmp constant expressions. This is
631 // needed in order to store the predicate value for these instructions.
632 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
633 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
634 // allocate space for exactly two operands
635 void *operator new(size_t s) {
636 return User::operator new(s, 2);
638 unsigned short predicate;
639 CompareConstantExpr(const Type *ty, Instruction::OtherOps opc,
640 unsigned short pred, Constant* LHS, Constant* RHS)
641 : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
645 /// Transparently provide more efficient getOperand methods.
646 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
649 } // end anonymous namespace
652 struct OperandTraits<UnaryConstantExpr> : FixedNumOperandTraits<1> {
654 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
657 struct OperandTraits<BinaryConstantExpr> : FixedNumOperandTraits<2> {
659 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
662 struct OperandTraits<SelectConstantExpr> : FixedNumOperandTraits<3> {
664 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
667 struct OperandTraits<ExtractElementConstantExpr> : FixedNumOperandTraits<2> {
669 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
672 struct OperandTraits<InsertElementConstantExpr> : FixedNumOperandTraits<3> {
674 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
677 struct OperandTraits<ShuffleVectorConstantExpr> : FixedNumOperandTraits<3> {
679 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
682 struct OperandTraits<ExtractValueConstantExpr> : FixedNumOperandTraits<1> {
684 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractValueConstantExpr, Value)
687 struct OperandTraits<InsertValueConstantExpr> : FixedNumOperandTraits<2> {
689 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueConstantExpr, Value)
692 struct OperandTraits<GetElementPtrConstantExpr> : VariadicOperandTraits<1> {
695 GetElementPtrConstantExpr::GetElementPtrConstantExpr
697 const std::vector<Constant*> &IdxList,
699 : ConstantExpr(DestTy, Instruction::GetElementPtr,
700 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
701 - (IdxList.size()+1),
704 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
705 OperandList[i+1] = IdxList[i];
708 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
712 struct OperandTraits<CompareConstantExpr> : FixedNumOperandTraits<2> {
714 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
717 } // End llvm namespace
720 // Utility function for determining if a ConstantExpr is a CastOp or not. This
721 // can't be inline because we don't want to #include Instruction.h into
723 bool ConstantExpr::isCast() const {
724 return Instruction::isCast(getOpcode());
727 bool ConstantExpr::isCompare() const {
728 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
731 bool ConstantExpr::hasIndices() const {
732 return getOpcode() == Instruction::ExtractValue ||
733 getOpcode() == Instruction::InsertValue;
736 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
737 if (const ExtractValueConstantExpr *EVCE =
738 dyn_cast<ExtractValueConstantExpr>(this))
739 return EVCE->Indices;
741 return cast<InsertValueConstantExpr>(this)->Indices;
744 /// ConstantExpr::get* - Return some common constants without having to
745 /// specify the full Instruction::OPCODE identifier.
747 Constant *ConstantExpr::getNeg(Constant *C) {
748 return get(Instruction::Sub,
749 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
752 Constant *ConstantExpr::getNot(Constant *C) {
753 assert(isa<IntegerType>(C->getType()) && "Cannot NOT a nonintegral value!");
754 return get(Instruction::Xor, C,
755 ConstantInt::getAllOnesValue(C->getType()));
757 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
758 return get(Instruction::Add, C1, C2);
760 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
761 return get(Instruction::Sub, C1, C2);
763 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
764 return get(Instruction::Mul, C1, C2);
766 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
767 return get(Instruction::UDiv, C1, C2);
769 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
770 return get(Instruction::SDiv, C1, C2);
772 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
773 return get(Instruction::FDiv, C1, C2);
775 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
776 return get(Instruction::URem, C1, C2);
778 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
779 return get(Instruction::SRem, C1, C2);
781 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
782 return get(Instruction::FRem, C1, C2);
784 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
785 return get(Instruction::And, C1, C2);
787 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
788 return get(Instruction::Or, C1, C2);
790 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
791 return get(Instruction::Xor, C1, C2);
793 unsigned ConstantExpr::getPredicate() const {
794 assert(getOpcode() == Instruction::FCmp ||
795 getOpcode() == Instruction::ICmp ||
796 getOpcode() == Instruction::VFCmp ||
797 getOpcode() == Instruction::VICmp);
798 return ((const CompareConstantExpr*)this)->predicate;
800 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
801 return get(Instruction::Shl, C1, C2);
803 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
804 return get(Instruction::LShr, C1, C2);
806 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
807 return get(Instruction::AShr, C1, C2);
810 /// getWithOperandReplaced - Return a constant expression identical to this
811 /// one, but with the specified operand set to the specified value.
813 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
814 assert(OpNo < getNumOperands() && "Operand num is out of range!");
815 assert(Op->getType() == getOperand(OpNo)->getType() &&
816 "Replacing operand with value of different type!");
817 if (getOperand(OpNo) == Op)
818 return const_cast<ConstantExpr*>(this);
820 Constant *Op0, *Op1, *Op2;
821 switch (getOpcode()) {
822 case Instruction::Trunc:
823 case Instruction::ZExt:
824 case Instruction::SExt:
825 case Instruction::FPTrunc:
826 case Instruction::FPExt:
827 case Instruction::UIToFP:
828 case Instruction::SIToFP:
829 case Instruction::FPToUI:
830 case Instruction::FPToSI:
831 case Instruction::PtrToInt:
832 case Instruction::IntToPtr:
833 case Instruction::BitCast:
834 return ConstantExpr::getCast(getOpcode(), Op, getType());
835 case Instruction::Select:
836 Op0 = (OpNo == 0) ? Op : getOperand(0);
837 Op1 = (OpNo == 1) ? Op : getOperand(1);
838 Op2 = (OpNo == 2) ? Op : getOperand(2);
839 return ConstantExpr::getSelect(Op0, Op1, Op2);
840 case Instruction::InsertElement:
841 Op0 = (OpNo == 0) ? Op : getOperand(0);
842 Op1 = (OpNo == 1) ? Op : getOperand(1);
843 Op2 = (OpNo == 2) ? Op : getOperand(2);
844 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
845 case Instruction::ExtractElement:
846 Op0 = (OpNo == 0) ? Op : getOperand(0);
847 Op1 = (OpNo == 1) ? Op : getOperand(1);
848 return ConstantExpr::getExtractElement(Op0, Op1);
849 case Instruction::ShuffleVector:
850 Op0 = (OpNo == 0) ? Op : getOperand(0);
851 Op1 = (OpNo == 1) ? Op : getOperand(1);
852 Op2 = (OpNo == 2) ? Op : getOperand(2);
853 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
854 case Instruction::InsertValue: {
855 const SmallVector<unsigned, 4> &Indices = getIndices();
856 Op0 = (OpNo == 0) ? Op : getOperand(0);
857 Op1 = (OpNo == 1) ? Op : getOperand(1);
858 return ConstantExpr::getInsertValue(Op0, Op1,
859 &Indices[0], Indices.size());
861 case Instruction::ExtractValue: {
862 assert(OpNo == 0 && "ExtractaValue has only one operand!");
863 const SmallVector<unsigned, 4> &Indices = getIndices();
865 ConstantExpr::getExtractValue(Op, &Indices[0], Indices.size());
867 case Instruction::GetElementPtr: {
868 SmallVector<Constant*, 8> Ops;
869 Ops.resize(getNumOperands()-1);
870 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
871 Ops[i-1] = getOperand(i);
873 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
875 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
878 assert(getNumOperands() == 2 && "Must be binary operator?");
879 Op0 = (OpNo == 0) ? Op : getOperand(0);
880 Op1 = (OpNo == 1) ? Op : getOperand(1);
881 return ConstantExpr::get(getOpcode(), Op0, Op1);
885 /// getWithOperands - This returns the current constant expression with the
886 /// operands replaced with the specified values. The specified operands must
887 /// match count and type with the existing ones.
888 Constant *ConstantExpr::
889 getWithOperands(const std::vector<Constant*> &Ops) const {
890 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
891 bool AnyChange = false;
892 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
893 assert(Ops[i]->getType() == getOperand(i)->getType() &&
894 "Operand type mismatch!");
895 AnyChange |= Ops[i] != getOperand(i);
897 if (!AnyChange) // No operands changed, return self.
898 return const_cast<ConstantExpr*>(this);
900 switch (getOpcode()) {
901 case Instruction::Trunc:
902 case Instruction::ZExt:
903 case Instruction::SExt:
904 case Instruction::FPTrunc:
905 case Instruction::FPExt:
906 case Instruction::UIToFP:
907 case Instruction::SIToFP:
908 case Instruction::FPToUI:
909 case Instruction::FPToSI:
910 case Instruction::PtrToInt:
911 case Instruction::IntToPtr:
912 case Instruction::BitCast:
913 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
914 case Instruction::Select:
915 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
916 case Instruction::InsertElement:
917 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
918 case Instruction::ExtractElement:
919 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
920 case Instruction::ShuffleVector:
921 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
922 case Instruction::InsertValue: {
923 const SmallVector<unsigned, 4> &Indices = getIndices();
924 return ConstantExpr::getInsertValue(Ops[0], Ops[1],
925 &Indices[0], Indices.size());
927 case Instruction::ExtractValue: {
928 const SmallVector<unsigned, 4> &Indices = getIndices();
929 return ConstantExpr::getExtractValue(Ops[0],
930 &Indices[0], Indices.size());
932 case Instruction::GetElementPtr:
933 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], Ops.size()-1);
934 case Instruction::ICmp:
935 case Instruction::FCmp:
936 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
938 assert(getNumOperands() == 2 && "Must be binary operator?");
939 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
944 //===----------------------------------------------------------------------===//
945 // isValueValidForType implementations
947 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
948 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
949 if (Ty == Type::Int1Ty)
950 return Val == 0 || Val == 1;
952 return true; // always true, has to fit in largest type
953 uint64_t Max = (1ll << NumBits) - 1;
957 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
958 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
959 if (Ty == Type::Int1Ty)
960 return Val == 0 || Val == 1 || Val == -1;
962 return true; // always true, has to fit in largest type
963 int64_t Min = -(1ll << (NumBits-1));
964 int64_t Max = (1ll << (NumBits-1)) - 1;
965 return (Val >= Min && Val <= Max);
968 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
969 // convert modifies in place, so make a copy.
970 APFloat Val2 = APFloat(Val);
971 switch (Ty->getTypeID()) {
973 return false; // These can't be represented as floating point!
975 // FIXME rounding mode needs to be more flexible
976 case Type::FloatTyID:
977 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
978 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven) ==
980 case Type::DoubleTyID:
981 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
982 &Val2.getSemantics() == &APFloat::IEEEdouble ||
983 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven) ==
985 case Type::X86_FP80TyID:
986 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
987 &Val2.getSemantics() == &APFloat::IEEEdouble ||
988 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
989 case Type::FP128TyID:
990 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
991 &Val2.getSemantics() == &APFloat::IEEEdouble ||
992 &Val2.getSemantics() == &APFloat::IEEEquad;
993 case Type::PPC_FP128TyID:
994 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
995 &Val2.getSemantics() == &APFloat::IEEEdouble ||
996 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
1000 //===----------------------------------------------------------------------===//
1001 // Factory Function Implementation
1004 // The number of operands for each ConstantCreator::create method is
1005 // determined by the ConstantTraits template.
1006 // ConstantCreator - A class that is used to create constants by
1007 // ValueMap*. This class should be partially specialized if there is
1008 // something strange that needs to be done to interface to the ctor for the
1012 template<class ValType>
1013 struct ConstantTraits;
1015 template<typename T, typename Alloc>
1016 struct VISIBILITY_HIDDEN ConstantTraits< std::vector<T, Alloc> > {
1017 static unsigned uses(const std::vector<T, Alloc>& v) {
1022 template<class ConstantClass, class TypeClass, class ValType>
1023 struct VISIBILITY_HIDDEN ConstantCreator {
1024 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
1025 return new(ConstantTraits<ValType>::uses(V)) ConstantClass(Ty, V);
1029 template<class ConstantClass, class TypeClass>
1030 struct VISIBILITY_HIDDEN ConvertConstantType {
1031 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
1032 assert(0 && "This type cannot be converted!\n");
1037 template<class ValType, class TypeClass, class ConstantClass,
1038 bool HasLargeKey = false /*true for arrays and structs*/ >
1039 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
1041 typedef std::pair<const Type*, ValType> MapKey;
1042 typedef std::map<MapKey, Constant *> MapTy;
1043 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
1044 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
1046 /// Map - This is the main map from the element descriptor to the Constants.
1047 /// This is the primary way we avoid creating two of the same shape
1051 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
1052 /// from the constants to their element in Map. This is important for
1053 /// removal of constants from the array, which would otherwise have to scan
1054 /// through the map with very large keys.
1055 InverseMapTy InverseMap;
1057 /// AbstractTypeMap - Map for abstract type constants.
1059 AbstractTypeMapTy AbstractTypeMap;
1062 typename MapTy::iterator map_end() { return Map.end(); }
1064 /// InsertOrGetItem - Return an iterator for the specified element.
1065 /// If the element exists in the map, the returned iterator points to the
1066 /// entry and Exists=true. If not, the iterator points to the newly
1067 /// inserted entry and returns Exists=false. Newly inserted entries have
1068 /// I->second == 0, and should be filled in.
1069 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
1072 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
1073 Exists = !IP.second;
1078 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
1080 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
1081 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
1082 IMI->second->second == CP &&
1083 "InverseMap corrupt!");
1087 typename MapTy::iterator I =
1088 Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
1089 if (I == Map.end() || I->second != CP) {
1090 // FIXME: This should not use a linear scan. If this gets to be a
1091 // performance problem, someone should look at this.
1092 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
1099 /// getOrCreate - Return the specified constant from the map, creating it if
1101 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
1102 MapKey Lookup(Ty, V);
1103 typename MapTy::iterator I = Map.lower_bound(Lookup);
1104 // Is it in the map?
1105 if (I != Map.end() && I->first == Lookup)
1106 return static_cast<ConstantClass *>(I->second);
1108 // If no preexisting value, create one now...
1109 ConstantClass *Result =
1110 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
1112 /// FIXME: why does this assert fail when loading 176.gcc?
1113 //assert(Result->getType() == Ty && "Type specified is not correct!");
1114 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
1116 if (HasLargeKey) // Remember the reverse mapping if needed.
1117 InverseMap.insert(std::make_pair(Result, I));
1119 // If the type of the constant is abstract, make sure that an entry exists
1120 // for it in the AbstractTypeMap.
1121 if (Ty->isAbstract()) {
1122 typename AbstractTypeMapTy::iterator TI =
1123 AbstractTypeMap.lower_bound(Ty);
1125 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
1126 // Add ourselves to the ATU list of the type.
1127 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
1129 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
1135 void remove(ConstantClass *CP) {
1136 typename MapTy::iterator I = FindExistingElement(CP);
1137 assert(I != Map.end() && "Constant not found in constant table!");
1138 assert(I->second == CP && "Didn't find correct element?");
1140 if (HasLargeKey) // Remember the reverse mapping if needed.
1141 InverseMap.erase(CP);
1143 // Now that we found the entry, make sure this isn't the entry that
1144 // the AbstractTypeMap points to.
1145 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
1146 if (Ty->isAbstract()) {
1147 assert(AbstractTypeMap.count(Ty) &&
1148 "Abstract type not in AbstractTypeMap?");
1149 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
1150 if (ATMEntryIt == I) {
1151 // Yes, we are removing the representative entry for this type.
1152 // See if there are any other entries of the same type.
1153 typename MapTy::iterator TmpIt = ATMEntryIt;
1155 // First check the entry before this one...
1156 if (TmpIt != Map.begin()) {
1158 if (TmpIt->first.first != Ty) // Not the same type, move back...
1162 // If we didn't find the same type, try to move forward...
1163 if (TmpIt == ATMEntryIt) {
1165 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
1166 --TmpIt; // No entry afterwards with the same type
1169 // If there is another entry in the map of the same abstract type,
1170 // update the AbstractTypeMap entry now.
1171 if (TmpIt != ATMEntryIt) {
1174 // Otherwise, we are removing the last instance of this type
1175 // from the table. Remove from the ATM, and from user list.
1176 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
1177 AbstractTypeMap.erase(Ty);
1186 /// MoveConstantToNewSlot - If we are about to change C to be the element
1187 /// specified by I, update our internal data structures to reflect this
1189 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
1190 // First, remove the old location of the specified constant in the map.
1191 typename MapTy::iterator OldI = FindExistingElement(C);
1192 assert(OldI != Map.end() && "Constant not found in constant table!");
1193 assert(OldI->second == C && "Didn't find correct element?");
1195 // If this constant is the representative element for its abstract type,
1196 // update the AbstractTypeMap so that the representative element is I.
1197 if (C->getType()->isAbstract()) {
1198 typename AbstractTypeMapTy::iterator ATI =
1199 AbstractTypeMap.find(C->getType());
1200 assert(ATI != AbstractTypeMap.end() &&
1201 "Abstract type not in AbstractTypeMap?");
1202 if (ATI->second == OldI)
1206 // Remove the old entry from the map.
1209 // Update the inverse map so that we know that this constant is now
1210 // located at descriptor I.
1212 assert(I->second == C && "Bad inversemap entry!");
1217 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
1218 typename AbstractTypeMapTy::iterator I =
1219 AbstractTypeMap.find(cast<Type>(OldTy));
1221 assert(I != AbstractTypeMap.end() &&
1222 "Abstract type not in AbstractTypeMap?");
1224 // Convert a constant at a time until the last one is gone. The last one
1225 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
1226 // eliminated eventually.
1228 ConvertConstantType<ConstantClass,
1229 TypeClass>::convert(
1230 static_cast<ConstantClass *>(I->second->second),
1231 cast<TypeClass>(NewTy));
1233 I = AbstractTypeMap.find(cast<Type>(OldTy));
1234 } while (I != AbstractTypeMap.end());
1237 // If the type became concrete without being refined to any other existing
1238 // type, we just remove ourselves from the ATU list.
1239 void typeBecameConcrete(const DerivedType *AbsTy) {
1240 AbsTy->removeAbstractTypeUser(this);
1244 DOUT << "Constant.cpp: ValueMap\n";
1251 //---- ConstantAggregateZero::get() implementation...
1254 // ConstantAggregateZero does not take extra "value" argument...
1255 template<class ValType>
1256 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
1257 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
1258 return new ConstantAggregateZero(Ty);
1263 struct ConvertConstantType<ConstantAggregateZero, Type> {
1264 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1265 // Make everyone now use a constant of the new type...
1266 Constant *New = ConstantAggregateZero::get(NewTy);
1267 assert(New != OldC && "Didn't replace constant??");
1268 OldC->uncheckedReplaceAllUsesWith(New);
1269 OldC->destroyConstant(); // This constant is now dead, destroy it.
1274 static ManagedStatic<ValueMap<char, Type,
1275 ConstantAggregateZero> > AggZeroConstants;
1277 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1279 Constant *ConstantAggregateZero::get(const Type *Ty) {
1280 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
1281 "Cannot create an aggregate zero of non-aggregate type!");
1282 return AggZeroConstants->getOrCreate(Ty, 0);
1285 // destroyConstant - Remove the constant from the constant table...
1287 void ConstantAggregateZero::destroyConstant() {
1288 AggZeroConstants->remove(this);
1289 destroyConstantImpl();
1292 //---- ConstantArray::get() implementation...
1296 struct ConvertConstantType<ConstantArray, ArrayType> {
1297 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1298 // Make everyone now use a constant of the new type...
1299 std::vector<Constant*> C;
1300 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1301 C.push_back(cast<Constant>(OldC->getOperand(i)));
1302 Constant *New = ConstantArray::get(NewTy, C);
1303 assert(New != OldC && "Didn't replace constant??");
1304 OldC->uncheckedReplaceAllUsesWith(New);
1305 OldC->destroyConstant(); // This constant is now dead, destroy it.
1310 static std::vector<Constant*> getValType(ConstantArray *CA) {
1311 std::vector<Constant*> Elements;
1312 Elements.reserve(CA->getNumOperands());
1313 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1314 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1318 typedef ValueMap<std::vector<Constant*>, ArrayType,
1319 ConstantArray, true /*largekey*/> ArrayConstantsTy;
1320 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
1322 Constant *ConstantArray::get(const ArrayType *Ty,
1323 const std::vector<Constant*> &V) {
1324 // If this is an all-zero array, return a ConstantAggregateZero object
1327 if (!C->isNullValue())
1328 return ArrayConstants->getOrCreate(Ty, V);
1329 for (unsigned i = 1, e = V.size(); i != e; ++i)
1331 return ArrayConstants->getOrCreate(Ty, V);
1333 return ConstantAggregateZero::get(Ty);
1336 // destroyConstant - Remove the constant from the constant table...
1338 void ConstantArray::destroyConstant() {
1339 ArrayConstants->remove(this);
1340 destroyConstantImpl();
1343 /// ConstantArray::get(const string&) - Return an array that is initialized to
1344 /// contain the specified string. If length is zero then a null terminator is
1345 /// added to the specified string so that it may be used in a natural way.
1346 /// Otherwise, the length parameter specifies how much of the string to use
1347 /// and it won't be null terminated.
1349 Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
1350 std::vector<Constant*> ElementVals;
1351 for (unsigned i = 0; i < Str.length(); ++i)
1352 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
1354 // Add a null terminator to the string...
1356 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
1359 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
1360 return ConstantArray::get(ATy, ElementVals);
1363 /// isString - This method returns true if the array is an array of i8, and
1364 /// if the elements of the array are all ConstantInt's.
1365 bool ConstantArray::isString() const {
1366 // Check the element type for i8...
1367 if (getType()->getElementType() != Type::Int8Ty)
1369 // Check the elements to make sure they are all integers, not constant
1371 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1372 if (!isa<ConstantInt>(getOperand(i)))
1377 /// isCString - This method returns true if the array is a string (see
1378 /// isString) and it ends in a null byte \0 and does not contains any other
1379 /// null bytes except its terminator.
1380 bool ConstantArray::isCString() const {
1381 // Check the element type for i8...
1382 if (getType()->getElementType() != Type::Int8Ty)
1384 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1385 // Last element must be a null.
1386 if (getOperand(getNumOperands()-1) != Zero)
1388 // Other elements must be non-null integers.
1389 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1390 if (!isa<ConstantInt>(getOperand(i)))
1392 if (getOperand(i) == Zero)
1399 // getAsString - If the sub-element type of this array is i8
1400 // then this method converts the array to an std::string and returns it.
1401 // Otherwise, it asserts out.
1403 std::string ConstantArray::getAsString() const {
1404 assert(isString() && "Not a string!");
1406 Result.reserve(getNumOperands());
1407 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1408 Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
1413 //---- ConstantStruct::get() implementation...
1418 struct ConvertConstantType<ConstantStruct, StructType> {
1419 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1420 // Make everyone now use a constant of the new type...
1421 std::vector<Constant*> C;
1422 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1423 C.push_back(cast<Constant>(OldC->getOperand(i)));
1424 Constant *New = ConstantStruct::get(NewTy, C);
1425 assert(New != OldC && "Didn't replace constant??");
1427 OldC->uncheckedReplaceAllUsesWith(New);
1428 OldC->destroyConstant(); // This constant is now dead, destroy it.
1433 typedef ValueMap<std::vector<Constant*>, StructType,
1434 ConstantStruct, true /*largekey*/> StructConstantsTy;
1435 static ManagedStatic<StructConstantsTy> StructConstants;
1437 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1438 std::vector<Constant*> Elements;
1439 Elements.reserve(CS->getNumOperands());
1440 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1441 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1445 Constant *ConstantStruct::get(const StructType *Ty,
1446 const std::vector<Constant*> &V) {
1447 // Create a ConstantAggregateZero value if all elements are zeros...
1448 for (unsigned i = 0, e = V.size(); i != e; ++i)
1449 if (!V[i]->isNullValue())
1450 return StructConstants->getOrCreate(Ty, V);
1452 return ConstantAggregateZero::get(Ty);
1455 Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
1456 std::vector<const Type*> StructEls;
1457 StructEls.reserve(V.size());
1458 for (unsigned i = 0, e = V.size(); i != e; ++i)
1459 StructEls.push_back(V[i]->getType());
1460 return get(StructType::get(StructEls, packed), V);
1463 // destroyConstant - Remove the constant from the constant table...
1465 void ConstantStruct::destroyConstant() {
1466 StructConstants->remove(this);
1467 destroyConstantImpl();
1470 //---- ConstantVector::get() implementation...
1474 struct ConvertConstantType<ConstantVector, VectorType> {
1475 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
1476 // Make everyone now use a constant of the new type...
1477 std::vector<Constant*> C;
1478 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1479 C.push_back(cast<Constant>(OldC->getOperand(i)));
1480 Constant *New = ConstantVector::get(NewTy, C);
1481 assert(New != OldC && "Didn't replace constant??");
1482 OldC->uncheckedReplaceAllUsesWith(New);
1483 OldC->destroyConstant(); // This constant is now dead, destroy it.
1488 static std::vector<Constant*> getValType(ConstantVector *CP) {
1489 std::vector<Constant*> Elements;
1490 Elements.reserve(CP->getNumOperands());
1491 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1492 Elements.push_back(CP->getOperand(i));
1496 static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
1497 ConstantVector> > VectorConstants;
1499 Constant *ConstantVector::get(const VectorType *Ty,
1500 const std::vector<Constant*> &V) {
1501 assert(!V.empty() && "Vectors can't be empty");
1502 // If this is an all-undef or alll-zero vector, return a
1503 // ConstantAggregateZero or UndefValue.
1505 bool isZero = C->isNullValue();
1506 bool isUndef = isa<UndefValue>(C);
1508 if (isZero || isUndef) {
1509 for (unsigned i = 1, e = V.size(); i != e; ++i)
1511 isZero = isUndef = false;
1517 return ConstantAggregateZero::get(Ty);
1519 return UndefValue::get(Ty);
1520 return VectorConstants->getOrCreate(Ty, V);
1523 Constant *ConstantVector::get(const std::vector<Constant*> &V) {
1524 assert(!V.empty() && "Cannot infer type if V is empty");
1525 return get(VectorType::get(V.front()->getType(),V.size()), V);
1528 // destroyConstant - Remove the constant from the constant table...
1530 void ConstantVector::destroyConstant() {
1531 VectorConstants->remove(this);
1532 destroyConstantImpl();
1535 /// This function will return true iff every element in this vector constant
1536 /// is set to all ones.
1537 /// @returns true iff this constant's emements are all set to all ones.
1538 /// @brief Determine if the value is all ones.
1539 bool ConstantVector::isAllOnesValue() const {
1540 // Check out first element.
1541 const Constant *Elt = getOperand(0);
1542 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1543 if (!CI || !CI->isAllOnesValue()) return false;
1544 // Then make sure all remaining elements point to the same value.
1545 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1546 if (getOperand(I) != Elt) return false;
1551 /// getSplatValue - If this is a splat constant, where all of the
1552 /// elements have the same value, return that value. Otherwise return null.
1553 Constant *ConstantVector::getSplatValue() {
1554 // Check out first element.
1555 Constant *Elt = getOperand(0);
1556 // Then make sure all remaining elements point to the same value.
1557 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1558 if (getOperand(I) != Elt) return 0;
1562 //---- ConstantPointerNull::get() implementation...
1566 // ConstantPointerNull does not take extra "value" argument...
1567 template<class ValType>
1568 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1569 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1570 return new ConstantPointerNull(Ty);
1575 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1576 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1577 // Make everyone now use a constant of the new type...
1578 Constant *New = ConstantPointerNull::get(NewTy);
1579 assert(New != OldC && "Didn't replace constant??");
1580 OldC->uncheckedReplaceAllUsesWith(New);
1581 OldC->destroyConstant(); // This constant is now dead, destroy it.
1586 static ManagedStatic<ValueMap<char, PointerType,
1587 ConstantPointerNull> > NullPtrConstants;
1589 static char getValType(ConstantPointerNull *) {
1594 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1595 return NullPtrConstants->getOrCreate(Ty, 0);
1598 // destroyConstant - Remove the constant from the constant table...
1600 void ConstantPointerNull::destroyConstant() {
1601 NullPtrConstants->remove(this);
1602 destroyConstantImpl();
1606 //---- UndefValue::get() implementation...
1610 // UndefValue does not take extra "value" argument...
1611 template<class ValType>
1612 struct ConstantCreator<UndefValue, Type, ValType> {
1613 static UndefValue *create(const Type *Ty, const ValType &V) {
1614 return new UndefValue(Ty);
1619 struct ConvertConstantType<UndefValue, Type> {
1620 static void convert(UndefValue *OldC, const Type *NewTy) {
1621 // Make everyone now use a constant of the new type.
1622 Constant *New = UndefValue::get(NewTy);
1623 assert(New != OldC && "Didn't replace constant??");
1624 OldC->uncheckedReplaceAllUsesWith(New);
1625 OldC->destroyConstant(); // This constant is now dead, destroy it.
1630 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1632 static char getValType(UndefValue *) {
1637 UndefValue *UndefValue::get(const Type *Ty) {
1638 return UndefValueConstants->getOrCreate(Ty, 0);
1641 // destroyConstant - Remove the constant from the constant table.
1643 void UndefValue::destroyConstant() {
1644 UndefValueConstants->remove(this);
1645 destroyConstantImpl();
1649 //---- ConstantExpr::get() implementations...
1654 struct ExprMapKeyType {
1655 typedef SmallVector<unsigned, 4> IndexList;
1657 ExprMapKeyType(unsigned opc,
1658 const std::vector<Constant*> &ops,
1659 unsigned short pred = 0,
1660 const IndexList &inds = IndexList())
1661 : opcode(opc), predicate(pred), operands(ops), indices(inds) {}
1664 std::vector<Constant*> operands;
1666 bool operator==(const ExprMapKeyType& that) const {
1667 return this->opcode == that.opcode &&
1668 this->predicate == that.predicate &&
1669 this->operands == that.operands;
1670 this->indices == that.indices;
1672 bool operator<(const ExprMapKeyType & that) const {
1673 return this->opcode < that.opcode ||
1674 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1675 (this->opcode == that.opcode && this->predicate == that.predicate &&
1676 this->operands < that.operands) ||
1677 (this->opcode == that.opcode && this->predicate == that.predicate &&
1678 this->operands == that.operands && this->indices < that.indices);
1681 bool operator!=(const ExprMapKeyType& that) const {
1682 return !(*this == that);
1690 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1691 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1692 unsigned short pred = 0) {
1693 if (Instruction::isCast(V.opcode))
1694 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1695 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1696 V.opcode < Instruction::BinaryOpsEnd))
1697 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1698 if (V.opcode == Instruction::Select)
1699 return new SelectConstantExpr(V.operands[0], V.operands[1],
1701 if (V.opcode == Instruction::ExtractElement)
1702 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1703 if (V.opcode == Instruction::InsertElement)
1704 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1706 if (V.opcode == Instruction::ShuffleVector)
1707 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1709 if (V.opcode == Instruction::InsertValue)
1710 return new InsertValueConstantExpr(V.operands[0], V.operands[1],
1712 if (V.opcode == Instruction::ExtractValue)
1713 return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
1714 if (V.opcode == Instruction::GetElementPtr) {
1715 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1716 return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
1719 // The compare instructions are weird. We have to encode the predicate
1720 // value and it is combined with the instruction opcode by multiplying
1721 // the opcode by one hundred. We must decode this to get the predicate.
1722 if (V.opcode == Instruction::ICmp)
1723 return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate,
1724 V.operands[0], V.operands[1]);
1725 if (V.opcode == Instruction::FCmp)
1726 return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate,
1727 V.operands[0], V.operands[1]);
1728 if (V.opcode == Instruction::VICmp)
1729 return new CompareConstantExpr(Ty, Instruction::VICmp, V.predicate,
1730 V.operands[0], V.operands[1]);
1731 if (V.opcode == Instruction::VFCmp)
1732 return new CompareConstantExpr(Ty, Instruction::VFCmp, V.predicate,
1733 V.operands[0], V.operands[1]);
1734 assert(0 && "Invalid ConstantExpr!");
1740 struct ConvertConstantType<ConstantExpr, Type> {
1741 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1743 switch (OldC->getOpcode()) {
1744 case Instruction::Trunc:
1745 case Instruction::ZExt:
1746 case Instruction::SExt:
1747 case Instruction::FPTrunc:
1748 case Instruction::FPExt:
1749 case Instruction::UIToFP:
1750 case Instruction::SIToFP:
1751 case Instruction::FPToUI:
1752 case Instruction::FPToSI:
1753 case Instruction::PtrToInt:
1754 case Instruction::IntToPtr:
1755 case Instruction::BitCast:
1756 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1759 case Instruction::Select:
1760 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1761 OldC->getOperand(1),
1762 OldC->getOperand(2));
1765 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1766 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1767 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1768 OldC->getOperand(1));
1770 case Instruction::GetElementPtr:
1771 // Make everyone now use a constant of the new type...
1772 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1773 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1774 &Idx[0], Idx.size());
1778 assert(New != OldC && "Didn't replace constant??");
1779 OldC->uncheckedReplaceAllUsesWith(New);
1780 OldC->destroyConstant(); // This constant is now dead, destroy it.
1783 } // end namespace llvm
1786 static ExprMapKeyType getValType(ConstantExpr *CE) {
1787 std::vector<Constant*> Operands;
1788 Operands.reserve(CE->getNumOperands());
1789 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1790 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1791 return ExprMapKeyType(CE->getOpcode(), Operands,
1792 CE->isCompare() ? CE->getPredicate() : 0,
1794 CE->getIndices() : SmallVector<unsigned, 4>());
1797 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1798 ConstantExpr> > ExprConstants;
1800 /// This is a utility function to handle folding of casts and lookup of the
1801 /// cast in the ExprConstants map. It is used by the various get* methods below.
1802 static inline Constant *getFoldedCast(
1803 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1804 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1805 // Fold a few common cases
1806 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1809 // Look up the constant in the table first to ensure uniqueness
1810 std::vector<Constant*> argVec(1, C);
1811 ExprMapKeyType Key(opc, argVec);
1812 return ExprConstants->getOrCreate(Ty, Key);
1815 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1816 Instruction::CastOps opc = Instruction::CastOps(oc);
1817 assert(Instruction::isCast(opc) && "opcode out of range");
1818 assert(C && Ty && "Null arguments to getCast");
1819 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1823 assert(0 && "Invalid cast opcode");
1825 case Instruction::Trunc: return getTrunc(C, Ty);
1826 case Instruction::ZExt: return getZExt(C, Ty);
1827 case Instruction::SExt: return getSExt(C, Ty);
1828 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1829 case Instruction::FPExt: return getFPExtend(C, Ty);
1830 case Instruction::UIToFP: return getUIToFP(C, Ty);
1831 case Instruction::SIToFP: return getSIToFP(C, Ty);
1832 case Instruction::FPToUI: return getFPToUI(C, Ty);
1833 case Instruction::FPToSI: return getFPToSI(C, Ty);
1834 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1835 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1836 case Instruction::BitCast: return getBitCast(C, Ty);
1841 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1842 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1843 return getCast(Instruction::BitCast, C, Ty);
1844 return getCast(Instruction::ZExt, C, Ty);
1847 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1848 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1849 return getCast(Instruction::BitCast, C, Ty);
1850 return getCast(Instruction::SExt, C, Ty);
1853 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1854 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1855 return getCast(Instruction::BitCast, C, Ty);
1856 return getCast(Instruction::Trunc, C, Ty);
1859 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1860 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1861 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1863 if (Ty->isInteger())
1864 return getCast(Instruction::PtrToInt, S, Ty);
1865 return getCast(Instruction::BitCast, S, Ty);
1868 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1870 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1871 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1872 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1873 Instruction::CastOps opcode =
1874 (SrcBits == DstBits ? Instruction::BitCast :
1875 (SrcBits > DstBits ? Instruction::Trunc :
1876 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1877 return getCast(opcode, C, Ty);
1880 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1881 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1883 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1884 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1885 if (SrcBits == DstBits)
1886 return C; // Avoid a useless cast
1887 Instruction::CastOps opcode =
1888 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1889 return getCast(opcode, C, Ty);
1892 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1893 assert(C->getType()->isInteger() && "Trunc operand must be integer");
1894 assert(Ty->isInteger() && "Trunc produces only integral");
1895 assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1896 "SrcTy must be larger than DestTy for Trunc!");
1898 return getFoldedCast(Instruction::Trunc, C, Ty);
1901 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1902 assert(C->getType()->isInteger() && "SEXt operand must be integral");
1903 assert(Ty->isInteger() && "SExt produces only integer");
1904 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1905 "SrcTy must be smaller than DestTy for SExt!");
1907 return getFoldedCast(Instruction::SExt, C, Ty);
1910 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1911 assert(C->getType()->isInteger() && "ZEXt operand must be integral");
1912 assert(Ty->isInteger() && "ZExt produces only integer");
1913 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1914 "SrcTy must be smaller than DestTy for ZExt!");
1916 return getFoldedCast(Instruction::ZExt, C, Ty);
1919 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1920 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1921 C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1922 "This is an illegal floating point truncation!");
1923 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1926 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1927 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1928 C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1929 "This is an illegal floating point extension!");
1930 return getFoldedCast(Instruction::FPExt, C, Ty);
1933 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1934 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1935 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1936 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1937 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1938 "This is an illegal uint to floating point cast!");
1939 return getFoldedCast(Instruction::UIToFP, C, Ty);
1942 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1943 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1944 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1945 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1946 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1947 "This is an illegal sint to floating point cast!");
1948 return getFoldedCast(Instruction::SIToFP, C, Ty);
1951 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1952 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1953 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1954 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1955 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1956 "This is an illegal floating point to uint cast!");
1957 return getFoldedCast(Instruction::FPToUI, C, Ty);
1960 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1961 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1962 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1963 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1964 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1965 "This is an illegal floating point to sint cast!");
1966 return getFoldedCast(Instruction::FPToSI, C, Ty);
1969 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1970 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1971 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1972 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1975 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1976 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1977 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1978 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1981 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1982 // BitCast implies a no-op cast of type only. No bits change. However, you
1983 // can't cast pointers to anything but pointers.
1984 const Type *SrcTy = C->getType();
1985 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1986 "BitCast cannot cast pointer to non-pointer and vice versa");
1988 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1989 // or nonptr->ptr). For all the other types, the cast is okay if source and
1990 // destination bit widths are identical.
1991 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1992 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1993 assert(SrcBitSize == DstBitSize && "BitCast requies types of same width");
1994 return getFoldedCast(Instruction::BitCast, C, DstTy);
1997 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
1998 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1999 Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
2001 getGetElementPtr(getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
2002 return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
2005 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
2006 Constant *C1, Constant *C2) {
2007 // Check the operands for consistency first
2008 assert(Opcode >= Instruction::BinaryOpsBegin &&
2009 Opcode < Instruction::BinaryOpsEnd &&
2010 "Invalid opcode in binary constant expression");
2011 assert(C1->getType() == C2->getType() &&
2012 "Operand types in binary constant expression should match");
2014 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
2015 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
2016 return FC; // Fold a few common cases...
2018 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
2019 ExprMapKeyType Key(Opcode, argVec);
2020 return ExprConstants->getOrCreate(ReqTy, Key);
2023 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
2024 Constant *C1, Constant *C2) {
2025 switch (predicate) {
2026 default: assert(0 && "Invalid CmpInst predicate");
2027 case FCmpInst::FCMP_FALSE: case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_OGT:
2028 case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OLE:
2029 case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_ORD: case FCmpInst::FCMP_UNO:
2030 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UGT: case FCmpInst::FCMP_UGE:
2031 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_ULE: case FCmpInst::FCMP_UNE:
2032 case FCmpInst::FCMP_TRUE:
2033 return getFCmp(predicate, C1, C2);
2034 case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGT:
2035 case ICmpInst::ICMP_UGE: case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE:
2036 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_SGE: case ICmpInst::ICMP_SLT:
2037 case ICmpInst::ICMP_SLE:
2038 return getICmp(predicate, C1, C2);
2042 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
2045 case Instruction::Add:
2046 case Instruction::Sub:
2047 case Instruction::Mul:
2048 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2049 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
2050 isa<VectorType>(C1->getType())) &&
2051 "Tried to create an arithmetic operation on a non-arithmetic type!");
2053 case Instruction::UDiv:
2054 case Instruction::SDiv:
2055 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2056 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
2057 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
2058 "Tried to create an arithmetic operation on a non-arithmetic type!");
2060 case Instruction::FDiv:
2061 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2062 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
2063 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
2064 && "Tried to create an arithmetic operation on a non-arithmetic type!");
2066 case Instruction::URem:
2067 case Instruction::SRem:
2068 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2069 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
2070 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
2071 "Tried to create an arithmetic operation on a non-arithmetic type!");
2073 case Instruction::FRem:
2074 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2075 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
2076 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
2077 && "Tried to create an arithmetic operation on a non-arithmetic type!");
2079 case Instruction::And:
2080 case Instruction::Or:
2081 case Instruction::Xor:
2082 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2083 assert((C1->getType()->isInteger() || isa<VectorType>(C1->getType())) &&
2084 "Tried to create a logical operation on a non-integral type!");
2086 case Instruction::Shl:
2087 case Instruction::LShr:
2088 case Instruction::AShr:
2089 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2090 assert(C1->getType()->isInteger() &&
2091 "Tried to create a shift operation on a non-integer type!");
2098 return getTy(C1->getType(), Opcode, C1, C2);
2101 Constant *ConstantExpr::getCompare(unsigned short pred,
2102 Constant *C1, Constant *C2) {
2103 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2104 return getCompareTy(pred, C1, C2);
2107 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
2108 Constant *V1, Constant *V2) {
2109 assert(C->getType() == Type::Int1Ty && "Select condition must be i1!");
2110 assert(V1->getType() == V2->getType() && "Select value types must match!");
2111 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
2113 if (ReqTy == V1->getType())
2114 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
2115 return SC; // Fold common cases
2117 std::vector<Constant*> argVec(3, C);
2120 ExprMapKeyType Key(Instruction::Select, argVec);
2121 return ExprConstants->getOrCreate(ReqTy, Key);
2124 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
2127 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
2129 cast<PointerType>(ReqTy)->getElementType() &&
2130 "GEP indices invalid!");
2132 if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs, NumIdx))
2133 return FC; // Fold a few common cases...
2135 assert(isa<PointerType>(C->getType()) &&
2136 "Non-pointer type for constant GetElementPtr expression");
2137 // Look up the constant in the table first to ensure uniqueness
2138 std::vector<Constant*> ArgVec;
2139 ArgVec.reserve(NumIdx+1);
2140 ArgVec.push_back(C);
2141 for (unsigned i = 0; i != NumIdx; ++i)
2142 ArgVec.push_back(cast<Constant>(Idxs[i]));
2143 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
2144 return ExprConstants->getOrCreate(ReqTy, Key);
2147 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
2149 // Get the result type of the getelementptr!
2151 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
2152 assert(Ty && "GEP indices invalid!");
2153 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
2154 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
2157 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
2159 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
2164 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2165 assert(LHS->getType() == RHS->getType());
2166 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2167 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
2169 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2170 return FC; // Fold a few common cases...
2172 // Look up the constant in the table first to ensure uniqueness
2173 std::vector<Constant*> ArgVec;
2174 ArgVec.push_back(LHS);
2175 ArgVec.push_back(RHS);
2176 // Get the key type with both the opcode and predicate
2177 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
2178 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2182 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2183 assert(LHS->getType() == RHS->getType());
2184 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
2186 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2187 return FC; // Fold a few common cases...
2189 // Look up the constant in the table first to ensure uniqueness
2190 std::vector<Constant*> ArgVec;
2191 ArgVec.push_back(LHS);
2192 ArgVec.push_back(RHS);
2193 // Get the key type with both the opcode and predicate
2194 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
2195 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2199 ConstantExpr::getVICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2200 assert(isa<VectorType>(LHS->getType()) &&
2201 "Tried to create vicmp operation on non-vector type!");
2202 assert(LHS->getType() == RHS->getType());
2203 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2204 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid VICmp Predicate");
2206 const VectorType *VTy = cast<VectorType>(LHS->getType());
2207 const Type *EltTy = VTy->getElementType();
2208 unsigned NumElts = VTy->getNumElements();
2210 SmallVector<Constant *, 8> Elts;
2211 for (unsigned i = 0; i != NumElts; ++i) {
2212 Constant *FC = ConstantFoldCompareInstruction(pred, LHS->getOperand(i),
2213 RHS->getOperand(i));
2215 uint64_t Val = cast<ConstantInt>(FC)->getZExtValue();
2217 Elts.push_back(ConstantInt::getAllOnesValue(EltTy));
2219 Elts.push_back(ConstantInt::get(EltTy, 0ULL));
2222 if (Elts.size() == NumElts)
2223 return ConstantVector::get(&Elts[0], Elts.size());
2225 // Look up the constant in the table first to ensure uniqueness
2226 std::vector<Constant*> ArgVec;
2227 ArgVec.push_back(LHS);
2228 ArgVec.push_back(RHS);
2229 // Get the key type with both the opcode and predicate
2230 const ExprMapKeyType Key(Instruction::VICmp, ArgVec, pred);
2231 return ExprConstants->getOrCreate(LHS->getType(), Key);
2235 ConstantExpr::getVFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2236 assert(isa<VectorType>(LHS->getType()) &&
2237 "Tried to create vfcmp operation on non-vector type!");
2238 assert(LHS->getType() == RHS->getType());
2239 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid VFCmp Predicate");
2241 const VectorType *VTy = cast<VectorType>(LHS->getType());
2242 unsigned NumElts = VTy->getNumElements();
2243 const Type *EltTy = VTy->getElementType();
2244 const Type *REltTy = IntegerType::get(EltTy->getPrimitiveSizeInBits());
2245 const Type *ResultTy = VectorType::get(REltTy, NumElts);
2247 SmallVector<Constant *, 8> Elts;
2248 for (unsigned i = 0; i != NumElts; ++i) {
2249 Constant *FC = ConstantFoldCompareInstruction(pred, LHS->getOperand(i),
2250 RHS->getOperand(i));
2252 uint64_t Val = cast<ConstantInt>(FC)->getZExtValue();
2254 Elts.push_back(ConstantInt::getAllOnesValue(REltTy));
2256 Elts.push_back(ConstantInt::get(REltTy, 0ULL));
2259 if (Elts.size() == NumElts)
2260 return ConstantVector::get(&Elts[0], Elts.size());
2262 // Look up the constant in the table first to ensure uniqueness
2263 std::vector<Constant*> ArgVec;
2264 ArgVec.push_back(LHS);
2265 ArgVec.push_back(RHS);
2266 // Get the key type with both the opcode and predicate
2267 const ExprMapKeyType Key(Instruction::VFCmp, ArgVec, pred);
2268 return ExprConstants->getOrCreate(ResultTy, Key);
2271 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
2273 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
2274 return FC; // Fold a few common cases...
2275 // Look up the constant in the table first to ensure uniqueness
2276 std::vector<Constant*> ArgVec(1, Val);
2277 ArgVec.push_back(Idx);
2278 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
2279 return ExprConstants->getOrCreate(ReqTy, Key);
2282 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
2283 assert(isa<VectorType>(Val->getType()) &&
2284 "Tried to create extractelement operation on non-vector type!");
2285 assert(Idx->getType() == Type::Int32Ty &&
2286 "Extractelement index must be i32 type!");
2287 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
2291 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
2292 Constant *Elt, Constant *Idx) {
2293 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2294 return FC; // Fold a few common cases...
2295 // Look up the constant in the table first to ensure uniqueness
2296 std::vector<Constant*> ArgVec(1, Val);
2297 ArgVec.push_back(Elt);
2298 ArgVec.push_back(Idx);
2299 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
2300 return ExprConstants->getOrCreate(ReqTy, Key);
2303 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2305 assert(isa<VectorType>(Val->getType()) &&
2306 "Tried to create insertelement operation on non-vector type!");
2307 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
2308 && "Insertelement types must match!");
2309 assert(Idx->getType() == Type::Int32Ty &&
2310 "Insertelement index must be i32 type!");
2311 return getInsertElementTy(cast<VectorType>(Val->getType())->getElementType(),
2315 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
2316 Constant *V2, Constant *Mask) {
2317 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2318 return FC; // Fold a few common cases...
2319 // Look up the constant in the table first to ensure uniqueness
2320 std::vector<Constant*> ArgVec(1, V1);
2321 ArgVec.push_back(V2);
2322 ArgVec.push_back(Mask);
2323 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
2324 return ExprConstants->getOrCreate(ReqTy, Key);
2327 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2329 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2330 "Invalid shuffle vector constant expr operands!");
2331 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
2334 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
2336 const unsigned *Idxs, unsigned NumIdx) {
2337 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2338 Idxs+NumIdx) == Val->getType() &&
2339 "insertvalue indices invalid!");
2340 assert(Agg->getType() == ReqTy &&
2341 "insertvalue type invalid!");
2342 assert(Agg->getType()->isFirstClassType() &&
2343 "Non-first-class type for constant InsertValue expression");
2344 if (Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs, NumIdx))
2345 return FC; // Fold a few common cases...
2346 // Look up the constant in the table first to ensure uniqueness
2347 std::vector<Constant*> ArgVec;
2348 ArgVec.push_back(Agg);
2349 ArgVec.push_back(Val);
2350 SmallVector<unsigned, 4> Indices(Idxs, Idxs + NumIdx);
2351 const ExprMapKeyType Key(Instruction::InsertValue, ArgVec, 0, Indices);
2352 return ExprConstants->getOrCreate(ReqTy, Key);
2355 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
2356 const unsigned *IdxList, unsigned NumIdx) {
2357 assert(Agg->getType()->isFirstClassType() &&
2358 "Tried to create insertelement operation on non-first-class type!");
2360 const Type *ReqTy = Agg->getType();
2362 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2363 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
2364 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
2367 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
2368 const unsigned *Idxs, unsigned NumIdx) {
2369 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2370 Idxs+NumIdx) == ReqTy &&
2371 "extractvalue indices invalid!");
2372 assert(Agg->getType()->isFirstClassType() &&
2373 "Non-first-class type for constant extractvalue expression");
2374 if (Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs, NumIdx))
2375 return FC; // Fold a few common cases...
2376 // Look up the constant in the table first to ensure uniqueness
2377 std::vector<Constant*> ArgVec;
2378 ArgVec.push_back(Agg);
2379 SmallVector<unsigned, 4> Indices(Idxs, Idxs + NumIdx);
2380 const ExprMapKeyType Key(Instruction::ExtractValue, ArgVec, 0, Indices);
2381 return ExprConstants->getOrCreate(ReqTy, Key);
2384 Constant *ConstantExpr::getExtractValue(Constant *Agg,
2385 const unsigned *IdxList, unsigned NumIdx) {
2386 assert(Agg->getType()->isFirstClassType() &&
2387 "Tried to create extractelement operation on non-first-class type!");
2390 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2391 assert(ReqTy && "extractvalue indices invalid!");
2392 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
2395 Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
2396 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
2397 if (PTy->getElementType()->isFloatingPoint()) {
2398 std::vector<Constant*> zeros(PTy->getNumElements(),
2399 ConstantFP::getNegativeZero(PTy->getElementType()));
2400 return ConstantVector::get(PTy, zeros);
2403 if (Ty->isFloatingPoint())
2404 return ConstantFP::getNegativeZero(Ty);
2406 return Constant::getNullValue(Ty);
2409 // destroyConstant - Remove the constant from the constant table...
2411 void ConstantExpr::destroyConstant() {
2412 ExprConstants->remove(this);
2413 destroyConstantImpl();
2416 const char *ConstantExpr::getOpcodeName() const {
2417 return Instruction::getOpcodeName(getOpcode());
2420 //===----------------------------------------------------------------------===//
2421 // replaceUsesOfWithOnConstant implementations
2423 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2424 /// 'From' to be uses of 'To'. This must update the uniquing data structures
2427 /// Note that we intentionally replace all uses of From with To here. Consider
2428 /// a large array that uses 'From' 1000 times. By handling this case all here,
2429 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2430 /// single invocation handles all 1000 uses. Handling them one at a time would
2431 /// work, but would be really slow because it would have to unique each updated
2433 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
2435 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2436 Constant *ToC = cast<Constant>(To);
2438 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
2439 Lookup.first.first = getType();
2440 Lookup.second = this;
2442 std::vector<Constant*> &Values = Lookup.first.second;
2443 Values.reserve(getNumOperands()); // Build replacement array.
2445 // Fill values with the modified operands of the constant array. Also,
2446 // compute whether this turns into an all-zeros array.
2447 bool isAllZeros = false;
2448 unsigned NumUpdated = 0;
2449 if (!ToC->isNullValue()) {
2450 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2451 Constant *Val = cast<Constant>(O->get());
2456 Values.push_back(Val);
2460 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2461 Constant *Val = cast<Constant>(O->get());
2466 Values.push_back(Val);
2467 if (isAllZeros) isAllZeros = Val->isNullValue();
2471 Constant *Replacement = 0;
2473 Replacement = ConstantAggregateZero::get(getType());
2475 // Check to see if we have this array type already.
2477 ArrayConstantsTy::MapTy::iterator I =
2478 ArrayConstants->InsertOrGetItem(Lookup, Exists);
2481 Replacement = I->second;
2483 // Okay, the new shape doesn't exist in the system yet. Instead of
2484 // creating a new constant array, inserting it, replaceallusesof'ing the
2485 // old with the new, then deleting the old... just update the current one
2487 ArrayConstants->MoveConstantToNewSlot(this, I);
2489 // Update to the new value. Optimize for the case when we have a single
2490 // operand that we're changing, but handle bulk updates efficiently.
2491 if (NumUpdated == 1) {
2492 unsigned OperandToUpdate = U-OperandList;
2493 assert(getOperand(OperandToUpdate) == From &&
2494 "ReplaceAllUsesWith broken!");
2495 setOperand(OperandToUpdate, ToC);
2497 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2498 if (getOperand(i) == From)
2505 // Otherwise, I do need to replace this with an existing value.
2506 assert(Replacement != this && "I didn't contain From!");
2508 // Everyone using this now uses the replacement.
2509 uncheckedReplaceAllUsesWith(Replacement);
2511 // Delete the old constant!
2515 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2517 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2518 Constant *ToC = cast<Constant>(To);
2520 unsigned OperandToUpdate = U-OperandList;
2521 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2523 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
2524 Lookup.first.first = getType();
2525 Lookup.second = this;
2526 std::vector<Constant*> &Values = Lookup.first.second;
2527 Values.reserve(getNumOperands()); // Build replacement struct.
2530 // Fill values with the modified operands of the constant struct. Also,
2531 // compute whether this turns into an all-zeros struct.
2532 bool isAllZeros = false;
2533 if (!ToC->isNullValue()) {
2534 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2535 Values.push_back(cast<Constant>(O->get()));
2538 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2539 Constant *Val = cast<Constant>(O->get());
2540 Values.push_back(Val);
2541 if (isAllZeros) isAllZeros = Val->isNullValue();
2544 Values[OperandToUpdate] = ToC;
2546 Constant *Replacement = 0;
2548 Replacement = ConstantAggregateZero::get(getType());
2550 // Check to see if we have this array type already.
2552 StructConstantsTy::MapTy::iterator I =
2553 StructConstants->InsertOrGetItem(Lookup, Exists);
2556 Replacement = I->second;
2558 // Okay, the new shape doesn't exist in the system yet. Instead of
2559 // creating a new constant struct, inserting it, replaceallusesof'ing the
2560 // old with the new, then deleting the old... just update the current one
2562 StructConstants->MoveConstantToNewSlot(this, I);
2564 // Update to the new value.
2565 setOperand(OperandToUpdate, ToC);
2570 assert(Replacement != this && "I didn't contain From!");
2572 // Everyone using this now uses the replacement.
2573 uncheckedReplaceAllUsesWith(Replacement);
2575 // Delete the old constant!
2579 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2581 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2583 std::vector<Constant*> Values;
2584 Values.reserve(getNumOperands()); // Build replacement array...
2585 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2586 Constant *Val = getOperand(i);
2587 if (Val == From) Val = cast<Constant>(To);
2588 Values.push_back(Val);
2591 Constant *Replacement = ConstantVector::get(getType(), Values);
2592 assert(Replacement != this && "I didn't contain From!");
2594 // Everyone using this now uses the replacement.
2595 uncheckedReplaceAllUsesWith(Replacement);
2597 // Delete the old constant!
2601 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2603 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2604 Constant *To = cast<Constant>(ToV);
2606 Constant *Replacement = 0;
2607 if (getOpcode() == Instruction::GetElementPtr) {
2608 SmallVector<Constant*, 8> Indices;
2609 Constant *Pointer = getOperand(0);
2610 Indices.reserve(getNumOperands()-1);
2611 if (Pointer == From) Pointer = To;
2613 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2614 Constant *Val = getOperand(i);
2615 if (Val == From) Val = To;
2616 Indices.push_back(Val);
2618 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2619 &Indices[0], Indices.size());
2620 } else if (getOpcode() == Instruction::ExtractValue) {
2621 Constant *Agg = getOperand(0);
2622 if (Agg == From) Agg = To;
2624 const SmallVector<unsigned, 4> &Indices = getIndices();
2625 Replacement = ConstantExpr::getExtractValue(Agg,
2626 &Indices[0], Indices.size());
2627 } else if (getOpcode() == Instruction::InsertValue) {
2628 Constant *Agg = getOperand(0);
2629 Constant *Val = getOperand(1);
2630 if (Agg == From) Agg = To;
2631 if (Val == From) Val = To;
2633 const SmallVector<unsigned, 4> &Indices = getIndices();
2634 Replacement = ConstantExpr::getInsertValue(Agg, Val,
2635 &Indices[0], Indices.size());
2636 } else if (isCast()) {
2637 assert(getOperand(0) == From && "Cast only has one use!");
2638 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2639 } else if (getOpcode() == Instruction::Select) {
2640 Constant *C1 = getOperand(0);
2641 Constant *C2 = getOperand(1);
2642 Constant *C3 = getOperand(2);
2643 if (C1 == From) C1 = To;
2644 if (C2 == From) C2 = To;
2645 if (C3 == From) C3 = To;
2646 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2647 } else if (getOpcode() == Instruction::ExtractElement) {
2648 Constant *C1 = getOperand(0);
2649 Constant *C2 = getOperand(1);
2650 if (C1 == From) C1 = To;
2651 if (C2 == From) C2 = To;
2652 Replacement = ConstantExpr::getExtractElement(C1, C2);
2653 } else if (getOpcode() == Instruction::InsertElement) {
2654 Constant *C1 = getOperand(0);
2655 Constant *C2 = getOperand(1);
2656 Constant *C3 = getOperand(1);
2657 if (C1 == From) C1 = To;
2658 if (C2 == From) C2 = To;
2659 if (C3 == From) C3 = To;
2660 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2661 } else if (getOpcode() == Instruction::ShuffleVector) {
2662 Constant *C1 = getOperand(0);
2663 Constant *C2 = getOperand(1);
2664 Constant *C3 = getOperand(2);
2665 if (C1 == From) C1 = To;
2666 if (C2 == From) C2 = To;
2667 if (C3 == From) C3 = To;
2668 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2669 } else if (isCompare()) {
2670 Constant *C1 = getOperand(0);
2671 Constant *C2 = getOperand(1);
2672 if (C1 == From) C1 = To;
2673 if (C2 == From) C2 = To;
2674 if (getOpcode() == Instruction::ICmp)
2675 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2677 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2678 } else if (getNumOperands() == 2) {
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::get(getOpcode(), C1, C2);
2685 assert(0 && "Unknown ConstantExpr type!");
2689 assert(Replacement != this && "I didn't contain From!");
2691 // Everyone using this now uses the replacement.
2692 uncheckedReplaceAllUsesWith(Replacement);
2694 // Delete the old constant!