Another portability fix provided via Casey Carter:
[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
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 void Constant::destroyConstantImpl() {
38   // When a Constant is destroyed, there may be lingering
39   // references to the constant by other constants in the constant pool.  These
40   // constants are implicitly dependant on the module that is being deleted,
41   // but they don't know that.  Because we only find out when the CPV is
42   // deleted, we must now notify all of our users (that should only be
43   // Constants) that they are, in fact, invalid now and should be deleted.
44   //
45   while (!use_empty()) {
46     Value *V = use_back();
47 #ifndef NDEBUG      // Only in -g mode...
48     if (!isa<Constant>(V))
49       std::cerr << "While deleting: " << *this
50                 << "\n\nUse still stuck around after Def is destroyed: "
51                 << *V << "\n\n";
52 #endif
53     assert(isa<Constant>(V) && "References remain to Constant being destroyed");
54     Constant *CPV = cast<Constant>(V);
55     CPV->destroyConstant();
56
57     // The constant should remove itself from our use list...
58     assert((use_empty() || use_back() != V) && "Constant not removed!");
59   }
60
61   // Value has no outstanding references it is safe to delete it now...
62   delete this;
63 }
64
65 // Static constructor to create a '0' constant of arbitrary type...
66 Constant *Constant::getNullValue(const Type *Ty) {
67   switch (Ty->getPrimitiveID()) {
68   case Type::BoolTyID:   return ConstantBool::get(false);
69   case Type::SByteTyID:
70   case Type::ShortTyID:
71   case Type::IntTyID:
72   case Type::LongTyID:   return ConstantSInt::get(Ty, 0);
73
74   case Type::UByteTyID:
75   case Type::UShortTyID:
76   case Type::UIntTyID:
77   case Type::ULongTyID:  return ConstantUInt::get(Ty, 0);
78
79   case Type::FloatTyID:
80   case Type::DoubleTyID: return ConstantFP::get(Ty, 0);
81
82   case Type::PointerTyID: 
83     return ConstantPointerNull::get(cast<PointerType>(Ty));
84   default:
85     return 0;
86   }
87 }
88
89 // Static constructor to create the maximum constant of an integral type...
90 ConstantIntegral *ConstantIntegral::getMaxValue(const Type *Ty) {
91   switch (Ty->getPrimitiveID()) {
92   case Type::BoolTyID:   return ConstantBool::True;
93   case Type::SByteTyID:
94   case Type::ShortTyID:
95   case Type::IntTyID:
96   case Type::LongTyID: {
97     // Calculate 011111111111111... 
98     unsigned TypeBits = Ty->getPrimitiveSize()*8;
99     int64_t Val = INT64_MAX;             // All ones
100     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
101     return ConstantSInt::get(Ty, Val);
102   }
103
104   case Type::UByteTyID:
105   case Type::UShortTyID:
106   case Type::UIntTyID:
107   case Type::ULongTyID:  return getAllOnesValue(Ty);
108
109   default: return 0;
110   }
111 }
112
113 // Static constructor to create the minimum constant for an integral type...
114 ConstantIntegral *ConstantIntegral::getMinValue(const Type *Ty) {
115   switch (Ty->getPrimitiveID()) {
116   case Type::BoolTyID:   return ConstantBool::False;
117   case Type::SByteTyID:
118   case Type::ShortTyID:
119   case Type::IntTyID:
120   case Type::LongTyID: {
121      // Calculate 1111111111000000000000 
122      unsigned TypeBits = Ty->getPrimitiveSize()*8;
123      int64_t Val = -1;                    // All ones
124      Val <<= TypeBits-1;                  // Shift over to the right spot
125      return ConstantSInt::get(Ty, Val);
126   }
127
128   case Type::UByteTyID:
129   case Type::UShortTyID:
130   case Type::UIntTyID:
131   case Type::ULongTyID:  return ConstantUInt::get(Ty, 0);
132
133   default: return 0;
134   }
135 }
136
137 // Static constructor to create an integral constant with all bits set
138 ConstantIntegral *ConstantIntegral::getAllOnesValue(const Type *Ty) {
139   switch (Ty->getPrimitiveID()) {
140   case Type::BoolTyID:   return ConstantBool::True;
141   case Type::SByteTyID:
142   case Type::ShortTyID:
143   case Type::IntTyID:
144   case Type::LongTyID:   return ConstantSInt::get(Ty, -1);
145
146   case Type::UByteTyID:
147   case Type::UShortTyID:
148   case Type::UIntTyID:
149   case Type::ULongTyID: {
150     // Calculate ~0 of the right type...
151     unsigned TypeBits = Ty->getPrimitiveSize()*8;
152     uint64_t Val = ~0ULL;                // All ones
153     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
154     return ConstantUInt::get(Ty, Val);
155   }
156   default: return 0;
157   }
158 }
159
160
161 //===----------------------------------------------------------------------===//
162 //                            ConstantXXX Classes
163 //===----------------------------------------------------------------------===//
164
165 //===----------------------------------------------------------------------===//
166 //                             Normal Constructors
167
168 ConstantBool::ConstantBool(bool V) : ConstantIntegral(Type::BoolTy) {
169   Val = V;
170 }
171
172 ConstantInt::ConstantInt(const Type *Ty, uint64_t V) : ConstantIntegral(Ty) {
173   Val.Unsigned = V;
174 }
175
176 ConstantSInt::ConstantSInt(const Type *Ty, int64_t V) : ConstantInt(Ty, V) {
177   assert(Ty->isInteger() && Ty->isSigned() &&
178          "Illegal type for unsigned integer constant!");
179   assert(isValueValidForType(Ty, V) && "Value too large for type!");
180 }
181
182 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V) : ConstantInt(Ty, V) {
183   assert(Ty->isInteger() && Ty->isUnsigned() &&
184          "Illegal type for unsigned integer constant!");
185   assert(isValueValidForType(Ty, V) && "Value too large for type!");
186 }
187
188 ConstantFP::ConstantFP(const Type *Ty, double V) : Constant(Ty) {
189   assert(isValueValidForType(Ty, V) && "Value too large for type!");
190   Val = V;
191 }
192
193 ConstantArray::ConstantArray(const ArrayType *T,
194                              const std::vector<Constant*> &V) : Constant(T) {
195   for (unsigned i = 0; i < V.size(); i++) {
196     assert(V[i]->getType() == T->getElementType());
197     Operands.push_back(Use(V[i], this));
198   }
199 }
200
201 ConstantStruct::ConstantStruct(const StructType *T,
202                                const std::vector<Constant*> &V) : Constant(T) {
203   const StructType::ElementTypes &ETypes = T->getElementTypes();
204   assert(V.size() == ETypes.size() &&
205          "Invalid initializer vector for constant structure");
206   for (unsigned i = 0; i < V.size(); i++) {
207     assert(V[i]->getType() == ETypes[i]);
208     Operands.push_back(Use(V[i], this));
209   }
210 }
211
212 ConstantPointerRef::ConstantPointerRef(GlobalValue *GV)
213   : ConstantPointer(GV->getType()) {
214   Operands.push_back(Use(GV, this));
215 }
216
217 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
218   : Constant(Ty), iType(Opcode) {
219   Operands.push_back(Use(C, this));
220 }
221
222 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
223   : Constant(C1->getType()), iType(Opcode) {
224   Operands.push_back(Use(C1, this));
225   Operands.push_back(Use(C2, this));
226 }
227
228 ConstantExpr::ConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
229                            const Type *DestTy)
230   : Constant(DestTy), iType(Instruction::GetElementPtr) {
231   Operands.reserve(1+IdxList.size());
232   Operands.push_back(Use(C, this));
233   for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
234     Operands.push_back(Use(IdxList[i], this));
235 }
236
237
238
239 //===----------------------------------------------------------------------===//
240 //                           classof implementations
241
242 bool ConstantIntegral::classof(const Constant *CPV) {
243   return CPV->getType()->isIntegral() && !isa<ConstantExpr>(CPV);
244 }
245
246 bool ConstantInt::classof(const Constant *CPV) {
247   return CPV->getType()->isInteger() && !isa<ConstantExpr>(CPV);
248 }
249 bool ConstantSInt::classof(const Constant *CPV) {
250   return CPV->getType()->isSigned() && !isa<ConstantExpr>(CPV);
251 }
252 bool ConstantUInt::classof(const Constant *CPV) {
253   return CPV->getType()->isUnsigned() && !isa<ConstantExpr>(CPV);
254 }
255 bool ConstantFP::classof(const Constant *CPV) {
256   const Type *Ty = CPV->getType();
257   return ((Ty == Type::FloatTy || Ty == Type::DoubleTy) &&
258           !isa<ConstantExpr>(CPV));
259 }
260 bool ConstantArray::classof(const Constant *CPV) {
261   return isa<ArrayType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
262 }
263 bool ConstantStruct::classof(const Constant *CPV) {
264   return isa<StructType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
265 }
266 bool ConstantPointer::classof(const Constant *CPV) {
267   return (isa<PointerType>(CPV->getType()) && !isa<ConstantExpr>(CPV));
268 }
269
270
271
272 //===----------------------------------------------------------------------===//
273 //                      isValueValidForType implementations
274
275 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
276   switch (Ty->getPrimitiveID()) {
277   default:
278     return false;         // These can't be represented as integers!!!
279
280     // Signed types...
281   case Type::SByteTyID:
282     return (Val <= INT8_MAX && Val >= INT8_MIN);
283   case Type::ShortTyID:
284     return (Val <= INT16_MAX && Val >= INT16_MIN);
285   case Type::IntTyID:
286     return (Val <= INT32_MAX && Val >= INT32_MIN);
287   case Type::LongTyID:
288     return true;          // This is the largest type...
289   }
290   assert(0 && "WTF?");
291   return false;
292 }
293
294 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
295   switch (Ty->getPrimitiveID()) {
296   default:
297     return false;         // These can't be represented as integers!!!
298
299     // Unsigned types...
300   case Type::UByteTyID:
301     return (Val <= UINT8_MAX);
302   case Type::UShortTyID:
303     return (Val <= UINT16_MAX);
304   case Type::UIntTyID:
305     return (Val <= UINT32_MAX);
306   case Type::ULongTyID:
307     return true;          // This is the largest type...
308   }
309   assert(0 && "WTF?");
310   return false;
311 }
312
313 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
314   switch (Ty->getPrimitiveID()) {
315   default:
316     return false;         // These can't be represented as floating point!
317
318     // TODO: Figure out how to test if a double can be cast to a float!
319   case Type::FloatTyID:
320     /*
321     return (Val <= UINT8_MAX);
322     */
323   case Type::DoubleTyID:
324     return true;          // This is the largest type...
325   }
326 };
327
328 //===----------------------------------------------------------------------===//
329 //                      Factory Function Implementation
330
331 template<class ValType, class ConstantClass>
332 struct ValueMap {
333   typedef pair<const Type*, ValType> ConstHashKey;
334   map<ConstHashKey, ConstantClass *> Map;
335
336   inline ConstantClass *get(const Type *Ty, ValType V) {
337     typename map<ConstHashKey,ConstantClass *>::iterator I =
338       Map.find(ConstHashKey(Ty, V));
339     return (I != Map.end()) ? I->second : 0;
340   }
341
342   inline void add(const Type *Ty, ValType V, ConstantClass *CP) {
343     Map.insert(make_pair(ConstHashKey(Ty, V), CP));
344   }
345
346   inline void remove(ConstantClass *CP) {
347     for (typename map<ConstHashKey,ConstantClass *>::iterator I = Map.begin(),
348                                                       E = Map.end(); I != E;++I)
349       if (I->second == CP) {
350         Map.erase(I);
351         return;
352       }
353   }
354 };
355
356 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
357 //
358 static ValueMap<uint64_t, ConstantInt> IntConstants;
359
360 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
361   ConstantSInt *Result = (ConstantSInt*)IntConstants.get(Ty, (uint64_t)V);
362   if (!Result)   // If no preexisting value, create one now...
363     IntConstants.add(Ty, V, Result = new ConstantSInt(Ty, V));
364   return Result;
365 }
366
367 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
368   ConstantUInt *Result = (ConstantUInt*)IntConstants.get(Ty, V);
369   if (!Result)   // If no preexisting value, create one now...
370     IntConstants.add(Ty, V, Result = new ConstantUInt(Ty, V));
371   return Result;
372 }
373
374 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
375   assert(V <= 127 && "Can only be used with very small positive constants!");
376   if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
377   return ConstantUInt::get(Ty, V);
378 }
379
380 //---- ConstantFP::get() implementation...
381 //
382 static ValueMap<double, ConstantFP> FPConstants;
383
384 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
385   ConstantFP *Result = FPConstants.get(Ty, V);
386   if (!Result)   // If no preexisting value, create one now...
387     FPConstants.add(Ty, V, Result = new ConstantFP(Ty, V));
388   return Result;
389 }
390
391 //---- ConstantArray::get() implementation...
392 //
393 static ValueMap<std::vector<Constant*>, ConstantArray> ArrayConstants;
394
395 ConstantArray *ConstantArray::get(const ArrayType *Ty,
396                                   const std::vector<Constant*> &V) {
397   ConstantArray *Result = ArrayConstants.get(Ty, V);
398   if (!Result)   // If no preexisting value, create one now...
399     ArrayConstants.add(Ty, V, Result = new ConstantArray(Ty, V));
400   return Result;
401 }
402
403 // ConstantArray::get(const string&) - Return an array that is initialized to
404 // contain the specified string.  A null terminator is added to the specified
405 // string so that it may be used in a natural way...
406 //
407 ConstantArray *ConstantArray::get(const std::string &Str) {
408   std::vector<Constant*> ElementVals;
409
410   for (unsigned i = 0; i < Str.length(); ++i)
411     ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
412
413   // Add a null terminator to the string...
414   ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
415
416   ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
417   return ConstantArray::get(ATy, ElementVals);
418 }
419
420
421 // destroyConstant - Remove the constant from the constant table...
422 //
423 void ConstantArray::destroyConstant() {
424   ArrayConstants.remove(this);
425   destroyConstantImpl();
426 }
427
428 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
429 // then this method converts the array to an std::string and returns it.
430 // Otherwise, it asserts out.
431 //
432 std::string ConstantArray::getAsString() const {
433   std::string Result;
434   if (getType()->getElementType() == Type::SByteTy)
435     for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
436       Result += (char)cast<ConstantSInt>(getOperand(i))->getValue();
437   else {
438     assert(getType()->getElementType() == Type::UByteTy && "Not a string!");
439     for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
440       Result += (char)cast<ConstantUInt>(getOperand(i))->getValue();
441   }
442   return Result;
443 }
444
445
446 //---- ConstantStruct::get() implementation...
447 //
448 static ValueMap<std::vector<Constant*>, ConstantStruct> StructConstants;
449
450 ConstantStruct *ConstantStruct::get(const StructType *Ty,
451                                     const std::vector<Constant*> &V) {
452   ConstantStruct *Result = StructConstants.get(Ty, V);
453   if (!Result)   // If no preexisting value, create one now...
454     StructConstants.add(Ty, V, Result = new ConstantStruct(Ty, V));
455   return Result;
456 }
457
458 // destroyConstant - Remove the constant from the constant table...
459 //
460 void ConstantStruct::destroyConstant() {
461   StructConstants.remove(this);
462   destroyConstantImpl();
463 }
464
465
466 //---- ConstantPointerNull::get() implementation...
467 //
468 static ValueMap<char, ConstantPointerNull> NullPtrConstants;
469
470 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
471   ConstantPointerNull *Result = NullPtrConstants.get(Ty, 0);
472   if (!Result)   // If no preexisting value, create one now...
473     NullPtrConstants.add(Ty, 0, Result = new ConstantPointerNull(Ty));
474   return Result;
475 }
476
477 // destroyConstant - Remove the constant from the constant table...
478 //
479 void ConstantPointerNull::destroyConstant() {
480   NullPtrConstants.remove(this);
481   destroyConstantImpl();
482 }
483
484
485 //---- ConstantPointerRef::get() implementation...
486 //
487 ConstantPointerRef *ConstantPointerRef::get(GlobalValue *GV) {
488   assert(GV->getParent() && "Global Value must be attached to a module!");
489   
490   // The Module handles the pointer reference sharing...
491   return GV->getParent()->getConstantPointerRef(GV);
492 }
493
494 // destroyConstant - Remove the constant from the constant table...
495 //
496 void ConstantPointerRef::destroyConstant() {
497   getValue()->getParent()->destroyConstantPointerRef(this);
498   destroyConstantImpl();
499 }
500
501
502 //---- ConstantExpr::get() implementations...
503 //
504 typedef pair<unsigned, vector<Constant*> > ExprMapKeyType;
505 static ValueMap<const ExprMapKeyType, ConstantExpr> ExprConstants;
506
507 ConstantExpr *ConstantExpr::getCast(Constant *C, const Type *Ty) {
508
509   // Look up the constant in the table first to ensure uniqueness
510   vector<Constant*> argVec(1, C);
511   const ExprMapKeyType &Key = make_pair(Instruction::Cast, argVec);
512   ConstantExpr *Result = ExprConstants.get(Ty, Key);
513   if (Result) return Result;
514   
515   // Its not in the table so create a new one and put it in the table.
516   Result = new ConstantExpr(Instruction::Cast, C, Ty);
517   ExprConstants.add(Ty, Key, Result);
518   return Result;
519 }
520
521 ConstantExpr *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
522   // Look up the constant in the table first to ensure uniqueness
523   vector<Constant*> argVec(1, C1); argVec.push_back(C2);
524   const ExprMapKeyType &Key = make_pair(Opcode, argVec);
525   ConstantExpr *Result = ExprConstants.get(C1->getType(), Key);
526   if (Result) return Result;
527   
528   // Its not in the table so create a new one and put it in the table.
529   // Check the operands for consistency first
530   assert((Opcode >= Instruction::FirstBinaryOp &&
531           Opcode < Instruction::NumBinaryOps) &&
532          "Invalid opcode in binary constant expression");
533
534   assert(C1->getType() == C2->getType() &&
535          "Operand types in binary constant expression should match");
536   
537   Result = new ConstantExpr(Opcode, C1, C2);
538   ExprConstants.add(C1->getType(), Key, Result);
539   return Result;
540 }
541
542 ConstantExpr *ConstantExpr::getGetElementPtr(Constant *C,
543                                         const std::vector<Constant*> &IdxList) {
544   const Type *Ty = C->getType();
545
546   // Look up the constant in the table first to ensure uniqueness
547   vector<Constant*> argVec(1, C);
548   argVec.insert(argVec.end(), IdxList.begin(), IdxList.end());
549   
550   const ExprMapKeyType &Key = make_pair(Instruction::GetElementPtr, argVec);
551   ConstantExpr *Result = ExprConstants.get(Ty, Key);
552   if (Result) return Result;
553
554   // Its not in the table so create a new one and put it in the table.
555   // Check the operands for consistency first
556   // 
557   assert(isa<PointerType>(Ty) &&
558          "Non-pointer type for constant GelElementPtr expression");
559
560   // Check that the indices list is valid...
561   std::vector<Value*> ValIdxList(IdxList.begin(), IdxList.end());
562   const Type *DestTy = GetElementPtrInst::getIndexedType(Ty, ValIdxList, true);
563   assert(DestTy && "Invalid index list for constant GelElementPtr expression");
564   
565   Result = new ConstantExpr(C, IdxList, PointerType::get(DestTy));
566   ExprConstants.add(Ty, Key, Result);
567   return Result;
568 }
569
570 // destroyConstant - Remove the constant from the constant table...
571 //
572 void ConstantExpr::destroyConstant() {
573   ExprConstants.remove(this);
574   destroyConstantImpl();
575 }
576
577 const char *ConstantExpr::getOpcodeName() const {
578   return Instruction::getOpcodeName(getOpcode());
579 }
580
581
582 //---- ConstantPointerRef::mutateReferences() implementation...
583 //
584 unsigned ConstantPointerRef::mutateReferences(Value *OldV, Value *NewV) {
585   assert(getValue() == OldV && "Cannot mutate old value if I'm not using it!");
586   GlobalValue *NewGV = cast<GlobalValue>(NewV);
587   getValue()->getParent()->mutateConstantPointerRef(getValue(), NewGV);
588   Operands[0] = NewGV;
589   return 1;
590 }
591
592
593 //---- ConstantPointerExpr::mutateReferences() implementation...
594 //
595 unsigned ConstantExpr::mutateReferences(Value* OldV, Value *NewV) {
596   unsigned NumReplaced = 0;
597   Constant *NewC = cast<Constant>(NewV);
598   for (unsigned i = 0, N = getNumOperands(); i != N; ++i)
599     if (Operands[i] == OldV) {
600       ++NumReplaced;
601       Operands[i] = NewC;
602     }
603   return NumReplaced;
604 }