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