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/MathExtras.h"
23 #include "llvm/Support/Compiler.h"
24 #include "llvm/Support/ManagedStatic.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 std::cerr << "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 // Static constructor to create a '0' constant of arbitrary type...
62 Constant *Constant::getNullValue(const Type *Ty) {
63 switch (Ty->getTypeID()) {
64 case Type::BoolTyID: {
65 static Constant *NullBool = ConstantBool::get(false);
68 case Type::SByteTyID: {
69 static Constant *NullSByte = ConstantSInt::get(Type::SByteTy, 0);
72 case Type::UByteTyID: {
73 static Constant *NullUByte = ConstantUInt::get(Type::UByteTy, 0);
76 case Type::ShortTyID: {
77 static Constant *NullShort = ConstantSInt::get(Type::ShortTy, 0);
80 case Type::UShortTyID: {
81 static Constant *NullUShort = ConstantUInt::get(Type::UShortTy, 0);
85 static Constant *NullInt = ConstantSInt::get(Type::IntTy, 0);
88 case Type::UIntTyID: {
89 static Constant *NullUInt = ConstantUInt::get(Type::UIntTy, 0);
92 case Type::LongTyID: {
93 static Constant *NullLong = ConstantSInt::get(Type::LongTy, 0);
96 case Type::ULongTyID: {
97 static Constant *NullULong = ConstantUInt::get(Type::ULongTy, 0);
101 case Type::FloatTyID: {
102 static Constant *NullFloat = ConstantFP::get(Type::FloatTy, 0);
105 case Type::DoubleTyID: {
106 static Constant *NullDouble = ConstantFP::get(Type::DoubleTy, 0);
110 case Type::PointerTyID:
111 return ConstantPointerNull::get(cast<PointerType>(Ty));
113 case Type::StructTyID:
114 case Type::ArrayTyID:
115 case Type::PackedTyID:
116 return ConstantAggregateZero::get(Ty);
118 // Function, Label, or Opaque type?
119 assert(!"Cannot create a null constant of that type!");
124 // Static constructor to create the maximum constant of an integral type...
125 ConstantIntegral *ConstantIntegral::getMaxValue(const Type *Ty) {
126 switch (Ty->getTypeID()) {
127 case Type::BoolTyID: return ConstantBool::getTrue();
128 case Type::SByteTyID:
129 case Type::ShortTyID:
131 case Type::LongTyID: {
132 // Calculate 011111111111111...
133 unsigned TypeBits = Ty->getPrimitiveSize()*8;
134 int64_t Val = INT64_MAX; // All ones
135 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
136 return ConstantSInt::get(Ty, Val);
139 case Type::UByteTyID:
140 case Type::UShortTyID:
142 case Type::ULongTyID: return getAllOnesValue(Ty);
148 // Static constructor to create the minimum constant for an integral type...
149 ConstantIntegral *ConstantIntegral::getMinValue(const Type *Ty) {
150 switch (Ty->getTypeID()) {
151 case Type::BoolTyID: return ConstantBool::getFalse();
152 case Type::SByteTyID:
153 case Type::ShortTyID:
155 case Type::LongTyID: {
156 // Calculate 1111111111000000000000
157 unsigned TypeBits = Ty->getPrimitiveSize()*8;
158 int64_t Val = -1; // All ones
159 Val <<= TypeBits-1; // Shift over to the right spot
160 return ConstantSInt::get(Ty, Val);
163 case Type::UByteTyID:
164 case Type::UShortTyID:
166 case Type::ULongTyID: return ConstantUInt::get(Ty, 0);
172 // Static constructor to create an integral constant with all bits set
173 ConstantIntegral *ConstantIntegral::getAllOnesValue(const Type *Ty) {
174 switch (Ty->getTypeID()) {
175 case Type::BoolTyID: return ConstantBool::getTrue();
176 case Type::SByteTyID:
177 case Type::ShortTyID:
179 case Type::LongTyID: return ConstantSInt::get(Ty, -1);
181 case Type::UByteTyID:
182 case Type::UShortTyID:
184 case Type::ULongTyID: {
185 // Calculate ~0 of the right type...
186 unsigned TypeBits = Ty->getPrimitiveSize()*8;
187 uint64_t Val = ~0ULL; // All ones
188 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
189 return ConstantUInt::get(Ty, Val);
195 bool ConstantUInt::isAllOnesValue() const {
196 unsigned TypeBits = getType()->getPrimitiveSize()*8;
197 uint64_t Val = ~0ULL; // All ones
198 Val >>= 64-TypeBits; // Shift out inappropriate bits
199 return getValue() == Val;
203 //===----------------------------------------------------------------------===//
204 // ConstantXXX Classes
205 //===----------------------------------------------------------------------===//
207 //===----------------------------------------------------------------------===//
208 // Normal Constructors
210 ConstantIntegral::ConstantIntegral(const Type *Ty, ValueTy VT, uint64_t V)
211 : Constant(Ty, VT, 0, 0) {
215 ConstantBool::ConstantBool(bool V)
216 : ConstantIntegral(Type::BoolTy, ConstantBoolVal, V) {
219 ConstantInt::ConstantInt(const Type *Ty, ValueTy VT, uint64_t V)
220 : ConstantIntegral(Ty, VT, V) {
223 ConstantSInt::ConstantSInt(const Type *Ty, int64_t V)
224 : ConstantInt(Ty, ConstantSIntVal, V) {
225 assert(Ty->isInteger() && Ty->isSigned() &&
226 "Illegal type for signed integer constant!");
227 assert(isValueValidForType(Ty, V) && "Value too large for type!");
230 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V)
231 : ConstantInt(Ty, ConstantUIntVal, V) {
232 assert(Ty->isInteger() && Ty->isUnsigned() &&
233 "Illegal type for unsigned integer constant!");
234 assert(isValueValidForType(Ty, V) && "Value too large for type!");
237 ConstantFP::ConstantFP(const Type *Ty, double V)
238 : Constant(Ty, ConstantFPVal, 0, 0) {
239 assert(isValueValidForType(Ty, V) && "Value too large for type!");
243 ConstantArray::ConstantArray(const ArrayType *T,
244 const std::vector<Constant*> &V)
245 : Constant(T, ConstantArrayVal, new Use[V.size()], V.size()) {
246 assert(V.size() == T->getNumElements() &&
247 "Invalid initializer vector for constant array");
248 Use *OL = OperandList;
249 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
252 assert((C->getType() == T->getElementType() ||
254 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
255 "Initializer for array element doesn't match array element type!");
260 ConstantArray::~ConstantArray() {
261 delete [] OperandList;
264 ConstantStruct::ConstantStruct(const StructType *T,
265 const std::vector<Constant*> &V)
266 : Constant(T, ConstantStructVal, new Use[V.size()], V.size()) {
267 assert(V.size() == T->getNumElements() &&
268 "Invalid initializer vector for constant structure");
269 Use *OL = OperandList;
270 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
273 assert((C->getType() == T->getElementType(I-V.begin()) ||
274 ((T->getElementType(I-V.begin())->isAbstract() ||
275 C->getType()->isAbstract()) &&
276 T->getElementType(I-V.begin())->getTypeID() ==
277 C->getType()->getTypeID())) &&
278 "Initializer for struct element doesn't match struct element type!");
283 ConstantStruct::~ConstantStruct() {
284 delete [] OperandList;
288 ConstantPacked::ConstantPacked(const PackedType *T,
289 const std::vector<Constant*> &V)
290 : Constant(T, ConstantPackedVal, new Use[V.size()], V.size()) {
291 Use *OL = OperandList;
292 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
295 assert((C->getType() == T->getElementType() ||
297 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
298 "Initializer for packed element doesn't match packed element type!");
303 ConstantPacked::~ConstantPacked() {
304 delete [] OperandList;
307 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
308 /// behind the scenes to implement unary constant exprs.
310 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
313 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
314 : ConstantExpr(Ty, Opcode, &Op, 1), Op(C, this) {}
318 static bool isSetCC(unsigned Opcode) {
319 return Opcode == Instruction::SetEQ || Opcode == Instruction::SetNE ||
320 Opcode == Instruction::SetLT || Opcode == Instruction::SetGT ||
321 Opcode == Instruction::SetLE || Opcode == Instruction::SetGE;
324 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
325 /// behind the scenes to implement binary constant exprs.
327 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
330 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
331 : ConstantExpr(isSetCC(Opcode) ? Type::BoolTy : C1->getType(),
333 Ops[0].init(C1, this);
334 Ops[1].init(C2, this);
339 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
340 /// behind the scenes to implement select constant exprs.
342 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
345 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
346 : ConstantExpr(C2->getType(), Instruction::Select, Ops, 3) {
347 Ops[0].init(C1, this);
348 Ops[1].init(C2, this);
349 Ops[2].init(C3, this);
354 /// ExtractElementConstantExpr - This class is private to
355 /// Constants.cpp, and is used behind the scenes to implement
356 /// extractelement constant exprs.
358 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
361 ExtractElementConstantExpr(Constant *C1, Constant *C2)
362 : ConstantExpr(cast<PackedType>(C1->getType())->getElementType(),
363 Instruction::ExtractElement, Ops, 2) {
364 Ops[0].init(C1, this);
365 Ops[1].init(C2, this);
370 /// InsertElementConstantExpr - This class is private to
371 /// Constants.cpp, and is used behind the scenes to implement
372 /// insertelement constant exprs.
374 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
377 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
378 : ConstantExpr(C1->getType(), Instruction::InsertElement,
380 Ops[0].init(C1, this);
381 Ops[1].init(C2, this);
382 Ops[2].init(C3, this);
387 /// ShuffleVectorConstantExpr - This class is private to
388 /// Constants.cpp, and is used behind the scenes to implement
389 /// shufflevector constant exprs.
391 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
394 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
395 : ConstantExpr(C1->getType(), Instruction::ShuffleVector,
397 Ops[0].init(C1, this);
398 Ops[1].init(C2, this);
399 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.
407 struct VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
408 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
410 : ConstantExpr(DestTy, Instruction::GetElementPtr,
411 new Use[IdxList.size()+1], IdxList.size()+1) {
412 OperandList[0].init(C, this);
413 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
414 OperandList[i+1].init(IdxList[i], this);
416 ~GetElementPtrConstantExpr() {
417 delete [] OperandList;
422 /// ConstantExpr::get* - Return some common constants without having to
423 /// specify the full Instruction::OPCODE identifier.
425 Constant *ConstantExpr::getNeg(Constant *C) {
426 if (!C->getType()->isFloatingPoint())
427 return get(Instruction::Sub, getNullValue(C->getType()), C);
429 return get(Instruction::Sub, ConstantFP::get(C->getType(), -0.0), C);
431 Constant *ConstantExpr::getNot(Constant *C) {
432 assert(isa<ConstantIntegral>(C) && "Cannot NOT a nonintegral type!");
433 return get(Instruction::Xor, C,
434 ConstantIntegral::getAllOnesValue(C->getType()));
436 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
437 return get(Instruction::Add, C1, C2);
439 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
440 return get(Instruction::Sub, C1, C2);
442 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
443 return get(Instruction::Mul, C1, C2);
445 Constant *ConstantExpr::getDiv(Constant *C1, Constant *C2) {
446 return get(Instruction::Div, C1, C2);
448 Constant *ConstantExpr::getRem(Constant *C1, Constant *C2) {
449 return get(Instruction::Rem, C1, C2);
451 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
452 return get(Instruction::And, C1, C2);
454 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
455 return get(Instruction::Or, C1, C2);
457 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
458 return get(Instruction::Xor, C1, C2);
460 Constant *ConstantExpr::getSetEQ(Constant *C1, Constant *C2) {
461 return get(Instruction::SetEQ, C1, C2);
463 Constant *ConstantExpr::getSetNE(Constant *C1, Constant *C2) {
464 return get(Instruction::SetNE, C1, C2);
466 Constant *ConstantExpr::getSetLT(Constant *C1, Constant *C2) {
467 return get(Instruction::SetLT, C1, C2);
469 Constant *ConstantExpr::getSetGT(Constant *C1, Constant *C2) {
470 return get(Instruction::SetGT, C1, C2);
472 Constant *ConstantExpr::getSetLE(Constant *C1, Constant *C2) {
473 return get(Instruction::SetLE, C1, C2);
475 Constant *ConstantExpr::getSetGE(Constant *C1, Constant *C2) {
476 return get(Instruction::SetGE, C1, C2);
478 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
479 return get(Instruction::Shl, C1, C2);
481 Constant *ConstantExpr::getShr(Constant *C1, Constant *C2) {
482 return get(Instruction::Shr, C1, C2);
485 Constant *ConstantExpr::getUShr(Constant *C1, Constant *C2) {
486 if (C1->getType()->isUnsigned()) return getShr(C1, C2);
487 return getCast(getShr(getCast(C1,
488 C1->getType()->getUnsignedVersion()), C2), C1->getType());
491 Constant *ConstantExpr::getSShr(Constant *C1, Constant *C2) {
492 if (C1->getType()->isSigned()) return getShr(C1, C2);
493 return getCast(getShr(getCast(C1,
494 C1->getType()->getSignedVersion()), C2), C1->getType());
497 /// getWithOperandReplaced - Return a constant expression identical to this
498 /// one, but with the specified operand set to the specified value.
499 Constant *ConstantExpr::getWithOperandReplaced(unsigned OpNo,
500 Constant *Op) const {
501 assert(OpNo < getNumOperands() && "Operand num is out of range!");
502 assert(Op->getType() == getOperand(OpNo)->getType() &&
503 "Replacing operand with value of different type!");
504 if (getOperand(OpNo) == Op)
505 return const_cast<ConstantExpr*>(this);
507 Constant *Op0, *Op1, *Op2;
508 switch (getOpcode()) {
509 case Instruction::Cast:
510 return ConstantExpr::getCast(Op, getType());
511 case Instruction::Select:
512 Op0 = (OpNo == 0) ? Op : getOperand(0);
513 Op1 = (OpNo == 1) ? Op : getOperand(1);
514 Op2 = (OpNo == 2) ? Op : getOperand(2);
515 return ConstantExpr::getSelect(Op0, Op1, Op2);
516 case Instruction::InsertElement:
517 Op0 = (OpNo == 0) ? Op : getOperand(0);
518 Op1 = (OpNo == 1) ? Op : getOperand(1);
519 Op2 = (OpNo == 2) ? Op : getOperand(2);
520 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
521 case Instruction::ExtractElement:
522 Op0 = (OpNo == 0) ? Op : getOperand(0);
523 Op1 = (OpNo == 1) ? Op : getOperand(1);
524 return ConstantExpr::getExtractElement(Op0, Op1);
525 case Instruction::ShuffleVector:
526 Op0 = (OpNo == 0) ? Op : getOperand(0);
527 Op1 = (OpNo == 1) ? Op : getOperand(1);
528 Op2 = (OpNo == 2) ? Op : getOperand(2);
529 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
530 case Instruction::GetElementPtr: {
531 std::vector<Constant*> Ops;
532 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
533 Ops.push_back(getOperand(i));
535 return ConstantExpr::getGetElementPtr(Op, Ops);
537 return ConstantExpr::getGetElementPtr(getOperand(0), Ops);
540 assert(getNumOperands() == 2 && "Must be binary operator?");
541 Op0 = (OpNo == 0) ? Op : getOperand(0);
542 Op1 = (OpNo == 1) ? Op : getOperand(1);
543 return ConstantExpr::get(getOpcode(), Op0, Op1);
547 /// getWithOperands - This returns the current constant expression with the
548 /// operands replaced with the specified values. The specified operands must
549 /// match count and type with the existing ones.
550 Constant *ConstantExpr::
551 getWithOperands(const std::vector<Constant*> &Ops) const {
552 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
553 bool AnyChange = false;
554 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
555 assert(Ops[i]->getType() == getOperand(i)->getType() &&
556 "Operand type mismatch!");
557 AnyChange |= Ops[i] != getOperand(i);
559 if (!AnyChange) // No operands changed, return self.
560 return const_cast<ConstantExpr*>(this);
562 switch (getOpcode()) {
563 case Instruction::Cast:
564 return ConstantExpr::getCast(Ops[0], getType());
565 case Instruction::Select:
566 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
567 case Instruction::InsertElement:
568 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
569 case Instruction::ExtractElement:
570 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
571 case Instruction::ShuffleVector:
572 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
573 case Instruction::GetElementPtr: {
574 std::vector<Constant*> ActualOps(Ops.begin()+1, Ops.end());
575 return ConstantExpr::getGetElementPtr(Ops[0], ActualOps);
578 assert(getNumOperands() == 2 && "Must be binary operator?");
579 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
584 //===----------------------------------------------------------------------===//
585 // isValueValidForType implementations
587 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
588 switch (Ty->getTypeID()) {
590 return false; // These can't be represented as integers!!!
592 case Type::SByteTyID:
593 return (Val <= INT8_MAX && Val >= INT8_MIN);
594 case Type::ShortTyID:
595 return (Val <= INT16_MAX && Val >= INT16_MIN);
597 return (Val <= int(INT32_MAX) && Val >= int(INT32_MIN));
599 return true; // This is the largest type...
603 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
604 switch (Ty->getTypeID()) {
606 return false; // These can't be represented as integers!!!
609 case Type::UByteTyID:
610 return (Val <= UINT8_MAX);
611 case Type::UShortTyID:
612 return (Val <= UINT16_MAX);
614 return (Val <= UINT32_MAX);
615 case Type::ULongTyID:
616 return true; // This is the largest type...
620 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
621 switch (Ty->getTypeID()) {
623 return false; // These can't be represented as floating point!
625 // TODO: Figure out how to test if a double can be cast to a float!
626 case Type::FloatTyID:
627 case Type::DoubleTyID:
628 return true; // This is the largest type...
632 //===----------------------------------------------------------------------===//
633 // Factory Function Implementation
635 // ConstantCreator - A class that is used to create constants by
636 // ValueMap*. This class should be partially specialized if there is
637 // something strange that needs to be done to interface to the ctor for the
641 template<class ConstantClass, class TypeClass, class ValType>
642 struct VISIBILITY_HIDDEN ConstantCreator {
643 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
644 return new ConstantClass(Ty, V);
648 template<class ConstantClass, class TypeClass>
649 struct VISIBILITY_HIDDEN ConvertConstantType {
650 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
651 assert(0 && "This type cannot be converted!\n");
656 template<class ValType, class TypeClass, class ConstantClass,
657 bool HasLargeKey = false /*true for arrays and structs*/ >
658 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
660 typedef std::pair<const Type*, ValType> MapKey;
661 typedef std::map<MapKey, Constant *> MapTy;
662 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
663 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
665 /// Map - This is the main map from the element descriptor to the Constants.
666 /// This is the primary way we avoid creating two of the same shape
670 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
671 /// from the constants to their element in Map. This is important for
672 /// removal of constants from the array, which would otherwise have to scan
673 /// through the map with very large keys.
674 InverseMapTy InverseMap;
676 /// AbstractTypeMap - Map for abstract type constants.
678 AbstractTypeMapTy AbstractTypeMap;
681 void clear(std::vector<Constant *> &Constants) {
682 for(typename MapTy::iterator I = Map.begin(); I != Map.end(); ++I)
683 Constants.push_back(I->second);
685 AbstractTypeMap.clear();
690 typename MapTy::iterator map_end() { return Map.end(); }
692 /// InsertOrGetItem - Return an iterator for the specified element.
693 /// If the element exists in the map, the returned iterator points to the
694 /// entry and Exists=true. If not, the iterator points to the newly
695 /// inserted entry and returns Exists=false. Newly inserted entries have
696 /// I->second == 0, and should be filled in.
697 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
700 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
706 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
708 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
709 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
710 IMI->second->second == CP &&
711 "InverseMap corrupt!");
715 typename MapTy::iterator I =
716 Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
717 if (I == Map.end() || I->second != CP) {
718 // FIXME: This should not use a linear scan. If this gets to be a
719 // performance problem, someone should look at this.
720 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
727 /// getOrCreate - Return the specified constant from the map, creating it if
729 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
730 MapKey Lookup(Ty, V);
731 typename MapTy::iterator I = Map.lower_bound(Lookup);
732 if (I != Map.end() && I->first == Lookup)
733 return static_cast<ConstantClass *>(I->second); // Is it in the map?
735 // If no preexisting value, create one now...
736 ConstantClass *Result =
737 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
739 /// FIXME: why does this assert fail when loading 176.gcc?
740 //assert(Result->getType() == Ty && "Type specified is not correct!");
741 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
743 if (HasLargeKey) // Remember the reverse mapping if needed.
744 InverseMap.insert(std::make_pair(Result, I));
746 // If the type of the constant is abstract, make sure that an entry exists
747 // for it in the AbstractTypeMap.
748 if (Ty->isAbstract()) {
749 typename AbstractTypeMapTy::iterator TI =
750 AbstractTypeMap.lower_bound(Ty);
752 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
753 // Add ourselves to the ATU list of the type.
754 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
756 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
762 void remove(ConstantClass *CP) {
763 typename MapTy::iterator I = FindExistingElement(CP);
764 assert(I != Map.end() && "Constant not found in constant table!");
765 assert(I->second == CP && "Didn't find correct element?");
767 if (HasLargeKey) // Remember the reverse mapping if needed.
768 InverseMap.erase(CP);
770 // Now that we found the entry, make sure this isn't the entry that
771 // the AbstractTypeMap points to.
772 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
773 if (Ty->isAbstract()) {
774 assert(AbstractTypeMap.count(Ty) &&
775 "Abstract type not in AbstractTypeMap?");
776 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
777 if (ATMEntryIt == I) {
778 // Yes, we are removing the representative entry for this type.
779 // See if there are any other entries of the same type.
780 typename MapTy::iterator TmpIt = ATMEntryIt;
782 // First check the entry before this one...
783 if (TmpIt != Map.begin()) {
785 if (TmpIt->first.first != Ty) // Not the same type, move back...
789 // If we didn't find the same type, try to move forward...
790 if (TmpIt == ATMEntryIt) {
792 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
793 --TmpIt; // No entry afterwards with the same type
796 // If there is another entry in the map of the same abstract type,
797 // update the AbstractTypeMap entry now.
798 if (TmpIt != ATMEntryIt) {
801 // Otherwise, we are removing the last instance of this type
802 // from the table. Remove from the ATM, and from user list.
803 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
804 AbstractTypeMap.erase(Ty);
813 /// MoveConstantToNewSlot - If we are about to change C to be the element
814 /// specified by I, update our internal data structures to reflect this
816 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
817 // First, remove the old location of the specified constant in the map.
818 typename MapTy::iterator OldI = FindExistingElement(C);
819 assert(OldI != Map.end() && "Constant not found in constant table!");
820 assert(OldI->second == C && "Didn't find correct element?");
822 // If this constant is the representative element for its abstract type,
823 // update the AbstractTypeMap so that the representative element is I.
824 if (C->getType()->isAbstract()) {
825 typename AbstractTypeMapTy::iterator ATI =
826 AbstractTypeMap.find(C->getType());
827 assert(ATI != AbstractTypeMap.end() &&
828 "Abstract type not in AbstractTypeMap?");
829 if (ATI->second == OldI)
833 // Remove the old entry from the map.
836 // Update the inverse map so that we know that this constant is now
837 // located at descriptor I.
839 assert(I->second == C && "Bad inversemap entry!");
844 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
845 typename AbstractTypeMapTy::iterator I =
846 AbstractTypeMap.find(cast<Type>(OldTy));
848 assert(I != AbstractTypeMap.end() &&
849 "Abstract type not in AbstractTypeMap?");
851 // Convert a constant at a time until the last one is gone. The last one
852 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
853 // eliminated eventually.
855 ConvertConstantType<ConstantClass,
857 static_cast<ConstantClass *>(I->second->second),
858 cast<TypeClass>(NewTy));
860 I = AbstractTypeMap.find(cast<Type>(OldTy));
861 } while (I != AbstractTypeMap.end());
864 // If the type became concrete without being refined to any other existing
865 // type, we just remove ourselves from the ATU list.
866 void typeBecameConcrete(const DerivedType *AbsTy) {
867 AbsTy->removeAbstractTypeUser(this);
871 std::cerr << "Constant.cpp: ValueMap\n";
877 //---- ConstantBool::get*() implementation.
879 ConstantBool *ConstantBool::getTrue() {
880 static ConstantBool *T = 0;
882 return T = new ConstantBool(true);
884 ConstantBool *ConstantBool::getFalse() {
885 static ConstantBool *F = 0;
887 return F = new ConstantBool(false);
890 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
892 static ManagedStatic<ValueMap< int64_t, Type, ConstantSInt> > SIntConstants;
893 static ManagedStatic<ValueMap<uint64_t, Type, ConstantUInt> > UIntConstants;
895 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
896 return SIntConstants->getOrCreate(Ty, V);
899 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
900 return UIntConstants->getOrCreate(Ty, V);
903 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
904 assert(V <= 127 && "Can only be used with very small positive constants!");
905 if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
906 return ConstantUInt::get(Ty, V);
909 //---- ConstantFP::get() implementation...
913 struct ConstantCreator<ConstantFP, Type, uint64_t> {
914 static ConstantFP *create(const Type *Ty, uint64_t V) {
915 assert(Ty == Type::DoubleTy);
916 return new ConstantFP(Ty, BitsToDouble(V));
920 struct ConstantCreator<ConstantFP, Type, uint32_t> {
921 static ConstantFP *create(const Type *Ty, uint32_t V) {
922 assert(Ty == Type::FloatTy);
923 return new ConstantFP(Ty, BitsToFloat(V));
928 static ManagedStatic<ValueMap<uint64_t, Type, ConstantFP> > DoubleConstants;
929 static ManagedStatic<ValueMap<uint32_t, Type, ConstantFP> > FloatConstants;
931 bool ConstantFP::isNullValue() const {
932 return DoubleToBits(Val) == 0;
935 bool ConstantFP::isExactlyValue(double V) const {
936 return DoubleToBits(V) == DoubleToBits(Val);
940 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
941 if (Ty == Type::FloatTy) {
942 // Force the value through memory to normalize it.
943 return FloatConstants->getOrCreate(Ty, FloatToBits(V));
945 assert(Ty == Type::DoubleTy);
946 return DoubleConstants->getOrCreate(Ty, DoubleToBits(V));
950 //---- ConstantAggregateZero::get() implementation...
953 // ConstantAggregateZero does not take extra "value" argument...
954 template<class ValType>
955 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
956 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
957 return new ConstantAggregateZero(Ty);
962 struct ConvertConstantType<ConstantAggregateZero, Type> {
963 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
964 // Make everyone now use a constant of the new type...
965 Constant *New = ConstantAggregateZero::get(NewTy);
966 assert(New != OldC && "Didn't replace constant??");
967 OldC->uncheckedReplaceAllUsesWith(New);
968 OldC->destroyConstant(); // This constant is now dead, destroy it.
973 static ManagedStatic<ValueMap<char, Type,
974 ConstantAggregateZero> > AggZeroConstants;
976 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
978 Constant *ConstantAggregateZero::get(const Type *Ty) {
979 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<PackedType>(Ty)) &&
980 "Cannot create an aggregate zero of non-aggregate type!");
981 return AggZeroConstants->getOrCreate(Ty, 0);
984 // destroyConstant - Remove the constant from the constant table...
986 void ConstantAggregateZero::destroyConstant() {
987 AggZeroConstants->remove(this);
988 destroyConstantImpl();
991 //---- ConstantArray::get() implementation...
995 struct ConvertConstantType<ConstantArray, ArrayType> {
996 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
997 // Make everyone now use a constant of the new type...
998 std::vector<Constant*> C;
999 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1000 C.push_back(cast<Constant>(OldC->getOperand(i)));
1001 Constant *New = ConstantArray::get(NewTy, C);
1002 assert(New != OldC && "Didn't replace constant??");
1003 OldC->uncheckedReplaceAllUsesWith(New);
1004 OldC->destroyConstant(); // This constant is now dead, destroy it.
1009 static std::vector<Constant*> getValType(ConstantArray *CA) {
1010 std::vector<Constant*> Elements;
1011 Elements.reserve(CA->getNumOperands());
1012 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1013 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1017 typedef ValueMap<std::vector<Constant*>, ArrayType,
1018 ConstantArray, true /*largekey*/> ArrayConstantsTy;
1019 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
1021 Constant *ConstantArray::get(const ArrayType *Ty,
1022 const std::vector<Constant*> &V) {
1023 // If this is an all-zero array, return a ConstantAggregateZero object
1026 if (!C->isNullValue())
1027 return ArrayConstants->getOrCreate(Ty, V);
1028 for (unsigned i = 1, e = V.size(); i != e; ++i)
1030 return ArrayConstants->getOrCreate(Ty, V);
1032 return ConstantAggregateZero::get(Ty);
1035 // destroyConstant - Remove the constant from the constant table...
1037 void ConstantArray::destroyConstant() {
1038 ArrayConstants->remove(this);
1039 destroyConstantImpl();
1042 /// ConstantArray::get(const string&) - Return an array that is initialized to
1043 /// contain the specified string. If length is zero then a null terminator is
1044 /// added to the specified string so that it may be used in a natural way.
1045 /// Otherwise, the length parameter specifies how much of the string to use
1046 /// and it won't be null terminated.
1048 Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
1049 std::vector<Constant*> ElementVals;
1050 for (unsigned i = 0; i < Str.length(); ++i)
1051 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
1053 // Add a null terminator to the string...
1055 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
1058 ArrayType *ATy = ArrayType::get(Type::SByteTy, ElementVals.size());
1059 return ConstantArray::get(ATy, ElementVals);
1062 /// isString - This method returns true if the array is an array of sbyte or
1063 /// ubyte, and if the elements of the array are all ConstantInt's.
1064 bool ConstantArray::isString() const {
1065 // Check the element type for sbyte or ubyte...
1066 if (getType()->getElementType() != Type::UByteTy &&
1067 getType()->getElementType() != Type::SByteTy)
1069 // Check the elements to make sure they are all integers, not constant
1071 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1072 if (!isa<ConstantInt>(getOperand(i)))
1077 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
1078 // then this method converts the array to an std::string and returns it.
1079 // Otherwise, it asserts out.
1081 std::string ConstantArray::getAsString() const {
1082 assert(isString() && "Not a string!");
1084 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1085 Result += (char)cast<ConstantInt>(getOperand(i))->getRawValue();
1090 //---- ConstantStruct::get() implementation...
1095 struct ConvertConstantType<ConstantStruct, StructType> {
1096 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1097 // Make everyone now use a constant of the new type...
1098 std::vector<Constant*> C;
1099 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1100 C.push_back(cast<Constant>(OldC->getOperand(i)));
1101 Constant *New = ConstantStruct::get(NewTy, C);
1102 assert(New != OldC && "Didn't replace constant??");
1104 OldC->uncheckedReplaceAllUsesWith(New);
1105 OldC->destroyConstant(); // This constant is now dead, destroy it.
1110 typedef ValueMap<std::vector<Constant*>, StructType,
1111 ConstantStruct, true /*largekey*/> StructConstantsTy;
1112 static ManagedStatic<StructConstantsTy> StructConstants;
1114 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1115 std::vector<Constant*> Elements;
1116 Elements.reserve(CS->getNumOperands());
1117 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1118 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1122 Constant *ConstantStruct::get(const StructType *Ty,
1123 const std::vector<Constant*> &V) {
1124 // Create a ConstantAggregateZero value if all elements are zeros...
1125 for (unsigned i = 0, e = V.size(); i != e; ++i)
1126 if (!V[i]->isNullValue())
1127 return StructConstants->getOrCreate(Ty, V);
1129 return ConstantAggregateZero::get(Ty);
1132 Constant *ConstantStruct::get(const std::vector<Constant*> &V) {
1133 std::vector<const Type*> StructEls;
1134 StructEls.reserve(V.size());
1135 for (unsigned i = 0, e = V.size(); i != e; ++i)
1136 StructEls.push_back(V[i]->getType());
1137 return get(StructType::get(StructEls), V);
1140 // destroyConstant - Remove the constant from the constant table...
1142 void ConstantStruct::destroyConstant() {
1143 StructConstants->remove(this);
1144 destroyConstantImpl();
1147 //---- ConstantPacked::get() implementation...
1151 struct ConvertConstantType<ConstantPacked, PackedType> {
1152 static void convert(ConstantPacked *OldC, const PackedType *NewTy) {
1153 // Make everyone now use a constant of the new type...
1154 std::vector<Constant*> C;
1155 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1156 C.push_back(cast<Constant>(OldC->getOperand(i)));
1157 Constant *New = ConstantPacked::get(NewTy, C);
1158 assert(New != OldC && "Didn't replace constant??");
1159 OldC->uncheckedReplaceAllUsesWith(New);
1160 OldC->destroyConstant(); // This constant is now dead, destroy it.
1165 static std::vector<Constant*> getValType(ConstantPacked *CP) {
1166 std::vector<Constant*> Elements;
1167 Elements.reserve(CP->getNumOperands());
1168 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1169 Elements.push_back(CP->getOperand(i));
1173 static ManagedStatic<ValueMap<std::vector<Constant*>, PackedType,
1174 ConstantPacked> > PackedConstants;
1176 Constant *ConstantPacked::get(const PackedType *Ty,
1177 const std::vector<Constant*> &V) {
1178 // If this is an all-zero packed, return a ConstantAggregateZero object
1181 if (!C->isNullValue())
1182 return PackedConstants->getOrCreate(Ty, V);
1183 for (unsigned i = 1, e = V.size(); i != e; ++i)
1185 return PackedConstants->getOrCreate(Ty, V);
1187 return ConstantAggregateZero::get(Ty);
1190 Constant *ConstantPacked::get(const std::vector<Constant*> &V) {
1191 assert(!V.empty() && "Cannot infer type if V is empty");
1192 return get(PackedType::get(V.front()->getType(),V.size()), V);
1195 // destroyConstant - Remove the constant from the constant table...
1197 void ConstantPacked::destroyConstant() {
1198 PackedConstants->remove(this);
1199 destroyConstantImpl();
1202 //---- ConstantPointerNull::get() implementation...
1206 // ConstantPointerNull does not take extra "value" argument...
1207 template<class ValType>
1208 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1209 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1210 return new ConstantPointerNull(Ty);
1215 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1216 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1217 // Make everyone now use a constant of the new type...
1218 Constant *New = ConstantPointerNull::get(NewTy);
1219 assert(New != OldC && "Didn't replace constant??");
1220 OldC->uncheckedReplaceAllUsesWith(New);
1221 OldC->destroyConstant(); // This constant is now dead, destroy it.
1226 static ManagedStatic<ValueMap<char, PointerType,
1227 ConstantPointerNull> > NullPtrConstants;
1229 static char getValType(ConstantPointerNull *) {
1234 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1235 return NullPtrConstants->getOrCreate(Ty, 0);
1238 // destroyConstant - Remove the constant from the constant table...
1240 void ConstantPointerNull::destroyConstant() {
1241 NullPtrConstants->remove(this);
1242 destroyConstantImpl();
1246 //---- UndefValue::get() implementation...
1250 // UndefValue does not take extra "value" argument...
1251 template<class ValType>
1252 struct ConstantCreator<UndefValue, Type, ValType> {
1253 static UndefValue *create(const Type *Ty, const ValType &V) {
1254 return new UndefValue(Ty);
1259 struct ConvertConstantType<UndefValue, Type> {
1260 static void convert(UndefValue *OldC, const Type *NewTy) {
1261 // Make everyone now use a constant of the new type.
1262 Constant *New = UndefValue::get(NewTy);
1263 assert(New != OldC && "Didn't replace constant??");
1264 OldC->uncheckedReplaceAllUsesWith(New);
1265 OldC->destroyConstant(); // This constant is now dead, destroy it.
1270 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1272 static char getValType(UndefValue *) {
1277 UndefValue *UndefValue::get(const Type *Ty) {
1278 return UndefValueConstants->getOrCreate(Ty, 0);
1281 // destroyConstant - Remove the constant from the constant table.
1283 void UndefValue::destroyConstant() {
1284 UndefValueConstants->remove(this);
1285 destroyConstantImpl();
1291 //---- ConstantExpr::get() implementations...
1293 typedef std::pair<unsigned, std::vector<Constant*> > ExprMapKeyType;
1297 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1298 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V) {
1299 if (V.first == Instruction::Cast)
1300 return new UnaryConstantExpr(Instruction::Cast, V.second[0], Ty);
1301 if ((V.first >= Instruction::BinaryOpsBegin &&
1302 V.first < Instruction::BinaryOpsEnd) ||
1303 V.first == Instruction::Shl || V.first == Instruction::Shr)
1304 return new BinaryConstantExpr(V.first, V.second[0], V.second[1]);
1305 if (V.first == Instruction::Select)
1306 return new SelectConstantExpr(V.second[0], V.second[1], V.second[2]);
1307 if (V.first == Instruction::ExtractElement)
1308 return new ExtractElementConstantExpr(V.second[0], V.second[1]);
1309 if (V.first == Instruction::InsertElement)
1310 return new InsertElementConstantExpr(V.second[0], V.second[1],
1312 if (V.first == Instruction::ShuffleVector)
1313 return new ShuffleVectorConstantExpr(V.second[0], V.second[1],
1316 assert(V.first == Instruction::GetElementPtr && "Invalid ConstantExpr!");
1318 std::vector<Constant*> IdxList(V.second.begin()+1, V.second.end());
1319 return new GetElementPtrConstantExpr(V.second[0], IdxList, Ty);
1324 struct ConvertConstantType<ConstantExpr, Type> {
1325 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1327 switch (OldC->getOpcode()) {
1328 case Instruction::Cast:
1329 New = ConstantExpr::getCast(OldC->getOperand(0), NewTy);
1331 case Instruction::Select:
1332 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1333 OldC->getOperand(1),
1334 OldC->getOperand(2));
1336 case Instruction::Shl:
1337 case Instruction::Shr:
1338 New = ConstantExpr::getShiftTy(NewTy, OldC->getOpcode(),
1339 OldC->getOperand(0), OldC->getOperand(1));
1342 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1343 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1344 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1345 OldC->getOperand(1));
1347 case Instruction::GetElementPtr:
1348 // Make everyone now use a constant of the new type...
1349 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1350 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0), Idx);
1354 assert(New != OldC && "Didn't replace constant??");
1355 OldC->uncheckedReplaceAllUsesWith(New);
1356 OldC->destroyConstant(); // This constant is now dead, destroy it.
1359 } // end namespace llvm
1362 static ExprMapKeyType getValType(ConstantExpr *CE) {
1363 std::vector<Constant*> Operands;
1364 Operands.reserve(CE->getNumOperands());
1365 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1366 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1367 return ExprMapKeyType(CE->getOpcode(), Operands);
1370 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1371 ConstantExpr> > ExprConstants;
1373 Constant *ConstantExpr::getCast(Constant *C, const Type *Ty) {
1374 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1376 if (Constant *FC = ConstantFoldCastInstruction(C, Ty))
1377 return FC; // Fold a few common cases...
1379 // Look up the constant in the table first to ensure uniqueness
1380 std::vector<Constant*> argVec(1, C);
1381 ExprMapKeyType Key = std::make_pair(Instruction::Cast, argVec);
1382 return ExprConstants->getOrCreate(Ty, Key);
1385 Constant *ConstantExpr::getSignExtend(Constant *C, const Type *Ty) {
1386 assert(C->getType()->isIntegral() && Ty->isIntegral() &&
1387 C->getType()->getPrimitiveSize() <= Ty->getPrimitiveSize() &&
1388 "This is an illegal sign extension!");
1389 if (C->getType() != Type::BoolTy) {
1390 C = ConstantExpr::getCast(C, C->getType()->getSignedVersion());
1391 return ConstantExpr::getCast(C, Ty);
1393 if (C == ConstantBool::getTrue())
1394 return ConstantIntegral::getAllOnesValue(Ty);
1396 return ConstantIntegral::getNullValue(Ty);
1400 Constant *ConstantExpr::getZeroExtend(Constant *C, const Type *Ty) {
1401 assert(C->getType()->isIntegral() && Ty->isIntegral() &&
1402 C->getType()->getPrimitiveSize() <= Ty->getPrimitiveSize() &&
1403 "This is an illegal zero extension!");
1404 if (C->getType() != Type::BoolTy)
1405 C = ConstantExpr::getCast(C, C->getType()->getUnsignedVersion());
1406 return ConstantExpr::getCast(C, Ty);
1409 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
1410 // sizeof is implemented as: (ulong) gep (Ty*)null, 1
1412 getGetElementPtr(getNullValue(PointerType::get(Ty)),
1413 std::vector<Constant*>(1, ConstantInt::get(Type::UIntTy, 1))),
1417 Constant *ConstantExpr::getPtrPtrFromArrayPtr(Constant *C) {
1418 // pointer from array is implemented as: getelementptr arr ptr, 0, 0
1419 static std::vector<Constant*> Indices(2, ConstantUInt::get(Type::UIntTy, 0));
1421 return ConstantExpr::getGetElementPtr(C, Indices);
1424 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1425 Constant *C1, Constant *C2) {
1426 if (Opcode == Instruction::Shl || Opcode == Instruction::Shr)
1427 return getShiftTy(ReqTy, Opcode, C1, C2);
1428 // Check the operands for consistency first
1429 assert((Opcode >= Instruction::BinaryOpsBegin &&
1430 Opcode < Instruction::BinaryOpsEnd) &&
1431 "Invalid opcode in binary constant expression");
1432 assert(C1->getType() == C2->getType() &&
1433 "Operand types in binary constant expression should match");
1435 if (ReqTy == C1->getType() || (Instruction::isComparison(Opcode) &&
1436 ReqTy == Type::BoolTy))
1437 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1438 return FC; // Fold a few common cases...
1440 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1441 ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1442 return ExprConstants->getOrCreate(ReqTy, Key);
1445 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1448 case Instruction::Add: case Instruction::Sub:
1449 case Instruction::Mul: case Instruction::Div:
1450 case Instruction::Rem:
1451 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1452 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
1453 isa<PackedType>(C1->getType())) &&
1454 "Tried to create an arithmetic operation on a non-arithmetic type!");
1456 case Instruction::And:
1457 case Instruction::Or:
1458 case Instruction::Xor:
1459 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1460 assert((C1->getType()->isIntegral() || isa<PackedType>(C1->getType())) &&
1461 "Tried to create a logical operation on a non-integral type!");
1463 case Instruction::SetLT: case Instruction::SetGT: case Instruction::SetLE:
1464 case Instruction::SetGE: case Instruction::SetEQ: case Instruction::SetNE:
1465 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1467 case Instruction::Shl:
1468 case Instruction::Shr:
1469 assert(C2->getType() == Type::UByteTy && "Shift should be by ubyte!");
1470 assert((C1->getType()->isInteger() || isa<PackedType>(C1->getType())) &&
1471 "Tried to create a shift operation on a non-integer type!");
1478 if (Instruction::isComparison(Opcode))
1479 return getTy(Type::BoolTy, Opcode, C1, C2);
1481 return getTy(C1->getType(), Opcode, C1, C2);
1484 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1485 Constant *V1, Constant *V2) {
1486 assert(C->getType() == Type::BoolTy && "Select condition must be bool!");
1487 assert(V1->getType() == V2->getType() && "Select value types must match!");
1488 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1490 if (ReqTy == V1->getType())
1491 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1492 return SC; // Fold common cases
1494 std::vector<Constant*> argVec(3, C);
1497 ExprMapKeyType Key = std::make_pair(Instruction::Select, argVec);
1498 return ExprConstants->getOrCreate(ReqTy, Key);
1501 /// getShiftTy - Return a shift left or shift right constant expr
1502 Constant *ConstantExpr::getShiftTy(const Type *ReqTy, unsigned Opcode,
1503 Constant *C1, Constant *C2) {
1504 // Check the operands for consistency first
1505 assert((Opcode == Instruction::Shl ||
1506 Opcode == Instruction::Shr) &&
1507 "Invalid opcode in binary constant expression");
1508 assert(C1->getType()->isIntegral() && C2->getType() == Type::UByteTy &&
1509 "Invalid operand types for Shift constant expr!");
1511 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1512 return FC; // Fold a few common cases...
1514 // Look up the constant in the table first to ensure uniqueness
1515 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1516 ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1517 return ExprConstants->getOrCreate(ReqTy, Key);
1521 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1522 const std::vector<Value*> &IdxList) {
1523 assert(GetElementPtrInst::getIndexedType(C->getType(), IdxList, true) &&
1524 "GEP indices invalid!");
1526 if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
1527 return FC; // Fold a few common cases...
1529 assert(isa<PointerType>(C->getType()) &&
1530 "Non-pointer type for constant GetElementPtr expression");
1531 // Look up the constant in the table first to ensure uniqueness
1532 std::vector<Constant*> ArgVec;
1533 ArgVec.reserve(IdxList.size()+1);
1534 ArgVec.push_back(C);
1535 for (unsigned i = 0, e = IdxList.size(); i != e; ++i)
1536 ArgVec.push_back(cast<Constant>(IdxList[i]));
1537 const ExprMapKeyType &Key = std::make_pair(Instruction::GetElementPtr,ArgVec);
1538 return ExprConstants->getOrCreate(ReqTy, Key);
1541 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1542 const std::vector<Constant*> &IdxList){
1543 // Get the result type of the getelementptr!
1544 std::vector<Value*> VIdxList(IdxList.begin(), IdxList.end());
1546 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), VIdxList,
1548 assert(Ty && "GEP indices invalid!");
1549 return getGetElementPtrTy(PointerType::get(Ty), C, VIdxList);
1552 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1553 const std::vector<Value*> &IdxList) {
1554 // Get the result type of the getelementptr!
1555 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
1557 assert(Ty && "GEP indices invalid!");
1558 return getGetElementPtrTy(PointerType::get(Ty), C, IdxList);
1561 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1563 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1564 return FC; // Fold a few common cases...
1565 // Look up the constant in the table first to ensure uniqueness
1566 std::vector<Constant*> ArgVec(1, Val);
1567 ArgVec.push_back(Idx);
1568 const ExprMapKeyType &Key = std::make_pair(Instruction::ExtractElement,ArgVec);
1569 return ExprConstants->getOrCreate(ReqTy, Key);
1572 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1573 assert(isa<PackedType>(Val->getType()) &&
1574 "Tried to create extractelement operation on non-packed type!");
1575 assert(Idx->getType() == Type::UIntTy &&
1576 "Extractelement index must be uint type!");
1577 return getExtractElementTy(cast<PackedType>(Val->getType())->getElementType(),
1581 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1582 Constant *Elt, Constant *Idx) {
1583 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1584 return FC; // Fold a few common cases...
1585 // Look up the constant in the table first to ensure uniqueness
1586 std::vector<Constant*> ArgVec(1, Val);
1587 ArgVec.push_back(Elt);
1588 ArgVec.push_back(Idx);
1589 const ExprMapKeyType &Key = std::make_pair(Instruction::InsertElement,ArgVec);
1590 return ExprConstants->getOrCreate(ReqTy, Key);
1593 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1595 assert(isa<PackedType>(Val->getType()) &&
1596 "Tried to create insertelement operation on non-packed type!");
1597 assert(Elt->getType() == cast<PackedType>(Val->getType())->getElementType()
1598 && "Insertelement types must match!");
1599 assert(Idx->getType() == Type::UIntTy &&
1600 "Insertelement index must be uint type!");
1601 return getInsertElementTy(cast<PackedType>(Val->getType())->getElementType(),
1605 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1606 Constant *V2, Constant *Mask) {
1607 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1608 return FC; // Fold a few common cases...
1609 // Look up the constant in the table first to ensure uniqueness
1610 std::vector<Constant*> ArgVec(1, V1);
1611 ArgVec.push_back(V2);
1612 ArgVec.push_back(Mask);
1613 const ExprMapKeyType &Key = std::make_pair(Instruction::ShuffleVector,ArgVec);
1614 return ExprConstants->getOrCreate(ReqTy, Key);
1617 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1619 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1620 "Invalid shuffle vector constant expr operands!");
1621 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
1625 // destroyConstant - Remove the constant from the constant table...
1627 void ConstantExpr::destroyConstant() {
1628 ExprConstants->remove(this);
1629 destroyConstantImpl();
1632 const char *ConstantExpr::getOpcodeName() const {
1633 return Instruction::getOpcodeName(getOpcode());
1636 //===----------------------------------------------------------------------===//
1637 // replaceUsesOfWithOnConstant implementations
1639 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1641 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1642 Constant *ToC = cast<Constant>(To);
1644 unsigned OperandToUpdate = U-OperandList;
1645 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1647 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
1648 Lookup.first.first = getType();
1649 Lookup.second = this;
1651 std::vector<Constant*> &Values = Lookup.first.second;
1652 Values.reserve(getNumOperands()); // Build replacement array.
1654 // Fill values with the modified operands of the constant array. Also,
1655 // compute whether this turns into an all-zeros array.
1656 bool isAllZeros = false;
1657 if (!ToC->isNullValue()) {
1658 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1659 Values.push_back(cast<Constant>(O->get()));
1662 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1663 Constant *Val = cast<Constant>(O->get());
1664 Values.push_back(Val);
1665 if (isAllZeros) isAllZeros = Val->isNullValue();
1668 Values[OperandToUpdate] = ToC;
1670 Constant *Replacement = 0;
1672 Replacement = ConstantAggregateZero::get(getType());
1674 // Check to see if we have this array type already.
1676 ArrayConstantsTy::MapTy::iterator I =
1677 ArrayConstants->InsertOrGetItem(Lookup, Exists);
1680 Replacement = I->second;
1682 // Okay, the new shape doesn't exist in the system yet. Instead of
1683 // creating a new constant array, inserting it, replaceallusesof'ing the
1684 // old with the new, then deleting the old... just update the current one
1686 ArrayConstants->MoveConstantToNewSlot(this, I);
1688 // Update to the new value.
1689 setOperand(OperandToUpdate, ToC);
1694 // Otherwise, I do need to replace this with an existing value.
1695 assert(Replacement != this && "I didn't contain From!");
1697 // Everyone using this now uses the replacement.
1698 uncheckedReplaceAllUsesWith(Replacement);
1700 // Delete the old constant!
1704 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
1706 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1707 Constant *ToC = cast<Constant>(To);
1709 unsigned OperandToUpdate = U-OperandList;
1710 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1712 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
1713 Lookup.first.first = getType();
1714 Lookup.second = this;
1715 std::vector<Constant*> &Values = Lookup.first.second;
1716 Values.reserve(getNumOperands()); // Build replacement struct.
1719 // Fill values with the modified operands of the constant struct. Also,
1720 // compute whether this turns into an all-zeros struct.
1721 bool isAllZeros = false;
1722 if (!ToC->isNullValue()) {
1723 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1724 Values.push_back(cast<Constant>(O->get()));
1727 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1728 Constant *Val = cast<Constant>(O->get());
1729 Values.push_back(Val);
1730 if (isAllZeros) isAllZeros = Val->isNullValue();
1733 Values[OperandToUpdate] = ToC;
1735 Constant *Replacement = 0;
1737 Replacement = ConstantAggregateZero::get(getType());
1739 // Check to see if we have this array type already.
1741 StructConstantsTy::MapTy::iterator I =
1742 StructConstants->InsertOrGetItem(Lookup, Exists);
1745 Replacement = I->second;
1747 // Okay, the new shape doesn't exist in the system yet. Instead of
1748 // creating a new constant struct, inserting it, replaceallusesof'ing the
1749 // old with the new, then deleting the old... just update the current one
1751 StructConstants->MoveConstantToNewSlot(this, I);
1753 // Update to the new value.
1754 setOperand(OperandToUpdate, ToC);
1759 assert(Replacement != this && "I didn't contain From!");
1761 // Everyone using this now uses the replacement.
1762 uncheckedReplaceAllUsesWith(Replacement);
1764 // Delete the old constant!
1768 void ConstantPacked::replaceUsesOfWithOnConstant(Value *From, Value *To,
1770 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1772 std::vector<Constant*> Values;
1773 Values.reserve(getNumOperands()); // Build replacement array...
1774 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1775 Constant *Val = getOperand(i);
1776 if (Val == From) Val = cast<Constant>(To);
1777 Values.push_back(Val);
1780 Constant *Replacement = ConstantPacked::get(getType(), Values);
1781 assert(Replacement != this && "I didn't contain From!");
1783 // Everyone using this now uses the replacement.
1784 uncheckedReplaceAllUsesWith(Replacement);
1786 // Delete the old constant!
1790 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
1792 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
1793 Constant *To = cast<Constant>(ToV);
1795 Constant *Replacement = 0;
1796 if (getOpcode() == Instruction::GetElementPtr) {
1797 std::vector<Constant*> Indices;
1798 Constant *Pointer = getOperand(0);
1799 Indices.reserve(getNumOperands()-1);
1800 if (Pointer == From) Pointer = To;
1802 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1803 Constant *Val = getOperand(i);
1804 if (Val == From) Val = To;
1805 Indices.push_back(Val);
1807 Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
1808 } else if (getOpcode() == Instruction::Cast) {
1809 assert(getOperand(0) == From && "Cast only has one use!");
1810 Replacement = ConstantExpr::getCast(To, getType());
1811 } else if (getOpcode() == Instruction::Select) {
1812 Constant *C1 = getOperand(0);
1813 Constant *C2 = getOperand(1);
1814 Constant *C3 = getOperand(2);
1815 if (C1 == From) C1 = To;
1816 if (C2 == From) C2 = To;
1817 if (C3 == From) C3 = To;
1818 Replacement = ConstantExpr::getSelect(C1, C2, C3);
1819 } else if (getOpcode() == Instruction::ExtractElement) {
1820 Constant *C1 = getOperand(0);
1821 Constant *C2 = getOperand(1);
1822 if (C1 == From) C1 = To;
1823 if (C2 == From) C2 = To;
1824 Replacement = ConstantExpr::getExtractElement(C1, C2);
1825 } else if (getOpcode() == Instruction::InsertElement) {
1826 Constant *C1 = getOperand(0);
1827 Constant *C2 = getOperand(1);
1828 Constant *C3 = getOperand(1);
1829 if (C1 == From) C1 = To;
1830 if (C2 == From) C2 = To;
1831 if (C3 == From) C3 = To;
1832 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
1833 } else if (getOpcode() == Instruction::ShuffleVector) {
1834 Constant *C1 = getOperand(0);
1835 Constant *C2 = getOperand(1);
1836 Constant *C3 = getOperand(2);
1837 if (C1 == From) C1 = To;
1838 if (C2 == From) C2 = To;
1839 if (C3 == From) C3 = To;
1840 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
1841 } else if (getNumOperands() == 2) {
1842 Constant *C1 = getOperand(0);
1843 Constant *C2 = getOperand(1);
1844 if (C1 == From) C1 = To;
1845 if (C2 == From) C2 = To;
1846 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
1848 assert(0 && "Unknown ConstantExpr type!");
1852 assert(Replacement != this && "I didn't contain From!");
1854 // Everyone using this now uses the replacement.
1855 uncheckedReplaceAllUsesWith(Replacement);
1857 // Delete the old constant!
1862 /// getStringValue - Turn an LLVM constant pointer that eventually points to a
1863 /// global into a string value. Return an empty string if we can't do it.
1864 /// Parameter Chop determines if the result is chopped at the first null
1867 std::string Constant::getStringValue(bool Chop, unsigned Offset) {
1868 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
1869 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
1870 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
1871 if (Init->isString()) {
1872 std::string Result = Init->getAsString();
1873 if (Offset < Result.size()) {
1874 // If we are pointing INTO The string, erase the beginning...
1875 Result.erase(Result.begin(), Result.begin()+Offset);
1877 // Take off the null terminator, and any string fragments after it.
1879 std::string::size_type NullPos = Result.find_first_of((char)0);
1880 if (NullPos != std::string::npos)
1881 Result.erase(Result.begin()+NullPos, Result.end());
1887 } else if (Constant *C = dyn_cast<Constant>(this)) {
1888 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
1889 return GV->getStringValue(Chop, Offset);
1890 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1891 if (CE->getOpcode() == Instruction::GetElementPtr) {
1892 // Turn a gep into the specified offset.
1893 if (CE->getNumOperands() == 3 &&
1894 cast<Constant>(CE->getOperand(1))->isNullValue() &&
1895 isa<ConstantInt>(CE->getOperand(2))) {
1896 Offset += cast<ConstantInt>(CE->getOperand(2))->getRawValue();
1897 return CE->getOperand(0)->getStringValue(Chop, Offset);