1 //===-- ConstantVals.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/ConstantVals.h"
9 #include "llvm/DerivedTypes.h"
10 #include "llvm/SymbolTable.h"
11 #include "llvm/GlobalValue.h"
12 #include "llvm/Module.h"
13 #include "llvm/Analysis/SlotCalculator.h"
14 #include "Support/StringExtras.h"
21 ConstantBool *ConstantBool::True = new ConstantBool(true);
22 ConstantBool *ConstantBool::False = new ConstantBool(false);
25 //===----------------------------------------------------------------------===//
27 //===----------------------------------------------------------------------===//
29 // Specialize setName to take care of symbol table majik
30 void Constant::setName(const std::string &Name, SymbolTable *ST) {
31 assert(ST && "Type::setName - Must provide symbol table argument!");
33 if (Name.size()) ST->insert(Name, this);
36 // Static constructor to create a '0' constant of arbitrary type...
37 Constant *Constant::getNullConstant(const Type *Ty) {
38 switch (Ty->getPrimitiveID()) {
39 case Type::BoolTyID: return ConstantBool::get(false);
43 case Type::LongTyID: return ConstantSInt::get(Ty, 0);
46 case Type::UShortTyID:
48 case Type::ULongTyID: return ConstantUInt::get(Ty, 0);
51 case Type::DoubleTyID: return ConstantFP::get(Ty, 0);
53 case Type::PointerTyID:
54 return ConstantPointerNull::get(cast<PointerType>(Ty));
61 #include "llvm/Assembly/Writer.h"
65 void Constant::destroyConstantImpl() {
66 // When a Constant is destroyed, there may be lingering
67 // references to the constant by other constants in the constant pool. These
68 // constants are implicitly dependant on the module that is being deleted,
69 // but they don't know that. Because we only find out when the CPV is
70 // deleted, we must now notify all of our users (that should only be
71 // Constants) that they are, in fact, invalid now and should be deleted.
73 while (!use_empty()) {
74 Value *V = use_back();
75 #ifndef NDEBUG // Only in -g mode...
76 if (!isa<Constant>(V)) {
77 cerr << "While deleting: " << this << "\n";
78 cerr << "Use still stuck around after Def is destroyed: " << V << "\n";
81 assert(isa<Constant>(V) && "References remain to ConstantPointerRef!");
82 Constant *CPV = cast<Constant>(V);
83 CPV->destroyConstant();
85 // The constant should remove itself from our use list...
86 assert((use_empty() || use_back() == V) && "Constant not removed!");
89 // Value has no outstanding references it is safe to delete it now...
93 //===----------------------------------------------------------------------===//
94 // ConstantXXX Classes
95 //===----------------------------------------------------------------------===//
97 //===----------------------------------------------------------------------===//
98 // Normal Constructors
100 ConstantBool::ConstantBool(bool V) : Constant(Type::BoolTy) {
104 ConstantInt::ConstantInt(const Type *Ty, uint64_t V) : Constant(Ty) {
108 ConstantSInt::ConstantSInt(const Type *Ty, int64_t V) : ConstantInt(Ty, V) {
109 assert(isValueValidForType(Ty, V) && "Value too large for type!");
112 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V) : ConstantInt(Ty, V) {
113 assert(isValueValidForType(Ty, V) && "Value too large for type!");
116 ConstantFP::ConstantFP(const Type *Ty, double V) : Constant(Ty) {
117 assert(isValueValidForType(Ty, V) && "Value too large for type!");
121 ConstantArray::ConstantArray(const ArrayType *T,
122 const std::vector<Constant*> &V) : Constant(T) {
123 for (unsigned i = 0; i < V.size(); i++) {
124 assert(V[i]->getType() == T->getElementType());
125 Operands.push_back(Use(V[i], this));
129 ConstantStruct::ConstantStruct(const StructType *T,
130 const std::vector<Constant*> &V) : Constant(T) {
131 const StructType::ElementTypes &ETypes = T->getElementTypes();
133 for (unsigned i = 0; i < V.size(); i++) {
134 assert(V[i]->getType() == ETypes[i]);
135 Operands.push_back(Use(V[i], this));
139 ConstantPointerRef::ConstantPointerRef(GlobalValue *GV)
140 : ConstantPointer(GV->getType()) {
141 Operands.push_back(Use(GV, this));
146 //===----------------------------------------------------------------------===//
147 // getStrValue implementations
149 std::string ConstantBool::getStrValue() const {
150 return Val ? "true" : "false";
153 std::string ConstantSInt::getStrValue() const {
154 return itostr(Val.Signed);
157 std::string ConstantUInt::getStrValue() const {
158 return utostr(Val.Unsigned);
161 // ConstantFP::getStrValue - We would like to output the FP constant value in
162 // exponential notation, but we cannot do this if doing so will lose precision.
163 // Check here to make sure that we only output it in exponential format if we
164 // can parse the value back and get the same value.
166 std::string ConstantFP::getStrValue() const {
167 std::string StrVal = ftostr(Val);
169 // Check to make sure that the stringized number is not some string like "Inf"
170 // or NaN, that atof will accept, but the lexer will not. Check that the
171 // string matches the "[-+]?[0-9]" regex.
173 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
174 ((StrVal[0] == '-' || StrVal[0] == '+') &&
175 (StrVal[0] >= '0' && StrVal[0] <= '9'))) {
176 double TestVal = atof(StrVal.c_str()); // Reparse stringized version!
181 // Otherwise we could not reparse it to exactly the same value, so we must
182 // output the string in hexadecimal format!
184 // Behave nicely in the face of C TBAA rules... see:
185 // http://www.nullstone.com/htmls/category/aliastyp.htm
187 char *Ptr = (char*)&Val;
188 assert(sizeof(double) == sizeof(uint64_t) && sizeof(double) == 8 &&
189 "assuming that double is 64 bits!");
190 return "0x"+utohexstr(*(uint64_t*)Ptr);
193 std::string ConstantArray::getStrValue() const {
196 // As a special case, print the array as a string if it is an array of
197 // ubytes or an array of sbytes with positive values.
199 const Type *ETy = cast<ArrayType>(getType())->getElementType();
200 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
202 if (ETy == Type::SByteTy) {
203 for (unsigned i = 0; i < Operands.size(); ++i)
204 if (ETy == Type::SByteTy &&
205 cast<ConstantSInt>(Operands[i])->getValue() < 0) {
213 for (unsigned i = 0; i < Operands.size(); ++i) {
214 unsigned char C = (ETy == Type::SByteTy) ?
215 (unsigned char)cast<ConstantSInt>(Operands[i])->getValue() :
216 (unsigned char)cast<ConstantUInt>(Operands[i])->getValue();
222 Result += ( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A');
223 Result += ((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A');
230 if (Operands.size()) {
231 Result += " " + Operands[0]->getType()->getDescription() +
232 " " + cast<Constant>(Operands[0])->getStrValue();
233 for (unsigned i = 1; i < Operands.size(); i++)
234 Result += ", " + Operands[i]->getType()->getDescription() +
235 " " + cast<Constant>(Operands[i])->getStrValue();
243 std::string ConstantStruct::getStrValue() const {
244 std::string Result = "{";
245 if (Operands.size()) {
246 Result += " " + Operands[0]->getType()->getDescription() +
247 " " + cast<Constant>(Operands[0])->getStrValue();
248 for (unsigned i = 1; i < Operands.size(); i++)
249 Result += ", " + Operands[i]->getType()->getDescription() +
250 " " + cast<Constant>(Operands[i])->getStrValue();
253 return Result + " }";
256 std::string ConstantPointerNull::getStrValue() const {
260 std::string ConstantPointerRef::getStrValue() const {
261 const GlobalValue *V = getValue();
262 if (V->hasName()) return "%" + V->getName();
264 SlotCalculator *Table = new SlotCalculator(V->getParent(), true);
265 int Slot = Table->getValSlot(V);
268 if (Slot >= 0) return std::string(" %") + itostr(Slot);
269 else return "<pointer reference badref>";
273 //===----------------------------------------------------------------------===//
274 // classof implementations
276 bool ConstantInt::classof(const Constant *CPV) {
277 return CPV->getType()->isIntegral();
279 bool ConstantSInt::classof(const Constant *CPV) {
280 return CPV->getType()->isSigned();
282 bool ConstantUInt::classof(const Constant *CPV) {
283 return CPV->getType()->isUnsigned();
285 bool ConstantFP::classof(const Constant *CPV) {
286 const Type *Ty = CPV->getType();
287 return Ty == Type::FloatTy || Ty == Type::DoubleTy;
289 bool ConstantArray::classof(const Constant *CPV) {
290 return isa<ArrayType>(CPV->getType());
292 bool ConstantStruct::classof(const Constant *CPV) {
293 return isa<StructType>(CPV->getType());
295 bool ConstantPointer::classof(const Constant *CPV) {
296 return isa<PointerType>(CPV->getType());
300 //===----------------------------------------------------------------------===//
301 // isValueValidForType implementations
303 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
304 switch (Ty->getPrimitiveID()) {
306 return false; // These can't be represented as integers!!!
309 case Type::SByteTyID:
310 return (Val <= INT8_MAX && Val >= INT8_MIN);
311 case Type::ShortTyID:
312 return (Val <= INT16_MAX && Val >= INT16_MIN);
314 return (Val <= INT32_MAX && Val >= INT32_MIN);
316 return true; // This is the largest type...
322 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
323 switch (Ty->getPrimitiveID()) {
325 return false; // These can't be represented as integers!!!
328 case Type::UByteTyID:
329 return (Val <= UINT8_MAX);
330 case Type::UShortTyID:
331 return (Val <= UINT16_MAX);
333 return (Val <= UINT32_MAX);
334 case Type::ULongTyID:
335 return true; // This is the largest type...
341 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
342 switch (Ty->getPrimitiveID()) {
344 return false; // These can't be represented as floating point!
346 // TODO: Figure out how to test if a double can be cast to a float!
347 case Type::FloatTyID:
349 return (Val <= UINT8_MAX);
351 case Type::DoubleTyID:
352 return true; // This is the largest type...
356 //===----------------------------------------------------------------------===//
357 // Hash Function Implementations
359 unsigned ConstantSInt::hash(const Type *Ty, int64_t V) {
360 return unsigned(Ty->getPrimitiveID() ^ V);
363 unsigned ConstantUInt::hash(const Type *Ty, uint64_t V) {
364 return unsigned(Ty->getPrimitiveID() ^ V);
367 unsigned ConstantFP::hash(const Type *Ty, double V) {
368 return Ty->getPrimitiveID() ^ unsigned(V);
371 unsigned ConstantArray::hash(const ArrayType *Ty,
372 const std::vector<Constant*> &V) {
373 unsigned Result = (Ty->getUniqueID() << 5) ^ (Ty->getUniqueID() * 7);
374 for (unsigned i = 0; i < V.size(); ++i)
375 Result ^= V[i]->getHash() << (i & 7);
379 unsigned ConstantStruct::hash(const StructType *Ty,
380 const std::vector<Constant*> &V) {
381 unsigned Result = (Ty->getUniqueID() << 5) ^ (Ty->getUniqueID() * 7);
382 for (unsigned i = 0; i < V.size(); ++i)
383 Result ^= V[i]->getHash() << (i & 7);
388 //===----------------------------------------------------------------------===//
389 // Factory Function Implementation
391 template<class ValType, class ConstantClass>
393 typedef pair<const Type*, ValType> ConstHashKey;
394 map<ConstHashKey, ConstantClass *> Map;
396 inline ConstantClass *get(const Type *Ty, ValType V) {
397 map<ConstHashKey,ConstantClass *>::iterator I =
398 Map.find(ConstHashKey(Ty, V));
399 return (I != Map.end()) ? I->second : 0;
402 inline void add(const Type *Ty, ValType V, ConstantClass *CP) {
403 Map.insert(make_pair(ConstHashKey(Ty, V), CP));
406 inline void remove(ConstantClass *CP) {
407 for (map<ConstHashKey,ConstantClass *>::iterator I = Map.begin(),
408 E = Map.end(); I != E;++I)
409 if (I->second == CP) {
416 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
418 static ValueMap<uint64_t, ConstantInt> IntConstants;
420 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
421 ConstantSInt *Result = (ConstantSInt*)IntConstants.get(Ty, (uint64_t)V);
422 if (!Result) // If no preexisting value, create one now...
423 IntConstants.add(Ty, V, Result = new ConstantSInt(Ty, V));
427 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
428 ConstantUInt *Result = (ConstantUInt*)IntConstants.get(Ty, V);
429 if (!Result) // If no preexisting value, create one now...
430 IntConstants.add(Ty, V, Result = new ConstantUInt(Ty, V));
434 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
435 assert(V <= 127 && "Can only be used with very small positive constants!");
436 if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
437 return ConstantUInt::get(Ty, V);
440 //---- ConstantFP::get() implementation...
442 static ValueMap<double, ConstantFP> FPConstants;
444 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
445 ConstantFP *Result = FPConstants.get(Ty, V);
446 if (!Result) // If no preexisting value, create one now...
447 FPConstants.add(Ty, V, Result = new ConstantFP(Ty, V));
451 //---- ConstantArray::get() implementation...
453 static ValueMap<std::vector<Constant*>, ConstantArray> ArrayConstants;
455 ConstantArray *ConstantArray::get(const ArrayType *Ty,
456 const std::vector<Constant*> &V) {
457 ConstantArray *Result = ArrayConstants.get(Ty, V);
458 if (!Result) // If no preexisting value, create one now...
459 ArrayConstants.add(Ty, V, Result = new ConstantArray(Ty, V));
463 // ConstantArray::get(const string&) - Return an array that is initialized to
464 // contain the specified string. A null terminator is added to the specified
465 // string so that it may be used in a natural way...
467 ConstantArray *ConstantArray::get(const std::string &Str) {
468 std::vector<Constant*> ElementVals;
470 for (unsigned i = 0; i < Str.length(); ++i)
471 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
473 // Add a null terminator to the string...
474 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
476 ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
477 return ConstantArray::get(ATy, ElementVals);
481 // destroyConstant - Remove the constant from the constant table...
483 void ConstantArray::destroyConstant() {
484 ArrayConstants.remove(this);
485 destroyConstantImpl();
488 //---- ConstantStruct::get() implementation...
490 static ValueMap<std::vector<Constant*>, ConstantStruct> StructConstants;
492 ConstantStruct *ConstantStruct::get(const StructType *Ty,
493 const std::vector<Constant*> &V) {
494 ConstantStruct *Result = StructConstants.get(Ty, V);
495 if (!Result) // If no preexisting value, create one now...
496 StructConstants.add(Ty, V, Result = new ConstantStruct(Ty, V));
500 // destroyConstant - Remove the constant from the constant table...
502 void ConstantStruct::destroyConstant() {
503 StructConstants.remove(this);
504 destroyConstantImpl();
507 //---- ConstantPointerNull::get() implementation...
509 static ValueMap<char, ConstantPointerNull> NullPtrConstants;
511 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
512 ConstantPointerNull *Result = NullPtrConstants.get(Ty, 0);
513 if (!Result) // If no preexisting value, create one now...
514 NullPtrConstants.add(Ty, 0, Result = new ConstantPointerNull(Ty));
518 //---- ConstantPointerRef::get() implementation...
520 ConstantPointerRef *ConstantPointerRef::get(GlobalValue *GV) {
521 assert(GV->getParent() && "Global Value must be attached to a module!");
523 // The Module handles the pointer reference sharing...
524 return GV->getParent()->getConstantPointerRef(GV);
528 void ConstantPointerRef::mutateReference(GlobalValue *NewGV) {
529 getValue()->getParent()->mutateConstantPointerRef(getValue(), NewGV);