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(Ty->isInteger() && Ty->isSigned() &&
178 "Illegal type for unsigned integer constant!");
179 assert(isValueValidForType(Ty, V) && "Value too large for type!");
182 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V) : ConstantInt(Ty, V) {
183 assert(Ty->isInteger() && Ty->isUnsigned() &&
184 "Illegal type for unsigned integer constant!");
185 assert(isValueValidForType(Ty, V) && "Value too large for type!");
188 ConstantFP::ConstantFP(const Type *Ty, double V) : Constant(Ty) {
189 assert(isValueValidForType(Ty, V) && "Value too large for type!");
193 ConstantArray::ConstantArray(const ArrayType *T,
194 const std::vector<Constant*> &V) : Constant(T) {
195 for (unsigned i = 0; i < V.size(); i++) {
196 assert(V[i]->getType() == T->getElementType());
197 Operands.push_back(Use(V[i], this));
201 ConstantStruct::ConstantStruct(const StructType *T,
202 const std::vector<Constant*> &V) : Constant(T) {
203 const StructType::ElementTypes &ETypes = T->getElementTypes();
204 assert(V.size() == ETypes.size() &&
205 "Invalid initializer vector for constant structure");
206 for (unsigned i = 0; i < V.size(); i++) {
207 assert(V[i]->getType() == ETypes[i]);
208 Operands.push_back(Use(V[i], this));
212 ConstantPointerRef::ConstantPointerRef(GlobalValue *GV)
213 : ConstantPointer(GV->getType()) {
214 Operands.push_back(Use(GV, this));
217 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
218 : Constant(Ty), iType(Opcode) {
219 Operands.push_back(Use(C, this));
222 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
223 : Constant(C1->getType()), iType(Opcode) {
224 Operands.push_back(Use(C1, this));
225 Operands.push_back(Use(C2, this));
228 ConstantExpr::ConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
230 : Constant(DestTy), iType(Instruction::GetElementPtr) {
231 Operands.reserve(1+IdxList.size());
232 Operands.push_back(Use(C, this));
233 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
234 Operands.push_back(Use(IdxList[i], this));
239 //===----------------------------------------------------------------------===//
240 // classof implementations
242 bool ConstantIntegral::classof(const Constant *CPV) {
243 return CPV->getType()->isIntegral() && !isa<ConstantExpr>(CPV);
246 bool ConstantInt::classof(const Constant *CPV) {
247 return CPV->getType()->isInteger() && !isa<ConstantExpr>(CPV);
249 bool ConstantSInt::classof(const Constant *CPV) {
250 return CPV->getType()->isSigned() && !isa<ConstantExpr>(CPV);
252 bool ConstantUInt::classof(const Constant *CPV) {
253 return CPV->getType()->isUnsigned() && !isa<ConstantExpr>(CPV);
255 bool ConstantFP::classof(const Constant *CPV) {
256 const Type *Ty = CPV->getType();
257 return ((Ty == Type::FloatTy || Ty == Type::DoubleTy) &&
258 !isa<ConstantExpr>(CPV));
260 bool ConstantArray::classof(const Constant *CPV) {
261 return isa<ArrayType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
263 bool ConstantStruct::classof(const Constant *CPV) {
264 return isa<StructType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
266 bool ConstantPointer::classof(const Constant *CPV) {
267 return (isa<PointerType>(CPV->getType()) && !isa<ConstantExpr>(CPV));
272 //===----------------------------------------------------------------------===//
273 // isValueValidForType implementations
275 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
276 switch (Ty->getPrimitiveID()) {
278 return false; // These can't be represented as integers!!!
281 case Type::SByteTyID:
282 return (Val <= INT8_MAX && Val >= INT8_MIN);
283 case Type::ShortTyID:
284 return (Val <= INT16_MAX && Val >= INT16_MIN);
286 return (Val <= INT32_MAX && Val >= INT32_MIN);
288 return true; // This is the largest type...
294 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
295 switch (Ty->getPrimitiveID()) {
297 return false; // These can't be represented as integers!!!
300 case Type::UByteTyID:
301 return (Val <= UINT8_MAX);
302 case Type::UShortTyID:
303 return (Val <= UINT16_MAX);
305 return (Val <= UINT32_MAX);
306 case Type::ULongTyID:
307 return true; // This is the largest type...
313 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
314 switch (Ty->getPrimitiveID()) {
316 return false; // These can't be represented as floating point!
318 // TODO: Figure out how to test if a double can be cast to a float!
319 case Type::FloatTyID:
321 return (Val <= UINT8_MAX);
323 case Type::DoubleTyID:
324 return true; // This is the largest type...
328 //===----------------------------------------------------------------------===//
329 // Factory Function Implementation
331 template<class ValType, class ConstantClass>
333 typedef pair<const Type*, ValType> ConstHashKey;
334 map<ConstHashKey, ConstantClass *> Map;
336 inline ConstantClass *get(const Type *Ty, ValType V) {
337 typename map<ConstHashKey,ConstantClass *>::iterator I =
338 Map.find(ConstHashKey(Ty, V));
339 return (I != Map.end()) ? I->second : 0;
342 inline void add(const Type *Ty, ValType V, ConstantClass *CP) {
343 Map.insert(make_pair(ConstHashKey(Ty, V), CP));
346 inline void remove(ConstantClass *CP) {
347 for (typename map<ConstHashKey,ConstantClass *>::iterator I = Map.begin(),
348 E = Map.end(); I != E;++I)
349 if (I->second == CP) {
356 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
358 static ValueMap<uint64_t, ConstantInt> IntConstants;
360 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
361 ConstantSInt *Result = (ConstantSInt*)IntConstants.get(Ty, (uint64_t)V);
362 if (!Result) // If no preexisting value, create one now...
363 IntConstants.add(Ty, V, Result = new ConstantSInt(Ty, V));
367 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
368 ConstantUInt *Result = (ConstantUInt*)IntConstants.get(Ty, V);
369 if (!Result) // If no preexisting value, create one now...
370 IntConstants.add(Ty, V, Result = new ConstantUInt(Ty, V));
374 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
375 assert(V <= 127 && "Can only be used with very small positive constants!");
376 if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
377 return ConstantUInt::get(Ty, V);
380 //---- ConstantFP::get() implementation...
382 static ValueMap<double, ConstantFP> FPConstants;
384 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
385 ConstantFP *Result = FPConstants.get(Ty, V);
386 if (!Result) // If no preexisting value, create one now...
387 FPConstants.add(Ty, V, Result = new ConstantFP(Ty, V));
391 //---- ConstantArray::get() implementation...
393 static ValueMap<std::vector<Constant*>, ConstantArray> ArrayConstants;
395 ConstantArray *ConstantArray::get(const ArrayType *Ty,
396 const std::vector<Constant*> &V) {
397 ConstantArray *Result = ArrayConstants.get(Ty, V);
398 if (!Result) // If no preexisting value, create one now...
399 ArrayConstants.add(Ty, V, Result = new ConstantArray(Ty, V));
403 // ConstantArray::get(const string&) - Return an array that is initialized to
404 // contain the specified string. A null terminator is added to the specified
405 // string so that it may be used in a natural way...
407 ConstantArray *ConstantArray::get(const std::string &Str) {
408 std::vector<Constant*> ElementVals;
410 for (unsigned i = 0; i < Str.length(); ++i)
411 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
413 // Add a null terminator to the string...
414 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
416 ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
417 return ConstantArray::get(ATy, ElementVals);
421 // destroyConstant - Remove the constant from the constant table...
423 void ConstantArray::destroyConstant() {
424 ArrayConstants.remove(this);
425 destroyConstantImpl();
428 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
429 // then this method converts the array to an std::string and returns it.
430 // Otherwise, it asserts out.
432 std::string ConstantArray::getAsString() const {
434 if (getType()->getElementType() == Type::SByteTy)
435 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
436 Result += (char)cast<ConstantSInt>(getOperand(i))->getValue();
438 assert(getType()->getElementType() == Type::UByteTy && "Not a string!");
439 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
440 Result += (char)cast<ConstantUInt>(getOperand(i))->getValue();
446 //---- ConstantStruct::get() implementation...
448 static ValueMap<std::vector<Constant*>, ConstantStruct> StructConstants;
450 ConstantStruct *ConstantStruct::get(const StructType *Ty,
451 const std::vector<Constant*> &V) {
452 ConstantStruct *Result = StructConstants.get(Ty, V);
453 if (!Result) // If no preexisting value, create one now...
454 StructConstants.add(Ty, V, Result = new ConstantStruct(Ty, V));
458 // destroyConstant - Remove the constant from the constant table...
460 void ConstantStruct::destroyConstant() {
461 StructConstants.remove(this);
462 destroyConstantImpl();
466 //---- ConstantPointerNull::get() implementation...
468 static ValueMap<char, ConstantPointerNull> NullPtrConstants;
470 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
471 ConstantPointerNull *Result = NullPtrConstants.get(Ty, 0);
472 if (!Result) // If no preexisting value, create one now...
473 NullPtrConstants.add(Ty, 0, Result = new ConstantPointerNull(Ty));
477 // destroyConstant - Remove the constant from the constant table...
479 void ConstantPointerNull::destroyConstant() {
480 NullPtrConstants.remove(this);
481 destroyConstantImpl();
485 //---- ConstantPointerRef::get() implementation...
487 ConstantPointerRef *ConstantPointerRef::get(GlobalValue *GV) {
488 assert(GV->getParent() && "Global Value must be attached to a module!");
490 // The Module handles the pointer reference sharing...
491 return GV->getParent()->getConstantPointerRef(GV);
494 // destroyConstant - Remove the constant from the constant table...
496 void ConstantPointerRef::destroyConstant() {
497 getValue()->getParent()->destroyConstantPointerRef(this);
498 destroyConstantImpl();
502 //---- ConstantExpr::get() implementations...
504 typedef pair<unsigned, vector<Constant*> > ExprMapKeyType;
505 static ValueMap<const ExprMapKeyType, ConstantExpr> ExprConstants;
507 ConstantExpr *ConstantExpr::getCast(Constant *C, const Type *Ty) {
509 // Look up the constant in the table first to ensure uniqueness
510 vector<Constant*> argVec(1, C);
511 const ExprMapKeyType &Key = make_pair(Instruction::Cast, argVec);
512 ConstantExpr *Result = ExprConstants.get(Ty, Key);
513 if (Result) return Result;
515 // Its not in the table so create a new one and put it in the table.
516 Result = new ConstantExpr(Instruction::Cast, C, Ty);
517 ExprConstants.add(Ty, Key, Result);
521 ConstantExpr *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
522 // Look up the constant in the table first to ensure uniqueness
523 vector<Constant*> argVec(1, C1); argVec.push_back(C2);
524 const ExprMapKeyType &Key = make_pair(Opcode, argVec);
525 ConstantExpr *Result = ExprConstants.get(C1->getType(), Key);
526 if (Result) return Result;
528 // Its not in the table so create a new one and put it in the table.
529 // Check the operands for consistency first
530 assert((Opcode >= Instruction::FirstBinaryOp &&
531 Opcode < Instruction::NumBinaryOps) &&
532 "Invalid opcode in binary constant expression");
534 assert(C1->getType() == C2->getType() &&
535 "Operand types in binary constant expression should match");
537 Result = new ConstantExpr(Opcode, C1, C2);
538 ExprConstants.add(C1->getType(), Key, Result);
542 ConstantExpr *ConstantExpr::getGetElementPtr(Constant *C,
543 const std::vector<Constant*> &IdxList) {
544 const Type *Ty = C->getType();
546 // Look up the constant in the table first to ensure uniqueness
547 vector<Constant*> argVec(1, C);
548 argVec.insert(argVec.end(), IdxList.begin(), IdxList.end());
550 const ExprMapKeyType &Key = make_pair(Instruction::GetElementPtr, argVec);
551 ConstantExpr *Result = ExprConstants.get(Ty, Key);
552 if (Result) return Result;
554 // Its not in the table so create a new one and put it in the table.
555 // Check the operands for consistency first
557 assert(isa<PointerType>(Ty) &&
558 "Non-pointer type for constant GelElementPtr expression");
560 // Check that the indices list is valid...
561 std::vector<Value*> ValIdxList(IdxList.begin(), IdxList.end());
562 const Type *DestTy = GetElementPtrInst::getIndexedType(Ty, ValIdxList, true);
563 assert(DestTy && "Invalid index list for constant GelElementPtr expression");
565 Result = new ConstantExpr(C, IdxList, PointerType::get(DestTy));
566 ExprConstants.add(Ty, Key, Result);
570 // destroyConstant - Remove the constant from the constant table...
572 void ConstantExpr::destroyConstant() {
573 ExprConstants.remove(this);
574 destroyConstantImpl();
577 const char *ConstantExpr::getOpcodeName() const {
578 return Instruction::getOpcodeName(getOpcode());
582 //---- ConstantPointerRef::mutateReferences() implementation...
584 unsigned ConstantPointerRef::mutateReferences(Value *OldV, Value *NewV) {
585 assert(getValue() == OldV && "Cannot mutate old value if I'm not using it!");
586 GlobalValue *NewGV = cast<GlobalValue>(NewV);
587 getValue()->getParent()->mutateConstantPointerRef(getValue(), NewGV);
593 //---- ConstantPointerExpr::mutateReferences() implementation...
595 unsigned ConstantExpr::mutateReferences(Value* OldV, Value *NewV) {
596 unsigned NumReplaced = 0;
597 Constant *NewC = cast<Constant>(NewV);
598 for (unsigned i = 0, N = getNumOperands(); i != N; ++i)
599 if (Operands[i] == OldV) {