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 return ConstantFP::get(Ty, 0.0);
112 case Type::PointerTyID:
113 return ConstantPointerNull::get(cast<PointerType>(Ty));
114 case Type::StructTyID:
115 case Type::ArrayTyID:
116 case Type::VectorTyID:
117 return ConstantAggregateZero::get(Ty);
119 // Function, Label, or Opaque type?
120 assert(!"Cannot create a null constant of that type!");
125 Constant *Constant::getAllOnesValue(const Type *Ty) {
126 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
127 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
128 return ConstantVector::getAllOnesValue(cast<VectorType>(Ty));
131 // Static constructor to create an integral constant with all bits set
132 ConstantInt *ConstantInt::getAllOnesValue(const Type *Ty) {
133 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
134 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
138 /// @returns the value for a vector integer constant of the given type that
139 /// has all its bits set to true.
140 /// @brief Get the all ones value
141 ConstantVector *ConstantVector::getAllOnesValue(const VectorType *Ty) {
142 std::vector<Constant*> Elts;
143 Elts.resize(Ty->getNumElements(),
144 ConstantInt::getAllOnesValue(Ty->getElementType()));
145 assert(Elts[0] && "Not a vector integer type!");
146 return cast<ConstantVector>(ConstantVector::get(Elts));
150 //===----------------------------------------------------------------------===//
152 //===----------------------------------------------------------------------===//
154 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
155 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
156 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
159 ConstantInt *ConstantInt::TheTrueVal = 0;
160 ConstantInt *ConstantInt::TheFalseVal = 0;
163 void CleanupTrueFalse(void *) {
164 ConstantInt::ResetTrueFalse();
168 static ManagedCleanup<llvm::CleanupTrueFalse> TrueFalseCleanup;
170 ConstantInt *ConstantInt::CreateTrueFalseVals(bool WhichOne) {
171 assert(TheTrueVal == 0 && TheFalseVal == 0);
172 TheTrueVal = get(Type::Int1Ty, 1);
173 TheFalseVal = get(Type::Int1Ty, 0);
175 // Ensure that llvm_shutdown nulls out TheTrueVal/TheFalseVal.
176 TrueFalseCleanup.Register();
178 return WhichOne ? TheTrueVal : TheFalseVal;
183 struct DenseMapAPIntKeyInfo {
187 KeyTy(const APInt& V, const Type* Ty) : val(V), type(Ty) {}
188 KeyTy(const KeyTy& that) : val(that.val), type(that.type) {}
189 bool operator==(const KeyTy& that) const {
190 return type == that.type && this->val == that.val;
192 bool operator!=(const KeyTy& that) const {
193 return !this->operator==(that);
196 static inline KeyTy getEmptyKey() { return KeyTy(APInt(1,0), 0); }
197 static inline KeyTy getTombstoneKey() { return KeyTy(APInt(1,1), 0); }
198 static unsigned getHashValue(const KeyTy &Key) {
199 return DenseMapKeyInfo<void*>::getHashValue(Key.type) ^
200 Key.val.getHashValue();
202 static bool isPod() { return true; }
207 typedef DenseMap<DenseMapAPIntKeyInfo::KeyTy, ConstantInt*,
208 DenseMapAPIntKeyInfo> IntMapTy;
209 static ManagedStatic<IntMapTy> IntConstants;
211 ConstantInt *ConstantInt::get(const Type *Ty, uint64_t V, bool isSigned) {
212 const IntegerType *ITy = cast<IntegerType>(Ty);
213 return get(APInt(ITy->getBitWidth(), V, isSigned));
216 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
217 // as the key, is a DensMapAPIntKeyInfo::KeyTy which has provided the
218 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
219 // compare APInt's of different widths, which would violate an APInt class
220 // invariant which generates an assertion.
221 ConstantInt *ConstantInt::get(const APInt& V) {
222 // Get the corresponding integer type for the bit width of the value.
223 const IntegerType *ITy = IntegerType::get(V.getBitWidth());
224 // get an existing value or the insertion position
225 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
226 ConstantInt *&Slot = (*IntConstants)[Key];
227 // if it exists, return it.
230 // otherwise create a new one, insert it, and return it.
231 return Slot = new ConstantInt(ITy, V);
234 //===----------------------------------------------------------------------===//
236 //===----------------------------------------------------------------------===//
239 ConstantFP::ConstantFP(const Type *Ty, double V)
240 : Constant(Ty, ConstantFPVal, 0, 0) {
244 bool ConstantFP::isNullValue() const {
245 return DoubleToBits(Val) == 0;
248 bool ConstantFP::isExactlyValue(double V) const {
249 return DoubleToBits(V) == DoubleToBits(Val);
254 struct DenseMapInt64KeyInfo {
255 typedef std::pair<uint64_t, const Type*> KeyTy;
256 static inline KeyTy getEmptyKey() { return KeyTy(0, 0); }
257 static inline KeyTy getTombstoneKey() { return KeyTy(1, 0); }
258 static unsigned getHashValue(const KeyTy &Key) {
259 return DenseMapKeyInfo<void*>::getHashValue(Key.second) ^ Key.first;
261 static bool isPod() { return true; }
263 struct DenseMapInt32KeyInfo {
264 typedef std::pair<uint32_t, const Type*> KeyTy;
265 static inline KeyTy getEmptyKey() { return KeyTy(0, 0); }
266 static inline KeyTy getTombstoneKey() { return KeyTy(1, 0); }
267 static unsigned getHashValue(const KeyTy &Key) {
268 return DenseMapKeyInfo<void*>::getHashValue(Key.second) ^ Key.first;
270 static bool isPod() { return true; }
274 //---- ConstantFP::get() implementation...
276 typedef DenseMap<DenseMapInt32KeyInfo::KeyTy, ConstantFP*,
277 DenseMapInt32KeyInfo> FloatMapTy;
278 typedef DenseMap<DenseMapInt64KeyInfo::KeyTy, ConstantFP*,
279 DenseMapInt64KeyInfo> DoubleMapTy;
281 static ManagedStatic<FloatMapTy> FloatConstants;
282 static ManagedStatic<DoubleMapTy> DoubleConstants;
284 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
285 if (Ty == Type::FloatTy) {
286 uint32_t IntVal = FloatToBits((float)V);
288 ConstantFP *&Slot = (*FloatConstants)[std::make_pair(IntVal, Ty)];
289 if (Slot) return Slot;
290 return Slot = new ConstantFP(Ty, (float)V);
292 assert(Ty == Type::DoubleTy);
293 uint64_t IntVal = DoubleToBits(V);
294 ConstantFP *&Slot = (*DoubleConstants)[std::make_pair(IntVal, Ty)];
295 if (Slot) return Slot;
296 return Slot = new ConstantFP(Ty, V);
301 //===----------------------------------------------------------------------===//
302 // ConstantXXX Classes
303 //===----------------------------------------------------------------------===//
306 ConstantArray::ConstantArray(const ArrayType *T,
307 const std::vector<Constant*> &V)
308 : Constant(T, ConstantArrayVal, new Use[V.size()], V.size()) {
309 assert(V.size() == T->getNumElements() &&
310 "Invalid initializer vector for constant array");
311 Use *OL = OperandList;
312 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
315 assert((C->getType() == T->getElementType() ||
317 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
318 "Initializer for array element doesn't match array element type!");
323 ConstantArray::~ConstantArray() {
324 delete [] OperandList;
327 ConstantStruct::ConstantStruct(const StructType *T,
328 const std::vector<Constant*> &V)
329 : Constant(T, ConstantStructVal, new Use[V.size()], V.size()) {
330 assert(V.size() == T->getNumElements() &&
331 "Invalid initializer vector for constant structure");
332 Use *OL = OperandList;
333 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
336 assert((C->getType() == T->getElementType(I-V.begin()) ||
337 ((T->getElementType(I-V.begin())->isAbstract() ||
338 C->getType()->isAbstract()) &&
339 T->getElementType(I-V.begin())->getTypeID() ==
340 C->getType()->getTypeID())) &&
341 "Initializer for struct element doesn't match struct element type!");
346 ConstantStruct::~ConstantStruct() {
347 delete [] OperandList;
351 ConstantVector::ConstantVector(const VectorType *T,
352 const std::vector<Constant*> &V)
353 : Constant(T, ConstantVectorVal, new Use[V.size()], V.size()) {
354 Use *OL = OperandList;
355 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
358 assert((C->getType() == T->getElementType() ||
360 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
361 "Initializer for vector element doesn't match vector element type!");
366 ConstantVector::~ConstantVector() {
367 delete [] OperandList;
370 // We declare several classes private to this file, so use an anonymous
374 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
375 /// behind the scenes to implement unary constant exprs.
376 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
379 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
380 : ConstantExpr(Ty, Opcode, &Op, 1), Op(C, this) {}
383 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
384 /// behind the scenes to implement binary constant exprs.
385 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
388 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
389 : ConstantExpr(C1->getType(), Opcode, Ops, 2) {
390 Ops[0].init(C1, this);
391 Ops[1].init(C2, this);
395 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
396 /// behind the scenes to implement select constant exprs.
397 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
400 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
401 : ConstantExpr(C2->getType(), Instruction::Select, Ops, 3) {
402 Ops[0].init(C1, this);
403 Ops[1].init(C2, this);
404 Ops[2].init(C3, this);
408 /// ExtractElementConstantExpr - This class is private to
409 /// Constants.cpp, and is used behind the scenes to implement
410 /// extractelement constant exprs.
411 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
414 ExtractElementConstantExpr(Constant *C1, Constant *C2)
415 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
416 Instruction::ExtractElement, Ops, 2) {
417 Ops[0].init(C1, this);
418 Ops[1].init(C2, this);
422 /// InsertElementConstantExpr - This class is private to
423 /// Constants.cpp, and is used behind the scenes to implement
424 /// insertelement constant exprs.
425 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
428 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
429 : ConstantExpr(C1->getType(), Instruction::InsertElement,
431 Ops[0].init(C1, this);
432 Ops[1].init(C2, this);
433 Ops[2].init(C3, this);
437 /// ShuffleVectorConstantExpr - This class is private to
438 /// Constants.cpp, and is used behind the scenes to implement
439 /// shufflevector constant exprs.
440 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
443 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
444 : ConstantExpr(C1->getType(), Instruction::ShuffleVector,
446 Ops[0].init(C1, this);
447 Ops[1].init(C2, this);
448 Ops[2].init(C3, this);
452 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
453 /// used behind the scenes to implement getelementpr constant exprs.
454 struct VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
455 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
457 : ConstantExpr(DestTy, Instruction::GetElementPtr,
458 new Use[IdxList.size()+1], IdxList.size()+1) {
459 OperandList[0].init(C, this);
460 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
461 OperandList[i+1].init(IdxList[i], this);
463 ~GetElementPtrConstantExpr() {
464 delete [] OperandList;
468 // CompareConstantExpr - This class is private to Constants.cpp, and is used
469 // behind the scenes to implement ICmp and FCmp constant expressions. This is
470 // needed in order to store the predicate value for these instructions.
471 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
472 unsigned short predicate;
474 CompareConstantExpr(Instruction::OtherOps opc, unsigned short pred,
475 Constant* LHS, Constant* RHS)
476 : ConstantExpr(Type::Int1Ty, opc, Ops, 2), predicate(pred) {
477 OperandList[0].init(LHS, this);
478 OperandList[1].init(RHS, this);
482 } // end anonymous namespace
485 // Utility function for determining if a ConstantExpr is a CastOp or not. This
486 // can't be inline because we don't want to #include Instruction.h into
488 bool ConstantExpr::isCast() const {
489 return Instruction::isCast(getOpcode());
492 bool ConstantExpr::isCompare() const {
493 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
496 /// ConstantExpr::get* - Return some common constants without having to
497 /// specify the full Instruction::OPCODE identifier.
499 Constant *ConstantExpr::getNeg(Constant *C) {
500 return get(Instruction::Sub,
501 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
504 Constant *ConstantExpr::getNot(Constant *C) {
505 assert(isa<ConstantInt>(C) && "Cannot NOT a nonintegral type!");
506 return get(Instruction::Xor, C,
507 ConstantInt::getAllOnesValue(C->getType()));
509 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
510 return get(Instruction::Add, C1, C2);
512 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
513 return get(Instruction::Sub, C1, C2);
515 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
516 return get(Instruction::Mul, C1, C2);
518 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
519 return get(Instruction::UDiv, C1, C2);
521 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
522 return get(Instruction::SDiv, C1, C2);
524 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
525 return get(Instruction::FDiv, C1, C2);
527 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
528 return get(Instruction::URem, C1, C2);
530 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
531 return get(Instruction::SRem, C1, C2);
533 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
534 return get(Instruction::FRem, C1, C2);
536 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
537 return get(Instruction::And, C1, C2);
539 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
540 return get(Instruction::Or, C1, C2);
542 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
543 return get(Instruction::Xor, C1, C2);
545 unsigned ConstantExpr::getPredicate() const {
546 assert(getOpcode() == Instruction::FCmp || getOpcode() == Instruction::ICmp);
547 return dynamic_cast<const CompareConstantExpr*>(this)->predicate;
549 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
550 return get(Instruction::Shl, C1, C2);
552 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
553 return get(Instruction::LShr, C1, C2);
555 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
556 return get(Instruction::AShr, C1, C2);
559 /// getWithOperandReplaced - Return a constant expression identical to this
560 /// one, but with the specified operand set to the specified value.
562 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
563 assert(OpNo < getNumOperands() && "Operand num is out of range!");
564 assert(Op->getType() == getOperand(OpNo)->getType() &&
565 "Replacing operand with value of different type!");
566 if (getOperand(OpNo) == Op)
567 return const_cast<ConstantExpr*>(this);
569 Constant *Op0, *Op1, *Op2;
570 switch (getOpcode()) {
571 case Instruction::Trunc:
572 case Instruction::ZExt:
573 case Instruction::SExt:
574 case Instruction::FPTrunc:
575 case Instruction::FPExt:
576 case Instruction::UIToFP:
577 case Instruction::SIToFP:
578 case Instruction::FPToUI:
579 case Instruction::FPToSI:
580 case Instruction::PtrToInt:
581 case Instruction::IntToPtr:
582 case Instruction::BitCast:
583 return ConstantExpr::getCast(getOpcode(), Op, getType());
584 case Instruction::Select:
585 Op0 = (OpNo == 0) ? Op : getOperand(0);
586 Op1 = (OpNo == 1) ? Op : getOperand(1);
587 Op2 = (OpNo == 2) ? Op : getOperand(2);
588 return ConstantExpr::getSelect(Op0, Op1, Op2);
589 case Instruction::InsertElement:
590 Op0 = (OpNo == 0) ? Op : getOperand(0);
591 Op1 = (OpNo == 1) ? Op : getOperand(1);
592 Op2 = (OpNo == 2) ? Op : getOperand(2);
593 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
594 case Instruction::ExtractElement:
595 Op0 = (OpNo == 0) ? Op : getOperand(0);
596 Op1 = (OpNo == 1) ? Op : getOperand(1);
597 return ConstantExpr::getExtractElement(Op0, Op1);
598 case Instruction::ShuffleVector:
599 Op0 = (OpNo == 0) ? Op : getOperand(0);
600 Op1 = (OpNo == 1) ? Op : getOperand(1);
601 Op2 = (OpNo == 2) ? Op : getOperand(2);
602 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
603 case Instruction::GetElementPtr: {
604 SmallVector<Constant*, 8> Ops;
605 Ops.resize(getNumOperands());
606 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
607 Ops[i] = getOperand(i);
609 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
611 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
614 assert(getNumOperands() == 2 && "Must be binary operator?");
615 Op0 = (OpNo == 0) ? Op : getOperand(0);
616 Op1 = (OpNo == 1) ? Op : getOperand(1);
617 return ConstantExpr::get(getOpcode(), Op0, Op1);
621 /// getWithOperands - This returns the current constant expression with the
622 /// operands replaced with the specified values. The specified operands must
623 /// match count and type with the existing ones.
624 Constant *ConstantExpr::
625 getWithOperands(const std::vector<Constant*> &Ops) const {
626 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
627 bool AnyChange = false;
628 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
629 assert(Ops[i]->getType() == getOperand(i)->getType() &&
630 "Operand type mismatch!");
631 AnyChange |= Ops[i] != getOperand(i);
633 if (!AnyChange) // No operands changed, return self.
634 return const_cast<ConstantExpr*>(this);
636 switch (getOpcode()) {
637 case Instruction::Trunc:
638 case Instruction::ZExt:
639 case Instruction::SExt:
640 case Instruction::FPTrunc:
641 case Instruction::FPExt:
642 case Instruction::UIToFP:
643 case Instruction::SIToFP:
644 case Instruction::FPToUI:
645 case Instruction::FPToSI:
646 case Instruction::PtrToInt:
647 case Instruction::IntToPtr:
648 case Instruction::BitCast:
649 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
650 case Instruction::Select:
651 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
652 case Instruction::InsertElement:
653 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
654 case Instruction::ExtractElement:
655 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
656 case Instruction::ShuffleVector:
657 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
658 case Instruction::GetElementPtr:
659 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], Ops.size()-1);
660 case Instruction::ICmp:
661 case Instruction::FCmp:
662 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
664 assert(getNumOperands() == 2 && "Must be binary operator?");
665 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
670 //===----------------------------------------------------------------------===//
671 // isValueValidForType implementations
673 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
674 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
675 if (Ty == Type::Int1Ty)
676 return Val == 0 || Val == 1;
678 return true; // always true, has to fit in largest type
679 uint64_t Max = (1ll << NumBits) - 1;
683 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
684 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
685 if (Ty == Type::Int1Ty)
686 return Val == 0 || Val == 1 || Val == -1;
688 return true; // always true, has to fit in largest type
689 int64_t Min = -(1ll << (NumBits-1));
690 int64_t Max = (1ll << (NumBits-1)) - 1;
691 return (Val >= Min && Val <= Max);
694 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
695 switch (Ty->getTypeID()) {
697 return false; // These can't be represented as floating point!
699 // TODO: Figure out how to test if a double can be cast to a float!
700 case Type::FloatTyID:
701 case Type::DoubleTyID:
702 return true; // This is the largest type...
706 //===----------------------------------------------------------------------===//
707 // Factory Function Implementation
709 // ConstantCreator - A class that is used to create constants by
710 // ValueMap*. This class should be partially specialized if there is
711 // something strange that needs to be done to interface to the ctor for the
715 template<class ConstantClass, class TypeClass, class ValType>
716 struct VISIBILITY_HIDDEN ConstantCreator {
717 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
718 return new ConstantClass(Ty, V);
722 template<class ConstantClass, class TypeClass>
723 struct VISIBILITY_HIDDEN ConvertConstantType {
724 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
725 assert(0 && "This type cannot be converted!\n");
730 template<class ValType, class TypeClass, class ConstantClass,
731 bool HasLargeKey = false /*true for arrays and structs*/ >
732 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
734 typedef std::pair<const Type*, ValType> MapKey;
735 typedef std::map<MapKey, Constant *> MapTy;
736 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
737 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
739 /// Map - This is the main map from the element descriptor to the Constants.
740 /// This is the primary way we avoid creating two of the same shape
744 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
745 /// from the constants to their element in Map. This is important for
746 /// removal of constants from the array, which would otherwise have to scan
747 /// through the map with very large keys.
748 InverseMapTy InverseMap;
750 /// AbstractTypeMap - Map for abstract type constants.
752 AbstractTypeMapTy AbstractTypeMap;
755 typename MapTy::iterator map_end() { return Map.end(); }
757 /// InsertOrGetItem - Return an iterator for the specified element.
758 /// If the element exists in the map, the returned iterator points to the
759 /// entry and Exists=true. If not, the iterator points to the newly
760 /// inserted entry and returns Exists=false. Newly inserted entries have
761 /// I->second == 0, and should be filled in.
762 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
765 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
771 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
773 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
774 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
775 IMI->second->second == CP &&
776 "InverseMap corrupt!");
780 typename MapTy::iterator I =
781 Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
782 if (I == Map.end() || I->second != CP) {
783 // FIXME: This should not use a linear scan. If this gets to be a
784 // performance problem, someone should look at this.
785 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
792 /// getOrCreate - Return the specified constant from the map, creating it if
794 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
795 MapKey Lookup(Ty, V);
796 typename MapTy::iterator I = Map.lower_bound(Lookup);
798 if (I != Map.end() && I->first == Lookup)
799 return static_cast<ConstantClass *>(I->second);
801 // If no preexisting value, create one now...
802 ConstantClass *Result =
803 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
805 /// FIXME: why does this assert fail when loading 176.gcc?
806 //assert(Result->getType() == Ty && "Type specified is not correct!");
807 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
809 if (HasLargeKey) // Remember the reverse mapping if needed.
810 InverseMap.insert(std::make_pair(Result, I));
812 // If the type of the constant is abstract, make sure that an entry exists
813 // for it in the AbstractTypeMap.
814 if (Ty->isAbstract()) {
815 typename AbstractTypeMapTy::iterator TI =
816 AbstractTypeMap.lower_bound(Ty);
818 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
819 // Add ourselves to the ATU list of the type.
820 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
822 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
828 void remove(ConstantClass *CP) {
829 typename MapTy::iterator I = FindExistingElement(CP);
830 assert(I != Map.end() && "Constant not found in constant table!");
831 assert(I->second == CP && "Didn't find correct element?");
833 if (HasLargeKey) // Remember the reverse mapping if needed.
834 InverseMap.erase(CP);
836 // Now that we found the entry, make sure this isn't the entry that
837 // the AbstractTypeMap points to.
838 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
839 if (Ty->isAbstract()) {
840 assert(AbstractTypeMap.count(Ty) &&
841 "Abstract type not in AbstractTypeMap?");
842 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
843 if (ATMEntryIt == I) {
844 // Yes, we are removing the representative entry for this type.
845 // See if there are any other entries of the same type.
846 typename MapTy::iterator TmpIt = ATMEntryIt;
848 // First check the entry before this one...
849 if (TmpIt != Map.begin()) {
851 if (TmpIt->first.first != Ty) // Not the same type, move back...
855 // If we didn't find the same type, try to move forward...
856 if (TmpIt == ATMEntryIt) {
858 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
859 --TmpIt; // No entry afterwards with the same type
862 // If there is another entry in the map of the same abstract type,
863 // update the AbstractTypeMap entry now.
864 if (TmpIt != ATMEntryIt) {
867 // Otherwise, we are removing the last instance of this type
868 // from the table. Remove from the ATM, and from user list.
869 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
870 AbstractTypeMap.erase(Ty);
879 /// MoveConstantToNewSlot - If we are about to change C to be the element
880 /// specified by I, update our internal data structures to reflect this
882 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
883 // First, remove the old location of the specified constant in the map.
884 typename MapTy::iterator OldI = FindExistingElement(C);
885 assert(OldI != Map.end() && "Constant not found in constant table!");
886 assert(OldI->second == C && "Didn't find correct element?");
888 // If this constant is the representative element for its abstract type,
889 // update the AbstractTypeMap so that the representative element is I.
890 if (C->getType()->isAbstract()) {
891 typename AbstractTypeMapTy::iterator ATI =
892 AbstractTypeMap.find(C->getType());
893 assert(ATI != AbstractTypeMap.end() &&
894 "Abstract type not in AbstractTypeMap?");
895 if (ATI->second == OldI)
899 // Remove the old entry from the map.
902 // Update the inverse map so that we know that this constant is now
903 // located at descriptor I.
905 assert(I->second == C && "Bad inversemap entry!");
910 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
911 typename AbstractTypeMapTy::iterator I =
912 AbstractTypeMap.find(cast<Type>(OldTy));
914 assert(I != AbstractTypeMap.end() &&
915 "Abstract type not in AbstractTypeMap?");
917 // Convert a constant at a time until the last one is gone. The last one
918 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
919 // eliminated eventually.
921 ConvertConstantType<ConstantClass,
923 static_cast<ConstantClass *>(I->second->second),
924 cast<TypeClass>(NewTy));
926 I = AbstractTypeMap.find(cast<Type>(OldTy));
927 } while (I != AbstractTypeMap.end());
930 // If the type became concrete without being refined to any other existing
931 // type, we just remove ourselves from the ATU list.
932 void typeBecameConcrete(const DerivedType *AbsTy) {
933 AbsTy->removeAbstractTypeUser(this);
937 DOUT << "Constant.cpp: ValueMap\n";
944 //---- ConstantAggregateZero::get() implementation...
947 // ConstantAggregateZero does not take extra "value" argument...
948 template<class ValType>
949 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
950 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
951 return new ConstantAggregateZero(Ty);
956 struct ConvertConstantType<ConstantAggregateZero, Type> {
957 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
958 // Make everyone now use a constant of the new type...
959 Constant *New = ConstantAggregateZero::get(NewTy);
960 assert(New != OldC && "Didn't replace constant??");
961 OldC->uncheckedReplaceAllUsesWith(New);
962 OldC->destroyConstant(); // This constant is now dead, destroy it.
967 static ManagedStatic<ValueMap<char, Type,
968 ConstantAggregateZero> > AggZeroConstants;
970 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
972 Constant *ConstantAggregateZero::get(const Type *Ty) {
973 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
974 "Cannot create an aggregate zero of non-aggregate type!");
975 return AggZeroConstants->getOrCreate(Ty, 0);
978 // destroyConstant - Remove the constant from the constant table...
980 void ConstantAggregateZero::destroyConstant() {
981 AggZeroConstants->remove(this);
982 destroyConstantImpl();
985 //---- ConstantArray::get() implementation...
989 struct ConvertConstantType<ConstantArray, ArrayType> {
990 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
991 // Make everyone now use a constant of the new type...
992 std::vector<Constant*> C;
993 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
994 C.push_back(cast<Constant>(OldC->getOperand(i)));
995 Constant *New = ConstantArray::get(NewTy, C);
996 assert(New != OldC && "Didn't replace constant??");
997 OldC->uncheckedReplaceAllUsesWith(New);
998 OldC->destroyConstant(); // This constant is now dead, destroy it.
1003 static std::vector<Constant*> getValType(ConstantArray *CA) {
1004 std::vector<Constant*> Elements;
1005 Elements.reserve(CA->getNumOperands());
1006 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1007 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1011 typedef ValueMap<std::vector<Constant*>, ArrayType,
1012 ConstantArray, true /*largekey*/> ArrayConstantsTy;
1013 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
1015 Constant *ConstantArray::get(const ArrayType *Ty,
1016 const std::vector<Constant*> &V) {
1017 // If this is an all-zero array, return a ConstantAggregateZero object
1020 if (!C->isNullValue())
1021 return ArrayConstants->getOrCreate(Ty, V);
1022 for (unsigned i = 1, e = V.size(); i != e; ++i)
1024 return ArrayConstants->getOrCreate(Ty, V);
1026 return ConstantAggregateZero::get(Ty);
1029 // destroyConstant - Remove the constant from the constant table...
1031 void ConstantArray::destroyConstant() {
1032 ArrayConstants->remove(this);
1033 destroyConstantImpl();
1036 /// ConstantArray::get(const string&) - Return an array that is initialized to
1037 /// contain the specified string. If length is zero then a null terminator is
1038 /// added to the specified string so that it may be used in a natural way.
1039 /// Otherwise, the length parameter specifies how much of the string to use
1040 /// and it won't be null terminated.
1042 Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
1043 std::vector<Constant*> ElementVals;
1044 for (unsigned i = 0; i < Str.length(); ++i)
1045 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
1047 // Add a null terminator to the string...
1049 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
1052 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
1053 return ConstantArray::get(ATy, ElementVals);
1056 /// isString - This method returns true if the array is an array of i8, and
1057 /// if the elements of the array are all ConstantInt's.
1058 bool ConstantArray::isString() const {
1059 // Check the element type for i8...
1060 if (getType()->getElementType() != Type::Int8Ty)
1062 // Check the elements to make sure they are all integers, not constant
1064 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1065 if (!isa<ConstantInt>(getOperand(i)))
1070 /// isCString - This method returns true if the array is a string (see
1071 /// isString) and it ends in a null byte \0 and does not contains any other
1072 /// null bytes except its terminator.
1073 bool ConstantArray::isCString() const {
1074 // Check the element type for i8...
1075 if (getType()->getElementType() != Type::Int8Ty)
1077 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1078 // Last element must be a null.
1079 if (getOperand(getNumOperands()-1) != Zero)
1081 // Other elements must be non-null integers.
1082 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1083 if (!isa<ConstantInt>(getOperand(i)))
1085 if (getOperand(i) == Zero)
1092 // getAsString - If the sub-element type of this array is i8
1093 // then this method converts the array to an std::string and returns it.
1094 // Otherwise, it asserts out.
1096 std::string ConstantArray::getAsString() const {
1097 assert(isString() && "Not a string!");
1099 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1100 Result += (char)cast<ConstantInt>(getOperand(i))->getZExtValue();
1105 //---- ConstantStruct::get() implementation...
1110 struct ConvertConstantType<ConstantStruct, StructType> {
1111 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1112 // Make everyone now use a constant of the new type...
1113 std::vector<Constant*> C;
1114 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1115 C.push_back(cast<Constant>(OldC->getOperand(i)));
1116 Constant *New = ConstantStruct::get(NewTy, C);
1117 assert(New != OldC && "Didn't replace constant??");
1119 OldC->uncheckedReplaceAllUsesWith(New);
1120 OldC->destroyConstant(); // This constant is now dead, destroy it.
1125 typedef ValueMap<std::vector<Constant*>, StructType,
1126 ConstantStruct, true /*largekey*/> StructConstantsTy;
1127 static ManagedStatic<StructConstantsTy> StructConstants;
1129 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1130 std::vector<Constant*> Elements;
1131 Elements.reserve(CS->getNumOperands());
1132 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1133 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1137 Constant *ConstantStruct::get(const StructType *Ty,
1138 const std::vector<Constant*> &V) {
1139 // Create a ConstantAggregateZero value if all elements are zeros...
1140 for (unsigned i = 0, e = V.size(); i != e; ++i)
1141 if (!V[i]->isNullValue())
1142 return StructConstants->getOrCreate(Ty, V);
1144 return ConstantAggregateZero::get(Ty);
1147 Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
1148 std::vector<const Type*> StructEls;
1149 StructEls.reserve(V.size());
1150 for (unsigned i = 0, e = V.size(); i != e; ++i)
1151 StructEls.push_back(V[i]->getType());
1152 return get(StructType::get(StructEls, packed), V);
1155 // destroyConstant - Remove the constant from the constant table...
1157 void ConstantStruct::destroyConstant() {
1158 StructConstants->remove(this);
1159 destroyConstantImpl();
1162 //---- ConstantVector::get() implementation...
1166 struct ConvertConstantType<ConstantVector, VectorType> {
1167 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
1168 // Make everyone now use a constant of the new type...
1169 std::vector<Constant*> C;
1170 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1171 C.push_back(cast<Constant>(OldC->getOperand(i)));
1172 Constant *New = ConstantVector::get(NewTy, C);
1173 assert(New != OldC && "Didn't replace constant??");
1174 OldC->uncheckedReplaceAllUsesWith(New);
1175 OldC->destroyConstant(); // This constant is now dead, destroy it.
1180 static std::vector<Constant*> getValType(ConstantVector *CP) {
1181 std::vector<Constant*> Elements;
1182 Elements.reserve(CP->getNumOperands());
1183 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1184 Elements.push_back(CP->getOperand(i));
1188 static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
1189 ConstantVector> > VectorConstants;
1191 Constant *ConstantVector::get(const VectorType *Ty,
1192 const std::vector<Constant*> &V) {
1193 // If this is an all-zero vector, return a ConstantAggregateZero object
1196 if (!C->isNullValue())
1197 return VectorConstants->getOrCreate(Ty, V);
1198 for (unsigned i = 1, e = V.size(); i != e; ++i)
1200 return VectorConstants->getOrCreate(Ty, V);
1202 return ConstantAggregateZero::get(Ty);
1205 Constant *ConstantVector::get(const std::vector<Constant*> &V) {
1206 assert(!V.empty() && "Cannot infer type if V is empty");
1207 return get(VectorType::get(V.front()->getType(),V.size()), V);
1210 // destroyConstant - Remove the constant from the constant table...
1212 void ConstantVector::destroyConstant() {
1213 VectorConstants->remove(this);
1214 destroyConstantImpl();
1217 /// This function will return true iff every element in this vector constant
1218 /// is set to all ones.
1219 /// @returns true iff this constant's emements are all set to all ones.
1220 /// @brief Determine if the value is all ones.
1221 bool ConstantVector::isAllOnesValue() const {
1222 // Check out first element.
1223 const Constant *Elt = getOperand(0);
1224 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1225 if (!CI || !CI->isAllOnesValue()) return false;
1226 // Then make sure all remaining elements point to the same value.
1227 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1228 if (getOperand(I) != Elt) return false;
1233 //---- ConstantPointerNull::get() implementation...
1237 // ConstantPointerNull does not take extra "value" argument...
1238 template<class ValType>
1239 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1240 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1241 return new ConstantPointerNull(Ty);
1246 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1247 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1248 // Make everyone now use a constant of the new type...
1249 Constant *New = ConstantPointerNull::get(NewTy);
1250 assert(New != OldC && "Didn't replace constant??");
1251 OldC->uncheckedReplaceAllUsesWith(New);
1252 OldC->destroyConstant(); // This constant is now dead, destroy it.
1257 static ManagedStatic<ValueMap<char, PointerType,
1258 ConstantPointerNull> > NullPtrConstants;
1260 static char getValType(ConstantPointerNull *) {
1265 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1266 return NullPtrConstants->getOrCreate(Ty, 0);
1269 // destroyConstant - Remove the constant from the constant table...
1271 void ConstantPointerNull::destroyConstant() {
1272 NullPtrConstants->remove(this);
1273 destroyConstantImpl();
1277 //---- UndefValue::get() implementation...
1281 // UndefValue does not take extra "value" argument...
1282 template<class ValType>
1283 struct ConstantCreator<UndefValue, Type, ValType> {
1284 static UndefValue *create(const Type *Ty, const ValType &V) {
1285 return new UndefValue(Ty);
1290 struct ConvertConstantType<UndefValue, Type> {
1291 static void convert(UndefValue *OldC, const Type *NewTy) {
1292 // Make everyone now use a constant of the new type.
1293 Constant *New = UndefValue::get(NewTy);
1294 assert(New != OldC && "Didn't replace constant??");
1295 OldC->uncheckedReplaceAllUsesWith(New);
1296 OldC->destroyConstant(); // This constant is now dead, destroy it.
1301 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1303 static char getValType(UndefValue *) {
1308 UndefValue *UndefValue::get(const Type *Ty) {
1309 return UndefValueConstants->getOrCreate(Ty, 0);
1312 // destroyConstant - Remove the constant from the constant table.
1314 void UndefValue::destroyConstant() {
1315 UndefValueConstants->remove(this);
1316 destroyConstantImpl();
1320 //---- ConstantExpr::get() implementations...
1323 struct ExprMapKeyType {
1324 explicit ExprMapKeyType(unsigned opc, std::vector<Constant*> ops,
1325 unsigned short pred = 0) : opcode(opc), predicate(pred), operands(ops) { }
1328 std::vector<Constant*> operands;
1329 bool operator==(const ExprMapKeyType& that) const {
1330 return this->opcode == that.opcode &&
1331 this->predicate == that.predicate &&
1332 this->operands == that.operands;
1334 bool operator<(const ExprMapKeyType & that) const {
1335 return this->opcode < that.opcode ||
1336 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1337 (this->opcode == that.opcode && this->predicate == that.predicate &&
1338 this->operands < that.operands);
1341 bool operator!=(const ExprMapKeyType& that) const {
1342 return !(*this == that);
1348 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1349 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1350 unsigned short pred = 0) {
1351 if (Instruction::isCast(V.opcode))
1352 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1353 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1354 V.opcode < Instruction::BinaryOpsEnd))
1355 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1356 if (V.opcode == Instruction::Select)
1357 return new SelectConstantExpr(V.operands[0], V.operands[1],
1359 if (V.opcode == Instruction::ExtractElement)
1360 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1361 if (V.opcode == Instruction::InsertElement)
1362 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1364 if (V.opcode == Instruction::ShuffleVector)
1365 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1367 if (V.opcode == Instruction::GetElementPtr) {
1368 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1369 return new GetElementPtrConstantExpr(V.operands[0], IdxList, Ty);
1372 // The compare instructions are weird. We have to encode the predicate
1373 // value and it is combined with the instruction opcode by multiplying
1374 // the opcode by one hundred. We must decode this to get the predicate.
1375 if (V.opcode == Instruction::ICmp)
1376 return new CompareConstantExpr(Instruction::ICmp, V.predicate,
1377 V.operands[0], V.operands[1]);
1378 if (V.opcode == Instruction::FCmp)
1379 return new CompareConstantExpr(Instruction::FCmp, V.predicate,
1380 V.operands[0], V.operands[1]);
1381 assert(0 && "Invalid ConstantExpr!");
1387 struct ConvertConstantType<ConstantExpr, Type> {
1388 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1390 switch (OldC->getOpcode()) {
1391 case Instruction::Trunc:
1392 case Instruction::ZExt:
1393 case Instruction::SExt:
1394 case Instruction::FPTrunc:
1395 case Instruction::FPExt:
1396 case Instruction::UIToFP:
1397 case Instruction::SIToFP:
1398 case Instruction::FPToUI:
1399 case Instruction::FPToSI:
1400 case Instruction::PtrToInt:
1401 case Instruction::IntToPtr:
1402 case Instruction::BitCast:
1403 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1406 case Instruction::Select:
1407 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1408 OldC->getOperand(1),
1409 OldC->getOperand(2));
1412 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1413 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1414 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1415 OldC->getOperand(1));
1417 case Instruction::GetElementPtr:
1418 // Make everyone now use a constant of the new type...
1419 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1420 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1421 &Idx[0], Idx.size());
1425 assert(New != OldC && "Didn't replace constant??");
1426 OldC->uncheckedReplaceAllUsesWith(New);
1427 OldC->destroyConstant(); // This constant is now dead, destroy it.
1430 } // end namespace llvm
1433 static ExprMapKeyType getValType(ConstantExpr *CE) {
1434 std::vector<Constant*> Operands;
1435 Operands.reserve(CE->getNumOperands());
1436 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1437 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1438 return ExprMapKeyType(CE->getOpcode(), Operands,
1439 CE->isCompare() ? CE->getPredicate() : 0);
1442 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1443 ConstantExpr> > ExprConstants;
1445 /// This is a utility function to handle folding of casts and lookup of the
1446 /// cast in the ExprConstants map. It is usedby the various get* methods below.
1447 static inline Constant *getFoldedCast(
1448 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1449 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1450 // Fold a few common cases
1451 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1454 // Look up the constant in the table first to ensure uniqueness
1455 std::vector<Constant*> argVec(1, C);
1456 ExprMapKeyType Key(opc, argVec);
1457 return ExprConstants->getOrCreate(Ty, Key);
1460 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1461 Instruction::CastOps opc = Instruction::CastOps(oc);
1462 assert(Instruction::isCast(opc) && "opcode out of range");
1463 assert(C && Ty && "Null arguments to getCast");
1464 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1468 assert(0 && "Invalid cast opcode");
1470 case Instruction::Trunc: return getTrunc(C, Ty);
1471 case Instruction::ZExt: return getZExt(C, Ty);
1472 case Instruction::SExt: return getSExt(C, Ty);
1473 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1474 case Instruction::FPExt: return getFPExtend(C, Ty);
1475 case Instruction::UIToFP: return getUIToFP(C, Ty);
1476 case Instruction::SIToFP: return getSIToFP(C, Ty);
1477 case Instruction::FPToUI: return getFPToUI(C, Ty);
1478 case Instruction::FPToSI: return getFPToSI(C, Ty);
1479 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1480 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1481 case Instruction::BitCast: return getBitCast(C, Ty);
1486 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1487 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1488 return getCast(Instruction::BitCast, C, Ty);
1489 return getCast(Instruction::ZExt, C, Ty);
1492 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1493 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1494 return getCast(Instruction::BitCast, C, Ty);
1495 return getCast(Instruction::SExt, C, Ty);
1498 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1499 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1500 return getCast(Instruction::BitCast, C, Ty);
1501 return getCast(Instruction::Trunc, C, Ty);
1504 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1505 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1506 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1508 if (Ty->isInteger())
1509 return getCast(Instruction::PtrToInt, S, Ty);
1510 return getCast(Instruction::BitCast, S, Ty);
1513 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1515 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1516 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1517 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1518 Instruction::CastOps opcode =
1519 (SrcBits == DstBits ? Instruction::BitCast :
1520 (SrcBits > DstBits ? Instruction::Trunc :
1521 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1522 return getCast(opcode, C, Ty);
1525 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1526 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1528 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1529 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1530 if (SrcBits == DstBits)
1531 return C; // Avoid a useless cast
1532 Instruction::CastOps opcode =
1533 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1534 return getCast(opcode, C, Ty);
1537 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1538 assert(C->getType()->isInteger() && "Trunc operand must be integer");
1539 assert(Ty->isInteger() && "Trunc produces only integral");
1540 assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1541 "SrcTy must be larger than DestTy for Trunc!");
1543 return getFoldedCast(Instruction::Trunc, C, Ty);
1546 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1547 assert(C->getType()->isInteger() && "SEXt operand must be integral");
1548 assert(Ty->isInteger() && "SExt produces only integer");
1549 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1550 "SrcTy must be smaller than DestTy for SExt!");
1552 return getFoldedCast(Instruction::SExt, C, Ty);
1555 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1556 assert(C->getType()->isInteger() && "ZEXt operand must be integral");
1557 assert(Ty->isInteger() && "ZExt produces only integer");
1558 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1559 "SrcTy must be smaller than DestTy for ZExt!");
1561 return getFoldedCast(Instruction::ZExt, C, Ty);
1564 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1565 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1566 C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1567 "This is an illegal floating point truncation!");
1568 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1571 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1572 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1573 C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1574 "This is an illegal floating point extension!");
1575 return getFoldedCast(Instruction::FPExt, C, Ty);
1578 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1579 assert(C->getType()->isInteger() && Ty->isFloatingPoint() &&
1580 "This is an illegal i32 to floating point cast!");
1581 return getFoldedCast(Instruction::UIToFP, C, Ty);
1584 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1585 assert(C->getType()->isInteger() && Ty->isFloatingPoint() &&
1586 "This is an illegal sint to floating point cast!");
1587 return getFoldedCast(Instruction::SIToFP, C, Ty);
1590 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1591 assert(C->getType()->isFloatingPoint() && Ty->isInteger() &&
1592 "This is an illegal floating point to i32 cast!");
1593 return getFoldedCast(Instruction::FPToUI, C, Ty);
1596 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1597 assert(C->getType()->isFloatingPoint() && Ty->isInteger() &&
1598 "This is an illegal floating point to i32 cast!");
1599 return getFoldedCast(Instruction::FPToSI, C, Ty);
1602 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1603 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1604 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1605 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1608 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1609 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1610 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1611 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1614 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1615 // BitCast implies a no-op cast of type only. No bits change. However, you
1616 // can't cast pointers to anything but pointers.
1617 const Type *SrcTy = C->getType();
1618 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1619 "BitCast cannot cast pointer to non-pointer and vice versa");
1621 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1622 // or nonptr->ptr). For all the other types, the cast is okay if source and
1623 // destination bit widths are identical.
1624 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1625 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1626 assert(SrcBitSize == DstBitSize && "BitCast requies types of same width");
1627 return getFoldedCast(Instruction::BitCast, C, DstTy);
1630 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
1631 // sizeof is implemented as: (ulong) gep (Ty*)null, 1
1632 Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
1634 getGetElementPtr(getNullValue(PointerType::get(Ty)), &GEPIdx, 1);
1635 return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
1638 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1639 Constant *C1, Constant *C2) {
1640 // Check the operands for consistency first
1641 assert(Opcode >= Instruction::BinaryOpsBegin &&
1642 Opcode < Instruction::BinaryOpsEnd &&
1643 "Invalid opcode in binary constant expression");
1644 assert(C1->getType() == C2->getType() &&
1645 "Operand types in binary constant expression should match");
1647 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
1648 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1649 return FC; // Fold a few common cases...
1651 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1652 ExprMapKeyType Key(Opcode, argVec);
1653 return ExprConstants->getOrCreate(ReqTy, Key);
1656 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1657 Constant *C1, Constant *C2) {
1658 switch (predicate) {
1659 default: assert(0 && "Invalid CmpInst predicate");
1660 case FCmpInst::FCMP_FALSE: case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_OGT:
1661 case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OLE:
1662 case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_ORD: case FCmpInst::FCMP_UNO:
1663 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UGT: case FCmpInst::FCMP_UGE:
1664 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_ULE: case FCmpInst::FCMP_UNE:
1665 case FCmpInst::FCMP_TRUE:
1666 return getFCmp(predicate, C1, C2);
1667 case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGT:
1668 case ICmpInst::ICMP_UGE: case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE:
1669 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_SGE: case ICmpInst::ICMP_SLT:
1670 case ICmpInst::ICMP_SLE:
1671 return getICmp(predicate, C1, C2);
1675 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1678 case Instruction::Add:
1679 case Instruction::Sub:
1680 case Instruction::Mul:
1681 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1682 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
1683 isa<VectorType>(C1->getType())) &&
1684 "Tried to create an arithmetic operation on a non-arithmetic type!");
1686 case Instruction::UDiv:
1687 case Instruction::SDiv:
1688 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1689 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1690 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
1691 "Tried to create an arithmetic operation on a non-arithmetic type!");
1693 case Instruction::FDiv:
1694 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1695 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1696 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
1697 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1699 case Instruction::URem:
1700 case Instruction::SRem:
1701 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1702 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1703 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
1704 "Tried to create an arithmetic operation on a non-arithmetic type!");
1706 case Instruction::FRem:
1707 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1708 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1709 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
1710 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1712 case Instruction::And:
1713 case Instruction::Or:
1714 case Instruction::Xor:
1715 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1716 assert((C1->getType()->isInteger() || isa<VectorType>(C1->getType())) &&
1717 "Tried to create a logical operation on a non-integral type!");
1719 case Instruction::Shl:
1720 case Instruction::LShr:
1721 case Instruction::AShr:
1722 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1723 assert(C1->getType()->isInteger() &&
1724 "Tried to create a shift operation on a non-integer type!");
1731 return getTy(C1->getType(), Opcode, C1, C2);
1734 Constant *ConstantExpr::getCompare(unsigned short pred,
1735 Constant *C1, Constant *C2) {
1736 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1737 return getCompareTy(pred, C1, C2);
1740 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1741 Constant *V1, Constant *V2) {
1742 assert(C->getType() == Type::Int1Ty && "Select condition must be i1!");
1743 assert(V1->getType() == V2->getType() && "Select value types must match!");
1744 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1746 if (ReqTy == V1->getType())
1747 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1748 return SC; // Fold common cases
1750 std::vector<Constant*> argVec(3, C);
1753 ExprMapKeyType Key(Instruction::Select, argVec);
1754 return ExprConstants->getOrCreate(ReqTy, Key);
1757 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1760 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs, NumIdx, true) &&
1761 "GEP indices invalid!");
1763 if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs, NumIdx))
1764 return FC; // Fold a few common cases...
1766 assert(isa<PointerType>(C->getType()) &&
1767 "Non-pointer type for constant GetElementPtr expression");
1768 // Look up the constant in the table first to ensure uniqueness
1769 std::vector<Constant*> ArgVec;
1770 ArgVec.reserve(NumIdx+1);
1771 ArgVec.push_back(C);
1772 for (unsigned i = 0; i != NumIdx; ++i)
1773 ArgVec.push_back(cast<Constant>(Idxs[i]));
1774 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
1775 return ExprConstants->getOrCreate(ReqTy, Key);
1778 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1780 // Get the result type of the getelementptr!
1782 GetElementPtrInst::getIndexedType(C->getType(), Idxs, NumIdx, true);
1783 assert(Ty && "GEP indices invalid!");
1784 return getGetElementPtrTy(PointerType::get(Ty), C, Idxs, NumIdx);
1787 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1789 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1794 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1795 assert(LHS->getType() == RHS->getType());
1796 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1797 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1799 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1800 return FC; // Fold a few common cases...
1802 // Look up the constant in the table first to ensure uniqueness
1803 std::vector<Constant*> ArgVec;
1804 ArgVec.push_back(LHS);
1805 ArgVec.push_back(RHS);
1806 // Get the key type with both the opcode and predicate
1807 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1808 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1812 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1813 assert(LHS->getType() == RHS->getType());
1814 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1816 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1817 return FC; // Fold a few common cases...
1819 // Look up the constant in the table first to ensure uniqueness
1820 std::vector<Constant*> ArgVec;
1821 ArgVec.push_back(LHS);
1822 ArgVec.push_back(RHS);
1823 // Get the key type with both the opcode and predicate
1824 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1825 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1828 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1830 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1831 return FC; // Fold a few common cases...
1832 // Look up the constant in the table first to ensure uniqueness
1833 std::vector<Constant*> ArgVec(1, Val);
1834 ArgVec.push_back(Idx);
1835 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1836 return ExprConstants->getOrCreate(ReqTy, Key);
1839 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1840 assert(isa<VectorType>(Val->getType()) &&
1841 "Tried to create extractelement operation on non-vector type!");
1842 assert(Idx->getType() == Type::Int32Ty &&
1843 "Extractelement index must be i32 type!");
1844 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
1848 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1849 Constant *Elt, Constant *Idx) {
1850 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1851 return FC; // Fold a few common cases...
1852 // Look up the constant in the table first to ensure uniqueness
1853 std::vector<Constant*> ArgVec(1, Val);
1854 ArgVec.push_back(Elt);
1855 ArgVec.push_back(Idx);
1856 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1857 return ExprConstants->getOrCreate(ReqTy, Key);
1860 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1862 assert(isa<VectorType>(Val->getType()) &&
1863 "Tried to create insertelement operation on non-vector type!");
1864 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
1865 && "Insertelement types must match!");
1866 assert(Idx->getType() == Type::Int32Ty &&
1867 "Insertelement index must be i32 type!");
1868 return getInsertElementTy(cast<VectorType>(Val->getType())->getElementType(),
1872 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1873 Constant *V2, Constant *Mask) {
1874 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1875 return FC; // Fold a few common cases...
1876 // Look up the constant in the table first to ensure uniqueness
1877 std::vector<Constant*> ArgVec(1, V1);
1878 ArgVec.push_back(V2);
1879 ArgVec.push_back(Mask);
1880 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1881 return ExprConstants->getOrCreate(ReqTy, Key);
1884 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1886 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1887 "Invalid shuffle vector constant expr operands!");
1888 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
1891 Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
1892 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
1893 if (PTy->getElementType()->isFloatingPoint()) {
1894 std::vector<Constant*> zeros(PTy->getNumElements(),
1895 ConstantFP::get(PTy->getElementType(),-0.0));
1896 return ConstantVector::get(PTy, zeros);
1899 if (Ty->isFloatingPoint())
1900 return ConstantFP::get(Ty, -0.0);
1902 return Constant::getNullValue(Ty);
1905 // destroyConstant - Remove the constant from the constant table...
1907 void ConstantExpr::destroyConstant() {
1908 ExprConstants->remove(this);
1909 destroyConstantImpl();
1912 const char *ConstantExpr::getOpcodeName() const {
1913 return Instruction::getOpcodeName(getOpcode());
1916 //===----------------------------------------------------------------------===//
1917 // replaceUsesOfWithOnConstant implementations
1919 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1921 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1922 Constant *ToC = cast<Constant>(To);
1924 unsigned OperandToUpdate = U-OperandList;
1925 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1927 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
1928 Lookup.first.first = getType();
1929 Lookup.second = this;
1931 std::vector<Constant*> &Values = Lookup.first.second;
1932 Values.reserve(getNumOperands()); // Build replacement array.
1934 // Fill values with the modified operands of the constant array. Also,
1935 // compute whether this turns into an all-zeros array.
1936 bool isAllZeros = false;
1937 if (!ToC->isNullValue()) {
1938 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1939 Values.push_back(cast<Constant>(O->get()));
1942 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1943 Constant *Val = cast<Constant>(O->get());
1944 Values.push_back(Val);
1945 if (isAllZeros) isAllZeros = Val->isNullValue();
1948 Values[OperandToUpdate] = ToC;
1950 Constant *Replacement = 0;
1952 Replacement = ConstantAggregateZero::get(getType());
1954 // Check to see if we have this array type already.
1956 ArrayConstantsTy::MapTy::iterator I =
1957 ArrayConstants->InsertOrGetItem(Lookup, Exists);
1960 Replacement = I->second;
1962 // Okay, the new shape doesn't exist in the system yet. Instead of
1963 // creating a new constant array, inserting it, replaceallusesof'ing the
1964 // old with the new, then deleting the old... just update the current one
1966 ArrayConstants->MoveConstantToNewSlot(this, I);
1968 // Update to the new value.
1969 setOperand(OperandToUpdate, ToC);
1974 // Otherwise, I do need to replace this with an existing value.
1975 assert(Replacement != this && "I didn't contain From!");
1977 // Everyone using this now uses the replacement.
1978 uncheckedReplaceAllUsesWith(Replacement);
1980 // Delete the old constant!
1984 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
1986 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1987 Constant *ToC = cast<Constant>(To);
1989 unsigned OperandToUpdate = U-OperandList;
1990 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1992 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
1993 Lookup.first.first = getType();
1994 Lookup.second = this;
1995 std::vector<Constant*> &Values = Lookup.first.second;
1996 Values.reserve(getNumOperands()); // Build replacement struct.
1999 // Fill values with the modified operands of the constant struct. Also,
2000 // compute whether this turns into an all-zeros struct.
2001 bool isAllZeros = false;
2002 if (!ToC->isNullValue()) {
2003 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2004 Values.push_back(cast<Constant>(O->get()));
2007 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2008 Constant *Val = cast<Constant>(O->get());
2009 Values.push_back(Val);
2010 if (isAllZeros) isAllZeros = Val->isNullValue();
2013 Values[OperandToUpdate] = ToC;
2015 Constant *Replacement = 0;
2017 Replacement = ConstantAggregateZero::get(getType());
2019 // Check to see if we have this array type already.
2021 StructConstantsTy::MapTy::iterator I =
2022 StructConstants->InsertOrGetItem(Lookup, Exists);
2025 Replacement = I->second;
2027 // Okay, the new shape doesn't exist in the system yet. Instead of
2028 // creating a new constant struct, inserting it, replaceallusesof'ing the
2029 // old with the new, then deleting the old... just update the current one
2031 StructConstants->MoveConstantToNewSlot(this, I);
2033 // Update to the new value.
2034 setOperand(OperandToUpdate, ToC);
2039 assert(Replacement != this && "I didn't contain From!");
2041 // Everyone using this now uses the replacement.
2042 uncheckedReplaceAllUsesWith(Replacement);
2044 // Delete the old constant!
2048 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2050 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2052 std::vector<Constant*> Values;
2053 Values.reserve(getNumOperands()); // Build replacement array...
2054 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2055 Constant *Val = getOperand(i);
2056 if (Val == From) Val = cast<Constant>(To);
2057 Values.push_back(Val);
2060 Constant *Replacement = ConstantVector::get(getType(), Values);
2061 assert(Replacement != this && "I didn't contain From!");
2063 // Everyone using this now uses the replacement.
2064 uncheckedReplaceAllUsesWith(Replacement);
2066 // Delete the old constant!
2070 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2072 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2073 Constant *To = cast<Constant>(ToV);
2075 Constant *Replacement = 0;
2076 if (getOpcode() == Instruction::GetElementPtr) {
2077 SmallVector<Constant*, 8> Indices;
2078 Constant *Pointer = getOperand(0);
2079 Indices.reserve(getNumOperands()-1);
2080 if (Pointer == From) Pointer = To;
2082 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2083 Constant *Val = getOperand(i);
2084 if (Val == From) Val = To;
2085 Indices.push_back(Val);
2087 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2088 &Indices[0], Indices.size());
2089 } else if (isCast()) {
2090 assert(getOperand(0) == From && "Cast only has one use!");
2091 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2092 } else if (getOpcode() == Instruction::Select) {
2093 Constant *C1 = getOperand(0);
2094 Constant *C2 = getOperand(1);
2095 Constant *C3 = getOperand(2);
2096 if (C1 == From) C1 = To;
2097 if (C2 == From) C2 = To;
2098 if (C3 == From) C3 = To;
2099 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2100 } else if (getOpcode() == Instruction::ExtractElement) {
2101 Constant *C1 = getOperand(0);
2102 Constant *C2 = getOperand(1);
2103 if (C1 == From) C1 = To;
2104 if (C2 == From) C2 = To;
2105 Replacement = ConstantExpr::getExtractElement(C1, C2);
2106 } else if (getOpcode() == Instruction::InsertElement) {
2107 Constant *C1 = getOperand(0);
2108 Constant *C2 = getOperand(1);
2109 Constant *C3 = getOperand(1);
2110 if (C1 == From) C1 = To;
2111 if (C2 == From) C2 = To;
2112 if (C3 == From) C3 = To;
2113 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2114 } else if (getOpcode() == Instruction::ShuffleVector) {
2115 Constant *C1 = getOperand(0);
2116 Constant *C2 = getOperand(1);
2117 Constant *C3 = getOperand(2);
2118 if (C1 == From) C1 = To;
2119 if (C2 == From) C2 = To;
2120 if (C3 == From) C3 = To;
2121 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2122 } else if (isCompare()) {
2123 Constant *C1 = getOperand(0);
2124 Constant *C2 = getOperand(1);
2125 if (C1 == From) C1 = To;
2126 if (C2 == From) C2 = To;
2127 if (getOpcode() == Instruction::ICmp)
2128 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2130 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2131 } else if (getNumOperands() == 2) {
2132 Constant *C1 = getOperand(0);
2133 Constant *C2 = getOperand(1);
2134 if (C1 == From) C1 = To;
2135 if (C2 == From) C2 = To;
2136 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2138 assert(0 && "Unknown ConstantExpr type!");
2142 assert(Replacement != this && "I didn't contain From!");
2144 // Everyone using this now uses the replacement.
2145 uncheckedReplaceAllUsesWith(Replacement);
2147 // Delete the old constant!
2152 /// getStringValue - Turn an LLVM constant pointer that eventually points to a
2153 /// global into a string value. Return an empty string if we can't do it.
2154 /// Parameter Chop determines if the result is chopped at the first null
2157 std::string Constant::getStringValue(bool Chop, unsigned Offset) {
2158 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
2159 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
2160 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
2161 if (Init->isString()) {
2162 std::string Result = Init->getAsString();
2163 if (Offset < Result.size()) {
2164 // If we are pointing INTO The string, erase the beginning...
2165 Result.erase(Result.begin(), Result.begin()+Offset);
2167 // Take off the null terminator, and any string fragments after it.
2169 std::string::size_type NullPos = Result.find_first_of((char)0);
2170 if (NullPos != std::string::npos)
2171 Result.erase(Result.begin()+NullPos, Result.end());
2177 } else if (Constant *C = dyn_cast<Constant>(this)) {
2178 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
2179 return GV->getStringValue(Chop, Offset);
2180 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2181 if (CE->getOpcode() == Instruction::GetElementPtr) {
2182 // Turn a gep into the specified offset.
2183 if (CE->getNumOperands() == 3 &&
2184 cast<Constant>(CE->getOperand(1))->isNullValue() &&
2185 isa<ConstantInt>(CE->getOperand(2))) {
2186 Offset += cast<ConstantInt>(CE->getOperand(2))->getZExtValue();
2187 return CE->getOperand(0)->getStringValue(Chop, Offset);