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 /// ConstantExpr::get* - Return some common constants without having to
446 /// specify the full Instruction::OPCODE identifier.
448 Constant *ConstantExpr::getNeg(Constant *C) {
449 if (!C->getType()->isFloatingPoint())
450 return get(Instruction::Sub, getNullValue(C->getType()), C);
452 return get(Instruction::Sub, ConstantFP::get(C->getType(), -0.0), C);
454 Constant *ConstantExpr::getNot(Constant *C) {
455 assert(isa<ConstantIntegral>(C) && "Cannot NOT a nonintegral type!");
456 return get(Instruction::Xor, C,
457 ConstantIntegral::getAllOnesValue(C->getType()));
459 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
460 return get(Instruction::Add, C1, C2);
462 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
463 return get(Instruction::Sub, C1, C2);
465 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
466 return get(Instruction::Mul, C1, C2);
468 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
469 return get(Instruction::UDiv, C1, C2);
471 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
472 return get(Instruction::SDiv, C1, C2);
474 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
475 return get(Instruction::FDiv, C1, C2);
477 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
478 return get(Instruction::URem, C1, C2);
480 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
481 return get(Instruction::SRem, C1, C2);
483 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
484 return get(Instruction::FRem, C1, C2);
486 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
487 return get(Instruction::And, C1, C2);
489 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
490 return get(Instruction::Or, C1, C2);
492 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
493 return get(Instruction::Xor, C1, C2);
495 Constant *ConstantExpr::getSetEQ(Constant *C1, Constant *C2) {
496 return get(Instruction::SetEQ, C1, C2);
498 Constant *ConstantExpr::getSetNE(Constant *C1, Constant *C2) {
499 return get(Instruction::SetNE, C1, C2);
501 Constant *ConstantExpr::getSetLT(Constant *C1, Constant *C2) {
502 return get(Instruction::SetLT, C1, C2);
504 Constant *ConstantExpr::getSetGT(Constant *C1, Constant *C2) {
505 return get(Instruction::SetGT, C1, C2);
507 Constant *ConstantExpr::getSetLE(Constant *C1, Constant *C2) {
508 return get(Instruction::SetLE, C1, C2);
510 Constant *ConstantExpr::getSetGE(Constant *C1, Constant *C2) {
511 return get(Instruction::SetGE, C1, C2);
514 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
515 assert(LHS->getType() == RHS->getType());
516 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
517 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
518 CompareConstantExpr *Result =
519 new CompareConstantExpr(Instruction::ICmp, pred, LHS, RHS);
523 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
524 assert(LHS->getType() == RHS->getType());
525 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid ICmp Predicate");
526 CompareConstantExpr *Result =
527 new CompareConstantExpr(Instruction::FCmp, pred, LHS, RHS);
530 unsigned ConstantExpr::getPredicate() const {
531 assert(getOpcode() == Instruction::FCmp || getOpcode() == Instruction::ICmp);
532 return dynamic_cast<const CompareConstantExpr*>(this)->predicate;
534 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
535 return get(Instruction::Shl, C1, C2);
537 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
538 return get(Instruction::LShr, C1, C2);
540 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
541 return get(Instruction::AShr, C1, C2);
544 /// getWithOperandReplaced - Return a constant expression identical to this
545 /// one, but with the specified operand set to the specified value.
547 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
548 assert(OpNo < getNumOperands() && "Operand num is out of range!");
549 assert(Op->getType() == getOperand(OpNo)->getType() &&
550 "Replacing operand with value of different type!");
551 if (getOperand(OpNo) == Op)
552 return const_cast<ConstantExpr*>(this);
554 Constant *Op0, *Op1, *Op2;
555 switch (getOpcode()) {
556 case Instruction::Trunc:
557 case Instruction::ZExt:
558 case Instruction::SExt:
559 case Instruction::FPTrunc:
560 case Instruction::FPExt:
561 case Instruction::UIToFP:
562 case Instruction::SIToFP:
563 case Instruction::FPToUI:
564 case Instruction::FPToSI:
565 case Instruction::PtrToInt:
566 case Instruction::IntToPtr:
567 case Instruction::BitCast:
568 return ConstantExpr::getCast(getOpcode(), Op, getType());
569 case Instruction::Select:
570 Op0 = (OpNo == 0) ? Op : getOperand(0);
571 Op1 = (OpNo == 1) ? Op : getOperand(1);
572 Op2 = (OpNo == 2) ? Op : getOperand(2);
573 return ConstantExpr::getSelect(Op0, Op1, Op2);
574 case Instruction::InsertElement:
575 Op0 = (OpNo == 0) ? Op : getOperand(0);
576 Op1 = (OpNo == 1) ? Op : getOperand(1);
577 Op2 = (OpNo == 2) ? Op : getOperand(2);
578 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
579 case Instruction::ExtractElement:
580 Op0 = (OpNo == 0) ? Op : getOperand(0);
581 Op1 = (OpNo == 1) ? Op : getOperand(1);
582 return ConstantExpr::getExtractElement(Op0, Op1);
583 case Instruction::ShuffleVector:
584 Op0 = (OpNo == 0) ? Op : getOperand(0);
585 Op1 = (OpNo == 1) ? Op : getOperand(1);
586 Op2 = (OpNo == 2) ? Op : getOperand(2);
587 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
588 case Instruction::GetElementPtr: {
589 std::vector<Constant*> Ops;
590 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
591 Ops.push_back(getOperand(i));
593 return ConstantExpr::getGetElementPtr(Op, Ops);
595 return ConstantExpr::getGetElementPtr(getOperand(0), Ops);
598 assert(getNumOperands() == 2 && "Must be binary operator?");
599 Op0 = (OpNo == 0) ? Op : getOperand(0);
600 Op1 = (OpNo == 1) ? Op : getOperand(1);
601 return ConstantExpr::get(getOpcode(), Op0, Op1);
605 /// getWithOperands - This returns the current constant expression with the
606 /// operands replaced with the specified values. The specified operands must
607 /// match count and type with the existing ones.
608 Constant *ConstantExpr::
609 getWithOperands(const std::vector<Constant*> &Ops) const {
610 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
611 bool AnyChange = false;
612 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
613 assert(Ops[i]->getType() == getOperand(i)->getType() &&
614 "Operand type mismatch!");
615 AnyChange |= Ops[i] != getOperand(i);
617 if (!AnyChange) // No operands changed, return self.
618 return const_cast<ConstantExpr*>(this);
620 switch (getOpcode()) {
621 case Instruction::Trunc:
622 case Instruction::ZExt:
623 case Instruction::SExt:
624 case Instruction::FPTrunc:
625 case Instruction::FPExt:
626 case Instruction::UIToFP:
627 case Instruction::SIToFP:
628 case Instruction::FPToUI:
629 case Instruction::FPToSI:
630 case Instruction::PtrToInt:
631 case Instruction::IntToPtr:
632 case Instruction::BitCast:
633 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
634 case Instruction::Select:
635 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
636 case Instruction::InsertElement:
637 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
638 case Instruction::ExtractElement:
639 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
640 case Instruction::ShuffleVector:
641 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
642 case Instruction::GetElementPtr: {
643 std::vector<Constant*> ActualOps(Ops.begin()+1, Ops.end());
644 return ConstantExpr::getGetElementPtr(Ops[0], ActualOps);
647 assert(getNumOperands() == 2 && "Must be binary operator?");
648 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
653 //===----------------------------------------------------------------------===//
654 // isValueValidForType implementations
656 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
657 switch (Ty->getTypeID()) {
659 return false; // These can't be represented as integers!!!
661 case Type::SByteTyID:
662 return (Val <= INT8_MAX && Val >= INT8_MIN);
663 case Type::UByteTyID:
664 return (Val >= 0) && (Val <= UINT8_MAX);
665 case Type::ShortTyID:
666 return (Val <= INT16_MAX && Val >= INT16_MIN);
667 case Type::UShortTyID:
668 return (Val >= 0) && (Val <= UINT16_MAX);
670 return (Val <= int(INT32_MAX) && Val >= int(INT32_MIN));
672 return (Val >= 0) && (Val <= UINT32_MAX);
674 case Type::ULongTyID:
675 return true; // always true, has to fit in largest type
679 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
680 switch (Ty->getTypeID()) {
682 return false; // These can't be represented as floating point!
684 // TODO: Figure out how to test if a double can be cast to a float!
685 case Type::FloatTyID:
686 case Type::DoubleTyID:
687 return true; // This is the largest type...
691 //===----------------------------------------------------------------------===//
692 // Factory Function Implementation
694 // ConstantCreator - A class that is used to create constants by
695 // ValueMap*. This class should be partially specialized if there is
696 // something strange that needs to be done to interface to the ctor for the
700 template<class ConstantClass, class TypeClass, class ValType>
701 struct VISIBILITY_HIDDEN ConstantCreator {
702 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
703 return new ConstantClass(Ty, V);
707 template<class ConstantClass, class TypeClass>
708 struct VISIBILITY_HIDDEN ConvertConstantType {
709 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
710 assert(0 && "This type cannot be converted!\n");
715 template<class ValType, class TypeClass, class ConstantClass,
716 bool HasLargeKey = false /*true for arrays and structs*/ >
717 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
719 typedef std::pair<const Type*, ValType> MapKey;
720 typedef std::map<MapKey, Constant *> MapTy;
721 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
722 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
724 /// Map - This is the main map from the element descriptor to the Constants.
725 /// This is the primary way we avoid creating two of the same shape
729 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
730 /// from the constants to their element in Map. This is important for
731 /// removal of constants from the array, which would otherwise have to scan
732 /// through the map with very large keys.
733 InverseMapTy InverseMap;
735 /// AbstractTypeMap - Map for abstract type constants.
737 AbstractTypeMapTy AbstractTypeMap;
740 void clear(std::vector<Constant *> &Constants) {
741 for(typename MapTy::iterator I = Map.begin(); I != Map.end(); ++I)
742 Constants.push_back(I->second);
744 AbstractTypeMap.clear();
749 typename MapTy::iterator map_end() { return Map.end(); }
751 /// InsertOrGetItem - Return an iterator for the specified element.
752 /// If the element exists in the map, the returned iterator points to the
753 /// entry and Exists=true. If not, the iterator points to the newly
754 /// inserted entry and returns Exists=false. Newly inserted entries have
755 /// I->second == 0, and should be filled in.
756 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
759 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
765 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
767 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
768 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
769 IMI->second->second == CP &&
770 "InverseMap corrupt!");
774 typename MapTy::iterator I =
775 Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
776 if (I == Map.end() || I->second != CP) {
777 // FIXME: This should not use a linear scan. If this gets to be a
778 // performance problem, someone should look at this.
779 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
786 /// getOrCreate - Return the specified constant from the map, creating it if
788 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
789 MapKey Lookup(Ty, V);
790 typename MapTy::iterator I = Map.lower_bound(Lookup);
792 if (I != Map.end() && I->first == Lookup)
793 return static_cast<ConstantClass *>(I->second);
795 // If no preexisting value, create one now...
796 ConstantClass *Result =
797 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
799 /// FIXME: why does this assert fail when loading 176.gcc?
800 //assert(Result->getType() == Ty && "Type specified is not correct!");
801 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
803 if (HasLargeKey) // Remember the reverse mapping if needed.
804 InverseMap.insert(std::make_pair(Result, I));
806 // If the type of the constant is abstract, make sure that an entry exists
807 // for it in the AbstractTypeMap.
808 if (Ty->isAbstract()) {
809 typename AbstractTypeMapTy::iterator TI =
810 AbstractTypeMap.lower_bound(Ty);
812 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
813 // Add ourselves to the ATU list of the type.
814 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
816 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
822 void remove(ConstantClass *CP) {
823 typename MapTy::iterator I = FindExistingElement(CP);
824 assert(I != Map.end() && "Constant not found in constant table!");
825 assert(I->second == CP && "Didn't find correct element?");
827 if (HasLargeKey) // Remember the reverse mapping if needed.
828 InverseMap.erase(CP);
830 // Now that we found the entry, make sure this isn't the entry that
831 // the AbstractTypeMap points to.
832 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
833 if (Ty->isAbstract()) {
834 assert(AbstractTypeMap.count(Ty) &&
835 "Abstract type not in AbstractTypeMap?");
836 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
837 if (ATMEntryIt == I) {
838 // Yes, we are removing the representative entry for this type.
839 // See if there are any other entries of the same type.
840 typename MapTy::iterator TmpIt = ATMEntryIt;
842 // First check the entry before this one...
843 if (TmpIt != Map.begin()) {
845 if (TmpIt->first.first != Ty) // Not the same type, move back...
849 // If we didn't find the same type, try to move forward...
850 if (TmpIt == ATMEntryIt) {
852 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
853 --TmpIt; // No entry afterwards with the same type
856 // If there is another entry in the map of the same abstract type,
857 // update the AbstractTypeMap entry now.
858 if (TmpIt != ATMEntryIt) {
861 // Otherwise, we are removing the last instance of this type
862 // from the table. Remove from the ATM, and from user list.
863 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
864 AbstractTypeMap.erase(Ty);
873 /// MoveConstantToNewSlot - If we are about to change C to be the element
874 /// specified by I, update our internal data structures to reflect this
876 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
877 // First, remove the old location of the specified constant in the map.
878 typename MapTy::iterator OldI = FindExistingElement(C);
879 assert(OldI != Map.end() && "Constant not found in constant table!");
880 assert(OldI->second == C && "Didn't find correct element?");
882 // If this constant is the representative element for its abstract type,
883 // update the AbstractTypeMap so that the representative element is I.
884 if (C->getType()->isAbstract()) {
885 typename AbstractTypeMapTy::iterator ATI =
886 AbstractTypeMap.find(C->getType());
887 assert(ATI != AbstractTypeMap.end() &&
888 "Abstract type not in AbstractTypeMap?");
889 if (ATI->second == OldI)
893 // Remove the old entry from the map.
896 // Update the inverse map so that we know that this constant is now
897 // located at descriptor I.
899 assert(I->second == C && "Bad inversemap entry!");
904 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
905 typename AbstractTypeMapTy::iterator I =
906 AbstractTypeMap.find(cast<Type>(OldTy));
908 assert(I != AbstractTypeMap.end() &&
909 "Abstract type not in AbstractTypeMap?");
911 // Convert a constant at a time until the last one is gone. The last one
912 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
913 // eliminated eventually.
915 ConvertConstantType<ConstantClass,
917 static_cast<ConstantClass *>(I->second->second),
918 cast<TypeClass>(NewTy));
920 I = AbstractTypeMap.find(cast<Type>(OldTy));
921 } while (I != AbstractTypeMap.end());
924 // If the type became concrete without being refined to any other existing
925 // type, we just remove ourselves from the ATU list.
926 void typeBecameConcrete(const DerivedType *AbsTy) {
927 AbsTy->removeAbstractTypeUser(this);
931 DOUT << "Constant.cpp: ValueMap\n";
937 //---- ConstantBool::get*() implementation.
939 ConstantBool *ConstantBool::getTrue() {
940 static ConstantBool *T = 0;
942 return T = new ConstantBool(true);
944 ConstantBool *ConstantBool::getFalse() {
945 static ConstantBool *F = 0;
947 return F = new ConstantBool(false);
950 //---- ConstantInt::get() implementations...
952 static ManagedStatic<ValueMap<uint64_t, Type, ConstantInt> > IntConstants;
954 // Get a ConstantInt from an int64_t. Note here that we canoncialize the value
955 // to a uint64_t value that has been zero extended down to the size of the
956 // integer type of the ConstantInt. This allows the getZExtValue method to
957 // just return the stored value while getSExtValue has to convert back to sign
958 // extended. getZExtValue is more common in LLVM than getSExtValue().
959 ConstantInt *ConstantInt::get(const Type *Ty, int64_t V) {
960 return IntConstants->getOrCreate(Ty, V & Ty->getIntegralTypeMask());
963 ConstantIntegral *ConstantIntegral::get(const Type *Ty, int64_t V) {
964 if (Ty == Type::BoolTy) return ConstantBool::get(V&1);
965 return IntConstants->getOrCreate(Ty, V & Ty->getIntegralTypeMask());
968 //---- ConstantFP::get() implementation...
972 struct ConstantCreator<ConstantFP, Type, uint64_t> {
973 static ConstantFP *create(const Type *Ty, uint64_t V) {
974 assert(Ty == Type::DoubleTy);
975 return new ConstantFP(Ty, BitsToDouble(V));
979 struct ConstantCreator<ConstantFP, Type, uint32_t> {
980 static ConstantFP *create(const Type *Ty, uint32_t V) {
981 assert(Ty == Type::FloatTy);
982 return new ConstantFP(Ty, BitsToFloat(V));
987 static ManagedStatic<ValueMap<uint64_t, Type, ConstantFP> > DoubleConstants;
988 static ManagedStatic<ValueMap<uint32_t, Type, ConstantFP> > FloatConstants;
990 bool ConstantFP::isNullValue() const {
991 return DoubleToBits(Val) == 0;
994 bool ConstantFP::isExactlyValue(double V) const {
995 return DoubleToBits(V) == DoubleToBits(Val);
999 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
1000 if (Ty == Type::FloatTy) {
1001 // Force the value through memory to normalize it.
1002 return FloatConstants->getOrCreate(Ty, FloatToBits(V));
1004 assert(Ty == Type::DoubleTy);
1005 return DoubleConstants->getOrCreate(Ty, DoubleToBits(V));
1009 //---- ConstantAggregateZero::get() implementation...
1012 // ConstantAggregateZero does not take extra "value" argument...
1013 template<class ValType>
1014 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
1015 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
1016 return new ConstantAggregateZero(Ty);
1021 struct ConvertConstantType<ConstantAggregateZero, Type> {
1022 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1023 // Make everyone now use a constant of the new type...
1024 Constant *New = ConstantAggregateZero::get(NewTy);
1025 assert(New != OldC && "Didn't replace constant??");
1026 OldC->uncheckedReplaceAllUsesWith(New);
1027 OldC->destroyConstant(); // This constant is now dead, destroy it.
1032 static ManagedStatic<ValueMap<char, Type,
1033 ConstantAggregateZero> > AggZeroConstants;
1035 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1037 Constant *ConstantAggregateZero::get(const Type *Ty) {
1038 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<PackedType>(Ty)) &&
1039 "Cannot create an aggregate zero of non-aggregate type!");
1040 return AggZeroConstants->getOrCreate(Ty, 0);
1043 // destroyConstant - Remove the constant from the constant table...
1045 void ConstantAggregateZero::destroyConstant() {
1046 AggZeroConstants->remove(this);
1047 destroyConstantImpl();
1050 //---- ConstantArray::get() implementation...
1054 struct ConvertConstantType<ConstantArray, ArrayType> {
1055 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1056 // Make everyone now use a constant of the new type...
1057 std::vector<Constant*> C;
1058 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1059 C.push_back(cast<Constant>(OldC->getOperand(i)));
1060 Constant *New = ConstantArray::get(NewTy, C);
1061 assert(New != OldC && "Didn't replace constant??");
1062 OldC->uncheckedReplaceAllUsesWith(New);
1063 OldC->destroyConstant(); // This constant is now dead, destroy it.
1068 static std::vector<Constant*> getValType(ConstantArray *CA) {
1069 std::vector<Constant*> Elements;
1070 Elements.reserve(CA->getNumOperands());
1071 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1072 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1076 typedef ValueMap<std::vector<Constant*>, ArrayType,
1077 ConstantArray, true /*largekey*/> ArrayConstantsTy;
1078 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
1080 Constant *ConstantArray::get(const ArrayType *Ty,
1081 const std::vector<Constant*> &V) {
1082 // If this is an all-zero array, return a ConstantAggregateZero object
1085 if (!C->isNullValue())
1086 return ArrayConstants->getOrCreate(Ty, V);
1087 for (unsigned i = 1, e = V.size(); i != e; ++i)
1089 return ArrayConstants->getOrCreate(Ty, V);
1091 return ConstantAggregateZero::get(Ty);
1094 // destroyConstant - Remove the constant from the constant table...
1096 void ConstantArray::destroyConstant() {
1097 ArrayConstants->remove(this);
1098 destroyConstantImpl();
1101 /// ConstantArray::get(const string&) - Return an array that is initialized to
1102 /// contain the specified string. If length is zero then a null terminator is
1103 /// added to the specified string so that it may be used in a natural way.
1104 /// Otherwise, the length parameter specifies how much of the string to use
1105 /// and it won't be null terminated.
1107 Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
1108 std::vector<Constant*> ElementVals;
1109 for (unsigned i = 0; i < Str.length(); ++i)
1110 ElementVals.push_back(ConstantInt::get(Type::SByteTy, Str[i]));
1112 // Add a null terminator to the string...
1114 ElementVals.push_back(ConstantInt::get(Type::SByteTy, 0));
1117 ArrayType *ATy = ArrayType::get(Type::SByteTy, ElementVals.size());
1118 return ConstantArray::get(ATy, ElementVals);
1121 /// isString - This method returns true if the array is an array of sbyte or
1122 /// ubyte, and if the elements of the array are all ConstantInt's.
1123 bool ConstantArray::isString() const {
1124 // Check the element type for sbyte or ubyte...
1125 if (getType()->getElementType() != Type::UByteTy &&
1126 getType()->getElementType() != Type::SByteTy)
1128 // Check the elements to make sure they are all integers, not constant
1130 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1131 if (!isa<ConstantInt>(getOperand(i)))
1136 /// isCString - This method returns true if the array is a string (see
1137 /// isString) and it ends in a null byte \0 and does not contains any other
1138 /// null bytes except its terminator.
1139 bool ConstantArray::isCString() const {
1140 // Check the element type for sbyte or ubyte...
1141 if (getType()->getElementType() != Type::UByteTy &&
1142 getType()->getElementType() != Type::SByteTy)
1144 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1145 // Last element must be a null.
1146 if (getOperand(getNumOperands()-1) != Zero)
1148 // Other elements must be non-null integers.
1149 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1150 if (!isa<ConstantInt>(getOperand(i)))
1152 if (getOperand(i) == Zero)
1159 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
1160 // then this method converts the array to an std::string and returns it.
1161 // Otherwise, it asserts out.
1163 std::string ConstantArray::getAsString() const {
1164 assert(isString() && "Not a string!");
1166 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1167 Result += (char)cast<ConstantInt>(getOperand(i))->getZExtValue();
1172 //---- ConstantStruct::get() implementation...
1177 struct ConvertConstantType<ConstantStruct, StructType> {
1178 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1179 // Make everyone now use a constant of the new type...
1180 std::vector<Constant*> C;
1181 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1182 C.push_back(cast<Constant>(OldC->getOperand(i)));
1183 Constant *New = ConstantStruct::get(NewTy, C);
1184 assert(New != OldC && "Didn't replace constant??");
1186 OldC->uncheckedReplaceAllUsesWith(New);
1187 OldC->destroyConstant(); // This constant is now dead, destroy it.
1192 typedef ValueMap<std::vector<Constant*>, StructType,
1193 ConstantStruct, true /*largekey*/> StructConstantsTy;
1194 static ManagedStatic<StructConstantsTy> StructConstants;
1196 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1197 std::vector<Constant*> Elements;
1198 Elements.reserve(CS->getNumOperands());
1199 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1200 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1204 Constant *ConstantStruct::get(const StructType *Ty,
1205 const std::vector<Constant*> &V) {
1206 // Create a ConstantAggregateZero value if all elements are zeros...
1207 for (unsigned i = 0, e = V.size(); i != e; ++i)
1208 if (!V[i]->isNullValue())
1209 return StructConstants->getOrCreate(Ty, V);
1211 return ConstantAggregateZero::get(Ty);
1214 Constant *ConstantStruct::get(const std::vector<Constant*> &V) {
1215 std::vector<const Type*> StructEls;
1216 StructEls.reserve(V.size());
1217 for (unsigned i = 0, e = V.size(); i != e; ++i)
1218 StructEls.push_back(V[i]->getType());
1219 return get(StructType::get(StructEls), V);
1222 // destroyConstant - Remove the constant from the constant table...
1224 void ConstantStruct::destroyConstant() {
1225 StructConstants->remove(this);
1226 destroyConstantImpl();
1229 //---- ConstantPacked::get() implementation...
1233 struct ConvertConstantType<ConstantPacked, PackedType> {
1234 static void convert(ConstantPacked *OldC, const PackedType *NewTy) {
1235 // Make everyone now use a constant of the new type...
1236 std::vector<Constant*> C;
1237 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1238 C.push_back(cast<Constant>(OldC->getOperand(i)));
1239 Constant *New = ConstantPacked::get(NewTy, C);
1240 assert(New != OldC && "Didn't replace constant??");
1241 OldC->uncheckedReplaceAllUsesWith(New);
1242 OldC->destroyConstant(); // This constant is now dead, destroy it.
1247 static std::vector<Constant*> getValType(ConstantPacked *CP) {
1248 std::vector<Constant*> Elements;
1249 Elements.reserve(CP->getNumOperands());
1250 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1251 Elements.push_back(CP->getOperand(i));
1255 static ManagedStatic<ValueMap<std::vector<Constant*>, PackedType,
1256 ConstantPacked> > PackedConstants;
1258 Constant *ConstantPacked::get(const PackedType *Ty,
1259 const std::vector<Constant*> &V) {
1260 // If this is an all-zero packed, return a ConstantAggregateZero object
1263 if (!C->isNullValue())
1264 return PackedConstants->getOrCreate(Ty, V);
1265 for (unsigned i = 1, e = V.size(); i != e; ++i)
1267 return PackedConstants->getOrCreate(Ty, V);
1269 return ConstantAggregateZero::get(Ty);
1272 Constant *ConstantPacked::get(const std::vector<Constant*> &V) {
1273 assert(!V.empty() && "Cannot infer type if V is empty");
1274 return get(PackedType::get(V.front()->getType(),V.size()), V);
1277 // destroyConstant - Remove the constant from the constant table...
1279 void ConstantPacked::destroyConstant() {
1280 PackedConstants->remove(this);
1281 destroyConstantImpl();
1284 //---- ConstantPointerNull::get() implementation...
1288 // ConstantPointerNull does not take extra "value" argument...
1289 template<class ValType>
1290 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1291 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1292 return new ConstantPointerNull(Ty);
1297 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1298 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1299 // Make everyone now use a constant of the new type...
1300 Constant *New = ConstantPointerNull::get(NewTy);
1301 assert(New != OldC && "Didn't replace constant??");
1302 OldC->uncheckedReplaceAllUsesWith(New);
1303 OldC->destroyConstant(); // This constant is now dead, destroy it.
1308 static ManagedStatic<ValueMap<char, PointerType,
1309 ConstantPointerNull> > NullPtrConstants;
1311 static char getValType(ConstantPointerNull *) {
1316 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1317 return NullPtrConstants->getOrCreate(Ty, 0);
1320 // destroyConstant - Remove the constant from the constant table...
1322 void ConstantPointerNull::destroyConstant() {
1323 NullPtrConstants->remove(this);
1324 destroyConstantImpl();
1328 //---- UndefValue::get() implementation...
1332 // UndefValue does not take extra "value" argument...
1333 template<class ValType>
1334 struct ConstantCreator<UndefValue, Type, ValType> {
1335 static UndefValue *create(const Type *Ty, const ValType &V) {
1336 return new UndefValue(Ty);
1341 struct ConvertConstantType<UndefValue, Type> {
1342 static void convert(UndefValue *OldC, const Type *NewTy) {
1343 // Make everyone now use a constant of the new type.
1344 Constant *New = UndefValue::get(NewTy);
1345 assert(New != OldC && "Didn't replace constant??");
1346 OldC->uncheckedReplaceAllUsesWith(New);
1347 OldC->destroyConstant(); // This constant is now dead, destroy it.
1352 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1354 static char getValType(UndefValue *) {
1359 UndefValue *UndefValue::get(const Type *Ty) {
1360 return UndefValueConstants->getOrCreate(Ty, 0);
1363 // destroyConstant - Remove the constant from the constant table.
1365 void UndefValue::destroyConstant() {
1366 UndefValueConstants->remove(this);
1367 destroyConstantImpl();
1371 //---- ConstantExpr::get() implementations...
1373 typedef std::pair<unsigned, std::vector<Constant*> > ExprMapKeyType;
1377 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1378 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1379 unsigned short pred = 0) {
1380 if (Instruction::isCast(V.first))
1381 return new UnaryConstantExpr(V.first, V.second[0], Ty);
1382 if ((V.first >= Instruction::BinaryOpsBegin &&
1383 V.first < Instruction::BinaryOpsEnd) ||
1384 V.first == Instruction::Shl ||
1385 V.first == Instruction::LShr ||
1386 V.first == Instruction::AShr)
1387 return new BinaryConstantExpr(V.first, V.second[0], V.second[1]);
1388 if (V.first == Instruction::Select)
1389 return new SelectConstantExpr(V.second[0], V.second[1], V.second[2]);
1390 if (V.first == Instruction::ExtractElement)
1391 return new ExtractElementConstantExpr(V.second[0], V.second[1]);
1392 if (V.first == Instruction::InsertElement)
1393 return new InsertElementConstantExpr(V.second[0], V.second[1],
1395 if (V.first == Instruction::ShuffleVector)
1396 return new ShuffleVectorConstantExpr(V.second[0], V.second[1],
1398 if (V.first == Instruction::ICmp)
1399 return new CompareConstantExpr(Instruction::ICmp, pred,
1400 V.second[0], V.second[1]);
1401 if (V.first == Instruction::FCmp)
1402 return new CompareConstantExpr(Instruction::FCmp, pred,
1403 V.second[0], V.second[1]);
1405 assert(V.first == Instruction::GetElementPtr && "Invalid ConstantExpr!");
1406 std::vector<Constant*> IdxList(V.second.begin()+1, V.second.end());
1407 return new GetElementPtrConstantExpr(V.second[0], IdxList, Ty);
1412 struct ConvertConstantType<ConstantExpr, Type> {
1413 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1415 switch (OldC->getOpcode()) {
1416 case Instruction::Trunc:
1417 case Instruction::ZExt:
1418 case Instruction::SExt:
1419 case Instruction::FPTrunc:
1420 case Instruction::FPExt:
1421 case Instruction::UIToFP:
1422 case Instruction::SIToFP:
1423 case Instruction::FPToUI:
1424 case Instruction::FPToSI:
1425 case Instruction::PtrToInt:
1426 case Instruction::IntToPtr:
1427 case Instruction::BitCast:
1428 New = ConstantExpr::getCast(
1429 OldC->getOpcode(), OldC->getOperand(0), NewTy);
1431 case Instruction::Select:
1432 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1433 OldC->getOperand(1),
1434 OldC->getOperand(2));
1436 case Instruction::Shl:
1437 case Instruction::LShr:
1438 case Instruction::AShr:
1439 New = ConstantExpr::getShiftTy(NewTy, OldC->getOpcode(),
1440 OldC->getOperand(0), OldC->getOperand(1));
1443 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1444 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1445 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1446 OldC->getOperand(1));
1448 case Instruction::GetElementPtr:
1449 // Make everyone now use a constant of the new type...
1450 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1451 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0), Idx);
1455 assert(New != OldC && "Didn't replace constant??");
1456 OldC->uncheckedReplaceAllUsesWith(New);
1457 OldC->destroyConstant(); // This constant is now dead, destroy it.
1460 } // end namespace llvm
1463 static ExprMapKeyType getValType(ConstantExpr *CE) {
1464 std::vector<Constant*> Operands;
1465 Operands.reserve(CE->getNumOperands());
1466 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1467 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1468 return ExprMapKeyType(CE->getOpcode(), Operands);
1471 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1472 ConstantExpr> > ExprConstants;
1474 /// This is a utility function to handle folding of casts and lookup of the
1475 /// cast in the ExprConstants map. It is usedby the various get* methods below.
1476 static inline Constant *getFoldedCast(
1477 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1478 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1479 // Fold a few common cases
1480 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1483 // Look up the constant in the table first to ensure uniqueness
1484 std::vector<Constant*> argVec(1, C);
1485 ExprMapKeyType Key = std::make_pair(opc, argVec);
1486 return ExprConstants->getOrCreate(Ty, Key);
1489 Constant *ConstantExpr::getInferredCast(Constant *C, bool SrcIsSigned,
1490 const Type *Ty, bool DestIsSigned) {
1491 // Note: we can't inline this because it requires the Instructions.h header
1493 CastInst::getCastOpcode(C, SrcIsSigned, Ty, DestIsSigned), C, Ty);
1496 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1497 Instruction::CastOps opc = Instruction::CastOps(oc);
1498 assert(Instruction::isCast(opc) && "opcode out of range");
1499 assert(C && Ty && "Null arguments to getCast");
1500 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1504 assert(0 && "Invalid cast opcode");
1506 case Instruction::Trunc: return getTrunc(C, Ty);
1507 case Instruction::ZExt: return getZeroExtend(C, Ty);
1508 case Instruction::SExt: return getSignExtend(C, Ty);
1509 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1510 case Instruction::FPExt: return getFPExtend(C, Ty);
1511 case Instruction::UIToFP: return getUIToFP(C, Ty);
1512 case Instruction::SIToFP: return getSIToFP(C, Ty);
1513 case Instruction::FPToUI: return getFPToUI(C, Ty);
1514 case Instruction::FPToSI: return getFPToSI(C, Ty);
1515 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1516 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1517 case Instruction::BitCast: return getBitCast(C, Ty);
1522 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1523 assert(C->getType()->isInteger() && "Trunc operand must be integer");
1524 assert(Ty->isIntegral() && "Trunc produces only integral");
1525 assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1526 "SrcTy must be larger than DestTy for Trunc!");
1528 return getFoldedCast(Instruction::Trunc, C, Ty);
1531 Constant *ConstantExpr::getSignExtend(Constant *C, const Type *Ty) {
1532 assert(C->getType()->isIntegral() && "SEXt operand must be integral");
1533 assert(Ty->isInteger() && "SExt produces only integer");
1534 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1535 "SrcTy must be smaller than DestTy for SExt!");
1537 return getFoldedCast(Instruction::SExt, C, Ty);
1540 Constant *ConstantExpr::getZeroExtend(Constant *C, const Type *Ty) {
1541 assert(C->getType()->isIntegral() && "ZEXt operand must be integral");
1542 assert(Ty->isInteger() && "ZExt produces only integer");
1543 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1544 "SrcTy must be smaller than DestTy for ZExt!");
1546 return getFoldedCast(Instruction::ZExt, C, Ty);
1549 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1550 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1551 C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1552 "This is an illegal floating point truncation!");
1553 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1556 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1557 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1558 C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1559 "This is an illegal floating point extension!");
1560 return getFoldedCast(Instruction::FPExt, C, Ty);
1563 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1564 assert(C->getType()->isIntegral() && Ty->isFloatingPoint() &&
1565 "This is an illegal uint to floating point cast!");
1566 return getFoldedCast(Instruction::UIToFP, C, Ty);
1569 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1570 assert(C->getType()->isIntegral() && Ty->isFloatingPoint() &&
1571 "This is an illegal sint to floating point cast!");
1572 return getFoldedCast(Instruction::SIToFP, C, Ty);
1575 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1576 assert(C->getType()->isFloatingPoint() && Ty->isIntegral() &&
1577 "This is an illegal floating point to uint cast!");
1578 return getFoldedCast(Instruction::FPToUI, C, Ty);
1581 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1582 assert(C->getType()->isFloatingPoint() && Ty->isIntegral() &&
1583 "This is an illegal floating point to sint cast!");
1584 return getFoldedCast(Instruction::FPToSI, C, Ty);
1587 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1588 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1589 assert(DstTy->isIntegral() && "PtrToInt destination must be integral");
1590 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1593 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1594 assert(C->getType()->isIntegral() && "IntToPtr source must be integral");
1595 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1596 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1599 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1600 // BitCast implies a no-op cast of type only. No bits change. However, you
1601 // can't cast pointers to anything but pointers.
1602 const Type *SrcTy = C->getType();
1603 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1604 "Bitcast cannot cast pointer to non-pointer and vice versa");
1606 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1607 // or nonptr->ptr). For all the other types, the cast is okay if source and
1608 // destination bit widths are identical.
1609 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1610 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1611 assert(SrcBitSize == DstBitSize && "Bitcast requies types of same width");
1612 return getFoldedCast(Instruction::BitCast, C, DstTy);
1615 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
1616 // sizeof is implemented as: (ulong) gep (Ty*)null, 1
1617 return getCast(Instruction::PtrToInt, getGetElementPtr(getNullValue(
1618 PointerType::get(Ty)), std::vector<Constant*>(1,
1619 ConstantInt::get(Type::UIntTy, 1))), Type::ULongTy);
1622 Constant *ConstantExpr::getPtrPtrFromArrayPtr(Constant *C) {
1623 // pointer from array is implemented as: getelementptr arr ptr, 0, 0
1624 static std::vector<Constant*> Indices(2, ConstantInt::get(Type::UIntTy, 0));
1626 return ConstantExpr::getGetElementPtr(C, Indices);
1629 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1630 Constant *C1, Constant *C2) {
1631 if (Opcode == Instruction::Shl || Opcode == Instruction::LShr ||
1632 Opcode == Instruction::AShr)
1633 return getShiftTy(ReqTy, Opcode, C1, C2);
1634 // Check the operands for consistency first
1635 assert(Opcode >= Instruction::BinaryOpsBegin &&
1636 Opcode < Instruction::BinaryOpsEnd &&
1637 "Invalid opcode in binary constant expression");
1638 assert(C1->getType() == C2->getType() &&
1639 "Operand types in binary constant expression should match");
1641 if (ReqTy == C1->getType() || (Instruction::isComparison(Opcode) &&
1642 ReqTy == Type::BoolTy))
1643 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1644 return FC; // Fold a few common cases...
1646 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1647 ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1648 return ExprConstants->getOrCreate(ReqTy, Key);
1651 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1654 case Instruction::Add:
1655 case Instruction::Sub:
1656 case Instruction::Mul:
1657 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1658 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
1659 isa<PackedType>(C1->getType())) &&
1660 "Tried to create an arithmetic operation on a non-arithmetic type!");
1662 case Instruction::UDiv:
1663 case Instruction::SDiv:
1664 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1665 assert((C1->getType()->isInteger() || (isa<PackedType>(C1->getType()) &&
1666 cast<PackedType>(C1->getType())->getElementType()->isInteger())) &&
1667 "Tried to create an arithmetic operation on a non-arithmetic type!");
1669 case Instruction::FDiv:
1670 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1671 assert((C1->getType()->isFloatingPoint() || (isa<PackedType>(C1->getType())
1672 && cast<PackedType>(C1->getType())->getElementType()->isFloatingPoint()))
1673 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1675 case Instruction::URem:
1676 case Instruction::SRem:
1677 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1678 assert((C1->getType()->isInteger() || (isa<PackedType>(C1->getType()) &&
1679 cast<PackedType>(C1->getType())->getElementType()->isInteger())) &&
1680 "Tried to create an arithmetic operation on a non-arithmetic type!");
1682 case Instruction::FRem:
1683 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1684 assert((C1->getType()->isFloatingPoint() || (isa<PackedType>(C1->getType())
1685 && cast<PackedType>(C1->getType())->getElementType()->isFloatingPoint()))
1686 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1688 case Instruction::And:
1689 case Instruction::Or:
1690 case Instruction::Xor:
1691 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1692 assert((C1->getType()->isIntegral() || isa<PackedType>(C1->getType())) &&
1693 "Tried to create a logical operation on a non-integral type!");
1695 case Instruction::SetLT: case Instruction::SetGT: case Instruction::SetLE:
1696 case Instruction::SetGE: case Instruction::SetEQ: case Instruction::SetNE:
1697 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1699 case Instruction::Shl:
1700 case Instruction::LShr:
1701 case Instruction::AShr:
1702 assert(C2->getType() == Type::UByteTy && "Shift should be by ubyte!");
1703 assert(C1->getType()->isInteger() &&
1704 "Tried to create a shift operation on a non-integer type!");
1711 if (Instruction::isComparison(Opcode))
1712 return getTy(Type::BoolTy, Opcode, C1, C2);
1714 return getTy(C1->getType(), Opcode, C1, C2);
1717 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1718 Constant *V1, Constant *V2) {
1719 assert(C->getType() == Type::BoolTy && "Select condition must be bool!");
1720 assert(V1->getType() == V2->getType() && "Select value types must match!");
1721 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1723 if (ReqTy == V1->getType())
1724 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1725 return SC; // Fold common cases
1727 std::vector<Constant*> argVec(3, C);
1730 ExprMapKeyType Key = std::make_pair(Instruction::Select, argVec);
1731 return ExprConstants->getOrCreate(ReqTy, Key);
1734 /// getShiftTy - Return a shift left or shift right constant expr
1735 Constant *ConstantExpr::getShiftTy(const Type *ReqTy, unsigned Opcode,
1736 Constant *C1, Constant *C2) {
1737 // Check the operands for consistency first
1738 assert((Opcode == Instruction::Shl ||
1739 Opcode == Instruction::LShr ||
1740 Opcode == Instruction::AShr) &&
1741 "Invalid opcode in binary constant expression");
1742 assert(C1->getType()->isIntegral() && C2->getType() == Type::UByteTy &&
1743 "Invalid operand types for Shift constant expr!");
1745 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1746 return FC; // Fold a few common cases...
1748 // Look up the constant in the table first to ensure uniqueness
1749 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1750 ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1751 return ExprConstants->getOrCreate(ReqTy, Key);
1755 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1756 const std::vector<Value*> &IdxList) {
1757 assert(GetElementPtrInst::getIndexedType(C->getType(), IdxList, true) &&
1758 "GEP indices invalid!");
1760 if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
1761 return FC; // Fold a few common cases...
1763 assert(isa<PointerType>(C->getType()) &&
1764 "Non-pointer type for constant GetElementPtr expression");
1765 // Look up the constant in the table first to ensure uniqueness
1766 std::vector<Constant*> ArgVec;
1767 ArgVec.reserve(IdxList.size()+1);
1768 ArgVec.push_back(C);
1769 for (unsigned i = 0, e = IdxList.size(); i != e; ++i)
1770 ArgVec.push_back(cast<Constant>(IdxList[i]));
1771 const ExprMapKeyType &Key = std::make_pair(Instruction::GetElementPtr,ArgVec);
1772 return ExprConstants->getOrCreate(ReqTy, Key);
1775 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1776 const std::vector<Constant*> &IdxList){
1777 // Get the result type of the getelementptr!
1778 std::vector<Value*> VIdxList(IdxList.begin(), IdxList.end());
1780 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), VIdxList,
1782 assert(Ty && "GEP indices invalid!");
1783 return getGetElementPtrTy(PointerType::get(Ty), C, VIdxList);
1786 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1787 const std::vector<Value*> &IdxList) {
1788 // Get the result type of the getelementptr!
1789 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
1791 assert(Ty && "GEP indices invalid!");
1792 return getGetElementPtrTy(PointerType::get(Ty), C, IdxList);
1795 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1797 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1798 return FC; // Fold a few common cases...
1799 // Look up the constant in the table first to ensure uniqueness
1800 std::vector<Constant*> ArgVec(1, Val);
1801 ArgVec.push_back(Idx);
1802 const ExprMapKeyType &Key = std::make_pair(Instruction::ExtractElement,ArgVec);
1803 return ExprConstants->getOrCreate(ReqTy, Key);
1806 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1807 assert(isa<PackedType>(Val->getType()) &&
1808 "Tried to create extractelement operation on non-packed type!");
1809 assert(Idx->getType() == Type::UIntTy &&
1810 "Extractelement index must be uint type!");
1811 return getExtractElementTy(cast<PackedType>(Val->getType())->getElementType(),
1815 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1816 Constant *Elt, Constant *Idx) {
1817 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1818 return FC; // Fold a few common cases...
1819 // Look up the constant in the table first to ensure uniqueness
1820 std::vector<Constant*> ArgVec(1, Val);
1821 ArgVec.push_back(Elt);
1822 ArgVec.push_back(Idx);
1823 const ExprMapKeyType &Key = std::make_pair(Instruction::InsertElement,ArgVec);
1824 return ExprConstants->getOrCreate(ReqTy, Key);
1827 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1829 assert(isa<PackedType>(Val->getType()) &&
1830 "Tried to create insertelement operation on non-packed type!");
1831 assert(Elt->getType() == cast<PackedType>(Val->getType())->getElementType()
1832 && "Insertelement types must match!");
1833 assert(Idx->getType() == Type::UIntTy &&
1834 "Insertelement index must be uint type!");
1835 return getInsertElementTy(cast<PackedType>(Val->getType())->getElementType(),
1839 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1840 Constant *V2, Constant *Mask) {
1841 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1842 return FC; // Fold a few common cases...
1843 // Look up the constant in the table first to ensure uniqueness
1844 std::vector<Constant*> ArgVec(1, V1);
1845 ArgVec.push_back(V2);
1846 ArgVec.push_back(Mask);
1847 const ExprMapKeyType &Key = std::make_pair(Instruction::ShuffleVector,ArgVec);
1848 return ExprConstants->getOrCreate(ReqTy, Key);
1851 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1853 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1854 "Invalid shuffle vector constant expr operands!");
1855 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
1858 // destroyConstant - Remove the constant from the constant table...
1860 void ConstantExpr::destroyConstant() {
1861 ExprConstants->remove(this);
1862 destroyConstantImpl();
1865 const char *ConstantExpr::getOpcodeName() const {
1866 return Instruction::getOpcodeName(getOpcode());
1869 //===----------------------------------------------------------------------===//
1870 // replaceUsesOfWithOnConstant implementations
1872 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1874 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1875 Constant *ToC = cast<Constant>(To);
1877 unsigned OperandToUpdate = U-OperandList;
1878 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1880 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
1881 Lookup.first.first = getType();
1882 Lookup.second = this;
1884 std::vector<Constant*> &Values = Lookup.first.second;
1885 Values.reserve(getNumOperands()); // Build replacement array.
1887 // Fill values with the modified operands of the constant array. Also,
1888 // compute whether this turns into an all-zeros array.
1889 bool isAllZeros = false;
1890 if (!ToC->isNullValue()) {
1891 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1892 Values.push_back(cast<Constant>(O->get()));
1895 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1896 Constant *Val = cast<Constant>(O->get());
1897 Values.push_back(Val);
1898 if (isAllZeros) isAllZeros = Val->isNullValue();
1901 Values[OperandToUpdate] = ToC;
1903 Constant *Replacement = 0;
1905 Replacement = ConstantAggregateZero::get(getType());
1907 // Check to see if we have this array type already.
1909 ArrayConstantsTy::MapTy::iterator I =
1910 ArrayConstants->InsertOrGetItem(Lookup, Exists);
1913 Replacement = I->second;
1915 // Okay, the new shape doesn't exist in the system yet. Instead of
1916 // creating a new constant array, inserting it, replaceallusesof'ing the
1917 // old with the new, then deleting the old... just update the current one
1919 ArrayConstants->MoveConstantToNewSlot(this, I);
1921 // Update to the new value.
1922 setOperand(OperandToUpdate, ToC);
1927 // Otherwise, I do need to replace this with an existing value.
1928 assert(Replacement != this && "I didn't contain From!");
1930 // Everyone using this now uses the replacement.
1931 uncheckedReplaceAllUsesWith(Replacement);
1933 // Delete the old constant!
1937 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
1939 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1940 Constant *ToC = cast<Constant>(To);
1942 unsigned OperandToUpdate = U-OperandList;
1943 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1945 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
1946 Lookup.first.first = getType();
1947 Lookup.second = this;
1948 std::vector<Constant*> &Values = Lookup.first.second;
1949 Values.reserve(getNumOperands()); // Build replacement struct.
1952 // Fill values with the modified operands of the constant struct. Also,
1953 // compute whether this turns into an all-zeros struct.
1954 bool isAllZeros = false;
1955 if (!ToC->isNullValue()) {
1956 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1957 Values.push_back(cast<Constant>(O->get()));
1960 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1961 Constant *Val = cast<Constant>(O->get());
1962 Values.push_back(Val);
1963 if (isAllZeros) isAllZeros = Val->isNullValue();
1966 Values[OperandToUpdate] = ToC;
1968 Constant *Replacement = 0;
1970 Replacement = ConstantAggregateZero::get(getType());
1972 // Check to see if we have this array type already.
1974 StructConstantsTy::MapTy::iterator I =
1975 StructConstants->InsertOrGetItem(Lookup, Exists);
1978 Replacement = I->second;
1980 // Okay, the new shape doesn't exist in the system yet. Instead of
1981 // creating a new constant struct, inserting it, replaceallusesof'ing the
1982 // old with the new, then deleting the old... just update the current one
1984 StructConstants->MoveConstantToNewSlot(this, I);
1986 // Update to the new value.
1987 setOperand(OperandToUpdate, ToC);
1992 assert(Replacement != this && "I didn't contain From!");
1994 // Everyone using this now uses the replacement.
1995 uncheckedReplaceAllUsesWith(Replacement);
1997 // Delete the old constant!
2001 void ConstantPacked::replaceUsesOfWithOnConstant(Value *From, Value *To,
2003 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2005 std::vector<Constant*> Values;
2006 Values.reserve(getNumOperands()); // Build replacement array...
2007 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2008 Constant *Val = getOperand(i);
2009 if (Val == From) Val = cast<Constant>(To);
2010 Values.push_back(Val);
2013 Constant *Replacement = ConstantPacked::get(getType(), Values);
2014 assert(Replacement != this && "I didn't contain From!");
2016 // Everyone using this now uses the replacement.
2017 uncheckedReplaceAllUsesWith(Replacement);
2019 // Delete the old constant!
2023 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2025 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2026 Constant *To = cast<Constant>(ToV);
2028 Constant *Replacement = 0;
2029 if (getOpcode() == Instruction::GetElementPtr) {
2030 std::vector<Constant*> Indices;
2031 Constant *Pointer = getOperand(0);
2032 Indices.reserve(getNumOperands()-1);
2033 if (Pointer == From) Pointer = To;
2035 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2036 Constant *Val = getOperand(i);
2037 if (Val == From) Val = To;
2038 Indices.push_back(Val);
2040 Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
2041 } else if (isCast()) {
2042 assert(getOperand(0) == From && "Cast only has one use!");
2043 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2044 } else if (getOpcode() == Instruction::Select) {
2045 Constant *C1 = getOperand(0);
2046 Constant *C2 = getOperand(1);
2047 Constant *C3 = getOperand(2);
2048 if (C1 == From) C1 = To;
2049 if (C2 == From) C2 = To;
2050 if (C3 == From) C3 = To;
2051 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2052 } else if (getOpcode() == Instruction::ExtractElement) {
2053 Constant *C1 = getOperand(0);
2054 Constant *C2 = getOperand(1);
2055 if (C1 == From) C1 = To;
2056 if (C2 == From) C2 = To;
2057 Replacement = ConstantExpr::getExtractElement(C1, C2);
2058 } else if (getOpcode() == Instruction::InsertElement) {
2059 Constant *C1 = getOperand(0);
2060 Constant *C2 = getOperand(1);
2061 Constant *C3 = getOperand(1);
2062 if (C1 == From) C1 = To;
2063 if (C2 == From) C2 = To;
2064 if (C3 == From) C3 = To;
2065 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2066 } else if (getOpcode() == Instruction::ShuffleVector) {
2067 Constant *C1 = getOperand(0);
2068 Constant *C2 = getOperand(1);
2069 Constant *C3 = getOperand(2);
2070 if (C1 == From) C1 = To;
2071 if (C2 == From) C2 = To;
2072 if (C3 == From) C3 = To;
2073 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2074 } else if (getNumOperands() == 2) {
2075 Constant *C1 = getOperand(0);
2076 Constant *C2 = getOperand(1);
2077 if (C1 == From) C1 = To;
2078 if (C2 == From) C2 = To;
2079 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2081 assert(0 && "Unknown ConstantExpr type!");
2085 assert(Replacement != this && "I didn't contain From!");
2087 // Everyone using this now uses the replacement.
2088 uncheckedReplaceAllUsesWith(Replacement);
2090 // Delete the old constant!
2095 /// getStringValue - Turn an LLVM constant pointer that eventually points to a
2096 /// global into a string value. Return an empty string if we can't do it.
2097 /// Parameter Chop determines if the result is chopped at the first null
2100 std::string Constant::getStringValue(bool Chop, unsigned Offset) {
2101 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
2102 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
2103 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
2104 if (Init->isString()) {
2105 std::string Result = Init->getAsString();
2106 if (Offset < Result.size()) {
2107 // If we are pointing INTO The string, erase the beginning...
2108 Result.erase(Result.begin(), Result.begin()+Offset);
2110 // Take off the null terminator, and any string fragments after it.
2112 std::string::size_type NullPos = Result.find_first_of((char)0);
2113 if (NullPos != std::string::npos)
2114 Result.erase(Result.begin()+NullPos, Result.end());
2120 } else if (Constant *C = dyn_cast<Constant>(this)) {
2121 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
2122 return GV->getStringValue(Chop, Offset);
2123 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2124 if (CE->getOpcode() == Instruction::GetElementPtr) {
2125 // Turn a gep into the specified offset.
2126 if (CE->getNumOperands() == 3 &&
2127 cast<Constant>(CE->getOperand(1))->isNullValue() &&
2128 isa<ConstantInt>(CE->getOperand(2))) {
2129 Offset += cast<ConstantInt>(CE->getOperand(2))->getZExtValue();
2130 return CE->getOperand(0)->getStringValue(Chop, Offset);