1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 switch (Ty->getTypeID()) {
107 case Type::IntegerTyID:
108 return ConstantInt::get(Ty, 0);
109 case Type::FloatTyID:
110 case Type::DoubleTyID:
111 case Type::X86_FP80TyID:
112 case Type::PPC_FP128TyID:
113 case Type::FP128TyID:
114 return ConstantFP::get(Ty, 0.0);
115 case Type::PointerTyID:
116 return ConstantPointerNull::get(cast<PointerType>(Ty));
117 case Type::StructTyID:
118 case Type::ArrayTyID:
119 case Type::VectorTyID:
120 return ConstantAggregateZero::get(Ty);
122 // Function, Label, or Opaque type?
123 assert(!"Cannot create a null constant of that type!");
128 Constant *Constant::getAllOnesValue(const Type *Ty) {
129 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
130 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
131 return ConstantVector::getAllOnesValue(cast<VectorType>(Ty));
134 // Static constructor to create an integral constant with all bits set
135 ConstantInt *ConstantInt::getAllOnesValue(const Type *Ty) {
136 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
137 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
141 /// @returns the value for a vector integer constant of the given type that
142 /// has all its bits set to true.
143 /// @brief Get the all ones value
144 ConstantVector *ConstantVector::getAllOnesValue(const VectorType *Ty) {
145 std::vector<Constant*> Elts;
146 Elts.resize(Ty->getNumElements(),
147 ConstantInt::getAllOnesValue(Ty->getElementType()));
148 assert(Elts[0] && "Not a vector integer type!");
149 return cast<ConstantVector>(ConstantVector::get(Elts));
153 //===----------------------------------------------------------------------===//
155 //===----------------------------------------------------------------------===//
157 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
158 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
159 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
162 ConstantInt *ConstantInt::TheTrueVal = 0;
163 ConstantInt *ConstantInt::TheFalseVal = 0;
166 void CleanupTrueFalse(void *) {
167 ConstantInt::ResetTrueFalse();
171 static ManagedCleanup<llvm::CleanupTrueFalse> TrueFalseCleanup;
173 ConstantInt *ConstantInt::CreateTrueFalseVals(bool WhichOne) {
174 assert(TheTrueVal == 0 && TheFalseVal == 0);
175 TheTrueVal = get(Type::Int1Ty, 1);
176 TheFalseVal = get(Type::Int1Ty, 0);
178 // Ensure that llvm_shutdown nulls out TheTrueVal/TheFalseVal.
179 TrueFalseCleanup.Register();
181 return WhichOne ? TheTrueVal : TheFalseVal;
186 struct DenseMapAPIntKeyInfo {
190 KeyTy(const APInt& V, const Type* Ty) : val(V), type(Ty) {}
191 KeyTy(const KeyTy& that) : val(that.val), type(that.type) {}
192 bool operator==(const KeyTy& that) const {
193 return type == that.type && this->val == that.val;
195 bool operator!=(const KeyTy& that) const {
196 return !this->operator==(that);
199 static inline KeyTy getEmptyKey() { return KeyTy(APInt(1,0), 0); }
200 static inline KeyTy getTombstoneKey() { return KeyTy(APInt(1,1), 0); }
201 static unsigned getHashValue(const KeyTy &Key) {
202 return DenseMapKeyInfo<void*>::getHashValue(Key.type) ^
203 Key.val.getHashValue();
205 static bool isPod() { return false; }
210 typedef DenseMap<DenseMapAPIntKeyInfo::KeyTy, ConstantInt*,
211 DenseMapAPIntKeyInfo> IntMapTy;
212 static ManagedStatic<IntMapTy> IntConstants;
214 ConstantInt *ConstantInt::get(const Type *Ty, uint64_t V, bool isSigned) {
215 const IntegerType *ITy = cast<IntegerType>(Ty);
216 return get(APInt(ITy->getBitWidth(), V, isSigned));
219 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
220 // as the key, is a DensMapAPIntKeyInfo::KeyTy which has provided the
221 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
222 // compare APInt's of different widths, which would violate an APInt class
223 // invariant which generates an assertion.
224 ConstantInt *ConstantInt::get(const APInt& V) {
225 // Get the corresponding integer type for the bit width of the value.
226 const IntegerType *ITy = IntegerType::get(V.getBitWidth());
227 // get an existing value or the insertion position
228 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
229 ConstantInt *&Slot = (*IntConstants)[Key];
230 // if it exists, return it.
233 // otherwise create a new one, insert it, and return it.
234 return Slot = new ConstantInt(ITy, V);
237 //===----------------------------------------------------------------------===//
239 //===----------------------------------------------------------------------===//
242 ConstantFP::ConstantFP(const Type *Ty, double V)
243 : Constant(Ty, ConstantFPVal, 0, 0),
244 Val(Ty==Type::FloatTy ? APFloat((float)V) : APFloat(V)) {
246 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
247 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
249 if (Ty==Type::FloatTy)
250 assert(&V.getSemantics()==&APFloat::IEEEsingle);
252 assert(&V.getSemantics()==&APFloat::IEEEdouble);
255 bool ConstantFP::isNullValue() const {
256 return Val.isZero() && !Val.isNegative();
259 bool ConstantFP::isExactlyValue(const APFloat& V) const {
260 return Val.bitwiseIsEqual(V);
264 struct DenseMapAPFloatKeyInfo {
267 KeyTy(const APFloat& V) : val(V){}
268 KeyTy(const KeyTy& that) : val(that.val) {}
269 bool operator==(const KeyTy& that) const {
270 return this->val.bitwiseIsEqual(that.val);
272 bool operator!=(const KeyTy& that) const {
273 return !this->operator==(that);
276 static inline KeyTy getEmptyKey() {
277 return KeyTy(APFloat(APFloat::Bogus,1));
279 static inline KeyTy getTombstoneKey() {
280 return KeyTy(APFloat(APFloat::Bogus,2));
282 static unsigned getHashValue(const KeyTy &Key) {
283 return Key.val.getHashValue();
285 static bool isPod() { return false; }
289 //---- ConstantFP::get() implementation...
291 typedef DenseMap<DenseMapAPFloatKeyInfo::KeyTy, ConstantFP*,
292 DenseMapAPFloatKeyInfo> FPMapTy;
294 static ManagedStatic<FPMapTy> FPConstants;
296 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
297 if (Ty == Type::FloatTy) {
298 DenseMapAPFloatKeyInfo::KeyTy Key(APFloat((float)V));
299 ConstantFP *&Slot = (*FPConstants)[Key];
300 if (Slot) return Slot;
301 return Slot = new ConstantFP(Ty, APFloat((float)V));
302 } else if (Ty == Type::DoubleTy) {
303 // Without the redundant cast, the following is taken to be
304 // a function declaration. What a language.
305 DenseMapAPFloatKeyInfo::KeyTy Key(APFloat((double)V));
306 ConstantFP *&Slot = (*FPConstants)[Key];
307 if (Slot) return Slot;
308 return Slot = new ConstantFP(Ty, APFloat(V));
309 } else if (Ty == Type::X86_FP80Ty ||
310 Ty == Type::PPC_FP128Ty || Ty == Type::FP128Ty) {
311 assert(0 && "Long double constants not handled yet.");
313 assert(0 && "Unknown FP Type!");
317 ConstantFP *ConstantFP::get(const Type *Ty, const APFloat& V) {
319 if (Ty==Type::FloatTy)
320 assert(&V.getSemantics()==&APFloat::IEEEsingle);
322 assert(&V.getSemantics()==&APFloat::IEEEdouble);
324 DenseMapAPFloatKeyInfo::KeyTy Key(V);
325 ConstantFP *&Slot = (*FPConstants)[Key];
326 if (Slot) return Slot;
327 return Slot = new ConstantFP(Ty, V);
330 //===----------------------------------------------------------------------===//
331 // ConstantXXX Classes
332 //===----------------------------------------------------------------------===//
335 ConstantArray::ConstantArray(const ArrayType *T,
336 const std::vector<Constant*> &V)
337 : Constant(T, ConstantArrayVal, new Use[V.size()], V.size()) {
338 assert(V.size() == T->getNumElements() &&
339 "Invalid initializer vector for constant array");
340 Use *OL = OperandList;
341 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
344 assert((C->getType() == T->getElementType() ||
346 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
347 "Initializer for array element doesn't match array element type!");
352 ConstantArray::~ConstantArray() {
353 delete [] OperandList;
356 ConstantStruct::ConstantStruct(const StructType *T,
357 const std::vector<Constant*> &V)
358 : Constant(T, ConstantStructVal, new Use[V.size()], V.size()) {
359 assert(V.size() == T->getNumElements() &&
360 "Invalid initializer vector for constant structure");
361 Use *OL = OperandList;
362 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
365 assert((C->getType() == T->getElementType(I-V.begin()) ||
366 ((T->getElementType(I-V.begin())->isAbstract() ||
367 C->getType()->isAbstract()) &&
368 T->getElementType(I-V.begin())->getTypeID() ==
369 C->getType()->getTypeID())) &&
370 "Initializer for struct element doesn't match struct element type!");
375 ConstantStruct::~ConstantStruct() {
376 delete [] OperandList;
380 ConstantVector::ConstantVector(const VectorType *T,
381 const std::vector<Constant*> &V)
382 : Constant(T, ConstantVectorVal, new Use[V.size()], V.size()) {
383 Use *OL = OperandList;
384 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
387 assert((C->getType() == T->getElementType() ||
389 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
390 "Initializer for vector element doesn't match vector element type!");
395 ConstantVector::~ConstantVector() {
396 delete [] OperandList;
399 // We declare several classes private to this file, so use an anonymous
403 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
404 /// behind the scenes to implement unary constant exprs.
405 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
408 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
409 : ConstantExpr(Ty, Opcode, &Op, 1), Op(C, this) {}
412 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
413 /// behind the scenes to implement binary constant exprs.
414 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
417 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
418 : ConstantExpr(C1->getType(), Opcode, Ops, 2) {
419 Ops[0].init(C1, this);
420 Ops[1].init(C2, this);
424 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
425 /// behind the scenes to implement select constant exprs.
426 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
429 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
430 : ConstantExpr(C2->getType(), Instruction::Select, Ops, 3) {
431 Ops[0].init(C1, this);
432 Ops[1].init(C2, this);
433 Ops[2].init(C3, this);
437 /// ExtractElementConstantExpr - This class is private to
438 /// Constants.cpp, and is used behind the scenes to implement
439 /// extractelement constant exprs.
440 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
443 ExtractElementConstantExpr(Constant *C1, Constant *C2)
444 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
445 Instruction::ExtractElement, Ops, 2) {
446 Ops[0].init(C1, this);
447 Ops[1].init(C2, this);
451 /// InsertElementConstantExpr - This class is private to
452 /// Constants.cpp, and is used behind the scenes to implement
453 /// insertelement constant exprs.
454 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
457 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
458 : ConstantExpr(C1->getType(), Instruction::InsertElement,
460 Ops[0].init(C1, this);
461 Ops[1].init(C2, this);
462 Ops[2].init(C3, this);
466 /// ShuffleVectorConstantExpr - This class is private to
467 /// Constants.cpp, and is used behind the scenes to implement
468 /// shufflevector constant exprs.
469 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
472 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
473 : ConstantExpr(C1->getType(), Instruction::ShuffleVector,
475 Ops[0].init(C1, this);
476 Ops[1].init(C2, this);
477 Ops[2].init(C3, this);
481 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
482 /// used behind the scenes to implement getelementpr constant exprs.
483 struct VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
484 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
486 : ConstantExpr(DestTy, Instruction::GetElementPtr,
487 new Use[IdxList.size()+1], IdxList.size()+1) {
488 OperandList[0].init(C, this);
489 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
490 OperandList[i+1].init(IdxList[i], this);
492 ~GetElementPtrConstantExpr() {
493 delete [] OperandList;
497 // CompareConstantExpr - This class is private to Constants.cpp, and is used
498 // behind the scenes to implement ICmp and FCmp constant expressions. This is
499 // needed in order to store the predicate value for these instructions.
500 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
501 unsigned short predicate;
503 CompareConstantExpr(Instruction::OtherOps opc, unsigned short pred,
504 Constant* LHS, Constant* RHS)
505 : ConstantExpr(Type::Int1Ty, opc, Ops, 2), predicate(pred) {
506 OperandList[0].init(LHS, this);
507 OperandList[1].init(RHS, this);
511 } // end anonymous namespace
514 // Utility function for determining if a ConstantExpr is a CastOp or not. This
515 // can't be inline because we don't want to #include Instruction.h into
517 bool ConstantExpr::isCast() const {
518 return Instruction::isCast(getOpcode());
521 bool ConstantExpr::isCompare() const {
522 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
525 /// ConstantExpr::get* - Return some common constants without having to
526 /// specify the full Instruction::OPCODE identifier.
528 Constant *ConstantExpr::getNeg(Constant *C) {
529 return get(Instruction::Sub,
530 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
533 Constant *ConstantExpr::getNot(Constant *C) {
534 assert(isa<ConstantInt>(C) && "Cannot NOT a nonintegral type!");
535 return get(Instruction::Xor, C,
536 ConstantInt::getAllOnesValue(C->getType()));
538 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
539 return get(Instruction::Add, C1, C2);
541 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
542 return get(Instruction::Sub, C1, C2);
544 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
545 return get(Instruction::Mul, C1, C2);
547 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
548 return get(Instruction::UDiv, C1, C2);
550 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
551 return get(Instruction::SDiv, C1, C2);
553 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
554 return get(Instruction::FDiv, C1, C2);
556 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
557 return get(Instruction::URem, C1, C2);
559 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
560 return get(Instruction::SRem, C1, C2);
562 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
563 return get(Instruction::FRem, C1, C2);
565 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
566 return get(Instruction::And, C1, C2);
568 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
569 return get(Instruction::Or, C1, C2);
571 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
572 return get(Instruction::Xor, C1, C2);
574 unsigned ConstantExpr::getPredicate() const {
575 assert(getOpcode() == Instruction::FCmp || getOpcode() == Instruction::ICmp);
576 return dynamic_cast<const CompareConstantExpr*>(this)->predicate;
578 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
579 return get(Instruction::Shl, C1, C2);
581 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
582 return get(Instruction::LShr, C1, C2);
584 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
585 return get(Instruction::AShr, C1, C2);
588 /// getWithOperandReplaced - Return a constant expression identical to this
589 /// one, but with the specified operand set to the specified value.
591 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
592 assert(OpNo < getNumOperands() && "Operand num is out of range!");
593 assert(Op->getType() == getOperand(OpNo)->getType() &&
594 "Replacing operand with value of different type!");
595 if (getOperand(OpNo) == Op)
596 return const_cast<ConstantExpr*>(this);
598 Constant *Op0, *Op1, *Op2;
599 switch (getOpcode()) {
600 case Instruction::Trunc:
601 case Instruction::ZExt:
602 case Instruction::SExt:
603 case Instruction::FPTrunc:
604 case Instruction::FPExt:
605 case Instruction::UIToFP:
606 case Instruction::SIToFP:
607 case Instruction::FPToUI:
608 case Instruction::FPToSI:
609 case Instruction::PtrToInt:
610 case Instruction::IntToPtr:
611 case Instruction::BitCast:
612 return ConstantExpr::getCast(getOpcode(), Op, getType());
613 case Instruction::Select:
614 Op0 = (OpNo == 0) ? Op : getOperand(0);
615 Op1 = (OpNo == 1) ? Op : getOperand(1);
616 Op2 = (OpNo == 2) ? Op : getOperand(2);
617 return ConstantExpr::getSelect(Op0, Op1, Op2);
618 case Instruction::InsertElement:
619 Op0 = (OpNo == 0) ? Op : getOperand(0);
620 Op1 = (OpNo == 1) ? Op : getOperand(1);
621 Op2 = (OpNo == 2) ? Op : getOperand(2);
622 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
623 case Instruction::ExtractElement:
624 Op0 = (OpNo == 0) ? Op : getOperand(0);
625 Op1 = (OpNo == 1) ? Op : getOperand(1);
626 return ConstantExpr::getExtractElement(Op0, Op1);
627 case Instruction::ShuffleVector:
628 Op0 = (OpNo == 0) ? Op : getOperand(0);
629 Op1 = (OpNo == 1) ? Op : getOperand(1);
630 Op2 = (OpNo == 2) ? Op : getOperand(2);
631 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
632 case Instruction::GetElementPtr: {
633 SmallVector<Constant*, 8> Ops;
634 Ops.resize(getNumOperands());
635 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
636 Ops[i] = getOperand(i);
638 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
640 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
643 assert(getNumOperands() == 2 && "Must be binary operator?");
644 Op0 = (OpNo == 0) ? Op : getOperand(0);
645 Op1 = (OpNo == 1) ? Op : getOperand(1);
646 return ConstantExpr::get(getOpcode(), Op0, Op1);
650 /// getWithOperands - This returns the current constant expression with the
651 /// operands replaced with the specified values. The specified operands must
652 /// match count and type with the existing ones.
653 Constant *ConstantExpr::
654 getWithOperands(const std::vector<Constant*> &Ops) const {
655 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
656 bool AnyChange = false;
657 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
658 assert(Ops[i]->getType() == getOperand(i)->getType() &&
659 "Operand type mismatch!");
660 AnyChange |= Ops[i] != getOperand(i);
662 if (!AnyChange) // No operands changed, return self.
663 return const_cast<ConstantExpr*>(this);
665 switch (getOpcode()) {
666 case Instruction::Trunc:
667 case Instruction::ZExt:
668 case Instruction::SExt:
669 case Instruction::FPTrunc:
670 case Instruction::FPExt:
671 case Instruction::UIToFP:
672 case Instruction::SIToFP:
673 case Instruction::FPToUI:
674 case Instruction::FPToSI:
675 case Instruction::PtrToInt:
676 case Instruction::IntToPtr:
677 case Instruction::BitCast:
678 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
679 case Instruction::Select:
680 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
681 case Instruction::InsertElement:
682 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
683 case Instruction::ExtractElement:
684 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
685 case Instruction::ShuffleVector:
686 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
687 case Instruction::GetElementPtr:
688 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], Ops.size()-1);
689 case Instruction::ICmp:
690 case Instruction::FCmp:
691 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
693 assert(getNumOperands() == 2 && "Must be binary operator?");
694 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
699 //===----------------------------------------------------------------------===//
700 // isValueValidForType implementations
702 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
703 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
704 if (Ty == Type::Int1Ty)
705 return Val == 0 || Val == 1;
707 return true; // always true, has to fit in largest type
708 uint64_t Max = (1ll << NumBits) - 1;
712 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
713 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
714 if (Ty == Type::Int1Ty)
715 return Val == 0 || Val == 1 || Val == -1;
717 return true; // always true, has to fit in largest type
718 int64_t Min = -(1ll << (NumBits-1));
719 int64_t Max = (1ll << (NumBits-1)) - 1;
720 return (Val >= Min && Val <= Max);
723 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
724 // convert modifies in place, so make a copy.
725 APFloat Val2 = APFloat(Val);
726 switch (Ty->getTypeID()) {
728 return false; // These can't be represented as floating point!
730 // FIXME rounding mode needs to be more flexible
731 case Type::FloatTyID:
732 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
733 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven) ==
735 case Type::DoubleTyID:
736 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
737 &Val2.getSemantics() == &APFloat::IEEEdouble ||
738 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven) ==
740 // TODO: Figure out how to test if we can use a shorter type instead!
741 case Type::X86_FP80TyID:
742 case Type::PPC_FP128TyID:
743 case Type::FP128TyID:
748 //===----------------------------------------------------------------------===//
749 // Factory Function Implementation
751 // ConstantCreator - A class that is used to create constants by
752 // ValueMap*. This class should be partially specialized if there is
753 // something strange that needs to be done to interface to the ctor for the
757 template<class ConstantClass, class TypeClass, class ValType>
758 struct VISIBILITY_HIDDEN ConstantCreator {
759 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
760 return new ConstantClass(Ty, V);
764 template<class ConstantClass, class TypeClass>
765 struct VISIBILITY_HIDDEN ConvertConstantType {
766 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
767 assert(0 && "This type cannot be converted!\n");
772 template<class ValType, class TypeClass, class ConstantClass,
773 bool HasLargeKey = false /*true for arrays and structs*/ >
774 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
776 typedef std::pair<const Type*, ValType> MapKey;
777 typedef std::map<MapKey, Constant *> MapTy;
778 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
779 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
781 /// Map - This is the main map from the element descriptor to the Constants.
782 /// This is the primary way we avoid creating two of the same shape
786 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
787 /// from the constants to their element in Map. This is important for
788 /// removal of constants from the array, which would otherwise have to scan
789 /// through the map with very large keys.
790 InverseMapTy InverseMap;
792 /// AbstractTypeMap - Map for abstract type constants.
794 AbstractTypeMapTy AbstractTypeMap;
797 typename MapTy::iterator map_end() { return Map.end(); }
799 /// InsertOrGetItem - Return an iterator for the specified element.
800 /// If the element exists in the map, the returned iterator points to the
801 /// entry and Exists=true. If not, the iterator points to the newly
802 /// inserted entry and returns Exists=false. Newly inserted entries have
803 /// I->second == 0, and should be filled in.
804 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
807 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
813 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
815 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
816 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
817 IMI->second->second == CP &&
818 "InverseMap corrupt!");
822 typename MapTy::iterator I =
823 Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
824 if (I == Map.end() || I->second != CP) {
825 // FIXME: This should not use a linear scan. If this gets to be a
826 // performance problem, someone should look at this.
827 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
834 /// getOrCreate - Return the specified constant from the map, creating it if
836 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
837 MapKey Lookup(Ty, V);
838 typename MapTy::iterator I = Map.lower_bound(Lookup);
840 if (I != Map.end() && I->first == Lookup)
841 return static_cast<ConstantClass *>(I->second);
843 // If no preexisting value, create one now...
844 ConstantClass *Result =
845 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
847 /// FIXME: why does this assert fail when loading 176.gcc?
848 //assert(Result->getType() == Ty && "Type specified is not correct!");
849 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
851 if (HasLargeKey) // Remember the reverse mapping if needed.
852 InverseMap.insert(std::make_pair(Result, I));
854 // If the type of the constant is abstract, make sure that an entry exists
855 // for it in the AbstractTypeMap.
856 if (Ty->isAbstract()) {
857 typename AbstractTypeMapTy::iterator TI =
858 AbstractTypeMap.lower_bound(Ty);
860 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
861 // Add ourselves to the ATU list of the type.
862 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
864 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
870 void remove(ConstantClass *CP) {
871 typename MapTy::iterator I = FindExistingElement(CP);
872 assert(I != Map.end() && "Constant not found in constant table!");
873 assert(I->second == CP && "Didn't find correct element?");
875 if (HasLargeKey) // Remember the reverse mapping if needed.
876 InverseMap.erase(CP);
878 // Now that we found the entry, make sure this isn't the entry that
879 // the AbstractTypeMap points to.
880 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
881 if (Ty->isAbstract()) {
882 assert(AbstractTypeMap.count(Ty) &&
883 "Abstract type not in AbstractTypeMap?");
884 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
885 if (ATMEntryIt == I) {
886 // Yes, we are removing the representative entry for this type.
887 // See if there are any other entries of the same type.
888 typename MapTy::iterator TmpIt = ATMEntryIt;
890 // First check the entry before this one...
891 if (TmpIt != Map.begin()) {
893 if (TmpIt->first.first != Ty) // Not the same type, move back...
897 // If we didn't find the same type, try to move forward...
898 if (TmpIt == ATMEntryIt) {
900 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
901 --TmpIt; // No entry afterwards with the same type
904 // If there is another entry in the map of the same abstract type,
905 // update the AbstractTypeMap entry now.
906 if (TmpIt != ATMEntryIt) {
909 // Otherwise, we are removing the last instance of this type
910 // from the table. Remove from the ATM, and from user list.
911 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
912 AbstractTypeMap.erase(Ty);
921 /// MoveConstantToNewSlot - If we are about to change C to be the element
922 /// specified by I, update our internal data structures to reflect this
924 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
925 // First, remove the old location of the specified constant in the map.
926 typename MapTy::iterator OldI = FindExistingElement(C);
927 assert(OldI != Map.end() && "Constant not found in constant table!");
928 assert(OldI->second == C && "Didn't find correct element?");
930 // If this constant is the representative element for its abstract type,
931 // update the AbstractTypeMap so that the representative element is I.
932 if (C->getType()->isAbstract()) {
933 typename AbstractTypeMapTy::iterator ATI =
934 AbstractTypeMap.find(C->getType());
935 assert(ATI != AbstractTypeMap.end() &&
936 "Abstract type not in AbstractTypeMap?");
937 if (ATI->second == OldI)
941 // Remove the old entry from the map.
944 // Update the inverse map so that we know that this constant is now
945 // located at descriptor I.
947 assert(I->second == C && "Bad inversemap entry!");
952 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
953 typename AbstractTypeMapTy::iterator I =
954 AbstractTypeMap.find(cast<Type>(OldTy));
956 assert(I != AbstractTypeMap.end() &&
957 "Abstract type not in AbstractTypeMap?");
959 // Convert a constant at a time until the last one is gone. The last one
960 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
961 // eliminated eventually.
963 ConvertConstantType<ConstantClass,
965 static_cast<ConstantClass *>(I->second->second),
966 cast<TypeClass>(NewTy));
968 I = AbstractTypeMap.find(cast<Type>(OldTy));
969 } while (I != AbstractTypeMap.end());
972 // If the type became concrete without being refined to any other existing
973 // type, we just remove ourselves from the ATU list.
974 void typeBecameConcrete(const DerivedType *AbsTy) {
975 AbsTy->removeAbstractTypeUser(this);
979 DOUT << "Constant.cpp: ValueMap\n";
986 //---- ConstantAggregateZero::get() implementation...
989 // ConstantAggregateZero does not take extra "value" argument...
990 template<class ValType>
991 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
992 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
993 return new ConstantAggregateZero(Ty);
998 struct ConvertConstantType<ConstantAggregateZero, Type> {
999 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1000 // Make everyone now use a constant of the new type...
1001 Constant *New = ConstantAggregateZero::get(NewTy);
1002 assert(New != OldC && "Didn't replace constant??");
1003 OldC->uncheckedReplaceAllUsesWith(New);
1004 OldC->destroyConstant(); // This constant is now dead, destroy it.
1009 static ManagedStatic<ValueMap<char, Type,
1010 ConstantAggregateZero> > AggZeroConstants;
1012 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1014 Constant *ConstantAggregateZero::get(const Type *Ty) {
1015 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
1016 "Cannot create an aggregate zero of non-aggregate type!");
1017 return AggZeroConstants->getOrCreate(Ty, 0);
1020 // destroyConstant - Remove the constant from the constant table...
1022 void ConstantAggregateZero::destroyConstant() {
1023 AggZeroConstants->remove(this);
1024 destroyConstantImpl();
1027 //---- ConstantArray::get() implementation...
1031 struct ConvertConstantType<ConstantArray, ArrayType> {
1032 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1033 // Make everyone now use a constant of the new type...
1034 std::vector<Constant*> C;
1035 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1036 C.push_back(cast<Constant>(OldC->getOperand(i)));
1037 Constant *New = ConstantArray::get(NewTy, C);
1038 assert(New != OldC && "Didn't replace constant??");
1039 OldC->uncheckedReplaceAllUsesWith(New);
1040 OldC->destroyConstant(); // This constant is now dead, destroy it.
1045 static std::vector<Constant*> getValType(ConstantArray *CA) {
1046 std::vector<Constant*> Elements;
1047 Elements.reserve(CA->getNumOperands());
1048 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1049 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1053 typedef ValueMap<std::vector<Constant*>, ArrayType,
1054 ConstantArray, true /*largekey*/> ArrayConstantsTy;
1055 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
1057 Constant *ConstantArray::get(const ArrayType *Ty,
1058 const std::vector<Constant*> &V) {
1059 // If this is an all-zero array, return a ConstantAggregateZero object
1062 if (!C->isNullValue())
1063 return ArrayConstants->getOrCreate(Ty, V);
1064 for (unsigned i = 1, e = V.size(); i != e; ++i)
1066 return ArrayConstants->getOrCreate(Ty, V);
1068 return ConstantAggregateZero::get(Ty);
1071 // destroyConstant - Remove the constant from the constant table...
1073 void ConstantArray::destroyConstant() {
1074 ArrayConstants->remove(this);
1075 destroyConstantImpl();
1078 /// ConstantArray::get(const string&) - Return an array that is initialized to
1079 /// contain the specified string. If length is zero then a null terminator is
1080 /// added to the specified string so that it may be used in a natural way.
1081 /// Otherwise, the length parameter specifies how much of the string to use
1082 /// and it won't be null terminated.
1084 Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
1085 std::vector<Constant*> ElementVals;
1086 for (unsigned i = 0; i < Str.length(); ++i)
1087 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
1089 // Add a null terminator to the string...
1091 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
1094 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
1095 return ConstantArray::get(ATy, ElementVals);
1098 /// isString - This method returns true if the array is an array of i8, and
1099 /// if the elements of the array are all ConstantInt's.
1100 bool ConstantArray::isString() const {
1101 // Check the element type for i8...
1102 if (getType()->getElementType() != Type::Int8Ty)
1104 // Check the elements to make sure they are all integers, not constant
1106 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1107 if (!isa<ConstantInt>(getOperand(i)))
1112 /// isCString - This method returns true if the array is a string (see
1113 /// isString) and it ends in a null byte \0 and does not contains any other
1114 /// null bytes except its terminator.
1115 bool ConstantArray::isCString() const {
1116 // Check the element type for i8...
1117 if (getType()->getElementType() != Type::Int8Ty)
1119 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1120 // Last element must be a null.
1121 if (getOperand(getNumOperands()-1) != Zero)
1123 // Other elements must be non-null integers.
1124 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1125 if (!isa<ConstantInt>(getOperand(i)))
1127 if (getOperand(i) == Zero)
1134 // getAsString - If the sub-element type of this array is i8
1135 // then this method converts the array to an std::string and returns it.
1136 // Otherwise, it asserts out.
1138 std::string ConstantArray::getAsString() const {
1139 assert(isString() && "Not a string!");
1141 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1142 Result += (char)cast<ConstantInt>(getOperand(i))->getZExtValue();
1147 //---- ConstantStruct::get() implementation...
1152 struct ConvertConstantType<ConstantStruct, StructType> {
1153 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1154 // Make everyone now use a constant of the new type...
1155 std::vector<Constant*> C;
1156 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1157 C.push_back(cast<Constant>(OldC->getOperand(i)));
1158 Constant *New = ConstantStruct::get(NewTy, C);
1159 assert(New != OldC && "Didn't replace constant??");
1161 OldC->uncheckedReplaceAllUsesWith(New);
1162 OldC->destroyConstant(); // This constant is now dead, destroy it.
1167 typedef ValueMap<std::vector<Constant*>, StructType,
1168 ConstantStruct, true /*largekey*/> StructConstantsTy;
1169 static ManagedStatic<StructConstantsTy> StructConstants;
1171 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1172 std::vector<Constant*> Elements;
1173 Elements.reserve(CS->getNumOperands());
1174 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1175 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1179 Constant *ConstantStruct::get(const StructType *Ty,
1180 const std::vector<Constant*> &V) {
1181 // Create a ConstantAggregateZero value if all elements are zeros...
1182 for (unsigned i = 0, e = V.size(); i != e; ++i)
1183 if (!V[i]->isNullValue())
1184 return StructConstants->getOrCreate(Ty, V);
1186 return ConstantAggregateZero::get(Ty);
1189 Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
1190 std::vector<const Type*> StructEls;
1191 StructEls.reserve(V.size());
1192 for (unsigned i = 0, e = V.size(); i != e; ++i)
1193 StructEls.push_back(V[i]->getType());
1194 return get(StructType::get(StructEls, packed), V);
1197 // destroyConstant - Remove the constant from the constant table...
1199 void ConstantStruct::destroyConstant() {
1200 StructConstants->remove(this);
1201 destroyConstantImpl();
1204 //---- ConstantVector::get() implementation...
1208 struct ConvertConstantType<ConstantVector, VectorType> {
1209 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
1210 // Make everyone now use a constant of the new type...
1211 std::vector<Constant*> C;
1212 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1213 C.push_back(cast<Constant>(OldC->getOperand(i)));
1214 Constant *New = ConstantVector::get(NewTy, C);
1215 assert(New != OldC && "Didn't replace constant??");
1216 OldC->uncheckedReplaceAllUsesWith(New);
1217 OldC->destroyConstant(); // This constant is now dead, destroy it.
1222 static std::vector<Constant*> getValType(ConstantVector *CP) {
1223 std::vector<Constant*> Elements;
1224 Elements.reserve(CP->getNumOperands());
1225 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1226 Elements.push_back(CP->getOperand(i));
1230 static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
1231 ConstantVector> > VectorConstants;
1233 Constant *ConstantVector::get(const VectorType *Ty,
1234 const std::vector<Constant*> &V) {
1235 // If this is an all-zero vector, return a ConstantAggregateZero object
1238 if (!C->isNullValue())
1239 return VectorConstants->getOrCreate(Ty, V);
1240 for (unsigned i = 1, e = V.size(); i != e; ++i)
1242 return VectorConstants->getOrCreate(Ty, V);
1244 return ConstantAggregateZero::get(Ty);
1247 Constant *ConstantVector::get(const std::vector<Constant*> &V) {
1248 assert(!V.empty() && "Cannot infer type if V is empty");
1249 return get(VectorType::get(V.front()->getType(),V.size()), V);
1252 // destroyConstant - Remove the constant from the constant table...
1254 void ConstantVector::destroyConstant() {
1255 VectorConstants->remove(this);
1256 destroyConstantImpl();
1259 /// This function will return true iff every element in this vector constant
1260 /// is set to all ones.
1261 /// @returns true iff this constant's emements are all set to all ones.
1262 /// @brief Determine if the value is all ones.
1263 bool ConstantVector::isAllOnesValue() const {
1264 // Check out first element.
1265 const Constant *Elt = getOperand(0);
1266 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1267 if (!CI || !CI->isAllOnesValue()) return false;
1268 // Then make sure all remaining elements point to the same value.
1269 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1270 if (getOperand(I) != Elt) return false;
1275 //---- ConstantPointerNull::get() implementation...
1279 // ConstantPointerNull does not take extra "value" argument...
1280 template<class ValType>
1281 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1282 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1283 return new ConstantPointerNull(Ty);
1288 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1289 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1290 // Make everyone now use a constant of the new type...
1291 Constant *New = ConstantPointerNull::get(NewTy);
1292 assert(New != OldC && "Didn't replace constant??");
1293 OldC->uncheckedReplaceAllUsesWith(New);
1294 OldC->destroyConstant(); // This constant is now dead, destroy it.
1299 static ManagedStatic<ValueMap<char, PointerType,
1300 ConstantPointerNull> > NullPtrConstants;
1302 static char getValType(ConstantPointerNull *) {
1307 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1308 return NullPtrConstants->getOrCreate(Ty, 0);
1311 // destroyConstant - Remove the constant from the constant table...
1313 void ConstantPointerNull::destroyConstant() {
1314 NullPtrConstants->remove(this);
1315 destroyConstantImpl();
1319 //---- UndefValue::get() implementation...
1323 // UndefValue does not take extra "value" argument...
1324 template<class ValType>
1325 struct ConstantCreator<UndefValue, Type, ValType> {
1326 static UndefValue *create(const Type *Ty, const ValType &V) {
1327 return new UndefValue(Ty);
1332 struct ConvertConstantType<UndefValue, Type> {
1333 static void convert(UndefValue *OldC, const Type *NewTy) {
1334 // Make everyone now use a constant of the new type.
1335 Constant *New = UndefValue::get(NewTy);
1336 assert(New != OldC && "Didn't replace constant??");
1337 OldC->uncheckedReplaceAllUsesWith(New);
1338 OldC->destroyConstant(); // This constant is now dead, destroy it.
1343 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1345 static char getValType(UndefValue *) {
1350 UndefValue *UndefValue::get(const Type *Ty) {
1351 return UndefValueConstants->getOrCreate(Ty, 0);
1354 // destroyConstant - Remove the constant from the constant table.
1356 void UndefValue::destroyConstant() {
1357 UndefValueConstants->remove(this);
1358 destroyConstantImpl();
1362 //---- ConstantExpr::get() implementations...
1365 struct ExprMapKeyType {
1366 explicit ExprMapKeyType(unsigned opc, std::vector<Constant*> ops,
1367 unsigned short pred = 0) : opcode(opc), predicate(pred), operands(ops) { }
1370 std::vector<Constant*> operands;
1371 bool operator==(const ExprMapKeyType& that) const {
1372 return this->opcode == that.opcode &&
1373 this->predicate == that.predicate &&
1374 this->operands == that.operands;
1376 bool operator<(const ExprMapKeyType & that) const {
1377 return this->opcode < that.opcode ||
1378 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1379 (this->opcode == that.opcode && this->predicate == that.predicate &&
1380 this->operands < that.operands);
1383 bool operator!=(const ExprMapKeyType& that) const {
1384 return !(*this == that);
1390 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1391 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1392 unsigned short pred = 0) {
1393 if (Instruction::isCast(V.opcode))
1394 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1395 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1396 V.opcode < Instruction::BinaryOpsEnd))
1397 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1398 if (V.opcode == Instruction::Select)
1399 return new SelectConstantExpr(V.operands[0], V.operands[1],
1401 if (V.opcode == Instruction::ExtractElement)
1402 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1403 if (V.opcode == Instruction::InsertElement)
1404 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1406 if (V.opcode == Instruction::ShuffleVector)
1407 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1409 if (V.opcode == Instruction::GetElementPtr) {
1410 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1411 return new GetElementPtrConstantExpr(V.operands[0], IdxList, Ty);
1414 // The compare instructions are weird. We have to encode the predicate
1415 // value and it is combined with the instruction opcode by multiplying
1416 // the opcode by one hundred. We must decode this to get the predicate.
1417 if (V.opcode == Instruction::ICmp)
1418 return new CompareConstantExpr(Instruction::ICmp, V.predicate,
1419 V.operands[0], V.operands[1]);
1420 if (V.opcode == Instruction::FCmp)
1421 return new CompareConstantExpr(Instruction::FCmp, V.predicate,
1422 V.operands[0], V.operands[1]);
1423 assert(0 && "Invalid ConstantExpr!");
1429 struct ConvertConstantType<ConstantExpr, Type> {
1430 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1432 switch (OldC->getOpcode()) {
1433 case Instruction::Trunc:
1434 case Instruction::ZExt:
1435 case Instruction::SExt:
1436 case Instruction::FPTrunc:
1437 case Instruction::FPExt:
1438 case Instruction::UIToFP:
1439 case Instruction::SIToFP:
1440 case Instruction::FPToUI:
1441 case Instruction::FPToSI:
1442 case Instruction::PtrToInt:
1443 case Instruction::IntToPtr:
1444 case Instruction::BitCast:
1445 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1448 case Instruction::Select:
1449 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1450 OldC->getOperand(1),
1451 OldC->getOperand(2));
1454 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1455 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1456 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1457 OldC->getOperand(1));
1459 case Instruction::GetElementPtr:
1460 // Make everyone now use a constant of the new type...
1461 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1462 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1463 &Idx[0], Idx.size());
1467 assert(New != OldC && "Didn't replace constant??");
1468 OldC->uncheckedReplaceAllUsesWith(New);
1469 OldC->destroyConstant(); // This constant is now dead, destroy it.
1472 } // end namespace llvm
1475 static ExprMapKeyType getValType(ConstantExpr *CE) {
1476 std::vector<Constant*> Operands;
1477 Operands.reserve(CE->getNumOperands());
1478 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1479 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1480 return ExprMapKeyType(CE->getOpcode(), Operands,
1481 CE->isCompare() ? CE->getPredicate() : 0);
1484 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1485 ConstantExpr> > ExprConstants;
1487 /// This is a utility function to handle folding of casts and lookup of the
1488 /// cast in the ExprConstants map. It is usedby the various get* methods below.
1489 static inline Constant *getFoldedCast(
1490 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1491 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1492 // Fold a few common cases
1493 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1496 // Look up the constant in the table first to ensure uniqueness
1497 std::vector<Constant*> argVec(1, C);
1498 ExprMapKeyType Key(opc, argVec);
1499 return ExprConstants->getOrCreate(Ty, Key);
1502 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1503 Instruction::CastOps opc = Instruction::CastOps(oc);
1504 assert(Instruction::isCast(opc) && "opcode out of range");
1505 assert(C && Ty && "Null arguments to getCast");
1506 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1510 assert(0 && "Invalid cast opcode");
1512 case Instruction::Trunc: return getTrunc(C, Ty);
1513 case Instruction::ZExt: return getZExt(C, Ty);
1514 case Instruction::SExt: return getSExt(C, Ty);
1515 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1516 case Instruction::FPExt: return getFPExtend(C, Ty);
1517 case Instruction::UIToFP: return getUIToFP(C, Ty);
1518 case Instruction::SIToFP: return getSIToFP(C, Ty);
1519 case Instruction::FPToUI: return getFPToUI(C, Ty);
1520 case Instruction::FPToSI: return getFPToSI(C, Ty);
1521 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1522 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1523 case Instruction::BitCast: return getBitCast(C, Ty);
1528 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1529 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1530 return getCast(Instruction::BitCast, C, Ty);
1531 return getCast(Instruction::ZExt, C, Ty);
1534 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1535 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1536 return getCast(Instruction::BitCast, C, Ty);
1537 return getCast(Instruction::SExt, C, Ty);
1540 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1541 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1542 return getCast(Instruction::BitCast, C, Ty);
1543 return getCast(Instruction::Trunc, C, Ty);
1546 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1547 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1548 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1550 if (Ty->isInteger())
1551 return getCast(Instruction::PtrToInt, S, Ty);
1552 return getCast(Instruction::BitCast, S, Ty);
1555 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1557 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1558 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1559 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1560 Instruction::CastOps opcode =
1561 (SrcBits == DstBits ? Instruction::BitCast :
1562 (SrcBits > DstBits ? Instruction::Trunc :
1563 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1564 return getCast(opcode, C, Ty);
1567 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1568 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1570 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1571 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1572 if (SrcBits == DstBits)
1573 return C; // Avoid a useless cast
1574 Instruction::CastOps opcode =
1575 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1576 return getCast(opcode, C, Ty);
1579 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1580 assert(C->getType()->isInteger() && "Trunc operand must be integer");
1581 assert(Ty->isInteger() && "Trunc produces only integral");
1582 assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1583 "SrcTy must be larger than DestTy for Trunc!");
1585 return getFoldedCast(Instruction::Trunc, C, Ty);
1588 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1589 assert(C->getType()->isInteger() && "SEXt operand must be integral");
1590 assert(Ty->isInteger() && "SExt produces only integer");
1591 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1592 "SrcTy must be smaller than DestTy for SExt!");
1594 return getFoldedCast(Instruction::SExt, C, Ty);
1597 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1598 assert(C->getType()->isInteger() && "ZEXt operand must be integral");
1599 assert(Ty->isInteger() && "ZExt produces only integer");
1600 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1601 "SrcTy must be smaller than DestTy for ZExt!");
1603 return getFoldedCast(Instruction::ZExt, C, Ty);
1606 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1607 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1608 C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1609 "This is an illegal floating point truncation!");
1610 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1613 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1614 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1615 C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1616 "This is an illegal floating point extension!");
1617 return getFoldedCast(Instruction::FPExt, C, Ty);
1620 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1621 assert(C->getType()->isInteger() && Ty->isFloatingPoint() &&
1622 "This is an illegal i32 to floating point cast!");
1623 return getFoldedCast(Instruction::UIToFP, C, Ty);
1626 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1627 assert(C->getType()->isInteger() && Ty->isFloatingPoint() &&
1628 "This is an illegal sint to floating point cast!");
1629 return getFoldedCast(Instruction::SIToFP, C, Ty);
1632 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1633 assert(C->getType()->isFloatingPoint() && Ty->isInteger() &&
1634 "This is an illegal floating point to i32 cast!");
1635 return getFoldedCast(Instruction::FPToUI, C, Ty);
1638 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1639 assert(C->getType()->isFloatingPoint() && Ty->isInteger() &&
1640 "This is an illegal floating point to i32 cast!");
1641 return getFoldedCast(Instruction::FPToSI, C, Ty);
1644 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1645 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1646 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1647 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1650 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1651 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1652 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1653 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1656 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1657 // BitCast implies a no-op cast of type only. No bits change. However, you
1658 // can't cast pointers to anything but pointers.
1659 const Type *SrcTy = C->getType();
1660 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1661 "BitCast cannot cast pointer to non-pointer and vice versa");
1663 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1664 // or nonptr->ptr). For all the other types, the cast is okay if source and
1665 // destination bit widths are identical.
1666 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1667 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1668 assert(SrcBitSize == DstBitSize && "BitCast requies types of same width");
1669 return getFoldedCast(Instruction::BitCast, C, DstTy);
1672 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
1673 // sizeof is implemented as: (ulong) gep (Ty*)null, 1
1674 Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
1676 getGetElementPtr(getNullValue(PointerType::get(Ty)), &GEPIdx, 1);
1677 return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
1680 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1681 Constant *C1, Constant *C2) {
1682 // Check the operands for consistency first
1683 assert(Opcode >= Instruction::BinaryOpsBegin &&
1684 Opcode < Instruction::BinaryOpsEnd &&
1685 "Invalid opcode in binary constant expression");
1686 assert(C1->getType() == C2->getType() &&
1687 "Operand types in binary constant expression should match");
1689 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
1690 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1691 return FC; // Fold a few common cases...
1693 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1694 ExprMapKeyType Key(Opcode, argVec);
1695 return ExprConstants->getOrCreate(ReqTy, Key);
1698 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1699 Constant *C1, Constant *C2) {
1700 switch (predicate) {
1701 default: assert(0 && "Invalid CmpInst predicate");
1702 case FCmpInst::FCMP_FALSE: case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_OGT:
1703 case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OLE:
1704 case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_ORD: case FCmpInst::FCMP_UNO:
1705 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UGT: case FCmpInst::FCMP_UGE:
1706 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_ULE: case FCmpInst::FCMP_UNE:
1707 case FCmpInst::FCMP_TRUE:
1708 return getFCmp(predicate, C1, C2);
1709 case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGT:
1710 case ICmpInst::ICMP_UGE: case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE:
1711 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_SGE: case ICmpInst::ICMP_SLT:
1712 case ICmpInst::ICMP_SLE:
1713 return getICmp(predicate, C1, C2);
1717 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1720 case Instruction::Add:
1721 case Instruction::Sub:
1722 case Instruction::Mul:
1723 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1724 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
1725 isa<VectorType>(C1->getType())) &&
1726 "Tried to create an arithmetic operation on a non-arithmetic type!");
1728 case Instruction::UDiv:
1729 case Instruction::SDiv:
1730 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1731 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1732 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
1733 "Tried to create an arithmetic operation on a non-arithmetic type!");
1735 case Instruction::FDiv:
1736 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1737 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1738 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
1739 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1741 case Instruction::URem:
1742 case Instruction::SRem:
1743 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1744 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1745 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
1746 "Tried to create an arithmetic operation on a non-arithmetic type!");
1748 case Instruction::FRem:
1749 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1750 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1751 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
1752 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1754 case Instruction::And:
1755 case Instruction::Or:
1756 case Instruction::Xor:
1757 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1758 assert((C1->getType()->isInteger() || isa<VectorType>(C1->getType())) &&
1759 "Tried to create a logical operation on a non-integral type!");
1761 case Instruction::Shl:
1762 case Instruction::LShr:
1763 case Instruction::AShr:
1764 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1765 assert(C1->getType()->isInteger() &&
1766 "Tried to create a shift operation on a non-integer type!");
1773 return getTy(C1->getType(), Opcode, C1, C2);
1776 Constant *ConstantExpr::getCompare(unsigned short pred,
1777 Constant *C1, Constant *C2) {
1778 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1779 return getCompareTy(pred, C1, C2);
1782 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1783 Constant *V1, Constant *V2) {
1784 assert(C->getType() == Type::Int1Ty && "Select condition must be i1!");
1785 assert(V1->getType() == V2->getType() && "Select value types must match!");
1786 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1788 if (ReqTy == V1->getType())
1789 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1790 return SC; // Fold common cases
1792 std::vector<Constant*> argVec(3, C);
1795 ExprMapKeyType Key(Instruction::Select, argVec);
1796 return ExprConstants->getOrCreate(ReqTy, Key);
1799 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1802 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs, NumIdx, true) &&
1803 "GEP indices invalid!");
1805 if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs, NumIdx))
1806 return FC; // Fold a few common cases...
1808 assert(isa<PointerType>(C->getType()) &&
1809 "Non-pointer type for constant GetElementPtr expression");
1810 // Look up the constant in the table first to ensure uniqueness
1811 std::vector<Constant*> ArgVec;
1812 ArgVec.reserve(NumIdx+1);
1813 ArgVec.push_back(C);
1814 for (unsigned i = 0; i != NumIdx; ++i)
1815 ArgVec.push_back(cast<Constant>(Idxs[i]));
1816 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
1817 return ExprConstants->getOrCreate(ReqTy, Key);
1820 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1822 // Get the result type of the getelementptr!
1824 GetElementPtrInst::getIndexedType(C->getType(), Idxs, NumIdx, true);
1825 assert(Ty && "GEP indices invalid!");
1826 return getGetElementPtrTy(PointerType::get(Ty), C, Idxs, NumIdx);
1829 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1831 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1836 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1837 assert(LHS->getType() == RHS->getType());
1838 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1839 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1841 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1842 return FC; // Fold a few common cases...
1844 // Look up the constant in the table first to ensure uniqueness
1845 std::vector<Constant*> ArgVec;
1846 ArgVec.push_back(LHS);
1847 ArgVec.push_back(RHS);
1848 // Get the key type with both the opcode and predicate
1849 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1850 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1854 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1855 assert(LHS->getType() == RHS->getType());
1856 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1858 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1859 return FC; // Fold a few common cases...
1861 // Look up the constant in the table first to ensure uniqueness
1862 std::vector<Constant*> ArgVec;
1863 ArgVec.push_back(LHS);
1864 ArgVec.push_back(RHS);
1865 // Get the key type with both the opcode and predicate
1866 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1867 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1870 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1872 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1873 return FC; // Fold a few common cases...
1874 // Look up the constant in the table first to ensure uniqueness
1875 std::vector<Constant*> ArgVec(1, Val);
1876 ArgVec.push_back(Idx);
1877 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1878 return ExprConstants->getOrCreate(ReqTy, Key);
1881 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1882 assert(isa<VectorType>(Val->getType()) &&
1883 "Tried to create extractelement operation on non-vector type!");
1884 assert(Idx->getType() == Type::Int32Ty &&
1885 "Extractelement index must be i32 type!");
1886 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
1890 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1891 Constant *Elt, Constant *Idx) {
1892 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1893 return FC; // Fold a few common cases...
1894 // Look up the constant in the table first to ensure uniqueness
1895 std::vector<Constant*> ArgVec(1, Val);
1896 ArgVec.push_back(Elt);
1897 ArgVec.push_back(Idx);
1898 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1899 return ExprConstants->getOrCreate(ReqTy, Key);
1902 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1904 assert(isa<VectorType>(Val->getType()) &&
1905 "Tried to create insertelement operation on non-vector type!");
1906 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
1907 && "Insertelement types must match!");
1908 assert(Idx->getType() == Type::Int32Ty &&
1909 "Insertelement index must be i32 type!");
1910 return getInsertElementTy(cast<VectorType>(Val->getType())->getElementType(),
1914 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1915 Constant *V2, Constant *Mask) {
1916 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1917 return FC; // Fold a few common cases...
1918 // Look up the constant in the table first to ensure uniqueness
1919 std::vector<Constant*> ArgVec(1, V1);
1920 ArgVec.push_back(V2);
1921 ArgVec.push_back(Mask);
1922 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1923 return ExprConstants->getOrCreate(ReqTy, Key);
1926 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1928 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1929 "Invalid shuffle vector constant expr operands!");
1930 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
1933 Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
1934 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
1935 if (PTy->getElementType()->isFloatingPoint()) {
1936 std::vector<Constant*> zeros(PTy->getNumElements(),
1937 ConstantFP::get(PTy->getElementType(),-0.0));
1938 return ConstantVector::get(PTy, zeros);
1941 if (Ty->isFloatingPoint())
1942 return ConstantFP::get(Ty, -0.0);
1944 return Constant::getNullValue(Ty);
1947 // destroyConstant - Remove the constant from the constant table...
1949 void ConstantExpr::destroyConstant() {
1950 ExprConstants->remove(this);
1951 destroyConstantImpl();
1954 const char *ConstantExpr::getOpcodeName() const {
1955 return Instruction::getOpcodeName(getOpcode());
1958 //===----------------------------------------------------------------------===//
1959 // replaceUsesOfWithOnConstant implementations
1961 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
1962 /// 'From' to be uses of 'To'. This must update the uniquing data structures
1965 /// Note that we intentionally replace all uses of From with To here. Consider
1966 /// a large array that uses 'From' 1000 times. By handling this case all here,
1967 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
1968 /// single invocation handles all 1000 uses. Handling them one at a time would
1969 /// work, but would be really slow because it would have to unique each updated
1971 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1973 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1974 Constant *ToC = cast<Constant>(To);
1976 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
1977 Lookup.first.first = getType();
1978 Lookup.second = this;
1980 std::vector<Constant*> &Values = Lookup.first.second;
1981 Values.reserve(getNumOperands()); // Build replacement array.
1983 // Fill values with the modified operands of the constant array. Also,
1984 // compute whether this turns into an all-zeros array.
1985 bool isAllZeros = false;
1986 unsigned NumUpdated = 0;
1987 if (!ToC->isNullValue()) {
1988 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1989 Constant *Val = cast<Constant>(O->get());
1994 Values.push_back(Val);
1998 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1999 Constant *Val = cast<Constant>(O->get());
2004 Values.push_back(Val);
2005 if (isAllZeros) isAllZeros = Val->isNullValue();
2009 Constant *Replacement = 0;
2011 Replacement = ConstantAggregateZero::get(getType());
2013 // Check to see if we have this array type already.
2015 ArrayConstantsTy::MapTy::iterator I =
2016 ArrayConstants->InsertOrGetItem(Lookup, Exists);
2019 Replacement = I->second;
2021 // Okay, the new shape doesn't exist in the system yet. Instead of
2022 // creating a new constant array, inserting it, replaceallusesof'ing the
2023 // old with the new, then deleting the old... just update the current one
2025 ArrayConstants->MoveConstantToNewSlot(this, I);
2027 // Update to the new value. Optimize for the case when we have a single
2028 // operand that we're changing, but handle bulk updates efficiently.
2029 if (NumUpdated == 1) {
2030 unsigned OperandToUpdate = U-OperandList;
2031 assert(getOperand(OperandToUpdate) == From &&
2032 "ReplaceAllUsesWith broken!");
2033 setOperand(OperandToUpdate, ToC);
2035 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2036 if (getOperand(i) == From)
2043 // Otherwise, I do need to replace this with an existing value.
2044 assert(Replacement != this && "I didn't contain From!");
2046 // Everyone using this now uses the replacement.
2047 uncheckedReplaceAllUsesWith(Replacement);
2049 // Delete the old constant!
2053 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2055 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2056 Constant *ToC = cast<Constant>(To);
2058 unsigned OperandToUpdate = U-OperandList;
2059 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2061 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
2062 Lookup.first.first = getType();
2063 Lookup.second = this;
2064 std::vector<Constant*> &Values = Lookup.first.second;
2065 Values.reserve(getNumOperands()); // Build replacement struct.
2068 // Fill values with the modified operands of the constant struct. Also,
2069 // compute whether this turns into an all-zeros struct.
2070 bool isAllZeros = false;
2071 if (!ToC->isNullValue()) {
2072 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2073 Values.push_back(cast<Constant>(O->get()));
2076 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2077 Constant *Val = cast<Constant>(O->get());
2078 Values.push_back(Val);
2079 if (isAllZeros) isAllZeros = Val->isNullValue();
2082 Values[OperandToUpdate] = ToC;
2084 Constant *Replacement = 0;
2086 Replacement = ConstantAggregateZero::get(getType());
2088 // Check to see if we have this array type already.
2090 StructConstantsTy::MapTy::iterator I =
2091 StructConstants->InsertOrGetItem(Lookup, Exists);
2094 Replacement = I->second;
2096 // Okay, the new shape doesn't exist in the system yet. Instead of
2097 // creating a new constant struct, inserting it, replaceallusesof'ing the
2098 // old with the new, then deleting the old... just update the current one
2100 StructConstants->MoveConstantToNewSlot(this, I);
2102 // Update to the new value.
2103 setOperand(OperandToUpdate, ToC);
2108 assert(Replacement != this && "I didn't contain From!");
2110 // Everyone using this now uses the replacement.
2111 uncheckedReplaceAllUsesWith(Replacement);
2113 // Delete the old constant!
2117 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2119 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2121 std::vector<Constant*> Values;
2122 Values.reserve(getNumOperands()); // Build replacement array...
2123 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2124 Constant *Val = getOperand(i);
2125 if (Val == From) Val = cast<Constant>(To);
2126 Values.push_back(Val);
2129 Constant *Replacement = ConstantVector::get(getType(), Values);
2130 assert(Replacement != this && "I didn't contain From!");
2132 // Everyone using this now uses the replacement.
2133 uncheckedReplaceAllUsesWith(Replacement);
2135 // Delete the old constant!
2139 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2141 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2142 Constant *To = cast<Constant>(ToV);
2144 Constant *Replacement = 0;
2145 if (getOpcode() == Instruction::GetElementPtr) {
2146 SmallVector<Constant*, 8> Indices;
2147 Constant *Pointer = getOperand(0);
2148 Indices.reserve(getNumOperands()-1);
2149 if (Pointer == From) Pointer = To;
2151 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2152 Constant *Val = getOperand(i);
2153 if (Val == From) Val = To;
2154 Indices.push_back(Val);
2156 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2157 &Indices[0], Indices.size());
2158 } else if (isCast()) {
2159 assert(getOperand(0) == From && "Cast only has one use!");
2160 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2161 } else if (getOpcode() == Instruction::Select) {
2162 Constant *C1 = getOperand(0);
2163 Constant *C2 = getOperand(1);
2164 Constant *C3 = getOperand(2);
2165 if (C1 == From) C1 = To;
2166 if (C2 == From) C2 = To;
2167 if (C3 == From) C3 = To;
2168 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2169 } else if (getOpcode() == Instruction::ExtractElement) {
2170 Constant *C1 = getOperand(0);
2171 Constant *C2 = getOperand(1);
2172 if (C1 == From) C1 = To;
2173 if (C2 == From) C2 = To;
2174 Replacement = ConstantExpr::getExtractElement(C1, C2);
2175 } else if (getOpcode() == Instruction::InsertElement) {
2176 Constant *C1 = getOperand(0);
2177 Constant *C2 = getOperand(1);
2178 Constant *C3 = getOperand(1);
2179 if (C1 == From) C1 = To;
2180 if (C2 == From) C2 = To;
2181 if (C3 == From) C3 = To;
2182 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2183 } else if (getOpcode() == Instruction::ShuffleVector) {
2184 Constant *C1 = getOperand(0);
2185 Constant *C2 = getOperand(1);
2186 Constant *C3 = getOperand(2);
2187 if (C1 == From) C1 = To;
2188 if (C2 == From) C2 = To;
2189 if (C3 == From) C3 = To;
2190 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2191 } else if (isCompare()) {
2192 Constant *C1 = getOperand(0);
2193 Constant *C2 = getOperand(1);
2194 if (C1 == From) C1 = To;
2195 if (C2 == From) C2 = To;
2196 if (getOpcode() == Instruction::ICmp)
2197 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2199 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2200 } else if (getNumOperands() == 2) {
2201 Constant *C1 = getOperand(0);
2202 Constant *C2 = getOperand(1);
2203 if (C1 == From) C1 = To;
2204 if (C2 == From) C2 = To;
2205 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2207 assert(0 && "Unknown ConstantExpr type!");
2211 assert(Replacement != this && "I didn't contain From!");
2213 // Everyone using this now uses the replacement.
2214 uncheckedReplaceAllUsesWith(Replacement);
2216 // Delete the old constant!
2221 /// getStringValue - Turn an LLVM constant pointer that eventually points to a
2222 /// global into a string value. Return an empty string if we can't do it.
2223 /// Parameter Chop determines if the result is chopped at the first null
2226 std::string Constant::getStringValue(bool Chop, unsigned Offset) {
2227 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
2228 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
2229 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
2230 if (Init->isString()) {
2231 std::string Result = Init->getAsString();
2232 if (Offset < Result.size()) {
2233 // If we are pointing INTO The string, erase the beginning...
2234 Result.erase(Result.begin(), Result.begin()+Offset);
2236 // Take off the null terminator, and any string fragments after it.
2238 std::string::size_type NullPos = Result.find_first_of((char)0);
2239 if (NullPos != std::string::npos)
2240 Result.erase(Result.begin()+NullPos, Result.end());
2246 } else if (Constant *C = dyn_cast<Constant>(this)) {
2247 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
2248 return GV->getStringValue(Chop, Offset);
2249 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2250 if (CE->getOpcode() == Instruction::GetElementPtr) {
2251 // Turn a gep into the specified offset.
2252 if (CE->getNumOperands() == 3 &&
2253 cast<Constant>(CE->getOperand(1))->isNullValue() &&
2254 isa<ConstantInt>(CE->getOperand(2))) {
2255 Offset += cast<ConstantInt>(CE->getOperand(2))->getZExtValue();
2256 return CE->getOperand(0)->getStringValue(Chop, Offset);