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, new Use[V.size()], V.size()) {
358 assert(V.size() == T->getNumElements() &&
359 "Invalid initializer vector for constant array");
360 Use *OL = OperandList;
361 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
364 assert((C->getType() == T->getElementType() ||
366 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
367 "Initializer for array element doesn't match array element type!");
372 ConstantArray::~ConstantArray() {
373 delete [] OperandList;
376 ConstantStruct::ConstantStruct(const StructType *T,
377 const std::vector<Constant*> &V)
378 : Constant(T, ConstantStructVal, new Use[V.size()], V.size()) {
379 assert(V.size() == T->getNumElements() &&
380 "Invalid initializer vector for constant structure");
381 Use *OL = OperandList;
382 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
385 assert((C->getType() == T->getElementType(I-V.begin()) ||
386 ((T->getElementType(I-V.begin())->isAbstract() ||
387 C->getType()->isAbstract()) &&
388 T->getElementType(I-V.begin())->getTypeID() ==
389 C->getType()->getTypeID())) &&
390 "Initializer for struct element doesn't match struct element type!");
395 ConstantStruct::~ConstantStruct() {
396 delete [] OperandList;
400 ConstantVector::ConstantVector(const VectorType *T,
401 const std::vector<Constant*> &V)
402 : Constant(T, ConstantVectorVal, new Use[V.size()], V.size()) {
403 Use *OL = OperandList;
404 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
407 assert((C->getType() == T->getElementType() ||
409 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
410 "Initializer for vector element doesn't match vector element type!");
415 ConstantVector::~ConstantVector() {
416 delete [] OperandList;
419 // We declare several classes private to this file, so use an anonymous
423 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
424 /// behind the scenes to implement unary constant exprs.
425 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
426 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
429 // allocate space for exactly one operand
430 void *operator new(size_t s) {
431 return User::operator new(s, 1);
433 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
434 : ConstantExpr(Ty, Opcode, &Op, 1), Op(C, this) {}
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
443 // allocate space for exactly two operands
444 void *operator new(size_t s) {
445 return User::operator new(s, 2);
447 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
448 : ConstantExpr(C1->getType(), Opcode, Ops, 2) {
449 Ops[0].init(C1, this);
450 Ops[1].init(C2, this);
454 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
455 /// behind the scenes to implement select constant exprs.
456 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
457 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, Ops, 3) {
466 Ops[0].init(C1, this);
467 Ops[1].init(C2, this);
468 Ops[2].init(C3, this);
472 /// ExtractElementConstantExpr - This class is private to
473 /// Constants.cpp, and is used behind the scenes to implement
474 /// extractelement constant exprs.
475 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
476 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
479 // allocate space for exactly two operands
480 void *operator new(size_t s) {
481 return User::operator new(s, 2);
483 ExtractElementConstantExpr(Constant *C1, Constant *C2)
484 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
485 Instruction::ExtractElement, Ops, 2) {
486 Ops[0].init(C1, this);
487 Ops[1].init(C2, this);
491 /// InsertElementConstantExpr - This class is private to
492 /// Constants.cpp, and is used behind the scenes to implement
493 /// insertelement constant exprs.
494 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
495 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
498 // allocate space for exactly three operands
499 void *operator new(size_t s) {
500 return User::operator new(s, 3);
502 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
503 : ConstantExpr(C1->getType(), Instruction::InsertElement,
505 Ops[0].init(C1, this);
506 Ops[1].init(C2, this);
507 Ops[2].init(C3, this);
511 /// ShuffleVectorConstantExpr - This class is private to
512 /// Constants.cpp, and is used behind the scenes to implement
513 /// shufflevector constant exprs.
514 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
515 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
518 // allocate space for exactly three operands
519 void *operator new(size_t s) {
520 return User::operator new(s, 3);
522 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
523 : ConstantExpr(C1->getType(), Instruction::ShuffleVector,
525 Ops[0].init(C1, this);
526 Ops[1].init(C2, this);
527 Ops[2].init(C3, this);
531 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
532 /// used behind the scenes to implement getelementpr constant exprs.
533 class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
534 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
536 : ConstantExpr(DestTy, Instruction::GetElementPtr,
537 new Use[IdxList.size()+1], IdxList.size()+1) {
538 OperandList[0].init(C, this);
539 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
540 OperandList[i+1].init(IdxList[i], this);
543 static GetElementPtrConstantExpr *Create(Constant *C, const std::vector<Constant*> &IdxList,
544 const Type *DestTy) {
545 return new(IdxList.size() + 1/*FIXME*/) GetElementPtrConstantExpr(C, IdxList, DestTy);
547 ~GetElementPtrConstantExpr() {
548 delete [] OperandList;
552 // CompareConstantExpr - This class is private to Constants.cpp, and is used
553 // behind the scenes to implement ICmp and FCmp constant expressions. This is
554 // needed in order to store the predicate value for these instructions.
555 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
556 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
557 // allocate space for exactly two operands
558 void *operator new(size_t s) {
559 return User::operator new(s, 2);
561 unsigned short predicate;
563 CompareConstantExpr(Instruction::OtherOps opc, unsigned short pred,
564 Constant* LHS, Constant* RHS)
565 : ConstantExpr(Type::Int1Ty, opc, Ops, 2), predicate(pred) {
566 OperandList[0].init(LHS, this);
567 OperandList[1].init(RHS, this);
571 } // end anonymous namespace
574 // Utility function for determining if a ConstantExpr is a CastOp or not. This
575 // can't be inline because we don't want to #include Instruction.h into
577 bool ConstantExpr::isCast() const {
578 return Instruction::isCast(getOpcode());
581 bool ConstantExpr::isCompare() const {
582 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
585 /// ConstantExpr::get* - Return some common constants without having to
586 /// specify the full Instruction::OPCODE identifier.
588 Constant *ConstantExpr::getNeg(Constant *C) {
589 return get(Instruction::Sub,
590 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
593 Constant *ConstantExpr::getNot(Constant *C) {
594 assert(isa<IntegerType>(C->getType()) && "Cannot NOT a nonintegral value!");
595 return get(Instruction::Xor, C,
596 ConstantInt::getAllOnesValue(C->getType()));
598 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
599 return get(Instruction::Add, C1, C2);
601 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
602 return get(Instruction::Sub, C1, C2);
604 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
605 return get(Instruction::Mul, C1, C2);
607 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
608 return get(Instruction::UDiv, C1, C2);
610 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
611 return get(Instruction::SDiv, C1, C2);
613 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
614 return get(Instruction::FDiv, C1, C2);
616 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
617 return get(Instruction::URem, C1, C2);
619 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
620 return get(Instruction::SRem, C1, C2);
622 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
623 return get(Instruction::FRem, C1, C2);
625 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
626 return get(Instruction::And, C1, C2);
628 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
629 return get(Instruction::Or, C1, C2);
631 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
632 return get(Instruction::Xor, C1, C2);
634 unsigned ConstantExpr::getPredicate() const {
635 assert(getOpcode() == Instruction::FCmp || getOpcode() == Instruction::ICmp);
636 return ((const CompareConstantExpr*)this)->predicate;
638 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
639 return get(Instruction::Shl, C1, C2);
641 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
642 return get(Instruction::LShr, C1, C2);
644 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
645 return get(Instruction::AShr, C1, C2);
648 /// getWithOperandReplaced - Return a constant expression identical to this
649 /// one, but with the specified operand set to the specified value.
651 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
652 assert(OpNo < getNumOperands() && "Operand num is out of range!");
653 assert(Op->getType() == getOperand(OpNo)->getType() &&
654 "Replacing operand with value of different type!");
655 if (getOperand(OpNo) == Op)
656 return const_cast<ConstantExpr*>(this);
658 Constant *Op0, *Op1, *Op2;
659 switch (getOpcode()) {
660 case Instruction::Trunc:
661 case Instruction::ZExt:
662 case Instruction::SExt:
663 case Instruction::FPTrunc:
664 case Instruction::FPExt:
665 case Instruction::UIToFP:
666 case Instruction::SIToFP:
667 case Instruction::FPToUI:
668 case Instruction::FPToSI:
669 case Instruction::PtrToInt:
670 case Instruction::IntToPtr:
671 case Instruction::BitCast:
672 return ConstantExpr::getCast(getOpcode(), Op, getType());
673 case Instruction::Select:
674 Op0 = (OpNo == 0) ? Op : getOperand(0);
675 Op1 = (OpNo == 1) ? Op : getOperand(1);
676 Op2 = (OpNo == 2) ? Op : getOperand(2);
677 return ConstantExpr::getSelect(Op0, Op1, Op2);
678 case Instruction::InsertElement:
679 Op0 = (OpNo == 0) ? Op : getOperand(0);
680 Op1 = (OpNo == 1) ? Op : getOperand(1);
681 Op2 = (OpNo == 2) ? Op : getOperand(2);
682 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
683 case Instruction::ExtractElement:
684 Op0 = (OpNo == 0) ? Op : getOperand(0);
685 Op1 = (OpNo == 1) ? Op : getOperand(1);
686 return ConstantExpr::getExtractElement(Op0, Op1);
687 case Instruction::ShuffleVector:
688 Op0 = (OpNo == 0) ? Op : getOperand(0);
689 Op1 = (OpNo == 1) ? Op : getOperand(1);
690 Op2 = (OpNo == 2) ? Op : getOperand(2);
691 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
692 case Instruction::GetElementPtr: {
693 SmallVector<Constant*, 8> Ops;
694 Ops.resize(getNumOperands());
695 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
696 Ops[i] = getOperand(i);
698 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
700 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
703 assert(getNumOperands() == 2 && "Must be binary operator?");
704 Op0 = (OpNo == 0) ? Op : getOperand(0);
705 Op1 = (OpNo == 1) ? Op : getOperand(1);
706 return ConstantExpr::get(getOpcode(), Op0, Op1);
710 /// getWithOperands - This returns the current constant expression with the
711 /// operands replaced with the specified values. The specified operands must
712 /// match count and type with the existing ones.
713 Constant *ConstantExpr::
714 getWithOperands(const std::vector<Constant*> &Ops) const {
715 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
716 bool AnyChange = false;
717 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
718 assert(Ops[i]->getType() == getOperand(i)->getType() &&
719 "Operand type mismatch!");
720 AnyChange |= Ops[i] != getOperand(i);
722 if (!AnyChange) // No operands changed, return self.
723 return const_cast<ConstantExpr*>(this);
725 switch (getOpcode()) {
726 case Instruction::Trunc:
727 case Instruction::ZExt:
728 case Instruction::SExt:
729 case Instruction::FPTrunc:
730 case Instruction::FPExt:
731 case Instruction::UIToFP:
732 case Instruction::SIToFP:
733 case Instruction::FPToUI:
734 case Instruction::FPToSI:
735 case Instruction::PtrToInt:
736 case Instruction::IntToPtr:
737 case Instruction::BitCast:
738 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
739 case Instruction::Select:
740 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
741 case Instruction::InsertElement:
742 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
743 case Instruction::ExtractElement:
744 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
745 case Instruction::ShuffleVector:
746 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
747 case Instruction::GetElementPtr:
748 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], Ops.size()-1);
749 case Instruction::ICmp:
750 case Instruction::FCmp:
751 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
753 assert(getNumOperands() == 2 && "Must be binary operator?");
754 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
759 //===----------------------------------------------------------------------===//
760 // isValueValidForType implementations
762 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
763 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
764 if (Ty == Type::Int1Ty)
765 return Val == 0 || Val == 1;
767 return true; // always true, has to fit in largest type
768 uint64_t Max = (1ll << NumBits) - 1;
772 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
773 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
774 if (Ty == Type::Int1Ty)
775 return Val == 0 || Val == 1 || Val == -1;
777 return true; // always true, has to fit in largest type
778 int64_t Min = -(1ll << (NumBits-1));
779 int64_t Max = (1ll << (NumBits-1)) - 1;
780 return (Val >= Min && Val <= Max);
783 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
784 // convert modifies in place, so make a copy.
785 APFloat Val2 = APFloat(Val);
786 switch (Ty->getTypeID()) {
788 return false; // These can't be represented as floating point!
790 // FIXME rounding mode needs to be more flexible
791 case Type::FloatTyID:
792 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
793 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven) ==
795 case Type::DoubleTyID:
796 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
797 &Val2.getSemantics() == &APFloat::IEEEdouble ||
798 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven) ==
800 case Type::X86_FP80TyID:
801 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
802 &Val2.getSemantics() == &APFloat::IEEEdouble ||
803 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
804 case Type::FP128TyID:
805 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
806 &Val2.getSemantics() == &APFloat::IEEEdouble ||
807 &Val2.getSemantics() == &APFloat::IEEEquad;
808 case Type::PPC_FP128TyID:
809 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
810 &Val2.getSemantics() == &APFloat::IEEEdouble ||
811 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
815 //===----------------------------------------------------------------------===//
816 // Factory Function Implementation
818 // ConstantCreator - A class that is used to create constants by
819 // ValueMap*. This class should be partially specialized if there is
820 // something strange that needs to be done to interface to the ctor for the
824 template<class ConstantClass, class TypeClass, class ValType>
825 struct VISIBILITY_HIDDEN ConstantCreator {
826 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
827 unsigned FIXME = 0; // = traits<ValType>::uses(V)
828 return new(FIXME) ConstantClass(Ty, V);
832 template<class ConstantClass, class TypeClass>
833 struct VISIBILITY_HIDDEN ConvertConstantType {
834 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
835 assert(0 && "This type cannot be converted!\n");
840 template<class ValType, class TypeClass, class ConstantClass,
841 bool HasLargeKey = false /*true for arrays and structs*/ >
842 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
844 typedef std::pair<const Type*, ValType> MapKey;
845 typedef std::map<MapKey, Constant *> MapTy;
846 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
847 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
849 /// Map - This is the main map from the element descriptor to the Constants.
850 /// This is the primary way we avoid creating two of the same shape
854 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
855 /// from the constants to their element in Map. This is important for
856 /// removal of constants from the array, which would otherwise have to scan
857 /// through the map with very large keys.
858 InverseMapTy InverseMap;
860 /// AbstractTypeMap - Map for abstract type constants.
862 AbstractTypeMapTy AbstractTypeMap;
865 typename MapTy::iterator map_end() { return Map.end(); }
867 /// InsertOrGetItem - Return an iterator for the specified element.
868 /// If the element exists in the map, the returned iterator points to the
869 /// entry and Exists=true. If not, the iterator points to the newly
870 /// inserted entry and returns Exists=false. Newly inserted entries have
871 /// I->second == 0, and should be filled in.
872 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
875 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
881 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
883 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
884 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
885 IMI->second->second == CP &&
886 "InverseMap corrupt!");
890 typename MapTy::iterator I =
891 Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
892 if (I == Map.end() || I->second != CP) {
893 // FIXME: This should not use a linear scan. If this gets to be a
894 // performance problem, someone should look at this.
895 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
902 /// getOrCreate - Return the specified constant from the map, creating it if
904 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
905 MapKey Lookup(Ty, V);
906 typename MapTy::iterator I = Map.lower_bound(Lookup);
908 if (I != Map.end() && I->first == Lookup)
909 return static_cast<ConstantClass *>(I->second);
911 // If no preexisting value, create one now...
912 ConstantClass *Result =
913 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
915 /// FIXME: why does this assert fail when loading 176.gcc?
916 //assert(Result->getType() == Ty && "Type specified is not correct!");
917 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
919 if (HasLargeKey) // Remember the reverse mapping if needed.
920 InverseMap.insert(std::make_pair(Result, I));
922 // If the type of the constant is abstract, make sure that an entry exists
923 // for it in the AbstractTypeMap.
924 if (Ty->isAbstract()) {
925 typename AbstractTypeMapTy::iterator TI =
926 AbstractTypeMap.lower_bound(Ty);
928 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
929 // Add ourselves to the ATU list of the type.
930 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
932 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
938 void remove(ConstantClass *CP) {
939 typename MapTy::iterator I = FindExistingElement(CP);
940 assert(I != Map.end() && "Constant not found in constant table!");
941 assert(I->second == CP && "Didn't find correct element?");
943 if (HasLargeKey) // Remember the reverse mapping if needed.
944 InverseMap.erase(CP);
946 // Now that we found the entry, make sure this isn't the entry that
947 // the AbstractTypeMap points to.
948 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
949 if (Ty->isAbstract()) {
950 assert(AbstractTypeMap.count(Ty) &&
951 "Abstract type not in AbstractTypeMap?");
952 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
953 if (ATMEntryIt == I) {
954 // Yes, we are removing the representative entry for this type.
955 // See if there are any other entries of the same type.
956 typename MapTy::iterator TmpIt = ATMEntryIt;
958 // First check the entry before this one...
959 if (TmpIt != Map.begin()) {
961 if (TmpIt->first.first != Ty) // Not the same type, move back...
965 // If we didn't find the same type, try to move forward...
966 if (TmpIt == ATMEntryIt) {
968 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
969 --TmpIt; // No entry afterwards with the same type
972 // If there is another entry in the map of the same abstract type,
973 // update the AbstractTypeMap entry now.
974 if (TmpIt != ATMEntryIt) {
977 // Otherwise, we are removing the last instance of this type
978 // from the table. Remove from the ATM, and from user list.
979 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
980 AbstractTypeMap.erase(Ty);
989 /// MoveConstantToNewSlot - If we are about to change C to be the element
990 /// specified by I, update our internal data structures to reflect this
992 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
993 // First, remove the old location of the specified constant in the map.
994 typename MapTy::iterator OldI = FindExistingElement(C);
995 assert(OldI != Map.end() && "Constant not found in constant table!");
996 assert(OldI->second == C && "Didn't find correct element?");
998 // If this constant is the representative element for its abstract type,
999 // update the AbstractTypeMap so that the representative element is I.
1000 if (C->getType()->isAbstract()) {
1001 typename AbstractTypeMapTy::iterator ATI =
1002 AbstractTypeMap.find(C->getType());
1003 assert(ATI != AbstractTypeMap.end() &&
1004 "Abstract type not in AbstractTypeMap?");
1005 if (ATI->second == OldI)
1009 // Remove the old entry from the map.
1012 // Update the inverse map so that we know that this constant is now
1013 // located at descriptor I.
1015 assert(I->second == C && "Bad inversemap entry!");
1020 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
1021 typename AbstractTypeMapTy::iterator I =
1022 AbstractTypeMap.find(cast<Type>(OldTy));
1024 assert(I != AbstractTypeMap.end() &&
1025 "Abstract type not in AbstractTypeMap?");
1027 // Convert a constant at a time until the last one is gone. The last one
1028 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
1029 // eliminated eventually.
1031 ConvertConstantType<ConstantClass,
1032 TypeClass>::convert(
1033 static_cast<ConstantClass *>(I->second->second),
1034 cast<TypeClass>(NewTy));
1036 I = AbstractTypeMap.find(cast<Type>(OldTy));
1037 } while (I != AbstractTypeMap.end());
1040 // If the type became concrete without being refined to any other existing
1041 // type, we just remove ourselves from the ATU list.
1042 void typeBecameConcrete(const DerivedType *AbsTy) {
1043 AbsTy->removeAbstractTypeUser(this);
1047 DOUT << "Constant.cpp: ValueMap\n";
1054 //---- ConstantAggregateZero::get() implementation...
1057 // ConstantAggregateZero does not take extra "value" argument...
1058 template<class ValType>
1059 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
1060 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
1061 return new ConstantAggregateZero(Ty);
1066 struct ConvertConstantType<ConstantAggregateZero, Type> {
1067 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1068 // Make everyone now use a constant of the new type...
1069 Constant *New = ConstantAggregateZero::get(NewTy);
1070 assert(New != OldC && "Didn't replace constant??");
1071 OldC->uncheckedReplaceAllUsesWith(New);
1072 OldC->destroyConstant(); // This constant is now dead, destroy it.
1077 static ManagedStatic<ValueMap<char, Type,
1078 ConstantAggregateZero> > AggZeroConstants;
1080 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1082 Constant *ConstantAggregateZero::get(const Type *Ty) {
1083 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
1084 "Cannot create an aggregate zero of non-aggregate type!");
1085 return AggZeroConstants->getOrCreate(Ty, 0);
1088 // destroyConstant - Remove the constant from the constant table...
1090 void ConstantAggregateZero::destroyConstant() {
1091 AggZeroConstants->remove(this);
1092 destroyConstantImpl();
1095 //---- ConstantArray::get() implementation...
1099 struct ConvertConstantType<ConstantArray, ArrayType> {
1100 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1101 // Make everyone now use a constant of the new type...
1102 std::vector<Constant*> C;
1103 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1104 C.push_back(cast<Constant>(OldC->getOperand(i)));
1105 Constant *New = ConstantArray::get(NewTy, C);
1106 assert(New != OldC && "Didn't replace constant??");
1107 OldC->uncheckedReplaceAllUsesWith(New);
1108 OldC->destroyConstant(); // This constant is now dead, destroy it.
1113 static std::vector<Constant*> getValType(ConstantArray *CA) {
1114 std::vector<Constant*> Elements;
1115 Elements.reserve(CA->getNumOperands());
1116 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1117 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1121 typedef ValueMap<std::vector<Constant*>, ArrayType,
1122 ConstantArray, true /*largekey*/> ArrayConstantsTy;
1123 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
1125 Constant *ConstantArray::get(const ArrayType *Ty,
1126 const std::vector<Constant*> &V) {
1127 // If this is an all-zero array, return a ConstantAggregateZero object
1130 if (!C->isNullValue())
1131 return ArrayConstants->getOrCreate(Ty, V);
1132 for (unsigned i = 1, e = V.size(); i != e; ++i)
1134 return ArrayConstants->getOrCreate(Ty, V);
1136 return ConstantAggregateZero::get(Ty);
1139 // destroyConstant - Remove the constant from the constant table...
1141 void ConstantArray::destroyConstant() {
1142 ArrayConstants->remove(this);
1143 destroyConstantImpl();
1146 /// ConstantArray::get(const string&) - Return an array that is initialized to
1147 /// contain the specified string. If length is zero then a null terminator is
1148 /// added to the specified string so that it may be used in a natural way.
1149 /// Otherwise, the length parameter specifies how much of the string to use
1150 /// and it won't be null terminated.
1152 Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
1153 std::vector<Constant*> ElementVals;
1154 for (unsigned i = 0; i < Str.length(); ++i)
1155 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
1157 // Add a null terminator to the string...
1159 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
1162 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
1163 return ConstantArray::get(ATy, ElementVals);
1166 /// isString - This method returns true if the array is an array of i8, and
1167 /// if the elements of the array are all ConstantInt's.
1168 bool ConstantArray::isString() const {
1169 // Check the element type for i8...
1170 if (getType()->getElementType() != Type::Int8Ty)
1172 // Check the elements to make sure they are all integers, not constant
1174 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1175 if (!isa<ConstantInt>(getOperand(i)))
1180 /// isCString - This method returns true if the array is a string (see
1181 /// isString) and it ends in a null byte \0 and does not contains any other
1182 /// null bytes except its terminator.
1183 bool ConstantArray::isCString() const {
1184 // Check the element type for i8...
1185 if (getType()->getElementType() != Type::Int8Ty)
1187 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1188 // Last element must be a null.
1189 if (getOperand(getNumOperands()-1) != Zero)
1191 // Other elements must be non-null integers.
1192 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1193 if (!isa<ConstantInt>(getOperand(i)))
1195 if (getOperand(i) == Zero)
1202 // getAsString - If the sub-element type of this array is i8
1203 // then this method converts the array to an std::string and returns it.
1204 // Otherwise, it asserts out.
1206 std::string ConstantArray::getAsString() const {
1207 assert(isString() && "Not a string!");
1209 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1210 Result += (char)cast<ConstantInt>(getOperand(i))->getZExtValue();
1215 //---- ConstantStruct::get() implementation...
1220 struct ConvertConstantType<ConstantStruct, StructType> {
1221 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1222 // Make everyone now use a constant of the new type...
1223 std::vector<Constant*> C;
1224 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1225 C.push_back(cast<Constant>(OldC->getOperand(i)));
1226 Constant *New = ConstantStruct::get(NewTy, C);
1227 assert(New != OldC && "Didn't replace constant??");
1229 OldC->uncheckedReplaceAllUsesWith(New);
1230 OldC->destroyConstant(); // This constant is now dead, destroy it.
1235 typedef ValueMap<std::vector<Constant*>, StructType,
1236 ConstantStruct, true /*largekey*/> StructConstantsTy;
1237 static ManagedStatic<StructConstantsTy> StructConstants;
1239 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1240 std::vector<Constant*> Elements;
1241 Elements.reserve(CS->getNumOperands());
1242 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1243 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1247 Constant *ConstantStruct::get(const StructType *Ty,
1248 const std::vector<Constant*> &V) {
1249 // Create a ConstantAggregateZero value if all elements are zeros...
1250 for (unsigned i = 0, e = V.size(); i != e; ++i)
1251 if (!V[i]->isNullValue())
1252 return StructConstants->getOrCreate(Ty, V);
1254 return ConstantAggregateZero::get(Ty);
1257 Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
1258 std::vector<const Type*> StructEls;
1259 StructEls.reserve(V.size());
1260 for (unsigned i = 0, e = V.size(); i != e; ++i)
1261 StructEls.push_back(V[i]->getType());
1262 return get(StructType::get(StructEls, packed), V);
1265 // destroyConstant - Remove the constant from the constant table...
1267 void ConstantStruct::destroyConstant() {
1268 StructConstants->remove(this);
1269 destroyConstantImpl();
1272 //---- ConstantVector::get() implementation...
1276 struct ConvertConstantType<ConstantVector, VectorType> {
1277 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
1278 // Make everyone now use a constant of the new type...
1279 std::vector<Constant*> C;
1280 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1281 C.push_back(cast<Constant>(OldC->getOperand(i)));
1282 Constant *New = ConstantVector::get(NewTy, C);
1283 assert(New != OldC && "Didn't replace constant??");
1284 OldC->uncheckedReplaceAllUsesWith(New);
1285 OldC->destroyConstant(); // This constant is now dead, destroy it.
1290 static std::vector<Constant*> getValType(ConstantVector *CP) {
1291 std::vector<Constant*> Elements;
1292 Elements.reserve(CP->getNumOperands());
1293 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1294 Elements.push_back(CP->getOperand(i));
1298 static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
1299 ConstantVector> > VectorConstants;
1301 Constant *ConstantVector::get(const VectorType *Ty,
1302 const std::vector<Constant*> &V) {
1303 // If this is an all-zero vector, return a ConstantAggregateZero object
1306 if (!C->isNullValue())
1307 return VectorConstants->getOrCreate(Ty, V);
1308 for (unsigned i = 1, e = V.size(); i != e; ++i)
1310 return VectorConstants->getOrCreate(Ty, V);
1312 return ConstantAggregateZero::get(Ty);
1315 Constant *ConstantVector::get(const std::vector<Constant*> &V) {
1316 assert(!V.empty() && "Cannot infer type if V is empty");
1317 return get(VectorType::get(V.front()->getType(),V.size()), V);
1320 // destroyConstant - Remove the constant from the constant table...
1322 void ConstantVector::destroyConstant() {
1323 VectorConstants->remove(this);
1324 destroyConstantImpl();
1327 /// This function will return true iff every element in this vector constant
1328 /// is set to all ones.
1329 /// @returns true iff this constant's emements are all set to all ones.
1330 /// @brief Determine if the value is all ones.
1331 bool ConstantVector::isAllOnesValue() const {
1332 // Check out first element.
1333 const Constant *Elt = getOperand(0);
1334 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1335 if (!CI || !CI->isAllOnesValue()) return false;
1336 // Then make sure all remaining elements point to the same value.
1337 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1338 if (getOperand(I) != Elt) return false;
1343 /// getSplatValue - If this is a splat constant, where all of the
1344 /// elements have the same value, return that value. Otherwise return null.
1345 Constant *ConstantVector::getSplatValue() {
1346 // Check out first element.
1347 Constant *Elt = getOperand(0);
1348 // Then make sure all remaining elements point to the same value.
1349 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1350 if (getOperand(I) != Elt) return 0;
1354 //---- ConstantPointerNull::get() implementation...
1358 // ConstantPointerNull does not take extra "value" argument...
1359 template<class ValType>
1360 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1361 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1362 return new ConstantPointerNull(Ty);
1367 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1368 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1369 // Make everyone now use a constant of the new type...
1370 Constant *New = ConstantPointerNull::get(NewTy);
1371 assert(New != OldC && "Didn't replace constant??");
1372 OldC->uncheckedReplaceAllUsesWith(New);
1373 OldC->destroyConstant(); // This constant is now dead, destroy it.
1378 static ManagedStatic<ValueMap<char, PointerType,
1379 ConstantPointerNull> > NullPtrConstants;
1381 static char getValType(ConstantPointerNull *) {
1386 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1387 return NullPtrConstants->getOrCreate(Ty, 0);
1390 // destroyConstant - Remove the constant from the constant table...
1392 void ConstantPointerNull::destroyConstant() {
1393 NullPtrConstants->remove(this);
1394 destroyConstantImpl();
1398 //---- UndefValue::get() implementation...
1402 // UndefValue does not take extra "value" argument...
1403 template<class ValType>
1404 struct ConstantCreator<UndefValue, Type, ValType> {
1405 static UndefValue *create(const Type *Ty, const ValType &V) {
1406 return new UndefValue(Ty);
1411 struct ConvertConstantType<UndefValue, Type> {
1412 static void convert(UndefValue *OldC, const Type *NewTy) {
1413 // Make everyone now use a constant of the new type.
1414 Constant *New = UndefValue::get(NewTy);
1415 assert(New != OldC && "Didn't replace constant??");
1416 OldC->uncheckedReplaceAllUsesWith(New);
1417 OldC->destroyConstant(); // This constant is now dead, destroy it.
1422 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1424 static char getValType(UndefValue *) {
1429 UndefValue *UndefValue::get(const Type *Ty) {
1430 return UndefValueConstants->getOrCreate(Ty, 0);
1433 // destroyConstant - Remove the constant from the constant table.
1435 void UndefValue::destroyConstant() {
1436 UndefValueConstants->remove(this);
1437 destroyConstantImpl();
1441 //---- ConstantExpr::get() implementations...
1444 struct ExprMapKeyType {
1445 explicit ExprMapKeyType(unsigned opc, std::vector<Constant*> ops,
1446 unsigned short pred = 0) : opcode(opc), predicate(pred), operands(ops) { }
1449 std::vector<Constant*> operands;
1450 bool operator==(const ExprMapKeyType& that) const {
1451 return this->opcode == that.opcode &&
1452 this->predicate == that.predicate &&
1453 this->operands == that.operands;
1455 bool operator<(const ExprMapKeyType & that) const {
1456 return this->opcode < that.opcode ||
1457 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1458 (this->opcode == that.opcode && this->predicate == that.predicate &&
1459 this->operands < that.operands);
1462 bool operator!=(const ExprMapKeyType& that) const {
1463 return !(*this == that);
1469 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1470 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1471 unsigned short pred = 0) {
1472 if (Instruction::isCast(V.opcode))
1473 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1474 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1475 V.opcode < Instruction::BinaryOpsEnd))
1476 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1477 if (V.opcode == Instruction::Select)
1478 return new SelectConstantExpr(V.operands[0], V.operands[1],
1480 if (V.opcode == Instruction::ExtractElement)
1481 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1482 if (V.opcode == Instruction::InsertElement)
1483 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1485 if (V.opcode == Instruction::ShuffleVector)
1486 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1488 if (V.opcode == Instruction::GetElementPtr) {
1489 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1490 return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
1493 // The compare instructions are weird. We have to encode the predicate
1494 // value and it is combined with the instruction opcode by multiplying
1495 // the opcode by one hundred. We must decode this to get the predicate.
1496 if (V.opcode == Instruction::ICmp)
1497 return new CompareConstantExpr(Instruction::ICmp, V.predicate,
1498 V.operands[0], V.operands[1]);
1499 if (V.opcode == Instruction::FCmp)
1500 return new CompareConstantExpr(Instruction::FCmp, V.predicate,
1501 V.operands[0], V.operands[1]);
1502 assert(0 && "Invalid ConstantExpr!");
1508 struct ConvertConstantType<ConstantExpr, Type> {
1509 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1511 switch (OldC->getOpcode()) {
1512 case Instruction::Trunc:
1513 case Instruction::ZExt:
1514 case Instruction::SExt:
1515 case Instruction::FPTrunc:
1516 case Instruction::FPExt:
1517 case Instruction::UIToFP:
1518 case Instruction::SIToFP:
1519 case Instruction::FPToUI:
1520 case Instruction::FPToSI:
1521 case Instruction::PtrToInt:
1522 case Instruction::IntToPtr:
1523 case Instruction::BitCast:
1524 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1527 case Instruction::Select:
1528 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1529 OldC->getOperand(1),
1530 OldC->getOperand(2));
1533 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1534 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1535 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1536 OldC->getOperand(1));
1538 case Instruction::GetElementPtr:
1539 // Make everyone now use a constant of the new type...
1540 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1541 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1542 &Idx[0], Idx.size());
1546 assert(New != OldC && "Didn't replace constant??");
1547 OldC->uncheckedReplaceAllUsesWith(New);
1548 OldC->destroyConstant(); // This constant is now dead, destroy it.
1551 } // end namespace llvm
1554 static ExprMapKeyType getValType(ConstantExpr *CE) {
1555 std::vector<Constant*> Operands;
1556 Operands.reserve(CE->getNumOperands());
1557 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1558 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1559 return ExprMapKeyType(CE->getOpcode(), Operands,
1560 CE->isCompare() ? CE->getPredicate() : 0);
1563 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1564 ConstantExpr> > ExprConstants;
1566 /// This is a utility function to handle folding of casts and lookup of the
1567 /// cast in the ExprConstants map. It is used by the various get* methods below.
1568 static inline Constant *getFoldedCast(
1569 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1570 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1571 // Fold a few common cases
1572 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1575 // Look up the constant in the table first to ensure uniqueness
1576 std::vector<Constant*> argVec(1, C);
1577 ExprMapKeyType Key(opc, argVec);
1578 return ExprConstants->getOrCreate(Ty, Key);
1581 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1582 Instruction::CastOps opc = Instruction::CastOps(oc);
1583 assert(Instruction::isCast(opc) && "opcode out of range");
1584 assert(C && Ty && "Null arguments to getCast");
1585 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1589 assert(0 && "Invalid cast opcode");
1591 case Instruction::Trunc: return getTrunc(C, Ty);
1592 case Instruction::ZExt: return getZExt(C, Ty);
1593 case Instruction::SExt: return getSExt(C, Ty);
1594 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1595 case Instruction::FPExt: return getFPExtend(C, Ty);
1596 case Instruction::UIToFP: return getUIToFP(C, Ty);
1597 case Instruction::SIToFP: return getSIToFP(C, Ty);
1598 case Instruction::FPToUI: return getFPToUI(C, Ty);
1599 case Instruction::FPToSI: return getFPToSI(C, Ty);
1600 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1601 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1602 case Instruction::BitCast: return getBitCast(C, Ty);
1607 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1608 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1609 return getCast(Instruction::BitCast, C, Ty);
1610 return getCast(Instruction::ZExt, C, Ty);
1613 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1614 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1615 return getCast(Instruction::BitCast, C, Ty);
1616 return getCast(Instruction::SExt, C, Ty);
1619 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1620 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1621 return getCast(Instruction::BitCast, C, Ty);
1622 return getCast(Instruction::Trunc, C, Ty);
1625 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1626 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1627 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1629 if (Ty->isInteger())
1630 return getCast(Instruction::PtrToInt, S, Ty);
1631 return getCast(Instruction::BitCast, S, Ty);
1634 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1636 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1637 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1638 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1639 Instruction::CastOps opcode =
1640 (SrcBits == DstBits ? Instruction::BitCast :
1641 (SrcBits > DstBits ? Instruction::Trunc :
1642 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1643 return getCast(opcode, C, Ty);
1646 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1647 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1649 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1650 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1651 if (SrcBits == DstBits)
1652 return C; // Avoid a useless cast
1653 Instruction::CastOps opcode =
1654 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1655 return getCast(opcode, C, Ty);
1658 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1659 assert(C->getType()->isInteger() && "Trunc operand must be integer");
1660 assert(Ty->isInteger() && "Trunc produces only integral");
1661 assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1662 "SrcTy must be larger than DestTy for Trunc!");
1664 return getFoldedCast(Instruction::Trunc, C, Ty);
1667 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1668 assert(C->getType()->isInteger() && "SEXt operand must be integral");
1669 assert(Ty->isInteger() && "SExt produces only integer");
1670 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1671 "SrcTy must be smaller than DestTy for SExt!");
1673 return getFoldedCast(Instruction::SExt, C, Ty);
1676 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1677 assert(C->getType()->isInteger() && "ZEXt operand must be integral");
1678 assert(Ty->isInteger() && "ZExt produces only integer");
1679 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1680 "SrcTy must be smaller than DestTy for ZExt!");
1682 return getFoldedCast(Instruction::ZExt, C, Ty);
1685 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1686 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1687 C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1688 "This is an illegal floating point truncation!");
1689 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1692 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1693 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1694 C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1695 "This is an illegal floating point extension!");
1696 return getFoldedCast(Instruction::FPExt, C, Ty);
1699 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1700 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1701 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1702 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1703 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1704 "This is an illegal uint to floating point cast!");
1705 return getFoldedCast(Instruction::UIToFP, C, Ty);
1708 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1709 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1710 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1711 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1712 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1713 "This is an illegal sint to floating point cast!");
1714 return getFoldedCast(Instruction::SIToFP, C, Ty);
1717 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1718 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1719 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1720 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1721 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1722 "This is an illegal floating point to uint cast!");
1723 return getFoldedCast(Instruction::FPToUI, C, Ty);
1726 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1727 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1728 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1729 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1730 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1731 "This is an illegal floating point to sint cast!");
1732 return getFoldedCast(Instruction::FPToSI, C, Ty);
1735 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1736 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1737 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1738 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1741 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1742 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1743 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1744 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1747 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1748 // BitCast implies a no-op cast of type only. No bits change. However, you
1749 // can't cast pointers to anything but pointers.
1750 const Type *SrcTy = C->getType();
1751 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1752 "BitCast cannot cast pointer to non-pointer and vice versa");
1754 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1755 // or nonptr->ptr). For all the other types, the cast is okay if source and
1756 // destination bit widths are identical.
1757 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1758 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1759 assert(SrcBitSize == DstBitSize && "BitCast requies types of same width");
1760 return getFoldedCast(Instruction::BitCast, C, DstTy);
1763 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
1764 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1765 Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
1767 getGetElementPtr(getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
1768 return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
1771 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1772 Constant *C1, Constant *C2) {
1773 // Check the operands for consistency first
1774 assert(Opcode >= Instruction::BinaryOpsBegin &&
1775 Opcode < Instruction::BinaryOpsEnd &&
1776 "Invalid opcode in binary constant expression");
1777 assert(C1->getType() == C2->getType() &&
1778 "Operand types in binary constant expression should match");
1780 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
1781 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1782 return FC; // Fold a few common cases...
1784 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1785 ExprMapKeyType Key(Opcode, argVec);
1786 return ExprConstants->getOrCreate(ReqTy, Key);
1789 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1790 Constant *C1, Constant *C2) {
1791 switch (predicate) {
1792 default: assert(0 && "Invalid CmpInst predicate");
1793 case FCmpInst::FCMP_FALSE: case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_OGT:
1794 case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OLE:
1795 case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_ORD: case FCmpInst::FCMP_UNO:
1796 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UGT: case FCmpInst::FCMP_UGE:
1797 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_ULE: case FCmpInst::FCMP_UNE:
1798 case FCmpInst::FCMP_TRUE:
1799 return getFCmp(predicate, C1, C2);
1800 case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGT:
1801 case ICmpInst::ICMP_UGE: case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE:
1802 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_SGE: case ICmpInst::ICMP_SLT:
1803 case ICmpInst::ICMP_SLE:
1804 return getICmp(predicate, C1, C2);
1808 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1811 case Instruction::Add:
1812 case Instruction::Sub:
1813 case Instruction::Mul:
1814 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1815 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
1816 isa<VectorType>(C1->getType())) &&
1817 "Tried to create an arithmetic operation on a non-arithmetic type!");
1819 case Instruction::UDiv:
1820 case Instruction::SDiv:
1821 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1822 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1823 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
1824 "Tried to create an arithmetic operation on a non-arithmetic type!");
1826 case Instruction::FDiv:
1827 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1828 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1829 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
1830 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1832 case Instruction::URem:
1833 case Instruction::SRem:
1834 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1835 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1836 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
1837 "Tried to create an arithmetic operation on a non-arithmetic type!");
1839 case Instruction::FRem:
1840 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1841 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1842 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
1843 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1845 case Instruction::And:
1846 case Instruction::Or:
1847 case Instruction::Xor:
1848 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1849 assert((C1->getType()->isInteger() || isa<VectorType>(C1->getType())) &&
1850 "Tried to create a logical operation on a non-integral type!");
1852 case Instruction::Shl:
1853 case Instruction::LShr:
1854 case Instruction::AShr:
1855 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1856 assert(C1->getType()->isInteger() &&
1857 "Tried to create a shift operation on a non-integer type!");
1864 return getTy(C1->getType(), Opcode, C1, C2);
1867 Constant *ConstantExpr::getCompare(unsigned short pred,
1868 Constant *C1, Constant *C2) {
1869 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1870 return getCompareTy(pred, C1, C2);
1873 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1874 Constant *V1, Constant *V2) {
1875 assert(C->getType() == Type::Int1Ty && "Select condition must be i1!");
1876 assert(V1->getType() == V2->getType() && "Select value types must match!");
1877 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1879 if (ReqTy == V1->getType())
1880 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1881 return SC; // Fold common cases
1883 std::vector<Constant*> argVec(3, C);
1886 ExprMapKeyType Key(Instruction::Select, argVec);
1887 return ExprConstants->getOrCreate(ReqTy, Key);
1890 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1893 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx, true) &&
1894 "GEP indices invalid!");
1896 if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs, NumIdx))
1897 return FC; // Fold a few common cases...
1899 assert(isa<PointerType>(C->getType()) &&
1900 "Non-pointer type for constant GetElementPtr expression");
1901 // Look up the constant in the table first to ensure uniqueness
1902 std::vector<Constant*> ArgVec;
1903 ArgVec.reserve(NumIdx+1);
1904 ArgVec.push_back(C);
1905 for (unsigned i = 0; i != NumIdx; ++i)
1906 ArgVec.push_back(cast<Constant>(Idxs[i]));
1907 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
1908 return ExprConstants->getOrCreate(ReqTy, Key);
1911 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1913 // Get the result type of the getelementptr!
1915 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx, true);
1916 assert(Ty && "GEP indices invalid!");
1917 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
1918 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
1921 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1923 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1928 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1929 assert(LHS->getType() == RHS->getType());
1930 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1931 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1933 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1934 return FC; // Fold a few common cases...
1936 // Look up the constant in the table first to ensure uniqueness
1937 std::vector<Constant*> ArgVec;
1938 ArgVec.push_back(LHS);
1939 ArgVec.push_back(RHS);
1940 // Get the key type with both the opcode and predicate
1941 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1942 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1946 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1947 assert(LHS->getType() == RHS->getType());
1948 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1950 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1951 return FC; // Fold a few common cases...
1953 // Look up the constant in the table first to ensure uniqueness
1954 std::vector<Constant*> ArgVec;
1955 ArgVec.push_back(LHS);
1956 ArgVec.push_back(RHS);
1957 // Get the key type with both the opcode and predicate
1958 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1959 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1962 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1964 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1965 return FC; // Fold a few common cases...
1966 // Look up the constant in the table first to ensure uniqueness
1967 std::vector<Constant*> ArgVec(1, Val);
1968 ArgVec.push_back(Idx);
1969 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1970 return ExprConstants->getOrCreate(ReqTy, Key);
1973 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1974 assert(isa<VectorType>(Val->getType()) &&
1975 "Tried to create extractelement operation on non-vector type!");
1976 assert(Idx->getType() == Type::Int32Ty &&
1977 "Extractelement index must be i32 type!");
1978 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
1982 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1983 Constant *Elt, Constant *Idx) {
1984 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1985 return FC; // Fold a few common cases...
1986 // Look up the constant in the table first to ensure uniqueness
1987 std::vector<Constant*> ArgVec(1, Val);
1988 ArgVec.push_back(Elt);
1989 ArgVec.push_back(Idx);
1990 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1991 return ExprConstants->getOrCreate(ReqTy, Key);
1994 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1996 assert(isa<VectorType>(Val->getType()) &&
1997 "Tried to create insertelement operation on non-vector type!");
1998 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
1999 && "Insertelement types must match!");
2000 assert(Idx->getType() == Type::Int32Ty &&
2001 "Insertelement index must be i32 type!");
2002 return getInsertElementTy(cast<VectorType>(Val->getType())->getElementType(),
2006 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
2007 Constant *V2, Constant *Mask) {
2008 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2009 return FC; // Fold a few common cases...
2010 // Look up the constant in the table first to ensure uniqueness
2011 std::vector<Constant*> ArgVec(1, V1);
2012 ArgVec.push_back(V2);
2013 ArgVec.push_back(Mask);
2014 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
2015 return ExprConstants->getOrCreate(ReqTy, Key);
2018 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2020 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2021 "Invalid shuffle vector constant expr operands!");
2022 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
2025 Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
2026 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
2027 if (PTy->getElementType()->isFloatingPoint()) {
2028 std::vector<Constant*> zeros(PTy->getNumElements(),
2029 ConstantFP::getNegativeZero(PTy->getElementType()));
2030 return ConstantVector::get(PTy, zeros);
2033 if (Ty->isFloatingPoint())
2034 return ConstantFP::getNegativeZero(Ty);
2036 return Constant::getNullValue(Ty);
2039 // destroyConstant - Remove the constant from the constant table...
2041 void ConstantExpr::destroyConstant() {
2042 ExprConstants->remove(this);
2043 destroyConstantImpl();
2046 const char *ConstantExpr::getOpcodeName() const {
2047 return Instruction::getOpcodeName(getOpcode());
2050 //===----------------------------------------------------------------------===//
2051 // replaceUsesOfWithOnConstant implementations
2053 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2054 /// 'From' to be uses of 'To'. This must update the uniquing data structures
2057 /// Note that we intentionally replace all uses of From with To here. Consider
2058 /// a large array that uses 'From' 1000 times. By handling this case all here,
2059 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2060 /// single invocation handles all 1000 uses. Handling them one at a time would
2061 /// work, but would be really slow because it would have to unique each updated
2063 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
2065 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2066 Constant *ToC = cast<Constant>(To);
2068 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
2069 Lookup.first.first = getType();
2070 Lookup.second = this;
2072 std::vector<Constant*> &Values = Lookup.first.second;
2073 Values.reserve(getNumOperands()); // Build replacement array.
2075 // Fill values with the modified operands of the constant array. Also,
2076 // compute whether this turns into an all-zeros array.
2077 bool isAllZeros = false;
2078 unsigned NumUpdated = 0;
2079 if (!ToC->isNullValue()) {
2080 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2081 Constant *Val = cast<Constant>(O->get());
2086 Values.push_back(Val);
2090 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2091 Constant *Val = cast<Constant>(O->get());
2096 Values.push_back(Val);
2097 if (isAllZeros) isAllZeros = Val->isNullValue();
2101 Constant *Replacement = 0;
2103 Replacement = ConstantAggregateZero::get(getType());
2105 // Check to see if we have this array type already.
2107 ArrayConstantsTy::MapTy::iterator I =
2108 ArrayConstants->InsertOrGetItem(Lookup, Exists);
2111 Replacement = I->second;
2113 // Okay, the new shape doesn't exist in the system yet. Instead of
2114 // creating a new constant array, inserting it, replaceallusesof'ing the
2115 // old with the new, then deleting the old... just update the current one
2117 ArrayConstants->MoveConstantToNewSlot(this, I);
2119 // Update to the new value. Optimize for the case when we have a single
2120 // operand that we're changing, but handle bulk updates efficiently.
2121 if (NumUpdated == 1) {
2122 unsigned OperandToUpdate = U-OperandList;
2123 assert(getOperand(OperandToUpdate) == From &&
2124 "ReplaceAllUsesWith broken!");
2125 setOperand(OperandToUpdate, ToC);
2127 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2128 if (getOperand(i) == From)
2135 // Otherwise, I do need to replace this with an existing value.
2136 assert(Replacement != this && "I didn't contain From!");
2138 // Everyone using this now uses the replacement.
2139 uncheckedReplaceAllUsesWith(Replacement);
2141 // Delete the old constant!
2145 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2147 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2148 Constant *ToC = cast<Constant>(To);
2150 unsigned OperandToUpdate = U-OperandList;
2151 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2153 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
2154 Lookup.first.first = getType();
2155 Lookup.second = this;
2156 std::vector<Constant*> &Values = Lookup.first.second;
2157 Values.reserve(getNumOperands()); // Build replacement struct.
2160 // Fill values with the modified operands of the constant struct. Also,
2161 // compute whether this turns into an all-zeros struct.
2162 bool isAllZeros = false;
2163 if (!ToC->isNullValue()) {
2164 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2165 Values.push_back(cast<Constant>(O->get()));
2168 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2169 Constant *Val = cast<Constant>(O->get());
2170 Values.push_back(Val);
2171 if (isAllZeros) isAllZeros = Val->isNullValue();
2174 Values[OperandToUpdate] = ToC;
2176 Constant *Replacement = 0;
2178 Replacement = ConstantAggregateZero::get(getType());
2180 // Check to see if we have this array type already.
2182 StructConstantsTy::MapTy::iterator I =
2183 StructConstants->InsertOrGetItem(Lookup, Exists);
2186 Replacement = I->second;
2188 // Okay, the new shape doesn't exist in the system yet. Instead of
2189 // creating a new constant struct, inserting it, replaceallusesof'ing the
2190 // old with the new, then deleting the old... just update the current one
2192 StructConstants->MoveConstantToNewSlot(this, I);
2194 // Update to the new value.
2195 setOperand(OperandToUpdate, ToC);
2200 assert(Replacement != this && "I didn't contain From!");
2202 // Everyone using this now uses the replacement.
2203 uncheckedReplaceAllUsesWith(Replacement);
2205 // Delete the old constant!
2209 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2211 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2213 std::vector<Constant*> Values;
2214 Values.reserve(getNumOperands()); // Build replacement array...
2215 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2216 Constant *Val = getOperand(i);
2217 if (Val == From) Val = cast<Constant>(To);
2218 Values.push_back(Val);
2221 Constant *Replacement = ConstantVector::get(getType(), Values);
2222 assert(Replacement != this && "I didn't contain From!");
2224 // Everyone using this now uses the replacement.
2225 uncheckedReplaceAllUsesWith(Replacement);
2227 // Delete the old constant!
2231 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2233 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2234 Constant *To = cast<Constant>(ToV);
2236 Constant *Replacement = 0;
2237 if (getOpcode() == Instruction::GetElementPtr) {
2238 SmallVector<Constant*, 8> Indices;
2239 Constant *Pointer = getOperand(0);
2240 Indices.reserve(getNumOperands()-1);
2241 if (Pointer == From) Pointer = To;
2243 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2244 Constant *Val = getOperand(i);
2245 if (Val == From) Val = To;
2246 Indices.push_back(Val);
2248 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2249 &Indices[0], Indices.size());
2250 } else if (isCast()) {
2251 assert(getOperand(0) == From && "Cast only has one use!");
2252 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2253 } else if (getOpcode() == Instruction::Select) {
2254 Constant *C1 = getOperand(0);
2255 Constant *C2 = getOperand(1);
2256 Constant *C3 = getOperand(2);
2257 if (C1 == From) C1 = To;
2258 if (C2 == From) C2 = To;
2259 if (C3 == From) C3 = To;
2260 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2261 } else if (getOpcode() == Instruction::ExtractElement) {
2262 Constant *C1 = getOperand(0);
2263 Constant *C2 = getOperand(1);
2264 if (C1 == From) C1 = To;
2265 if (C2 == From) C2 = To;
2266 Replacement = ConstantExpr::getExtractElement(C1, C2);
2267 } else if (getOpcode() == Instruction::InsertElement) {
2268 Constant *C1 = getOperand(0);
2269 Constant *C2 = getOperand(1);
2270 Constant *C3 = getOperand(1);
2271 if (C1 == From) C1 = To;
2272 if (C2 == From) C2 = To;
2273 if (C3 == From) C3 = To;
2274 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2275 } else if (getOpcode() == Instruction::ShuffleVector) {
2276 Constant *C1 = getOperand(0);
2277 Constant *C2 = getOperand(1);
2278 Constant *C3 = getOperand(2);
2279 if (C1 == From) C1 = To;
2280 if (C2 == From) C2 = To;
2281 if (C3 == From) C3 = To;
2282 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2283 } else if (isCompare()) {
2284 Constant *C1 = getOperand(0);
2285 Constant *C2 = getOperand(1);
2286 if (C1 == From) C1 = To;
2287 if (C2 == From) C2 = To;
2288 if (getOpcode() == Instruction::ICmp)
2289 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2291 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2292 } else if (getNumOperands() == 2) {
2293 Constant *C1 = getOperand(0);
2294 Constant *C2 = getOperand(1);
2295 if (C1 == From) C1 = To;
2296 if (C2 == From) C2 = To;
2297 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2299 assert(0 && "Unknown ConstantExpr type!");
2303 assert(Replacement != this && "I didn't contain From!");
2305 // Everyone using this now uses the replacement.
2306 uncheckedReplaceAllUsesWith(Replacement);
2308 // Delete the old constant!
2313 /// getStringValue - Turn an LLVM constant pointer that eventually points to a
2314 /// global into a string value. Return an empty string if we can't do it.
2315 /// Parameter Chop determines if the result is chopped at the first null
2318 std::string Constant::getStringValue(bool Chop, unsigned Offset) {
2319 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
2320 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
2321 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
2322 if (Init->isString()) {
2323 std::string Result = Init->getAsString();
2324 if (Offset < Result.size()) {
2325 // If we are pointing INTO The string, erase the beginning...
2326 Result.erase(Result.begin(), Result.begin()+Offset);
2328 // Take off the null terminator, and any string fragments after it.
2330 std::string::size_type NullPos = Result.find_first_of((char)0);
2331 if (NullPos != std::string::npos)
2332 Result.erase(Result.begin()+NullPos, Result.end());
2338 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(this)) {
2339 if (CE->getOpcode() == Instruction::GetElementPtr) {
2340 // Turn a gep into the specified offset.
2341 if (CE->getNumOperands() == 3 &&
2342 cast<Constant>(CE->getOperand(1))->isNullValue() &&
2343 isa<ConstantInt>(CE->getOperand(2))) {
2344 Offset += cast<ConstantInt>(CE->getOperand(2))->getZExtValue();
2345 return CE->getOperand(0)->getStringValue(Chop, Offset);