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.find(Lookup);
1104 // Is it in the map?
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 = AbstractTypeMap.find(Ty);
1124 if (TI == AbstractTypeMap.end()) {
1125 // Add ourselves to the ATU list of the type.
1126 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
1128 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
1134 void remove(ConstantClass *CP) {
1135 typename MapTy::iterator I = FindExistingElement(CP);
1136 assert(I != Map.end() && "Constant not found in constant table!");
1137 assert(I->second == CP && "Didn't find correct element?");
1139 if (HasLargeKey) // Remember the reverse mapping if needed.
1140 InverseMap.erase(CP);
1142 // Now that we found the entry, make sure this isn't the entry that
1143 // the AbstractTypeMap points to.
1144 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
1145 if (Ty->isAbstract()) {
1146 assert(AbstractTypeMap.count(Ty) &&
1147 "Abstract type not in AbstractTypeMap?");
1148 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
1149 if (ATMEntryIt == I) {
1150 // Yes, we are removing the representative entry for this type.
1151 // See if there are any other entries of the same type.
1152 typename MapTy::iterator TmpIt = ATMEntryIt;
1154 // First check the entry before this one...
1155 if (TmpIt != Map.begin()) {
1157 if (TmpIt->first.first != Ty) // Not the same type, move back...
1161 // If we didn't find the same type, try to move forward...
1162 if (TmpIt == ATMEntryIt) {
1164 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
1165 --TmpIt; // No entry afterwards with the same type
1168 // If there is another entry in the map of the same abstract type,
1169 // update the AbstractTypeMap entry now.
1170 if (TmpIt != ATMEntryIt) {
1173 // Otherwise, we are removing the last instance of this type
1174 // from the table. Remove from the ATM, and from user list.
1175 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
1176 AbstractTypeMap.erase(Ty);
1185 /// MoveConstantToNewSlot - If we are about to change C to be the element
1186 /// specified by I, update our internal data structures to reflect this
1188 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
1189 // First, remove the old location of the specified constant in the map.
1190 typename MapTy::iterator OldI = FindExistingElement(C);
1191 assert(OldI != Map.end() && "Constant not found in constant table!");
1192 assert(OldI->second == C && "Didn't find correct element?");
1194 // If this constant is the representative element for its abstract type,
1195 // update the AbstractTypeMap so that the representative element is I.
1196 if (C->getType()->isAbstract()) {
1197 typename AbstractTypeMapTy::iterator ATI =
1198 AbstractTypeMap.find(C->getType());
1199 assert(ATI != AbstractTypeMap.end() &&
1200 "Abstract type not in AbstractTypeMap?");
1201 if (ATI->second == OldI)
1205 // Remove the old entry from the map.
1208 // Update the inverse map so that we know that this constant is now
1209 // located at descriptor I.
1211 assert(I->second == C && "Bad inversemap entry!");
1216 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
1217 typename AbstractTypeMapTy::iterator I =
1218 AbstractTypeMap.find(cast<Type>(OldTy));
1220 assert(I != AbstractTypeMap.end() &&
1221 "Abstract type not in AbstractTypeMap?");
1223 // Convert a constant at a time until the last one is gone. The last one
1224 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
1225 // eliminated eventually.
1227 ConvertConstantType<ConstantClass,
1228 TypeClass>::convert(
1229 static_cast<ConstantClass *>(I->second->second),
1230 cast<TypeClass>(NewTy));
1232 I = AbstractTypeMap.find(cast<Type>(OldTy));
1233 } while (I != AbstractTypeMap.end());
1236 // If the type became concrete without being refined to any other existing
1237 // type, we just remove ourselves from the ATU list.
1238 void typeBecameConcrete(const DerivedType *AbsTy) {
1239 AbsTy->removeAbstractTypeUser(this);
1243 DOUT << "Constant.cpp: ValueMap\n";
1250 //---- ConstantAggregateZero::get() implementation...
1253 // ConstantAggregateZero does not take extra "value" argument...
1254 template<class ValType>
1255 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
1256 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
1257 return new ConstantAggregateZero(Ty);
1262 struct ConvertConstantType<ConstantAggregateZero, Type> {
1263 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1264 // Make everyone now use a constant of the new type...
1265 Constant *New = ConstantAggregateZero::get(NewTy);
1266 assert(New != OldC && "Didn't replace constant??");
1267 OldC->uncheckedReplaceAllUsesWith(New);
1268 OldC->destroyConstant(); // This constant is now dead, destroy it.
1273 static ManagedStatic<ValueMap<char, Type,
1274 ConstantAggregateZero> > AggZeroConstants;
1276 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1278 Constant *ConstantAggregateZero::get(const Type *Ty) {
1279 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
1280 "Cannot create an aggregate zero of non-aggregate type!");
1281 return AggZeroConstants->getOrCreate(Ty, 0);
1284 // destroyConstant - Remove the constant from the constant table...
1286 void ConstantAggregateZero::destroyConstant() {
1287 AggZeroConstants->remove(this);
1288 destroyConstantImpl();
1291 //---- ConstantArray::get() implementation...
1295 struct ConvertConstantType<ConstantArray, ArrayType> {
1296 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1297 // Make everyone now use a constant of the new type...
1298 std::vector<Constant*> C;
1299 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1300 C.push_back(cast<Constant>(OldC->getOperand(i)));
1301 Constant *New = ConstantArray::get(NewTy, C);
1302 assert(New != OldC && "Didn't replace constant??");
1303 OldC->uncheckedReplaceAllUsesWith(New);
1304 OldC->destroyConstant(); // This constant is now dead, destroy it.
1309 static std::vector<Constant*> getValType(ConstantArray *CA) {
1310 std::vector<Constant*> Elements;
1311 Elements.reserve(CA->getNumOperands());
1312 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1313 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1317 typedef ValueMap<std::vector<Constant*>, ArrayType,
1318 ConstantArray, true /*largekey*/> ArrayConstantsTy;
1319 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
1321 Constant *ConstantArray::get(const ArrayType *Ty,
1322 const std::vector<Constant*> &V) {
1323 // If this is an all-zero array, return a ConstantAggregateZero object
1326 if (!C->isNullValue())
1327 return ArrayConstants->getOrCreate(Ty, V);
1328 for (unsigned i = 1, e = V.size(); i != e; ++i)
1330 return ArrayConstants->getOrCreate(Ty, V);
1332 return ConstantAggregateZero::get(Ty);
1335 // destroyConstant - Remove the constant from the constant table...
1337 void ConstantArray::destroyConstant() {
1338 ArrayConstants->remove(this);
1339 destroyConstantImpl();
1342 /// ConstantArray::get(const string&) - Return an array that is initialized to
1343 /// contain the specified string. If length is zero then a null terminator is
1344 /// added to the specified string so that it may be used in a natural way.
1345 /// Otherwise, the length parameter specifies how much of the string to use
1346 /// and it won't be null terminated.
1348 Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
1349 std::vector<Constant*> ElementVals;
1350 for (unsigned i = 0; i < Str.length(); ++i)
1351 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
1353 // Add a null terminator to the string...
1355 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
1358 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
1359 return ConstantArray::get(ATy, ElementVals);
1362 /// isString - This method returns true if the array is an array of i8, and
1363 /// if the elements of the array are all ConstantInt's.
1364 bool ConstantArray::isString() const {
1365 // Check the element type for i8...
1366 if (getType()->getElementType() != Type::Int8Ty)
1368 // Check the elements to make sure they are all integers, not constant
1370 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1371 if (!isa<ConstantInt>(getOperand(i)))
1376 /// isCString - This method returns true if the array is a string (see
1377 /// isString) and it ends in a null byte \0 and does not contains any other
1378 /// null bytes except its terminator.
1379 bool ConstantArray::isCString() const {
1380 // Check the element type for i8...
1381 if (getType()->getElementType() != Type::Int8Ty)
1383 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1384 // Last element must be a null.
1385 if (getOperand(getNumOperands()-1) != Zero)
1387 // Other elements must be non-null integers.
1388 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1389 if (!isa<ConstantInt>(getOperand(i)))
1391 if (getOperand(i) == Zero)
1398 // getAsString - If the sub-element type of this array is i8
1399 // then this method converts the array to an std::string and returns it.
1400 // Otherwise, it asserts out.
1402 std::string ConstantArray::getAsString() const {
1403 assert(isString() && "Not a string!");
1405 Result.reserve(getNumOperands());
1406 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1407 Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
1412 //---- ConstantStruct::get() implementation...
1417 struct ConvertConstantType<ConstantStruct, StructType> {
1418 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1419 // Make everyone now use a constant of the new type...
1420 std::vector<Constant*> C;
1421 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1422 C.push_back(cast<Constant>(OldC->getOperand(i)));
1423 Constant *New = ConstantStruct::get(NewTy, C);
1424 assert(New != OldC && "Didn't replace constant??");
1426 OldC->uncheckedReplaceAllUsesWith(New);
1427 OldC->destroyConstant(); // This constant is now dead, destroy it.
1432 typedef ValueMap<std::vector<Constant*>, StructType,
1433 ConstantStruct, true /*largekey*/> StructConstantsTy;
1434 static ManagedStatic<StructConstantsTy> StructConstants;
1436 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1437 std::vector<Constant*> Elements;
1438 Elements.reserve(CS->getNumOperands());
1439 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1440 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1444 Constant *ConstantStruct::get(const StructType *Ty,
1445 const std::vector<Constant*> &V) {
1446 // Create a ConstantAggregateZero value if all elements are zeros...
1447 for (unsigned i = 0, e = V.size(); i != e; ++i)
1448 if (!V[i]->isNullValue())
1449 return StructConstants->getOrCreate(Ty, V);
1451 return ConstantAggregateZero::get(Ty);
1454 Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
1455 std::vector<const Type*> StructEls;
1456 StructEls.reserve(V.size());
1457 for (unsigned i = 0, e = V.size(); i != e; ++i)
1458 StructEls.push_back(V[i]->getType());
1459 return get(StructType::get(StructEls, packed), V);
1462 // destroyConstant - Remove the constant from the constant table...
1464 void ConstantStruct::destroyConstant() {
1465 StructConstants->remove(this);
1466 destroyConstantImpl();
1469 //---- ConstantVector::get() implementation...
1473 struct ConvertConstantType<ConstantVector, VectorType> {
1474 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
1475 // Make everyone now use a constant of the new type...
1476 std::vector<Constant*> C;
1477 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1478 C.push_back(cast<Constant>(OldC->getOperand(i)));
1479 Constant *New = ConstantVector::get(NewTy, C);
1480 assert(New != OldC && "Didn't replace constant??");
1481 OldC->uncheckedReplaceAllUsesWith(New);
1482 OldC->destroyConstant(); // This constant is now dead, destroy it.
1487 static std::vector<Constant*> getValType(ConstantVector *CP) {
1488 std::vector<Constant*> Elements;
1489 Elements.reserve(CP->getNumOperands());
1490 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1491 Elements.push_back(CP->getOperand(i));
1495 static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
1496 ConstantVector> > VectorConstants;
1498 Constant *ConstantVector::get(const VectorType *Ty,
1499 const std::vector<Constant*> &V) {
1500 assert(!V.empty() && "Vectors can't be empty");
1501 // If this is an all-undef or alll-zero vector, return a
1502 // ConstantAggregateZero or UndefValue.
1504 bool isZero = C->isNullValue();
1505 bool isUndef = isa<UndefValue>(C);
1507 if (isZero || isUndef) {
1508 for (unsigned i = 1, e = V.size(); i != e; ++i)
1510 isZero = isUndef = false;
1516 return ConstantAggregateZero::get(Ty);
1518 return UndefValue::get(Ty);
1519 return VectorConstants->getOrCreate(Ty, V);
1522 Constant *ConstantVector::get(const std::vector<Constant*> &V) {
1523 assert(!V.empty() && "Cannot infer type if V is empty");
1524 return get(VectorType::get(V.front()->getType(),V.size()), V);
1527 // destroyConstant - Remove the constant from the constant table...
1529 void ConstantVector::destroyConstant() {
1530 VectorConstants->remove(this);
1531 destroyConstantImpl();
1534 /// This function will return true iff every element in this vector constant
1535 /// is set to all ones.
1536 /// @returns true iff this constant's emements are all set to all ones.
1537 /// @brief Determine if the value is all ones.
1538 bool ConstantVector::isAllOnesValue() const {
1539 // Check out first element.
1540 const Constant *Elt = getOperand(0);
1541 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1542 if (!CI || !CI->isAllOnesValue()) return false;
1543 // Then make sure all remaining elements point to the same value.
1544 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1545 if (getOperand(I) != Elt) return false;
1550 /// getSplatValue - If this is a splat constant, where all of the
1551 /// elements have the same value, return that value. Otherwise return null.
1552 Constant *ConstantVector::getSplatValue() {
1553 // Check out first element.
1554 Constant *Elt = getOperand(0);
1555 // Then make sure all remaining elements point to the same value.
1556 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1557 if (getOperand(I) != Elt) return 0;
1561 //---- ConstantPointerNull::get() implementation...
1565 // ConstantPointerNull does not take extra "value" argument...
1566 template<class ValType>
1567 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1568 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1569 return new ConstantPointerNull(Ty);
1574 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1575 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1576 // Make everyone now use a constant of the new type...
1577 Constant *New = ConstantPointerNull::get(NewTy);
1578 assert(New != OldC && "Didn't replace constant??");
1579 OldC->uncheckedReplaceAllUsesWith(New);
1580 OldC->destroyConstant(); // This constant is now dead, destroy it.
1585 static ManagedStatic<ValueMap<char, PointerType,
1586 ConstantPointerNull> > NullPtrConstants;
1588 static char getValType(ConstantPointerNull *) {
1593 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1594 return NullPtrConstants->getOrCreate(Ty, 0);
1597 // destroyConstant - Remove the constant from the constant table...
1599 void ConstantPointerNull::destroyConstant() {
1600 NullPtrConstants->remove(this);
1601 destroyConstantImpl();
1605 //---- UndefValue::get() implementation...
1609 // UndefValue does not take extra "value" argument...
1610 template<class ValType>
1611 struct ConstantCreator<UndefValue, Type, ValType> {
1612 static UndefValue *create(const Type *Ty, const ValType &V) {
1613 return new UndefValue(Ty);
1618 struct ConvertConstantType<UndefValue, Type> {
1619 static void convert(UndefValue *OldC, const Type *NewTy) {
1620 // Make everyone now use a constant of the new type.
1621 Constant *New = UndefValue::get(NewTy);
1622 assert(New != OldC && "Didn't replace constant??");
1623 OldC->uncheckedReplaceAllUsesWith(New);
1624 OldC->destroyConstant(); // This constant is now dead, destroy it.
1629 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1631 static char getValType(UndefValue *) {
1636 UndefValue *UndefValue::get(const Type *Ty) {
1637 return UndefValueConstants->getOrCreate(Ty, 0);
1640 // destroyConstant - Remove the constant from the constant table.
1642 void UndefValue::destroyConstant() {
1643 UndefValueConstants->remove(this);
1644 destroyConstantImpl();
1648 //---- ConstantExpr::get() implementations...
1653 struct ExprMapKeyType {
1654 typedef SmallVector<unsigned, 4> IndexList;
1656 ExprMapKeyType(unsigned opc,
1657 const std::vector<Constant*> &ops,
1658 unsigned short pred = 0,
1659 const IndexList &inds = IndexList())
1660 : opcode(opc), predicate(pred), operands(ops), indices(inds) {}
1663 std::vector<Constant*> operands;
1665 bool operator==(const ExprMapKeyType& that) const {
1666 return this->opcode == that.opcode &&
1667 this->predicate == that.predicate &&
1668 this->operands == that.operands;
1669 this->indices == that.indices;
1671 bool operator<(const ExprMapKeyType & that) const {
1672 return this->opcode < that.opcode ||
1673 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1674 (this->opcode == that.opcode && this->predicate == that.predicate &&
1675 this->operands < that.operands) ||
1676 (this->opcode == that.opcode && this->predicate == that.predicate &&
1677 this->operands == that.operands && this->indices < that.indices);
1680 bool operator!=(const ExprMapKeyType& that) const {
1681 return !(*this == that);
1689 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1690 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1691 unsigned short pred = 0) {
1692 if (Instruction::isCast(V.opcode))
1693 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1694 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1695 V.opcode < Instruction::BinaryOpsEnd))
1696 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1697 if (V.opcode == Instruction::Select)
1698 return new SelectConstantExpr(V.operands[0], V.operands[1],
1700 if (V.opcode == Instruction::ExtractElement)
1701 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1702 if (V.opcode == Instruction::InsertElement)
1703 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1705 if (V.opcode == Instruction::ShuffleVector)
1706 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1708 if (V.opcode == Instruction::InsertValue)
1709 return new InsertValueConstantExpr(V.operands[0], V.operands[1],
1711 if (V.opcode == Instruction::ExtractValue)
1712 return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
1713 if (V.opcode == Instruction::GetElementPtr) {
1714 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1715 return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
1718 // The compare instructions are weird. We have to encode the predicate
1719 // value and it is combined with the instruction opcode by multiplying
1720 // the opcode by one hundred. We must decode this to get the predicate.
1721 if (V.opcode == Instruction::ICmp)
1722 return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate,
1723 V.operands[0], V.operands[1]);
1724 if (V.opcode == Instruction::FCmp)
1725 return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate,
1726 V.operands[0], V.operands[1]);
1727 if (V.opcode == Instruction::VICmp)
1728 return new CompareConstantExpr(Ty, Instruction::VICmp, V.predicate,
1729 V.operands[0], V.operands[1]);
1730 if (V.opcode == Instruction::VFCmp)
1731 return new CompareConstantExpr(Ty, Instruction::VFCmp, V.predicate,
1732 V.operands[0], V.operands[1]);
1733 assert(0 && "Invalid ConstantExpr!");
1739 struct ConvertConstantType<ConstantExpr, Type> {
1740 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1742 switch (OldC->getOpcode()) {
1743 case Instruction::Trunc:
1744 case Instruction::ZExt:
1745 case Instruction::SExt:
1746 case Instruction::FPTrunc:
1747 case Instruction::FPExt:
1748 case Instruction::UIToFP:
1749 case Instruction::SIToFP:
1750 case Instruction::FPToUI:
1751 case Instruction::FPToSI:
1752 case Instruction::PtrToInt:
1753 case Instruction::IntToPtr:
1754 case Instruction::BitCast:
1755 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1758 case Instruction::Select:
1759 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1760 OldC->getOperand(1),
1761 OldC->getOperand(2));
1764 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1765 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1766 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1767 OldC->getOperand(1));
1769 case Instruction::GetElementPtr:
1770 // Make everyone now use a constant of the new type...
1771 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1772 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1773 &Idx[0], Idx.size());
1777 assert(New != OldC && "Didn't replace constant??");
1778 OldC->uncheckedReplaceAllUsesWith(New);
1779 OldC->destroyConstant(); // This constant is now dead, destroy it.
1782 } // end namespace llvm
1785 static ExprMapKeyType getValType(ConstantExpr *CE) {
1786 std::vector<Constant*> Operands;
1787 Operands.reserve(CE->getNumOperands());
1788 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1789 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1790 return ExprMapKeyType(CE->getOpcode(), Operands,
1791 CE->isCompare() ? CE->getPredicate() : 0,
1793 CE->getIndices() : SmallVector<unsigned, 4>());
1796 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1797 ConstantExpr> > ExprConstants;
1799 /// This is a utility function to handle folding of casts and lookup of the
1800 /// cast in the ExprConstants map. It is used by the various get* methods below.
1801 static inline Constant *getFoldedCast(
1802 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1803 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1804 // Fold a few common cases
1805 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1808 // Look up the constant in the table first to ensure uniqueness
1809 std::vector<Constant*> argVec(1, C);
1810 ExprMapKeyType Key(opc, argVec);
1811 return ExprConstants->getOrCreate(Ty, Key);
1814 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1815 Instruction::CastOps opc = Instruction::CastOps(oc);
1816 assert(Instruction::isCast(opc) && "opcode out of range");
1817 assert(C && Ty && "Null arguments to getCast");
1818 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1822 assert(0 && "Invalid cast opcode");
1824 case Instruction::Trunc: return getTrunc(C, Ty);
1825 case Instruction::ZExt: return getZExt(C, Ty);
1826 case Instruction::SExt: return getSExt(C, Ty);
1827 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1828 case Instruction::FPExt: return getFPExtend(C, Ty);
1829 case Instruction::UIToFP: return getUIToFP(C, Ty);
1830 case Instruction::SIToFP: return getSIToFP(C, Ty);
1831 case Instruction::FPToUI: return getFPToUI(C, Ty);
1832 case Instruction::FPToSI: return getFPToSI(C, Ty);
1833 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1834 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1835 case Instruction::BitCast: return getBitCast(C, Ty);
1840 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1841 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1842 return getCast(Instruction::BitCast, C, Ty);
1843 return getCast(Instruction::ZExt, C, Ty);
1846 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1847 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1848 return getCast(Instruction::BitCast, C, Ty);
1849 return getCast(Instruction::SExt, C, Ty);
1852 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1853 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1854 return getCast(Instruction::BitCast, C, Ty);
1855 return getCast(Instruction::Trunc, C, Ty);
1858 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1859 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1860 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1862 if (Ty->isInteger())
1863 return getCast(Instruction::PtrToInt, S, Ty);
1864 return getCast(Instruction::BitCast, S, Ty);
1867 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1869 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1870 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1871 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1872 Instruction::CastOps opcode =
1873 (SrcBits == DstBits ? Instruction::BitCast :
1874 (SrcBits > DstBits ? Instruction::Trunc :
1875 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1876 return getCast(opcode, C, Ty);
1879 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1880 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1882 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1883 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1884 if (SrcBits == DstBits)
1885 return C; // Avoid a useless cast
1886 Instruction::CastOps opcode =
1887 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1888 return getCast(opcode, C, Ty);
1891 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1892 assert(C->getType()->isInteger() && "Trunc operand must be integer");
1893 assert(Ty->isInteger() && "Trunc produces only integral");
1894 assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1895 "SrcTy must be larger than DestTy for Trunc!");
1897 return getFoldedCast(Instruction::Trunc, C, Ty);
1900 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1901 assert(C->getType()->isInteger() && "SEXt operand must be integral");
1902 assert(Ty->isInteger() && "SExt produces only integer");
1903 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1904 "SrcTy must be smaller than DestTy for SExt!");
1906 return getFoldedCast(Instruction::SExt, C, Ty);
1909 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1910 assert(C->getType()->isInteger() && "ZEXt operand must be integral");
1911 assert(Ty->isInteger() && "ZExt produces only integer");
1912 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1913 "SrcTy must be smaller than DestTy for ZExt!");
1915 return getFoldedCast(Instruction::ZExt, C, Ty);
1918 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1919 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1920 C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1921 "This is an illegal floating point truncation!");
1922 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1925 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1926 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1927 C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1928 "This is an illegal floating point extension!");
1929 return getFoldedCast(Instruction::FPExt, C, Ty);
1932 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1933 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1934 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1935 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1936 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1937 "This is an illegal uint to floating point cast!");
1938 return getFoldedCast(Instruction::UIToFP, C, Ty);
1941 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1942 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1943 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1944 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1945 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1946 "This is an illegal sint to floating point cast!");
1947 return getFoldedCast(Instruction::SIToFP, C, Ty);
1950 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1951 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1952 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1953 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1954 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1955 "This is an illegal floating point to uint cast!");
1956 return getFoldedCast(Instruction::FPToUI, C, Ty);
1959 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1960 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1961 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1962 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1963 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1964 "This is an illegal floating point to sint cast!");
1965 return getFoldedCast(Instruction::FPToSI, C, Ty);
1968 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1969 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1970 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1971 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1974 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1975 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1976 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1977 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1980 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1981 // BitCast implies a no-op cast of type only. No bits change. However, you
1982 // can't cast pointers to anything but pointers.
1983 const Type *SrcTy = C->getType();
1984 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1985 "BitCast cannot cast pointer to non-pointer and vice versa");
1987 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1988 // or nonptr->ptr). For all the other types, the cast is okay if source and
1989 // destination bit widths are identical.
1990 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1991 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1992 assert(SrcBitSize == DstBitSize && "BitCast requies types of same width");
1993 return getFoldedCast(Instruction::BitCast, C, DstTy);
1996 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
1997 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1998 Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
2000 getGetElementPtr(getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
2001 return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
2004 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
2005 Constant *C1, Constant *C2) {
2006 // Check the operands for consistency first
2007 assert(Opcode >= Instruction::BinaryOpsBegin &&
2008 Opcode < Instruction::BinaryOpsEnd &&
2009 "Invalid opcode in binary constant expression");
2010 assert(C1->getType() == C2->getType() &&
2011 "Operand types in binary constant expression should match");
2013 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
2014 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
2015 return FC; // Fold a few common cases...
2017 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
2018 ExprMapKeyType Key(Opcode, argVec);
2019 return ExprConstants->getOrCreate(ReqTy, Key);
2022 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
2023 Constant *C1, Constant *C2) {
2024 switch (predicate) {
2025 default: assert(0 && "Invalid CmpInst predicate");
2026 case FCmpInst::FCMP_FALSE: case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_OGT:
2027 case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OLE:
2028 case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_ORD: case FCmpInst::FCMP_UNO:
2029 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UGT: case FCmpInst::FCMP_UGE:
2030 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_ULE: case FCmpInst::FCMP_UNE:
2031 case FCmpInst::FCMP_TRUE:
2032 return getFCmp(predicate, C1, C2);
2033 case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGT:
2034 case ICmpInst::ICMP_UGE: case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE:
2035 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_SGE: case ICmpInst::ICMP_SLT:
2036 case ICmpInst::ICMP_SLE:
2037 return getICmp(predicate, C1, C2);
2041 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
2044 case Instruction::Add:
2045 case Instruction::Sub:
2046 case Instruction::Mul:
2047 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2048 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
2049 isa<VectorType>(C1->getType())) &&
2050 "Tried to create an arithmetic operation on a non-arithmetic type!");
2052 case Instruction::UDiv:
2053 case Instruction::SDiv:
2054 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2055 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
2056 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
2057 "Tried to create an arithmetic operation on a non-arithmetic type!");
2059 case Instruction::FDiv:
2060 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2061 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
2062 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
2063 && "Tried to create an arithmetic operation on a non-arithmetic type!");
2065 case Instruction::URem:
2066 case Instruction::SRem:
2067 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2068 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
2069 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
2070 "Tried to create an arithmetic operation on a non-arithmetic type!");
2072 case Instruction::FRem:
2073 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2074 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
2075 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
2076 && "Tried to create an arithmetic operation on a non-arithmetic type!");
2078 case Instruction::And:
2079 case Instruction::Or:
2080 case Instruction::Xor:
2081 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2082 assert((C1->getType()->isInteger() || isa<VectorType>(C1->getType())) &&
2083 "Tried to create a logical operation on a non-integral type!");
2085 case Instruction::Shl:
2086 case Instruction::LShr:
2087 case Instruction::AShr:
2088 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2089 assert(C1->getType()->isInteger() &&
2090 "Tried to create a shift operation on a non-integer type!");
2097 return getTy(C1->getType(), Opcode, C1, C2);
2100 Constant *ConstantExpr::getCompare(unsigned short pred,
2101 Constant *C1, Constant *C2) {
2102 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2103 return getCompareTy(pred, C1, C2);
2106 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
2107 Constant *V1, Constant *V2) {
2108 assert(C->getType() == Type::Int1Ty && "Select condition must be i1!");
2109 assert(V1->getType() == V2->getType() && "Select value types must match!");
2110 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
2112 if (ReqTy == V1->getType())
2113 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
2114 return SC; // Fold common cases
2116 std::vector<Constant*> argVec(3, C);
2119 ExprMapKeyType Key(Instruction::Select, argVec);
2120 return ExprConstants->getOrCreate(ReqTy, Key);
2123 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
2126 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
2128 cast<PointerType>(ReqTy)->getElementType() &&
2129 "GEP indices invalid!");
2131 if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs, NumIdx))
2132 return FC; // Fold a few common cases...
2134 assert(isa<PointerType>(C->getType()) &&
2135 "Non-pointer type for constant GetElementPtr expression");
2136 // Look up the constant in the table first to ensure uniqueness
2137 std::vector<Constant*> ArgVec;
2138 ArgVec.reserve(NumIdx+1);
2139 ArgVec.push_back(C);
2140 for (unsigned i = 0; i != NumIdx; ++i)
2141 ArgVec.push_back(cast<Constant>(Idxs[i]));
2142 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
2143 return ExprConstants->getOrCreate(ReqTy, Key);
2146 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
2148 // Get the result type of the getelementptr!
2150 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
2151 assert(Ty && "GEP indices invalid!");
2152 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
2153 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
2156 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
2158 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
2163 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2164 assert(LHS->getType() == RHS->getType());
2165 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2166 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
2168 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2169 return FC; // Fold a few common cases...
2171 // Look up the constant in the table first to ensure uniqueness
2172 std::vector<Constant*> ArgVec;
2173 ArgVec.push_back(LHS);
2174 ArgVec.push_back(RHS);
2175 // Get the key type with both the opcode and predicate
2176 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
2177 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2181 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2182 assert(LHS->getType() == RHS->getType());
2183 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
2185 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2186 return FC; // Fold a few common cases...
2188 // Look up the constant in the table first to ensure uniqueness
2189 std::vector<Constant*> ArgVec;
2190 ArgVec.push_back(LHS);
2191 ArgVec.push_back(RHS);
2192 // Get the key type with both the opcode and predicate
2193 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
2194 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2198 ConstantExpr::getVICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2199 assert(isa<VectorType>(LHS->getType()) &&
2200 "Tried to create vicmp operation on non-vector type!");
2201 assert(LHS->getType() == RHS->getType());
2202 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2203 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid VICmp Predicate");
2205 const VectorType *VTy = cast<VectorType>(LHS->getType());
2206 const Type *EltTy = VTy->getElementType();
2207 unsigned NumElts = VTy->getNumElements();
2209 SmallVector<Constant *, 8> Elts;
2210 for (unsigned i = 0; i != NumElts; ++i) {
2211 Constant *FC = ConstantFoldCompareInstruction(pred, LHS->getOperand(i),
2212 RHS->getOperand(i));
2214 uint64_t Val = cast<ConstantInt>(FC)->getZExtValue();
2216 Elts.push_back(ConstantInt::getAllOnesValue(EltTy));
2218 Elts.push_back(ConstantInt::get(EltTy, 0ULL));
2221 if (Elts.size() == NumElts)
2222 return ConstantVector::get(&Elts[0], Elts.size());
2224 // Look up the constant in the table first to ensure uniqueness
2225 std::vector<Constant*> ArgVec;
2226 ArgVec.push_back(LHS);
2227 ArgVec.push_back(RHS);
2228 // Get the key type with both the opcode and predicate
2229 const ExprMapKeyType Key(Instruction::VICmp, ArgVec, pred);
2230 return ExprConstants->getOrCreate(LHS->getType(), Key);
2234 ConstantExpr::getVFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2235 assert(isa<VectorType>(LHS->getType()) &&
2236 "Tried to create vfcmp operation on non-vector type!");
2237 assert(LHS->getType() == RHS->getType());
2238 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid VFCmp Predicate");
2240 const VectorType *VTy = cast<VectorType>(LHS->getType());
2241 unsigned NumElts = VTy->getNumElements();
2242 const Type *EltTy = VTy->getElementType();
2243 const Type *REltTy = IntegerType::get(EltTy->getPrimitiveSizeInBits());
2244 const Type *ResultTy = VectorType::get(REltTy, NumElts);
2246 SmallVector<Constant *, 8> Elts;
2247 for (unsigned i = 0; i != NumElts; ++i) {
2248 Constant *FC = ConstantFoldCompareInstruction(pred, LHS->getOperand(i),
2249 RHS->getOperand(i));
2251 uint64_t Val = cast<ConstantInt>(FC)->getZExtValue();
2253 Elts.push_back(ConstantInt::getAllOnesValue(REltTy));
2255 Elts.push_back(ConstantInt::get(REltTy, 0ULL));
2258 if (Elts.size() == NumElts)
2259 return ConstantVector::get(&Elts[0], Elts.size());
2261 // Look up the constant in the table first to ensure uniqueness
2262 std::vector<Constant*> ArgVec;
2263 ArgVec.push_back(LHS);
2264 ArgVec.push_back(RHS);
2265 // Get the key type with both the opcode and predicate
2266 const ExprMapKeyType Key(Instruction::VFCmp, ArgVec, pred);
2267 return ExprConstants->getOrCreate(ResultTy, Key);
2270 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
2272 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
2273 return FC; // Fold a few common cases...
2274 // Look up the constant in the table first to ensure uniqueness
2275 std::vector<Constant*> ArgVec(1, Val);
2276 ArgVec.push_back(Idx);
2277 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
2278 return ExprConstants->getOrCreate(ReqTy, Key);
2281 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
2282 assert(isa<VectorType>(Val->getType()) &&
2283 "Tried to create extractelement operation on non-vector type!");
2284 assert(Idx->getType() == Type::Int32Ty &&
2285 "Extractelement index must be i32 type!");
2286 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
2290 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
2291 Constant *Elt, Constant *Idx) {
2292 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2293 return FC; // Fold a few common cases...
2294 // Look up the constant in the table first to ensure uniqueness
2295 std::vector<Constant*> ArgVec(1, Val);
2296 ArgVec.push_back(Elt);
2297 ArgVec.push_back(Idx);
2298 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
2299 return ExprConstants->getOrCreate(ReqTy, Key);
2302 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2304 assert(isa<VectorType>(Val->getType()) &&
2305 "Tried to create insertelement operation on non-vector type!");
2306 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
2307 && "Insertelement types must match!");
2308 assert(Idx->getType() == Type::Int32Ty &&
2309 "Insertelement index must be i32 type!");
2310 return getInsertElementTy(cast<VectorType>(Val->getType())->getElementType(),
2314 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
2315 Constant *V2, Constant *Mask) {
2316 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2317 return FC; // Fold a few common cases...
2318 // Look up the constant in the table first to ensure uniqueness
2319 std::vector<Constant*> ArgVec(1, V1);
2320 ArgVec.push_back(V2);
2321 ArgVec.push_back(Mask);
2322 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
2323 return ExprConstants->getOrCreate(ReqTy, Key);
2326 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2328 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2329 "Invalid shuffle vector constant expr operands!");
2330 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
2333 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
2335 const unsigned *Idxs, unsigned NumIdx) {
2336 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2337 Idxs+NumIdx) == Val->getType() &&
2338 "insertvalue indices invalid!");
2339 assert(Agg->getType() == ReqTy &&
2340 "insertvalue type invalid!");
2341 assert(Agg->getType()->isFirstClassType() &&
2342 "Non-first-class type for constant InsertValue expression");
2343 if (Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs, NumIdx))
2344 return FC; // Fold a few common cases...
2345 // Look up the constant in the table first to ensure uniqueness
2346 std::vector<Constant*> ArgVec;
2347 ArgVec.push_back(Agg);
2348 ArgVec.push_back(Val);
2349 SmallVector<unsigned, 4> Indices(Idxs, Idxs + NumIdx);
2350 const ExprMapKeyType Key(Instruction::InsertValue, ArgVec, 0, Indices);
2351 return ExprConstants->getOrCreate(ReqTy, Key);
2354 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
2355 const unsigned *IdxList, unsigned NumIdx) {
2356 assert(Agg->getType()->isFirstClassType() &&
2357 "Tried to create insertelement operation on non-first-class type!");
2359 const Type *ReqTy = Agg->getType();
2361 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2362 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
2363 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
2366 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
2367 const unsigned *Idxs, unsigned NumIdx) {
2368 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2369 Idxs+NumIdx) == ReqTy &&
2370 "extractvalue indices invalid!");
2371 assert(Agg->getType()->isFirstClassType() &&
2372 "Non-first-class type for constant extractvalue expression");
2373 if (Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs, NumIdx))
2374 return FC; // Fold a few common cases...
2375 // Look up the constant in the table first to ensure uniqueness
2376 std::vector<Constant*> ArgVec;
2377 ArgVec.push_back(Agg);
2378 SmallVector<unsigned, 4> Indices(Idxs, Idxs + NumIdx);
2379 const ExprMapKeyType Key(Instruction::ExtractValue, ArgVec, 0, Indices);
2380 return ExprConstants->getOrCreate(ReqTy, Key);
2383 Constant *ConstantExpr::getExtractValue(Constant *Agg,
2384 const unsigned *IdxList, unsigned NumIdx) {
2385 assert(Agg->getType()->isFirstClassType() &&
2386 "Tried to create extractelement operation on non-first-class type!");
2389 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2390 assert(ReqTy && "extractvalue indices invalid!");
2391 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
2394 Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
2395 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
2396 if (PTy->getElementType()->isFloatingPoint()) {
2397 std::vector<Constant*> zeros(PTy->getNumElements(),
2398 ConstantFP::getNegativeZero(PTy->getElementType()));
2399 return ConstantVector::get(PTy, zeros);
2402 if (Ty->isFloatingPoint())
2403 return ConstantFP::getNegativeZero(Ty);
2405 return Constant::getNullValue(Ty);
2408 // destroyConstant - Remove the constant from the constant table...
2410 void ConstantExpr::destroyConstant() {
2411 ExprConstants->remove(this);
2412 destroyConstantImpl();
2415 const char *ConstantExpr::getOpcodeName() const {
2416 return Instruction::getOpcodeName(getOpcode());
2419 //===----------------------------------------------------------------------===//
2420 // replaceUsesOfWithOnConstant implementations
2422 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2423 /// 'From' to be uses of 'To'. This must update the uniquing data structures
2426 /// Note that we intentionally replace all uses of From with To here. Consider
2427 /// a large array that uses 'From' 1000 times. By handling this case all here,
2428 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2429 /// single invocation handles all 1000 uses. Handling them one at a time would
2430 /// work, but would be really slow because it would have to unique each updated
2432 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
2434 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2435 Constant *ToC = cast<Constant>(To);
2437 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
2438 Lookup.first.first = getType();
2439 Lookup.second = this;
2441 std::vector<Constant*> &Values = Lookup.first.second;
2442 Values.reserve(getNumOperands()); // Build replacement array.
2444 // Fill values with the modified operands of the constant array. Also,
2445 // compute whether this turns into an all-zeros array.
2446 bool isAllZeros = false;
2447 unsigned NumUpdated = 0;
2448 if (!ToC->isNullValue()) {
2449 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2450 Constant *Val = cast<Constant>(O->get());
2455 Values.push_back(Val);
2459 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2460 Constant *Val = cast<Constant>(O->get());
2465 Values.push_back(Val);
2466 if (isAllZeros) isAllZeros = Val->isNullValue();
2470 Constant *Replacement = 0;
2472 Replacement = ConstantAggregateZero::get(getType());
2474 // Check to see if we have this array type already.
2476 ArrayConstantsTy::MapTy::iterator I =
2477 ArrayConstants->InsertOrGetItem(Lookup, Exists);
2480 Replacement = I->second;
2482 // Okay, the new shape doesn't exist in the system yet. Instead of
2483 // creating a new constant array, inserting it, replaceallusesof'ing the
2484 // old with the new, then deleting the old... just update the current one
2486 ArrayConstants->MoveConstantToNewSlot(this, I);
2488 // Update to the new value. Optimize for the case when we have a single
2489 // operand that we're changing, but handle bulk updates efficiently.
2490 if (NumUpdated == 1) {
2491 unsigned OperandToUpdate = U-OperandList;
2492 assert(getOperand(OperandToUpdate) == From &&
2493 "ReplaceAllUsesWith broken!");
2494 setOperand(OperandToUpdate, ToC);
2496 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2497 if (getOperand(i) == From)
2504 // Otherwise, I do need to replace this with an existing value.
2505 assert(Replacement != this && "I didn't contain From!");
2507 // Everyone using this now uses the replacement.
2508 uncheckedReplaceAllUsesWith(Replacement);
2510 // Delete the old constant!
2514 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2516 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2517 Constant *ToC = cast<Constant>(To);
2519 unsigned OperandToUpdate = U-OperandList;
2520 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2522 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
2523 Lookup.first.first = getType();
2524 Lookup.second = this;
2525 std::vector<Constant*> &Values = Lookup.first.second;
2526 Values.reserve(getNumOperands()); // Build replacement struct.
2529 // Fill values with the modified operands of the constant struct. Also,
2530 // compute whether this turns into an all-zeros struct.
2531 bool isAllZeros = false;
2532 if (!ToC->isNullValue()) {
2533 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2534 Values.push_back(cast<Constant>(O->get()));
2537 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2538 Constant *Val = cast<Constant>(O->get());
2539 Values.push_back(Val);
2540 if (isAllZeros) isAllZeros = Val->isNullValue();
2543 Values[OperandToUpdate] = ToC;
2545 Constant *Replacement = 0;
2547 Replacement = ConstantAggregateZero::get(getType());
2549 // Check to see if we have this array type already.
2551 StructConstantsTy::MapTy::iterator I =
2552 StructConstants->InsertOrGetItem(Lookup, Exists);
2555 Replacement = I->second;
2557 // Okay, the new shape doesn't exist in the system yet. Instead of
2558 // creating a new constant struct, inserting it, replaceallusesof'ing the
2559 // old with the new, then deleting the old... just update the current one
2561 StructConstants->MoveConstantToNewSlot(this, I);
2563 // Update to the new value.
2564 setOperand(OperandToUpdate, ToC);
2569 assert(Replacement != this && "I didn't contain From!");
2571 // Everyone using this now uses the replacement.
2572 uncheckedReplaceAllUsesWith(Replacement);
2574 // Delete the old constant!
2578 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2580 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2582 std::vector<Constant*> Values;
2583 Values.reserve(getNumOperands()); // Build replacement array...
2584 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2585 Constant *Val = getOperand(i);
2586 if (Val == From) Val = cast<Constant>(To);
2587 Values.push_back(Val);
2590 Constant *Replacement = ConstantVector::get(getType(), Values);
2591 assert(Replacement != this && "I didn't contain From!");
2593 // Everyone using this now uses the replacement.
2594 uncheckedReplaceAllUsesWith(Replacement);
2596 // Delete the old constant!
2600 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2602 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2603 Constant *To = cast<Constant>(ToV);
2605 Constant *Replacement = 0;
2606 if (getOpcode() == Instruction::GetElementPtr) {
2607 SmallVector<Constant*, 8> Indices;
2608 Constant *Pointer = getOperand(0);
2609 Indices.reserve(getNumOperands()-1);
2610 if (Pointer == From) Pointer = To;
2612 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2613 Constant *Val = getOperand(i);
2614 if (Val == From) Val = To;
2615 Indices.push_back(Val);
2617 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2618 &Indices[0], Indices.size());
2619 } else if (getOpcode() == Instruction::ExtractValue) {
2620 Constant *Agg = getOperand(0);
2621 if (Agg == From) Agg = To;
2623 const SmallVector<unsigned, 4> &Indices = getIndices();
2624 Replacement = ConstantExpr::getExtractValue(Agg,
2625 &Indices[0], Indices.size());
2626 } else if (getOpcode() == Instruction::InsertValue) {
2627 Constant *Agg = getOperand(0);
2628 Constant *Val = getOperand(1);
2629 if (Agg == From) Agg = To;
2630 if (Val == From) Val = To;
2632 const SmallVector<unsigned, 4> &Indices = getIndices();
2633 Replacement = ConstantExpr::getInsertValue(Agg, Val,
2634 &Indices[0], Indices.size());
2635 } else if (isCast()) {
2636 assert(getOperand(0) == From && "Cast only has one use!");
2637 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2638 } else if (getOpcode() == Instruction::Select) {
2639 Constant *C1 = getOperand(0);
2640 Constant *C2 = getOperand(1);
2641 Constant *C3 = getOperand(2);
2642 if (C1 == From) C1 = To;
2643 if (C2 == From) C2 = To;
2644 if (C3 == From) C3 = To;
2645 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2646 } else if (getOpcode() == Instruction::ExtractElement) {
2647 Constant *C1 = getOperand(0);
2648 Constant *C2 = getOperand(1);
2649 if (C1 == From) C1 = To;
2650 if (C2 == From) C2 = To;
2651 Replacement = ConstantExpr::getExtractElement(C1, C2);
2652 } else if (getOpcode() == Instruction::InsertElement) {
2653 Constant *C1 = getOperand(0);
2654 Constant *C2 = getOperand(1);
2655 Constant *C3 = getOperand(1);
2656 if (C1 == From) C1 = To;
2657 if (C2 == From) C2 = To;
2658 if (C3 == From) C3 = To;
2659 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2660 } else if (getOpcode() == Instruction::ShuffleVector) {
2661 Constant *C1 = getOperand(0);
2662 Constant *C2 = getOperand(1);
2663 Constant *C3 = getOperand(2);
2664 if (C1 == From) C1 = To;
2665 if (C2 == From) C2 = To;
2666 if (C3 == From) C3 = To;
2667 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2668 } else if (isCompare()) {
2669 Constant *C1 = getOperand(0);
2670 Constant *C2 = getOperand(1);
2671 if (C1 == From) C1 = To;
2672 if (C2 == From) C2 = To;
2673 if (getOpcode() == Instruction::ICmp)
2674 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2676 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2677 } else if (getNumOperands() == 2) {
2678 Constant *C1 = getOperand(0);
2679 Constant *C2 = getOperand(1);
2680 if (C1 == From) C1 = To;
2681 if (C2 == From) C2 = To;
2682 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2684 assert(0 && "Unknown ConstantExpr type!");
2688 assert(Replacement != this && "I didn't contain From!");
2690 // Everyone using this now uses the replacement.
2691 uncheckedReplaceAllUsesWith(Replacement);
2693 // Delete the old constant!