added std:: to cerr and endl
[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/iMemory.h"
11 #include "llvm/SymbolTable.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 using std::vector;
21 using std::cerr;
22 using std::endl;
23
24 ConstantBool *ConstantBool::True  = new ConstantBool(true);
25 ConstantBool *ConstantBool::False = new ConstantBool(false);
26
27
28 //===----------------------------------------------------------------------===//
29 //                              Constant Class
30 //===----------------------------------------------------------------------===//
31
32 // Specialize setName to take care of symbol table majik
33 void Constant::setName(const std::string &Name, SymbolTable *ST) {
34   assert(ST && "Type::setName - Must provide symbol table argument!");
35
36   if (Name.size()) ST->insert(Name, this);
37 }
38
39 // Static constructor to create a '0' constant of arbitrary type...
40 Constant *Constant::getNullValue(const Type *Ty) {
41   switch (Ty->getPrimitiveID()) {
42   case Type::BoolTyID:   return ConstantBool::get(false);
43   case Type::SByteTyID:
44   case Type::ShortTyID:
45   case Type::IntTyID:
46   case Type::LongTyID:   return ConstantSInt::get(Ty, 0);
47
48   case Type::UByteTyID:
49   case Type::UShortTyID:
50   case Type::UIntTyID:
51   case Type::ULongTyID:  return ConstantUInt::get(Ty, 0);
52
53   case Type::FloatTyID:
54   case Type::DoubleTyID: return ConstantFP::get(Ty, 0);
55
56   case Type::PointerTyID: 
57     return ConstantPointerNull::get(cast<PointerType>(Ty));
58   default:
59     return 0;
60   }
61 }
62
63 void Constant::destroyConstantImpl() {
64   // When a Constant is destroyed, there may be lingering
65   // references to the constant by other constants in the constant pool.  These
66   // constants are implicitly dependant on the module that is being deleted,
67   // but they don't know that.  Because we only find out when the CPV is
68   // deleted, we must now notify all of our users (that should only be
69   // Constants) that they are, in fact, invalid now and should be deleted.
70   //
71   while (!use_empty()) {
72     Value *V = use_back();
73 #ifndef NDEBUG      // Only in -g mode...
74     if (!isa<Constant>(V)) {
75       std::cerr << "While deleting: ";
76       dump();
77       std::cerr << "\nUse still stuck around after Def is destroyed: ";
78       V->dump();
79       std::cerr << "\n";
80     }
81 #endif
82     assert(isa<Constant>(V) && "References remain to Constant being destroyed");
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   assert(V.size() == ETypes.size() &&
134          "Invalid initializer vector for constant structure");
135   for (unsigned i = 0; i < V.size(); i++) {
136     assert(V[i]->getType() == ETypes[i]);
137     Operands.push_back(Use(V[i], this));
138   }
139 }
140
141 ConstantPointerRef::ConstantPointerRef(GlobalValue *GV)
142   : ConstantPointer(GV->getType()) {
143   Operands.push_back(Use(GV, this));
144 }
145
146 ConstantExpr::ConstantExpr(unsigned opCode, Constant *C,  const Type *Ty)
147   : Constant(Ty), iType(opCode) {
148   Operands.push_back(Use(C, this));
149 }
150
151 ConstantExpr::ConstantExpr(unsigned opCode, Constant* C1,
152                            Constant* C2, const Type *Ty)
153   : Constant(Ty), iType(opCode) {
154   Operands.push_back(Use(C1, this));
155   Operands.push_back(Use(C2, this));
156 }
157
158 ConstantExpr::ConstantExpr(unsigned opCode, Constant* C,
159                           const std::vector<Value*>& IdxList, const Type *Ty)
160   : Constant(Ty), iType(opCode) {
161   Operands.reserve(1+IdxList.size());
162   Operands.push_back(Use(C, this));
163   for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
164     Operands.push_back(Use(IdxList[i], this));
165 }
166
167
168
169 //===----------------------------------------------------------------------===//
170 //                           classof implementations
171
172 bool ConstantInt::classof(const Constant *CPV) {
173   return CPV->getType()->isIntegral() && ! isa<ConstantExpr>(CPV);
174 }
175 bool ConstantSInt::classof(const Constant *CPV) {
176   return CPV->getType()->isSigned() && ! isa<ConstantExpr>(CPV);
177 }
178 bool ConstantUInt::classof(const Constant *CPV) {
179   return CPV->getType()->isUnsigned() && ! isa<ConstantExpr>(CPV);
180 }
181 bool ConstantFP::classof(const Constant *CPV) {
182   const Type *Ty = CPV->getType();
183   return ((Ty == Type::FloatTy || Ty == Type::DoubleTy) &&
184           ! isa<ConstantExpr>(CPV));
185 }
186 bool ConstantArray::classof(const Constant *CPV) {
187   return isa<ArrayType>(CPV->getType()) && ! isa<ConstantExpr>(CPV);
188 }
189 bool ConstantStruct::classof(const Constant *CPV) {
190   return isa<StructType>(CPV->getType()) && ! isa<ConstantExpr>(CPV);
191 }
192 bool ConstantPointer::classof(const Constant *CPV) {
193   return (isa<PointerType>(CPV->getType()) && ! isa<ConstantExpr>(CPV));
194 }
195
196
197
198 //===----------------------------------------------------------------------===//
199 //                      isValueValidForType implementations
200
201 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
202   switch (Ty->getPrimitiveID()) {
203   default:
204     return false;         // These can't be represented as integers!!!
205
206     // Signed types...
207   case Type::SByteTyID:
208     return (Val <= INT8_MAX && Val >= INT8_MIN);
209   case Type::ShortTyID:
210     return (Val <= INT16_MAX && Val >= INT16_MIN);
211   case Type::IntTyID:
212     return (Val <= INT32_MAX && Val >= INT32_MIN);
213   case Type::LongTyID:
214     return true;          // This is the largest type...
215   }
216   assert(0 && "WTF?");
217   return false;
218 }
219
220 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
221   switch (Ty->getPrimitiveID()) {
222   default:
223     return false;         // These can't be represented as integers!!!
224
225     // Unsigned types...
226   case Type::UByteTyID:
227     return (Val <= UINT8_MAX);
228   case Type::UShortTyID:
229     return (Val <= UINT16_MAX);
230   case Type::UIntTyID:
231     return (Val <= UINT32_MAX);
232   case Type::ULongTyID:
233     return true;          // This is the largest type...
234   }
235   assert(0 && "WTF?");
236   return false;
237 }
238
239 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
240   switch (Ty->getPrimitiveID()) {
241   default:
242     return false;         // These can't be represented as floating point!
243
244     // TODO: Figure out how to test if a double can be cast to a float!
245   case Type::FloatTyID:
246     /*
247     return (Val <= UINT8_MAX);
248     */
249   case Type::DoubleTyID:
250     return true;          // This is the largest type...
251   }
252 };
253
254 //===----------------------------------------------------------------------===//
255 //                      Factory Function Implementation
256
257 template<class ValType, class ConstantClass>
258 struct ValueMap {
259   typedef pair<const Type*, ValType> ConstHashKey;
260   map<ConstHashKey, ConstantClass *> Map;
261
262   inline ConstantClass *get(const Type *Ty, ValType V) {
263     map<ConstHashKey,ConstantClass *>::iterator I =
264       Map.find(ConstHashKey(Ty, V));
265     return (I != Map.end()) ? I->second : 0;
266   }
267
268   inline void add(const Type *Ty, ValType V, ConstantClass *CP) {
269     Map.insert(make_pair(ConstHashKey(Ty, V), CP));
270   }
271
272   inline void remove(ConstantClass *CP) {
273     for (map<ConstHashKey,ConstantClass *>::iterator I = Map.begin(),
274                                                       E = Map.end(); I != E;++I)
275       if (I->second == CP) {
276         Map.erase(I);
277         return;
278       }
279   }
280 };
281
282 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
283 //
284 static ValueMap<uint64_t, ConstantInt> IntConstants;
285
286 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
287   ConstantSInt *Result = (ConstantSInt*)IntConstants.get(Ty, (uint64_t)V);
288   if (!Result)   // If no preexisting value, create one now...
289     IntConstants.add(Ty, V, Result = new ConstantSInt(Ty, V));
290   return Result;
291 }
292
293 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
294   ConstantUInt *Result = (ConstantUInt*)IntConstants.get(Ty, V);
295   if (!Result)   // If no preexisting value, create one now...
296     IntConstants.add(Ty, V, Result = new ConstantUInt(Ty, V));
297   return Result;
298 }
299
300 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
301   assert(V <= 127 && "Can only be used with very small positive constants!");
302   if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
303   return ConstantUInt::get(Ty, V);
304 }
305
306 //---- ConstantFP::get() implementation...
307 //
308 static ValueMap<double, ConstantFP> FPConstants;
309
310 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
311   ConstantFP *Result = FPConstants.get(Ty, V);
312   if (!Result)   // If no preexisting value, create one now...
313     FPConstants.add(Ty, V, Result = new ConstantFP(Ty, V));
314   return Result;
315 }
316
317 //---- ConstantArray::get() implementation...
318 //
319 static ValueMap<std::vector<Constant*>, ConstantArray> ArrayConstants;
320
321 ConstantArray *ConstantArray::get(const ArrayType *Ty,
322                                   const std::vector<Constant*> &V) {
323   ConstantArray *Result = ArrayConstants.get(Ty, V);
324   if (!Result)   // If no preexisting value, create one now...
325     ArrayConstants.add(Ty, V, Result = new ConstantArray(Ty, V));
326   return Result;
327 }
328
329 // ConstantArray::get(const string&) - Return an array that is initialized to
330 // contain the specified string.  A null terminator is added to the specified
331 // string so that it may be used in a natural way...
332 //
333 ConstantArray *ConstantArray::get(const std::string &Str) {
334   std::vector<Constant*> ElementVals;
335
336   for (unsigned i = 0; i < Str.length(); ++i)
337     ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
338
339   // Add a null terminator to the string...
340   ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
341
342   ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
343   return ConstantArray::get(ATy, ElementVals);
344 }
345
346
347 // destroyConstant - Remove the constant from the constant table...
348 //
349 void ConstantArray::destroyConstant() {
350   ArrayConstants.remove(this);
351   destroyConstantImpl();
352 }
353
354 //---- ConstantStruct::get() implementation...
355 //
356 static ValueMap<std::vector<Constant*>, ConstantStruct> StructConstants;
357
358 ConstantStruct *ConstantStruct::get(const StructType *Ty,
359                                     const std::vector<Constant*> &V) {
360   ConstantStruct *Result = StructConstants.get(Ty, V);
361   if (!Result)   // If no preexisting value, create one now...
362     StructConstants.add(Ty, V, Result = new ConstantStruct(Ty, V));
363   return Result;
364 }
365
366 // destroyConstant - Remove the constant from the constant table...
367 //
368 void ConstantStruct::destroyConstant() {
369   StructConstants.remove(this);
370   destroyConstantImpl();
371 }
372
373 //---- ConstantPointerNull::get() implementation...
374 //
375 static ValueMap<char, ConstantPointerNull> NullPtrConstants;
376
377 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
378   ConstantPointerNull *Result = NullPtrConstants.get(Ty, 0);
379   if (!Result)   // If no preexisting value, create one now...
380     NullPtrConstants.add(Ty, 0, Result = new ConstantPointerNull(Ty));
381   return Result;
382 }
383
384 //---- ConstantPointerRef::get() implementation...
385 //
386 ConstantPointerRef *ConstantPointerRef::get(GlobalValue *GV) {
387   assert(GV->getParent() && "Global Value must be attached to a module!");
388   
389   // The Module handles the pointer reference sharing...
390   return GV->getParent()->getConstantPointerRef(GV);
391 }
392
393 //---- ConstantExpr::get() implementations...
394 // Return NULL on invalid expressions.
395 //
396 typedef pair<unsigned, vector<Constant*> > ExprMapKeyType;
397 static ValueMap<const ExprMapKeyType, ConstantExpr> ExprConstants;
398
399 ConstantExpr*
400 ConstantExpr::get(unsigned opCode, Constant *C, const Type *Ty) {
401
402   // Look up the constant in the table first to ensure uniqueness
403   vector<Constant*> argVec(1, C);
404   const ExprMapKeyType& key = make_pair(opCode, argVec);
405   ConstantExpr* result = ExprConstants.get(Ty, key);
406   if (result)
407     return result;
408   
409   // Its not in the table so create a new one and put it in the table.
410   // Check the operands for consistency first
411   if (opCode != Instruction::Cast &&
412       (opCode < Instruction::FirstUnaryOp ||
413        opCode >= Instruction::NumUnaryOps)) {
414     std::cerr << "Invalid opcode " << ConstantExpr::getOpcodeName(opCode)
415          << " in unary constant expression" << std::endl;
416     return NULL;       // Not Cast or other unary opcode
417   }
418   // type of operand will not match result for Cast operation
419   if (opCode != Instruction::Cast && Ty != C->getType()) {
420     cerr << "Type of operand in unary constant expression should match result" << endl;
421     return NULL;
422   }
423   
424   result = new ConstantExpr(opCode, C, Ty);
425   ExprConstants.add(Ty, key, result);
426   return result;
427 }
428
429 ConstantExpr*
430 ConstantExpr::get(unsigned opCode, Constant *C1, Constant *C2,const Type *Ty) {
431
432   // Look up the constant in the table first to ensure uniqueness
433   vector<Constant*> argVec(1, C1); argVec.push_back(C2);
434   const ExprMapKeyType& key = make_pair(opCode, argVec);
435   ConstantExpr* result = ExprConstants.get(Ty, key);
436   if (result)
437     return result;
438   
439   // Its not in the table so create a new one and put it in the table.
440   // Check the operands for consistency first
441   if (opCode < Instruction::FirstBinaryOp ||
442       opCode >= Instruction::NumBinaryOps) {
443     cerr << "Invalid opcode " << ConstantExpr::getOpcodeName(opCode)
444          << " in binary constant expression" << endl;
445     return NULL;
446   }
447   if (Ty != C1->getType() || Ty != C2->getType()) {
448     cerr << "Types of both operands in binary constant expression should match result" << endl;
449     return NULL;
450   }
451   
452   result = new ConstantExpr(opCode, C1, C2, Ty);
453   ExprConstants.add(Ty, key, result);
454   return result;
455 }
456
457 ConstantExpr*
458 ConstantExpr::get(unsigned opCode, Constant*C,
459                   const std::vector<Value*>& idxList, const Type *Ty) {
460
461   // Look up the constant in the table first to ensure uniqueness
462   vector<Constant*> argVec(1, C);
463   for(vector<Value*>::const_iterator VI=idxList.begin(), VE=idxList.end();
464       VI != VE; ++VI)
465     if (Constant *C = dyn_cast<Constant>(*VI))
466         argVec.push_back(C);
467     else {
468       cerr << "Non-constant index in constant GetElementPtr expr";
469       return NULL;
470     }
471   
472   const ExprMapKeyType& key = make_pair(opCode, argVec);
473   ConstantExpr* result = ExprConstants.get(Ty, key);
474   if (result)
475     return result;
476   
477   // Its not in the table so create a new one and put it in the table.
478   // Check the operands for consistency first
479   // Must be a getElementPtr.  Check for valid getElementPtr expression.
480   // 
481   if (opCode != Instruction::GetElementPtr) {
482     cerr << "operator other than GetElementPtr used with an index list" << endl;
483     return NULL;
484   }
485   if (!isa<ConstantPointer>(C)) {
486     cerr << "Constant GelElementPtr expression using something other than a constant pointer" << endl;
487     return NULL;
488   }
489   if (!isa<PointerType>(Ty)) {
490     cerr << "Non-pointer type for constant GelElementPtr expression" << endl;
491     return NULL;
492   }
493   const Type* fldType = GetElementPtrInst::getIndexedType(C->getType(),
494                                                           idxList, true);
495   if (!fldType) {
496     cerr << "Invalid index list for constant GelElementPtr expression" << endl;
497     return NULL;
498   }
499   if (cast<PointerType>(Ty)->getElementType() != fldType) {
500     cerr << "Type for constant GelElementPtr expression does not match field type" << endl;
501     return NULL;
502   }
503   
504   result = new ConstantExpr(opCode, C, idxList, Ty);
505   ExprConstants.add(Ty, key, result);
506   return result;
507 }
508
509 // destroyConstant - Remove the constant from the constant table...
510 //
511 void ConstantExpr::destroyConstant() {
512   ExprConstants.remove(this);
513   destroyConstantImpl();
514 }
515
516 const char*
517 ConstantExpr::getOpcodeName(unsigned opCode) {
518   return Instruction::getOpcodeName(opCode);
519 }
520
521
522 //---- ConstantPointerRef::mutateReferences() implementation...
523 //
524 unsigned
525 ConstantPointerRef::mutateReferences(Value* OldV, Value *NewV) {
526   assert(getValue() == OldV && "Cannot mutate old value if I'm not using it!");
527   GlobalValue* NewGV = cast<GlobalValue>(NewV);
528   getValue()->getParent()->mutateConstantPointerRef(getValue(), NewGV);
529   Operands[0] = NewGV;
530   return 1;
531 }
532
533
534 //---- ConstantPointerExpr::mutateReferences() implementation...
535 //
536 unsigned
537 ConstantExpr::mutateReferences(Value* OldV, Value *NewV) {
538   unsigned numReplaced = 0;
539   Constant* NewC = cast<Constant>(NewV);
540   for (unsigned i=0, N = getNumOperands(); i < N; ++i)
541     if (Operands[i] == OldV) {
542       ++numReplaced;
543       Operands[i] = NewC;
544     }
545   return numReplaced;
546 }