*** empty log message ***
[oota-llvm.git] / lib / VMCore / Constants.cpp
1 //===-- Constants.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/Constants.h"
9 #include "llvm/DerivedTypes.h"
10 #include "llvm/SymbolTable.h"
11 #include "llvm/Module.h"
12 #include "llvm/SlotCalculator.h"
13 #include "Support/StringExtras.h"
14 #include <algorithm>
15
16 using std::map;
17 using std::pair;
18 using std::make_pair;
19
20 ConstantBool *ConstantBool::True  = new ConstantBool(true);
21 ConstantBool *ConstantBool::False = new ConstantBool(false);
22
23
24 //===----------------------------------------------------------------------===//
25 //                              Constant Class
26 //===----------------------------------------------------------------------===//
27
28 // Specialize setName to take care of symbol table majik
29 void Constant::setName(const std::string &Name, SymbolTable *ST) {
30   assert(ST && "Type::setName - Must provide symbol table argument!");
31
32   if (Name.size()) ST->insert(Name, this);
33 }
34
35 // Static constructor to create a '0' constant of arbitrary type...
36 Constant *Constant::getNullValue(const Type *Ty) {
37   switch (Ty->getPrimitiveID()) {
38   case Type::BoolTyID:   return ConstantBool::get(false);
39   case Type::SByteTyID:
40   case Type::ShortTyID:
41   case Type::IntTyID:
42   case Type::LongTyID:   return ConstantSInt::get(Ty, 0);
43
44   case Type::UByteTyID:
45   case Type::UShortTyID:
46   case Type::UIntTyID:
47   case Type::ULongTyID:  return ConstantUInt::get(Ty, 0);
48
49   case Type::FloatTyID:
50   case Type::DoubleTyID: return ConstantFP::get(Ty, 0);
51
52   case Type::PointerTyID: 
53     return ConstantPointerNull::get(cast<PointerType>(Ty));
54   default:
55     return 0;
56   }
57 }
58
59 void Constant::destroyConstantImpl() {
60   // When a Constant is destroyed, there may be lingering
61   // references to the constant by other constants in the constant pool.  These
62   // constants are implicitly dependant on the module that is being deleted,
63   // but they don't know that.  Because we only find out when the CPV is
64   // deleted, we must now notify all of our users (that should only be
65   // Constants) that they are, in fact, invalid now and should be deleted.
66   //
67   while (!use_empty()) {
68     Value *V = use_back();
69 #ifndef NDEBUG      // Only in -g mode...
70     if (!isa<Constant>(V)) {
71       std::cerr << "While deleting: ";
72       dump();
73       std::cerr << "\nUse still stuck around after Def is destroyed: ";
74       V->dump();
75       std::cerr << "\n";
76     }
77 #endif
78     assert(isa<Constant>(V) && "References remain to ConstantPointerRef!");
79     Constant *CPV = cast<Constant>(V);
80     CPV->destroyConstant();
81
82     // The constant should remove itself from our use list...
83     assert((use_empty() || use_back() == V) && "Constant not removed!");
84   }
85
86   // Value has no outstanding references it is safe to delete it now...
87   delete this;
88 }
89
90 //===----------------------------------------------------------------------===//
91 //                            ConstantXXX Classes
92 //===----------------------------------------------------------------------===//
93
94 //===----------------------------------------------------------------------===//
95 //                             Normal Constructors
96
97 ConstantBool::ConstantBool(bool V) : Constant(Type::BoolTy) {
98   Val = V;
99 }
100
101 ConstantInt::ConstantInt(const Type *Ty, uint64_t V) : Constant(Ty) {
102   Val.Unsigned = V;
103 }
104
105 ConstantSInt::ConstantSInt(const Type *Ty, int64_t V) : ConstantInt(Ty, V) {
106   assert(isValueValidForType(Ty, V) && "Value too large for type!");
107 }
108
109 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V) : ConstantInt(Ty, V) {
110   assert(isValueValidForType(Ty, V) && "Value too large for type!");
111 }
112
113 ConstantFP::ConstantFP(const Type *Ty, double V) : Constant(Ty) {
114   assert(isValueValidForType(Ty, V) && "Value too large for type!");
115   Val = V;
116 }
117
118 ConstantArray::ConstantArray(const ArrayType *T,
119                              const std::vector<Constant*> &V) : Constant(T) {
120   for (unsigned i = 0; i < V.size(); i++) {
121     assert(V[i]->getType() == T->getElementType());
122     Operands.push_back(Use(V[i], this));
123   }
124 }
125
126 ConstantStruct::ConstantStruct(const StructType *T,
127                                const std::vector<Constant*> &V) : Constant(T) {
128   const StructType::ElementTypes &ETypes = T->getElementTypes();
129   
130   for (unsigned i = 0; i < V.size(); i++) {
131     assert(V[i]->getType() == ETypes[i]);
132     Operands.push_back(Use(V[i], this));
133   }
134 }
135
136 ConstantPointerRef::ConstantPointerRef(GlobalValue *GV)
137   : ConstantPointer(GV->getType()) {
138   Operands.push_back(Use(GV, this));
139 }
140
141
142
143 //===----------------------------------------------------------------------===//
144 //                           classof implementations
145
146 bool ConstantInt::classof(const Constant *CPV) {
147   return CPV->getType()->isIntegral();
148 }
149 bool ConstantSInt::classof(const Constant *CPV) {
150   return CPV->getType()->isSigned();
151 }
152 bool ConstantUInt::classof(const Constant *CPV) {
153   return CPV->getType()->isUnsigned();
154 }
155 bool ConstantFP::classof(const Constant *CPV) {
156   const Type *Ty = CPV->getType();
157   return Ty == Type::FloatTy || Ty == Type::DoubleTy;
158 }
159 bool ConstantArray::classof(const Constant *CPV) {
160   return isa<ArrayType>(CPV->getType());
161 }
162 bool ConstantStruct::classof(const Constant *CPV) {
163   return isa<StructType>(CPV->getType());
164 }
165 bool ConstantPointer::classof(const Constant *CPV) {
166   return isa<PointerType>(CPV->getType());
167 }
168
169
170 //===----------------------------------------------------------------------===//
171 //                      isValueValidForType implementations
172
173 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
174   switch (Ty->getPrimitiveID()) {
175   default:
176     return false;         // These can't be represented as integers!!!
177
178     // Signed types...
179   case Type::SByteTyID:
180     return (Val <= INT8_MAX && Val >= INT8_MIN);
181   case Type::ShortTyID:
182     return (Val <= INT16_MAX && Val >= INT16_MIN);
183   case Type::IntTyID:
184     return (Val <= INT32_MAX && Val >= INT32_MIN);
185   case Type::LongTyID:
186     return true;          // This is the largest type...
187   }
188   assert(0 && "WTF?");
189   return false;
190 }
191
192 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
193   switch (Ty->getPrimitiveID()) {
194   default:
195     return false;         // These can't be represented as integers!!!
196
197     // Unsigned types...
198   case Type::UByteTyID:
199     return (Val <= UINT8_MAX);
200   case Type::UShortTyID:
201     return (Val <= UINT16_MAX);
202   case Type::UIntTyID:
203     return (Val <= UINT32_MAX);
204   case Type::ULongTyID:
205     return true;          // This is the largest type...
206   }
207   assert(0 && "WTF?");
208   return false;
209 }
210
211 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
212   switch (Ty->getPrimitiveID()) {
213   default:
214     return false;         // These can't be represented as floating point!
215
216     // TODO: Figure out how to test if a double can be cast to a float!
217   case Type::FloatTyID:
218     /*
219     return (Val <= UINT8_MAX);
220     */
221   case Type::DoubleTyID:
222     return true;          // This is the largest type...
223   }
224 };
225
226 //===----------------------------------------------------------------------===//
227 //                      Factory Function Implementation
228
229 template<class ValType, class ConstantClass>
230 struct ValueMap {
231   typedef pair<const Type*, ValType> ConstHashKey;
232   map<ConstHashKey, ConstantClass *> Map;
233
234   inline ConstantClass *get(const Type *Ty, ValType V) {
235     map<ConstHashKey,ConstantClass *>::iterator I =
236       Map.find(ConstHashKey(Ty, V));
237     return (I != Map.end()) ? I->second : 0;
238   }
239
240   inline void add(const Type *Ty, ValType V, ConstantClass *CP) {
241     Map.insert(make_pair(ConstHashKey(Ty, V), CP));
242   }
243
244   inline void remove(ConstantClass *CP) {
245     for (map<ConstHashKey,ConstantClass *>::iterator I = Map.begin(),
246                                                       E = Map.end(); I != E;++I)
247       if (I->second == CP) {
248         Map.erase(I);
249         return;
250       }
251   }
252 };
253
254 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
255 //
256 static ValueMap<uint64_t, ConstantInt> IntConstants;
257
258 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
259   ConstantSInt *Result = (ConstantSInt*)IntConstants.get(Ty, (uint64_t)V);
260   if (!Result)   // If no preexisting value, create one now...
261     IntConstants.add(Ty, V, Result = new ConstantSInt(Ty, V));
262   return Result;
263 }
264
265 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
266   ConstantUInt *Result = (ConstantUInt*)IntConstants.get(Ty, V);
267   if (!Result)   // If no preexisting value, create one now...
268     IntConstants.add(Ty, V, Result = new ConstantUInt(Ty, V));
269   return Result;
270 }
271
272 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
273   assert(V <= 127 && "Can only be used with very small positive constants!");
274   if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
275   return ConstantUInt::get(Ty, V);
276 }
277
278 //---- ConstantFP::get() implementation...
279 //
280 static ValueMap<double, ConstantFP> FPConstants;
281
282 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
283   ConstantFP *Result = FPConstants.get(Ty, V);
284   if (!Result)   // If no preexisting value, create one now...
285     FPConstants.add(Ty, V, Result = new ConstantFP(Ty, V));
286   return Result;
287 }
288
289 //---- ConstantArray::get() implementation...
290 //
291 static ValueMap<std::vector<Constant*>, ConstantArray> ArrayConstants;
292
293 ConstantArray *ConstantArray::get(const ArrayType *Ty,
294                                   const std::vector<Constant*> &V) {
295   ConstantArray *Result = ArrayConstants.get(Ty, V);
296   if (!Result)   // If no preexisting value, create one now...
297     ArrayConstants.add(Ty, V, Result = new ConstantArray(Ty, V));
298   return Result;
299 }
300
301 // ConstantArray::get(const string&) - Return an array that is initialized to
302 // contain the specified string.  A null terminator is added to the specified
303 // string so that it may be used in a natural way...
304 //
305 ConstantArray *ConstantArray::get(const std::string &Str) {
306   std::vector<Constant*> ElementVals;
307
308   for (unsigned i = 0; i < Str.length(); ++i)
309     ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
310
311   // Add a null terminator to the string...
312   ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
313
314   ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
315   return ConstantArray::get(ATy, ElementVals);
316 }
317
318
319 // destroyConstant - Remove the constant from the constant table...
320 //
321 void ConstantArray::destroyConstant() {
322   ArrayConstants.remove(this);
323   destroyConstantImpl();
324 }
325
326 //---- ConstantStruct::get() implementation...
327 //
328 static ValueMap<std::vector<Constant*>, ConstantStruct> StructConstants;
329
330 ConstantStruct *ConstantStruct::get(const StructType *Ty,
331                                     const std::vector<Constant*> &V) {
332   ConstantStruct *Result = StructConstants.get(Ty, V);
333   if (!Result)   // If no preexisting value, create one now...
334     StructConstants.add(Ty, V, Result = new ConstantStruct(Ty, V));
335   return Result;
336 }
337
338 // destroyConstant - Remove the constant from the constant table...
339 //
340 void ConstantStruct::destroyConstant() {
341   StructConstants.remove(this);
342   destroyConstantImpl();
343 }
344
345 //---- ConstantPointerNull::get() implementation...
346 //
347 static ValueMap<char, ConstantPointerNull> NullPtrConstants;
348
349 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
350   ConstantPointerNull *Result = NullPtrConstants.get(Ty, 0);
351   if (!Result)   // If no preexisting value, create one now...
352     NullPtrConstants.add(Ty, 0, Result = new ConstantPointerNull(Ty));
353   return Result;
354 }
355
356 //---- ConstantPointerRef::get() implementation...
357 //
358 ConstantPointerRef *ConstantPointerRef::get(GlobalValue *GV) {
359   assert(GV->getParent() && "Global Value must be attached to a module!");
360
361   // The Module handles the pointer reference sharing...
362   return GV->getParent()->getConstantPointerRef(GV);
363 }
364
365
366 void ConstantPointerRef::mutateReference(GlobalValue *NewGV) {
367   getValue()->getParent()->mutateConstantPointerRef(getValue(), NewGV);
368   Operands[0] = NewGV;
369 }