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 true; }
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) {
247 bool ConstantFP::isNullValue() const {
248 return DoubleToBits(Val) == 0;
251 bool ConstantFP::isExactlyValue(double V) const {
252 return DoubleToBits(V) == DoubleToBits(Val);
257 struct DenseMapInt64KeyInfo {
258 typedef std::pair<uint64_t, const Type*> KeyTy;
259 static inline KeyTy getEmptyKey() { return KeyTy(0, 0); }
260 static inline KeyTy getTombstoneKey() { return KeyTy(1, 0); }
261 static unsigned getHashValue(const KeyTy &Key) {
262 return DenseMapKeyInfo<void*>::getHashValue(Key.second) ^ Key.first;
264 static bool isPod() { return true; }
266 struct DenseMapInt32KeyInfo {
267 typedef std::pair<uint32_t, const Type*> KeyTy;
268 static inline KeyTy getEmptyKey() { return KeyTy(0, 0); }
269 static inline KeyTy getTombstoneKey() { return KeyTy(1, 0); }
270 static unsigned getHashValue(const KeyTy &Key) {
271 return DenseMapKeyInfo<void*>::getHashValue(Key.second) ^ Key.first;
273 static bool isPod() { return true; }
277 //---- ConstantFP::get() implementation...
279 typedef DenseMap<DenseMapInt32KeyInfo::KeyTy, ConstantFP*,
280 DenseMapInt32KeyInfo> FloatMapTy;
281 typedef DenseMap<DenseMapInt64KeyInfo::KeyTy, ConstantFP*,
282 DenseMapInt64KeyInfo> DoubleMapTy;
284 static ManagedStatic<FloatMapTy> FloatConstants;
285 static ManagedStatic<DoubleMapTy> DoubleConstants;
287 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
288 if (Ty == Type::FloatTy) {
289 uint32_t IntVal = FloatToBits((float)V);
291 ConstantFP *&Slot = (*FloatConstants)[std::make_pair(IntVal, Ty)];
292 if (Slot) return Slot;
293 return Slot = new ConstantFP(Ty, (float)V);
294 } else if (Ty == Type::DoubleTy) {
295 uint64_t IntVal = DoubleToBits(V);
296 ConstantFP *&Slot = (*DoubleConstants)[std::make_pair(IntVal, Ty)];
297 if (Slot) return Slot;
298 return Slot = new ConstantFP(Ty, V);
299 // FIXME: Make long double constants work.
300 } else if (Ty == Type::X86_FP80Ty ||
301 Ty == Type::PPC_FP128Ty || Ty == Type::FP128Ty) {
302 assert(0 && "Long double constants not handled yet.");
304 assert(0 && "Unknown FP Type!");
309 //===----------------------------------------------------------------------===//
310 // ConstantXXX Classes
311 //===----------------------------------------------------------------------===//
314 ConstantArray::ConstantArray(const ArrayType *T,
315 const std::vector<Constant*> &V)
316 : Constant(T, ConstantArrayVal, new Use[V.size()], V.size()) {
317 assert(V.size() == T->getNumElements() &&
318 "Invalid initializer vector for constant array");
319 Use *OL = OperandList;
320 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
323 assert((C->getType() == T->getElementType() ||
325 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
326 "Initializer for array element doesn't match array element type!");
331 ConstantArray::~ConstantArray() {
332 delete [] OperandList;
335 ConstantStruct::ConstantStruct(const StructType *T,
336 const std::vector<Constant*> &V)
337 : Constant(T, ConstantStructVal, new Use[V.size()], V.size()) {
338 assert(V.size() == T->getNumElements() &&
339 "Invalid initializer vector for constant structure");
340 Use *OL = OperandList;
341 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
344 assert((C->getType() == T->getElementType(I-V.begin()) ||
345 ((T->getElementType(I-V.begin())->isAbstract() ||
346 C->getType()->isAbstract()) &&
347 T->getElementType(I-V.begin())->getTypeID() ==
348 C->getType()->getTypeID())) &&
349 "Initializer for struct element doesn't match struct element type!");
354 ConstantStruct::~ConstantStruct() {
355 delete [] OperandList;
359 ConstantVector::ConstantVector(const VectorType *T,
360 const std::vector<Constant*> &V)
361 : Constant(T, ConstantVectorVal, new Use[V.size()], V.size()) {
362 Use *OL = OperandList;
363 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
366 assert((C->getType() == T->getElementType() ||
368 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
369 "Initializer for vector element doesn't match vector element type!");
374 ConstantVector::~ConstantVector() {
375 delete [] OperandList;
378 // We declare several classes private to this file, so use an anonymous
382 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
383 /// behind the scenes to implement unary constant exprs.
384 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
387 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
388 : ConstantExpr(Ty, Opcode, &Op, 1), Op(C, this) {}
391 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
392 /// behind the scenes to implement binary constant exprs.
393 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
396 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
397 : ConstantExpr(C1->getType(), Opcode, Ops, 2) {
398 Ops[0].init(C1, this);
399 Ops[1].init(C2, this);
403 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
404 /// behind the scenes to implement select constant exprs.
405 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
408 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
409 : ConstantExpr(C2->getType(), Instruction::Select, Ops, 3) {
410 Ops[0].init(C1, this);
411 Ops[1].init(C2, this);
412 Ops[2].init(C3, this);
416 /// ExtractElementConstantExpr - This class is private to
417 /// Constants.cpp, and is used behind the scenes to implement
418 /// extractelement constant exprs.
419 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
422 ExtractElementConstantExpr(Constant *C1, Constant *C2)
423 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
424 Instruction::ExtractElement, Ops, 2) {
425 Ops[0].init(C1, this);
426 Ops[1].init(C2, this);
430 /// InsertElementConstantExpr - This class is private to
431 /// Constants.cpp, and is used behind the scenes to implement
432 /// insertelement constant exprs.
433 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
436 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
437 : ConstantExpr(C1->getType(), Instruction::InsertElement,
439 Ops[0].init(C1, this);
440 Ops[1].init(C2, this);
441 Ops[2].init(C3, this);
445 /// ShuffleVectorConstantExpr - This class is private to
446 /// Constants.cpp, and is used behind the scenes to implement
447 /// shufflevector constant exprs.
448 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
451 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
452 : ConstantExpr(C1->getType(), Instruction::ShuffleVector,
454 Ops[0].init(C1, this);
455 Ops[1].init(C2, this);
456 Ops[2].init(C3, this);
460 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
461 /// used behind the scenes to implement getelementpr constant exprs.
462 struct VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
463 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
465 : ConstantExpr(DestTy, Instruction::GetElementPtr,
466 new Use[IdxList.size()+1], IdxList.size()+1) {
467 OperandList[0].init(C, this);
468 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
469 OperandList[i+1].init(IdxList[i], this);
471 ~GetElementPtrConstantExpr() {
472 delete [] OperandList;
476 // CompareConstantExpr - This class is private to Constants.cpp, and is used
477 // behind the scenes to implement ICmp and FCmp constant expressions. This is
478 // needed in order to store the predicate value for these instructions.
479 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
480 unsigned short predicate;
482 CompareConstantExpr(Instruction::OtherOps opc, unsigned short pred,
483 Constant* LHS, Constant* RHS)
484 : ConstantExpr(Type::Int1Ty, opc, Ops, 2), predicate(pred) {
485 OperandList[0].init(LHS, this);
486 OperandList[1].init(RHS, this);
490 } // end anonymous namespace
493 // Utility function for determining if a ConstantExpr is a CastOp or not. This
494 // can't be inline because we don't want to #include Instruction.h into
496 bool ConstantExpr::isCast() const {
497 return Instruction::isCast(getOpcode());
500 bool ConstantExpr::isCompare() const {
501 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
504 /// ConstantExpr::get* - Return some common constants without having to
505 /// specify the full Instruction::OPCODE identifier.
507 Constant *ConstantExpr::getNeg(Constant *C) {
508 return get(Instruction::Sub,
509 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
512 Constant *ConstantExpr::getNot(Constant *C) {
513 assert(isa<ConstantInt>(C) && "Cannot NOT a nonintegral type!");
514 return get(Instruction::Xor, C,
515 ConstantInt::getAllOnesValue(C->getType()));
517 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
518 return get(Instruction::Add, C1, C2);
520 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
521 return get(Instruction::Sub, C1, C2);
523 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
524 return get(Instruction::Mul, C1, C2);
526 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
527 return get(Instruction::UDiv, C1, C2);
529 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
530 return get(Instruction::SDiv, C1, C2);
532 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
533 return get(Instruction::FDiv, C1, C2);
535 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
536 return get(Instruction::URem, C1, C2);
538 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
539 return get(Instruction::SRem, C1, C2);
541 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
542 return get(Instruction::FRem, C1, C2);
544 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
545 return get(Instruction::And, C1, C2);
547 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
548 return get(Instruction::Or, C1, C2);
550 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
551 return get(Instruction::Xor, C1, C2);
553 unsigned ConstantExpr::getPredicate() const {
554 assert(getOpcode() == Instruction::FCmp || getOpcode() == Instruction::ICmp);
555 return dynamic_cast<const CompareConstantExpr*>(this)->predicate;
557 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
558 return get(Instruction::Shl, C1, C2);
560 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
561 return get(Instruction::LShr, C1, C2);
563 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
564 return get(Instruction::AShr, C1, C2);
567 /// getWithOperandReplaced - Return a constant expression identical to this
568 /// one, but with the specified operand set to the specified value.
570 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
571 assert(OpNo < getNumOperands() && "Operand num is out of range!");
572 assert(Op->getType() == getOperand(OpNo)->getType() &&
573 "Replacing operand with value of different type!");
574 if (getOperand(OpNo) == Op)
575 return const_cast<ConstantExpr*>(this);
577 Constant *Op0, *Op1, *Op2;
578 switch (getOpcode()) {
579 case Instruction::Trunc:
580 case Instruction::ZExt:
581 case Instruction::SExt:
582 case Instruction::FPTrunc:
583 case Instruction::FPExt:
584 case Instruction::UIToFP:
585 case Instruction::SIToFP:
586 case Instruction::FPToUI:
587 case Instruction::FPToSI:
588 case Instruction::PtrToInt:
589 case Instruction::IntToPtr:
590 case Instruction::BitCast:
591 return ConstantExpr::getCast(getOpcode(), Op, getType());
592 case Instruction::Select:
593 Op0 = (OpNo == 0) ? Op : getOperand(0);
594 Op1 = (OpNo == 1) ? Op : getOperand(1);
595 Op2 = (OpNo == 2) ? Op : getOperand(2);
596 return ConstantExpr::getSelect(Op0, Op1, Op2);
597 case Instruction::InsertElement:
598 Op0 = (OpNo == 0) ? Op : getOperand(0);
599 Op1 = (OpNo == 1) ? Op : getOperand(1);
600 Op2 = (OpNo == 2) ? Op : getOperand(2);
601 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
602 case Instruction::ExtractElement:
603 Op0 = (OpNo == 0) ? Op : getOperand(0);
604 Op1 = (OpNo == 1) ? Op : getOperand(1);
605 return ConstantExpr::getExtractElement(Op0, Op1);
606 case Instruction::ShuffleVector:
607 Op0 = (OpNo == 0) ? Op : getOperand(0);
608 Op1 = (OpNo == 1) ? Op : getOperand(1);
609 Op2 = (OpNo == 2) ? Op : getOperand(2);
610 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
611 case Instruction::GetElementPtr: {
612 SmallVector<Constant*, 8> Ops;
613 Ops.resize(getNumOperands());
614 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
615 Ops[i] = getOperand(i);
617 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
619 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
622 assert(getNumOperands() == 2 && "Must be binary operator?");
623 Op0 = (OpNo == 0) ? Op : getOperand(0);
624 Op1 = (OpNo == 1) ? Op : getOperand(1);
625 return ConstantExpr::get(getOpcode(), Op0, Op1);
629 /// getWithOperands - This returns the current constant expression with the
630 /// operands replaced with the specified values. The specified operands must
631 /// match count and type with the existing ones.
632 Constant *ConstantExpr::
633 getWithOperands(const std::vector<Constant*> &Ops) const {
634 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
635 bool AnyChange = false;
636 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
637 assert(Ops[i]->getType() == getOperand(i)->getType() &&
638 "Operand type mismatch!");
639 AnyChange |= Ops[i] != getOperand(i);
641 if (!AnyChange) // No operands changed, return self.
642 return const_cast<ConstantExpr*>(this);
644 switch (getOpcode()) {
645 case Instruction::Trunc:
646 case Instruction::ZExt:
647 case Instruction::SExt:
648 case Instruction::FPTrunc:
649 case Instruction::FPExt:
650 case Instruction::UIToFP:
651 case Instruction::SIToFP:
652 case Instruction::FPToUI:
653 case Instruction::FPToSI:
654 case Instruction::PtrToInt:
655 case Instruction::IntToPtr:
656 case Instruction::BitCast:
657 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
658 case Instruction::Select:
659 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
660 case Instruction::InsertElement:
661 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
662 case Instruction::ExtractElement:
663 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
664 case Instruction::ShuffleVector:
665 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
666 case Instruction::GetElementPtr:
667 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], Ops.size()-1);
668 case Instruction::ICmp:
669 case Instruction::FCmp:
670 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
672 assert(getNumOperands() == 2 && "Must be binary operator?");
673 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
678 //===----------------------------------------------------------------------===//
679 // isValueValidForType implementations
681 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
682 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
683 if (Ty == Type::Int1Ty)
684 return Val == 0 || Val == 1;
686 return true; // always true, has to fit in largest type
687 uint64_t Max = (1ll << NumBits) - 1;
691 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
692 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
693 if (Ty == Type::Int1Ty)
694 return Val == 0 || Val == 1 || Val == -1;
696 return true; // always true, has to fit in largest type
697 int64_t Min = -(1ll << (NumBits-1));
698 int64_t Max = (1ll << (NumBits-1)) - 1;
699 return (Val >= Min && Val <= Max);
702 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
703 switch (Ty->getTypeID()) {
705 return false; // These can't be represented as floating point!
707 // TODO: Figure out how to test if we can use a shorter type instead!
708 case Type::FloatTyID:
709 case Type::DoubleTyID:
710 case Type::X86_FP80TyID:
711 case Type::PPC_FP128TyID:
712 case Type::FP128TyID:
717 //===----------------------------------------------------------------------===//
718 // Factory Function Implementation
720 // ConstantCreator - A class that is used to create constants by
721 // ValueMap*. This class should be partially specialized if there is
722 // something strange that needs to be done to interface to the ctor for the
726 template<class ConstantClass, class TypeClass, class ValType>
727 struct VISIBILITY_HIDDEN ConstantCreator {
728 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
729 return new ConstantClass(Ty, V);
733 template<class ConstantClass, class TypeClass>
734 struct VISIBILITY_HIDDEN ConvertConstantType {
735 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
736 assert(0 && "This type cannot be converted!\n");
741 template<class ValType, class TypeClass, class ConstantClass,
742 bool HasLargeKey = false /*true for arrays and structs*/ >
743 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
745 typedef std::pair<const Type*, ValType> MapKey;
746 typedef std::map<MapKey, Constant *> MapTy;
747 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
748 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
750 /// Map - This is the main map from the element descriptor to the Constants.
751 /// This is the primary way we avoid creating two of the same shape
755 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
756 /// from the constants to their element in Map. This is important for
757 /// removal of constants from the array, which would otherwise have to scan
758 /// through the map with very large keys.
759 InverseMapTy InverseMap;
761 /// AbstractTypeMap - Map for abstract type constants.
763 AbstractTypeMapTy AbstractTypeMap;
766 typename MapTy::iterator map_end() { return Map.end(); }
768 /// InsertOrGetItem - Return an iterator for the specified element.
769 /// If the element exists in the map, the returned iterator points to the
770 /// entry and Exists=true. If not, the iterator points to the newly
771 /// inserted entry and returns Exists=false. Newly inserted entries have
772 /// I->second == 0, and should be filled in.
773 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
776 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
782 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
784 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
785 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
786 IMI->second->second == CP &&
787 "InverseMap corrupt!");
791 typename MapTy::iterator I =
792 Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
793 if (I == Map.end() || I->second != CP) {
794 // FIXME: This should not use a linear scan. If this gets to be a
795 // performance problem, someone should look at this.
796 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
803 /// getOrCreate - Return the specified constant from the map, creating it if
805 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
806 MapKey Lookup(Ty, V);
807 typename MapTy::iterator I = Map.lower_bound(Lookup);
809 if (I != Map.end() && I->first == Lookup)
810 return static_cast<ConstantClass *>(I->second);
812 // If no preexisting value, create one now...
813 ConstantClass *Result =
814 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
816 /// FIXME: why does this assert fail when loading 176.gcc?
817 //assert(Result->getType() == Ty && "Type specified is not correct!");
818 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
820 if (HasLargeKey) // Remember the reverse mapping if needed.
821 InverseMap.insert(std::make_pair(Result, I));
823 // If the type of the constant is abstract, make sure that an entry exists
824 // for it in the AbstractTypeMap.
825 if (Ty->isAbstract()) {
826 typename AbstractTypeMapTy::iterator TI =
827 AbstractTypeMap.lower_bound(Ty);
829 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
830 // Add ourselves to the ATU list of the type.
831 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
833 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
839 void remove(ConstantClass *CP) {
840 typename MapTy::iterator I = FindExistingElement(CP);
841 assert(I != Map.end() && "Constant not found in constant table!");
842 assert(I->second == CP && "Didn't find correct element?");
844 if (HasLargeKey) // Remember the reverse mapping if needed.
845 InverseMap.erase(CP);
847 // Now that we found the entry, make sure this isn't the entry that
848 // the AbstractTypeMap points to.
849 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
850 if (Ty->isAbstract()) {
851 assert(AbstractTypeMap.count(Ty) &&
852 "Abstract type not in AbstractTypeMap?");
853 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
854 if (ATMEntryIt == I) {
855 // Yes, we are removing the representative entry for this type.
856 // See if there are any other entries of the same type.
857 typename MapTy::iterator TmpIt = ATMEntryIt;
859 // First check the entry before this one...
860 if (TmpIt != Map.begin()) {
862 if (TmpIt->first.first != Ty) // Not the same type, move back...
866 // If we didn't find the same type, try to move forward...
867 if (TmpIt == ATMEntryIt) {
869 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
870 --TmpIt; // No entry afterwards with the same type
873 // If there is another entry in the map of the same abstract type,
874 // update the AbstractTypeMap entry now.
875 if (TmpIt != ATMEntryIt) {
878 // Otherwise, we are removing the last instance of this type
879 // from the table. Remove from the ATM, and from user list.
880 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
881 AbstractTypeMap.erase(Ty);
890 /// MoveConstantToNewSlot - If we are about to change C to be the element
891 /// specified by I, update our internal data structures to reflect this
893 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
894 // First, remove the old location of the specified constant in the map.
895 typename MapTy::iterator OldI = FindExistingElement(C);
896 assert(OldI != Map.end() && "Constant not found in constant table!");
897 assert(OldI->second == C && "Didn't find correct element?");
899 // If this constant is the representative element for its abstract type,
900 // update the AbstractTypeMap so that the representative element is I.
901 if (C->getType()->isAbstract()) {
902 typename AbstractTypeMapTy::iterator ATI =
903 AbstractTypeMap.find(C->getType());
904 assert(ATI != AbstractTypeMap.end() &&
905 "Abstract type not in AbstractTypeMap?");
906 if (ATI->second == OldI)
910 // Remove the old entry from the map.
913 // Update the inverse map so that we know that this constant is now
914 // located at descriptor I.
916 assert(I->second == C && "Bad inversemap entry!");
921 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
922 typename AbstractTypeMapTy::iterator I =
923 AbstractTypeMap.find(cast<Type>(OldTy));
925 assert(I != AbstractTypeMap.end() &&
926 "Abstract type not in AbstractTypeMap?");
928 // Convert a constant at a time until the last one is gone. The last one
929 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
930 // eliminated eventually.
932 ConvertConstantType<ConstantClass,
934 static_cast<ConstantClass *>(I->second->second),
935 cast<TypeClass>(NewTy));
937 I = AbstractTypeMap.find(cast<Type>(OldTy));
938 } while (I != AbstractTypeMap.end());
941 // If the type became concrete without being refined to any other existing
942 // type, we just remove ourselves from the ATU list.
943 void typeBecameConcrete(const DerivedType *AbsTy) {
944 AbsTy->removeAbstractTypeUser(this);
948 DOUT << "Constant.cpp: ValueMap\n";
955 //---- ConstantAggregateZero::get() implementation...
958 // ConstantAggregateZero does not take extra "value" argument...
959 template<class ValType>
960 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
961 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
962 return new ConstantAggregateZero(Ty);
967 struct ConvertConstantType<ConstantAggregateZero, Type> {
968 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
969 // Make everyone now use a constant of the new type...
970 Constant *New = ConstantAggregateZero::get(NewTy);
971 assert(New != OldC && "Didn't replace constant??");
972 OldC->uncheckedReplaceAllUsesWith(New);
973 OldC->destroyConstant(); // This constant is now dead, destroy it.
978 static ManagedStatic<ValueMap<char, Type,
979 ConstantAggregateZero> > AggZeroConstants;
981 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
983 Constant *ConstantAggregateZero::get(const Type *Ty) {
984 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
985 "Cannot create an aggregate zero of non-aggregate type!");
986 return AggZeroConstants->getOrCreate(Ty, 0);
989 // destroyConstant - Remove the constant from the constant table...
991 void ConstantAggregateZero::destroyConstant() {
992 AggZeroConstants->remove(this);
993 destroyConstantImpl();
996 //---- ConstantArray::get() implementation...
1000 struct ConvertConstantType<ConstantArray, ArrayType> {
1001 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1002 // Make everyone now use a constant of the new type...
1003 std::vector<Constant*> C;
1004 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1005 C.push_back(cast<Constant>(OldC->getOperand(i)));
1006 Constant *New = ConstantArray::get(NewTy, C);
1007 assert(New != OldC && "Didn't replace constant??");
1008 OldC->uncheckedReplaceAllUsesWith(New);
1009 OldC->destroyConstant(); // This constant is now dead, destroy it.
1014 static std::vector<Constant*> getValType(ConstantArray *CA) {
1015 std::vector<Constant*> Elements;
1016 Elements.reserve(CA->getNumOperands());
1017 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1018 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1022 typedef ValueMap<std::vector<Constant*>, ArrayType,
1023 ConstantArray, true /*largekey*/> ArrayConstantsTy;
1024 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
1026 Constant *ConstantArray::get(const ArrayType *Ty,
1027 const std::vector<Constant*> &V) {
1028 // If this is an all-zero array, return a ConstantAggregateZero object
1031 if (!C->isNullValue())
1032 return ArrayConstants->getOrCreate(Ty, V);
1033 for (unsigned i = 1, e = V.size(); i != e; ++i)
1035 return ArrayConstants->getOrCreate(Ty, V);
1037 return ConstantAggregateZero::get(Ty);
1040 // destroyConstant - Remove the constant from the constant table...
1042 void ConstantArray::destroyConstant() {
1043 ArrayConstants->remove(this);
1044 destroyConstantImpl();
1047 /// ConstantArray::get(const string&) - Return an array that is initialized to
1048 /// contain the specified string. If length is zero then a null terminator is
1049 /// added to the specified string so that it may be used in a natural way.
1050 /// Otherwise, the length parameter specifies how much of the string to use
1051 /// and it won't be null terminated.
1053 Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
1054 std::vector<Constant*> ElementVals;
1055 for (unsigned i = 0; i < Str.length(); ++i)
1056 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
1058 // Add a null terminator to the string...
1060 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
1063 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
1064 return ConstantArray::get(ATy, ElementVals);
1067 /// isString - This method returns true if the array is an array of i8, and
1068 /// if the elements of the array are all ConstantInt's.
1069 bool ConstantArray::isString() const {
1070 // Check the element type for i8...
1071 if (getType()->getElementType() != Type::Int8Ty)
1073 // Check the elements to make sure they are all integers, not constant
1075 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1076 if (!isa<ConstantInt>(getOperand(i)))
1081 /// isCString - This method returns true if the array is a string (see
1082 /// isString) and it ends in a null byte \0 and does not contains any other
1083 /// null bytes except its terminator.
1084 bool ConstantArray::isCString() const {
1085 // Check the element type for i8...
1086 if (getType()->getElementType() != Type::Int8Ty)
1088 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1089 // Last element must be a null.
1090 if (getOperand(getNumOperands()-1) != Zero)
1092 // Other elements must be non-null integers.
1093 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1094 if (!isa<ConstantInt>(getOperand(i)))
1096 if (getOperand(i) == Zero)
1103 // getAsString - If the sub-element type of this array is i8
1104 // then this method converts the array to an std::string and returns it.
1105 // Otherwise, it asserts out.
1107 std::string ConstantArray::getAsString() const {
1108 assert(isString() && "Not a string!");
1110 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1111 Result += (char)cast<ConstantInt>(getOperand(i))->getZExtValue();
1116 //---- ConstantStruct::get() implementation...
1121 struct ConvertConstantType<ConstantStruct, StructType> {
1122 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1123 // Make everyone now use a constant of the new type...
1124 std::vector<Constant*> C;
1125 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1126 C.push_back(cast<Constant>(OldC->getOperand(i)));
1127 Constant *New = ConstantStruct::get(NewTy, C);
1128 assert(New != OldC && "Didn't replace constant??");
1130 OldC->uncheckedReplaceAllUsesWith(New);
1131 OldC->destroyConstant(); // This constant is now dead, destroy it.
1136 typedef ValueMap<std::vector<Constant*>, StructType,
1137 ConstantStruct, true /*largekey*/> StructConstantsTy;
1138 static ManagedStatic<StructConstantsTy> StructConstants;
1140 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1141 std::vector<Constant*> Elements;
1142 Elements.reserve(CS->getNumOperands());
1143 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1144 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1148 Constant *ConstantStruct::get(const StructType *Ty,
1149 const std::vector<Constant*> &V) {
1150 // Create a ConstantAggregateZero value if all elements are zeros...
1151 for (unsigned i = 0, e = V.size(); i != e; ++i)
1152 if (!V[i]->isNullValue())
1153 return StructConstants->getOrCreate(Ty, V);
1155 return ConstantAggregateZero::get(Ty);
1158 Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
1159 std::vector<const Type*> StructEls;
1160 StructEls.reserve(V.size());
1161 for (unsigned i = 0, e = V.size(); i != e; ++i)
1162 StructEls.push_back(V[i]->getType());
1163 return get(StructType::get(StructEls, packed), V);
1166 // destroyConstant - Remove the constant from the constant table...
1168 void ConstantStruct::destroyConstant() {
1169 StructConstants->remove(this);
1170 destroyConstantImpl();
1173 //---- ConstantVector::get() implementation...
1177 struct ConvertConstantType<ConstantVector, VectorType> {
1178 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
1179 // Make everyone now use a constant of the new type...
1180 std::vector<Constant*> C;
1181 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1182 C.push_back(cast<Constant>(OldC->getOperand(i)));
1183 Constant *New = ConstantVector::get(NewTy, C);
1184 assert(New != OldC && "Didn't replace constant??");
1185 OldC->uncheckedReplaceAllUsesWith(New);
1186 OldC->destroyConstant(); // This constant is now dead, destroy it.
1191 static std::vector<Constant*> getValType(ConstantVector *CP) {
1192 std::vector<Constant*> Elements;
1193 Elements.reserve(CP->getNumOperands());
1194 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1195 Elements.push_back(CP->getOperand(i));
1199 static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
1200 ConstantVector> > VectorConstants;
1202 Constant *ConstantVector::get(const VectorType *Ty,
1203 const std::vector<Constant*> &V) {
1204 // If this is an all-zero vector, return a ConstantAggregateZero object
1207 if (!C->isNullValue())
1208 return VectorConstants->getOrCreate(Ty, V);
1209 for (unsigned i = 1, e = V.size(); i != e; ++i)
1211 return VectorConstants->getOrCreate(Ty, V);
1213 return ConstantAggregateZero::get(Ty);
1216 Constant *ConstantVector::get(const std::vector<Constant*> &V) {
1217 assert(!V.empty() && "Cannot infer type if V is empty");
1218 return get(VectorType::get(V.front()->getType(),V.size()), V);
1221 // destroyConstant - Remove the constant from the constant table...
1223 void ConstantVector::destroyConstant() {
1224 VectorConstants->remove(this);
1225 destroyConstantImpl();
1228 /// This function will return true iff every element in this vector constant
1229 /// is set to all ones.
1230 /// @returns true iff this constant's emements are all set to all ones.
1231 /// @brief Determine if the value is all ones.
1232 bool ConstantVector::isAllOnesValue() const {
1233 // Check out first element.
1234 const Constant *Elt = getOperand(0);
1235 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1236 if (!CI || !CI->isAllOnesValue()) return false;
1237 // Then make sure all remaining elements point to the same value.
1238 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1239 if (getOperand(I) != Elt) return false;
1244 //---- ConstantPointerNull::get() implementation...
1248 // ConstantPointerNull does not take extra "value" argument...
1249 template<class ValType>
1250 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1251 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1252 return new ConstantPointerNull(Ty);
1257 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1258 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1259 // Make everyone now use a constant of the new type...
1260 Constant *New = ConstantPointerNull::get(NewTy);
1261 assert(New != OldC && "Didn't replace constant??");
1262 OldC->uncheckedReplaceAllUsesWith(New);
1263 OldC->destroyConstant(); // This constant is now dead, destroy it.
1268 static ManagedStatic<ValueMap<char, PointerType,
1269 ConstantPointerNull> > NullPtrConstants;
1271 static char getValType(ConstantPointerNull *) {
1276 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1277 return NullPtrConstants->getOrCreate(Ty, 0);
1280 // destroyConstant - Remove the constant from the constant table...
1282 void ConstantPointerNull::destroyConstant() {
1283 NullPtrConstants->remove(this);
1284 destroyConstantImpl();
1288 //---- UndefValue::get() implementation...
1292 // UndefValue does not take extra "value" argument...
1293 template<class ValType>
1294 struct ConstantCreator<UndefValue, Type, ValType> {
1295 static UndefValue *create(const Type *Ty, const ValType &V) {
1296 return new UndefValue(Ty);
1301 struct ConvertConstantType<UndefValue, Type> {
1302 static void convert(UndefValue *OldC, const Type *NewTy) {
1303 // Make everyone now use a constant of the new type.
1304 Constant *New = UndefValue::get(NewTy);
1305 assert(New != OldC && "Didn't replace constant??");
1306 OldC->uncheckedReplaceAllUsesWith(New);
1307 OldC->destroyConstant(); // This constant is now dead, destroy it.
1312 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1314 static char getValType(UndefValue *) {
1319 UndefValue *UndefValue::get(const Type *Ty) {
1320 return UndefValueConstants->getOrCreate(Ty, 0);
1323 // destroyConstant - Remove the constant from the constant table.
1325 void UndefValue::destroyConstant() {
1326 UndefValueConstants->remove(this);
1327 destroyConstantImpl();
1331 //---- ConstantExpr::get() implementations...
1334 struct ExprMapKeyType {
1335 explicit ExprMapKeyType(unsigned opc, std::vector<Constant*> ops,
1336 unsigned short pred = 0) : opcode(opc), predicate(pred), operands(ops) { }
1339 std::vector<Constant*> operands;
1340 bool operator==(const ExprMapKeyType& that) const {
1341 return this->opcode == that.opcode &&
1342 this->predicate == that.predicate &&
1343 this->operands == that.operands;
1345 bool operator<(const ExprMapKeyType & that) const {
1346 return this->opcode < that.opcode ||
1347 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1348 (this->opcode == that.opcode && this->predicate == that.predicate &&
1349 this->operands < that.operands);
1352 bool operator!=(const ExprMapKeyType& that) const {
1353 return !(*this == that);
1359 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1360 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1361 unsigned short pred = 0) {
1362 if (Instruction::isCast(V.opcode))
1363 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1364 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1365 V.opcode < Instruction::BinaryOpsEnd))
1366 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1367 if (V.opcode == Instruction::Select)
1368 return new SelectConstantExpr(V.operands[0], V.operands[1],
1370 if (V.opcode == Instruction::ExtractElement)
1371 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1372 if (V.opcode == Instruction::InsertElement)
1373 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1375 if (V.opcode == Instruction::ShuffleVector)
1376 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1378 if (V.opcode == Instruction::GetElementPtr) {
1379 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1380 return new GetElementPtrConstantExpr(V.operands[0], IdxList, Ty);
1383 // The compare instructions are weird. We have to encode the predicate
1384 // value and it is combined with the instruction opcode by multiplying
1385 // the opcode by one hundred. We must decode this to get the predicate.
1386 if (V.opcode == Instruction::ICmp)
1387 return new CompareConstantExpr(Instruction::ICmp, V.predicate,
1388 V.operands[0], V.operands[1]);
1389 if (V.opcode == Instruction::FCmp)
1390 return new CompareConstantExpr(Instruction::FCmp, V.predicate,
1391 V.operands[0], V.operands[1]);
1392 assert(0 && "Invalid ConstantExpr!");
1398 struct ConvertConstantType<ConstantExpr, Type> {
1399 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1401 switch (OldC->getOpcode()) {
1402 case Instruction::Trunc:
1403 case Instruction::ZExt:
1404 case Instruction::SExt:
1405 case Instruction::FPTrunc:
1406 case Instruction::FPExt:
1407 case Instruction::UIToFP:
1408 case Instruction::SIToFP:
1409 case Instruction::FPToUI:
1410 case Instruction::FPToSI:
1411 case Instruction::PtrToInt:
1412 case Instruction::IntToPtr:
1413 case Instruction::BitCast:
1414 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1417 case Instruction::Select:
1418 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1419 OldC->getOperand(1),
1420 OldC->getOperand(2));
1423 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1424 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1425 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1426 OldC->getOperand(1));
1428 case Instruction::GetElementPtr:
1429 // Make everyone now use a constant of the new type...
1430 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1431 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1432 &Idx[0], Idx.size());
1436 assert(New != OldC && "Didn't replace constant??");
1437 OldC->uncheckedReplaceAllUsesWith(New);
1438 OldC->destroyConstant(); // This constant is now dead, destroy it.
1441 } // end namespace llvm
1444 static ExprMapKeyType getValType(ConstantExpr *CE) {
1445 std::vector<Constant*> Operands;
1446 Operands.reserve(CE->getNumOperands());
1447 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1448 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1449 return ExprMapKeyType(CE->getOpcode(), Operands,
1450 CE->isCompare() ? CE->getPredicate() : 0);
1453 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1454 ConstantExpr> > ExprConstants;
1456 /// This is a utility function to handle folding of casts and lookup of the
1457 /// cast in the ExprConstants map. It is usedby the various get* methods below.
1458 static inline Constant *getFoldedCast(
1459 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1460 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1461 // Fold a few common cases
1462 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1465 // Look up the constant in the table first to ensure uniqueness
1466 std::vector<Constant*> argVec(1, C);
1467 ExprMapKeyType Key(opc, argVec);
1468 return ExprConstants->getOrCreate(Ty, Key);
1471 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1472 Instruction::CastOps opc = Instruction::CastOps(oc);
1473 assert(Instruction::isCast(opc) && "opcode out of range");
1474 assert(C && Ty && "Null arguments to getCast");
1475 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1479 assert(0 && "Invalid cast opcode");
1481 case Instruction::Trunc: return getTrunc(C, Ty);
1482 case Instruction::ZExt: return getZExt(C, Ty);
1483 case Instruction::SExt: return getSExt(C, Ty);
1484 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1485 case Instruction::FPExt: return getFPExtend(C, Ty);
1486 case Instruction::UIToFP: return getUIToFP(C, Ty);
1487 case Instruction::SIToFP: return getSIToFP(C, Ty);
1488 case Instruction::FPToUI: return getFPToUI(C, Ty);
1489 case Instruction::FPToSI: return getFPToSI(C, Ty);
1490 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1491 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1492 case Instruction::BitCast: return getBitCast(C, Ty);
1497 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1498 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1499 return getCast(Instruction::BitCast, C, Ty);
1500 return getCast(Instruction::ZExt, C, Ty);
1503 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1504 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1505 return getCast(Instruction::BitCast, C, Ty);
1506 return getCast(Instruction::SExt, C, Ty);
1509 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1510 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1511 return getCast(Instruction::BitCast, C, Ty);
1512 return getCast(Instruction::Trunc, C, Ty);
1515 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1516 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1517 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1519 if (Ty->isInteger())
1520 return getCast(Instruction::PtrToInt, S, Ty);
1521 return getCast(Instruction::BitCast, S, Ty);
1524 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1526 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1527 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1528 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1529 Instruction::CastOps opcode =
1530 (SrcBits == DstBits ? Instruction::BitCast :
1531 (SrcBits > DstBits ? Instruction::Trunc :
1532 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1533 return getCast(opcode, C, Ty);
1536 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1537 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1539 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1540 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1541 if (SrcBits == DstBits)
1542 return C; // Avoid a useless cast
1543 Instruction::CastOps opcode =
1544 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1545 return getCast(opcode, C, Ty);
1548 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1549 assert(C->getType()->isInteger() && "Trunc operand must be integer");
1550 assert(Ty->isInteger() && "Trunc produces only integral");
1551 assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1552 "SrcTy must be larger than DestTy for Trunc!");
1554 return getFoldedCast(Instruction::Trunc, C, Ty);
1557 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1558 assert(C->getType()->isInteger() && "SEXt operand must be integral");
1559 assert(Ty->isInteger() && "SExt produces only integer");
1560 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1561 "SrcTy must be smaller than DestTy for SExt!");
1563 return getFoldedCast(Instruction::SExt, C, Ty);
1566 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1567 assert(C->getType()->isInteger() && "ZEXt operand must be integral");
1568 assert(Ty->isInteger() && "ZExt produces only integer");
1569 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1570 "SrcTy must be smaller than DestTy for ZExt!");
1572 return getFoldedCast(Instruction::ZExt, C, Ty);
1575 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1576 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1577 C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1578 "This is an illegal floating point truncation!");
1579 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1582 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1583 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1584 C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1585 "This is an illegal floating point extension!");
1586 return getFoldedCast(Instruction::FPExt, C, Ty);
1589 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1590 assert(C->getType()->isInteger() && Ty->isFloatingPoint() &&
1591 "This is an illegal i32 to floating point cast!");
1592 return getFoldedCast(Instruction::UIToFP, C, Ty);
1595 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1596 assert(C->getType()->isInteger() && Ty->isFloatingPoint() &&
1597 "This is an illegal sint to floating point cast!");
1598 return getFoldedCast(Instruction::SIToFP, C, Ty);
1601 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1602 assert(C->getType()->isFloatingPoint() && Ty->isInteger() &&
1603 "This is an illegal floating point to i32 cast!");
1604 return getFoldedCast(Instruction::FPToUI, C, Ty);
1607 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1608 assert(C->getType()->isFloatingPoint() && Ty->isInteger() &&
1609 "This is an illegal floating point to i32 cast!");
1610 return getFoldedCast(Instruction::FPToSI, C, Ty);
1613 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1614 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1615 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1616 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1619 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1620 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1621 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1622 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1625 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1626 // BitCast implies a no-op cast of type only. No bits change. However, you
1627 // can't cast pointers to anything but pointers.
1628 const Type *SrcTy = C->getType();
1629 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1630 "BitCast cannot cast pointer to non-pointer and vice versa");
1632 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1633 // or nonptr->ptr). For all the other types, the cast is okay if source and
1634 // destination bit widths are identical.
1635 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1636 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1637 assert(SrcBitSize == DstBitSize && "BitCast requies types of same width");
1638 return getFoldedCast(Instruction::BitCast, C, DstTy);
1641 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
1642 // sizeof is implemented as: (ulong) gep (Ty*)null, 1
1643 Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
1645 getGetElementPtr(getNullValue(PointerType::get(Ty)), &GEPIdx, 1);
1646 return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
1649 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1650 Constant *C1, Constant *C2) {
1651 // Check the operands for consistency first
1652 assert(Opcode >= Instruction::BinaryOpsBegin &&
1653 Opcode < Instruction::BinaryOpsEnd &&
1654 "Invalid opcode in binary constant expression");
1655 assert(C1->getType() == C2->getType() &&
1656 "Operand types in binary constant expression should match");
1658 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
1659 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1660 return FC; // Fold a few common cases...
1662 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1663 ExprMapKeyType Key(Opcode, argVec);
1664 return ExprConstants->getOrCreate(ReqTy, Key);
1667 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1668 Constant *C1, Constant *C2) {
1669 switch (predicate) {
1670 default: assert(0 && "Invalid CmpInst predicate");
1671 case FCmpInst::FCMP_FALSE: case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_OGT:
1672 case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OLE:
1673 case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_ORD: case FCmpInst::FCMP_UNO:
1674 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UGT: case FCmpInst::FCMP_UGE:
1675 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_ULE: case FCmpInst::FCMP_UNE:
1676 case FCmpInst::FCMP_TRUE:
1677 return getFCmp(predicate, C1, C2);
1678 case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGT:
1679 case ICmpInst::ICMP_UGE: case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE:
1680 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_SGE: case ICmpInst::ICMP_SLT:
1681 case ICmpInst::ICMP_SLE:
1682 return getICmp(predicate, C1, C2);
1686 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1689 case Instruction::Add:
1690 case Instruction::Sub:
1691 case Instruction::Mul:
1692 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1693 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
1694 isa<VectorType>(C1->getType())) &&
1695 "Tried to create an arithmetic operation on a non-arithmetic type!");
1697 case Instruction::UDiv:
1698 case Instruction::SDiv:
1699 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1700 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1701 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
1702 "Tried to create an arithmetic operation on a non-arithmetic type!");
1704 case Instruction::FDiv:
1705 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1706 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1707 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
1708 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1710 case Instruction::URem:
1711 case Instruction::SRem:
1712 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1713 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1714 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
1715 "Tried to create an arithmetic operation on a non-arithmetic type!");
1717 case Instruction::FRem:
1718 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1719 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1720 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
1721 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1723 case Instruction::And:
1724 case Instruction::Or:
1725 case Instruction::Xor:
1726 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1727 assert((C1->getType()->isInteger() || isa<VectorType>(C1->getType())) &&
1728 "Tried to create a logical operation on a non-integral type!");
1730 case Instruction::Shl:
1731 case Instruction::LShr:
1732 case Instruction::AShr:
1733 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1734 assert(C1->getType()->isInteger() &&
1735 "Tried to create a shift operation on a non-integer type!");
1742 return getTy(C1->getType(), Opcode, C1, C2);
1745 Constant *ConstantExpr::getCompare(unsigned short pred,
1746 Constant *C1, Constant *C2) {
1747 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1748 return getCompareTy(pred, C1, C2);
1751 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1752 Constant *V1, Constant *V2) {
1753 assert(C->getType() == Type::Int1Ty && "Select condition must be i1!");
1754 assert(V1->getType() == V2->getType() && "Select value types must match!");
1755 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1757 if (ReqTy == V1->getType())
1758 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1759 return SC; // Fold common cases
1761 std::vector<Constant*> argVec(3, C);
1764 ExprMapKeyType Key(Instruction::Select, argVec);
1765 return ExprConstants->getOrCreate(ReqTy, Key);
1768 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1771 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs, NumIdx, true) &&
1772 "GEP indices invalid!");
1774 if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs, NumIdx))
1775 return FC; // Fold a few common cases...
1777 assert(isa<PointerType>(C->getType()) &&
1778 "Non-pointer type for constant GetElementPtr expression");
1779 // Look up the constant in the table first to ensure uniqueness
1780 std::vector<Constant*> ArgVec;
1781 ArgVec.reserve(NumIdx+1);
1782 ArgVec.push_back(C);
1783 for (unsigned i = 0; i != NumIdx; ++i)
1784 ArgVec.push_back(cast<Constant>(Idxs[i]));
1785 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
1786 return ExprConstants->getOrCreate(ReqTy, Key);
1789 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1791 // Get the result type of the getelementptr!
1793 GetElementPtrInst::getIndexedType(C->getType(), Idxs, NumIdx, true);
1794 assert(Ty && "GEP indices invalid!");
1795 return getGetElementPtrTy(PointerType::get(Ty), C, Idxs, NumIdx);
1798 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1800 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1805 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1806 assert(LHS->getType() == RHS->getType());
1807 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1808 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1810 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1811 return FC; // Fold a few common cases...
1813 // Look up the constant in the table first to ensure uniqueness
1814 std::vector<Constant*> ArgVec;
1815 ArgVec.push_back(LHS);
1816 ArgVec.push_back(RHS);
1817 // Get the key type with both the opcode and predicate
1818 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1819 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1823 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1824 assert(LHS->getType() == RHS->getType());
1825 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1827 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1828 return FC; // Fold a few common cases...
1830 // Look up the constant in the table first to ensure uniqueness
1831 std::vector<Constant*> ArgVec;
1832 ArgVec.push_back(LHS);
1833 ArgVec.push_back(RHS);
1834 // Get the key type with both the opcode and predicate
1835 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1836 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1839 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1841 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1842 return FC; // Fold a few common cases...
1843 // Look up the constant in the table first to ensure uniqueness
1844 std::vector<Constant*> ArgVec(1, Val);
1845 ArgVec.push_back(Idx);
1846 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1847 return ExprConstants->getOrCreate(ReqTy, Key);
1850 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1851 assert(isa<VectorType>(Val->getType()) &&
1852 "Tried to create extractelement operation on non-vector type!");
1853 assert(Idx->getType() == Type::Int32Ty &&
1854 "Extractelement index must be i32 type!");
1855 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
1859 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1860 Constant *Elt, Constant *Idx) {
1861 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1862 return FC; // Fold a few common cases...
1863 // Look up the constant in the table first to ensure uniqueness
1864 std::vector<Constant*> ArgVec(1, Val);
1865 ArgVec.push_back(Elt);
1866 ArgVec.push_back(Idx);
1867 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1868 return ExprConstants->getOrCreate(ReqTy, Key);
1871 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1873 assert(isa<VectorType>(Val->getType()) &&
1874 "Tried to create insertelement operation on non-vector type!");
1875 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
1876 && "Insertelement types must match!");
1877 assert(Idx->getType() == Type::Int32Ty &&
1878 "Insertelement index must be i32 type!");
1879 return getInsertElementTy(cast<VectorType>(Val->getType())->getElementType(),
1883 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1884 Constant *V2, Constant *Mask) {
1885 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1886 return FC; // Fold a few common cases...
1887 // Look up the constant in the table first to ensure uniqueness
1888 std::vector<Constant*> ArgVec(1, V1);
1889 ArgVec.push_back(V2);
1890 ArgVec.push_back(Mask);
1891 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1892 return ExprConstants->getOrCreate(ReqTy, Key);
1895 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1897 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1898 "Invalid shuffle vector constant expr operands!");
1899 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
1902 Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
1903 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
1904 if (PTy->getElementType()->isFloatingPoint()) {
1905 std::vector<Constant*> zeros(PTy->getNumElements(),
1906 ConstantFP::get(PTy->getElementType(),-0.0));
1907 return ConstantVector::get(PTy, zeros);
1910 if (Ty->isFloatingPoint())
1911 return ConstantFP::get(Ty, -0.0);
1913 return Constant::getNullValue(Ty);
1916 // destroyConstant - Remove the constant from the constant table...
1918 void ConstantExpr::destroyConstant() {
1919 ExprConstants->remove(this);
1920 destroyConstantImpl();
1923 const char *ConstantExpr::getOpcodeName() const {
1924 return Instruction::getOpcodeName(getOpcode());
1927 //===----------------------------------------------------------------------===//
1928 // replaceUsesOfWithOnConstant implementations
1930 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
1931 /// 'From' to be uses of 'To'. This must update the uniquing data structures
1934 /// Note that we intentionally replace all uses of From with To here. Consider
1935 /// a large array that uses 'From' 1000 times. By handling this case all here,
1936 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
1937 /// single invocation handles all 1000 uses. Handling them one at a time would
1938 /// work, but would be really slow because it would have to unique each updated
1940 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1942 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1943 Constant *ToC = cast<Constant>(To);
1945 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
1946 Lookup.first.first = getType();
1947 Lookup.second = this;
1949 std::vector<Constant*> &Values = Lookup.first.second;
1950 Values.reserve(getNumOperands()); // Build replacement array.
1952 // Fill values with the modified operands of the constant array. Also,
1953 // compute whether this turns into an all-zeros array.
1954 bool isAllZeros = false;
1955 unsigned NumUpdated = 0;
1956 if (!ToC->isNullValue()) {
1957 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1958 Constant *Val = cast<Constant>(O->get());
1963 Values.push_back(Val);
1967 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1968 Constant *Val = cast<Constant>(O->get());
1973 Values.push_back(Val);
1974 if (isAllZeros) isAllZeros = Val->isNullValue();
1978 Constant *Replacement = 0;
1980 Replacement = ConstantAggregateZero::get(getType());
1982 // Check to see if we have this array type already.
1984 ArrayConstantsTy::MapTy::iterator I =
1985 ArrayConstants->InsertOrGetItem(Lookup, Exists);
1988 Replacement = I->second;
1990 // Okay, the new shape doesn't exist in the system yet. Instead of
1991 // creating a new constant array, inserting it, replaceallusesof'ing the
1992 // old with the new, then deleting the old... just update the current one
1994 ArrayConstants->MoveConstantToNewSlot(this, I);
1996 // Update to the new value. Optimize for the case when we have a single
1997 // operand that we're changing, but handle bulk updates efficiently.
1998 if (NumUpdated == 1) {
1999 unsigned OperandToUpdate = U-OperandList;
2000 assert(getOperand(OperandToUpdate) == From &&
2001 "ReplaceAllUsesWith broken!");
2002 setOperand(OperandToUpdate, ToC);
2004 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2005 if (getOperand(i) == From)
2012 // Otherwise, I do need to replace this with an existing value.
2013 assert(Replacement != this && "I didn't contain From!");
2015 // Everyone using this now uses the replacement.
2016 uncheckedReplaceAllUsesWith(Replacement);
2018 // Delete the old constant!
2022 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2024 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2025 Constant *ToC = cast<Constant>(To);
2027 unsigned OperandToUpdate = U-OperandList;
2028 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2030 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
2031 Lookup.first.first = getType();
2032 Lookup.second = this;
2033 std::vector<Constant*> &Values = Lookup.first.second;
2034 Values.reserve(getNumOperands()); // Build replacement struct.
2037 // Fill values with the modified operands of the constant struct. Also,
2038 // compute whether this turns into an all-zeros struct.
2039 bool isAllZeros = false;
2040 if (!ToC->isNullValue()) {
2041 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2042 Values.push_back(cast<Constant>(O->get()));
2045 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2046 Constant *Val = cast<Constant>(O->get());
2047 Values.push_back(Val);
2048 if (isAllZeros) isAllZeros = Val->isNullValue();
2051 Values[OperandToUpdate] = ToC;
2053 Constant *Replacement = 0;
2055 Replacement = ConstantAggregateZero::get(getType());
2057 // Check to see if we have this array type already.
2059 StructConstantsTy::MapTy::iterator I =
2060 StructConstants->InsertOrGetItem(Lookup, Exists);
2063 Replacement = I->second;
2065 // Okay, the new shape doesn't exist in the system yet. Instead of
2066 // creating a new constant struct, inserting it, replaceallusesof'ing the
2067 // old with the new, then deleting the old... just update the current one
2069 StructConstants->MoveConstantToNewSlot(this, I);
2071 // Update to the new value.
2072 setOperand(OperandToUpdate, ToC);
2077 assert(Replacement != this && "I didn't contain From!");
2079 // Everyone using this now uses the replacement.
2080 uncheckedReplaceAllUsesWith(Replacement);
2082 // Delete the old constant!
2086 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2088 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2090 std::vector<Constant*> Values;
2091 Values.reserve(getNumOperands()); // Build replacement array...
2092 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2093 Constant *Val = getOperand(i);
2094 if (Val == From) Val = cast<Constant>(To);
2095 Values.push_back(Val);
2098 Constant *Replacement = ConstantVector::get(getType(), Values);
2099 assert(Replacement != this && "I didn't contain From!");
2101 // Everyone using this now uses the replacement.
2102 uncheckedReplaceAllUsesWith(Replacement);
2104 // Delete the old constant!
2108 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2110 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2111 Constant *To = cast<Constant>(ToV);
2113 Constant *Replacement = 0;
2114 if (getOpcode() == Instruction::GetElementPtr) {
2115 SmallVector<Constant*, 8> Indices;
2116 Constant *Pointer = getOperand(0);
2117 Indices.reserve(getNumOperands()-1);
2118 if (Pointer == From) Pointer = To;
2120 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2121 Constant *Val = getOperand(i);
2122 if (Val == From) Val = To;
2123 Indices.push_back(Val);
2125 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2126 &Indices[0], Indices.size());
2127 } else if (isCast()) {
2128 assert(getOperand(0) == From && "Cast only has one use!");
2129 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2130 } else if (getOpcode() == Instruction::Select) {
2131 Constant *C1 = getOperand(0);
2132 Constant *C2 = getOperand(1);
2133 Constant *C3 = getOperand(2);
2134 if (C1 == From) C1 = To;
2135 if (C2 == From) C2 = To;
2136 if (C3 == From) C3 = To;
2137 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2138 } else if (getOpcode() == Instruction::ExtractElement) {
2139 Constant *C1 = getOperand(0);
2140 Constant *C2 = getOperand(1);
2141 if (C1 == From) C1 = To;
2142 if (C2 == From) C2 = To;
2143 Replacement = ConstantExpr::getExtractElement(C1, C2);
2144 } else if (getOpcode() == Instruction::InsertElement) {
2145 Constant *C1 = getOperand(0);
2146 Constant *C2 = getOperand(1);
2147 Constant *C3 = getOperand(1);
2148 if (C1 == From) C1 = To;
2149 if (C2 == From) C2 = To;
2150 if (C3 == From) C3 = To;
2151 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2152 } else if (getOpcode() == Instruction::ShuffleVector) {
2153 Constant *C1 = getOperand(0);
2154 Constant *C2 = getOperand(1);
2155 Constant *C3 = getOperand(2);
2156 if (C1 == From) C1 = To;
2157 if (C2 == From) C2 = To;
2158 if (C3 == From) C3 = To;
2159 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2160 } else if (isCompare()) {
2161 Constant *C1 = getOperand(0);
2162 Constant *C2 = getOperand(1);
2163 if (C1 == From) C1 = To;
2164 if (C2 == From) C2 = To;
2165 if (getOpcode() == Instruction::ICmp)
2166 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2168 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2169 } else if (getNumOperands() == 2) {
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::get(getOpcode(), C1, C2);
2176 assert(0 && "Unknown ConstantExpr type!");
2180 assert(Replacement != this && "I didn't contain From!");
2182 // Everyone using this now uses the replacement.
2183 uncheckedReplaceAllUsesWith(Replacement);
2185 // Delete the old constant!
2190 /// getStringValue - Turn an LLVM constant pointer that eventually points to a
2191 /// global into a string value. Return an empty string if we can't do it.
2192 /// Parameter Chop determines if the result is chopped at the first null
2195 std::string Constant::getStringValue(bool Chop, unsigned Offset) {
2196 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
2197 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
2198 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
2199 if (Init->isString()) {
2200 std::string Result = Init->getAsString();
2201 if (Offset < Result.size()) {
2202 // If we are pointing INTO The string, erase the beginning...
2203 Result.erase(Result.begin(), Result.begin()+Offset);
2205 // Take off the null terminator, and any string fragments after it.
2207 std::string::size_type NullPos = Result.find_first_of((char)0);
2208 if (NullPos != std::string::npos)
2209 Result.erase(Result.begin()+NullPos, Result.end());
2215 } else if (Constant *C = dyn_cast<Constant>(this)) {
2216 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
2217 return GV->getStringValue(Chop, Offset);
2218 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2219 if (CE->getOpcode() == Instruction::GetElementPtr) {
2220 // Turn a gep into the specified offset.
2221 if (CE->getNumOperands() == 3 &&
2222 cast<Constant>(CE->getOperand(1))->isNullValue() &&
2223 isa<ConstantInt>(CE->getOperand(2))) {
2224 Offset += cast<ConstantInt>(CE->getOperand(2))->getZExtValue();
2225 return CE->getOperand(0)->getStringValue(Chop, Offset);