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 //===----------------------------------------------------------------------===//
160 //===----------------------------------------------------------------------===//
162 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
163 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
164 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
167 ConstantInt *ConstantInt::TheTrueVal = 0;
168 ConstantInt *ConstantInt::TheFalseVal = 0;
171 void CleanupTrueFalse(void *) {
172 ConstantInt::ResetTrueFalse();
176 static ManagedCleanup<llvm::CleanupTrueFalse> TrueFalseCleanup;
178 ConstantInt *ConstantInt::CreateTrueFalseVals(bool WhichOne) {
179 assert(TheTrueVal == 0 && TheFalseVal == 0);
180 TheTrueVal = get(Type::Int1Ty, 1);
181 TheFalseVal = get(Type::Int1Ty, 0);
183 // Ensure that llvm_shutdown nulls out TheTrueVal/TheFalseVal.
184 TrueFalseCleanup.Register();
186 return WhichOne ? TheTrueVal : TheFalseVal;
191 struct DenseMapAPIntKeyInfo {
195 KeyTy(const APInt& V, const Type* Ty) : val(V), type(Ty) {}
196 KeyTy(const KeyTy& that) : val(that.val), type(that.type) {}
197 bool operator==(const KeyTy& that) const {
198 return type == that.type && this->val == that.val;
200 bool operator!=(const KeyTy& that) const {
201 return !this->operator==(that);
204 static inline KeyTy getEmptyKey() { return KeyTy(APInt(1,0), 0); }
205 static inline KeyTy getTombstoneKey() { return KeyTy(APInt(1,1), 0); }
206 static unsigned getHashValue(const KeyTy &Key) {
207 return DenseMapInfo<void*>::getHashValue(Key.type) ^
208 Key.val.getHashValue();
210 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
213 static bool isPod() { return false; }
218 typedef DenseMap<DenseMapAPIntKeyInfo::KeyTy, ConstantInt*,
219 DenseMapAPIntKeyInfo> IntMapTy;
220 static ManagedStatic<IntMapTy> IntConstants;
222 ConstantInt *ConstantInt::get(const Type *Ty, uint64_t V, bool isSigned) {
223 const IntegerType *ITy = cast<IntegerType>(Ty);
224 return get(APInt(ITy->getBitWidth(), V, isSigned));
227 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
228 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
229 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
230 // compare APInt's of different widths, which would violate an APInt class
231 // invariant which generates an assertion.
232 ConstantInt *ConstantInt::get(const APInt& V) {
233 // Get the corresponding integer type for the bit width of the value.
234 const IntegerType *ITy = IntegerType::get(V.getBitWidth());
235 // get an existing value or the insertion position
236 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
237 ConstantInt *&Slot = (*IntConstants)[Key];
238 // if it exists, return it.
241 // otherwise create a new one, insert it, and return it.
242 return Slot = new ConstantInt(ITy, V);
245 //===----------------------------------------------------------------------===//
247 //===----------------------------------------------------------------------===//
249 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
250 if (Ty == Type::FloatTy)
251 return &APFloat::IEEEsingle;
252 if (Ty == Type::DoubleTy)
253 return &APFloat::IEEEdouble;
254 if (Ty == Type::X86_FP80Ty)
255 return &APFloat::x87DoubleExtended;
256 else if (Ty == Type::FP128Ty)
257 return &APFloat::IEEEquad;
259 assert(Ty == Type::PPC_FP128Ty && "Unknown FP format");
260 return &APFloat::PPCDoubleDouble;
263 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
264 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
265 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
269 bool ConstantFP::isNullValue() const {
270 return Val.isZero() && !Val.isNegative();
273 ConstantFP *ConstantFP::getNegativeZero(const Type *Ty) {
274 APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
276 return ConstantFP::get(apf);
279 bool ConstantFP::isExactlyValue(const APFloat& V) const {
280 return Val.bitwiseIsEqual(V);
284 struct DenseMapAPFloatKeyInfo {
287 KeyTy(const APFloat& V) : val(V){}
288 KeyTy(const KeyTy& that) : val(that.val) {}
289 bool operator==(const KeyTy& that) const {
290 return this->val.bitwiseIsEqual(that.val);
292 bool operator!=(const KeyTy& that) const {
293 return !this->operator==(that);
296 static inline KeyTy getEmptyKey() {
297 return KeyTy(APFloat(APFloat::Bogus,1));
299 static inline KeyTy getTombstoneKey() {
300 return KeyTy(APFloat(APFloat::Bogus,2));
302 static unsigned getHashValue(const KeyTy &Key) {
303 return Key.val.getHashValue();
305 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
308 static bool isPod() { return false; }
312 //---- ConstantFP::get() implementation...
314 typedef DenseMap<DenseMapAPFloatKeyInfo::KeyTy, ConstantFP*,
315 DenseMapAPFloatKeyInfo> FPMapTy;
317 static ManagedStatic<FPMapTy> FPConstants;
319 ConstantFP *ConstantFP::get(const APFloat &V) {
320 DenseMapAPFloatKeyInfo::KeyTy Key(V);
321 ConstantFP *&Slot = (*FPConstants)[Key];
322 if (Slot) return Slot;
325 if (&V.getSemantics() == &APFloat::IEEEsingle)
327 else if (&V.getSemantics() == &APFloat::IEEEdouble)
329 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
330 Ty = Type::X86_FP80Ty;
331 else if (&V.getSemantics() == &APFloat::IEEEquad)
334 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble&&"Unknown FP format");
335 Ty = Type::PPC_FP128Ty;
338 return Slot = new ConstantFP(Ty, V);
341 /// get() - This returns a constant fp for the specified value in the
342 /// specified type. This should only be used for simple constant values like
343 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
344 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
346 FV.convert(*TypeToFloatSemantics(Ty), APFloat::rmNearestTiesToEven);
350 //===----------------------------------------------------------------------===//
351 // ConstantXXX Classes
352 //===----------------------------------------------------------------------===//
355 ConstantArray::ConstantArray(const ArrayType *T,
356 const std::vector<Constant*> &V)
357 : Constant(T, ConstantArrayVal,
358 OperandTraits<ConstantArray>::op_end(this) - V.size(),
360 assert(V.size() == T->getNumElements() &&
361 "Invalid initializer vector for constant array");
362 Use *OL = OperandList;
363 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
366 assert((C->getType() == T->getElementType() ||
368 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
369 "Initializer for array element doesn't match array element type!");
375 ConstantStruct::ConstantStruct(const StructType *T,
376 const std::vector<Constant*> &V)
377 : Constant(T, ConstantStructVal,
378 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
380 assert(V.size() == T->getNumElements() &&
381 "Invalid initializer vector for constant structure");
382 Use *OL = OperandList;
383 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
386 assert((C->getType() == T->getElementType(I-V.begin()) ||
387 ((T->getElementType(I-V.begin())->isAbstract() ||
388 C->getType()->isAbstract()) &&
389 T->getElementType(I-V.begin())->getTypeID() ==
390 C->getType()->getTypeID())) &&
391 "Initializer for struct element doesn't match struct element type!");
397 ConstantVector::ConstantVector(const VectorType *T,
398 const std::vector<Constant*> &V)
399 : Constant(T, ConstantVectorVal,
400 OperandTraits<ConstantVector>::op_end(this) - V.size(),
402 Use *OL = OperandList;
403 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
406 assert((C->getType() == T->getElementType() ||
408 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
409 "Initializer for vector element doesn't match vector element type!");
416 // We declare several classes private to this file, so use an anonymous
420 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
421 /// behind the scenes to implement unary constant exprs.
422 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
423 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
425 // allocate space for exactly one operand
426 void *operator new(size_t s) {
427 return User::operator new(s, 1);
429 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
430 : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
433 /// Transparently provide more efficient getOperand methods.
434 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
437 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
438 /// behind the scenes to implement binary constant exprs.
439 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
440 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
442 // allocate space for exactly two operands
443 void *operator new(size_t s) {
444 return User::operator new(s, 2);
446 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
447 : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
451 /// Transparently provide more efficient getOperand methods.
452 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
455 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
456 /// behind the scenes to implement select constant exprs.
457 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
458 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
460 // allocate space for exactly three operands
461 void *operator new(size_t s) {
462 return User::operator new(s, 3);
464 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
465 : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
470 /// Transparently provide more efficient getOperand methods.
471 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
474 /// ExtractElementConstantExpr - This class is private to
475 /// Constants.cpp, and is used behind the scenes to implement
476 /// extractelement constant exprs.
477 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
478 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
480 // allocate space for exactly two operands
481 void *operator new(size_t s) {
482 return User::operator new(s, 2);
484 ExtractElementConstantExpr(Constant *C1, Constant *C2)
485 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
486 Instruction::ExtractElement, &Op<0>(), 2) {
490 /// Transparently provide more efficient getOperand methods.
491 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
494 /// InsertElementConstantExpr - This class is private to
495 /// Constants.cpp, and is used behind the scenes to implement
496 /// insertelement constant exprs.
497 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
498 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
500 // allocate space for exactly three operands
501 void *operator new(size_t s) {
502 return User::operator new(s, 3);
504 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
505 : ConstantExpr(C1->getType(), Instruction::InsertElement,
511 /// Transparently provide more efficient getOperand methods.
512 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
515 /// ShuffleVectorConstantExpr - This class is private to
516 /// Constants.cpp, and is used behind the scenes to implement
517 /// shufflevector constant exprs.
518 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
519 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
521 // allocate space for exactly three operands
522 void *operator new(size_t s) {
523 return User::operator new(s, 3);
525 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
526 : ConstantExpr(C1->getType(), Instruction::ShuffleVector,
532 /// Transparently provide more efficient getOperand methods.
533 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
536 /// ExtractValueConstantExpr - This class is private to
537 /// Constants.cpp, and is used behind the scenes to implement
538 /// extractvalue constant exprs.
539 class VISIBILITY_HIDDEN ExtractValueConstantExpr : public ConstantExpr {
540 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
542 // allocate space for exactly one operand
543 void *operator new(size_t s) {
544 return User::operator new(s, 1);
546 ExtractValueConstantExpr(Constant *Agg,
547 const SmallVector<unsigned, 4> &IdxList,
549 : ConstantExpr(DestTy, Instruction::ExtractValue, &Op<0>(), 1),
554 /// Indices - These identify which value to extract.
555 const SmallVector<unsigned, 4> Indices;
557 /// Transparently provide more efficient getOperand methods.
558 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
561 /// InsertValueConstantExpr - This class is private to
562 /// Constants.cpp, and is used behind the scenes to implement
563 /// insertvalue constant exprs.
564 class VISIBILITY_HIDDEN InsertValueConstantExpr : 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, 2);
571 InsertValueConstantExpr(Constant *Agg, Constant *Val,
572 const SmallVector<unsigned, 4> &IdxList,
574 : ConstantExpr(DestTy, Instruction::InsertValue, &Op<0>(), 2),
580 /// Indices - These identify the position for the insertion.
581 const SmallVector<unsigned, 4> Indices;
583 /// Transparently provide more efficient getOperand methods.
584 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
588 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
589 /// used behind the scenes to implement getelementpr constant exprs.
590 class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
591 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
594 static GetElementPtrConstantExpr *Create(Constant *C,
595 const std::vector<Constant*>&IdxList,
596 const Type *DestTy) {
597 return new(IdxList.size() + 1)
598 GetElementPtrConstantExpr(C, IdxList, DestTy);
600 /// Transparently provide more efficient getOperand methods.
601 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
604 // CompareConstantExpr - This class is private to Constants.cpp, and is used
605 // behind the scenes to implement ICmp and FCmp constant expressions. This is
606 // needed in order to store the predicate value for these instructions.
607 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
608 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
609 // allocate space for exactly two operands
610 void *operator new(size_t s) {
611 return User::operator new(s, 2);
613 unsigned short predicate;
614 CompareConstantExpr(const Type *ty, Instruction::OtherOps opc,
615 unsigned short pred, Constant* LHS, Constant* RHS)
616 : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
620 /// Transparently provide more efficient getOperand methods.
621 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
624 } // end anonymous namespace
627 struct OperandTraits<UnaryConstantExpr> : FixedNumOperandTraits<1> {
629 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
632 struct OperandTraits<BinaryConstantExpr> : FixedNumOperandTraits<2> {
634 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
637 struct OperandTraits<SelectConstantExpr> : FixedNumOperandTraits<3> {
639 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
642 struct OperandTraits<ExtractElementConstantExpr> : FixedNumOperandTraits<2> {
644 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
647 struct OperandTraits<InsertElementConstantExpr> : FixedNumOperandTraits<3> {
649 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
652 struct OperandTraits<ShuffleVectorConstantExpr> : FixedNumOperandTraits<3> {
654 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
657 struct OperandTraits<ExtractValueConstantExpr> : FixedNumOperandTraits<1> {
659 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractValueConstantExpr, Value)
662 struct OperandTraits<InsertValueConstantExpr> : FixedNumOperandTraits<2> {
664 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueConstantExpr, Value)
667 struct OperandTraits<GetElementPtrConstantExpr> : VariadicOperandTraits<1> {
670 GetElementPtrConstantExpr::GetElementPtrConstantExpr
672 const std::vector<Constant*> &IdxList,
674 : ConstantExpr(DestTy, Instruction::GetElementPtr,
675 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
676 - (IdxList.size()+1),
679 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
680 OperandList[i+1] = IdxList[i];
683 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
687 struct OperandTraits<CompareConstantExpr> : FixedNumOperandTraits<2> {
689 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
692 } // End llvm namespace
695 // Utility function for determining if a ConstantExpr is a CastOp or not. This
696 // can't be inline because we don't want to #include Instruction.h into
698 bool ConstantExpr::isCast() const {
699 return Instruction::isCast(getOpcode());
702 bool ConstantExpr::isCompare() const {
703 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
706 bool ConstantExpr::hasIndices() const {
707 return getOpcode() == Instruction::ExtractValue ||
708 getOpcode() == Instruction::InsertValue;
711 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
712 if (const ExtractValueConstantExpr *EVCE =
713 dyn_cast<ExtractValueConstantExpr>(this))
714 return EVCE->Indices;
716 return cast<InsertValueConstantExpr>(this)->Indices;
719 /// ConstantExpr::get* - Return some common constants without having to
720 /// specify the full Instruction::OPCODE identifier.
722 Constant *ConstantExpr::getNeg(Constant *C) {
723 return get(Instruction::Sub,
724 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
727 Constant *ConstantExpr::getNot(Constant *C) {
728 assert(isa<IntegerType>(C->getType()) && "Cannot NOT a nonintegral value!");
729 return get(Instruction::Xor, C,
730 ConstantInt::getAllOnesValue(C->getType()));
732 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
733 return get(Instruction::Add, C1, C2);
735 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
736 return get(Instruction::Sub, C1, C2);
738 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
739 return get(Instruction::Mul, C1, C2);
741 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
742 return get(Instruction::UDiv, C1, C2);
744 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
745 return get(Instruction::SDiv, C1, C2);
747 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
748 return get(Instruction::FDiv, C1, C2);
750 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
751 return get(Instruction::URem, C1, C2);
753 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
754 return get(Instruction::SRem, C1, C2);
756 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
757 return get(Instruction::FRem, C1, C2);
759 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
760 return get(Instruction::And, C1, C2);
762 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
763 return get(Instruction::Or, C1, C2);
765 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
766 return get(Instruction::Xor, C1, C2);
768 unsigned ConstantExpr::getPredicate() const {
769 assert(getOpcode() == Instruction::FCmp ||
770 getOpcode() == Instruction::ICmp ||
771 getOpcode() == Instruction::VFCmp ||
772 getOpcode() == Instruction::VICmp);
773 return ((const CompareConstantExpr*)this)->predicate;
775 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
776 return get(Instruction::Shl, C1, C2);
778 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
779 return get(Instruction::LShr, C1, C2);
781 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
782 return get(Instruction::AShr, C1, C2);
785 /// getWithOperandReplaced - Return a constant expression identical to this
786 /// one, but with the specified operand set to the specified value.
788 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
789 assert(OpNo < getNumOperands() && "Operand num is out of range!");
790 assert(Op->getType() == getOperand(OpNo)->getType() &&
791 "Replacing operand with value of different type!");
792 if (getOperand(OpNo) == Op)
793 return const_cast<ConstantExpr*>(this);
795 Constant *Op0, *Op1, *Op2;
796 switch (getOpcode()) {
797 case Instruction::Trunc:
798 case Instruction::ZExt:
799 case Instruction::SExt:
800 case Instruction::FPTrunc:
801 case Instruction::FPExt:
802 case Instruction::UIToFP:
803 case Instruction::SIToFP:
804 case Instruction::FPToUI:
805 case Instruction::FPToSI:
806 case Instruction::PtrToInt:
807 case Instruction::IntToPtr:
808 case Instruction::BitCast:
809 return ConstantExpr::getCast(getOpcode(), Op, getType());
810 case Instruction::Select:
811 Op0 = (OpNo == 0) ? Op : getOperand(0);
812 Op1 = (OpNo == 1) ? Op : getOperand(1);
813 Op2 = (OpNo == 2) ? Op : getOperand(2);
814 return ConstantExpr::getSelect(Op0, Op1, Op2);
815 case Instruction::InsertElement:
816 Op0 = (OpNo == 0) ? Op : getOperand(0);
817 Op1 = (OpNo == 1) ? Op : getOperand(1);
818 Op2 = (OpNo == 2) ? Op : getOperand(2);
819 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
820 case Instruction::ExtractElement:
821 Op0 = (OpNo == 0) ? Op : getOperand(0);
822 Op1 = (OpNo == 1) ? Op : getOperand(1);
823 return ConstantExpr::getExtractElement(Op0, Op1);
824 case Instruction::ShuffleVector:
825 Op0 = (OpNo == 0) ? Op : getOperand(0);
826 Op1 = (OpNo == 1) ? Op : getOperand(1);
827 Op2 = (OpNo == 2) ? Op : getOperand(2);
828 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
829 case Instruction::InsertValue: {
830 const SmallVector<unsigned, 4> &Indices = getIndices();
831 Op0 = (OpNo == 0) ? Op : getOperand(0);
832 Op1 = (OpNo == 1) ? Op : getOperand(1);
833 return ConstantExpr::getInsertValue(Op0, Op1,
834 &Indices[0], Indices.size());
836 case Instruction::ExtractValue: {
837 assert(OpNo == 0 && "ExtractaValue has only one operand!");
838 const SmallVector<unsigned, 4> &Indices = getIndices();
840 ConstantExpr::getExtractValue(Op, &Indices[0], Indices.size());
842 case Instruction::GetElementPtr: {
843 SmallVector<Constant*, 8> Ops;
844 Ops.resize(getNumOperands()-1);
845 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
846 Ops[i-1] = getOperand(i);
848 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
850 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
853 assert(getNumOperands() == 2 && "Must be binary operator?");
854 Op0 = (OpNo == 0) ? Op : getOperand(0);
855 Op1 = (OpNo == 1) ? Op : getOperand(1);
856 return ConstantExpr::get(getOpcode(), Op0, Op1);
860 /// getWithOperands - This returns the current constant expression with the
861 /// operands replaced with the specified values. The specified operands must
862 /// match count and type with the existing ones.
863 Constant *ConstantExpr::
864 getWithOperands(const std::vector<Constant*> &Ops) const {
865 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
866 bool AnyChange = false;
867 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
868 assert(Ops[i]->getType() == getOperand(i)->getType() &&
869 "Operand type mismatch!");
870 AnyChange |= Ops[i] != getOperand(i);
872 if (!AnyChange) // No operands changed, return self.
873 return const_cast<ConstantExpr*>(this);
875 switch (getOpcode()) {
876 case Instruction::Trunc:
877 case Instruction::ZExt:
878 case Instruction::SExt:
879 case Instruction::FPTrunc:
880 case Instruction::FPExt:
881 case Instruction::UIToFP:
882 case Instruction::SIToFP:
883 case Instruction::FPToUI:
884 case Instruction::FPToSI:
885 case Instruction::PtrToInt:
886 case Instruction::IntToPtr:
887 case Instruction::BitCast:
888 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
889 case Instruction::Select:
890 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
891 case Instruction::InsertElement:
892 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
893 case Instruction::ExtractElement:
894 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
895 case Instruction::ShuffleVector:
896 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
897 case Instruction::InsertValue: {
898 const SmallVector<unsigned, 4> &Indices = getIndices();
899 return ConstantExpr::getInsertValue(Ops[0], Ops[1],
900 &Indices[0], Indices.size());
902 case Instruction::ExtractValue: {
903 const SmallVector<unsigned, 4> &Indices = getIndices();
904 return ConstantExpr::getExtractValue(Ops[0],
905 &Indices[0], Indices.size());
907 case Instruction::GetElementPtr:
908 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], Ops.size()-1);
909 case Instruction::ICmp:
910 case Instruction::FCmp:
911 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
913 assert(getNumOperands() == 2 && "Must be binary operator?");
914 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
919 //===----------------------------------------------------------------------===//
920 // isValueValidForType implementations
922 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
923 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
924 if (Ty == Type::Int1Ty)
925 return Val == 0 || Val == 1;
927 return true; // always true, has to fit in largest type
928 uint64_t Max = (1ll << NumBits) - 1;
932 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
933 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
934 if (Ty == Type::Int1Ty)
935 return Val == 0 || Val == 1 || Val == -1;
937 return true; // always true, has to fit in largest type
938 int64_t Min = -(1ll << (NumBits-1));
939 int64_t Max = (1ll << (NumBits-1)) - 1;
940 return (Val >= Min && Val <= Max);
943 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
944 // convert modifies in place, so make a copy.
945 APFloat Val2 = APFloat(Val);
946 switch (Ty->getTypeID()) {
948 return false; // These can't be represented as floating point!
950 // FIXME rounding mode needs to be more flexible
951 case Type::FloatTyID:
952 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
953 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven) ==
955 case Type::DoubleTyID:
956 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
957 &Val2.getSemantics() == &APFloat::IEEEdouble ||
958 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven) ==
960 case Type::X86_FP80TyID:
961 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
962 &Val2.getSemantics() == &APFloat::IEEEdouble ||
963 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
964 case Type::FP128TyID:
965 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
966 &Val2.getSemantics() == &APFloat::IEEEdouble ||
967 &Val2.getSemantics() == &APFloat::IEEEquad;
968 case Type::PPC_FP128TyID:
969 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
970 &Val2.getSemantics() == &APFloat::IEEEdouble ||
971 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
975 //===----------------------------------------------------------------------===//
976 // Factory Function Implementation
979 // The number of operands for each ConstantCreator::create method is
980 // determined by the ConstantTraits template.
981 // ConstantCreator - A class that is used to create constants by
982 // ValueMap*. This class should be partially specialized if there is
983 // something strange that needs to be done to interface to the ctor for the
987 template<class ValType>
988 struct ConstantTraits;
990 template<typename T, typename Alloc>
991 struct VISIBILITY_HIDDEN ConstantTraits< std::vector<T, Alloc> > {
992 static unsigned uses(const std::vector<T, Alloc>& v) {
997 template<class ConstantClass, class TypeClass, class ValType>
998 struct VISIBILITY_HIDDEN ConstantCreator {
999 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
1000 return new(ConstantTraits<ValType>::uses(V)) ConstantClass(Ty, V);
1004 template<class ConstantClass, class TypeClass>
1005 struct VISIBILITY_HIDDEN ConvertConstantType {
1006 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
1007 assert(0 && "This type cannot be converted!\n");
1012 template<class ValType, class TypeClass, class ConstantClass,
1013 bool HasLargeKey = false /*true for arrays and structs*/ >
1014 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
1016 typedef std::pair<const Type*, ValType> MapKey;
1017 typedef std::map<MapKey, Constant *> MapTy;
1018 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
1019 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
1021 /// Map - This is the main map from the element descriptor to the Constants.
1022 /// This is the primary way we avoid creating two of the same shape
1026 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
1027 /// from the constants to their element in Map. This is important for
1028 /// removal of constants from the array, which would otherwise have to scan
1029 /// through the map with very large keys.
1030 InverseMapTy InverseMap;
1032 /// AbstractTypeMap - Map for abstract type constants.
1034 AbstractTypeMapTy AbstractTypeMap;
1037 typename MapTy::iterator map_end() { return Map.end(); }
1039 /// InsertOrGetItem - Return an iterator for the specified element.
1040 /// If the element exists in the map, the returned iterator points to the
1041 /// entry and Exists=true. If not, the iterator points to the newly
1042 /// inserted entry and returns Exists=false. Newly inserted entries have
1043 /// I->second == 0, and should be filled in.
1044 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
1047 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
1048 Exists = !IP.second;
1053 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
1055 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
1056 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
1057 IMI->second->second == CP &&
1058 "InverseMap corrupt!");
1062 typename MapTy::iterator I =
1063 Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
1064 if (I == Map.end() || I->second != CP) {
1065 // FIXME: This should not use a linear scan. If this gets to be a
1066 // performance problem, someone should look at this.
1067 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
1074 /// getOrCreate - Return the specified constant from the map, creating it if
1076 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
1077 MapKey Lookup(Ty, V);
1078 typename MapTy::iterator I = Map.lower_bound(Lookup);
1079 // Is it in the map?
1080 if (I != Map.end() && I->first == Lookup)
1081 return static_cast<ConstantClass *>(I->second);
1083 // If no preexisting value, create one now...
1084 ConstantClass *Result =
1085 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
1087 /// FIXME: why does this assert fail when loading 176.gcc?
1088 //assert(Result->getType() == Ty && "Type specified is not correct!");
1089 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
1091 if (HasLargeKey) // Remember the reverse mapping if needed.
1092 InverseMap.insert(std::make_pair(Result, I));
1094 // If the type of the constant is abstract, make sure that an entry exists
1095 // for it in the AbstractTypeMap.
1096 if (Ty->isAbstract()) {
1097 typename AbstractTypeMapTy::iterator TI =
1098 AbstractTypeMap.lower_bound(Ty);
1100 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
1101 // Add ourselves to the ATU list of the type.
1102 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
1104 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
1110 void remove(ConstantClass *CP) {
1111 typename MapTy::iterator I = FindExistingElement(CP);
1112 assert(I != Map.end() && "Constant not found in constant table!");
1113 assert(I->second == CP && "Didn't find correct element?");
1115 if (HasLargeKey) // Remember the reverse mapping if needed.
1116 InverseMap.erase(CP);
1118 // Now that we found the entry, make sure this isn't the entry that
1119 // the AbstractTypeMap points to.
1120 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
1121 if (Ty->isAbstract()) {
1122 assert(AbstractTypeMap.count(Ty) &&
1123 "Abstract type not in AbstractTypeMap?");
1124 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
1125 if (ATMEntryIt == I) {
1126 // Yes, we are removing the representative entry for this type.
1127 // See if there are any other entries of the same type.
1128 typename MapTy::iterator TmpIt = ATMEntryIt;
1130 // First check the entry before this one...
1131 if (TmpIt != Map.begin()) {
1133 if (TmpIt->first.first != Ty) // Not the same type, move back...
1137 // If we didn't find the same type, try to move forward...
1138 if (TmpIt == ATMEntryIt) {
1140 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
1141 --TmpIt; // No entry afterwards with the same type
1144 // If there is another entry in the map of the same abstract type,
1145 // update the AbstractTypeMap entry now.
1146 if (TmpIt != ATMEntryIt) {
1149 // Otherwise, we are removing the last instance of this type
1150 // from the table. Remove from the ATM, and from user list.
1151 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
1152 AbstractTypeMap.erase(Ty);
1161 /// MoveConstantToNewSlot - If we are about to change C to be the element
1162 /// specified by I, update our internal data structures to reflect this
1164 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
1165 // First, remove the old location of the specified constant in the map.
1166 typename MapTy::iterator OldI = FindExistingElement(C);
1167 assert(OldI != Map.end() && "Constant not found in constant table!");
1168 assert(OldI->second == C && "Didn't find correct element?");
1170 // If this constant is the representative element for its abstract type,
1171 // update the AbstractTypeMap so that the representative element is I.
1172 if (C->getType()->isAbstract()) {
1173 typename AbstractTypeMapTy::iterator ATI =
1174 AbstractTypeMap.find(C->getType());
1175 assert(ATI != AbstractTypeMap.end() &&
1176 "Abstract type not in AbstractTypeMap?");
1177 if (ATI->second == OldI)
1181 // Remove the old entry from the map.
1184 // Update the inverse map so that we know that this constant is now
1185 // located at descriptor I.
1187 assert(I->second == C && "Bad inversemap entry!");
1192 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
1193 typename AbstractTypeMapTy::iterator I =
1194 AbstractTypeMap.find(cast<Type>(OldTy));
1196 assert(I != AbstractTypeMap.end() &&
1197 "Abstract type not in AbstractTypeMap?");
1199 // Convert a constant at a time until the last one is gone. The last one
1200 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
1201 // eliminated eventually.
1203 ConvertConstantType<ConstantClass,
1204 TypeClass>::convert(
1205 static_cast<ConstantClass *>(I->second->second),
1206 cast<TypeClass>(NewTy));
1208 I = AbstractTypeMap.find(cast<Type>(OldTy));
1209 } while (I != AbstractTypeMap.end());
1212 // If the type became concrete without being refined to any other existing
1213 // type, we just remove ourselves from the ATU list.
1214 void typeBecameConcrete(const DerivedType *AbsTy) {
1215 AbsTy->removeAbstractTypeUser(this);
1219 DOUT << "Constant.cpp: ValueMap\n";
1226 //---- ConstantAggregateZero::get() implementation...
1229 // ConstantAggregateZero does not take extra "value" argument...
1230 template<class ValType>
1231 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
1232 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
1233 return new ConstantAggregateZero(Ty);
1238 struct ConvertConstantType<ConstantAggregateZero, Type> {
1239 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1240 // Make everyone now use a constant of the new type...
1241 Constant *New = ConstantAggregateZero::get(NewTy);
1242 assert(New != OldC && "Didn't replace constant??");
1243 OldC->uncheckedReplaceAllUsesWith(New);
1244 OldC->destroyConstant(); // This constant is now dead, destroy it.
1249 static ManagedStatic<ValueMap<char, Type,
1250 ConstantAggregateZero> > AggZeroConstants;
1252 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1254 Constant *ConstantAggregateZero::get(const Type *Ty) {
1255 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
1256 "Cannot create an aggregate zero of non-aggregate type!");
1257 return AggZeroConstants->getOrCreate(Ty, 0);
1260 // destroyConstant - Remove the constant from the constant table...
1262 void ConstantAggregateZero::destroyConstant() {
1263 AggZeroConstants->remove(this);
1264 destroyConstantImpl();
1267 //---- ConstantArray::get() implementation...
1271 struct ConvertConstantType<ConstantArray, ArrayType> {
1272 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1273 // Make everyone now use a constant of the new type...
1274 std::vector<Constant*> C;
1275 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1276 C.push_back(cast<Constant>(OldC->getOperand(i)));
1277 Constant *New = ConstantArray::get(NewTy, C);
1278 assert(New != OldC && "Didn't replace constant??");
1279 OldC->uncheckedReplaceAllUsesWith(New);
1280 OldC->destroyConstant(); // This constant is now dead, destroy it.
1285 static std::vector<Constant*> getValType(ConstantArray *CA) {
1286 std::vector<Constant*> Elements;
1287 Elements.reserve(CA->getNumOperands());
1288 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1289 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1293 typedef ValueMap<std::vector<Constant*>, ArrayType,
1294 ConstantArray, true /*largekey*/> ArrayConstantsTy;
1295 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
1297 Constant *ConstantArray::get(const ArrayType *Ty,
1298 const std::vector<Constant*> &V) {
1299 // If this is an all-zero array, return a ConstantAggregateZero object
1302 if (!C->isNullValue())
1303 return ArrayConstants->getOrCreate(Ty, V);
1304 for (unsigned i = 1, e = V.size(); i != e; ++i)
1306 return ArrayConstants->getOrCreate(Ty, V);
1308 return ConstantAggregateZero::get(Ty);
1311 // destroyConstant - Remove the constant from the constant table...
1313 void ConstantArray::destroyConstant() {
1314 ArrayConstants->remove(this);
1315 destroyConstantImpl();
1318 /// ConstantArray::get(const string&) - Return an array that is initialized to
1319 /// contain the specified string. If length is zero then a null terminator is
1320 /// added to the specified string so that it may be used in a natural way.
1321 /// Otherwise, the length parameter specifies how much of the string to use
1322 /// and it won't be null terminated.
1324 Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
1325 std::vector<Constant*> ElementVals;
1326 for (unsigned i = 0; i < Str.length(); ++i)
1327 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
1329 // Add a null terminator to the string...
1331 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
1334 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
1335 return ConstantArray::get(ATy, ElementVals);
1338 /// isString - This method returns true if the array is an array of i8, and
1339 /// if the elements of the array are all ConstantInt's.
1340 bool ConstantArray::isString() const {
1341 // Check the element type for i8...
1342 if (getType()->getElementType() != Type::Int8Ty)
1344 // Check the elements to make sure they are all integers, not constant
1346 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1347 if (!isa<ConstantInt>(getOperand(i)))
1352 /// isCString - This method returns true if the array is a string (see
1353 /// isString) and it ends in a null byte \0 and does not contains any other
1354 /// null bytes except its terminator.
1355 bool ConstantArray::isCString() const {
1356 // Check the element type for i8...
1357 if (getType()->getElementType() != Type::Int8Ty)
1359 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1360 // Last element must be a null.
1361 if (getOperand(getNumOperands()-1) != Zero)
1363 // Other elements must be non-null integers.
1364 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1365 if (!isa<ConstantInt>(getOperand(i)))
1367 if (getOperand(i) == Zero)
1374 // getAsString - If the sub-element type of this array is i8
1375 // then this method converts the array to an std::string and returns it.
1376 // Otherwise, it asserts out.
1378 std::string ConstantArray::getAsString() const {
1379 assert(isString() && "Not a string!");
1381 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1382 Result += (char)cast<ConstantInt>(getOperand(i))->getZExtValue();
1387 //---- ConstantStruct::get() implementation...
1392 struct ConvertConstantType<ConstantStruct, StructType> {
1393 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1394 // Make everyone now use a constant of the new type...
1395 std::vector<Constant*> C;
1396 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1397 C.push_back(cast<Constant>(OldC->getOperand(i)));
1398 Constant *New = ConstantStruct::get(NewTy, C);
1399 assert(New != OldC && "Didn't replace constant??");
1401 OldC->uncheckedReplaceAllUsesWith(New);
1402 OldC->destroyConstant(); // This constant is now dead, destroy it.
1407 typedef ValueMap<std::vector<Constant*>, StructType,
1408 ConstantStruct, true /*largekey*/> StructConstantsTy;
1409 static ManagedStatic<StructConstantsTy> StructConstants;
1411 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1412 std::vector<Constant*> Elements;
1413 Elements.reserve(CS->getNumOperands());
1414 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1415 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1419 Constant *ConstantStruct::get(const StructType *Ty,
1420 const std::vector<Constant*> &V) {
1421 // Create a ConstantAggregateZero value if all elements are zeros...
1422 for (unsigned i = 0, e = V.size(); i != e; ++i)
1423 if (!V[i]->isNullValue())
1424 return StructConstants->getOrCreate(Ty, V);
1426 return ConstantAggregateZero::get(Ty);
1429 Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
1430 std::vector<const Type*> StructEls;
1431 StructEls.reserve(V.size());
1432 for (unsigned i = 0, e = V.size(); i != e; ++i)
1433 StructEls.push_back(V[i]->getType());
1434 return get(StructType::get(StructEls, packed), V);
1437 // destroyConstant - Remove the constant from the constant table...
1439 void ConstantStruct::destroyConstant() {
1440 StructConstants->remove(this);
1441 destroyConstantImpl();
1444 //---- ConstantVector::get() implementation...
1448 struct ConvertConstantType<ConstantVector, VectorType> {
1449 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
1450 // Make everyone now use a constant of the new type...
1451 std::vector<Constant*> C;
1452 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1453 C.push_back(cast<Constant>(OldC->getOperand(i)));
1454 Constant *New = ConstantVector::get(NewTy, C);
1455 assert(New != OldC && "Didn't replace constant??");
1456 OldC->uncheckedReplaceAllUsesWith(New);
1457 OldC->destroyConstant(); // This constant is now dead, destroy it.
1462 static std::vector<Constant*> getValType(ConstantVector *CP) {
1463 std::vector<Constant*> Elements;
1464 Elements.reserve(CP->getNumOperands());
1465 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1466 Elements.push_back(CP->getOperand(i));
1470 static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
1471 ConstantVector> > VectorConstants;
1473 Constant *ConstantVector::get(const VectorType *Ty,
1474 const std::vector<Constant*> &V) {
1475 // If this is an all-zero vector, return a ConstantAggregateZero object
1478 if (!C->isNullValue())
1479 return VectorConstants->getOrCreate(Ty, V);
1480 for (unsigned i = 1, e = V.size(); i != e; ++i)
1482 return VectorConstants->getOrCreate(Ty, V);
1484 return ConstantAggregateZero::get(Ty);
1487 Constant *ConstantVector::get(const std::vector<Constant*> &V) {
1488 assert(!V.empty() && "Cannot infer type if V is empty");
1489 return get(VectorType::get(V.front()->getType(),V.size()), V);
1492 // destroyConstant - Remove the constant from the constant table...
1494 void ConstantVector::destroyConstant() {
1495 VectorConstants->remove(this);
1496 destroyConstantImpl();
1499 /// This function will return true iff every element in this vector constant
1500 /// is set to all ones.
1501 /// @returns true iff this constant's emements are all set to all ones.
1502 /// @brief Determine if the value is all ones.
1503 bool ConstantVector::isAllOnesValue() const {
1504 // Check out first element.
1505 const Constant *Elt = getOperand(0);
1506 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1507 if (!CI || !CI->isAllOnesValue()) return false;
1508 // Then make sure all remaining elements point to the same value.
1509 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1510 if (getOperand(I) != Elt) return false;
1515 /// getSplatValue - If this is a splat constant, where all of the
1516 /// elements have the same value, return that value. Otherwise return null.
1517 Constant *ConstantVector::getSplatValue() {
1518 // Check out first element.
1519 Constant *Elt = getOperand(0);
1520 // Then make sure all remaining elements point to the same value.
1521 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1522 if (getOperand(I) != Elt) return 0;
1526 //---- ConstantPointerNull::get() implementation...
1530 // ConstantPointerNull does not take extra "value" argument...
1531 template<class ValType>
1532 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1533 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1534 return new ConstantPointerNull(Ty);
1539 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1540 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1541 // Make everyone now use a constant of the new type...
1542 Constant *New = ConstantPointerNull::get(NewTy);
1543 assert(New != OldC && "Didn't replace constant??");
1544 OldC->uncheckedReplaceAllUsesWith(New);
1545 OldC->destroyConstant(); // This constant is now dead, destroy it.
1550 static ManagedStatic<ValueMap<char, PointerType,
1551 ConstantPointerNull> > NullPtrConstants;
1553 static char getValType(ConstantPointerNull *) {
1558 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1559 return NullPtrConstants->getOrCreate(Ty, 0);
1562 // destroyConstant - Remove the constant from the constant table...
1564 void ConstantPointerNull::destroyConstant() {
1565 NullPtrConstants->remove(this);
1566 destroyConstantImpl();
1570 //---- UndefValue::get() implementation...
1574 // UndefValue does not take extra "value" argument...
1575 template<class ValType>
1576 struct ConstantCreator<UndefValue, Type, ValType> {
1577 static UndefValue *create(const Type *Ty, const ValType &V) {
1578 return new UndefValue(Ty);
1583 struct ConvertConstantType<UndefValue, Type> {
1584 static void convert(UndefValue *OldC, const Type *NewTy) {
1585 // Make everyone now use a constant of the new type.
1586 Constant *New = UndefValue::get(NewTy);
1587 assert(New != OldC && "Didn't replace constant??");
1588 OldC->uncheckedReplaceAllUsesWith(New);
1589 OldC->destroyConstant(); // This constant is now dead, destroy it.
1594 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1596 static char getValType(UndefValue *) {
1601 UndefValue *UndefValue::get(const Type *Ty) {
1602 return UndefValueConstants->getOrCreate(Ty, 0);
1605 // destroyConstant - Remove the constant from the constant table.
1607 void UndefValue::destroyConstant() {
1608 UndefValueConstants->remove(this);
1609 destroyConstantImpl();
1613 //---- ConstantExpr::get() implementations...
1618 struct ExprMapKeyType {
1619 typedef SmallVector<unsigned, 4> IndexList;
1621 ExprMapKeyType(unsigned opc,
1622 const std::vector<Constant*> &ops,
1623 unsigned short pred = 0,
1624 const IndexList &inds = IndexList())
1625 : opcode(opc), predicate(pred), operands(ops), indices(inds) {}
1628 std::vector<Constant*> operands;
1630 bool operator==(const ExprMapKeyType& that) const {
1631 return this->opcode == that.opcode &&
1632 this->predicate == that.predicate &&
1633 this->operands == that.operands;
1634 this->indices == that.indices;
1636 bool operator<(const ExprMapKeyType & that) const {
1637 return this->opcode < that.opcode ||
1638 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1639 (this->opcode == that.opcode && this->predicate == that.predicate &&
1640 this->operands < that.operands) ||
1641 (this->opcode == that.opcode && this->predicate == that.predicate &&
1642 this->operands == that.operands && this->indices < that.indices);
1645 bool operator!=(const ExprMapKeyType& that) const {
1646 return !(*this == that);
1654 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1655 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1656 unsigned short pred = 0) {
1657 if (Instruction::isCast(V.opcode))
1658 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1659 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1660 V.opcode < Instruction::BinaryOpsEnd))
1661 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1662 if (V.opcode == Instruction::Select)
1663 return new SelectConstantExpr(V.operands[0], V.operands[1],
1665 if (V.opcode == Instruction::ExtractElement)
1666 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1667 if (V.opcode == Instruction::InsertElement)
1668 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1670 if (V.opcode == Instruction::ShuffleVector)
1671 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1673 if (V.opcode == Instruction::InsertValue)
1674 return new InsertValueConstantExpr(V.operands[0], V.operands[1],
1676 if (V.opcode == Instruction::ExtractValue)
1677 return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
1678 if (V.opcode == Instruction::GetElementPtr) {
1679 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1680 return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
1683 // The compare instructions are weird. We have to encode the predicate
1684 // value and it is combined with the instruction opcode by multiplying
1685 // the opcode by one hundred. We must decode this to get the predicate.
1686 if (V.opcode == Instruction::ICmp)
1687 return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate,
1688 V.operands[0], V.operands[1]);
1689 if (V.opcode == Instruction::FCmp)
1690 return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate,
1691 V.operands[0], V.operands[1]);
1692 if (V.opcode == Instruction::VICmp)
1693 return new CompareConstantExpr(Ty, Instruction::VICmp, V.predicate,
1694 V.operands[0], V.operands[1]);
1695 if (V.opcode == Instruction::VFCmp)
1696 return new CompareConstantExpr(Ty, Instruction::VFCmp, V.predicate,
1697 V.operands[0], V.operands[1]);
1698 assert(0 && "Invalid ConstantExpr!");
1704 struct ConvertConstantType<ConstantExpr, Type> {
1705 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1707 switch (OldC->getOpcode()) {
1708 case Instruction::Trunc:
1709 case Instruction::ZExt:
1710 case Instruction::SExt:
1711 case Instruction::FPTrunc:
1712 case Instruction::FPExt:
1713 case Instruction::UIToFP:
1714 case Instruction::SIToFP:
1715 case Instruction::FPToUI:
1716 case Instruction::FPToSI:
1717 case Instruction::PtrToInt:
1718 case Instruction::IntToPtr:
1719 case Instruction::BitCast:
1720 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1723 case Instruction::Select:
1724 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1725 OldC->getOperand(1),
1726 OldC->getOperand(2));
1729 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1730 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1731 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1732 OldC->getOperand(1));
1734 case Instruction::GetElementPtr:
1735 // Make everyone now use a constant of the new type...
1736 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1737 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1738 &Idx[0], Idx.size());
1742 assert(New != OldC && "Didn't replace constant??");
1743 OldC->uncheckedReplaceAllUsesWith(New);
1744 OldC->destroyConstant(); // This constant is now dead, destroy it.
1747 } // end namespace llvm
1750 static ExprMapKeyType getValType(ConstantExpr *CE) {
1751 std::vector<Constant*> Operands;
1752 Operands.reserve(CE->getNumOperands());
1753 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1754 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1755 return ExprMapKeyType(CE->getOpcode(), Operands,
1756 CE->isCompare() ? CE->getPredicate() : 0,
1758 CE->getIndices() : SmallVector<unsigned, 4>());
1761 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1762 ConstantExpr> > ExprConstants;
1764 /// This is a utility function to handle folding of casts and lookup of the
1765 /// cast in the ExprConstants map. It is used by the various get* methods below.
1766 static inline Constant *getFoldedCast(
1767 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1768 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1769 // Fold a few common cases
1770 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1773 // Look up the constant in the table first to ensure uniqueness
1774 std::vector<Constant*> argVec(1, C);
1775 ExprMapKeyType Key(opc, argVec);
1776 return ExprConstants->getOrCreate(Ty, Key);
1779 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1780 Instruction::CastOps opc = Instruction::CastOps(oc);
1781 assert(Instruction::isCast(opc) && "opcode out of range");
1782 assert(C && Ty && "Null arguments to getCast");
1783 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1787 assert(0 && "Invalid cast opcode");
1789 case Instruction::Trunc: return getTrunc(C, Ty);
1790 case Instruction::ZExt: return getZExt(C, Ty);
1791 case Instruction::SExt: return getSExt(C, Ty);
1792 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1793 case Instruction::FPExt: return getFPExtend(C, Ty);
1794 case Instruction::UIToFP: return getUIToFP(C, Ty);
1795 case Instruction::SIToFP: return getSIToFP(C, Ty);
1796 case Instruction::FPToUI: return getFPToUI(C, Ty);
1797 case Instruction::FPToSI: return getFPToSI(C, Ty);
1798 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1799 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1800 case Instruction::BitCast: return getBitCast(C, Ty);
1805 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1806 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1807 return getCast(Instruction::BitCast, C, Ty);
1808 return getCast(Instruction::ZExt, C, Ty);
1811 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1812 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1813 return getCast(Instruction::BitCast, C, Ty);
1814 return getCast(Instruction::SExt, C, Ty);
1817 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1818 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1819 return getCast(Instruction::BitCast, C, Ty);
1820 return getCast(Instruction::Trunc, C, Ty);
1823 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1824 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1825 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1827 if (Ty->isInteger())
1828 return getCast(Instruction::PtrToInt, S, Ty);
1829 return getCast(Instruction::BitCast, S, Ty);
1832 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1834 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1835 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1836 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1837 Instruction::CastOps opcode =
1838 (SrcBits == DstBits ? Instruction::BitCast :
1839 (SrcBits > DstBits ? Instruction::Trunc :
1840 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1841 return getCast(opcode, C, Ty);
1844 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1845 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1847 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1848 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1849 if (SrcBits == DstBits)
1850 return C; // Avoid a useless cast
1851 Instruction::CastOps opcode =
1852 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1853 return getCast(opcode, C, Ty);
1856 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1857 assert(C->getType()->isInteger() && "Trunc operand must be integer");
1858 assert(Ty->isInteger() && "Trunc produces only integral");
1859 assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1860 "SrcTy must be larger than DestTy for Trunc!");
1862 return getFoldedCast(Instruction::Trunc, C, Ty);
1865 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1866 assert(C->getType()->isInteger() && "SEXt operand must be integral");
1867 assert(Ty->isInteger() && "SExt produces only integer");
1868 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1869 "SrcTy must be smaller than DestTy for SExt!");
1871 return getFoldedCast(Instruction::SExt, C, Ty);
1874 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1875 assert(C->getType()->isInteger() && "ZEXt operand must be integral");
1876 assert(Ty->isInteger() && "ZExt produces only integer");
1877 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1878 "SrcTy must be smaller than DestTy for ZExt!");
1880 return getFoldedCast(Instruction::ZExt, C, Ty);
1883 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1884 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1885 C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1886 "This is an illegal floating point truncation!");
1887 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1890 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1891 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1892 C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1893 "This is an illegal floating point extension!");
1894 return getFoldedCast(Instruction::FPExt, C, Ty);
1897 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1898 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1899 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1900 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1901 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1902 "This is an illegal uint to floating point cast!");
1903 return getFoldedCast(Instruction::UIToFP, C, Ty);
1906 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1907 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1908 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1909 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1910 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1911 "This is an illegal sint to floating point cast!");
1912 return getFoldedCast(Instruction::SIToFP, C, Ty);
1915 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1916 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1917 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1918 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1919 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1920 "This is an illegal floating point to uint cast!");
1921 return getFoldedCast(Instruction::FPToUI, C, Ty);
1924 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1925 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1926 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1927 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1928 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1929 "This is an illegal floating point to sint cast!");
1930 return getFoldedCast(Instruction::FPToSI, C, Ty);
1933 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1934 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1935 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1936 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1939 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1940 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1941 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1942 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1945 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1946 // BitCast implies a no-op cast of type only. No bits change. However, you
1947 // can't cast pointers to anything but pointers.
1948 const Type *SrcTy = C->getType();
1949 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1950 "BitCast cannot cast pointer to non-pointer and vice versa");
1952 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1953 // or nonptr->ptr). For all the other types, the cast is okay if source and
1954 // destination bit widths are identical.
1955 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1956 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1957 assert(SrcBitSize == DstBitSize && "BitCast requies types of same width");
1958 return getFoldedCast(Instruction::BitCast, C, DstTy);
1961 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
1962 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1963 Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
1965 getGetElementPtr(getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
1966 return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
1969 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1970 Constant *C1, Constant *C2) {
1971 // Check the operands for consistency first
1972 assert(Opcode >= Instruction::BinaryOpsBegin &&
1973 Opcode < Instruction::BinaryOpsEnd &&
1974 "Invalid opcode in binary constant expression");
1975 assert(C1->getType() == C2->getType() &&
1976 "Operand types in binary constant expression should match");
1978 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
1979 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1980 return FC; // Fold a few common cases...
1982 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1983 ExprMapKeyType Key(Opcode, argVec);
1984 return ExprConstants->getOrCreate(ReqTy, Key);
1987 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1988 Constant *C1, Constant *C2) {
1989 switch (predicate) {
1990 default: assert(0 && "Invalid CmpInst predicate");
1991 case FCmpInst::FCMP_FALSE: case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_OGT:
1992 case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OLE:
1993 case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_ORD: case FCmpInst::FCMP_UNO:
1994 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UGT: case FCmpInst::FCMP_UGE:
1995 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_ULE: case FCmpInst::FCMP_UNE:
1996 case FCmpInst::FCMP_TRUE:
1997 return getFCmp(predicate, C1, C2);
1998 case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGT:
1999 case ICmpInst::ICMP_UGE: case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE:
2000 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_SGE: case ICmpInst::ICMP_SLT:
2001 case ICmpInst::ICMP_SLE:
2002 return getICmp(predicate, C1, C2);
2006 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
2009 case Instruction::Add:
2010 case Instruction::Sub:
2011 case Instruction::Mul:
2012 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2013 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
2014 isa<VectorType>(C1->getType())) &&
2015 "Tried to create an arithmetic operation on a non-arithmetic type!");
2017 case Instruction::UDiv:
2018 case Instruction::SDiv:
2019 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2020 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
2021 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
2022 "Tried to create an arithmetic operation on a non-arithmetic type!");
2024 case Instruction::FDiv:
2025 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2026 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
2027 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
2028 && "Tried to create an arithmetic operation on a non-arithmetic type!");
2030 case Instruction::URem:
2031 case Instruction::SRem:
2032 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2033 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
2034 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
2035 "Tried to create an arithmetic operation on a non-arithmetic type!");
2037 case Instruction::FRem:
2038 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2039 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
2040 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
2041 && "Tried to create an arithmetic operation on a non-arithmetic type!");
2043 case Instruction::And:
2044 case Instruction::Or:
2045 case Instruction::Xor:
2046 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2047 assert((C1->getType()->isInteger() || isa<VectorType>(C1->getType())) &&
2048 "Tried to create a logical operation on a non-integral type!");
2050 case Instruction::Shl:
2051 case Instruction::LShr:
2052 case Instruction::AShr:
2053 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2054 assert(C1->getType()->isInteger() &&
2055 "Tried to create a shift operation on a non-integer type!");
2062 return getTy(C1->getType(), Opcode, C1, C2);
2065 Constant *ConstantExpr::getCompare(unsigned short pred,
2066 Constant *C1, Constant *C2) {
2067 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2068 return getCompareTy(pred, C1, C2);
2071 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
2072 Constant *V1, Constant *V2) {
2073 assert(C->getType() == Type::Int1Ty && "Select condition must be i1!");
2074 assert(V1->getType() == V2->getType() && "Select value types must match!");
2075 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
2077 if (ReqTy == V1->getType())
2078 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
2079 return SC; // Fold common cases
2081 std::vector<Constant*> argVec(3, C);
2084 ExprMapKeyType Key(Instruction::Select, argVec);
2085 return ExprConstants->getOrCreate(ReqTy, Key);
2088 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
2091 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
2093 cast<PointerType>(ReqTy)->getElementType() &&
2094 "GEP indices invalid!");
2096 if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs, NumIdx))
2097 return FC; // Fold a few common cases...
2099 assert(isa<PointerType>(C->getType()) &&
2100 "Non-pointer type for constant GetElementPtr expression");
2101 // Look up the constant in the table first to ensure uniqueness
2102 std::vector<Constant*> ArgVec;
2103 ArgVec.reserve(NumIdx+1);
2104 ArgVec.push_back(C);
2105 for (unsigned i = 0; i != NumIdx; ++i)
2106 ArgVec.push_back(cast<Constant>(Idxs[i]));
2107 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
2108 return ExprConstants->getOrCreate(ReqTy, Key);
2111 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
2113 // Get the result type of the getelementptr!
2115 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
2116 assert(Ty && "GEP indices invalid!");
2117 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
2118 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
2121 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
2123 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
2128 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2129 assert(LHS->getType() == RHS->getType());
2130 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2131 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
2133 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2134 return FC; // Fold a few common cases...
2136 // Look up the constant in the table first to ensure uniqueness
2137 std::vector<Constant*> ArgVec;
2138 ArgVec.push_back(LHS);
2139 ArgVec.push_back(RHS);
2140 // Get the key type with both the opcode and predicate
2141 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
2142 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2146 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2147 assert(LHS->getType() == RHS->getType());
2148 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
2150 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2151 return FC; // Fold a few common cases...
2153 // Look up the constant in the table first to ensure uniqueness
2154 std::vector<Constant*> ArgVec;
2155 ArgVec.push_back(LHS);
2156 ArgVec.push_back(RHS);
2157 // Get the key type with both the opcode and predicate
2158 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
2159 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2163 ConstantExpr::getVICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2164 assert(isa<VectorType>(LHS->getType()) &&
2165 "Tried to create vicmp operation on non-vector type!");
2166 assert(LHS->getType() == RHS->getType());
2167 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2168 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid VICmp Predicate");
2170 const VectorType *VTy = cast<VectorType>(LHS->getType());
2171 const Type *EltTy = VTy->getElementType();
2172 unsigned NumElts = VTy->getNumElements();
2174 SmallVector<Constant *, 8> Elts;
2175 for (unsigned i = 0; i != NumElts; ++i) {
2176 Constant *FC = ConstantFoldCompareInstruction(pred, LHS->getOperand(i),
2177 RHS->getOperand(i));
2179 uint64_t Val = cast<ConstantInt>(FC)->getZExtValue();
2181 Elts.push_back(ConstantInt::getAllOnesValue(EltTy));
2183 Elts.push_back(ConstantInt::get(EltTy, 0ULL));
2186 if (Elts.size() == NumElts)
2187 return ConstantVector::get(&Elts[0], Elts.size());
2189 // Look up the constant in the table first to ensure uniqueness
2190 std::vector<Constant*> ArgVec;
2191 ArgVec.push_back(LHS);
2192 ArgVec.push_back(RHS);
2193 // Get the key type with both the opcode and predicate
2194 const ExprMapKeyType Key(Instruction::VICmp, ArgVec, pred);
2195 return ExprConstants->getOrCreate(LHS->getType(), Key);
2199 ConstantExpr::getVFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2200 assert(isa<VectorType>(LHS->getType()) &&
2201 "Tried to create vfcmp operation on non-vector type!");
2202 assert(LHS->getType() == RHS->getType());
2203 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid VFCmp Predicate");
2205 const VectorType *VTy = cast<VectorType>(LHS->getType());
2206 unsigned NumElts = VTy->getNumElements();
2207 const Type *EltTy = VTy->getElementType();
2208 const Type *REltTy = IntegerType::get(EltTy->getPrimitiveSizeInBits());
2209 const Type *ResultTy = VectorType::get(REltTy, NumElts);
2211 SmallVector<Constant *, 8> Elts;
2212 for (unsigned i = 0; i != NumElts; ++i) {
2213 Constant *FC = ConstantFoldCompareInstruction(pred, LHS->getOperand(i),
2214 RHS->getOperand(i));
2216 uint64_t Val = cast<ConstantInt>(FC)->getZExtValue();
2218 Elts.push_back(ConstantInt::getAllOnesValue(REltTy));
2220 Elts.push_back(ConstantInt::get(REltTy, 0ULL));
2223 if (Elts.size() == NumElts)
2224 return ConstantVector::get(&Elts[0], Elts.size());
2226 // Look up the constant in the table first to ensure uniqueness
2227 std::vector<Constant*> ArgVec;
2228 ArgVec.push_back(LHS);
2229 ArgVec.push_back(RHS);
2230 // Get the key type with both the opcode and predicate
2231 const ExprMapKeyType Key(Instruction::VFCmp, ArgVec, pred);
2232 return ExprConstants->getOrCreate(ResultTy, Key);
2235 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
2237 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
2238 return FC; // Fold a few common cases...
2239 // Look up the constant in the table first to ensure uniqueness
2240 std::vector<Constant*> ArgVec(1, Val);
2241 ArgVec.push_back(Idx);
2242 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
2243 return ExprConstants->getOrCreate(ReqTy, Key);
2246 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
2247 assert(isa<VectorType>(Val->getType()) &&
2248 "Tried to create extractelement operation on non-vector type!");
2249 assert(Idx->getType() == Type::Int32Ty &&
2250 "Extractelement index must be i32 type!");
2251 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
2255 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
2256 Constant *Elt, Constant *Idx) {
2257 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2258 return FC; // Fold a few common cases...
2259 // Look up the constant in the table first to ensure uniqueness
2260 std::vector<Constant*> ArgVec(1, Val);
2261 ArgVec.push_back(Elt);
2262 ArgVec.push_back(Idx);
2263 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
2264 return ExprConstants->getOrCreate(ReqTy, Key);
2267 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2269 assert(isa<VectorType>(Val->getType()) &&
2270 "Tried to create insertelement operation on non-vector type!");
2271 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
2272 && "Insertelement types must match!");
2273 assert(Idx->getType() == Type::Int32Ty &&
2274 "Insertelement index must be i32 type!");
2275 return getInsertElementTy(cast<VectorType>(Val->getType())->getElementType(),
2279 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
2280 Constant *V2, Constant *Mask) {
2281 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2282 return FC; // Fold a few common cases...
2283 // Look up the constant in the table first to ensure uniqueness
2284 std::vector<Constant*> ArgVec(1, V1);
2285 ArgVec.push_back(V2);
2286 ArgVec.push_back(Mask);
2287 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
2288 return ExprConstants->getOrCreate(ReqTy, Key);
2291 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2293 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2294 "Invalid shuffle vector constant expr operands!");
2295 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
2298 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
2300 const unsigned *Idxs, unsigned NumIdx) {
2301 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2302 Idxs+NumIdx) == Val->getType() &&
2303 "insertvalue indices invalid!");
2304 assert(Agg->getType() == ReqTy &&
2305 "insertvalue type invalid!");
2306 assert(Agg->getType()->isFirstClassType() &&
2307 "Non-first-class type for constant InsertValue expression");
2308 if (Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs, NumIdx))
2309 return FC; // Fold a few common cases...
2310 // Look up the constant in the table first to ensure uniqueness
2311 std::vector<Constant*> ArgVec;
2312 ArgVec.push_back(Agg);
2313 ArgVec.push_back(Val);
2314 SmallVector<unsigned, 4> Indices(Idxs, Idxs + NumIdx);
2315 const ExprMapKeyType Key(Instruction::InsertValue, ArgVec, 0, Indices);
2316 return ExprConstants->getOrCreate(ReqTy, Key);
2319 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
2320 const unsigned *IdxList, unsigned NumIdx) {
2321 assert(Agg->getType()->isFirstClassType() &&
2322 "Tried to create insertelement operation on non-first-class type!");
2324 const Type *ReqTy = Agg->getType();
2326 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2327 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
2328 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
2331 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
2332 const unsigned *Idxs, unsigned NumIdx) {
2333 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2334 Idxs+NumIdx) == ReqTy &&
2335 "extractvalue indices invalid!");
2336 assert(Agg->getType()->isFirstClassType() &&
2337 "Non-first-class type for constant extractvalue expression");
2338 if (Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs, NumIdx))
2339 return FC; // Fold a few common cases...
2340 // Look up the constant in the table first to ensure uniqueness
2341 std::vector<Constant*> ArgVec;
2342 ArgVec.push_back(Agg);
2343 SmallVector<unsigned, 4> Indices(Idxs, Idxs + NumIdx);
2344 const ExprMapKeyType Key(Instruction::ExtractValue, ArgVec, 0, Indices);
2345 return ExprConstants->getOrCreate(ReqTy, Key);
2348 Constant *ConstantExpr::getExtractValue(Constant *Agg,
2349 const unsigned *IdxList, unsigned NumIdx) {
2350 assert(Agg->getType()->isFirstClassType() &&
2351 "Tried to create extractelement operation on non-first-class type!");
2354 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2355 assert(ReqTy && "extractvalue indices invalid!");
2356 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
2359 Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
2360 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
2361 if (PTy->getElementType()->isFloatingPoint()) {
2362 std::vector<Constant*> zeros(PTy->getNumElements(),
2363 ConstantFP::getNegativeZero(PTy->getElementType()));
2364 return ConstantVector::get(PTy, zeros);
2367 if (Ty->isFloatingPoint())
2368 return ConstantFP::getNegativeZero(Ty);
2370 return Constant::getNullValue(Ty);
2373 // destroyConstant - Remove the constant from the constant table...
2375 void ConstantExpr::destroyConstant() {
2376 ExprConstants->remove(this);
2377 destroyConstantImpl();
2380 const char *ConstantExpr::getOpcodeName() const {
2381 return Instruction::getOpcodeName(getOpcode());
2384 //===----------------------------------------------------------------------===//
2385 // replaceUsesOfWithOnConstant implementations
2387 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2388 /// 'From' to be uses of 'To'. This must update the uniquing data structures
2391 /// Note that we intentionally replace all uses of From with To here. Consider
2392 /// a large array that uses 'From' 1000 times. By handling this case all here,
2393 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2394 /// single invocation handles all 1000 uses. Handling them one at a time would
2395 /// work, but would be really slow because it would have to unique each updated
2397 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
2399 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2400 Constant *ToC = cast<Constant>(To);
2402 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
2403 Lookup.first.first = getType();
2404 Lookup.second = this;
2406 std::vector<Constant*> &Values = Lookup.first.second;
2407 Values.reserve(getNumOperands()); // Build replacement array.
2409 // Fill values with the modified operands of the constant array. Also,
2410 // compute whether this turns into an all-zeros array.
2411 bool isAllZeros = false;
2412 unsigned NumUpdated = 0;
2413 if (!ToC->isNullValue()) {
2414 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2415 Constant *Val = cast<Constant>(O->get());
2420 Values.push_back(Val);
2424 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2425 Constant *Val = cast<Constant>(O->get());
2430 Values.push_back(Val);
2431 if (isAllZeros) isAllZeros = Val->isNullValue();
2435 Constant *Replacement = 0;
2437 Replacement = ConstantAggregateZero::get(getType());
2439 // Check to see if we have this array type already.
2441 ArrayConstantsTy::MapTy::iterator I =
2442 ArrayConstants->InsertOrGetItem(Lookup, Exists);
2445 Replacement = I->second;
2447 // Okay, the new shape doesn't exist in the system yet. Instead of
2448 // creating a new constant array, inserting it, replaceallusesof'ing the
2449 // old with the new, then deleting the old... just update the current one
2451 ArrayConstants->MoveConstantToNewSlot(this, I);
2453 // Update to the new value. Optimize for the case when we have a single
2454 // operand that we're changing, but handle bulk updates efficiently.
2455 if (NumUpdated == 1) {
2456 unsigned OperandToUpdate = U-OperandList;
2457 assert(getOperand(OperandToUpdate) == From &&
2458 "ReplaceAllUsesWith broken!");
2459 setOperand(OperandToUpdate, ToC);
2461 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2462 if (getOperand(i) == From)
2469 // Otherwise, I do need to replace this with an existing value.
2470 assert(Replacement != this && "I didn't contain From!");
2472 // Everyone using this now uses the replacement.
2473 uncheckedReplaceAllUsesWith(Replacement);
2475 // Delete the old constant!
2479 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2481 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2482 Constant *ToC = cast<Constant>(To);
2484 unsigned OperandToUpdate = U-OperandList;
2485 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2487 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
2488 Lookup.first.first = getType();
2489 Lookup.second = this;
2490 std::vector<Constant*> &Values = Lookup.first.second;
2491 Values.reserve(getNumOperands()); // Build replacement struct.
2494 // Fill values with the modified operands of the constant struct. Also,
2495 // compute whether this turns into an all-zeros struct.
2496 bool isAllZeros = false;
2497 if (!ToC->isNullValue()) {
2498 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2499 Values.push_back(cast<Constant>(O->get()));
2502 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2503 Constant *Val = cast<Constant>(O->get());
2504 Values.push_back(Val);
2505 if (isAllZeros) isAllZeros = Val->isNullValue();
2508 Values[OperandToUpdate] = ToC;
2510 Constant *Replacement = 0;
2512 Replacement = ConstantAggregateZero::get(getType());
2514 // Check to see if we have this array type already.
2516 StructConstantsTy::MapTy::iterator I =
2517 StructConstants->InsertOrGetItem(Lookup, Exists);
2520 Replacement = I->second;
2522 // Okay, the new shape doesn't exist in the system yet. Instead of
2523 // creating a new constant struct, inserting it, replaceallusesof'ing the
2524 // old with the new, then deleting the old... just update the current one
2526 StructConstants->MoveConstantToNewSlot(this, I);
2528 // Update to the new value.
2529 setOperand(OperandToUpdate, ToC);
2534 assert(Replacement != this && "I didn't contain From!");
2536 // Everyone using this now uses the replacement.
2537 uncheckedReplaceAllUsesWith(Replacement);
2539 // Delete the old constant!
2543 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2545 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2547 std::vector<Constant*> Values;
2548 Values.reserve(getNumOperands()); // Build replacement array...
2549 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2550 Constant *Val = getOperand(i);
2551 if (Val == From) Val = cast<Constant>(To);
2552 Values.push_back(Val);
2555 Constant *Replacement = ConstantVector::get(getType(), Values);
2556 assert(Replacement != this && "I didn't contain From!");
2558 // Everyone using this now uses the replacement.
2559 uncheckedReplaceAllUsesWith(Replacement);
2561 // Delete the old constant!
2565 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2567 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2568 Constant *To = cast<Constant>(ToV);
2570 Constant *Replacement = 0;
2571 if (getOpcode() == Instruction::GetElementPtr) {
2572 SmallVector<Constant*, 8> Indices;
2573 Constant *Pointer = getOperand(0);
2574 Indices.reserve(getNumOperands()-1);
2575 if (Pointer == From) Pointer = To;
2577 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2578 Constant *Val = getOperand(i);
2579 if (Val == From) Val = To;
2580 Indices.push_back(Val);
2582 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2583 &Indices[0], Indices.size());
2584 } else if (getOpcode() == Instruction::ExtractValue) {
2585 Constant *Agg = getOperand(0);
2586 if (Agg == From) Agg = To;
2588 const SmallVector<unsigned, 4> &Indices = getIndices();
2589 Replacement = ConstantExpr::getExtractValue(Agg,
2590 &Indices[0], Indices.size());
2591 } else if (getOpcode() == Instruction::InsertValue) {
2592 Constant *Agg = getOperand(0);
2593 Constant *Val = getOperand(1);
2594 if (Agg == From) Agg = To;
2595 if (Val == From) Val = To;
2597 const SmallVector<unsigned, 4> &Indices = getIndices();
2598 Replacement = ConstantExpr::getInsertValue(Agg, Val,
2599 &Indices[0], Indices.size());
2600 } else if (isCast()) {
2601 assert(getOperand(0) == From && "Cast only has one use!");
2602 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2603 } else if (getOpcode() == Instruction::Select) {
2604 Constant *C1 = getOperand(0);
2605 Constant *C2 = getOperand(1);
2606 Constant *C3 = getOperand(2);
2607 if (C1 == From) C1 = To;
2608 if (C2 == From) C2 = To;
2609 if (C3 == From) C3 = To;
2610 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2611 } else if (getOpcode() == Instruction::ExtractElement) {
2612 Constant *C1 = getOperand(0);
2613 Constant *C2 = getOperand(1);
2614 if (C1 == From) C1 = To;
2615 if (C2 == From) C2 = To;
2616 Replacement = ConstantExpr::getExtractElement(C1, C2);
2617 } else if (getOpcode() == Instruction::InsertElement) {
2618 Constant *C1 = getOperand(0);
2619 Constant *C2 = getOperand(1);
2620 Constant *C3 = getOperand(1);
2621 if (C1 == From) C1 = To;
2622 if (C2 == From) C2 = To;
2623 if (C3 == From) C3 = To;
2624 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2625 } else if (getOpcode() == Instruction::ShuffleVector) {
2626 Constant *C1 = getOperand(0);
2627 Constant *C2 = getOperand(1);
2628 Constant *C3 = getOperand(2);
2629 if (C1 == From) C1 = To;
2630 if (C2 == From) C2 = To;
2631 if (C3 == From) C3 = To;
2632 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2633 } else if (isCompare()) {
2634 Constant *C1 = getOperand(0);
2635 Constant *C2 = getOperand(1);
2636 if (C1 == From) C1 = To;
2637 if (C2 == From) C2 = To;
2638 if (getOpcode() == Instruction::ICmp)
2639 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2641 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2642 } else if (getNumOperands() == 2) {
2643 Constant *C1 = getOperand(0);
2644 Constant *C2 = getOperand(1);
2645 if (C1 == From) C1 = To;
2646 if (C2 == From) C2 = To;
2647 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2649 assert(0 && "Unknown ConstantExpr type!");
2653 assert(Replacement != this && "I didn't contain From!");
2655 // Everyone using this now uses the replacement.
2656 uncheckedReplaceAllUsesWith(Replacement);
2658 // Delete the old constant!
2663 /// getStringValue - Turn an LLVM constant pointer that eventually points to a
2664 /// global into a string value. Return an empty string if we can't do it.
2665 /// Parameter Chop determines if the result is chopped at the first null
2668 std::string Constant::getStringValue(bool Chop, unsigned Offset) {
2669 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
2670 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
2671 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
2672 if (Init->isString()) {
2673 std::string Result = Init->getAsString();
2674 if (Offset < Result.size()) {
2675 // If we are pointing INTO The string, erase the beginning...
2676 Result.erase(Result.begin(), Result.begin()+Offset);
2678 // Take off the null terminator, and any string fragments after it.
2680 std::string::size_type NullPos = Result.find_first_of((char)0);
2681 if (NullPos != std::string::npos)
2682 Result.erase(Result.begin()+NullPos, Result.end());
2688 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(this)) {
2689 if (CE->getOpcode() == Instruction::GetElementPtr) {
2690 // Turn a gep into the specified offset.
2691 if (CE->getNumOperands() == 3 &&
2692 cast<Constant>(CE->getOperand(1))->isNullValue() &&
2693 isa<ConstantInt>(CE->getOperand(2))) {
2694 Offset += cast<ConstantInt>(CE->getOperand(2))->getZExtValue();
2695 return CE->getOperand(0)->getStringValue(Chop, Offset);