1 //===-- Constants.cpp - Implement Constant nodes -----------------*- C++ -*--=//
3 // This file implements the Constant* classes...
5 //===----------------------------------------------------------------------===//
7 #define __STDC_LIMIT_MACROS // Get defs for INT64_MAX and friends...
8 #include "llvm/Constants.h"
9 #include "llvm/DerivedTypes.h"
10 #include "llvm/iMemory.h"
11 #include "llvm/SymbolTable.h"
12 #include "llvm/Module.h"
13 #include "llvm/SlotCalculator.h"
14 #include "Support/StringExtras.h"
22 ConstantBool *ConstantBool::True = new ConstantBool(true);
23 ConstantBool *ConstantBool::False = new ConstantBool(false);
26 //===----------------------------------------------------------------------===//
28 //===----------------------------------------------------------------------===//
30 // Specialize setName to take care of symbol table majik
31 void Constant::setName(const std::string &Name, SymbolTable *ST) {
32 assert(ST && "Type::setName - Must provide symbol table argument!");
34 if (Name.size()) ST->insert(Name, this);
37 void Constant::destroyConstantImpl() {
38 // When a Constant is destroyed, there may be lingering
39 // references to the constant by other constants in the constant pool. These
40 // constants are implicitly dependant on the module that is being deleted,
41 // but they don't know that. Because we only find out when the CPV is
42 // deleted, we must now notify all of our users (that should only be
43 // Constants) that they are, in fact, invalid now and should be deleted.
45 while (!use_empty()) {
46 Value *V = use_back();
47 #ifndef NDEBUG // Only in -g mode...
48 if (!isa<Constant>(V))
49 std::cerr << "While deleting: " << *this
50 << "\n\nUse still stuck around after Def is destroyed: "
53 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
54 Constant *CPV = cast<Constant>(V);
55 CPV->destroyConstant();
57 // The constant should remove itself from our use list...
58 assert((use_empty() || use_back() != V) && "Constant not removed!");
61 // Value has no outstanding references it is safe to delete it now...
65 // Static constructor to create a '0' constant of arbitrary type...
66 Constant *Constant::getNullValue(const Type *Ty) {
67 switch (Ty->getPrimitiveID()) {
68 case Type::BoolTyID: return ConstantBool::get(false);
72 case Type::LongTyID: return ConstantSInt::get(Ty, 0);
75 case Type::UShortTyID:
77 case Type::ULongTyID: return ConstantUInt::get(Ty, 0);
80 case Type::DoubleTyID: return ConstantFP::get(Ty, 0);
82 case Type::PointerTyID:
83 return ConstantPointerNull::get(cast<PointerType>(Ty));
89 // Static constructor to create the maximum constant of an integral type...
90 ConstantIntegral *ConstantIntegral::getMaxValue(const Type *Ty) {
91 switch (Ty->getPrimitiveID()) {
92 case Type::BoolTyID: return ConstantBool::True;
96 case Type::LongTyID: {
97 // Calculate 011111111111111...
98 unsigned TypeBits = Ty->getPrimitiveSize()*8;
99 int64_t Val = INT64_MAX; // All ones
100 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
101 return ConstantSInt::get(Ty, Val);
104 case Type::UByteTyID:
105 case Type::UShortTyID:
107 case Type::ULongTyID: return getAllOnesValue(Ty);
113 // Static constructor to create the minimum constant for an integral type...
114 ConstantIntegral *ConstantIntegral::getMinValue(const Type *Ty) {
115 switch (Ty->getPrimitiveID()) {
116 case Type::BoolTyID: return ConstantBool::False;
117 case Type::SByteTyID:
118 case Type::ShortTyID:
120 case Type::LongTyID: {
121 // Calculate 1111111111000000000000
122 unsigned TypeBits = Ty->getPrimitiveSize()*8;
123 int64_t Val = -1; // All ones
124 Val <<= TypeBits-1; // Shift over to the right spot
125 return ConstantSInt::get(Ty, Val);
128 case Type::UByteTyID:
129 case Type::UShortTyID:
131 case Type::ULongTyID: return ConstantUInt::get(Ty, 0);
137 // Static constructor to create an integral constant with all bits set
138 ConstantIntegral *ConstantIntegral::getAllOnesValue(const Type *Ty) {
139 switch (Ty->getPrimitiveID()) {
140 case Type::BoolTyID: return ConstantBool::True;
141 case Type::SByteTyID:
142 case Type::ShortTyID:
144 case Type::LongTyID: return ConstantSInt::get(Ty, -1);
146 case Type::UByteTyID:
147 case Type::UShortTyID:
149 case Type::ULongTyID: {
150 // Calculate ~0 of the right type...
151 unsigned TypeBits = Ty->getPrimitiveSize()*8;
152 uint64_t Val = ~0ULL; // All ones
153 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
154 return ConstantUInt::get(Ty, Val);
161 //===----------------------------------------------------------------------===//
162 // ConstantXXX Classes
163 //===----------------------------------------------------------------------===//
165 //===----------------------------------------------------------------------===//
166 // Normal Constructors
168 ConstantBool::ConstantBool(bool V) : ConstantIntegral(Type::BoolTy) {
172 ConstantInt::ConstantInt(const Type *Ty, uint64_t V) : ConstantIntegral(Ty) {
176 ConstantSInt::ConstantSInt(const Type *Ty, int64_t V) : ConstantInt(Ty, V) {
177 assert(isValueValidForType(Ty, V) && "Value too large for type!");
180 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V) : ConstantInt(Ty, V) {
181 assert(isValueValidForType(Ty, V) && "Value too large for type!");
184 ConstantFP::ConstantFP(const Type *Ty, double V) : Constant(Ty) {
185 assert(isValueValidForType(Ty, V) && "Value too large for type!");
189 ConstantArray::ConstantArray(const ArrayType *T,
190 const std::vector<Constant*> &V) : Constant(T) {
191 for (unsigned i = 0; i < V.size(); i++) {
192 assert(V[i]->getType() == T->getElementType());
193 Operands.push_back(Use(V[i], this));
197 ConstantStruct::ConstantStruct(const StructType *T,
198 const std::vector<Constant*> &V) : Constant(T) {
199 const StructType::ElementTypes &ETypes = T->getElementTypes();
200 assert(V.size() == ETypes.size() &&
201 "Invalid initializer vector for constant structure");
202 for (unsigned i = 0; i < V.size(); i++) {
203 assert(V[i]->getType() == ETypes[i]);
204 Operands.push_back(Use(V[i], this));
208 ConstantPointerRef::ConstantPointerRef(GlobalValue *GV)
209 : ConstantPointer(GV->getType()) {
210 Operands.push_back(Use(GV, this));
213 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
214 : Constant(Ty), iType(Opcode) {
215 Operands.push_back(Use(C, this));
218 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
219 : Constant(C1->getType()), iType(Opcode) {
220 Operands.push_back(Use(C1, this));
221 Operands.push_back(Use(C2, this));
224 ConstantExpr::ConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
226 : Constant(DestTy), iType(Instruction::GetElementPtr) {
227 Operands.reserve(1+IdxList.size());
228 Operands.push_back(Use(C, this));
229 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
230 Operands.push_back(Use(IdxList[i], this));
235 //===----------------------------------------------------------------------===//
236 // classof implementations
238 bool ConstantIntegral::classof(const Constant *CPV) {
239 return CPV->getType()->isIntegral() && !isa<ConstantExpr>(CPV);
242 bool ConstantInt::classof(const Constant *CPV) {
243 return CPV->getType()->isInteger() && !isa<ConstantExpr>(CPV);
245 bool ConstantSInt::classof(const Constant *CPV) {
246 return CPV->getType()->isSigned() && !isa<ConstantExpr>(CPV);
248 bool ConstantUInt::classof(const Constant *CPV) {
249 return CPV->getType()->isUnsigned() && !isa<ConstantExpr>(CPV);
251 bool ConstantFP::classof(const Constant *CPV) {
252 const Type *Ty = CPV->getType();
253 return ((Ty == Type::FloatTy || Ty == Type::DoubleTy) &&
254 !isa<ConstantExpr>(CPV));
256 bool ConstantArray::classof(const Constant *CPV) {
257 return isa<ArrayType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
259 bool ConstantStruct::classof(const Constant *CPV) {
260 return isa<StructType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
262 bool ConstantPointer::classof(const Constant *CPV) {
263 return (isa<PointerType>(CPV->getType()) && !isa<ConstantExpr>(CPV));
268 //===----------------------------------------------------------------------===//
269 // isValueValidForType implementations
271 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
272 switch (Ty->getPrimitiveID()) {
274 return false; // These can't be represented as integers!!!
277 case Type::SByteTyID:
278 return (Val <= INT8_MAX && Val >= INT8_MIN);
279 case Type::ShortTyID:
280 return (Val <= INT16_MAX && Val >= INT16_MIN);
282 return (Val <= INT32_MAX && Val >= INT32_MIN);
284 return true; // This is the largest type...
290 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
291 switch (Ty->getPrimitiveID()) {
293 return false; // These can't be represented as integers!!!
296 case Type::UByteTyID:
297 return (Val <= UINT8_MAX);
298 case Type::UShortTyID:
299 return (Val <= UINT16_MAX);
301 return (Val <= UINT32_MAX);
302 case Type::ULongTyID:
303 return true; // This is the largest type...
309 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
310 switch (Ty->getPrimitiveID()) {
312 return false; // These can't be represented as floating point!
314 // TODO: Figure out how to test if a double can be cast to a float!
315 case Type::FloatTyID:
317 return (Val <= UINT8_MAX);
319 case Type::DoubleTyID:
320 return true; // This is the largest type...
324 //===----------------------------------------------------------------------===//
325 // Factory Function Implementation
327 template<class ValType, class ConstantClass>
329 typedef pair<const Type*, ValType> ConstHashKey;
330 map<ConstHashKey, ConstantClass *> Map;
332 inline ConstantClass *get(const Type *Ty, ValType V) {
333 typename map<ConstHashKey,ConstantClass *>::iterator I =
334 Map.find(ConstHashKey(Ty, V));
335 return (I != Map.end()) ? I->second : 0;
338 inline void add(const Type *Ty, ValType V, ConstantClass *CP) {
339 Map.insert(make_pair(ConstHashKey(Ty, V), CP));
342 inline void remove(ConstantClass *CP) {
343 for (typename map<ConstHashKey,ConstantClass *>::iterator I = Map.begin(),
344 E = Map.end(); I != E;++I)
345 if (I->second == CP) {
352 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
354 static ValueMap<uint64_t, ConstantInt> IntConstants;
356 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
357 ConstantSInt *Result = (ConstantSInt*)IntConstants.get(Ty, (uint64_t)V);
358 if (!Result) // If no preexisting value, create one now...
359 IntConstants.add(Ty, V, Result = new ConstantSInt(Ty, V));
363 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
364 ConstantUInt *Result = (ConstantUInt*)IntConstants.get(Ty, V);
365 if (!Result) // If no preexisting value, create one now...
366 IntConstants.add(Ty, V, Result = new ConstantUInt(Ty, V));
370 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
371 assert(V <= 127 && "Can only be used with very small positive constants!");
372 if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
373 return ConstantUInt::get(Ty, V);
376 //---- ConstantFP::get() implementation...
378 static ValueMap<double, ConstantFP> FPConstants;
380 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
381 ConstantFP *Result = FPConstants.get(Ty, V);
382 if (!Result) // If no preexisting value, create one now...
383 FPConstants.add(Ty, V, Result = new ConstantFP(Ty, V));
387 //---- ConstantArray::get() implementation...
389 static ValueMap<std::vector<Constant*>, ConstantArray> ArrayConstants;
391 ConstantArray *ConstantArray::get(const ArrayType *Ty,
392 const std::vector<Constant*> &V) {
393 ConstantArray *Result = ArrayConstants.get(Ty, V);
394 if (!Result) // If no preexisting value, create one now...
395 ArrayConstants.add(Ty, V, Result = new ConstantArray(Ty, V));
399 // ConstantArray::get(const string&) - Return an array that is initialized to
400 // contain the specified string. A null terminator is added to the specified
401 // string so that it may be used in a natural way...
403 ConstantArray *ConstantArray::get(const std::string &Str) {
404 std::vector<Constant*> ElementVals;
406 for (unsigned i = 0; i < Str.length(); ++i)
407 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
409 // Add a null terminator to the string...
410 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
412 ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
413 return ConstantArray::get(ATy, ElementVals);
417 // destroyConstant - Remove the constant from the constant table...
419 void ConstantArray::destroyConstant() {
420 ArrayConstants.remove(this);
421 destroyConstantImpl();
424 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
425 // then this method converts the array to an std::string and returns it.
426 // Otherwise, it asserts out.
428 std::string ConstantArray::getAsString() const {
430 if (getType()->getElementType() == Type::SByteTy)
431 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
432 Result += (char)cast<ConstantSInt>(getOperand(i))->getValue();
434 assert(getType()->getElementType() == Type::UByteTy && "Not a string!");
435 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
436 Result += (char)cast<ConstantUInt>(getOperand(i))->getValue();
442 //---- ConstantStruct::get() implementation...
444 static ValueMap<std::vector<Constant*>, ConstantStruct> StructConstants;
446 ConstantStruct *ConstantStruct::get(const StructType *Ty,
447 const std::vector<Constant*> &V) {
448 ConstantStruct *Result = StructConstants.get(Ty, V);
449 if (!Result) // If no preexisting value, create one now...
450 StructConstants.add(Ty, V, Result = new ConstantStruct(Ty, V));
454 // destroyConstant - Remove the constant from the constant table...
456 void ConstantStruct::destroyConstant() {
457 StructConstants.remove(this);
458 destroyConstantImpl();
462 //---- ConstantPointerNull::get() implementation...
464 static ValueMap<char, ConstantPointerNull> NullPtrConstants;
466 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
467 ConstantPointerNull *Result = NullPtrConstants.get(Ty, 0);
468 if (!Result) // If no preexisting value, create one now...
469 NullPtrConstants.add(Ty, 0, Result = new ConstantPointerNull(Ty));
473 // destroyConstant - Remove the constant from the constant table...
475 void ConstantPointerNull::destroyConstant() {
476 NullPtrConstants.remove(this);
477 destroyConstantImpl();
481 //---- ConstantPointerRef::get() implementation...
483 ConstantPointerRef *ConstantPointerRef::get(GlobalValue *GV) {
484 assert(GV->getParent() && "Global Value must be attached to a module!");
486 // The Module handles the pointer reference sharing...
487 return GV->getParent()->getConstantPointerRef(GV);
490 // destroyConstant - Remove the constant from the constant table...
492 void ConstantPointerRef::destroyConstant() {
493 getValue()->getParent()->destroyConstantPointerRef(this);
494 destroyConstantImpl();
498 //---- ConstantExpr::get() implementations...
500 typedef pair<unsigned, vector<Constant*> > ExprMapKeyType;
501 static ValueMap<const ExprMapKeyType, ConstantExpr> ExprConstants;
503 ConstantExpr *ConstantExpr::getCast(Constant *C, const Type *Ty) {
505 // Look up the constant in the table first to ensure uniqueness
506 vector<Constant*> argVec(1, C);
507 const ExprMapKeyType &Key = make_pair(Instruction::Cast, argVec);
508 ConstantExpr *Result = ExprConstants.get(Ty, Key);
509 if (Result) return Result;
511 // Its not in the table so create a new one and put it in the table.
512 Result = new ConstantExpr(Instruction::Cast, C, Ty);
513 ExprConstants.add(Ty, Key, Result);
517 ConstantExpr *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
518 // Look up the constant in the table first to ensure uniqueness
519 vector<Constant*> argVec(1, C1); argVec.push_back(C2);
520 const ExprMapKeyType &Key = make_pair(Opcode, argVec);
521 ConstantExpr *Result = ExprConstants.get(C1->getType(), Key);
522 if (Result) return Result;
524 // Its not in the table so create a new one and put it in the table.
525 // Check the operands for consistency first
526 assert((Opcode >= Instruction::FirstBinaryOp &&
527 Opcode < Instruction::NumBinaryOps) &&
528 "Invalid opcode in binary constant expression");
530 assert(C1->getType() == C2->getType() &&
531 "Operand types in binary constant expression should match");
533 Result = new ConstantExpr(Opcode, C1, C2);
534 ExprConstants.add(C1->getType(), Key, Result);
538 ConstantExpr *ConstantExpr::getGetElementPtr(Constant *C,
539 const std::vector<Constant*> &IdxList) {
540 const Type *Ty = C->getType();
542 // Look up the constant in the table first to ensure uniqueness
543 vector<Constant*> argVec(1, C);
544 argVec.insert(argVec.end(), IdxList.begin(), IdxList.end());
546 const ExprMapKeyType &Key = make_pair(Instruction::GetElementPtr, argVec);
547 ConstantExpr *Result = ExprConstants.get(Ty, Key);
548 if (Result) return Result;
550 // Its not in the table so create a new one and put it in the table.
551 // Check the operands for consistency first
553 assert(isa<PointerType>(Ty) &&
554 "Non-pointer type for constant GelElementPtr expression");
556 // Check that the indices list is valid...
557 std::vector<Value*> ValIdxList(IdxList.begin(), IdxList.end());
558 const Type *DestTy = GetElementPtrInst::getIndexedType(Ty, ValIdxList, true);
559 assert(DestTy && "Invalid index list for constant GelElementPtr expression");
561 Result = new ConstantExpr(C, IdxList, PointerType::get(DestTy));
562 ExprConstants.add(Ty, Key, Result);
566 // destroyConstant - Remove the constant from the constant table...
568 void ConstantExpr::destroyConstant() {
569 ExprConstants.remove(this);
570 destroyConstantImpl();
573 const char *ConstantExpr::getOpcodeName() const {
574 return Instruction::getOpcodeName(getOpcode());
578 //---- ConstantPointerRef::mutateReferences() implementation...
580 unsigned ConstantPointerRef::mutateReferences(Value *OldV, Value *NewV) {
581 assert(getValue() == OldV && "Cannot mutate old value if I'm not using it!");
582 GlobalValue *NewGV = cast<GlobalValue>(NewV);
583 getValue()->getParent()->mutateConstantPointerRef(getValue(), NewGV);
589 //---- ConstantPointerExpr::mutateReferences() implementation...
591 unsigned ConstantExpr::mutateReferences(Value* OldV, Value *NewV) {
592 unsigned NumReplaced = 0;
593 Constant *NewC = cast<Constant>(NewV);
594 for (unsigned i = 0, N = getNumOperands(); i != N; ++i)
595 if (Operands[i] == OldV) {