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);
168 double TestVal = atof(StrVal.c_str()); // Reparse stringized version!
172 // Otherwise we could not reparse it to exactly the same value, so we must
173 // output the string in hexadecimal format!
175 // Behave nicely in the face of C TBAA rules... see:
176 // http://www.nullstone.com/htmls/category/aliastyp.htm
178 char *Ptr = (char*)&Val;
179 assert(sizeof(double) == sizeof(uint64_t) && sizeof(double) == 8 &&
180 "assuming that double is 64 bits!");
181 return "0x"+utohexstr(*(uint64_t*)Ptr);
184 std::string ConstantArray::getStrValue() const {
187 // As a special case, print the array as a string if it is an array of
188 // ubytes or an array of sbytes with positive values.
190 const Type *ETy = cast<ArrayType>(getType())->getElementType();
191 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
193 if (ETy == Type::SByteTy) {
194 for (unsigned i = 0; i < Operands.size(); ++i)
195 if (ETy == Type::SByteTy &&
196 cast<ConstantSInt>(Operands[i])->getValue() < 0) {
204 for (unsigned i = 0; i < Operands.size(); ++i) {
205 unsigned char C = (ETy == Type::SByteTy) ?
206 (unsigned char)cast<ConstantSInt>(Operands[i])->getValue() :
207 (unsigned char)cast<ConstantUInt>(Operands[i])->getValue();
213 Result += ( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A');
214 Result += ((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A');
221 if (Operands.size()) {
222 Result += " " + Operands[0]->getType()->getDescription() +
223 " " + cast<Constant>(Operands[0])->getStrValue();
224 for (unsigned i = 1; i < Operands.size(); i++)
225 Result += ", " + Operands[i]->getType()->getDescription() +
226 " " + cast<Constant>(Operands[i])->getStrValue();
234 std::string ConstantStruct::getStrValue() const {
235 std::string Result = "{";
236 if (Operands.size()) {
237 Result += " " + Operands[0]->getType()->getDescription() +
238 " " + cast<Constant>(Operands[0])->getStrValue();
239 for (unsigned i = 1; i < Operands.size(); i++)
240 Result += ", " + Operands[i]->getType()->getDescription() +
241 " " + cast<Constant>(Operands[i])->getStrValue();
244 return Result + " }";
247 std::string ConstantPointerNull::getStrValue() const {
251 std::string ConstantPointerRef::getStrValue() const {
252 const GlobalValue *V = getValue();
253 if (V->hasName()) return "%" + V->getName();
255 SlotCalculator *Table = new SlotCalculator(V->getParent(), true);
256 int Slot = Table->getValSlot(V);
259 if (Slot >= 0) return std::string(" %") + itostr(Slot);
260 else return "<pointer reference badref>";
264 //===----------------------------------------------------------------------===//
265 // classof implementations
267 bool ConstantInt::classof(const Constant *CPV) {
268 return CPV->getType()->isIntegral();
270 bool ConstantSInt::classof(const Constant *CPV) {
271 return CPV->getType()->isSigned();
273 bool ConstantUInt::classof(const Constant *CPV) {
274 return CPV->getType()->isUnsigned();
276 bool ConstantFP::classof(const Constant *CPV) {
277 const Type *Ty = CPV->getType();
278 return Ty == Type::FloatTy || Ty == Type::DoubleTy;
280 bool ConstantArray::classof(const Constant *CPV) {
281 return isa<ArrayType>(CPV->getType());
283 bool ConstantStruct::classof(const Constant *CPV) {
284 return isa<StructType>(CPV->getType());
286 bool ConstantPointer::classof(const Constant *CPV) {
287 return isa<PointerType>(CPV->getType());
291 //===----------------------------------------------------------------------===//
292 // isValueValidForType implementations
294 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
295 switch (Ty->getPrimitiveID()) {
297 return false; // These can't be represented as integers!!!
300 case Type::SByteTyID:
301 return (Val <= INT8_MAX && Val >= INT8_MIN);
302 case Type::ShortTyID:
303 return (Val <= INT16_MAX && Val >= INT16_MIN);
305 return (Val <= INT32_MAX && Val >= INT32_MIN);
307 return true; // This is the largest type...
313 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
314 switch (Ty->getPrimitiveID()) {
316 return false; // These can't be represented as integers!!!
319 case Type::UByteTyID:
320 return (Val <= UINT8_MAX);
321 case Type::UShortTyID:
322 return (Val <= UINT16_MAX);
324 return (Val <= UINT32_MAX);
325 case Type::ULongTyID:
326 return true; // This is the largest type...
332 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
333 switch (Ty->getPrimitiveID()) {
335 return false; // These can't be represented as floating point!
337 // TODO: Figure out how to test if a double can be cast to a float!
338 case Type::FloatTyID:
340 return (Val <= UINT8_MAX);
342 case Type::DoubleTyID:
343 return true; // This is the largest type...
347 //===----------------------------------------------------------------------===//
348 // Hash Function Implementations
350 unsigned ConstantSInt::hash(const Type *Ty, int64_t V) {
351 return unsigned(Ty->getPrimitiveID() ^ V);
354 unsigned ConstantUInt::hash(const Type *Ty, uint64_t V) {
355 return unsigned(Ty->getPrimitiveID() ^ V);
358 unsigned ConstantFP::hash(const Type *Ty, double V) {
359 return Ty->getPrimitiveID() ^ unsigned(V);
362 unsigned ConstantArray::hash(const ArrayType *Ty,
363 const std::vector<Constant*> &V) {
364 unsigned Result = (Ty->getUniqueID() << 5) ^ (Ty->getUniqueID() * 7);
365 for (unsigned i = 0; i < V.size(); ++i)
366 Result ^= V[i]->getHash() << (i & 7);
370 unsigned ConstantStruct::hash(const StructType *Ty,
371 const std::vector<Constant*> &V) {
372 unsigned Result = (Ty->getUniqueID() << 5) ^ (Ty->getUniqueID() * 7);
373 for (unsigned i = 0; i < V.size(); ++i)
374 Result ^= V[i]->getHash() << (i & 7);
379 //===----------------------------------------------------------------------===//
380 // Factory Function Implementation
382 template<class ValType, class ConstantClass>
384 typedef pair<const Type*, ValType> ConstHashKey;
385 map<ConstHashKey, ConstantClass *> Map;
387 inline ConstantClass *get(const Type *Ty, ValType V) {
388 map<ConstHashKey,ConstantClass *>::iterator I =
389 Map.find(ConstHashKey(Ty, V));
390 return (I != Map.end()) ? I->second : 0;
393 inline void add(const Type *Ty, ValType V, ConstantClass *CP) {
394 Map.insert(make_pair(ConstHashKey(Ty, V), CP));
397 inline void remove(ConstantClass *CP) {
398 for (map<ConstHashKey,ConstantClass *>::iterator I = Map.begin(),
399 E = Map.end(); I != E;++I)
400 if (I->second == CP) {
407 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
409 static ValueMap<uint64_t, ConstantInt> IntConstants;
411 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
412 ConstantSInt *Result = (ConstantSInt*)IntConstants.get(Ty, (uint64_t)V);
413 if (!Result) // If no preexisting value, create one now...
414 IntConstants.add(Ty, V, Result = new ConstantSInt(Ty, V));
418 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
419 ConstantUInt *Result = (ConstantUInt*)IntConstants.get(Ty, V);
420 if (!Result) // If no preexisting value, create one now...
421 IntConstants.add(Ty, V, Result = new ConstantUInt(Ty, V));
425 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
426 assert(V <= 127 && "Can only be used with very small positive constants!");
427 if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
428 return ConstantUInt::get(Ty, V);
431 //---- ConstantFP::get() implementation...
433 static ValueMap<double, ConstantFP> FPConstants;
435 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
436 ConstantFP *Result = FPConstants.get(Ty, V);
437 if (!Result) // If no preexisting value, create one now...
438 FPConstants.add(Ty, V, Result = new ConstantFP(Ty, V));
442 //---- ConstantArray::get() implementation...
444 static ValueMap<std::vector<Constant*>, ConstantArray> ArrayConstants;
446 ConstantArray *ConstantArray::get(const ArrayType *Ty,
447 const std::vector<Constant*> &V) {
448 ConstantArray *Result = ArrayConstants.get(Ty, V);
449 if (!Result) // If no preexisting value, create one now...
450 ArrayConstants.add(Ty, V, Result = new ConstantArray(Ty, V));
454 // ConstantArray::get(const string&) - Return an array that is initialized to
455 // contain the specified string. A null terminator is added to the specified
456 // string so that it may be used in a natural way...
458 ConstantArray *ConstantArray::get(const std::string &Str) {
459 std::vector<Constant*> ElementVals;
461 for (unsigned i = 0; i < Str.length(); ++i)
462 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
464 // Add a null terminator to the string...
465 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
467 ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
468 return ConstantArray::get(ATy, ElementVals);
472 // destroyConstant - Remove the constant from the constant table...
474 void ConstantArray::destroyConstant() {
475 ArrayConstants.remove(this);
476 destroyConstantImpl();
479 //---- ConstantStruct::get() implementation...
481 static ValueMap<std::vector<Constant*>, ConstantStruct> StructConstants;
483 ConstantStruct *ConstantStruct::get(const StructType *Ty,
484 const std::vector<Constant*> &V) {
485 ConstantStruct *Result = StructConstants.get(Ty, V);
486 if (!Result) // If no preexisting value, create one now...
487 StructConstants.add(Ty, V, Result = new ConstantStruct(Ty, V));
491 // destroyConstant - Remove the constant from the constant table...
493 void ConstantStruct::destroyConstant() {
494 StructConstants.remove(this);
495 destroyConstantImpl();
498 //---- ConstantPointerNull::get() implementation...
500 static ValueMap<char, ConstantPointerNull> NullPtrConstants;
502 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
503 ConstantPointerNull *Result = NullPtrConstants.get(Ty, 0);
504 if (!Result) // If no preexisting value, create one now...
505 NullPtrConstants.add(Ty, 0, Result = new ConstantPointerNull(Ty));
509 //---- ConstantPointerRef::get() implementation...
511 ConstantPointerRef *ConstantPointerRef::get(GlobalValue *GV) {
512 assert(GV->getParent() && "Global Value must be attached to a module!");
514 // The Module handles the pointer reference sharing...
515 return GV->getParent()->getConstantPointerRef(GV);
519 void ConstantPointerRef::mutateReference(GlobalValue *NewGV) {
520 getValue()->getParent()->mutateConstantPointerRef(getValue(), NewGV);