Fix Bug: test/Regression/Other/2002-04-07-InfConstant.ll
[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/Analysis/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 #ifndef NDEBUG
61 #include "llvm/Assembly/Writer.h"
62 using std::cerr;
63 #endif
64
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.
72   //
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";
79     }
80 #endif
81     assert(isa<Constant>(V) && "References remain to ConstantPointerRef!");
82     Constant *CPV = cast<Constant>(V);
83     CPV->destroyConstant();
84
85     // The constant should remove itself from our use list...
86     assert((use_empty() || use_back() == V) && "Constant not removed!");
87   }
88
89   // Value has no outstanding references it is safe to delete it now...
90   delete this;
91 }
92
93 //===----------------------------------------------------------------------===//
94 //                            ConstantXXX Classes
95 //===----------------------------------------------------------------------===//
96
97 //===----------------------------------------------------------------------===//
98 //                             Normal Constructors
99
100 ConstantBool::ConstantBool(bool V) : Constant(Type::BoolTy) {
101   Val = V;
102 }
103
104 ConstantInt::ConstantInt(const Type *Ty, uint64_t V) : Constant(Ty) {
105   Val.Unsigned = V;
106 }
107
108 ConstantSInt::ConstantSInt(const Type *Ty, int64_t V) : ConstantInt(Ty, V) {
109   assert(isValueValidForType(Ty, V) && "Value too large for type!");
110 }
111
112 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V) : ConstantInt(Ty, V) {
113   assert(isValueValidForType(Ty, V) && "Value too large for type!");
114 }
115
116 ConstantFP::ConstantFP(const Type *Ty, double V) : Constant(Ty) {
117   assert(isValueValidForType(Ty, V) && "Value too large for type!");
118   Val = V;
119 }
120
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));
126   }
127 }
128
129 ConstantStruct::ConstantStruct(const StructType *T,
130                                const std::vector<Constant*> &V) : Constant(T) {
131   const StructType::ElementTypes &ETypes = T->getElementTypes();
132   
133   for (unsigned i = 0; i < V.size(); i++) {
134     assert(V[i]->getType() == ETypes[i]);
135     Operands.push_back(Use(V[i], this));
136   }
137 }
138
139 ConstantPointerRef::ConstantPointerRef(GlobalValue *GV)
140   : ConstantPointer(GV->getType()) {
141   Operands.push_back(Use(GV, this));
142 }
143
144
145
146 //===----------------------------------------------------------------------===//
147 //                          getStrValue implementations
148
149 std::string ConstantBool::getStrValue() const {
150   return Val ? "true" : "false";
151 }
152
153 std::string ConstantSInt::getStrValue() const {
154   return itostr(Val.Signed);
155 }
156
157 std::string ConstantUInt::getStrValue() const {
158   return utostr(Val.Unsigned);
159 }
160
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.
165 //
166 std::string ConstantFP::getStrValue() const {
167   std::string StrVal = ftostr(Val);
168
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.
172   //
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!
177     if (TestVal == Val)
178       return StrVal;
179   }
180
181   // Otherwise we could not reparse it to exactly the same value, so we must
182   // output the string in hexadecimal format!
183   //
184   // Behave nicely in the face of C TBAA rules... see:
185   // http://www.nullstone.com/htmls/category/aliastyp.htm
186   //
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);
191 }
192
193 std::string ConstantArray::getStrValue() const {
194   std::string Result;
195   
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.
198   // 
199   const Type *ETy = cast<ArrayType>(getType())->getElementType();
200   bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
201
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) {
206         isString = false;
207         break;
208       }
209   }
210
211   if (isString) {
212     Result = "c\"";
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();
217
218       if (isprint(C)) {
219         Result += C;
220       } else {
221         Result += '\\';
222         Result += ( C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A');
223         Result += ((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A');
224       }
225     }
226     Result += "\"";
227
228   } else {
229     Result = "[";
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();
236     }
237     Result += " ]";
238   }
239   
240   return Result;
241 }
242
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();
251   }
252
253   return Result + " }";
254 }
255
256 std::string ConstantPointerNull::getStrValue() const {
257   return "null";
258 }
259
260 std::string ConstantPointerRef::getStrValue() const {
261   const GlobalValue *V = getValue();
262   if (V->hasName()) return "%" + V->getName();
263
264   SlotCalculator *Table = new SlotCalculator(V->getParent(), true);
265   int Slot = Table->getValSlot(V);
266   delete Table;
267
268   if (Slot >= 0) return std::string(" %") + itostr(Slot);
269   else return "<pointer reference badref>";
270 }
271
272
273 //===----------------------------------------------------------------------===//
274 //                           classof implementations
275
276 bool ConstantInt::classof(const Constant *CPV) {
277   return CPV->getType()->isIntegral();
278 }
279 bool ConstantSInt::classof(const Constant *CPV) {
280   return CPV->getType()->isSigned();
281 }
282 bool ConstantUInt::classof(const Constant *CPV) {
283   return CPV->getType()->isUnsigned();
284 }
285 bool ConstantFP::classof(const Constant *CPV) {
286   const Type *Ty = CPV->getType();
287   return Ty == Type::FloatTy || Ty == Type::DoubleTy;
288 }
289 bool ConstantArray::classof(const Constant *CPV) {
290   return isa<ArrayType>(CPV->getType());
291 }
292 bool ConstantStruct::classof(const Constant *CPV) {
293   return isa<StructType>(CPV->getType());
294 }
295 bool ConstantPointer::classof(const Constant *CPV) {
296   return isa<PointerType>(CPV->getType());
297 }
298
299
300 //===----------------------------------------------------------------------===//
301 //                      isValueValidForType implementations
302
303 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
304   switch (Ty->getPrimitiveID()) {
305   default:
306     return false;         // These can't be represented as integers!!!
307
308     // Signed types...
309   case Type::SByteTyID:
310     return (Val <= INT8_MAX && Val >= INT8_MIN);
311   case Type::ShortTyID:
312     return (Val <= INT16_MAX && Val >= INT16_MIN);
313   case Type::IntTyID:
314     return (Val <= INT32_MAX && Val >= INT32_MIN);
315   case Type::LongTyID:
316     return true;          // This is the largest type...
317   }
318   assert(0 && "WTF?");
319   return false;
320 }
321
322 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
323   switch (Ty->getPrimitiveID()) {
324   default:
325     return false;         // These can't be represented as integers!!!
326
327     // Unsigned types...
328   case Type::UByteTyID:
329     return (Val <= UINT8_MAX);
330   case Type::UShortTyID:
331     return (Val <= UINT16_MAX);
332   case Type::UIntTyID:
333     return (Val <= UINT32_MAX);
334   case Type::ULongTyID:
335     return true;          // This is the largest type...
336   }
337   assert(0 && "WTF?");
338   return false;
339 }
340
341 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
342   switch (Ty->getPrimitiveID()) {
343   default:
344     return false;         // These can't be represented as floating point!
345
346     // TODO: Figure out how to test if a double can be cast to a float!
347   case Type::FloatTyID:
348     /*
349     return (Val <= UINT8_MAX);
350     */
351   case Type::DoubleTyID:
352     return true;          // This is the largest type...
353   }
354 };
355
356 //===----------------------------------------------------------------------===//
357 //                      Hash Function Implementations
358 #if 0
359 unsigned ConstantSInt::hash(const Type *Ty, int64_t V) {
360   return unsigned(Ty->getPrimitiveID() ^ V);
361 }
362
363 unsigned ConstantUInt::hash(const Type *Ty, uint64_t V) {
364   return unsigned(Ty->getPrimitiveID() ^ V);
365 }
366
367 unsigned ConstantFP::hash(const Type *Ty, double V) {
368   return Ty->getPrimitiveID() ^ unsigned(V);
369 }
370
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);
376   return Result;
377 }
378
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);
384   return Result;
385 }
386 #endif
387
388 //===----------------------------------------------------------------------===//
389 //                      Factory Function Implementation
390
391 template<class ValType, class ConstantClass>
392 struct ValueMap {
393   typedef pair<const Type*, ValType> ConstHashKey;
394   map<ConstHashKey, ConstantClass *> Map;
395
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;
400   }
401
402   inline void add(const Type *Ty, ValType V, ConstantClass *CP) {
403     Map.insert(make_pair(ConstHashKey(Ty, V), CP));
404   }
405
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) {
410         Map.erase(I);
411         return;
412       }
413   }
414 };
415
416 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
417 //
418 static ValueMap<uint64_t, ConstantInt> IntConstants;
419
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));
424   return Result;
425 }
426
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));
431   return Result;
432 }
433
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);
438 }
439
440 //---- ConstantFP::get() implementation...
441 //
442 static ValueMap<double, ConstantFP> FPConstants;
443
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));
448   return Result;
449 }
450
451 //---- ConstantArray::get() implementation...
452 //
453 static ValueMap<std::vector<Constant*>, ConstantArray> ArrayConstants;
454
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));
460   return Result;
461 }
462
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...
466 //
467 ConstantArray *ConstantArray::get(const std::string &Str) {
468   std::vector<Constant*> ElementVals;
469
470   for (unsigned i = 0; i < Str.length(); ++i)
471     ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
472
473   // Add a null terminator to the string...
474   ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
475
476   ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
477   return ConstantArray::get(ATy, ElementVals);
478 }
479
480
481 // destroyConstant - Remove the constant from the constant table...
482 //
483 void ConstantArray::destroyConstant() {
484   ArrayConstants.remove(this);
485   destroyConstantImpl();
486 }
487
488 //---- ConstantStruct::get() implementation...
489 //
490 static ValueMap<std::vector<Constant*>, ConstantStruct> StructConstants;
491
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));
497   return Result;
498 }
499
500 // destroyConstant - Remove the constant from the constant table...
501 //
502 void ConstantStruct::destroyConstant() {
503   StructConstants.remove(this);
504   destroyConstantImpl();
505 }
506
507 //---- ConstantPointerNull::get() implementation...
508 //
509 static ValueMap<char, ConstantPointerNull> NullPtrConstants;
510
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));
515   return Result;
516 }
517
518 //---- ConstantPointerRef::get() implementation...
519 //
520 ConstantPointerRef *ConstantPointerRef::get(GlobalValue *GV) {
521   assert(GV->getParent() && "Global Value must be attached to a module!");
522
523   // The Module handles the pointer reference sharing...
524   return GV->getParent()->getConstantPointerRef(GV);
525 }
526
527
528 void ConstantPointerRef::mutateReference(GlobalValue *NewGV) {
529   getValue()->getParent()->mutateConstantPointerRef(getValue(), NewGV);
530   Operands[0] = NewGV;
531 }