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 "ConstantFolding.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 // Static constructor to create a '0' constant of arbitrary type...
94 Constant *Constant::getNullValue(const Type *Ty) {
95 switch (Ty->getTypeID()) {
96 case Type::IntegerTyID:
97 return ConstantInt::get(Ty, 0);
99 case Type::DoubleTyID:
100 return ConstantFP::get(Ty, 0.0);
101 case Type::PointerTyID:
102 return ConstantPointerNull::get(cast<PointerType>(Ty));
103 case Type::StructTyID:
104 case Type::ArrayTyID:
105 case Type::VectorTyID:
106 return ConstantAggregateZero::get(Ty);
108 // Function, Label, or Opaque type?
109 assert(!"Cannot create a null constant of that type!");
115 // Static constructor to create an integral constant with all bits set
116 ConstantInt *ConstantInt::getAllOnesValue(const Type *Ty) {
117 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
118 if (ITy->getBitWidth() == 1)
119 return ConstantInt::getTrue();
121 return ConstantInt::get(Ty, int64_t(-1));
125 /// @returns the value for an packed integer constant of the given type that
126 /// has all its bits set to true.
127 /// @brief Get the all ones value
128 ConstantVector *ConstantVector::getAllOnesValue(const VectorType *Ty) {
129 std::vector<Constant*> Elts;
130 Elts.resize(Ty->getNumElements(),
131 ConstantInt::getAllOnesValue(Ty->getElementType()));
132 assert(Elts[0] && "Not a packed integer type!");
133 return cast<ConstantVector>(ConstantVector::get(Elts));
137 //===----------------------------------------------------------------------===//
139 //===----------------------------------------------------------------------===//
141 ConstantInt::ConstantInt(const IntegerType *Ty, uint64_t V)
142 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
145 ConstantInt *ConstantInt::TheTrueVal = 0;
146 ConstantInt *ConstantInt::TheFalseVal = 0;
149 void CleanupTrueFalse(void *) {
150 ConstantInt::ResetTrueFalse();
154 static ManagedCleanup<llvm::CleanupTrueFalse> TrueFalseCleanup;
156 ConstantInt *ConstantInt::CreateTrueFalseVals(bool WhichOne) {
157 assert(TheTrueVal == 0 && TheFalseVal == 0);
158 TheTrueVal = get(Type::Int1Ty, 1);
159 TheFalseVal = get(Type::Int1Ty, 0);
161 // Ensure that llvm_shutdown nulls out TheTrueVal/TheFalseVal.
162 TrueFalseCleanup.Register();
164 return WhichOne ? TheTrueVal : TheFalseVal;
169 struct DenseMapInt64KeyInfo {
170 typedef std::pair<uint64_t, const Type*> KeyTy;
171 static inline KeyTy getEmptyKey() { return KeyTy(0, 0); }
172 static inline KeyTy getTombstoneKey() { return KeyTy(1, 0); }
173 static unsigned getHashValue(const KeyTy &Key) {
174 return DenseMapKeyInfo<void*>::getHashValue(Key.second) ^ Key.first;
176 static bool isPod() { return true; }
181 typedef DenseMap<DenseMapInt64KeyInfo::KeyTy, ConstantInt*,
182 DenseMapInt64KeyInfo> IntMapTy;
183 static ManagedStatic<IntMapTy> IntConstants;
185 // Get a ConstantInt from an int64_t. Note here that we canoncialize the value
186 // to a uint64_t value that has been zero extended down to the size of the
187 // integer type of the ConstantInt. This allows the getZExtValue method to
188 // just return the stored value while getSExtValue has to convert back to sign
189 // extended. getZExtValue is more common in LLVM than getSExtValue().
190 ConstantInt *ConstantInt::get(const Type *Ty, int64_t V) {
191 const IntegerType *ITy = cast<IntegerType>(Ty);
192 V &= ITy->getBitMask();
193 ConstantInt *&Slot = (*IntConstants)[std::make_pair(uint64_t(V), Ty)];
194 if (Slot) return Slot;
195 return Slot = new ConstantInt(ITy, V);
198 //===----------------------------------------------------------------------===//
200 //===----------------------------------------------------------------------===//
203 ConstantFP::ConstantFP(const Type *Ty, double V)
204 : Constant(Ty, ConstantFPVal, 0, 0) {
208 bool ConstantFP::isNullValue() const {
209 return DoubleToBits(Val) == 0;
212 bool ConstantFP::isExactlyValue(double V) const {
213 return DoubleToBits(V) == DoubleToBits(Val);
218 struct DenseMapInt32KeyInfo {
219 typedef std::pair<uint32_t, const Type*> KeyTy;
220 static inline KeyTy getEmptyKey() { return KeyTy(0, 0); }
221 static inline KeyTy getTombstoneKey() { return KeyTy(1, 0); }
222 static unsigned getHashValue(const KeyTy &Key) {
223 return DenseMapKeyInfo<void*>::getHashValue(Key.second) ^ Key.first;
225 static bool isPod() { return true; }
229 //---- ConstantFP::get() implementation...
231 typedef DenseMap<DenseMapInt32KeyInfo::KeyTy, ConstantFP*,
232 DenseMapInt32KeyInfo> FloatMapTy;
233 typedef DenseMap<DenseMapInt64KeyInfo::KeyTy, ConstantFP*,
234 DenseMapInt64KeyInfo> DoubleMapTy;
236 static ManagedStatic<FloatMapTy> FloatConstants;
237 static ManagedStatic<DoubleMapTy> DoubleConstants;
239 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
240 if (Ty == Type::FloatTy) {
241 uint32_t IntVal = FloatToBits((float)V);
243 ConstantFP *&Slot = (*FloatConstants)[std::make_pair(IntVal, Ty)];
244 if (Slot) return Slot;
245 return Slot = new ConstantFP(Ty, (float)V);
247 assert(Ty == Type::DoubleTy);
248 uint64_t IntVal = DoubleToBits(V);
249 ConstantFP *&Slot = (*DoubleConstants)[std::make_pair(IntVal, Ty)];
250 if (Slot) return Slot;
251 return Slot = new ConstantFP(Ty, V);
256 //===----------------------------------------------------------------------===//
257 // ConstantXXX Classes
258 //===----------------------------------------------------------------------===//
261 ConstantArray::ConstantArray(const ArrayType *T,
262 const std::vector<Constant*> &V)
263 : Constant(T, ConstantArrayVal, new Use[V.size()], V.size()) {
264 assert(V.size() == T->getNumElements() &&
265 "Invalid initializer vector for constant array");
266 Use *OL = OperandList;
267 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
270 assert((C->getType() == T->getElementType() ||
272 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
273 "Initializer for array element doesn't match array element type!");
278 ConstantArray::~ConstantArray() {
279 delete [] OperandList;
282 ConstantStruct::ConstantStruct(const StructType *T,
283 const std::vector<Constant*> &V)
284 : Constant(T, ConstantStructVal, new Use[V.size()], V.size()) {
285 assert(V.size() == T->getNumElements() &&
286 "Invalid initializer vector for constant structure");
287 Use *OL = OperandList;
288 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
291 assert((C->getType() == T->getElementType(I-V.begin()) ||
292 ((T->getElementType(I-V.begin())->isAbstract() ||
293 C->getType()->isAbstract()) &&
294 T->getElementType(I-V.begin())->getTypeID() ==
295 C->getType()->getTypeID())) &&
296 "Initializer for struct element doesn't match struct element type!");
301 ConstantStruct::~ConstantStruct() {
302 delete [] OperandList;
306 ConstantVector::ConstantVector(const VectorType *T,
307 const std::vector<Constant*> &V)
308 : Constant(T, ConstantVectorVal, new Use[V.size()], V.size()) {
309 Use *OL = OperandList;
310 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
313 assert((C->getType() == T->getElementType() ||
315 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
316 "Initializer for packed element doesn't match packed element type!");
321 ConstantVector::~ConstantVector() {
322 delete [] OperandList;
325 // We declare several classes private to this file, so use an anonymous
329 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
330 /// behind the scenes to implement unary constant exprs.
331 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
334 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
335 : ConstantExpr(Ty, Opcode, &Op, 1), Op(C, this) {}
338 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
339 /// behind the scenes to implement binary constant exprs.
340 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
343 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
344 : ConstantExpr(C1->getType(), Opcode, Ops, 2) {
345 Ops[0].init(C1, this);
346 Ops[1].init(C2, this);
350 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
351 /// behind the scenes to implement select constant exprs.
352 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
355 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
356 : ConstantExpr(C2->getType(), Instruction::Select, Ops, 3) {
357 Ops[0].init(C1, this);
358 Ops[1].init(C2, this);
359 Ops[2].init(C3, this);
363 /// ExtractElementConstantExpr - This class is private to
364 /// Constants.cpp, and is used behind the scenes to implement
365 /// extractelement constant exprs.
366 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
369 ExtractElementConstantExpr(Constant *C1, Constant *C2)
370 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
371 Instruction::ExtractElement, Ops, 2) {
372 Ops[0].init(C1, this);
373 Ops[1].init(C2, this);
377 /// InsertElementConstantExpr - This class is private to
378 /// Constants.cpp, and is used behind the scenes to implement
379 /// insertelement constant exprs.
380 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
383 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
384 : ConstantExpr(C1->getType(), Instruction::InsertElement,
386 Ops[0].init(C1, this);
387 Ops[1].init(C2, this);
388 Ops[2].init(C3, this);
392 /// ShuffleVectorConstantExpr - This class is private to
393 /// Constants.cpp, and is used behind the scenes to implement
394 /// shufflevector constant exprs.
395 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
398 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
399 : ConstantExpr(C1->getType(), Instruction::ShuffleVector,
401 Ops[0].init(C1, this);
402 Ops[1].init(C2, this);
403 Ops[2].init(C3, this);
407 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
408 /// used behind the scenes to implement getelementpr constant exprs.
409 struct VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
410 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
412 : ConstantExpr(DestTy, Instruction::GetElementPtr,
413 new Use[IdxList.size()+1], IdxList.size()+1) {
414 OperandList[0].init(C, this);
415 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
416 OperandList[i+1].init(IdxList[i], this);
418 ~GetElementPtrConstantExpr() {
419 delete [] OperandList;
423 // CompareConstantExpr - This class is private to Constants.cpp, and is used
424 // behind the scenes to implement ICmp and FCmp constant expressions. This is
425 // needed in order to store the predicate value for these instructions.
426 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
427 unsigned short predicate;
429 CompareConstantExpr(Instruction::OtherOps opc, unsigned short pred,
430 Constant* LHS, Constant* RHS)
431 : ConstantExpr(Type::Int1Ty, opc, Ops, 2), predicate(pred) {
432 OperandList[0].init(LHS, this);
433 OperandList[1].init(RHS, this);
437 } // end anonymous namespace
440 // Utility function for determining if a ConstantExpr is a CastOp or not. This
441 // can't be inline because we don't want to #include Instruction.h into
443 bool ConstantExpr::isCast() const {
444 return Instruction::isCast(getOpcode());
447 bool ConstantExpr::isCompare() const {
448 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
451 /// ConstantExpr::get* - Return some common constants without having to
452 /// specify the full Instruction::OPCODE identifier.
454 Constant *ConstantExpr::getNeg(Constant *C) {
455 return get(Instruction::Sub,
456 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
459 Constant *ConstantExpr::getNot(Constant *C) {
460 assert(isa<ConstantInt>(C) && "Cannot NOT a nonintegral type!");
461 return get(Instruction::Xor, C,
462 ConstantInt::getAllOnesValue(C->getType()));
464 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
465 return get(Instruction::Add, C1, C2);
467 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
468 return get(Instruction::Sub, C1, C2);
470 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
471 return get(Instruction::Mul, C1, C2);
473 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
474 return get(Instruction::UDiv, C1, C2);
476 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
477 return get(Instruction::SDiv, C1, C2);
479 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
480 return get(Instruction::FDiv, C1, C2);
482 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
483 return get(Instruction::URem, C1, C2);
485 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
486 return get(Instruction::SRem, C1, C2);
488 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
489 return get(Instruction::FRem, C1, C2);
491 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
492 return get(Instruction::And, C1, C2);
494 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
495 return get(Instruction::Or, C1, C2);
497 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
498 return get(Instruction::Xor, C1, C2);
500 unsigned ConstantExpr::getPredicate() const {
501 assert(getOpcode() == Instruction::FCmp || getOpcode() == Instruction::ICmp);
502 return dynamic_cast<const CompareConstantExpr*>(this)->predicate;
504 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
505 return get(Instruction::Shl, C1, C2);
507 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
508 return get(Instruction::LShr, C1, C2);
510 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
511 return get(Instruction::AShr, C1, C2);
514 /// getWithOperandReplaced - Return a constant expression identical to this
515 /// one, but with the specified operand set to the specified value.
517 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
518 assert(OpNo < getNumOperands() && "Operand num is out of range!");
519 assert(Op->getType() == getOperand(OpNo)->getType() &&
520 "Replacing operand with value of different type!");
521 if (getOperand(OpNo) == Op)
522 return const_cast<ConstantExpr*>(this);
524 Constant *Op0, *Op1, *Op2;
525 switch (getOpcode()) {
526 case Instruction::Trunc:
527 case Instruction::ZExt:
528 case Instruction::SExt:
529 case Instruction::FPTrunc:
530 case Instruction::FPExt:
531 case Instruction::UIToFP:
532 case Instruction::SIToFP:
533 case Instruction::FPToUI:
534 case Instruction::FPToSI:
535 case Instruction::PtrToInt:
536 case Instruction::IntToPtr:
537 case Instruction::BitCast:
538 return ConstantExpr::getCast(getOpcode(), Op, getType());
539 case Instruction::Select:
540 Op0 = (OpNo == 0) ? Op : getOperand(0);
541 Op1 = (OpNo == 1) ? Op : getOperand(1);
542 Op2 = (OpNo == 2) ? Op : getOperand(2);
543 return ConstantExpr::getSelect(Op0, Op1, Op2);
544 case Instruction::InsertElement:
545 Op0 = (OpNo == 0) ? Op : getOperand(0);
546 Op1 = (OpNo == 1) ? Op : getOperand(1);
547 Op2 = (OpNo == 2) ? Op : getOperand(2);
548 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
549 case Instruction::ExtractElement:
550 Op0 = (OpNo == 0) ? Op : getOperand(0);
551 Op1 = (OpNo == 1) ? Op : getOperand(1);
552 return ConstantExpr::getExtractElement(Op0, Op1);
553 case Instruction::ShuffleVector:
554 Op0 = (OpNo == 0) ? Op : getOperand(0);
555 Op1 = (OpNo == 1) ? Op : getOperand(1);
556 Op2 = (OpNo == 2) ? Op : getOperand(2);
557 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
558 case Instruction::GetElementPtr: {
559 SmallVector<Constant*, 8> Ops;
560 Ops.resize(getNumOperands());
561 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
562 Ops[i] = getOperand(i);
564 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
566 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
569 assert(getNumOperands() == 2 && "Must be binary operator?");
570 Op0 = (OpNo == 0) ? Op : getOperand(0);
571 Op1 = (OpNo == 1) ? Op : getOperand(1);
572 return ConstantExpr::get(getOpcode(), Op0, Op1);
576 /// getWithOperands - This returns the current constant expression with the
577 /// operands replaced with the specified values. The specified operands must
578 /// match count and type with the existing ones.
579 Constant *ConstantExpr::
580 getWithOperands(const std::vector<Constant*> &Ops) const {
581 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
582 bool AnyChange = false;
583 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
584 assert(Ops[i]->getType() == getOperand(i)->getType() &&
585 "Operand type mismatch!");
586 AnyChange |= Ops[i] != getOperand(i);
588 if (!AnyChange) // No operands changed, return self.
589 return const_cast<ConstantExpr*>(this);
591 switch (getOpcode()) {
592 case Instruction::Trunc:
593 case Instruction::ZExt:
594 case Instruction::SExt:
595 case Instruction::FPTrunc:
596 case Instruction::FPExt:
597 case Instruction::UIToFP:
598 case Instruction::SIToFP:
599 case Instruction::FPToUI:
600 case Instruction::FPToSI:
601 case Instruction::PtrToInt:
602 case Instruction::IntToPtr:
603 case Instruction::BitCast:
604 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
605 case Instruction::Select:
606 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
607 case Instruction::InsertElement:
608 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
609 case Instruction::ExtractElement:
610 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
611 case Instruction::ShuffleVector:
612 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
613 case Instruction::GetElementPtr:
614 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], Ops.size()-1);
615 case Instruction::ICmp:
616 case Instruction::FCmp:
617 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
619 assert(getNumOperands() == 2 && "Must be binary operator?");
620 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
625 //===----------------------------------------------------------------------===//
626 // isValueValidForType implementations
628 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
629 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
630 if (Ty == Type::Int1Ty)
631 return Val == 0 || Val == 1;
633 return true; // always true, has to fit in largest type
634 uint64_t Max = (1ll << NumBits) - 1;
638 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
639 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
640 if (Ty == Type::Int1Ty)
641 return Val == 0 || Val == 1 || Val == -1;
643 return true; // always true, has to fit in largest type
644 int64_t Min = -(1ll << (NumBits-1));
645 int64_t Max = (1ll << (NumBits-1)) - 1;
646 return (Val >= Min && Val <= Max);
649 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
650 switch (Ty->getTypeID()) {
652 return false; // These can't be represented as floating point!
654 // TODO: Figure out how to test if a double can be cast to a float!
655 case Type::FloatTyID:
656 case Type::DoubleTyID:
657 return true; // This is the largest type...
661 //===----------------------------------------------------------------------===//
662 // Factory Function Implementation
664 // ConstantCreator - A class that is used to create constants by
665 // ValueMap*. This class should be partially specialized if there is
666 // something strange that needs to be done to interface to the ctor for the
670 template<class ConstantClass, class TypeClass, class ValType>
671 struct VISIBILITY_HIDDEN ConstantCreator {
672 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
673 return new ConstantClass(Ty, V);
677 template<class ConstantClass, class TypeClass>
678 struct VISIBILITY_HIDDEN ConvertConstantType {
679 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
680 assert(0 && "This type cannot be converted!\n");
685 template<class ValType, class TypeClass, class ConstantClass,
686 bool HasLargeKey = false /*true for arrays and structs*/ >
687 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
689 typedef std::pair<const Type*, ValType> MapKey;
690 typedef std::map<MapKey, Constant *> MapTy;
691 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
692 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
694 /// Map - This is the main map from the element descriptor to the Constants.
695 /// This is the primary way we avoid creating two of the same shape
699 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
700 /// from the constants to their element in Map. This is important for
701 /// removal of constants from the array, which would otherwise have to scan
702 /// through the map with very large keys.
703 InverseMapTy InverseMap;
705 /// AbstractTypeMap - Map for abstract type constants.
707 AbstractTypeMapTy AbstractTypeMap;
710 typename MapTy::iterator map_end() { return Map.end(); }
712 /// InsertOrGetItem - Return an iterator for the specified element.
713 /// If the element exists in the map, the returned iterator points to the
714 /// entry and Exists=true. If not, the iterator points to the newly
715 /// inserted entry and returns Exists=false. Newly inserted entries have
716 /// I->second == 0, and should be filled in.
717 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
720 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
726 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
728 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
729 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
730 IMI->second->second == CP &&
731 "InverseMap corrupt!");
735 typename MapTy::iterator I =
736 Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
737 if (I == Map.end() || I->second != CP) {
738 // FIXME: This should not use a linear scan. If this gets to be a
739 // performance problem, someone should look at this.
740 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
747 /// getOrCreate - Return the specified constant from the map, creating it if
749 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
750 MapKey Lookup(Ty, V);
751 typename MapTy::iterator I = Map.lower_bound(Lookup);
753 if (I != Map.end() && I->first == Lookup)
754 return static_cast<ConstantClass *>(I->second);
756 // If no preexisting value, create one now...
757 ConstantClass *Result =
758 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
760 /// FIXME: why does this assert fail when loading 176.gcc?
761 //assert(Result->getType() == Ty && "Type specified is not correct!");
762 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
764 if (HasLargeKey) // Remember the reverse mapping if needed.
765 InverseMap.insert(std::make_pair(Result, I));
767 // If the type of the constant is abstract, make sure that an entry exists
768 // for it in the AbstractTypeMap.
769 if (Ty->isAbstract()) {
770 typename AbstractTypeMapTy::iterator TI =
771 AbstractTypeMap.lower_bound(Ty);
773 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
774 // Add ourselves to the ATU list of the type.
775 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
777 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
783 void remove(ConstantClass *CP) {
784 typename MapTy::iterator I = FindExistingElement(CP);
785 assert(I != Map.end() && "Constant not found in constant table!");
786 assert(I->second == CP && "Didn't find correct element?");
788 if (HasLargeKey) // Remember the reverse mapping if needed.
789 InverseMap.erase(CP);
791 // Now that we found the entry, make sure this isn't the entry that
792 // the AbstractTypeMap points to.
793 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
794 if (Ty->isAbstract()) {
795 assert(AbstractTypeMap.count(Ty) &&
796 "Abstract type not in AbstractTypeMap?");
797 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
798 if (ATMEntryIt == I) {
799 // Yes, we are removing the representative entry for this type.
800 // See if there are any other entries of the same type.
801 typename MapTy::iterator TmpIt = ATMEntryIt;
803 // First check the entry before this one...
804 if (TmpIt != Map.begin()) {
806 if (TmpIt->first.first != Ty) // Not the same type, move back...
810 // If we didn't find the same type, try to move forward...
811 if (TmpIt == ATMEntryIt) {
813 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
814 --TmpIt; // No entry afterwards with the same type
817 // If there is another entry in the map of the same abstract type,
818 // update the AbstractTypeMap entry now.
819 if (TmpIt != ATMEntryIt) {
822 // Otherwise, we are removing the last instance of this type
823 // from the table. Remove from the ATM, and from user list.
824 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
825 AbstractTypeMap.erase(Ty);
834 /// MoveConstantToNewSlot - If we are about to change C to be the element
835 /// specified by I, update our internal data structures to reflect this
837 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
838 // First, remove the old location of the specified constant in the map.
839 typename MapTy::iterator OldI = FindExistingElement(C);
840 assert(OldI != Map.end() && "Constant not found in constant table!");
841 assert(OldI->second == C && "Didn't find correct element?");
843 // If this constant is the representative element for its abstract type,
844 // update the AbstractTypeMap so that the representative element is I.
845 if (C->getType()->isAbstract()) {
846 typename AbstractTypeMapTy::iterator ATI =
847 AbstractTypeMap.find(C->getType());
848 assert(ATI != AbstractTypeMap.end() &&
849 "Abstract type not in AbstractTypeMap?");
850 if (ATI->second == OldI)
854 // Remove the old entry from the map.
857 // Update the inverse map so that we know that this constant is now
858 // located at descriptor I.
860 assert(I->second == C && "Bad inversemap entry!");
865 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
866 typename AbstractTypeMapTy::iterator I =
867 AbstractTypeMap.find(cast<Type>(OldTy));
869 assert(I != AbstractTypeMap.end() &&
870 "Abstract type not in AbstractTypeMap?");
872 // Convert a constant at a time until the last one is gone. The last one
873 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
874 // eliminated eventually.
876 ConvertConstantType<ConstantClass,
878 static_cast<ConstantClass *>(I->second->second),
879 cast<TypeClass>(NewTy));
881 I = AbstractTypeMap.find(cast<Type>(OldTy));
882 } while (I != AbstractTypeMap.end());
885 // If the type became concrete without being refined to any other existing
886 // type, we just remove ourselves from the ATU list.
887 void typeBecameConcrete(const DerivedType *AbsTy) {
888 AbsTy->removeAbstractTypeUser(this);
892 DOUT << "Constant.cpp: ValueMap\n";
899 //---- ConstantAggregateZero::get() implementation...
902 // ConstantAggregateZero does not take extra "value" argument...
903 template<class ValType>
904 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
905 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
906 return new ConstantAggregateZero(Ty);
911 struct ConvertConstantType<ConstantAggregateZero, Type> {
912 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
913 // Make everyone now use a constant of the new type...
914 Constant *New = ConstantAggregateZero::get(NewTy);
915 assert(New != OldC && "Didn't replace constant??");
916 OldC->uncheckedReplaceAllUsesWith(New);
917 OldC->destroyConstant(); // This constant is now dead, destroy it.
922 static ManagedStatic<ValueMap<char, Type,
923 ConstantAggregateZero> > AggZeroConstants;
925 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
927 Constant *ConstantAggregateZero::get(const Type *Ty) {
928 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
929 "Cannot create an aggregate zero of non-aggregate type!");
930 return AggZeroConstants->getOrCreate(Ty, 0);
933 // destroyConstant - Remove the constant from the constant table...
935 void ConstantAggregateZero::destroyConstant() {
936 AggZeroConstants->remove(this);
937 destroyConstantImpl();
940 //---- ConstantArray::get() implementation...
944 struct ConvertConstantType<ConstantArray, ArrayType> {
945 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
946 // Make everyone now use a constant of the new type...
947 std::vector<Constant*> C;
948 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
949 C.push_back(cast<Constant>(OldC->getOperand(i)));
950 Constant *New = ConstantArray::get(NewTy, C);
951 assert(New != OldC && "Didn't replace constant??");
952 OldC->uncheckedReplaceAllUsesWith(New);
953 OldC->destroyConstant(); // This constant is now dead, destroy it.
958 static std::vector<Constant*> getValType(ConstantArray *CA) {
959 std::vector<Constant*> Elements;
960 Elements.reserve(CA->getNumOperands());
961 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
962 Elements.push_back(cast<Constant>(CA->getOperand(i)));
966 typedef ValueMap<std::vector<Constant*>, ArrayType,
967 ConstantArray, true /*largekey*/> ArrayConstantsTy;
968 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
970 Constant *ConstantArray::get(const ArrayType *Ty,
971 const std::vector<Constant*> &V) {
972 // If this is an all-zero array, return a ConstantAggregateZero object
975 if (!C->isNullValue())
976 return ArrayConstants->getOrCreate(Ty, V);
977 for (unsigned i = 1, e = V.size(); i != e; ++i)
979 return ArrayConstants->getOrCreate(Ty, V);
981 return ConstantAggregateZero::get(Ty);
984 // destroyConstant - Remove the constant from the constant table...
986 void ConstantArray::destroyConstant() {
987 ArrayConstants->remove(this);
988 destroyConstantImpl();
991 /// ConstantArray::get(const string&) - Return an array that is initialized to
992 /// contain the specified string. If length is zero then a null terminator is
993 /// added to the specified string so that it may be used in a natural way.
994 /// Otherwise, the length parameter specifies how much of the string to use
995 /// and it won't be null terminated.
997 Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
998 std::vector<Constant*> ElementVals;
999 for (unsigned i = 0; i < Str.length(); ++i)
1000 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
1002 // Add a null terminator to the string...
1004 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
1007 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
1008 return ConstantArray::get(ATy, ElementVals);
1011 /// isString - This method returns true if the array is an array of i8, and
1012 /// if the elements of the array are all ConstantInt's.
1013 bool ConstantArray::isString() const {
1014 // Check the element type for i8...
1015 if (getType()->getElementType() != Type::Int8Ty)
1017 // Check the elements to make sure they are all integers, not constant
1019 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1020 if (!isa<ConstantInt>(getOperand(i)))
1025 /// isCString - This method returns true if the array is a string (see
1026 /// isString) and it ends in a null byte \0 and does not contains any other
1027 /// null bytes except its terminator.
1028 bool ConstantArray::isCString() const {
1029 // Check the element type for i8...
1030 if (getType()->getElementType() != Type::Int8Ty)
1032 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1033 // Last element must be a null.
1034 if (getOperand(getNumOperands()-1) != Zero)
1036 // Other elements must be non-null integers.
1037 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1038 if (!isa<ConstantInt>(getOperand(i)))
1040 if (getOperand(i) == Zero)
1047 // getAsString - If the sub-element type of this array is i8
1048 // then this method converts the array to an std::string and returns it.
1049 // Otherwise, it asserts out.
1051 std::string ConstantArray::getAsString() const {
1052 assert(isString() && "Not a string!");
1054 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1055 Result += (char)cast<ConstantInt>(getOperand(i))->getZExtValue();
1060 //---- ConstantStruct::get() implementation...
1065 struct ConvertConstantType<ConstantStruct, StructType> {
1066 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1067 // Make everyone now use a constant of the new type...
1068 std::vector<Constant*> C;
1069 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1070 C.push_back(cast<Constant>(OldC->getOperand(i)));
1071 Constant *New = ConstantStruct::get(NewTy, C);
1072 assert(New != OldC && "Didn't replace constant??");
1074 OldC->uncheckedReplaceAllUsesWith(New);
1075 OldC->destroyConstant(); // This constant is now dead, destroy it.
1080 typedef ValueMap<std::vector<Constant*>, StructType,
1081 ConstantStruct, true /*largekey*/> StructConstantsTy;
1082 static ManagedStatic<StructConstantsTy> StructConstants;
1084 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1085 std::vector<Constant*> Elements;
1086 Elements.reserve(CS->getNumOperands());
1087 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1088 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1092 Constant *ConstantStruct::get(const StructType *Ty,
1093 const std::vector<Constant*> &V) {
1094 // Create a ConstantAggregateZero value if all elements are zeros...
1095 for (unsigned i = 0, e = V.size(); i != e; ++i)
1096 if (!V[i]->isNullValue())
1097 return StructConstants->getOrCreate(Ty, V);
1099 return ConstantAggregateZero::get(Ty);
1102 Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
1103 std::vector<const Type*> StructEls;
1104 StructEls.reserve(V.size());
1105 for (unsigned i = 0, e = V.size(); i != e; ++i)
1106 StructEls.push_back(V[i]->getType());
1107 return get(StructType::get(StructEls, packed), V);
1110 // destroyConstant - Remove the constant from the constant table...
1112 void ConstantStruct::destroyConstant() {
1113 StructConstants->remove(this);
1114 destroyConstantImpl();
1117 //---- ConstantVector::get() implementation...
1121 struct ConvertConstantType<ConstantVector, VectorType> {
1122 static void convert(ConstantVector *OldC, const VectorType *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 = ConstantVector::get(NewTy, C);
1128 assert(New != OldC && "Didn't replace constant??");
1129 OldC->uncheckedReplaceAllUsesWith(New);
1130 OldC->destroyConstant(); // This constant is now dead, destroy it.
1135 static std::vector<Constant*> getValType(ConstantVector *CP) {
1136 std::vector<Constant*> Elements;
1137 Elements.reserve(CP->getNumOperands());
1138 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1139 Elements.push_back(CP->getOperand(i));
1143 static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
1144 ConstantVector> > VectorConstants;
1146 Constant *ConstantVector::get(const VectorType *Ty,
1147 const std::vector<Constant*> &V) {
1148 // If this is an all-zero packed, return a ConstantAggregateZero object
1151 if (!C->isNullValue())
1152 return VectorConstants->getOrCreate(Ty, V);
1153 for (unsigned i = 1, e = V.size(); i != e; ++i)
1155 return VectorConstants->getOrCreate(Ty, V);
1157 return ConstantAggregateZero::get(Ty);
1160 Constant *ConstantVector::get(const std::vector<Constant*> &V) {
1161 assert(!V.empty() && "Cannot infer type if V is empty");
1162 return get(VectorType::get(V.front()->getType(),V.size()), V);
1165 // destroyConstant - Remove the constant from the constant table...
1167 void ConstantVector::destroyConstant() {
1168 VectorConstants->remove(this);
1169 destroyConstantImpl();
1172 /// This function will return true iff every element in this packed constant
1173 /// is set to all ones.
1174 /// @returns true iff this constant's emements are all set to all ones.
1175 /// @brief Determine if the value is all ones.
1176 bool ConstantVector::isAllOnesValue() const {
1177 // Check out first element.
1178 const Constant *Elt = getOperand(0);
1179 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1180 if (!CI || !CI->isAllOnesValue()) return false;
1181 // Then make sure all remaining elements point to the same value.
1182 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1183 if (getOperand(I) != Elt) return false;
1188 //---- ConstantPointerNull::get() implementation...
1192 // ConstantPointerNull does not take extra "value" argument...
1193 template<class ValType>
1194 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1195 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1196 return new ConstantPointerNull(Ty);
1201 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1202 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1203 // Make everyone now use a constant of the new type...
1204 Constant *New = ConstantPointerNull::get(NewTy);
1205 assert(New != OldC && "Didn't replace constant??");
1206 OldC->uncheckedReplaceAllUsesWith(New);
1207 OldC->destroyConstant(); // This constant is now dead, destroy it.
1212 static ManagedStatic<ValueMap<char, PointerType,
1213 ConstantPointerNull> > NullPtrConstants;
1215 static char getValType(ConstantPointerNull *) {
1220 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1221 return NullPtrConstants->getOrCreate(Ty, 0);
1224 // destroyConstant - Remove the constant from the constant table...
1226 void ConstantPointerNull::destroyConstant() {
1227 NullPtrConstants->remove(this);
1228 destroyConstantImpl();
1232 //---- UndefValue::get() implementation...
1236 // UndefValue does not take extra "value" argument...
1237 template<class ValType>
1238 struct ConstantCreator<UndefValue, Type, ValType> {
1239 static UndefValue *create(const Type *Ty, const ValType &V) {
1240 return new UndefValue(Ty);
1245 struct ConvertConstantType<UndefValue, Type> {
1246 static void convert(UndefValue *OldC, const Type *NewTy) {
1247 // Make everyone now use a constant of the new type.
1248 Constant *New = UndefValue::get(NewTy);
1249 assert(New != OldC && "Didn't replace constant??");
1250 OldC->uncheckedReplaceAllUsesWith(New);
1251 OldC->destroyConstant(); // This constant is now dead, destroy it.
1256 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1258 static char getValType(UndefValue *) {
1263 UndefValue *UndefValue::get(const Type *Ty) {
1264 return UndefValueConstants->getOrCreate(Ty, 0);
1267 // destroyConstant - Remove the constant from the constant table.
1269 void UndefValue::destroyConstant() {
1270 UndefValueConstants->remove(this);
1271 destroyConstantImpl();
1275 //---- ConstantExpr::get() implementations...
1278 struct ExprMapKeyType {
1279 explicit ExprMapKeyType(unsigned opc, std::vector<Constant*> ops,
1280 unsigned short pred = 0) : opcode(opc), predicate(pred), operands(ops) { }
1283 std::vector<Constant*> operands;
1284 bool operator==(const ExprMapKeyType& that) const {
1285 return this->opcode == that.opcode &&
1286 this->predicate == that.predicate &&
1287 this->operands == that.operands;
1289 bool operator<(const ExprMapKeyType & that) const {
1290 return this->opcode < that.opcode ||
1291 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1292 (this->opcode == that.opcode && this->predicate == that.predicate &&
1293 this->operands < that.operands);
1296 bool operator!=(const ExprMapKeyType& that) const {
1297 return !(*this == that);
1303 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1304 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1305 unsigned short pred = 0) {
1306 if (Instruction::isCast(V.opcode))
1307 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1308 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1309 V.opcode < Instruction::BinaryOpsEnd))
1310 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1311 if (V.opcode == Instruction::Select)
1312 return new SelectConstantExpr(V.operands[0], V.operands[1],
1314 if (V.opcode == Instruction::ExtractElement)
1315 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1316 if (V.opcode == Instruction::InsertElement)
1317 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1319 if (V.opcode == Instruction::ShuffleVector)
1320 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1322 if (V.opcode == Instruction::GetElementPtr) {
1323 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1324 return new GetElementPtrConstantExpr(V.operands[0], IdxList, Ty);
1327 // The compare instructions are weird. We have to encode the predicate
1328 // value and it is combined with the instruction opcode by multiplying
1329 // the opcode by one hundred. We must decode this to get the predicate.
1330 if (V.opcode == Instruction::ICmp)
1331 return new CompareConstantExpr(Instruction::ICmp, V.predicate,
1332 V.operands[0], V.operands[1]);
1333 if (V.opcode == Instruction::FCmp)
1334 return new CompareConstantExpr(Instruction::FCmp, V.predicate,
1335 V.operands[0], V.operands[1]);
1336 assert(0 && "Invalid ConstantExpr!");
1342 struct ConvertConstantType<ConstantExpr, Type> {
1343 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1345 switch (OldC->getOpcode()) {
1346 case Instruction::Trunc:
1347 case Instruction::ZExt:
1348 case Instruction::SExt:
1349 case Instruction::FPTrunc:
1350 case Instruction::FPExt:
1351 case Instruction::UIToFP:
1352 case Instruction::SIToFP:
1353 case Instruction::FPToUI:
1354 case Instruction::FPToSI:
1355 case Instruction::PtrToInt:
1356 case Instruction::IntToPtr:
1357 case Instruction::BitCast:
1358 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1361 case Instruction::Select:
1362 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1363 OldC->getOperand(1),
1364 OldC->getOperand(2));
1367 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1368 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1369 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1370 OldC->getOperand(1));
1372 case Instruction::GetElementPtr:
1373 // Make everyone now use a constant of the new type...
1374 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1375 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1376 &Idx[0], Idx.size());
1380 assert(New != OldC && "Didn't replace constant??");
1381 OldC->uncheckedReplaceAllUsesWith(New);
1382 OldC->destroyConstant(); // This constant is now dead, destroy it.
1385 } // end namespace llvm
1388 static ExprMapKeyType getValType(ConstantExpr *CE) {
1389 std::vector<Constant*> Operands;
1390 Operands.reserve(CE->getNumOperands());
1391 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1392 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1393 return ExprMapKeyType(CE->getOpcode(), Operands,
1394 CE->isCompare() ? CE->getPredicate() : 0);
1397 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1398 ConstantExpr> > ExprConstants;
1400 /// This is a utility function to handle folding of casts and lookup of the
1401 /// cast in the ExprConstants map. It is usedby the various get* methods below.
1402 static inline Constant *getFoldedCast(
1403 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1404 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1405 // Fold a few common cases
1406 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1409 // Look up the constant in the table first to ensure uniqueness
1410 std::vector<Constant*> argVec(1, C);
1411 ExprMapKeyType Key(opc, argVec);
1412 return ExprConstants->getOrCreate(Ty, Key);
1415 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1416 Instruction::CastOps opc = Instruction::CastOps(oc);
1417 assert(Instruction::isCast(opc) && "opcode out of range");
1418 assert(C && Ty && "Null arguments to getCast");
1419 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1423 assert(0 && "Invalid cast opcode");
1425 case Instruction::Trunc: return getTrunc(C, Ty);
1426 case Instruction::ZExt: return getZExt(C, Ty);
1427 case Instruction::SExt: return getSExt(C, Ty);
1428 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1429 case Instruction::FPExt: return getFPExtend(C, Ty);
1430 case Instruction::UIToFP: return getUIToFP(C, Ty);
1431 case Instruction::SIToFP: return getSIToFP(C, Ty);
1432 case Instruction::FPToUI: return getFPToUI(C, Ty);
1433 case Instruction::FPToSI: return getFPToSI(C, Ty);
1434 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1435 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1436 case Instruction::BitCast: return getBitCast(C, Ty);
1441 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1442 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1443 return getCast(Instruction::BitCast, C, Ty);
1444 return getCast(Instruction::ZExt, C, Ty);
1447 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1448 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1449 return getCast(Instruction::BitCast, C, Ty);
1450 return getCast(Instruction::SExt, C, Ty);
1453 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1454 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1455 return getCast(Instruction::BitCast, C, Ty);
1456 return getCast(Instruction::Trunc, C, Ty);
1459 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1460 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1461 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1463 if (Ty->isInteger())
1464 return getCast(Instruction::PtrToInt, S, Ty);
1465 return getCast(Instruction::BitCast, S, Ty);
1468 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1470 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1471 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1472 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1473 Instruction::CastOps opcode =
1474 (SrcBits == DstBits ? Instruction::BitCast :
1475 (SrcBits > DstBits ? Instruction::Trunc :
1476 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1477 return getCast(opcode, C, Ty);
1480 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1481 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1483 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1484 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1485 if (SrcBits == DstBits)
1486 return C; // Avoid a useless cast
1487 Instruction::CastOps opcode =
1488 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1489 return getCast(opcode, C, Ty);
1492 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1493 assert(C->getType()->isInteger() && "Trunc operand must be integer");
1494 assert(Ty->isInteger() && "Trunc produces only integral");
1495 assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1496 "SrcTy must be larger than DestTy for Trunc!");
1498 return getFoldedCast(Instruction::Trunc, C, Ty);
1501 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1502 assert(C->getType()->isInteger() && "SEXt operand must be integral");
1503 assert(Ty->isInteger() && "SExt produces only integer");
1504 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1505 "SrcTy must be smaller than DestTy for SExt!");
1507 return getFoldedCast(Instruction::SExt, C, Ty);
1510 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1511 assert(C->getType()->isInteger() && "ZEXt operand must be integral");
1512 assert(Ty->isInteger() && "ZExt produces only integer");
1513 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1514 "SrcTy must be smaller than DestTy for ZExt!");
1516 return getFoldedCast(Instruction::ZExt, C, Ty);
1519 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1520 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1521 C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1522 "This is an illegal floating point truncation!");
1523 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1526 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1527 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1528 C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1529 "This is an illegal floating point extension!");
1530 return getFoldedCast(Instruction::FPExt, C, Ty);
1533 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1534 assert(C->getType()->isInteger() && Ty->isFloatingPoint() &&
1535 "This is an illegal i32 to floating point cast!");
1536 return getFoldedCast(Instruction::UIToFP, C, Ty);
1539 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1540 assert(C->getType()->isInteger() && Ty->isFloatingPoint() &&
1541 "This is an illegal sint to floating point cast!");
1542 return getFoldedCast(Instruction::SIToFP, C, Ty);
1545 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1546 assert(C->getType()->isFloatingPoint() && Ty->isInteger() &&
1547 "This is an illegal floating point to i32 cast!");
1548 return getFoldedCast(Instruction::FPToUI, C, Ty);
1551 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1552 assert(C->getType()->isFloatingPoint() && Ty->isInteger() &&
1553 "This is an illegal floating point to i32 cast!");
1554 return getFoldedCast(Instruction::FPToSI, C, Ty);
1557 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1558 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1559 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1560 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1563 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1564 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1565 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1566 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1569 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1570 // BitCast implies a no-op cast of type only. No bits change. However, you
1571 // can't cast pointers to anything but pointers.
1572 const Type *SrcTy = C->getType();
1573 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1574 "BitCast cannot cast pointer to non-pointer and vice versa");
1576 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1577 // or nonptr->ptr). For all the other types, the cast is okay if source and
1578 // destination bit widths are identical.
1579 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1580 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1581 assert(SrcBitSize == DstBitSize && "BitCast requies types of same width");
1582 return getFoldedCast(Instruction::BitCast, C, DstTy);
1585 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
1586 // sizeof is implemented as: (ulong) gep (Ty*)null, 1
1587 Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
1589 getGetElementPtr(getNullValue(PointerType::get(Ty)), &GEPIdx, 1);
1590 return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
1593 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1594 Constant *C1, Constant *C2) {
1595 // Check the operands for consistency first
1596 assert(Opcode >= Instruction::BinaryOpsBegin &&
1597 Opcode < Instruction::BinaryOpsEnd &&
1598 "Invalid opcode in binary constant expression");
1599 assert(C1->getType() == C2->getType() &&
1600 "Operand types in binary constant expression should match");
1602 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
1603 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1604 return FC; // Fold a few common cases...
1606 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1607 ExprMapKeyType Key(Opcode, argVec);
1608 return ExprConstants->getOrCreate(ReqTy, Key);
1611 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1612 Constant *C1, Constant *C2) {
1613 switch (predicate) {
1614 default: assert(0 && "Invalid CmpInst predicate");
1615 case FCmpInst::FCMP_FALSE: case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_OGT:
1616 case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OLE:
1617 case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_ORD: case FCmpInst::FCMP_UNO:
1618 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UGT: case FCmpInst::FCMP_UGE:
1619 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_ULE: case FCmpInst::FCMP_UNE:
1620 case FCmpInst::FCMP_TRUE:
1621 return getFCmp(predicate, C1, C2);
1622 case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGT:
1623 case ICmpInst::ICMP_UGE: case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE:
1624 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_SGE: case ICmpInst::ICMP_SLT:
1625 case ICmpInst::ICMP_SLE:
1626 return getICmp(predicate, C1, C2);
1630 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1633 case Instruction::Add:
1634 case Instruction::Sub:
1635 case Instruction::Mul:
1636 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1637 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
1638 isa<VectorType>(C1->getType())) &&
1639 "Tried to create an arithmetic operation on a non-arithmetic type!");
1641 case Instruction::UDiv:
1642 case Instruction::SDiv:
1643 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1644 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1645 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
1646 "Tried to create an arithmetic operation on a non-arithmetic type!");
1648 case Instruction::FDiv:
1649 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1650 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1651 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
1652 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1654 case Instruction::URem:
1655 case Instruction::SRem:
1656 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1657 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1658 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
1659 "Tried to create an arithmetic operation on a non-arithmetic type!");
1661 case Instruction::FRem:
1662 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1663 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1664 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
1665 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1667 case Instruction::And:
1668 case Instruction::Or:
1669 case Instruction::Xor:
1670 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1671 assert((C1->getType()->isInteger() || isa<VectorType>(C1->getType())) &&
1672 "Tried to create a logical operation on a non-integral type!");
1674 case Instruction::Shl:
1675 case Instruction::LShr:
1676 case Instruction::AShr:
1677 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1678 assert(C1->getType()->isInteger() &&
1679 "Tried to create a shift operation on a non-integer type!");
1686 return getTy(C1->getType(), Opcode, C1, C2);
1689 Constant *ConstantExpr::getCompare(unsigned short pred,
1690 Constant *C1, Constant *C2) {
1691 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1692 return getCompareTy(pred, C1, C2);
1695 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1696 Constant *V1, Constant *V2) {
1697 assert(C->getType() == Type::Int1Ty && "Select condition must be i1!");
1698 assert(V1->getType() == V2->getType() && "Select value types must match!");
1699 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1701 if (ReqTy == V1->getType())
1702 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1703 return SC; // Fold common cases
1705 std::vector<Constant*> argVec(3, C);
1708 ExprMapKeyType Key(Instruction::Select, argVec);
1709 return ExprConstants->getOrCreate(ReqTy, Key);
1712 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1715 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs, NumIdx, true) &&
1716 "GEP indices invalid!");
1718 if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs, NumIdx))
1719 return FC; // Fold a few common cases...
1721 assert(isa<PointerType>(C->getType()) &&
1722 "Non-pointer type for constant GetElementPtr expression");
1723 // Look up the constant in the table first to ensure uniqueness
1724 std::vector<Constant*> ArgVec;
1725 ArgVec.reserve(NumIdx+1);
1726 ArgVec.push_back(C);
1727 for (unsigned i = 0; i != NumIdx; ++i)
1728 ArgVec.push_back(cast<Constant>(Idxs[i]));
1729 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
1730 return ExprConstants->getOrCreate(ReqTy, Key);
1733 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1735 // Get the result type of the getelementptr!
1737 GetElementPtrInst::getIndexedType(C->getType(), Idxs, NumIdx, true);
1738 assert(Ty && "GEP indices invalid!");
1739 return getGetElementPtrTy(PointerType::get(Ty), C, Idxs, NumIdx);
1742 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1744 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1749 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1750 assert(LHS->getType() == RHS->getType());
1751 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1752 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1754 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1755 return FC; // Fold a few common cases...
1757 // Look up the constant in the table first to ensure uniqueness
1758 std::vector<Constant*> ArgVec;
1759 ArgVec.push_back(LHS);
1760 ArgVec.push_back(RHS);
1761 // Get the key type with both the opcode and predicate
1762 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1763 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1767 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1768 assert(LHS->getType() == RHS->getType());
1769 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1771 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1772 return FC; // Fold a few common cases...
1774 // Look up the constant in the table first to ensure uniqueness
1775 std::vector<Constant*> ArgVec;
1776 ArgVec.push_back(LHS);
1777 ArgVec.push_back(RHS);
1778 // Get the key type with both the opcode and predicate
1779 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1780 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1783 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1785 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1786 return FC; // Fold a few common cases...
1787 // Look up the constant in the table first to ensure uniqueness
1788 std::vector<Constant*> ArgVec(1, Val);
1789 ArgVec.push_back(Idx);
1790 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1791 return ExprConstants->getOrCreate(ReqTy, Key);
1794 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1795 assert(isa<VectorType>(Val->getType()) &&
1796 "Tried to create extractelement operation on non-vector type!");
1797 assert(Idx->getType() == Type::Int32Ty &&
1798 "Extractelement index must be i32 type!");
1799 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
1803 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1804 Constant *Elt, Constant *Idx) {
1805 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1806 return FC; // Fold a few common cases...
1807 // Look up the constant in the table first to ensure uniqueness
1808 std::vector<Constant*> ArgVec(1, Val);
1809 ArgVec.push_back(Elt);
1810 ArgVec.push_back(Idx);
1811 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1812 return ExprConstants->getOrCreate(ReqTy, Key);
1815 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1817 assert(isa<VectorType>(Val->getType()) &&
1818 "Tried to create insertelement operation on non-vector type!");
1819 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
1820 && "Insertelement types must match!");
1821 assert(Idx->getType() == Type::Int32Ty &&
1822 "Insertelement index must be i32 type!");
1823 return getInsertElementTy(cast<VectorType>(Val->getType())->getElementType(),
1827 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1828 Constant *V2, Constant *Mask) {
1829 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1830 return FC; // Fold a few common cases...
1831 // Look up the constant in the table first to ensure uniqueness
1832 std::vector<Constant*> ArgVec(1, V1);
1833 ArgVec.push_back(V2);
1834 ArgVec.push_back(Mask);
1835 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1836 return ExprConstants->getOrCreate(ReqTy, Key);
1839 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1841 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1842 "Invalid shuffle vector constant expr operands!");
1843 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
1846 Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
1847 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
1848 if (PTy->getElementType()->isFloatingPoint()) {
1849 std::vector<Constant*> zeros(PTy->getNumElements(),
1850 ConstantFP::get(PTy->getElementType(),-0.0));
1851 return ConstantVector::get(PTy, zeros);
1854 if (Ty->isFloatingPoint())
1855 return ConstantFP::get(Ty, -0.0);
1857 return Constant::getNullValue(Ty);
1860 // destroyConstant - Remove the constant from the constant table...
1862 void ConstantExpr::destroyConstant() {
1863 ExprConstants->remove(this);
1864 destroyConstantImpl();
1867 const char *ConstantExpr::getOpcodeName() const {
1868 return Instruction::getOpcodeName(getOpcode());
1871 //===----------------------------------------------------------------------===//
1872 // replaceUsesOfWithOnConstant implementations
1874 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1876 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1877 Constant *ToC = cast<Constant>(To);
1879 unsigned OperandToUpdate = U-OperandList;
1880 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1882 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
1883 Lookup.first.first = getType();
1884 Lookup.second = this;
1886 std::vector<Constant*> &Values = Lookup.first.second;
1887 Values.reserve(getNumOperands()); // Build replacement array.
1889 // Fill values with the modified operands of the constant array. Also,
1890 // compute whether this turns into an all-zeros array.
1891 bool isAllZeros = false;
1892 if (!ToC->isNullValue()) {
1893 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1894 Values.push_back(cast<Constant>(O->get()));
1897 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1898 Constant *Val = cast<Constant>(O->get());
1899 Values.push_back(Val);
1900 if (isAllZeros) isAllZeros = Val->isNullValue();
1903 Values[OperandToUpdate] = ToC;
1905 Constant *Replacement = 0;
1907 Replacement = ConstantAggregateZero::get(getType());
1909 // Check to see if we have this array type already.
1911 ArrayConstantsTy::MapTy::iterator I =
1912 ArrayConstants->InsertOrGetItem(Lookup, Exists);
1915 Replacement = I->second;
1917 // Okay, the new shape doesn't exist in the system yet. Instead of
1918 // creating a new constant array, inserting it, replaceallusesof'ing the
1919 // old with the new, then deleting the old... just update the current one
1921 ArrayConstants->MoveConstantToNewSlot(this, I);
1923 // Update to the new value.
1924 setOperand(OperandToUpdate, ToC);
1929 // Otherwise, I do need to replace this with an existing value.
1930 assert(Replacement != this && "I didn't contain From!");
1932 // Everyone using this now uses the replacement.
1933 uncheckedReplaceAllUsesWith(Replacement);
1935 // Delete the old constant!
1939 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
1941 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1942 Constant *ToC = cast<Constant>(To);
1944 unsigned OperandToUpdate = U-OperandList;
1945 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1947 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
1948 Lookup.first.first = getType();
1949 Lookup.second = this;
1950 std::vector<Constant*> &Values = Lookup.first.second;
1951 Values.reserve(getNumOperands()); // Build replacement struct.
1954 // Fill values with the modified operands of the constant struct. Also,
1955 // compute whether this turns into an all-zeros struct.
1956 bool isAllZeros = false;
1957 if (!ToC->isNullValue()) {
1958 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1959 Values.push_back(cast<Constant>(O->get()));
1962 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1963 Constant *Val = cast<Constant>(O->get());
1964 Values.push_back(Val);
1965 if (isAllZeros) isAllZeros = Val->isNullValue();
1968 Values[OperandToUpdate] = ToC;
1970 Constant *Replacement = 0;
1972 Replacement = ConstantAggregateZero::get(getType());
1974 // Check to see if we have this array type already.
1976 StructConstantsTy::MapTy::iterator I =
1977 StructConstants->InsertOrGetItem(Lookup, Exists);
1980 Replacement = I->second;
1982 // Okay, the new shape doesn't exist in the system yet. Instead of
1983 // creating a new constant struct, inserting it, replaceallusesof'ing the
1984 // old with the new, then deleting the old... just update the current one
1986 StructConstants->MoveConstantToNewSlot(this, I);
1988 // Update to the new value.
1989 setOperand(OperandToUpdate, ToC);
1994 assert(Replacement != this && "I didn't contain From!");
1996 // Everyone using this now uses the replacement.
1997 uncheckedReplaceAllUsesWith(Replacement);
1999 // Delete the old constant!
2003 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2005 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2007 std::vector<Constant*> Values;
2008 Values.reserve(getNumOperands()); // Build replacement array...
2009 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2010 Constant *Val = getOperand(i);
2011 if (Val == From) Val = cast<Constant>(To);
2012 Values.push_back(Val);
2015 Constant *Replacement = ConstantVector::get(getType(), Values);
2016 assert(Replacement != this && "I didn't contain From!");
2018 // Everyone using this now uses the replacement.
2019 uncheckedReplaceAllUsesWith(Replacement);
2021 // Delete the old constant!
2025 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2027 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2028 Constant *To = cast<Constant>(ToV);
2030 Constant *Replacement = 0;
2031 if (getOpcode() == Instruction::GetElementPtr) {
2032 SmallVector<Constant*, 8> Indices;
2033 Constant *Pointer = getOperand(0);
2034 Indices.reserve(getNumOperands()-1);
2035 if (Pointer == From) Pointer = To;
2037 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2038 Constant *Val = getOperand(i);
2039 if (Val == From) Val = To;
2040 Indices.push_back(Val);
2042 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2043 &Indices[0], Indices.size());
2044 } else if (isCast()) {
2045 assert(getOperand(0) == From && "Cast only has one use!");
2046 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2047 } else if (getOpcode() == Instruction::Select) {
2048 Constant *C1 = getOperand(0);
2049 Constant *C2 = getOperand(1);
2050 Constant *C3 = getOperand(2);
2051 if (C1 == From) C1 = To;
2052 if (C2 == From) C2 = To;
2053 if (C3 == From) C3 = To;
2054 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2055 } else if (getOpcode() == Instruction::ExtractElement) {
2056 Constant *C1 = getOperand(0);
2057 Constant *C2 = getOperand(1);
2058 if (C1 == From) C1 = To;
2059 if (C2 == From) C2 = To;
2060 Replacement = ConstantExpr::getExtractElement(C1, C2);
2061 } else if (getOpcode() == Instruction::InsertElement) {
2062 Constant *C1 = getOperand(0);
2063 Constant *C2 = getOperand(1);
2064 Constant *C3 = getOperand(1);
2065 if (C1 == From) C1 = To;
2066 if (C2 == From) C2 = To;
2067 if (C3 == From) C3 = To;
2068 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2069 } else if (getOpcode() == Instruction::ShuffleVector) {
2070 Constant *C1 = getOperand(0);
2071 Constant *C2 = getOperand(1);
2072 Constant *C3 = getOperand(2);
2073 if (C1 == From) C1 = To;
2074 if (C2 == From) C2 = To;
2075 if (C3 == From) C3 = To;
2076 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2077 } else if (isCompare()) {
2078 Constant *C1 = getOperand(0);
2079 Constant *C2 = getOperand(1);
2080 if (C1 == From) C1 = To;
2081 if (C2 == From) C2 = To;
2082 if (getOpcode() == Instruction::ICmp)
2083 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2085 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2086 } else if (getNumOperands() == 2) {
2087 Constant *C1 = getOperand(0);
2088 Constant *C2 = getOperand(1);
2089 if (C1 == From) C1 = To;
2090 if (C2 == From) C2 = To;
2091 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2093 assert(0 && "Unknown ConstantExpr type!");
2097 assert(Replacement != this && "I didn't contain From!");
2099 // Everyone using this now uses the replacement.
2100 uncheckedReplaceAllUsesWith(Replacement);
2102 // Delete the old constant!
2107 /// getStringValue - Turn an LLVM constant pointer that eventually points to a
2108 /// global into a string value. Return an empty string if we can't do it.
2109 /// Parameter Chop determines if the result is chopped at the first null
2112 std::string Constant::getStringValue(bool Chop, unsigned Offset) {
2113 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
2114 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
2115 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
2116 if (Init->isString()) {
2117 std::string Result = Init->getAsString();
2118 if (Offset < Result.size()) {
2119 // If we are pointing INTO The string, erase the beginning...
2120 Result.erase(Result.begin(), Result.begin()+Offset);
2122 // Take off the null terminator, and any string fragments after it.
2124 std::string::size_type NullPos = Result.find_first_of((char)0);
2125 if (NullPos != std::string::npos)
2126 Result.erase(Result.begin()+NullPos, Result.end());
2132 } else if (Constant *C = dyn_cast<Constant>(this)) {
2133 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
2134 return GV->getStringValue(Chop, Offset);
2135 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2136 if (CE->getOpcode() == Instruction::GetElementPtr) {
2137 // Turn a gep into the specified offset.
2138 if (CE->getNumOperands() == 3 &&
2139 cast<Constant>(CE->getOperand(1))->isNullValue() &&
2140 isa<ConstantInt>(CE->getOperand(2))) {
2141 Offset += cast<ConstantInt>(CE->getOperand(2))->getZExtValue();
2142 return CE->getOperand(0)->getStringValue(Chop, Offset);