Add support for turning an array of characters into a string.
[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(isValueValidForType(Ty, V) && "Value too large for type!");
178 }
179
180 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V) : ConstantInt(Ty, V) {
181   assert(isValueValidForType(Ty, V) && "Value too large for type!");
182 }
183
184 ConstantFP::ConstantFP(const Type *Ty, double V) : Constant(Ty) {
185   assert(isValueValidForType(Ty, V) && "Value too large for type!");
186   Val = V;
187 }
188
189 ConstantArray::ConstantArray(const ArrayType *T,
190                              const std::vector<Constant*> &V) : Constant(T) {
191   for (unsigned i = 0; i < V.size(); i++) {
192     assert(V[i]->getType() == T->getElementType());
193     Operands.push_back(Use(V[i], this));
194   }
195 }
196
197 ConstantStruct::ConstantStruct(const StructType *T,
198                                const std::vector<Constant*> &V) : Constant(T) {
199   const StructType::ElementTypes &ETypes = T->getElementTypes();
200   assert(V.size() == ETypes.size() &&
201          "Invalid initializer vector for constant structure");
202   for (unsigned i = 0; i < V.size(); i++) {
203     assert(V[i]->getType() == ETypes[i]);
204     Operands.push_back(Use(V[i], this));
205   }
206 }
207
208 ConstantPointerRef::ConstantPointerRef(GlobalValue *GV)
209   : ConstantPointer(GV->getType()) {
210   Operands.push_back(Use(GV, this));
211 }
212
213 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
214   : Constant(Ty), iType(Opcode) {
215   Operands.push_back(Use(C, this));
216 }
217
218 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
219   : Constant(C1->getType()), iType(Opcode) {
220   Operands.push_back(Use(C1, this));
221   Operands.push_back(Use(C2, this));
222 }
223
224 ConstantExpr::ConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
225                            const Type *DestTy)
226   : Constant(DestTy), iType(Instruction::GetElementPtr) {
227   Operands.reserve(1+IdxList.size());
228   Operands.push_back(Use(C, this));
229   for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
230     Operands.push_back(Use(IdxList[i], this));
231 }
232
233
234
235 //===----------------------------------------------------------------------===//
236 //                           classof implementations
237
238 bool ConstantIntegral::classof(const Constant *CPV) {
239   return (CPV->getType()->isIntegral() || CPV->getType() == Type::BoolTy) &&
240           !isa<ConstantExpr>(CPV);
241 }
242
243 bool ConstantInt::classof(const Constant *CPV) {
244   return CPV->getType()->isIntegral() && !isa<ConstantExpr>(CPV);
245 }
246 bool ConstantSInt::classof(const Constant *CPV) {
247   return CPV->getType()->isSigned() && !isa<ConstantExpr>(CPV);
248 }
249 bool ConstantUInt::classof(const Constant *CPV) {
250   return CPV->getType()->isUnsigned() && !isa<ConstantExpr>(CPV);
251 }
252 bool ConstantFP::classof(const Constant *CPV) {
253   const Type *Ty = CPV->getType();
254   return ((Ty == Type::FloatTy || Ty == Type::DoubleTy) &&
255           !isa<ConstantExpr>(CPV));
256 }
257 bool ConstantArray::classof(const Constant *CPV) {
258   return isa<ArrayType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
259 }
260 bool ConstantStruct::classof(const Constant *CPV) {
261   return isa<StructType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
262 }
263 bool ConstantPointer::classof(const Constant *CPV) {
264   return (isa<PointerType>(CPV->getType()) && !isa<ConstantExpr>(CPV));
265 }
266
267
268
269 //===----------------------------------------------------------------------===//
270 //                      isValueValidForType implementations
271
272 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
273   switch (Ty->getPrimitiveID()) {
274   default:
275     return false;         // These can't be represented as integers!!!
276
277     // Signed types...
278   case Type::SByteTyID:
279     return (Val <= INT8_MAX && Val >= INT8_MIN);
280   case Type::ShortTyID:
281     return (Val <= INT16_MAX && Val >= INT16_MIN);
282   case Type::IntTyID:
283     return (Val <= INT32_MAX && Val >= INT32_MIN);
284   case Type::LongTyID:
285     return true;          // This is the largest type...
286   }
287   assert(0 && "WTF?");
288   return false;
289 }
290
291 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
292   switch (Ty->getPrimitiveID()) {
293   default:
294     return false;         // These can't be represented as integers!!!
295
296     // Unsigned types...
297   case Type::UByteTyID:
298     return (Val <= UINT8_MAX);
299   case Type::UShortTyID:
300     return (Val <= UINT16_MAX);
301   case Type::UIntTyID:
302     return (Val <= UINT32_MAX);
303   case Type::ULongTyID:
304     return true;          // This is the largest type...
305   }
306   assert(0 && "WTF?");
307   return false;
308 }
309
310 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
311   switch (Ty->getPrimitiveID()) {
312   default:
313     return false;         // These can't be represented as floating point!
314
315     // TODO: Figure out how to test if a double can be cast to a float!
316   case Type::FloatTyID:
317     /*
318     return (Val <= UINT8_MAX);
319     */
320   case Type::DoubleTyID:
321     return true;          // This is the largest type...
322   }
323 };
324
325 //===----------------------------------------------------------------------===//
326 //                      Factory Function Implementation
327
328 template<class ValType, class ConstantClass>
329 struct ValueMap {
330   typedef pair<const Type*, ValType> ConstHashKey;
331   map<ConstHashKey, ConstantClass *> Map;
332
333   inline ConstantClass *get(const Type *Ty, ValType V) {
334     typename map<ConstHashKey,ConstantClass *>::iterator I =
335       Map.find(ConstHashKey(Ty, V));
336     return (I != Map.end()) ? I->second : 0;
337   }
338
339   inline void add(const Type *Ty, ValType V, ConstantClass *CP) {
340     Map.insert(make_pair(ConstHashKey(Ty, V), CP));
341   }
342
343   inline void remove(ConstantClass *CP) {
344     for (typename map<ConstHashKey,ConstantClass *>::iterator I = Map.begin(),
345                                                       E = Map.end(); I != E;++I)
346       if (I->second == CP) {
347         Map.erase(I);
348         return;
349       }
350   }
351 };
352
353 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
354 //
355 static ValueMap<uint64_t, ConstantInt> IntConstants;
356
357 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
358   ConstantSInt *Result = (ConstantSInt*)IntConstants.get(Ty, (uint64_t)V);
359   if (!Result)   // If no preexisting value, create one now...
360     IntConstants.add(Ty, V, Result = new ConstantSInt(Ty, V));
361   return Result;
362 }
363
364 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
365   ConstantUInt *Result = (ConstantUInt*)IntConstants.get(Ty, V);
366   if (!Result)   // If no preexisting value, create one now...
367     IntConstants.add(Ty, V, Result = new ConstantUInt(Ty, V));
368   return Result;
369 }
370
371 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
372   assert(V <= 127 && "Can only be used with very small positive constants!");
373   if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
374   return ConstantUInt::get(Ty, V);
375 }
376
377 //---- ConstantFP::get() implementation...
378 //
379 static ValueMap<double, ConstantFP> FPConstants;
380
381 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
382   ConstantFP *Result = FPConstants.get(Ty, V);
383   if (!Result)   // If no preexisting value, create one now...
384     FPConstants.add(Ty, V, Result = new ConstantFP(Ty, V));
385   return Result;
386 }
387
388 //---- ConstantArray::get() implementation...
389 //
390 static ValueMap<std::vector<Constant*>, ConstantArray> ArrayConstants;
391
392 ConstantArray *ConstantArray::get(const ArrayType *Ty,
393                                   const std::vector<Constant*> &V) {
394   ConstantArray *Result = ArrayConstants.get(Ty, V);
395   if (!Result)   // If no preexisting value, create one now...
396     ArrayConstants.add(Ty, V, Result = new ConstantArray(Ty, V));
397   return Result;
398 }
399
400 // ConstantArray::get(const string&) - Return an array that is initialized to
401 // contain the specified string.  A null terminator is added to the specified
402 // string so that it may be used in a natural way...
403 //
404 ConstantArray *ConstantArray::get(const std::string &Str) {
405   std::vector<Constant*> ElementVals;
406
407   for (unsigned i = 0; i < Str.length(); ++i)
408     ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
409
410   // Add a null terminator to the string...
411   ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
412
413   ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
414   return ConstantArray::get(ATy, ElementVals);
415 }
416
417
418 // destroyConstant - Remove the constant from the constant table...
419 //
420 void ConstantArray::destroyConstant() {
421   ArrayConstants.remove(this);
422   destroyConstantImpl();
423 }
424
425 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
426 // then this method converts the array to an std::string and returns it.
427 // Otherwise, it asserts out.
428 //
429 std::string ConstantArray::getAsString() const {
430   std::string Result;
431   if (getType()->getElementType() == Type::SByteTy)
432     for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
433       Result += (char)cast<ConstantSInt>(getOperand(i))->getValue();
434   else {
435     assert(getType()->getElementType() == Type::UByteTy && "Not a string!");
436     for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
437       Result += (char)cast<ConstantUInt>(getOperand(i))->getValue();
438   }
439   return Result;
440 }
441
442
443 //---- ConstantStruct::get() implementation...
444 //
445 static ValueMap<std::vector<Constant*>, ConstantStruct> StructConstants;
446
447 ConstantStruct *ConstantStruct::get(const StructType *Ty,
448                                     const std::vector<Constant*> &V) {
449   ConstantStruct *Result = StructConstants.get(Ty, V);
450   if (!Result)   // If no preexisting value, create one now...
451     StructConstants.add(Ty, V, Result = new ConstantStruct(Ty, V));
452   return Result;
453 }
454
455 // destroyConstant - Remove the constant from the constant table...
456 //
457 void ConstantStruct::destroyConstant() {
458   StructConstants.remove(this);
459   destroyConstantImpl();
460 }
461
462
463 //---- ConstantPointerNull::get() implementation...
464 //
465 static ValueMap<char, ConstantPointerNull> NullPtrConstants;
466
467 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
468   ConstantPointerNull *Result = NullPtrConstants.get(Ty, 0);
469   if (!Result)   // If no preexisting value, create one now...
470     NullPtrConstants.add(Ty, 0, Result = new ConstantPointerNull(Ty));
471   return Result;
472 }
473
474 // destroyConstant - Remove the constant from the constant table...
475 //
476 void ConstantPointerNull::destroyConstant() {
477   NullPtrConstants.remove(this);
478   destroyConstantImpl();
479 }
480
481
482 //---- ConstantPointerRef::get() implementation...
483 //
484 ConstantPointerRef *ConstantPointerRef::get(GlobalValue *GV) {
485   assert(GV->getParent() && "Global Value must be attached to a module!");
486   
487   // The Module handles the pointer reference sharing...
488   return GV->getParent()->getConstantPointerRef(GV);
489 }
490
491 // destroyConstant - Remove the constant from the constant table...
492 //
493 void ConstantPointerRef::destroyConstant() {
494   getValue()->getParent()->destroyConstantPointerRef(this);
495   destroyConstantImpl();
496 }
497
498
499 //---- ConstantExpr::get() implementations...
500 //
501 typedef pair<unsigned, vector<Constant*> > ExprMapKeyType;
502 static ValueMap<const ExprMapKeyType, ConstantExpr> ExprConstants;
503
504 ConstantExpr *ConstantExpr::getCast(Constant *C, const Type *Ty) {
505
506   // Look up the constant in the table first to ensure uniqueness
507   vector<Constant*> argVec(1, C);
508   const ExprMapKeyType &Key = make_pair(Instruction::Cast, argVec);
509   ConstantExpr *Result = ExprConstants.get(Ty, Key);
510   if (Result) return Result;
511   
512   // Its not in the table so create a new one and put it in the table.
513   Result = new ConstantExpr(Instruction::Cast, C, Ty);
514   ExprConstants.add(Ty, Key, Result);
515   return Result;
516 }
517
518 ConstantExpr *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
519   // Look up the constant in the table first to ensure uniqueness
520   vector<Constant*> argVec(1, C1); argVec.push_back(C2);
521   const ExprMapKeyType &Key = make_pair(Opcode, argVec);
522   ConstantExpr *Result = ExprConstants.get(C1->getType(), Key);
523   if (Result) return Result;
524   
525   // Its not in the table so create a new one and put it in the table.
526   // Check the operands for consistency first
527   assert((Opcode >= Instruction::FirstBinaryOp &&
528           Opcode < Instruction::NumBinaryOps) &&
529          "Invalid opcode in binary constant expression");
530
531   assert(C1->getType() == C2->getType() &&
532          "Operand types in binary constant expression should match");
533   
534   Result = new ConstantExpr(Opcode, C1, C2);
535   ExprConstants.add(C1->getType(), Key, Result);
536   return Result;
537 }
538
539 ConstantExpr *ConstantExpr::getGetElementPtr(Constant *C,
540                                         const std::vector<Constant*> &IdxList) {
541   const Type *Ty = C->getType();
542
543   // Look up the constant in the table first to ensure uniqueness
544   vector<Constant*> argVec(1, C);
545   argVec.insert(argVec.end(), IdxList.begin(), IdxList.end());
546   
547   const ExprMapKeyType &Key = make_pair(Instruction::GetElementPtr, argVec);
548   ConstantExpr *Result = ExprConstants.get(Ty, Key);
549   if (Result) return Result;
550
551   // Its not in the table so create a new one and put it in the table.
552   // Check the operands for consistency first
553   // 
554   assert(isa<PointerType>(Ty) &&
555          "Non-pointer type for constant GelElementPtr expression");
556
557   // Check that the indices list is valid...
558   std::vector<Value*> ValIdxList(IdxList.begin(), IdxList.end());
559   const Type *DestTy = GetElementPtrInst::getIndexedType(Ty, ValIdxList, true);
560   assert(DestTy && "Invalid index list for constant GelElementPtr expression");
561   
562   Result = new ConstantExpr(C, IdxList, PointerType::get(DestTy));
563   ExprConstants.add(Ty, Key, Result);
564   return Result;
565 }
566
567 // destroyConstant - Remove the constant from the constant table...
568 //
569 void ConstantExpr::destroyConstant() {
570   ExprConstants.remove(this);
571   destroyConstantImpl();
572 }
573
574 const char *ConstantExpr::getOpcodeName() const {
575   return Instruction::getOpcodeName(getOpcode());
576 }
577
578
579 //---- ConstantPointerRef::mutateReferences() implementation...
580 //
581 unsigned ConstantPointerRef::mutateReferences(Value *OldV, Value *NewV) {
582   assert(getValue() == OldV && "Cannot mutate old value if I'm not using it!");
583   GlobalValue *NewGV = cast<GlobalValue>(NewV);
584   getValue()->getParent()->mutateConstantPointerRef(getValue(), NewGV);
585   Operands[0] = NewGV;
586   return 1;
587 }
588
589
590 //---- ConstantPointerExpr::mutateReferences() implementation...
591 //
592 unsigned ConstantExpr::mutateReferences(Value* OldV, Value *NewV) {
593   unsigned NumReplaced = 0;
594   Constant *NewC = cast<Constant>(NewV);
595   for (unsigned i = 0, N = getNumOperands(); i != N; ++i)
596     if (Operands[i] == OldV) {
597       ++NumReplaced;
598       Operands[i] = NewC;
599     }
600   return NumReplaced;
601 }