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/SymbolTable.h"
20 #include "llvm/Module.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/Support/Compiler.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/ManagedStatic.h"
25 #include "llvm/Support/MathExtras.h"
29 //===----------------------------------------------------------------------===//
31 //===----------------------------------------------------------------------===//
33 void Constant::destroyConstantImpl() {
34 // When a Constant is destroyed, there may be lingering
35 // references to the constant by other constants in the constant pool. These
36 // constants are implicitly dependent on the module that is being deleted,
37 // but they don't know that. Because we only find out when the CPV is
38 // deleted, we must now notify all of our users (that should only be
39 // Constants) that they are, in fact, invalid now and should be deleted.
41 while (!use_empty()) {
42 Value *V = use_back();
43 #ifndef NDEBUG // Only in -g mode...
44 if (!isa<Constant>(V))
45 DOUT << "While deleting: " << *this
46 << "\n\nUse still stuck around after Def is destroyed: "
49 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
50 Constant *CV = cast<Constant>(V);
51 CV->destroyConstant();
53 // The constant should remove itself from our use list...
54 assert((use_empty() || use_back() != V) && "Constant not removed!");
57 // Value has no outstanding references it is safe to delete it now...
61 /// canTrap - Return true if evaluation of this constant could trap. This is
62 /// true for things like constant expressions that could divide by zero.
63 bool Constant::canTrap() const {
64 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
65 // The only thing that could possibly trap are constant exprs.
66 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
67 if (!CE) return false;
69 // ConstantExpr traps if any operands can trap.
70 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
71 if (getOperand(i)->canTrap())
74 // Otherwise, only specific operations can trap.
75 switch (CE->getOpcode()) {
78 case Instruction::UDiv:
79 case Instruction::SDiv:
80 case Instruction::FDiv:
81 case Instruction::URem:
82 case Instruction::SRem:
83 case Instruction::FRem:
84 // Div and rem can trap if the RHS is not known to be non-zero.
85 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
92 // Static constructor to create a '0' constant of arbitrary type...
93 Constant *Constant::getNullValue(const Type *Ty) {
94 switch (Ty->getTypeID()) {
95 case Type::BoolTyID: {
96 static Constant *NullBool = ConstantBool::get(false);
99 case Type::SByteTyID: {
100 static Constant *NullSByte = ConstantInt::get(Type::SByteTy, 0);
103 case Type::UByteTyID: {
104 static Constant *NullUByte = ConstantInt::get(Type::UByteTy, 0);
107 case Type::ShortTyID: {
108 static Constant *NullShort = ConstantInt::get(Type::ShortTy, 0);
111 case Type::UShortTyID: {
112 static Constant *NullUShort = ConstantInt::get(Type::UShortTy, 0);
115 case Type::IntTyID: {
116 static Constant *NullInt = ConstantInt::get(Type::IntTy, 0);
119 case Type::UIntTyID: {
120 static Constant *NullUInt = ConstantInt::get(Type::UIntTy, 0);
123 case Type::LongTyID: {
124 static Constant *NullLong = ConstantInt::get(Type::LongTy, 0);
127 case Type::ULongTyID: {
128 static Constant *NullULong = ConstantInt::get(Type::ULongTy, 0);
132 case Type::FloatTyID: {
133 static Constant *NullFloat = ConstantFP::get(Type::FloatTy, 0);
136 case Type::DoubleTyID: {
137 static Constant *NullDouble = ConstantFP::get(Type::DoubleTy, 0);
141 case Type::PointerTyID:
142 return ConstantPointerNull::get(cast<PointerType>(Ty));
144 case Type::StructTyID:
145 case Type::ArrayTyID:
146 case Type::PackedTyID:
147 return ConstantAggregateZero::get(Ty);
149 // Function, Label, or Opaque type?
150 assert(!"Cannot create a null constant of that type!");
155 // Static constructor to create the maximum constant of an integral type...
156 ConstantIntegral *ConstantIntegral::getMaxValue(const Type *Ty) {
157 switch (Ty->getTypeID()) {
158 case Type::BoolTyID: return ConstantBool::getTrue();
159 case Type::SByteTyID:
160 case Type::ShortTyID:
162 case Type::LongTyID: {
163 // Calculate 011111111111111...
164 unsigned TypeBits = Ty->getPrimitiveSize()*8;
165 int64_t Val = INT64_MAX; // All ones
166 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
167 return ConstantInt::get(Ty, Val);
170 case Type::UByteTyID:
171 case Type::UShortTyID:
173 case Type::ULongTyID: return getAllOnesValue(Ty);
179 // Static constructor to create the minimum constant for an integral type...
180 ConstantIntegral *ConstantIntegral::getMinValue(const Type *Ty) {
181 switch (Ty->getTypeID()) {
182 case Type::BoolTyID: return ConstantBool::getFalse();
183 case Type::SByteTyID:
184 case Type::ShortTyID:
186 case Type::LongTyID: {
187 // Calculate 1111111111000000000000
188 unsigned TypeBits = Ty->getPrimitiveSize()*8;
189 int64_t Val = -1; // All ones
190 Val <<= TypeBits-1; // Shift over to the right spot
191 return ConstantInt::get(Ty, Val);
194 case Type::UByteTyID:
195 case Type::UShortTyID:
197 case Type::ULongTyID: return ConstantInt::get(Ty, 0);
203 // Static constructor to create an integral constant with all bits set
204 ConstantIntegral *ConstantIntegral::getAllOnesValue(const Type *Ty) {
205 switch (Ty->getTypeID()) {
206 case Type::BoolTyID: return ConstantBool::getTrue();
207 case Type::SByteTyID:
208 case Type::ShortTyID:
210 case Type::LongTyID: return ConstantInt::get(Ty, -1);
212 case Type::UByteTyID:
213 case Type::UShortTyID:
215 case Type::ULongTyID: {
216 // Calculate ~0 of the right type...
217 unsigned TypeBits = Ty->getPrimitiveSize()*8;
218 uint64_t Val = ~0ULL; // All ones
219 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
220 return ConstantInt::get(Ty, Val);
226 //===----------------------------------------------------------------------===//
227 // ConstantXXX Classes
228 //===----------------------------------------------------------------------===//
230 //===----------------------------------------------------------------------===//
231 // Normal Constructors
233 ConstantIntegral::ConstantIntegral(const Type *Ty, ValueTy VT, uint64_t V)
234 : Constant(Ty, VT, 0, 0), Val(V) {
237 ConstantBool::ConstantBool(bool V)
238 : ConstantIntegral(Type::BoolTy, ConstantBoolVal, uint64_t(V)) {
241 ConstantInt::ConstantInt(const Type *Ty, uint64_t V)
242 : ConstantIntegral(Ty, ConstantIntVal, V) {
245 ConstantFP::ConstantFP(const Type *Ty, double V)
246 : Constant(Ty, ConstantFPVal, 0, 0) {
247 assert(isValueValidForType(Ty, V) && "Value too large for type!");
251 ConstantArray::ConstantArray(const ArrayType *T,
252 const std::vector<Constant*> &V)
253 : Constant(T, ConstantArrayVal, new Use[V.size()], V.size()) {
254 assert(V.size() == T->getNumElements() &&
255 "Invalid initializer vector for constant array");
256 Use *OL = OperandList;
257 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
260 assert((C->getType() == T->getElementType() ||
262 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
263 "Initializer for array element doesn't match array element type!");
268 ConstantArray::~ConstantArray() {
269 delete [] OperandList;
272 ConstantStruct::ConstantStruct(const StructType *T,
273 const std::vector<Constant*> &V)
274 : Constant(T, ConstantStructVal, new Use[V.size()], V.size()) {
275 assert(V.size() == T->getNumElements() &&
276 "Invalid initializer vector for constant structure");
277 Use *OL = OperandList;
278 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
281 assert((C->getType() == T->getElementType(I-V.begin()) ||
282 ((T->getElementType(I-V.begin())->isAbstract() ||
283 C->getType()->isAbstract()) &&
284 T->getElementType(I-V.begin())->getTypeID() ==
285 C->getType()->getTypeID())) &&
286 "Initializer for struct element doesn't match struct element type!");
291 ConstantStruct::~ConstantStruct() {
292 delete [] OperandList;
296 ConstantPacked::ConstantPacked(const PackedType *T,
297 const std::vector<Constant*> &V)
298 : Constant(T, ConstantPackedVal, new Use[V.size()], V.size()) {
299 Use *OL = OperandList;
300 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
303 assert((C->getType() == T->getElementType() ||
305 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
306 "Initializer for packed element doesn't match packed element type!");
311 ConstantPacked::~ConstantPacked() {
312 delete [] OperandList;
315 static bool isSetCC(unsigned Opcode) {
316 return Opcode == Instruction::SetEQ || Opcode == Instruction::SetNE ||
317 Opcode == Instruction::SetLT || Opcode == Instruction::SetGT ||
318 Opcode == Instruction::SetLE || Opcode == Instruction::SetGE;
321 // We declare several classes private to this file, so use an anonymous
325 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
326 /// behind the scenes to implement unary constant exprs.
327 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
330 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
331 : ConstantExpr(Ty, Opcode, &Op, 1), Op(C, this) {}
334 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
335 /// behind the scenes to implement binary constant exprs.
336 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
339 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
340 : ConstantExpr(isSetCC(Opcode) ? Type::BoolTy : C1->getType(),
342 Ops[0].init(C1, this);
343 Ops[1].init(C2, this);
347 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
348 /// behind the scenes to implement select constant exprs.
349 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
352 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
353 : ConstantExpr(C2->getType(), Instruction::Select, Ops, 3) {
354 Ops[0].init(C1, this);
355 Ops[1].init(C2, this);
356 Ops[2].init(C3, this);
360 /// ExtractElementConstantExpr - This class is private to
361 /// Constants.cpp, and is used behind the scenes to implement
362 /// extractelement constant exprs.
363 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
366 ExtractElementConstantExpr(Constant *C1, Constant *C2)
367 : ConstantExpr(cast<PackedType>(C1->getType())->getElementType(),
368 Instruction::ExtractElement, Ops, 2) {
369 Ops[0].init(C1, this);
370 Ops[1].init(C2, this);
374 /// InsertElementConstantExpr - This class is private to
375 /// Constants.cpp, and is used behind the scenes to implement
376 /// insertelement constant exprs.
377 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
380 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
381 : ConstantExpr(C1->getType(), Instruction::InsertElement,
383 Ops[0].init(C1, this);
384 Ops[1].init(C2, this);
385 Ops[2].init(C3, this);
389 /// ShuffleVectorConstantExpr - This class is private to
390 /// Constants.cpp, and is used behind the scenes to implement
391 /// shufflevector constant exprs.
392 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
395 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
396 : ConstantExpr(C1->getType(), Instruction::ShuffleVector,
398 Ops[0].init(C1, this);
399 Ops[1].init(C2, this);
400 Ops[2].init(C3, this);
404 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
405 /// used behind the scenes to implement getelementpr constant exprs.
406 struct VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
407 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
409 : ConstantExpr(DestTy, Instruction::GetElementPtr,
410 new Use[IdxList.size()+1], IdxList.size()+1) {
411 OperandList[0].init(C, this);
412 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
413 OperandList[i+1].init(IdxList[i], this);
415 ~GetElementPtrConstantExpr() {
416 delete [] OperandList;
420 // CompareConstantExpr - This class is private to Constants.cpp, and is used
421 // behind the scenes to implement ICmp and FCmp constant expressions. This is
422 // needed in order to store the predicate value for these instructions.
423 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
424 unsigned short predicate;
426 CompareConstantExpr(Instruction::OtherOps opc, unsigned short pred,
427 Constant* LHS, Constant* RHS)
428 : ConstantExpr(Type::BoolTy, Instruction::OtherOps(opc), Ops, 2),
430 OperandList[0].init(LHS, this);
431 OperandList[1].init(RHS, this);
435 } // end anonymous namespace
438 // Utility function for determining if a ConstantExpr is a CastOp or not. This
439 // can't be inline because we don't want to #include Instruction.h into
441 bool ConstantExpr::isCast() const {
442 return Instruction::isCast(getOpcode());
445 bool ConstantExpr::isCompare() const {
446 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
449 /// ConstantExpr::get* - Return some common constants without having to
450 /// specify the full Instruction::OPCODE identifier.
452 Constant *ConstantExpr::getNeg(Constant *C) {
453 if (!C->getType()->isFloatingPoint())
454 return get(Instruction::Sub, getNullValue(C->getType()), C);
456 return get(Instruction::Sub, ConstantFP::get(C->getType(), -0.0), C);
458 Constant *ConstantExpr::getNot(Constant *C) {
459 assert(isa<ConstantIntegral>(C) && "Cannot NOT a nonintegral type!");
460 return get(Instruction::Xor, C,
461 ConstantIntegral::getAllOnesValue(C->getType()));
463 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
464 return get(Instruction::Add, C1, C2);
466 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
467 return get(Instruction::Sub, C1, C2);
469 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
470 return get(Instruction::Mul, C1, C2);
472 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
473 return get(Instruction::UDiv, C1, C2);
475 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
476 return get(Instruction::SDiv, C1, C2);
478 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
479 return get(Instruction::FDiv, C1, C2);
481 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
482 return get(Instruction::URem, C1, C2);
484 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
485 return get(Instruction::SRem, C1, C2);
487 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
488 return get(Instruction::FRem, C1, C2);
490 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
491 return get(Instruction::And, C1, C2);
493 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
494 return get(Instruction::Or, C1, C2);
496 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
497 return get(Instruction::Xor, C1, C2);
499 Constant *ConstantExpr::getSetEQ(Constant *C1, Constant *C2) {
500 return get(Instruction::SetEQ, C1, C2);
502 Constant *ConstantExpr::getSetNE(Constant *C1, Constant *C2) {
503 return get(Instruction::SetNE, C1, C2);
505 Constant *ConstantExpr::getSetLT(Constant *C1, Constant *C2) {
506 return get(Instruction::SetLT, C1, C2);
508 Constant *ConstantExpr::getSetGT(Constant *C1, Constant *C2) {
509 return get(Instruction::SetGT, C1, C2);
511 Constant *ConstantExpr::getSetLE(Constant *C1, Constant *C2) {
512 return get(Instruction::SetLE, C1, C2);
514 Constant *ConstantExpr::getSetGE(Constant *C1, Constant *C2) {
515 return get(Instruction::SetGE, C1, C2);
517 unsigned ConstantExpr::getPredicate() const {
518 assert(getOpcode() == Instruction::FCmp || getOpcode() == Instruction::ICmp);
519 return dynamic_cast<const CompareConstantExpr*>(this)->predicate;
521 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
522 return get(Instruction::Shl, C1, C2);
524 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
525 return get(Instruction::LShr, C1, C2);
527 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
528 return get(Instruction::AShr, C1, C2);
531 /// getWithOperandReplaced - Return a constant expression identical to this
532 /// one, but with the specified operand set to the specified value.
534 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
535 assert(OpNo < getNumOperands() && "Operand num is out of range!");
536 assert(Op->getType() == getOperand(OpNo)->getType() &&
537 "Replacing operand with value of different type!");
538 if (getOperand(OpNo) == Op)
539 return const_cast<ConstantExpr*>(this);
541 Constant *Op0, *Op1, *Op2;
542 switch (getOpcode()) {
543 case Instruction::Trunc:
544 case Instruction::ZExt:
545 case Instruction::SExt:
546 case Instruction::FPTrunc:
547 case Instruction::FPExt:
548 case Instruction::UIToFP:
549 case Instruction::SIToFP:
550 case Instruction::FPToUI:
551 case Instruction::FPToSI:
552 case Instruction::PtrToInt:
553 case Instruction::IntToPtr:
554 case Instruction::BitCast:
555 return ConstantExpr::getCast(getOpcode(), Op, getType());
556 case Instruction::Select:
557 Op0 = (OpNo == 0) ? Op : getOperand(0);
558 Op1 = (OpNo == 1) ? Op : getOperand(1);
559 Op2 = (OpNo == 2) ? Op : getOperand(2);
560 return ConstantExpr::getSelect(Op0, Op1, Op2);
561 case Instruction::InsertElement:
562 Op0 = (OpNo == 0) ? Op : getOperand(0);
563 Op1 = (OpNo == 1) ? Op : getOperand(1);
564 Op2 = (OpNo == 2) ? Op : getOperand(2);
565 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
566 case Instruction::ExtractElement:
567 Op0 = (OpNo == 0) ? Op : getOperand(0);
568 Op1 = (OpNo == 1) ? Op : getOperand(1);
569 return ConstantExpr::getExtractElement(Op0, Op1);
570 case Instruction::ShuffleVector:
571 Op0 = (OpNo == 0) ? Op : getOperand(0);
572 Op1 = (OpNo == 1) ? Op : getOperand(1);
573 Op2 = (OpNo == 2) ? Op : getOperand(2);
574 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
575 case Instruction::GetElementPtr: {
576 std::vector<Constant*> Ops;
577 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
578 Ops.push_back(getOperand(i));
580 return ConstantExpr::getGetElementPtr(Op, Ops);
582 return ConstantExpr::getGetElementPtr(getOperand(0), Ops);
585 assert(getNumOperands() == 2 && "Must be binary operator?");
586 Op0 = (OpNo == 0) ? Op : getOperand(0);
587 Op1 = (OpNo == 1) ? Op : getOperand(1);
588 return ConstantExpr::get(getOpcode(), Op0, Op1);
592 /// getWithOperands - This returns the current constant expression with the
593 /// operands replaced with the specified values. The specified operands must
594 /// match count and type with the existing ones.
595 Constant *ConstantExpr::
596 getWithOperands(const std::vector<Constant*> &Ops) const {
597 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
598 bool AnyChange = false;
599 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
600 assert(Ops[i]->getType() == getOperand(i)->getType() &&
601 "Operand type mismatch!");
602 AnyChange |= Ops[i] != getOperand(i);
604 if (!AnyChange) // No operands changed, return self.
605 return const_cast<ConstantExpr*>(this);
607 switch (getOpcode()) {
608 case Instruction::Trunc:
609 case Instruction::ZExt:
610 case Instruction::SExt:
611 case Instruction::FPTrunc:
612 case Instruction::FPExt:
613 case Instruction::UIToFP:
614 case Instruction::SIToFP:
615 case Instruction::FPToUI:
616 case Instruction::FPToSI:
617 case Instruction::PtrToInt:
618 case Instruction::IntToPtr:
619 case Instruction::BitCast:
620 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
621 case Instruction::Select:
622 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
623 case Instruction::InsertElement:
624 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
625 case Instruction::ExtractElement:
626 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
627 case Instruction::ShuffleVector:
628 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
629 case Instruction::GetElementPtr: {
630 std::vector<Constant*> ActualOps(Ops.begin()+1, Ops.end());
631 return ConstantExpr::getGetElementPtr(Ops[0], ActualOps);
634 assert(getNumOperands() == 2 && "Must be binary operator?");
635 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
640 //===----------------------------------------------------------------------===//
641 // isValueValidForType implementations
643 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
644 switch (Ty->getTypeID()) {
646 return false; // These can't be represented as integers!!!
648 case Type::SByteTyID:
649 return (Val <= INT8_MAX && Val >= INT8_MIN);
650 case Type::UByteTyID:
651 return (Val >= 0) && (Val <= UINT8_MAX);
652 case Type::ShortTyID:
653 return (Val <= INT16_MAX && Val >= INT16_MIN);
654 case Type::UShortTyID:
655 return (Val >= 0) && (Val <= UINT16_MAX);
657 return (Val <= int(INT32_MAX) && Val >= int(INT32_MIN));
659 return (Val >= 0) && (Val <= UINT32_MAX);
661 case Type::ULongTyID:
662 return true; // always true, has to fit in largest type
666 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
667 switch (Ty->getTypeID()) {
669 return false; // These can't be represented as floating point!
671 // TODO: Figure out how to test if a double can be cast to a float!
672 case Type::FloatTyID:
673 case Type::DoubleTyID:
674 return true; // This is the largest type...
678 //===----------------------------------------------------------------------===//
679 // Factory Function Implementation
681 // ConstantCreator - A class that is used to create constants by
682 // ValueMap*. This class should be partially specialized if there is
683 // something strange that needs to be done to interface to the ctor for the
687 template<class ConstantClass, class TypeClass, class ValType>
688 struct VISIBILITY_HIDDEN ConstantCreator {
689 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
690 return new ConstantClass(Ty, V);
694 template<class ConstantClass, class TypeClass>
695 struct VISIBILITY_HIDDEN ConvertConstantType {
696 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
697 assert(0 && "This type cannot be converted!\n");
702 template<class ValType, class TypeClass, class ConstantClass,
703 bool HasLargeKey = false /*true for arrays and structs*/ >
704 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
706 typedef std::pair<const Type*, ValType> MapKey;
707 typedef std::map<MapKey, Constant *> MapTy;
708 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
709 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
711 /// Map - This is the main map from the element descriptor to the Constants.
712 /// This is the primary way we avoid creating two of the same shape
716 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
717 /// from the constants to their element in Map. This is important for
718 /// removal of constants from the array, which would otherwise have to scan
719 /// through the map with very large keys.
720 InverseMapTy InverseMap;
722 /// AbstractTypeMap - Map for abstract type constants.
724 AbstractTypeMapTy AbstractTypeMap;
727 void clear(std::vector<Constant *> &Constants) {
728 for(typename MapTy::iterator I = Map.begin(); I != Map.end(); ++I)
729 Constants.push_back(I->second);
731 AbstractTypeMap.clear();
736 typename MapTy::iterator map_end() { return Map.end(); }
738 /// InsertOrGetItem - Return an iterator for the specified element.
739 /// If the element exists in the map, the returned iterator points to the
740 /// entry and Exists=true. If not, the iterator points to the newly
741 /// inserted entry and returns Exists=false. Newly inserted entries have
742 /// I->second == 0, and should be filled in.
743 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
746 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
752 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
754 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
755 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
756 IMI->second->second == CP &&
757 "InverseMap corrupt!");
761 typename MapTy::iterator I =
762 Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
763 if (I == Map.end() || I->second != CP) {
764 // FIXME: This should not use a linear scan. If this gets to be a
765 // performance problem, someone should look at this.
766 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
773 /// getOrCreate - Return the specified constant from the map, creating it if
775 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
776 MapKey Lookup(Ty, V);
777 typename MapTy::iterator I = Map.lower_bound(Lookup);
779 if (I != Map.end() && I->first == Lookup)
780 return static_cast<ConstantClass *>(I->second);
782 // If no preexisting value, create one now...
783 ConstantClass *Result =
784 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
786 /// FIXME: why does this assert fail when loading 176.gcc?
787 //assert(Result->getType() == Ty && "Type specified is not correct!");
788 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
790 if (HasLargeKey) // Remember the reverse mapping if needed.
791 InverseMap.insert(std::make_pair(Result, I));
793 // If the type of the constant is abstract, make sure that an entry exists
794 // for it in the AbstractTypeMap.
795 if (Ty->isAbstract()) {
796 typename AbstractTypeMapTy::iterator TI =
797 AbstractTypeMap.lower_bound(Ty);
799 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
800 // Add ourselves to the ATU list of the type.
801 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
803 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
809 void remove(ConstantClass *CP) {
810 typename MapTy::iterator I = FindExistingElement(CP);
811 assert(I != Map.end() && "Constant not found in constant table!");
812 assert(I->second == CP && "Didn't find correct element?");
814 if (HasLargeKey) // Remember the reverse mapping if needed.
815 InverseMap.erase(CP);
817 // Now that we found the entry, make sure this isn't the entry that
818 // the AbstractTypeMap points to.
819 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
820 if (Ty->isAbstract()) {
821 assert(AbstractTypeMap.count(Ty) &&
822 "Abstract type not in AbstractTypeMap?");
823 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
824 if (ATMEntryIt == I) {
825 // Yes, we are removing the representative entry for this type.
826 // See if there are any other entries of the same type.
827 typename MapTy::iterator TmpIt = ATMEntryIt;
829 // First check the entry before this one...
830 if (TmpIt != Map.begin()) {
832 if (TmpIt->first.first != Ty) // Not the same type, move back...
836 // If we didn't find the same type, try to move forward...
837 if (TmpIt == ATMEntryIt) {
839 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
840 --TmpIt; // No entry afterwards with the same type
843 // If there is another entry in the map of the same abstract type,
844 // update the AbstractTypeMap entry now.
845 if (TmpIt != ATMEntryIt) {
848 // Otherwise, we are removing the last instance of this type
849 // from the table. Remove from the ATM, and from user list.
850 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
851 AbstractTypeMap.erase(Ty);
860 /// MoveConstantToNewSlot - If we are about to change C to be the element
861 /// specified by I, update our internal data structures to reflect this
863 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
864 // First, remove the old location of the specified constant in the map.
865 typename MapTy::iterator OldI = FindExistingElement(C);
866 assert(OldI != Map.end() && "Constant not found in constant table!");
867 assert(OldI->second == C && "Didn't find correct element?");
869 // If this constant is the representative element for its abstract type,
870 // update the AbstractTypeMap so that the representative element is I.
871 if (C->getType()->isAbstract()) {
872 typename AbstractTypeMapTy::iterator ATI =
873 AbstractTypeMap.find(C->getType());
874 assert(ATI != AbstractTypeMap.end() &&
875 "Abstract type not in AbstractTypeMap?");
876 if (ATI->second == OldI)
880 // Remove the old entry from the map.
883 // Update the inverse map so that we know that this constant is now
884 // located at descriptor I.
886 assert(I->second == C && "Bad inversemap entry!");
891 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
892 typename AbstractTypeMapTy::iterator I =
893 AbstractTypeMap.find(cast<Type>(OldTy));
895 assert(I != AbstractTypeMap.end() &&
896 "Abstract type not in AbstractTypeMap?");
898 // Convert a constant at a time until the last one is gone. The last one
899 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
900 // eliminated eventually.
902 ConvertConstantType<ConstantClass,
904 static_cast<ConstantClass *>(I->second->second),
905 cast<TypeClass>(NewTy));
907 I = AbstractTypeMap.find(cast<Type>(OldTy));
908 } while (I != AbstractTypeMap.end());
911 // If the type became concrete without being refined to any other existing
912 // type, we just remove ourselves from the ATU list.
913 void typeBecameConcrete(const DerivedType *AbsTy) {
914 AbsTy->removeAbstractTypeUser(this);
918 DOUT << "Constant.cpp: ValueMap\n";
924 //---- ConstantBool::get*() implementation.
926 ConstantBool *ConstantBool::getTrue() {
927 static ConstantBool *T = 0;
929 return T = new ConstantBool(true);
931 ConstantBool *ConstantBool::getFalse() {
932 static ConstantBool *F = 0;
934 return F = new ConstantBool(false);
937 //---- ConstantInt::get() implementations...
939 static ManagedStatic<ValueMap<uint64_t, Type, ConstantInt> > IntConstants;
941 // Get a ConstantInt from an int64_t. Note here that we canoncialize the value
942 // to a uint64_t value that has been zero extended down to the size of the
943 // integer type of the ConstantInt. This allows the getZExtValue method to
944 // just return the stored value while getSExtValue has to convert back to sign
945 // extended. getZExtValue is more common in LLVM than getSExtValue().
946 ConstantInt *ConstantInt::get(const Type *Ty, int64_t V) {
947 return IntConstants->getOrCreate(Ty, V & Ty->getIntegralTypeMask());
950 ConstantIntegral *ConstantIntegral::get(const Type *Ty, int64_t V) {
951 if (Ty == Type::BoolTy) return ConstantBool::get(V&1);
952 return IntConstants->getOrCreate(Ty, V & Ty->getIntegralTypeMask());
955 //---- ConstantFP::get() implementation...
959 struct ConstantCreator<ConstantFP, Type, uint64_t> {
960 static ConstantFP *create(const Type *Ty, uint64_t V) {
961 assert(Ty == Type::DoubleTy);
962 return new ConstantFP(Ty, BitsToDouble(V));
966 struct ConstantCreator<ConstantFP, Type, uint32_t> {
967 static ConstantFP *create(const Type *Ty, uint32_t V) {
968 assert(Ty == Type::FloatTy);
969 return new ConstantFP(Ty, BitsToFloat(V));
974 static ManagedStatic<ValueMap<uint64_t, Type, ConstantFP> > DoubleConstants;
975 static ManagedStatic<ValueMap<uint32_t, Type, ConstantFP> > FloatConstants;
977 bool ConstantFP::isNullValue() const {
978 return DoubleToBits(Val) == 0;
981 bool ConstantFP::isExactlyValue(double V) const {
982 return DoubleToBits(V) == DoubleToBits(Val);
986 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
987 if (Ty == Type::FloatTy) {
988 // Force the value through memory to normalize it.
989 return FloatConstants->getOrCreate(Ty, FloatToBits(V));
991 assert(Ty == Type::DoubleTy);
992 return DoubleConstants->getOrCreate(Ty, DoubleToBits(V));
996 //---- ConstantAggregateZero::get() implementation...
999 // ConstantAggregateZero does not take extra "value" argument...
1000 template<class ValType>
1001 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
1002 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
1003 return new ConstantAggregateZero(Ty);
1008 struct ConvertConstantType<ConstantAggregateZero, Type> {
1009 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1010 // Make everyone now use a constant of the new type...
1011 Constant *New = ConstantAggregateZero::get(NewTy);
1012 assert(New != OldC && "Didn't replace constant??");
1013 OldC->uncheckedReplaceAllUsesWith(New);
1014 OldC->destroyConstant(); // This constant is now dead, destroy it.
1019 static ManagedStatic<ValueMap<char, Type,
1020 ConstantAggregateZero> > AggZeroConstants;
1022 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1024 Constant *ConstantAggregateZero::get(const Type *Ty) {
1025 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<PackedType>(Ty)) &&
1026 "Cannot create an aggregate zero of non-aggregate type!");
1027 return AggZeroConstants->getOrCreate(Ty, 0);
1030 // destroyConstant - Remove the constant from the constant table...
1032 void ConstantAggregateZero::destroyConstant() {
1033 AggZeroConstants->remove(this);
1034 destroyConstantImpl();
1037 //---- ConstantArray::get() implementation...
1041 struct ConvertConstantType<ConstantArray, ArrayType> {
1042 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1043 // Make everyone now use a constant of the new type...
1044 std::vector<Constant*> C;
1045 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1046 C.push_back(cast<Constant>(OldC->getOperand(i)));
1047 Constant *New = ConstantArray::get(NewTy, C);
1048 assert(New != OldC && "Didn't replace constant??");
1049 OldC->uncheckedReplaceAllUsesWith(New);
1050 OldC->destroyConstant(); // This constant is now dead, destroy it.
1055 static std::vector<Constant*> getValType(ConstantArray *CA) {
1056 std::vector<Constant*> Elements;
1057 Elements.reserve(CA->getNumOperands());
1058 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1059 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1063 typedef ValueMap<std::vector<Constant*>, ArrayType,
1064 ConstantArray, true /*largekey*/> ArrayConstantsTy;
1065 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
1067 Constant *ConstantArray::get(const ArrayType *Ty,
1068 const std::vector<Constant*> &V) {
1069 // If this is an all-zero array, return a ConstantAggregateZero object
1072 if (!C->isNullValue())
1073 return ArrayConstants->getOrCreate(Ty, V);
1074 for (unsigned i = 1, e = V.size(); i != e; ++i)
1076 return ArrayConstants->getOrCreate(Ty, V);
1078 return ConstantAggregateZero::get(Ty);
1081 // destroyConstant - Remove the constant from the constant table...
1083 void ConstantArray::destroyConstant() {
1084 ArrayConstants->remove(this);
1085 destroyConstantImpl();
1088 /// ConstantArray::get(const string&) - Return an array that is initialized to
1089 /// contain the specified string. If length is zero then a null terminator is
1090 /// added to the specified string so that it may be used in a natural way.
1091 /// Otherwise, the length parameter specifies how much of the string to use
1092 /// and it won't be null terminated.
1094 Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
1095 std::vector<Constant*> ElementVals;
1096 for (unsigned i = 0; i < Str.length(); ++i)
1097 ElementVals.push_back(ConstantInt::get(Type::SByteTy, Str[i]));
1099 // Add a null terminator to the string...
1101 ElementVals.push_back(ConstantInt::get(Type::SByteTy, 0));
1104 ArrayType *ATy = ArrayType::get(Type::SByteTy, ElementVals.size());
1105 return ConstantArray::get(ATy, ElementVals);
1108 /// isString - This method returns true if the array is an array of sbyte or
1109 /// ubyte, and if the elements of the array are all ConstantInt's.
1110 bool ConstantArray::isString() const {
1111 // Check the element type for sbyte or ubyte...
1112 if (getType()->getElementType() != Type::UByteTy &&
1113 getType()->getElementType() != Type::SByteTy)
1115 // Check the elements to make sure they are all integers, not constant
1117 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1118 if (!isa<ConstantInt>(getOperand(i)))
1123 /// isCString - This method returns true if the array is a string (see
1124 /// isString) and it ends in a null byte \0 and does not contains any other
1125 /// null bytes except its terminator.
1126 bool ConstantArray::isCString() const {
1127 // Check the element type for sbyte or ubyte...
1128 if (getType()->getElementType() != Type::UByteTy &&
1129 getType()->getElementType() != Type::SByteTy)
1131 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1132 // Last element must be a null.
1133 if (getOperand(getNumOperands()-1) != Zero)
1135 // Other elements must be non-null integers.
1136 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1137 if (!isa<ConstantInt>(getOperand(i)))
1139 if (getOperand(i) == Zero)
1146 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
1147 // then this method converts the array to an std::string and returns it.
1148 // Otherwise, it asserts out.
1150 std::string ConstantArray::getAsString() const {
1151 assert(isString() && "Not a string!");
1153 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1154 Result += (char)cast<ConstantInt>(getOperand(i))->getZExtValue();
1159 //---- ConstantStruct::get() implementation...
1164 struct ConvertConstantType<ConstantStruct, StructType> {
1165 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1166 // Make everyone now use a constant of the new type...
1167 std::vector<Constant*> C;
1168 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1169 C.push_back(cast<Constant>(OldC->getOperand(i)));
1170 Constant *New = ConstantStruct::get(NewTy, C);
1171 assert(New != OldC && "Didn't replace constant??");
1173 OldC->uncheckedReplaceAllUsesWith(New);
1174 OldC->destroyConstant(); // This constant is now dead, destroy it.
1179 typedef ValueMap<std::vector<Constant*>, StructType,
1180 ConstantStruct, true /*largekey*/> StructConstantsTy;
1181 static ManagedStatic<StructConstantsTy> StructConstants;
1183 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1184 std::vector<Constant*> Elements;
1185 Elements.reserve(CS->getNumOperands());
1186 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1187 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1191 Constant *ConstantStruct::get(const StructType *Ty,
1192 const std::vector<Constant*> &V) {
1193 // Create a ConstantAggregateZero value if all elements are zeros...
1194 for (unsigned i = 0, e = V.size(); i != e; ++i)
1195 if (!V[i]->isNullValue())
1196 return StructConstants->getOrCreate(Ty, V);
1198 return ConstantAggregateZero::get(Ty);
1201 Constant *ConstantStruct::get(const std::vector<Constant*> &V) {
1202 std::vector<const Type*> StructEls;
1203 StructEls.reserve(V.size());
1204 for (unsigned i = 0, e = V.size(); i != e; ++i)
1205 StructEls.push_back(V[i]->getType());
1206 return get(StructType::get(StructEls), V);
1209 // destroyConstant - Remove the constant from the constant table...
1211 void ConstantStruct::destroyConstant() {
1212 StructConstants->remove(this);
1213 destroyConstantImpl();
1216 //---- ConstantPacked::get() implementation...
1220 struct ConvertConstantType<ConstantPacked, PackedType> {
1221 static void convert(ConstantPacked *OldC, const PackedType *NewTy) {
1222 // Make everyone now use a constant of the new type...
1223 std::vector<Constant*> C;
1224 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1225 C.push_back(cast<Constant>(OldC->getOperand(i)));
1226 Constant *New = ConstantPacked::get(NewTy, C);
1227 assert(New != OldC && "Didn't replace constant??");
1228 OldC->uncheckedReplaceAllUsesWith(New);
1229 OldC->destroyConstant(); // This constant is now dead, destroy it.
1234 static std::vector<Constant*> getValType(ConstantPacked *CP) {
1235 std::vector<Constant*> Elements;
1236 Elements.reserve(CP->getNumOperands());
1237 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1238 Elements.push_back(CP->getOperand(i));
1242 static ManagedStatic<ValueMap<std::vector<Constant*>, PackedType,
1243 ConstantPacked> > PackedConstants;
1245 Constant *ConstantPacked::get(const PackedType *Ty,
1246 const std::vector<Constant*> &V) {
1247 // If this is an all-zero packed, return a ConstantAggregateZero object
1250 if (!C->isNullValue())
1251 return PackedConstants->getOrCreate(Ty, V);
1252 for (unsigned i = 1, e = V.size(); i != e; ++i)
1254 return PackedConstants->getOrCreate(Ty, V);
1256 return ConstantAggregateZero::get(Ty);
1259 Constant *ConstantPacked::get(const std::vector<Constant*> &V) {
1260 assert(!V.empty() && "Cannot infer type if V is empty");
1261 return get(PackedType::get(V.front()->getType(),V.size()), V);
1264 // destroyConstant - Remove the constant from the constant table...
1266 void ConstantPacked::destroyConstant() {
1267 PackedConstants->remove(this);
1268 destroyConstantImpl();
1271 //---- ConstantPointerNull::get() implementation...
1275 // ConstantPointerNull does not take extra "value" argument...
1276 template<class ValType>
1277 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1278 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1279 return new ConstantPointerNull(Ty);
1284 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1285 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1286 // Make everyone now use a constant of the new type...
1287 Constant *New = ConstantPointerNull::get(NewTy);
1288 assert(New != OldC && "Didn't replace constant??");
1289 OldC->uncheckedReplaceAllUsesWith(New);
1290 OldC->destroyConstant(); // This constant is now dead, destroy it.
1295 static ManagedStatic<ValueMap<char, PointerType,
1296 ConstantPointerNull> > NullPtrConstants;
1298 static char getValType(ConstantPointerNull *) {
1303 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1304 return NullPtrConstants->getOrCreate(Ty, 0);
1307 // destroyConstant - Remove the constant from the constant table...
1309 void ConstantPointerNull::destroyConstant() {
1310 NullPtrConstants->remove(this);
1311 destroyConstantImpl();
1315 //---- UndefValue::get() implementation...
1319 // UndefValue does not take extra "value" argument...
1320 template<class ValType>
1321 struct ConstantCreator<UndefValue, Type, ValType> {
1322 static UndefValue *create(const Type *Ty, const ValType &V) {
1323 return new UndefValue(Ty);
1328 struct ConvertConstantType<UndefValue, Type> {
1329 static void convert(UndefValue *OldC, const Type *NewTy) {
1330 // Make everyone now use a constant of the new type.
1331 Constant *New = UndefValue::get(NewTy);
1332 assert(New != OldC && "Didn't replace constant??");
1333 OldC->uncheckedReplaceAllUsesWith(New);
1334 OldC->destroyConstant(); // This constant is now dead, destroy it.
1339 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1341 static char getValType(UndefValue *) {
1346 UndefValue *UndefValue::get(const Type *Ty) {
1347 return UndefValueConstants->getOrCreate(Ty, 0);
1350 // destroyConstant - Remove the constant from the constant table.
1352 void UndefValue::destroyConstant() {
1353 UndefValueConstants->remove(this);
1354 destroyConstantImpl();
1358 //---- ConstantExpr::get() implementations...
1360 struct ExprMapKeyType {
1361 explicit ExprMapKeyType(unsigned opc, std::vector<Constant*> ops,
1362 unsigned short pred = 0) : opcode(opc), predicate(pred), operands(ops) { }
1365 std::vector<Constant*> operands;
1366 bool operator==(const ExprMapKeyType& that) const {
1367 return this->opcode == that.opcode &&
1368 this->predicate == that.predicate &&
1369 this->operands == that.operands;
1371 bool operator<(const ExprMapKeyType & that) const {
1372 return this->opcode < that.opcode ||
1373 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1374 (this->opcode == that.opcode && this->predicate == that.predicate &&
1375 this->operands < that.operands);
1378 bool operator!=(const ExprMapKeyType& that) const {
1379 return !(*this == that);
1385 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1386 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1387 unsigned short pred = 0) {
1388 if (Instruction::isCast(V.opcode))
1389 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1390 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1391 V.opcode < Instruction::BinaryOpsEnd) ||
1392 V.opcode == Instruction::Shl ||
1393 V.opcode == Instruction::LShr ||
1394 V.opcode == Instruction::AShr)
1395 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1396 if (V.opcode == Instruction::Select)
1397 return new SelectConstantExpr(V.operands[0], V.operands[1],
1399 if (V.opcode == Instruction::ExtractElement)
1400 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1401 if (V.opcode == Instruction::InsertElement)
1402 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1404 if (V.opcode == Instruction::ShuffleVector)
1405 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1407 if (V.opcode == Instruction::GetElementPtr) {
1408 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1409 return new GetElementPtrConstantExpr(V.operands[0], IdxList, Ty);
1412 // The compare instructions are weird. We have to encode the predicate
1413 // value and it is combined with the instruction opcode by multiplying
1414 // the opcode by one hundred. We must decode this to get the predicate.
1415 if (V.opcode == Instruction::ICmp)
1416 return new CompareConstantExpr(Instruction::ICmp, V.predicate,
1417 V.operands[0], V.operands[1]);
1418 if (V.opcode == Instruction::FCmp)
1419 return new CompareConstantExpr(Instruction::FCmp, V.predicate,
1420 V.operands[0], V.operands[1]);
1421 assert(0 && "Invalid ConstantExpr!");
1426 struct ConvertConstantType<ConstantExpr, Type> {
1427 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1429 switch (OldC->getOpcode()) {
1430 case Instruction::Trunc:
1431 case Instruction::ZExt:
1432 case Instruction::SExt:
1433 case Instruction::FPTrunc:
1434 case Instruction::FPExt:
1435 case Instruction::UIToFP:
1436 case Instruction::SIToFP:
1437 case Instruction::FPToUI:
1438 case Instruction::FPToSI:
1439 case Instruction::PtrToInt:
1440 case Instruction::IntToPtr:
1441 case Instruction::BitCast:
1442 New = ConstantExpr::getCast(
1443 OldC->getOpcode(), OldC->getOperand(0), NewTy);
1445 case Instruction::Select:
1446 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1447 OldC->getOperand(1),
1448 OldC->getOperand(2));
1450 case Instruction::Shl:
1451 case Instruction::LShr:
1452 case Instruction::AShr:
1453 New = ConstantExpr::getShiftTy(NewTy, OldC->getOpcode(),
1454 OldC->getOperand(0), OldC->getOperand(1));
1457 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1458 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1459 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1460 OldC->getOperand(1));
1462 case Instruction::GetElementPtr:
1463 // Make everyone now use a constant of the new type...
1464 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1465 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0), Idx);
1469 assert(New != OldC && "Didn't replace constant??");
1470 OldC->uncheckedReplaceAllUsesWith(New);
1471 OldC->destroyConstant(); // This constant is now dead, destroy it.
1474 } // end namespace llvm
1477 static ExprMapKeyType getValType(ConstantExpr *CE) {
1478 std::vector<Constant*> Operands;
1479 Operands.reserve(CE->getNumOperands());
1480 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1481 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1482 return ExprMapKeyType(CE->getOpcode(), Operands,
1483 CE->isCompare() ? CE->getPredicate() : 0);
1486 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1487 ConstantExpr> > ExprConstants;
1489 /// This is a utility function to handle folding of casts and lookup of the
1490 /// cast in the ExprConstants map. It is usedby the various get* methods below.
1491 static inline Constant *getFoldedCast(
1492 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1493 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1494 // Fold a few common cases
1495 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1498 // Look up the constant in the table first to ensure uniqueness
1499 std::vector<Constant*> argVec(1, C);
1500 ExprMapKeyType Key(opc, argVec);
1501 return ExprConstants->getOrCreate(Ty, Key);
1504 Constant *ConstantExpr::getInferredCast(Constant *C, bool SrcIsSigned,
1505 const Type *Ty, bool DestIsSigned) {
1506 // Note: we can't inline this because it requires the Instructions.h header
1508 CastInst::getCastOpcode(C, SrcIsSigned, Ty, DestIsSigned), C, Ty);
1511 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1512 Instruction::CastOps opc = Instruction::CastOps(oc);
1513 assert(Instruction::isCast(opc) && "opcode out of range");
1514 assert(C && Ty && "Null arguments to getCast");
1515 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1519 assert(0 && "Invalid cast opcode");
1521 case Instruction::Trunc: return getTrunc(C, Ty);
1522 case Instruction::ZExt: return getZeroExtend(C, Ty);
1523 case Instruction::SExt: return getSignExtend(C, Ty);
1524 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1525 case Instruction::FPExt: return getFPExtend(C, Ty);
1526 case Instruction::UIToFP: return getUIToFP(C, Ty);
1527 case Instruction::SIToFP: return getSIToFP(C, Ty);
1528 case Instruction::FPToUI: return getFPToUI(C, Ty);
1529 case Instruction::FPToSI: return getFPToSI(C, Ty);
1530 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1531 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1532 case Instruction::BitCast: return getBitCast(C, Ty);
1537 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1538 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1539 return getCast(Instruction::BitCast, C, Ty);
1540 return getCast(Instruction::ZExt, C, Ty);
1543 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1544 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1545 return getCast(Instruction::BitCast, C, Ty);
1546 return getCast(Instruction::SExt, C, Ty);
1549 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1550 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1551 return getCast(Instruction::BitCast, C, Ty);
1552 return getCast(Instruction::Trunc, C, Ty);
1555 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1556 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1557 assert((Ty->isIntegral() || Ty->getTypeID() == Type::PointerTyID) &&
1560 if (Ty->isIntegral())
1561 return getCast(Instruction::PtrToInt, S, Ty);
1562 return getCast(Instruction::BitCast, S, Ty);
1565 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1566 assert(C->getType()->isInteger() && "Trunc operand must be integer");
1567 assert(Ty->isIntegral() && "Trunc produces only integral");
1568 assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1569 "SrcTy must be larger than DestTy for Trunc!");
1571 return getFoldedCast(Instruction::Trunc, C, Ty);
1574 Constant *ConstantExpr::getSignExtend(Constant *C, const Type *Ty) {
1575 assert(C->getType()->isIntegral() && "SEXt operand must be integral");
1576 assert(Ty->isInteger() && "SExt produces only integer");
1577 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1578 "SrcTy must be smaller than DestTy for SExt!");
1580 return getFoldedCast(Instruction::SExt, C, Ty);
1583 Constant *ConstantExpr::getZeroExtend(Constant *C, const Type *Ty) {
1584 assert(C->getType()->isIntegral() && "ZEXt operand must be integral");
1585 assert(Ty->isInteger() && "ZExt produces only integer");
1586 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1587 "SrcTy must be smaller than DestTy for ZExt!");
1589 return getFoldedCast(Instruction::ZExt, C, Ty);
1592 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1593 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1594 C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1595 "This is an illegal floating point truncation!");
1596 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1599 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1600 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1601 C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1602 "This is an illegal floating point extension!");
1603 return getFoldedCast(Instruction::FPExt, C, Ty);
1606 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1607 assert(C->getType()->isIntegral() && Ty->isFloatingPoint() &&
1608 "This is an illegal uint to floating point cast!");
1609 return getFoldedCast(Instruction::UIToFP, C, Ty);
1612 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1613 assert(C->getType()->isIntegral() && Ty->isFloatingPoint() &&
1614 "This is an illegal sint to floating point cast!");
1615 return getFoldedCast(Instruction::SIToFP, C, Ty);
1618 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1619 assert(C->getType()->isFloatingPoint() && Ty->isIntegral() &&
1620 "This is an illegal floating point to uint cast!");
1621 return getFoldedCast(Instruction::FPToUI, C, Ty);
1624 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1625 assert(C->getType()->isFloatingPoint() && Ty->isIntegral() &&
1626 "This is an illegal floating point to sint cast!");
1627 return getFoldedCast(Instruction::FPToSI, C, Ty);
1630 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1631 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1632 assert(DstTy->isIntegral() && "PtrToInt destination must be integral");
1633 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1636 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1637 assert(C->getType()->isIntegral() && "IntToPtr source must be integral");
1638 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1639 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1642 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1643 // BitCast implies a no-op cast of type only. No bits change. However, you
1644 // can't cast pointers to anything but pointers.
1645 const Type *SrcTy = C->getType();
1646 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1647 "BitCast cannot cast pointer to non-pointer and vice versa");
1649 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1650 // or nonptr->ptr). For all the other types, the cast is okay if source and
1651 // destination bit widths are identical.
1652 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1653 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1654 assert(SrcBitSize == DstBitSize && "BitCast requies types of same width");
1655 return getFoldedCast(Instruction::BitCast, C, DstTy);
1658 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
1659 // sizeof is implemented as: (ulong) gep (Ty*)null, 1
1660 return getCast(Instruction::PtrToInt, getGetElementPtr(getNullValue(
1661 PointerType::get(Ty)), std::vector<Constant*>(1,
1662 ConstantInt::get(Type::UIntTy, 1))), Type::ULongTy);
1665 Constant *ConstantExpr::getPtrPtrFromArrayPtr(Constant *C) {
1666 // pointer from array is implemented as: getelementptr arr ptr, 0, 0
1667 static std::vector<Constant*> Indices(2, ConstantInt::get(Type::UIntTy, 0));
1669 return ConstantExpr::getGetElementPtr(C, Indices);
1672 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1673 Constant *C1, Constant *C2) {
1674 if (Opcode == Instruction::Shl || Opcode == Instruction::LShr ||
1675 Opcode == Instruction::AShr)
1676 return getShiftTy(ReqTy, Opcode, C1, C2);
1678 // Check the operands for consistency first
1679 assert(Opcode >= Instruction::BinaryOpsBegin &&
1680 Opcode < Instruction::BinaryOpsEnd &&
1681 "Invalid opcode in binary constant expression");
1682 assert(C1->getType() == C2->getType() &&
1683 "Operand types in binary constant expression should match");
1685 if (ReqTy == C1->getType() || (Instruction::isComparison(Opcode) &&
1686 ReqTy == Type::BoolTy))
1687 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1688 return FC; // Fold a few common cases...
1690 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1691 ExprMapKeyType Key(Opcode, argVec);
1692 return ExprConstants->getOrCreate(ReqTy, Key);
1695 Constant *ConstantExpr::getCompareTy(unsigned Opcode, unsigned short predicate,
1696 Constant *C1, Constant *C2) {
1697 if (Opcode == Instruction::ICmp)
1698 return getICmp(predicate, C1, C2);
1699 return getFCmp(predicate, C1, C2);
1702 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1705 case Instruction::Add:
1706 case Instruction::Sub:
1707 case Instruction::Mul:
1708 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1709 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
1710 isa<PackedType>(C1->getType())) &&
1711 "Tried to create an arithmetic operation on a non-arithmetic type!");
1713 case Instruction::UDiv:
1714 case Instruction::SDiv:
1715 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1716 assert((C1->getType()->isInteger() || (isa<PackedType>(C1->getType()) &&
1717 cast<PackedType>(C1->getType())->getElementType()->isInteger())) &&
1718 "Tried to create an arithmetic operation on a non-arithmetic type!");
1720 case Instruction::FDiv:
1721 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1722 assert((C1->getType()->isFloatingPoint() || (isa<PackedType>(C1->getType())
1723 && cast<PackedType>(C1->getType())->getElementType()->isFloatingPoint()))
1724 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1726 case Instruction::URem:
1727 case Instruction::SRem:
1728 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1729 assert((C1->getType()->isInteger() || (isa<PackedType>(C1->getType()) &&
1730 cast<PackedType>(C1->getType())->getElementType()->isInteger())) &&
1731 "Tried to create an arithmetic operation on a non-arithmetic type!");
1733 case Instruction::FRem:
1734 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1735 assert((C1->getType()->isFloatingPoint() || (isa<PackedType>(C1->getType())
1736 && cast<PackedType>(C1->getType())->getElementType()->isFloatingPoint()))
1737 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1739 case Instruction::And:
1740 case Instruction::Or:
1741 case Instruction::Xor:
1742 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1743 assert((C1->getType()->isIntegral() || isa<PackedType>(C1->getType())) &&
1744 "Tried to create a logical operation on a non-integral type!");
1746 case Instruction::SetLT: case Instruction::SetGT: case Instruction::SetLE:
1747 case Instruction::SetGE: case Instruction::SetEQ: case Instruction::SetNE:
1748 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1750 case Instruction::Shl:
1751 case Instruction::LShr:
1752 case Instruction::AShr:
1753 assert(C2->getType() == Type::UByteTy && "Shift should be by ubyte!");
1754 assert(C1->getType()->isInteger() &&
1755 "Tried to create a shift operation on a non-integer type!");
1762 return getTy(C1->getType(), Opcode, C1, C2);
1765 Constant *ConstantExpr::getCompare(unsigned Opcode, unsigned short pred,
1766 Constant *C1, Constant *C2) {
1767 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1768 return getCompareTy(Opcode, pred, C1, C2);
1771 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1772 Constant *V1, Constant *V2) {
1773 assert(C->getType() == Type::BoolTy && "Select condition must be bool!");
1774 assert(V1->getType() == V2->getType() && "Select value types must match!");
1775 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1777 if (ReqTy == V1->getType())
1778 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1779 return SC; // Fold common cases
1781 std::vector<Constant*> argVec(3, C);
1784 ExprMapKeyType Key(Instruction::Select, argVec);
1785 return ExprConstants->getOrCreate(ReqTy, Key);
1788 /// getShiftTy - Return a shift left or shift right constant expr
1789 Constant *ConstantExpr::getShiftTy(const Type *ReqTy, unsigned Opcode,
1790 Constant *C1, Constant *C2) {
1791 // Check the operands for consistency first
1792 assert((Opcode == Instruction::Shl ||
1793 Opcode == Instruction::LShr ||
1794 Opcode == Instruction::AShr) &&
1795 "Invalid opcode in binary constant expression");
1796 assert(C1->getType()->isIntegral() && C2->getType() == Type::UByteTy &&
1797 "Invalid operand types for Shift constant expr!");
1799 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
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(1, C1); argVec.push_back(C2);
1804 ExprMapKeyType Key(Opcode, argVec);
1805 return ExprConstants->getOrCreate(ReqTy, Key);
1808 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1809 const std::vector<Value*> &IdxList) {
1810 assert(GetElementPtrInst::getIndexedType(C->getType(), IdxList, true) &&
1811 "GEP indices invalid!");
1813 if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
1814 return FC; // Fold a few common cases...
1816 assert(isa<PointerType>(C->getType()) &&
1817 "Non-pointer type for constant GetElementPtr expression");
1818 // Look up the constant in the table first to ensure uniqueness
1819 std::vector<Constant*> ArgVec;
1820 ArgVec.reserve(IdxList.size()+1);
1821 ArgVec.push_back(C);
1822 for (unsigned i = 0, e = IdxList.size(); i != e; ++i)
1823 ArgVec.push_back(cast<Constant>(IdxList[i]));
1824 const ExprMapKeyType Key(Instruction::GetElementPtr,ArgVec);
1825 return ExprConstants->getOrCreate(ReqTy, Key);
1828 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1829 const std::vector<Constant*> &IdxList){
1830 // Get the result type of the getelementptr!
1831 std::vector<Value*> VIdxList(IdxList.begin(), IdxList.end());
1833 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), VIdxList,
1835 assert(Ty && "GEP indices invalid!");
1836 return getGetElementPtrTy(PointerType::get(Ty), C, VIdxList);
1839 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1840 const std::vector<Value*> &IdxList) {
1841 // Get the result type of the getelementptr!
1842 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
1844 assert(Ty && "GEP indices invalid!");
1845 return getGetElementPtrTy(PointerType::get(Ty), C, IdxList);
1849 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1850 assert(LHS->getType() == RHS->getType());
1851 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1852 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1854 if (Constant *FC = ConstantFoldCompare(Instruction::ICmp, LHS, RHS, pred))
1855 return FC; // Fold a few common cases...
1857 // Look up the constant in the table first to ensure uniqueness
1858 std::vector<Constant*> ArgVec;
1859 ArgVec.push_back(LHS);
1860 ArgVec.push_back(RHS);
1861 // Fake up an opcode value that encodes both the opcode and predicate
1862 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1863 return ExprConstants->getOrCreate(Type::BoolTy, Key);
1867 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1868 assert(LHS->getType() == RHS->getType());
1869 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1871 if (Constant *FC = ConstantFoldCompare(Instruction::FCmp, LHS, RHS, pred))
1872 return FC; // Fold a few common cases...
1874 // Look up the constant in the table first to ensure uniqueness
1875 std::vector<Constant*> ArgVec;
1876 ArgVec.push_back(LHS);
1877 ArgVec.push_back(RHS);
1878 // Fake up an opcode value that encodes both the opcode and predicate
1879 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1880 return ExprConstants->getOrCreate(Type::BoolTy, Key);
1883 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1885 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1886 return FC; // Fold a few common cases...
1887 // Look up the constant in the table first to ensure uniqueness
1888 std::vector<Constant*> ArgVec(1, Val);
1889 ArgVec.push_back(Idx);
1890 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1891 return ExprConstants->getOrCreate(ReqTy, Key);
1894 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1895 assert(isa<PackedType>(Val->getType()) &&
1896 "Tried to create extractelement operation on non-packed type!");
1897 assert(Idx->getType() == Type::UIntTy &&
1898 "Extractelement index must be uint type!");
1899 return getExtractElementTy(cast<PackedType>(Val->getType())->getElementType(),
1903 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1904 Constant *Elt, Constant *Idx) {
1905 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1906 return FC; // Fold a few common cases...
1907 // Look up the constant in the table first to ensure uniqueness
1908 std::vector<Constant*> ArgVec(1, Val);
1909 ArgVec.push_back(Elt);
1910 ArgVec.push_back(Idx);
1911 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1912 return ExprConstants->getOrCreate(ReqTy, Key);
1915 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1917 assert(isa<PackedType>(Val->getType()) &&
1918 "Tried to create insertelement operation on non-packed type!");
1919 assert(Elt->getType() == cast<PackedType>(Val->getType())->getElementType()
1920 && "Insertelement types must match!");
1921 assert(Idx->getType() == Type::UIntTy &&
1922 "Insertelement index must be uint type!");
1923 return getInsertElementTy(cast<PackedType>(Val->getType())->getElementType(),
1927 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1928 Constant *V2, Constant *Mask) {
1929 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1930 return FC; // Fold a few common cases...
1931 // Look up the constant in the table first to ensure uniqueness
1932 std::vector<Constant*> ArgVec(1, V1);
1933 ArgVec.push_back(V2);
1934 ArgVec.push_back(Mask);
1935 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1936 return ExprConstants->getOrCreate(ReqTy, Key);
1939 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1941 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1942 "Invalid shuffle vector constant expr operands!");
1943 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
1946 // destroyConstant - Remove the constant from the constant table...
1948 void ConstantExpr::destroyConstant() {
1949 ExprConstants->remove(this);
1950 destroyConstantImpl();
1953 const char *ConstantExpr::getOpcodeName() const {
1954 return Instruction::getOpcodeName(getOpcode());
1957 //===----------------------------------------------------------------------===//
1958 // replaceUsesOfWithOnConstant implementations
1960 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1962 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1963 Constant *ToC = cast<Constant>(To);
1965 unsigned OperandToUpdate = U-OperandList;
1966 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1968 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
1969 Lookup.first.first = getType();
1970 Lookup.second = this;
1972 std::vector<Constant*> &Values = Lookup.first.second;
1973 Values.reserve(getNumOperands()); // Build replacement array.
1975 // Fill values with the modified operands of the constant array. Also,
1976 // compute whether this turns into an all-zeros array.
1977 bool isAllZeros = false;
1978 if (!ToC->isNullValue()) {
1979 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1980 Values.push_back(cast<Constant>(O->get()));
1983 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1984 Constant *Val = cast<Constant>(O->get());
1985 Values.push_back(Val);
1986 if (isAllZeros) isAllZeros = Val->isNullValue();
1989 Values[OperandToUpdate] = ToC;
1991 Constant *Replacement = 0;
1993 Replacement = ConstantAggregateZero::get(getType());
1995 // Check to see if we have this array type already.
1997 ArrayConstantsTy::MapTy::iterator I =
1998 ArrayConstants->InsertOrGetItem(Lookup, Exists);
2001 Replacement = I->second;
2003 // Okay, the new shape doesn't exist in the system yet. Instead of
2004 // creating a new constant array, inserting it, replaceallusesof'ing the
2005 // old with the new, then deleting the old... just update the current one
2007 ArrayConstants->MoveConstantToNewSlot(this, I);
2009 // Update to the new value.
2010 setOperand(OperandToUpdate, ToC);
2015 // Otherwise, I do need to replace this with an existing value.
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 ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2027 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2028 Constant *ToC = cast<Constant>(To);
2030 unsigned OperandToUpdate = U-OperandList;
2031 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2033 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
2034 Lookup.first.first = getType();
2035 Lookup.second = this;
2036 std::vector<Constant*> &Values = Lookup.first.second;
2037 Values.reserve(getNumOperands()); // Build replacement struct.
2040 // Fill values with the modified operands of the constant struct. Also,
2041 // compute whether this turns into an all-zeros struct.
2042 bool isAllZeros = false;
2043 if (!ToC->isNullValue()) {
2044 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2045 Values.push_back(cast<Constant>(O->get()));
2048 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2049 Constant *Val = cast<Constant>(O->get());
2050 Values.push_back(Val);
2051 if (isAllZeros) isAllZeros = Val->isNullValue();
2054 Values[OperandToUpdate] = ToC;
2056 Constant *Replacement = 0;
2058 Replacement = ConstantAggregateZero::get(getType());
2060 // Check to see if we have this array type already.
2062 StructConstantsTy::MapTy::iterator I =
2063 StructConstants->InsertOrGetItem(Lookup, Exists);
2066 Replacement = I->second;
2068 // Okay, the new shape doesn't exist in the system yet. Instead of
2069 // creating a new constant struct, inserting it, replaceallusesof'ing the
2070 // old with the new, then deleting the old... just update the current one
2072 StructConstants->MoveConstantToNewSlot(this, I);
2074 // Update to the new value.
2075 setOperand(OperandToUpdate, ToC);
2080 assert(Replacement != this && "I didn't contain From!");
2082 // Everyone using this now uses the replacement.
2083 uncheckedReplaceAllUsesWith(Replacement);
2085 // Delete the old constant!
2089 void ConstantPacked::replaceUsesOfWithOnConstant(Value *From, Value *To,
2091 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2093 std::vector<Constant*> Values;
2094 Values.reserve(getNumOperands()); // Build replacement array...
2095 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2096 Constant *Val = getOperand(i);
2097 if (Val == From) Val = cast<Constant>(To);
2098 Values.push_back(Val);
2101 Constant *Replacement = ConstantPacked::get(getType(), Values);
2102 assert(Replacement != this && "I didn't contain From!");
2104 // Everyone using this now uses the replacement.
2105 uncheckedReplaceAllUsesWith(Replacement);
2107 // Delete the old constant!
2111 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2113 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2114 Constant *To = cast<Constant>(ToV);
2116 Constant *Replacement = 0;
2117 if (getOpcode() == Instruction::GetElementPtr) {
2118 std::vector<Constant*> Indices;
2119 Constant *Pointer = getOperand(0);
2120 Indices.reserve(getNumOperands()-1);
2121 if (Pointer == From) Pointer = To;
2123 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2124 Constant *Val = getOperand(i);
2125 if (Val == From) Val = To;
2126 Indices.push_back(Val);
2128 Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
2129 } else if (isCast()) {
2130 assert(getOperand(0) == From && "Cast only has one use!");
2131 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2132 } else if (getOpcode() == Instruction::Select) {
2133 Constant *C1 = getOperand(0);
2134 Constant *C2 = getOperand(1);
2135 Constant *C3 = getOperand(2);
2136 if (C1 == From) C1 = To;
2137 if (C2 == From) C2 = To;
2138 if (C3 == From) C3 = To;
2139 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2140 } else if (getOpcode() == Instruction::ExtractElement) {
2141 Constant *C1 = getOperand(0);
2142 Constant *C2 = getOperand(1);
2143 if (C1 == From) C1 = To;
2144 if (C2 == From) C2 = To;
2145 Replacement = ConstantExpr::getExtractElement(C1, C2);
2146 } else if (getOpcode() == Instruction::InsertElement) {
2147 Constant *C1 = getOperand(0);
2148 Constant *C2 = getOperand(1);
2149 Constant *C3 = getOperand(1);
2150 if (C1 == From) C1 = To;
2151 if (C2 == From) C2 = To;
2152 if (C3 == From) C3 = To;
2153 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2154 } else if (getOpcode() == Instruction::ShuffleVector) {
2155 Constant *C1 = getOperand(0);
2156 Constant *C2 = getOperand(1);
2157 Constant *C3 = getOperand(2);
2158 if (C1 == From) C1 = To;
2159 if (C2 == From) C2 = To;
2160 if (C3 == From) C3 = To;
2161 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2162 } else if (isCompare()) {
2163 Constant *C1 = getOperand(0);
2164 Constant *C2 = getOperand(1);
2165 if (C1 == From) C1 = To;
2166 if (C2 == From) C2 = To;
2167 if (getOpcode() == Instruction::ICmp)
2168 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2170 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2171 } else if (getNumOperands() == 2) {
2172 Constant *C1 = getOperand(0);
2173 Constant *C2 = getOperand(1);
2174 if (C1 == From) C1 = To;
2175 if (C2 == From) C2 = To;
2176 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2178 assert(0 && "Unknown ConstantExpr type!");
2182 assert(Replacement != this && "I didn't contain From!");
2184 // Everyone using this now uses the replacement.
2185 uncheckedReplaceAllUsesWith(Replacement);
2187 // Delete the old constant!
2192 /// getStringValue - Turn an LLVM constant pointer that eventually points to a
2193 /// global into a string value. Return an empty string if we can't do it.
2194 /// Parameter Chop determines if the result is chopped at the first null
2197 std::string Constant::getStringValue(bool Chop, unsigned Offset) {
2198 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
2199 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
2200 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
2201 if (Init->isString()) {
2202 std::string Result = Init->getAsString();
2203 if (Offset < Result.size()) {
2204 // If we are pointing INTO The string, erase the beginning...
2205 Result.erase(Result.begin(), Result.begin()+Offset);
2207 // Take off the null terminator, and any string fragments after it.
2209 std::string::size_type NullPos = Result.find_first_of((char)0);
2210 if (NullPos != std::string::npos)
2211 Result.erase(Result.begin()+NullPos, Result.end());
2217 } else if (Constant *C = dyn_cast<Constant>(this)) {
2218 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
2219 return GV->getStringValue(Chop, Offset);
2220 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2221 if (CE->getOpcode() == Instruction::GetElementPtr) {
2222 // Turn a gep into the specified offset.
2223 if (CE->getNumOperands() == 3 &&
2224 cast<Constant>(CE->getOperand(1))->isNullValue() &&
2225 isa<ConstantInt>(CE->getOperand(2))) {
2226 Offset += cast<ConstantInt>(CE->getOperand(2))->getZExtValue();
2227 return CE->getOperand(0)->getStringValue(Chop, Offset);