* Move include/llvm/Analysis/SlotCalculator.h to include/llvm/SlotCalculator.h
[oota-llvm.git] / lib / VMCore / Constants.cpp
1 //===-- ConstantVals.cpp - Implement Constant nodes --------------*- C++ -*--=//
2 //
3 // This file implements the Constant* classes...
4 //
5 //===----------------------------------------------------------------------===//
6
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/SlotCalculator.h"
14 #include "Support/StringExtras.h"
15 #include <algorithm>
16
17 using std::map;
18 using std::pair;
19 using std::make_pair;
20
21 ConstantBool *ConstantBool::True  = new ConstantBool(true);
22 ConstantBool *ConstantBool::False = new ConstantBool(false);
23
24
25 //===----------------------------------------------------------------------===//
26 //                              Constant Class
27 //===----------------------------------------------------------------------===//
28
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!");
32
33   if (Name.size()) ST->insert(Name, this);
34 }
35
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);
40   case Type::SByteTyID:
41   case Type::ShortTyID:
42   case Type::IntTyID:
43   case Type::LongTyID:   return ConstantSInt::get(Ty, 0);
44
45   case Type::UByteTyID:
46   case Type::UShortTyID:
47   case Type::UIntTyID:
48   case Type::ULongTyID:  return ConstantUInt::get(Ty, 0);
49
50   case Type::FloatTyID:
51   case Type::DoubleTyID: return ConstantFP::get(Ty, 0);
52
53   case Type::PointerTyID: 
54     return ConstantPointerNull::get(cast<PointerType>(Ty));
55   default:
56     return 0;
57   }
58 }
59
60 void Constant::destroyConstantImpl() {
61   // When a Constant is destroyed, there may be lingering
62   // references to the constant by other constants in the constant pool.  These
63   // constants are implicitly dependant on the module that is being deleted,
64   // but they don't know that.  Because we only find out when the CPV is
65   // deleted, we must now notify all of our users (that should only be
66   // Constants) that they are, in fact, invalid now and should be deleted.
67   //
68   while (!use_empty()) {
69     Value *V = use_back();
70 #ifndef NDEBUG      // Only in -g mode...
71     if (!isa<Constant>(V)) {
72       std::cerr << "While deleting: ";
73       dump();
74       std::cerr << "\nUse still stuck around after Def is destroyed: ";
75       V->dump();
76       std::cerr << "\n";
77     }
78 #endif
79     assert(isa<Constant>(V) && "References remain to ConstantPointerRef!");
80     Constant *CPV = cast<Constant>(V);
81     CPV->destroyConstant();
82
83     // The constant should remove itself from our use list...
84     assert((use_empty() || use_back() == V) && "Constant not removed!");
85   }
86
87   // Value has no outstanding references it is safe to delete it now...
88   delete this;
89 }
90
91 //===----------------------------------------------------------------------===//
92 //                            ConstantXXX Classes
93 //===----------------------------------------------------------------------===//
94
95 //===----------------------------------------------------------------------===//
96 //                             Normal Constructors
97
98 ConstantBool::ConstantBool(bool V) : Constant(Type::BoolTy) {
99   Val = V;
100 }
101
102 ConstantInt::ConstantInt(const Type *Ty, uint64_t V) : Constant(Ty) {
103   Val.Unsigned = V;
104 }
105
106 ConstantSInt::ConstantSInt(const Type *Ty, int64_t V) : ConstantInt(Ty, V) {
107   assert(isValueValidForType(Ty, V) && "Value too large for type!");
108 }
109
110 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V) : ConstantInt(Ty, V) {
111   assert(isValueValidForType(Ty, V) && "Value too large for type!");
112 }
113
114 ConstantFP::ConstantFP(const Type *Ty, double V) : Constant(Ty) {
115   assert(isValueValidForType(Ty, V) && "Value too large for type!");
116   Val = V;
117 }
118
119 ConstantArray::ConstantArray(const ArrayType *T,
120                              const std::vector<Constant*> &V) : Constant(T) {
121   for (unsigned i = 0; i < V.size(); i++) {
122     assert(V[i]->getType() == T->getElementType());
123     Operands.push_back(Use(V[i], this));
124   }
125 }
126
127 ConstantStruct::ConstantStruct(const StructType *T,
128                                const std::vector<Constant*> &V) : Constant(T) {
129   const StructType::ElementTypes &ETypes = T->getElementTypes();
130   
131   for (unsigned i = 0; i < V.size(); i++) {
132     assert(V[i]->getType() == ETypes[i]);
133     Operands.push_back(Use(V[i], this));
134   }
135 }
136
137 ConstantPointerRef::ConstantPointerRef(GlobalValue *GV)
138   : ConstantPointer(GV->getType()) {
139   Operands.push_back(Use(GV, this));
140 }
141
142
143
144 //===----------------------------------------------------------------------===//
145 //                          getStrValue implementations
146
147 std::string ConstantBool::getStrValue() const {
148   return Val ? "true" : "false";
149 }
150
151 std::string ConstantSInt::getStrValue() const {
152   return itostr(Val.Signed);
153 }
154
155 std::string ConstantUInt::getStrValue() const {
156   return utostr(Val.Unsigned);
157 }
158
159 // ConstantFP::getStrValue - We would like to output the FP constant value in
160 // exponential notation, but we cannot do this if doing so will lose precision.
161 // Check here to make sure that we only output it in exponential format if we
162 // can parse the value back and get the same value.
163 //
164 std::string ConstantFP::getStrValue() const {
165   std::string StrVal = ftostr(Val);
166
167   // Check to make sure that the stringized number is not some string like "Inf"
168   // or NaN, that atof will accept, but the lexer will not.  Check that the
169   // string matches the "[-+]?[0-9]" regex.
170   //
171   if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
172       ((StrVal[0] == '-' || StrVal[0] == '+') &&
173        (StrVal[0] >= '0' && StrVal[0] <= '9'))) {
174     double TestVal = atof(StrVal.c_str());  // Reparse stringized version!
175     if (TestVal == Val)
176       return StrVal;
177   }
178
179   // Otherwise we could not reparse it to exactly the same value, so we must
180   // output the string in hexadecimal format!
181   //
182   // Behave nicely in the face of C TBAA rules... see:
183   // http://www.nullstone.com/htmls/category/aliastyp.htm
184   //
185   char *Ptr = (char*)&Val;
186   assert(sizeof(double) == sizeof(uint64_t) && sizeof(double) == 8 &&
187          "assuming that double is 64 bits!");
188   return "0x"+utohexstr(*(uint64_t*)Ptr);
189 }
190
191 std::string ConstantArray::getStrValue() const {
192   std::string Result;
193   
194   // As a special case, print the array as a string if it is an array of
195   // ubytes or an array of sbytes with positive values.
196   // 
197   const Type *ETy = cast<ArrayType>(getType())->getElementType();
198   bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
199
200   if (ETy == Type::SByteTy) {
201     for (unsigned i = 0; i < Operands.size(); ++i)
202       if (ETy == Type::SByteTy &&
203           cast<ConstantSInt>(Operands[i])->getValue() < 0) {
204         isString = false;
205         break;
206       }
207   }
208
209   if (isString) {
210     Result = "c\"";
211     for (unsigned i = 0; i < Operands.size(); ++i) {
212       unsigned char C = (ETy == Type::SByteTy) ?
213         (unsigned char)cast<ConstantSInt>(Operands[i])->getValue() :
214         (unsigned char)cast<ConstantUInt>(Operands[i])->getValue();
215
216       if (isprint(C)) {
217         Result += C;
218       } else {
219         Result += '\\';
220         Result += ( C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A');
221         Result += ((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A');
222       }
223     }
224     Result += "\"";
225
226   } else {
227     Result = "[";
228     if (Operands.size()) {
229       Result += " " + Operands[0]->getType()->getDescription() + 
230                 " " + cast<Constant>(Operands[0])->getStrValue();
231       for (unsigned i = 1; i < Operands.size(); i++)
232         Result += ", " + Operands[i]->getType()->getDescription() + 
233                   " " + cast<Constant>(Operands[i])->getStrValue();
234     }
235     Result += " ]";
236   }
237   
238   return Result;
239 }
240
241 std::string ConstantStruct::getStrValue() const {
242   std::string Result = "{";
243   if (Operands.size()) {
244     Result += " " + Operands[0]->getType()->getDescription() + 
245               " " + cast<Constant>(Operands[0])->getStrValue();
246     for (unsigned i = 1; i < Operands.size(); i++)
247       Result += ", " + Operands[i]->getType()->getDescription() + 
248                 " " + cast<Constant>(Operands[i])->getStrValue();
249   }
250
251   return Result + " }";
252 }
253
254 std::string ConstantPointerNull::getStrValue() const {
255   return "null";
256 }
257
258 std::string ConstantPointerRef::getStrValue() const {
259   const GlobalValue *V = getValue();
260   if (V->hasName()) return "%" + V->getName();
261
262   // FIXME: This is a gross hack.
263   SlotCalculator *Table = new SlotCalculator(V->getParent(), true);
264   int Slot = Table->getValSlot(V);
265   delete Table;
266
267   if (Slot >= 0) return std::string(" %") + itostr(Slot);
268   else return "<pointer reference badref>";
269 }
270
271
272 //===----------------------------------------------------------------------===//
273 //                           classof implementations
274
275 bool ConstantInt::classof(const Constant *CPV) {
276   return CPV->getType()->isIntegral();
277 }
278 bool ConstantSInt::classof(const Constant *CPV) {
279   return CPV->getType()->isSigned();
280 }
281 bool ConstantUInt::classof(const Constant *CPV) {
282   return CPV->getType()->isUnsigned();
283 }
284 bool ConstantFP::classof(const Constant *CPV) {
285   const Type *Ty = CPV->getType();
286   return Ty == Type::FloatTy || Ty == Type::DoubleTy;
287 }
288 bool ConstantArray::classof(const Constant *CPV) {
289   return isa<ArrayType>(CPV->getType());
290 }
291 bool ConstantStruct::classof(const Constant *CPV) {
292   return isa<StructType>(CPV->getType());
293 }
294 bool ConstantPointer::classof(const Constant *CPV) {
295   return isa<PointerType>(CPV->getType());
296 }
297
298
299 //===----------------------------------------------------------------------===//
300 //                      isValueValidForType implementations
301
302 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
303   switch (Ty->getPrimitiveID()) {
304   default:
305     return false;         // These can't be represented as integers!!!
306
307     // Signed types...
308   case Type::SByteTyID:
309     return (Val <= INT8_MAX && Val >= INT8_MIN);
310   case Type::ShortTyID:
311     return (Val <= INT16_MAX && Val >= INT16_MIN);
312   case Type::IntTyID:
313     return (Val <= INT32_MAX && Val >= INT32_MIN);
314   case Type::LongTyID:
315     return true;          // This is the largest type...
316   }
317   assert(0 && "WTF?");
318   return false;
319 }
320
321 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
322   switch (Ty->getPrimitiveID()) {
323   default:
324     return false;         // These can't be represented as integers!!!
325
326     // Unsigned types...
327   case Type::UByteTyID:
328     return (Val <= UINT8_MAX);
329   case Type::UShortTyID:
330     return (Val <= UINT16_MAX);
331   case Type::UIntTyID:
332     return (Val <= UINT32_MAX);
333   case Type::ULongTyID:
334     return true;          // This is the largest type...
335   }
336   assert(0 && "WTF?");
337   return false;
338 }
339
340 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
341   switch (Ty->getPrimitiveID()) {
342   default:
343     return false;         // These can't be represented as floating point!
344
345     // TODO: Figure out how to test if a double can be cast to a float!
346   case Type::FloatTyID:
347     /*
348     return (Val <= UINT8_MAX);
349     */
350   case Type::DoubleTyID:
351     return true;          // This is the largest type...
352   }
353 };
354
355 //===----------------------------------------------------------------------===//
356 //                      Hash Function Implementations
357 #if 0
358 unsigned ConstantSInt::hash(const Type *Ty, int64_t V) {
359   return unsigned(Ty->getPrimitiveID() ^ V);
360 }
361
362 unsigned ConstantUInt::hash(const Type *Ty, uint64_t V) {
363   return unsigned(Ty->getPrimitiveID() ^ V);
364 }
365
366 unsigned ConstantFP::hash(const Type *Ty, double V) {
367   return Ty->getPrimitiveID() ^ unsigned(V);
368 }
369
370 unsigned ConstantArray::hash(const ArrayType *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);
375   return Result;
376 }
377
378 unsigned ConstantStruct::hash(const StructType *Ty,
379                               const std::vector<Constant*> &V) {
380   unsigned Result = (Ty->getUniqueID() << 5) ^ (Ty->getUniqueID() * 7);
381   for (unsigned i = 0; i < V.size(); ++i)
382     Result ^= V[i]->getHash() << (i & 7);
383   return Result;
384 }
385 #endif
386
387 //===----------------------------------------------------------------------===//
388 //                      Factory Function Implementation
389
390 template<class ValType, class ConstantClass>
391 struct ValueMap {
392   typedef pair<const Type*, ValType> ConstHashKey;
393   map<ConstHashKey, ConstantClass *> Map;
394
395   inline ConstantClass *get(const Type *Ty, ValType V) {
396     map<ConstHashKey,ConstantClass *>::iterator I =
397       Map.find(ConstHashKey(Ty, V));
398     return (I != Map.end()) ? I->second : 0;
399   }
400
401   inline void add(const Type *Ty, ValType V, ConstantClass *CP) {
402     Map.insert(make_pair(ConstHashKey(Ty, V), CP));
403   }
404
405   inline void remove(ConstantClass *CP) {
406     for (map<ConstHashKey,ConstantClass *>::iterator I = Map.begin(),
407                                                       E = Map.end(); I != E;++I)
408       if (I->second == CP) {
409         Map.erase(I);
410         return;
411       }
412   }
413 };
414
415 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
416 //
417 static ValueMap<uint64_t, ConstantInt> IntConstants;
418
419 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
420   ConstantSInt *Result = (ConstantSInt*)IntConstants.get(Ty, (uint64_t)V);
421   if (!Result)   // If no preexisting value, create one now...
422     IntConstants.add(Ty, V, Result = new ConstantSInt(Ty, V));
423   return Result;
424 }
425
426 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
427   ConstantUInt *Result = (ConstantUInt*)IntConstants.get(Ty, V);
428   if (!Result)   // If no preexisting value, create one now...
429     IntConstants.add(Ty, V, Result = new ConstantUInt(Ty, V));
430   return Result;
431 }
432
433 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
434   assert(V <= 127 && "Can only be used with very small positive constants!");
435   if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
436   return ConstantUInt::get(Ty, V);
437 }
438
439 //---- ConstantFP::get() implementation...
440 //
441 static ValueMap<double, ConstantFP> FPConstants;
442
443 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
444   ConstantFP *Result = FPConstants.get(Ty, V);
445   if (!Result)   // If no preexisting value, create one now...
446     FPConstants.add(Ty, V, Result = new ConstantFP(Ty, V));
447   return Result;
448 }
449
450 //---- ConstantArray::get() implementation...
451 //
452 static ValueMap<std::vector<Constant*>, ConstantArray> ArrayConstants;
453
454 ConstantArray *ConstantArray::get(const ArrayType *Ty,
455                                   const std::vector<Constant*> &V) {
456   ConstantArray *Result = ArrayConstants.get(Ty, V);
457   if (!Result)   // If no preexisting value, create one now...
458     ArrayConstants.add(Ty, V, Result = new ConstantArray(Ty, V));
459   return Result;
460 }
461
462 // ConstantArray::get(const string&) - Return an array that is initialized to
463 // contain the specified string.  A null terminator is added to the specified
464 // string so that it may be used in a natural way...
465 //
466 ConstantArray *ConstantArray::get(const std::string &Str) {
467   std::vector<Constant*> ElementVals;
468
469   for (unsigned i = 0; i < Str.length(); ++i)
470     ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
471
472   // Add a null terminator to the string...
473   ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
474
475   ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
476   return ConstantArray::get(ATy, ElementVals);
477 }
478
479
480 // destroyConstant - Remove the constant from the constant table...
481 //
482 void ConstantArray::destroyConstant() {
483   ArrayConstants.remove(this);
484   destroyConstantImpl();
485 }
486
487 //---- ConstantStruct::get() implementation...
488 //
489 static ValueMap<std::vector<Constant*>, ConstantStruct> StructConstants;
490
491 ConstantStruct *ConstantStruct::get(const StructType *Ty,
492                                     const std::vector<Constant*> &V) {
493   ConstantStruct *Result = StructConstants.get(Ty, V);
494   if (!Result)   // If no preexisting value, create one now...
495     StructConstants.add(Ty, V, Result = new ConstantStruct(Ty, V));
496   return Result;
497 }
498
499 // destroyConstant - Remove the constant from the constant table...
500 //
501 void ConstantStruct::destroyConstant() {
502   StructConstants.remove(this);
503   destroyConstantImpl();
504 }
505
506 //---- ConstantPointerNull::get() implementation...
507 //
508 static ValueMap<char, ConstantPointerNull> NullPtrConstants;
509
510 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
511   ConstantPointerNull *Result = NullPtrConstants.get(Ty, 0);
512   if (!Result)   // If no preexisting value, create one now...
513     NullPtrConstants.add(Ty, 0, Result = new ConstantPointerNull(Ty));
514   return Result;
515 }
516
517 //---- ConstantPointerRef::get() implementation...
518 //
519 ConstantPointerRef *ConstantPointerRef::get(GlobalValue *GV) {
520   assert(GV->getParent() && "Global Value must be attached to a module!");
521
522   // The Module handles the pointer reference sharing...
523   return GV->getParent()->getConstantPointerRef(GV);
524 }
525
526
527 void ConstantPointerRef::mutateReference(GlobalValue *NewGV) {
528   getValue()->getParent()->mutateConstantPointerRef(getValue(), NewGV);
529   Operands[0] = NewGV;
530 }