Generalize TargetData strings, to support more interesting forms of data.
[oota-llvm.git] / lib / Target / TargetData.cpp
1 //===-- TargetData.cpp - Data size & alignment routines --------------------==//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines target properties related to datatype size/offset/alignment
11 // information.
12 //
13 // This structure should be created once, filled in if the defaults are not
14 // correct and then passed around by const&.  None of the members functions
15 // require modification to the object.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/Target/TargetData.h"
20 #include "llvm/Module.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Constants.h"
23 #include "llvm/Support/GetElementPtrTypeIterator.h"
24 #include "llvm/Support/MathExtras.h"
25 #include "llvm/Support/ManagedStatic.h"
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include <algorithm>
29 #include <cstdlib>
30 #include <sstream>
31 using namespace llvm;
32
33 // Handle the Pass registration stuff necessary to use TargetData's.
34 namespace {
35   // Register the default SparcV9 implementation...
36   RegisterPass<TargetData> X("targetdata", "Target Data Layout");
37 }
38
39 //===----------------------------------------------------------------------===//
40 // Support for StructLayout
41 //===----------------------------------------------------------------------===//
42
43 StructLayout::StructLayout(const StructType *ST, const TargetData &TD) {
44   StructAlignment = 0;
45   StructSize = 0;
46   NumElements = ST->getNumElements();
47
48   // Loop over each of the elements, placing them in memory...
49   for (unsigned i = 0, e = NumElements; i != e; ++i) {
50     const Type *Ty = ST->getElementType(i);
51     unsigned TyAlign;
52     uint64_t TySize;
53     TyAlign = (unsigned) TD.getABITypeAlignment(Ty);
54     TySize = (unsigned) TD.getTypeSize(Ty);
55
56     // Add padding if necessary to make the data element aligned properly...
57     if (StructSize % TyAlign != 0)
58       StructSize = (StructSize/TyAlign + 1) * TyAlign;   // Add padding...
59
60     // Keep track of maximum alignment constraint
61     StructAlignment = std::max(TyAlign, StructAlignment);
62
63     MemberOffsets[i] = StructSize;
64     StructSize += TySize;                 // Consume space for this data item
65   }
66
67   // Empty structures have alignment of 1 byte.
68   if (StructAlignment == 0) StructAlignment = 1;
69
70   // Add padding to the end of the struct so that it could be put in an array
71   // and all array elements would be aligned correctly.
72   if (StructSize % StructAlignment != 0)
73     StructSize = (StructSize/StructAlignment + 1) * StructAlignment;
74 }
75
76
77 /// getElementContainingOffset - Given a valid offset into the structure,
78 /// return the structure index that contains it.
79 unsigned StructLayout::getElementContainingOffset(uint64_t Offset) const {
80   const uint64_t *SI =
81     std::upper_bound(&MemberOffsets[0], &MemberOffsets[NumElements], Offset);
82   assert(SI != &MemberOffsets[0] && "Offset not in structure type!");
83   --SI;
84   assert(*SI <= Offset && "upper_bound didn't work");
85   assert((SI == &MemberOffsets[0] || *(SI-1) < Offset) &&
86          (SI+1 == &MemberOffsets[NumElements] || *(SI+1) > Offset) &&
87          "Upper bound didn't work!");
88   return SI-&MemberOffsets[0];
89 }
90
91 //===----------------------------------------------------------------------===//
92 // TargetAlignElem, TargetAlign support
93 //===----------------------------------------------------------------------===//
94
95 TargetAlignElem
96 TargetAlignElem::get(AlignTypeEnum align_type, unsigned char abi_align,
97                      unsigned char pref_align, short bit_width)
98 {
99   TargetAlignElem retval;
100   retval.AlignType = align_type;
101   retval.ABIAlign = abi_align;
102   retval.PrefAlign = pref_align;
103   retval.TypeBitWidth = bit_width;
104   return retval;
105 }
106
107 bool
108 TargetAlignElem::operator<(const TargetAlignElem &rhs) const
109 {
110   return ((AlignType < rhs.AlignType)
111           || (AlignType == rhs.AlignType && TypeBitWidth < rhs.TypeBitWidth));
112 }
113
114 bool
115 TargetAlignElem::operator==(const TargetAlignElem &rhs) const
116 {
117   return (AlignType == rhs.AlignType
118           && ABIAlign == rhs.ABIAlign
119           && PrefAlign == rhs.PrefAlign
120           && TypeBitWidth == rhs.TypeBitWidth);
121 }
122
123 std::ostream &
124 TargetAlignElem::dump(std::ostream &os) const
125 {
126   return os << AlignType
127             << TypeBitWidth
128             << ":" << (int) (ABIAlign * 8)
129             << ":" << (int) (PrefAlign * 8);
130 }
131
132 std::ostream &
133 llvm::operator<<(std::ostream &os, const TargetAlignElem &elem)
134 {
135   return elem.dump(os);
136 }
137
138 const TargetAlignElem TargetData::InvalidAlignmentElem =
139                 TargetAlignElem::get((AlignTypeEnum) -1, 0, 0, 0);
140
141 //===----------------------------------------------------------------------===//
142 //                       TargetData Class Implementation
143 //===----------------------------------------------------------------------===//
144
145 /*!
146  A TargetDescription string consists of a sequence of hyphen-delimited
147  specifiers for target endianness, pointer size and alignments, and various
148  primitive type sizes and alignments. A typical string looks something like:
149  <br>
150  "E-p:32:32:32-i1:8:8-i8:8:8-i32:32:32-i64:32:64-f32:32:32-f64:32:64"
151  <br>
152  (note: this string is not fully specified and is only an example.)
153  \p
154  Alignments come in two flavors: ABI and preferred. ABI alignment (abi_align,
155  below) dictates how a type will be aligned within an aggregate and when used
156  as an argument.  Preferred alignment (pref_align, below) determines a type's
157  alignment when emitted as a global.
158  \p
159  Specifier string details:
160  <br><br>
161  <i>[E|e]</i>: Endianness. "E" specifies a big-endian target data model, "e"
162  specifies a little-endian target data model.
163  <br><br>
164  <i>p:<size>:<abi_align>:<pref_align></i>: Pointer size, ABI and preferred
165  alignment.
166  <br><br>
167  <i><type><size>:<abi_align>:<pref_align></i>: Numeric type alignment. Type is
168  one of <i>i|f|v|a</i>, corresponding to integer, floating point, vector (aka
169  packed) or aggregate.  Size indicates the size, e.g., 32 or 64 bits.
170  \p
171  The default string, fully specified is:
172  <br><br>
173  "E-p:64:64:64-a0:0:0-f32:32:32-f64:0:64"
174  "-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:0:64"
175  "-v64:64:64-v128:128:128"
176  <br><br>
177  Note that in the case of aggregates, 0 is the default ABI and preferred
178  alignment. This is a special case, where the aggregate's computed worst-case
179  alignment will be used.
180  */ 
181 void TargetData::init(const std::string &TargetDescription) {
182   std::string temp = TargetDescription;
183   
184   LittleEndian = false;
185   PointerMemSize = 8;
186   PointerABIAlign   = 8;
187   PointerPrefAlign = PointerABIAlign;
188
189   // Default alignments
190   setAlignment(INTEGER_ALIGN,   1,  1, 1); // Bool
191   setAlignment(INTEGER_ALIGN,   1,  1, 8); // Byte
192   setAlignment(INTEGER_ALIGN,   2,  2, 16); // short
193   setAlignment(INTEGER_ALIGN,   4,  4, 32); // int
194   setAlignment(INTEGER_ALIGN,   0,  8, 64); // long
195   setAlignment(FLOAT_ALIGN,     4,  4, 32); // float
196   setAlignment(FLOAT_ALIGN,     0,  8, 64); // double
197   setAlignment(PACKED_ALIGN,    8,  8, 64); // v2i32
198   setAlignment(PACKED_ALIGN,   16, 16, 128); // v16i8, v8i16, v4i32, ...
199   setAlignment(AGGREGATE_ALIGN, 0,  0,  0); // struct, union, class, ...
200   
201   while (!temp.empty()) {
202     std::string token = getToken(temp, "-");
203     
204     std::string arg0 = getToken(token, ":");
205     const char *p = arg0.c_str();
206     AlignTypeEnum align_type;
207     short size;
208     unsigned char abi_align;
209     unsigned char pref_align;
210
211     switch(*p) {
212     case 'E':
213       LittleEndian = false;
214       break;
215     case 'e':
216       LittleEndian = true;
217       break;
218     case 'p':
219       PointerMemSize = atoi(getToken(token,":").c_str()) / 8;
220       PointerABIAlign = atoi(getToken(token,":").c_str()) / 8;
221       PointerPrefAlign = atoi(getToken(token,":").c_str()) / 8;
222       if (PointerPrefAlign == 0)
223         PointerPrefAlign = PointerABIAlign;
224       break;
225     case 'i':
226     case 'v':
227     case 'f':
228     case 'a': {
229       align_type = (*p == 'i' ? INTEGER_ALIGN :
230                     (*p == 'f' ? FLOAT_ALIGN :
231                      (*p == 'v' ? PACKED_ALIGN : AGGREGATE_ALIGN)));
232       size = (short) atoi(++p);
233       abi_align = atoi(getToken(token, ":").c_str()) / 8;
234       pref_align = atoi(getToken(token, ":").c_str()) / 8;
235       if (pref_align == 0)
236         pref_align = abi_align;
237       setAlignment(align_type, abi_align, pref_align, size);
238       break;
239     }
240     default:
241       break;
242     }
243   }
244
245   // Unless explicitly specified, the alignments for longs and doubles is 
246   // capped by pointer size.
247   // FIXME: Is this still necessary?
248   const TargetAlignElem &long_align = getAlignment(INTEGER_ALIGN, 64);
249   if (long_align.ABIAlign == 0)
250     setAlignment(INTEGER_ALIGN, PointerMemSize, PointerMemSize, 64);
251
252   const TargetAlignElem &double_align = getAlignment(FLOAT_ALIGN, 64);
253   if (double_align.ABIAlign == 0)
254     setAlignment(FLOAT_ALIGN, PointerMemSize, PointerMemSize, 64);
255 }
256
257 TargetData::TargetData(const Module *M) {
258   init(M->getDataLayout());
259 }
260
261 void
262 TargetData::setAlignment(AlignTypeEnum align_type, unsigned char abi_align,
263                          unsigned char pref_align, short bit_width) {
264   TargetAlignElem elt = TargetAlignElem::get(align_type, abi_align,
265                                              pref_align, bit_width);
266   std::pair<align_iterator, align_iterator> ins_result =
267             std::equal_range(Alignments.begin(), Alignments.end(), elt);
268   align_iterator I = ins_result.first;
269   if (I->AlignType == align_type && I->TypeBitWidth == bit_width) {
270     // Update the abi, preferred alignments.
271     I->ABIAlign = abi_align;
272     I->PrefAlign = pref_align;
273   } else
274     Alignments.insert(I, elt);
275
276 #if 0
277   // Keep around for debugging and testing...
278   align_iterator E = ins_result.second;
279
280   cerr << "setAlignment(" << elt << ")\n";
281   cerr << "I = " << (I - Alignments.begin())
282        << ", E = " << (E - Alignments.begin()) << "\n";
283   std::copy(Alignments.begin(), Alignments.end(),
284             std::ostream_iterator<TargetAlignElem>(*cerr, "\n"));
285   cerr << "=====\n";
286 #endif
287 }
288
289 const TargetAlignElem &
290 TargetData::getAlignment(AlignTypeEnum align_type, short bit_width) const
291 {
292   std::pair<align_const_iterator, align_const_iterator> find_result =
293                 std::equal_range(Alignments.begin(), Alignments.end(),
294                                  TargetAlignElem::get(align_type, 0, 0,
295                                                       bit_width));
296   align_const_iterator I = find_result.first;
297
298   // Note: This may not be reasonable if variable-width integer sizes are
299   // passed, at which point, more sophisticated searching will need to be done.
300   return *I;
301 }
302
303 /// LayoutInfo - The lazy cache of structure layout information maintained by
304 /// TargetData.  Note that the struct types must have been free'd before
305 /// llvm_shutdown is called (and thus this is deallocated) because all the
306 /// targets with cached elements should have been destroyed.
307 ///
308 typedef std::pair<const TargetData*,const StructType*> LayoutKey;
309
310 struct DenseMapLayoutKeyInfo {
311   static inline LayoutKey getEmptyKey() { return LayoutKey(0, 0); }
312   static inline LayoutKey getTombstoneKey() {
313     return LayoutKey((TargetData*)(intptr_t)-1, 0);
314   }
315   static unsigned getHashValue(const LayoutKey &Val) {
316     return DenseMapKeyInfo<void*>::getHashValue(Val.first) ^
317            DenseMapKeyInfo<void*>::getHashValue(Val.second);
318   }
319   static bool isPod() { return true; }
320 };
321
322 typedef DenseMap<LayoutKey, StructLayout*, DenseMapLayoutKeyInfo> LayoutInfoTy;
323 static ManagedStatic<LayoutInfoTy> LayoutInfo;
324
325
326 TargetData::~TargetData() {
327   if (LayoutInfo.isConstructed()) {
328     // Remove any layouts for this TD.
329     LayoutInfoTy &TheMap = *LayoutInfo;
330     for (LayoutInfoTy::iterator I = TheMap.begin(), E = TheMap.end();
331          I != E; ) {
332       if (I->first.first == this) {
333         I->second->~StructLayout();
334         free(I->second);
335         TheMap.erase(I++);
336       } else {
337         ++I;
338       }
339     }
340   }
341 }
342
343 const StructLayout *TargetData::getStructLayout(const StructType *Ty) const {
344   LayoutInfoTy &TheMap = *LayoutInfo;
345   
346   StructLayout *&SL = TheMap[LayoutKey(this, Ty)];
347   if (SL) return SL;
348
349   // Otherwise, create the struct layout.  Because it is variable length, we 
350   // malloc it, then use placement new.
351   unsigned NumElts = Ty->getNumElements();
352   StructLayout *L =
353     (StructLayout *)malloc(sizeof(StructLayout)+(NumElts-1)*sizeof(uint64_t));
354   
355   // Set SL before calling StructLayout's ctor.  The ctor could cause other
356   // entries to be added to TheMap, invalidating our reference.
357   SL = L;
358   
359   new (L) StructLayout(Ty, *this);
360     
361   return L;
362 }
363
364 /// InvalidateStructLayoutInfo - TargetData speculatively caches StructLayout
365 /// objects.  If a TargetData object is alive when types are being refined and
366 /// removed, this method must be called whenever a StructType is removed to
367 /// avoid a dangling pointer in this cache.
368 void TargetData::InvalidateStructLayoutInfo(const StructType *Ty) const {
369   if (!LayoutInfo.isConstructed()) return;  // No cache.
370   
371   LayoutInfoTy::iterator I = LayoutInfo->find(LayoutKey(this, Ty));
372   if (I != LayoutInfo->end()) {
373     I->second->~StructLayout();
374     free(I->second);
375     LayoutInfo->erase(I);
376   }
377 }
378
379
380 struct hyphen_delimited :
381   public std::iterator<std::output_iterator_tag, void, void, void, void>
382 {
383   std::ostream &o;
384
385   hyphen_delimited(std::ostream &os) :
386     o(os)
387   { }
388
389   hyphen_delimited &operator=(const TargetAlignElem &elem)
390   {
391     o << "-" << elem;
392     return *this;
393   }
394
395   hyphen_delimited &operator*()
396   {
397     return *this;
398   }
399
400   hyphen_delimited &operator++()
401   {
402     return *this;
403   }
404 };
405
406
407 std::string TargetData::getStringRepresentation() const {
408   std::stringstream repr;
409
410   if (LittleEndian)
411     repr << "e";
412   else
413     repr << "E";
414   repr << "-p:" << (PointerMemSize * 8) << ":" << (PointerABIAlign * 8)
415        << ":" << (PointerPrefAlign * 8);
416   std::copy(Alignments.begin(), Alignments.end(), hyphen_delimited(repr));
417   return repr.str();
418 }
419
420
421 uint64_t TargetData::getTypeSize(const Type *Ty) const {
422   assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!");
423   switch (Ty->getTypeID()) {
424   case Type::LabelTyID:
425   case Type::PointerTyID:
426     return getPointerSize();
427   case Type::ArrayTyID: {
428     const ArrayType *ATy = cast<ArrayType>(Ty);
429     uint64_t Size;
430     unsigned char Alignment;
431     Size = getTypeSize(ATy->getElementType());
432     Alignment = getABITypeAlignment(ATy->getElementType());
433     unsigned AlignedSize = (Size + Alignment - 1)/Alignment*Alignment;
434     return AlignedSize*ATy->getNumElements();
435   }
436   case Type::StructTyID: {
437     // Get the layout annotation... which is lazily created on demand.
438     const StructLayout *Layout = getStructLayout(cast<StructType>(Ty));
439     return Layout->getSizeInBytes();
440   }
441   case Type::IntegerTyID: {
442     unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
443     if (BitWidth <= 8) {
444       return 1;
445     } else if (BitWidth <= 16) {
446       return 2;
447     } else if (BitWidth <= 32) {
448       return 4;
449     } else if (BitWidth <= 64) {
450       return 8;
451     } else
452       assert(0 && "Integer types > 64 bits not supported.");
453     break;
454   }
455   case Type::VoidTyID:
456     return 1;
457   case Type::FloatTyID:
458     return 4;
459   case Type::DoubleTyID:
460     return 8;
461   case Type::PackedTyID: {
462     const PackedType *PTy = cast<PackedType>(Ty);
463     return PTy->getBitWidth() / 8;
464   }
465   default:
466     assert(0 && "TargetData::getTypeSize(): Unsupported type");
467     break;
468   }
469   return 0;
470 }
471
472 uint64_t TargetData::getTypeSizeInBits(const Type *Ty) const {
473   if (Ty->isInteger())
474     return cast<IntegerType>(Ty)->getBitWidth();
475   else
476     return getTypeSize(Ty) * 8;
477 }
478
479
480 /*!
481   \param abi_or_pref Flag that determines which alignment is returned. true
482   returns the ABI alignment, false returns the preferred alignment.
483   \param Ty The underlying type for which alignment is determined.
484
485   Get the ABI (\a abi_or_pref == true) or preferred alignment (\a abi_or_pref
486   == false) for the requested type \a Ty.
487  */
488 unsigned char TargetData::getAlignment(const Type *Ty, bool abi_or_pref) const
489 {
490   int AlignType = -1;
491
492   assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!");
493   switch (Ty->getTypeID()) {
494   /* Early escape for the non-numeric types */
495   case Type::LabelTyID:
496   case Type::PointerTyID:
497     return (abi_or_pref
498             ? getPointerABIAlignment()
499             : getPointerPrefAlignment());
500   case Type::ArrayTyID: {
501     const ArrayType *ATy = cast<ArrayType>(Ty);
502     return (abi_or_pref
503             ? getABITypeAlignment(ATy->getElementType())
504             : getPrefTypeAlignment(ATy->getElementType()));
505   }
506   case Type::StructTyID: {
507       // Get the layout annotation... which is lazily created on demand.
508     const StructLayout *Layout = getStructLayout(cast<StructType>(Ty));
509     const TargetAlignElem &elem = getAlignment(AGGREGATE_ALIGN, 0);
510     assert(validAlignment(elem)
511            && "Aggregate alignment return invalid in getAlignment");
512     if (abi_or_pref) {
513       return (elem.ABIAlign < Layout->getAlignment()
514               ? Layout->StructAlignment
515               : elem.ABIAlign);
516     } else {
517       return (elem.PrefAlign < Layout->getAlignment()
518               ? Layout->StructAlignment
519               : elem.PrefAlign);
520     }
521   }
522   case Type::IntegerTyID:
523   case Type::VoidTyID:
524     AlignType = INTEGER_ALIGN;
525     break;
526   case Type::FloatTyID:
527   case Type::DoubleTyID:
528     AlignType = FLOAT_ALIGN;
529     break;
530   case Type::PackedTyID:
531     AlignType = PACKED_ALIGN;
532     break;
533   default:
534     assert(0 && "Bad type for getAlignment!!!");
535     break;
536   }
537
538   const TargetAlignElem &elem = getAlignment((AlignTypeEnum) AlignType,
539                                              getTypeSize(Ty) * 8);
540   if (validAlignment(elem))
541     return (abi_or_pref ? elem.ABIAlign : elem.PrefAlign);
542   else {
543     cerr << "TargetData::getAlignment: align type " << AlignType
544          << " size " << getTypeSize(Ty) << " not found in Alignments.\n";
545     abort();
546     /*NOTREACHED*/
547     return 0;
548   }
549 }
550
551 unsigned char TargetData::getABITypeAlignment(const Type *Ty) const {
552   return getAlignment(Ty, true);
553 }
554
555 unsigned char TargetData::getPrefTypeAlignment(const Type *Ty) const {
556   return getAlignment(Ty, false);
557 }
558
559 unsigned char TargetData::getPreferredTypeAlignmentShift(const Type *Ty) const {
560   unsigned Align = (unsigned) getPrefTypeAlignment(Ty);
561   assert(!(Align & (Align-1)) && "Alignment is not a power of two!");
562   return Log2_32(Align);
563 }
564
565 /// getIntPtrType - Return an unsigned integer type that is the same size or
566 /// greater to the host pointer size.
567 const Type *TargetData::getIntPtrType() const {
568   switch (getPointerSize()) {
569   default: assert(0 && "Unknown pointer size!");
570   case 2: return Type::Int16Ty;
571   case 4: return Type::Int32Ty;
572   case 8: return Type::Int64Ty;
573   }
574 }
575
576
577 uint64_t TargetData::getIndexedOffset(const Type *ptrTy, Value* const* Indices,
578                                       unsigned NumIndices) const {
579   const Type *Ty = ptrTy;
580   assert(isa<PointerType>(Ty) && "Illegal argument for getIndexedOffset()");
581   uint64_t Result = 0;
582
583   generic_gep_type_iterator<Value* const*>
584     TI = gep_type_begin(ptrTy, Indices, Indices+NumIndices);
585   for (unsigned CurIDX = 0; CurIDX != NumIndices; ++CurIDX, ++TI) {
586     if (const StructType *STy = dyn_cast<StructType>(*TI)) {
587       assert(Indices[CurIDX]->getType() == Type::Int32Ty &&"Illegal struct idx");
588       unsigned FieldNo = cast<ConstantInt>(Indices[CurIDX])->getZExtValue();
589
590       // Get structure layout information...
591       const StructLayout *Layout = getStructLayout(STy);
592
593       // Add in the offset, as calculated by the structure layout info...
594       Result += Layout->getElementOffset(FieldNo);
595
596       // Update Ty to refer to current element
597       Ty = STy->getElementType(FieldNo);
598     } else {
599       // Update Ty to refer to current element
600       Ty = cast<SequentialType>(Ty)->getElementType();
601
602       // Get the array index and the size of each array element.
603       int64_t arrayIdx = cast<ConstantInt>(Indices[CurIDX])->getSExtValue();
604       Result += arrayIdx * (int64_t)getTypeSize(Ty);
605     }
606   }
607
608   return Result;
609 }
610
611 /// getPreferredAlignmentLog - Return the preferred alignment of the
612 /// specified global, returned in log form.  This includes an explicitly
613 /// requested alignment (if the global has one).
614 unsigned TargetData::getPreferredAlignmentLog(const GlobalVariable *GV) const {
615   const Type *ElemType = GV->getType()->getElementType();
616   unsigned Alignment = getPreferredTypeAlignmentShift(ElemType);
617   if (GV->getAlignment() > (1U << Alignment))
618     Alignment = Log2_32(GV->getAlignment());
619   
620   if (GV->hasInitializer()) {
621     if (Alignment < 4) {
622       // If the global is not external, see if it is large.  If so, give it a
623       // larger alignment.
624       if (getTypeSize(ElemType) > 128)
625         Alignment = 4;    // 16-byte alignment.
626     }
627   }
628   return Alignment;
629 }