Although targets are not required to support integers > 64bits, TargetData
[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/ADT/StringExtras.h"
26 #include <algorithm>
27 #include <cstdlib>
28 #include <sstream>
29 using namespace llvm;
30
31 // Handle the Pass registration stuff necessary to use TargetData's.
32 namespace {
33   // Register the default SparcV9 implementation...
34   RegisterPass<TargetData> X("targetdata", "Target Data Layout");
35 }
36
37 static inline void getTypeInfoABI(const Type *Ty, const TargetData *TD,
38                                   uint64_t &Size, unsigned char &Alignment);
39
40 static inline void getTypeInfoPref(const Type *Ty, const TargetData *TD,
41                                    uint64_t &Size, unsigned char &Alignment);
42
43 //===----------------------------------------------------------------------===//
44 // Support for StructLayout
45 //===----------------------------------------------------------------------===//
46
47 StructLayout::StructLayout(const StructType *ST, const TargetData &TD) {
48   StructAlignment = 0;
49   StructSize = 0;
50
51   // Loop over each of the elements, placing them in memory...
52   for (StructType::element_iterator TI = ST->element_begin(),
53          TE = ST->element_end(); TI != TE; ++TI) {
54     const Type *Ty = *TI;
55     unsigned char A;
56     unsigned TyAlign;
57     uint64_t TySize;
58     getTypeInfoABI(Ty, &TD, TySize, A);
59     TyAlign = ST->isPacked() ? 1 : A;
60
61     // Add padding if necessary to make the data element aligned properly...
62     if (StructSize % TyAlign != 0)
63       StructSize = (StructSize/TyAlign + 1) * TyAlign;   // Add padding...
64
65     // Keep track of maximum alignment constraint
66     StructAlignment = std::max(TyAlign, StructAlignment);
67
68     MemberOffsets.push_back(StructSize);
69     StructSize += TySize;                 // Consume space for this data item
70   }
71
72   // Empty structures have alignment of 1 byte.
73   if (StructAlignment == 0) StructAlignment = 1;
74
75   // Add padding to the end of the struct so that it could be put in an array
76   // and all array elements would be aligned correctly.
77   if (StructSize % StructAlignment != 0)
78     StructSize = (StructSize/StructAlignment + 1) * StructAlignment;
79 }
80
81
82 /// getElementContainingOffset - Given a valid offset into the structure,
83 /// return the structure index that contains it.
84 unsigned StructLayout::getElementContainingOffset(uint64_t Offset) const {
85   std::vector<uint64_t>::const_iterator SI =
86     std::upper_bound(MemberOffsets.begin(), MemberOffsets.end(), Offset);
87   assert(SI != MemberOffsets.begin() && "Offset not in structure type!");
88   --SI;
89   assert(*SI <= Offset && "upper_bound didn't work");
90   assert((SI == MemberOffsets.begin() || *(SI-1) < Offset) &&
91          (SI+1 == MemberOffsets.end() || *(SI+1) > Offset) &&
92          "Upper bound didn't work!");
93   return SI-MemberOffsets.begin();
94 }
95
96 //===----------------------------------------------------------------------===//
97 //                       TargetData Class Implementation
98 //===----------------------------------------------------------------------===//
99
100 void TargetData::init(const std::string &TargetDescription) {
101   std::string temp = TargetDescription;
102   
103   LittleEndian = false;
104   PointerMemSize = 8;
105   PointerABIAlignment   = 8;
106   DoubleABIAlignment = 0;
107   FloatABIAlignment = 4;
108   LongABIAlignment   = 0;
109   IntABIAlignment   = 4;
110   ShortABIAlignment  = 2;
111   ByteABIAlignment  = 1;
112   BoolABIAlignment   = 1;
113   BoolPrefAlignment = BoolABIAlignment;
114   BytePrefAlignment = ByteABIAlignment;
115   ShortPrefAlignment = ShortABIAlignment;
116   IntPrefAlignment = IntABIAlignment;
117   LongPrefAlignment = 8;
118   FloatPrefAlignment = FloatABIAlignment;
119   DoublePrefAlignment = 8;
120   PointerPrefAlignment = PointerABIAlignment;
121   AggMinPrefAlignment = 0;
122   
123   while (!temp.empty()) {
124     std::string token = getToken(temp, "-");
125     
126     char signal = getToken(token, ":")[0];
127     
128     switch(signal) {
129     case 'E':
130       LittleEndian = false;
131       break;
132     case 'e':
133       LittleEndian = true;
134       break;
135     case 'p':
136       PointerMemSize = atoi(getToken(token,":").c_str()) / 8;
137       PointerABIAlignment = atoi(getToken(token,":").c_str()) / 8;
138       PointerPrefAlignment = atoi(getToken(token,":").c_str()) / 8;
139       if (PointerPrefAlignment == 0)
140         PointerPrefAlignment = PointerABIAlignment;
141       break;
142     case 'd':
143       DoubleABIAlignment = atoi(getToken(token,":").c_str()) / 8;
144       DoublePrefAlignment = atoi(getToken(token,":").c_str()) / 8;
145       if (DoublePrefAlignment == 0)
146         DoublePrefAlignment = DoubleABIAlignment;
147       break;
148     case 'f':
149       FloatABIAlignment = atoi(getToken(token, ":").c_str()) / 8;
150       FloatPrefAlignment = atoi(getToken(token,":").c_str()) / 8;
151       if (FloatPrefAlignment == 0)
152         FloatPrefAlignment = FloatABIAlignment;
153       break;
154     case 'l':
155       LongABIAlignment = atoi(getToken(token, ":").c_str()) / 8;
156       LongPrefAlignment = atoi(getToken(token,":").c_str()) / 8;
157       if (LongPrefAlignment == 0)
158         LongPrefAlignment = LongABIAlignment;
159       break;
160     case 'i':
161       IntABIAlignment = atoi(getToken(token, ":").c_str()) / 8;
162       IntPrefAlignment = atoi(getToken(token,":").c_str()) / 8;
163       if (IntPrefAlignment == 0)
164         IntPrefAlignment = IntABIAlignment;
165       break;
166     case 's':
167       ShortABIAlignment = atoi(getToken(token, ":").c_str()) / 8;
168       ShortPrefAlignment = atoi(getToken(token,":").c_str()) / 8;
169       if (ShortPrefAlignment == 0)
170         ShortPrefAlignment = ShortABIAlignment;
171       break;
172     case 'b':
173       ByteABIAlignment = atoi(getToken(token, ":").c_str()) / 8;
174       BytePrefAlignment = atoi(getToken(token,":").c_str()) / 8;
175       if (BytePrefAlignment == 0)
176         BytePrefAlignment = ByteABIAlignment;
177       break;
178     case 'B':
179       BoolABIAlignment = atoi(getToken(token, ":").c_str()) / 8;
180       BoolPrefAlignment = atoi(getToken(token,":").c_str()) / 8;
181       if (BoolPrefAlignment == 0)
182         BoolPrefAlignment = BoolABIAlignment;
183       break;
184     case 'A':
185       AggMinPrefAlignment = atoi(getToken(token,":").c_str()) / 8;
186       break;
187     default:
188       break;
189     }
190   }
191
192   // Unless explicitly specified, the alignments for longs and doubles is 
193   // capped by pointer size.
194   if (LongABIAlignment == 0)
195           LongABIAlignment = LongPrefAlignment = PointerMemSize;
196   if (DoubleABIAlignment == 0)
197     DoubleABIAlignment = DoublePrefAlignment = PointerMemSize;
198 }
199
200 TargetData::TargetData(const Module *M) {
201   init(M->getDataLayout());
202 }
203
204 /// Layouts - The lazy cache of structure layout information maintained by
205 /// TargetData.
206 ///
207 static std::map<std::pair<const TargetData*,const StructType*>,
208                 StructLayout> *Layouts = 0;
209
210
211 TargetData::~TargetData() {
212   if (Layouts) {
213     // Remove any layouts for this TD.
214     std::map<std::pair<const TargetData*,
215       const StructType*>, StructLayout>::iterator
216       I = Layouts->lower_bound(std::make_pair(this, (const StructType*)0));
217     while (I != Layouts->end() && I->first.first == this)
218       Layouts->erase(I++);
219     if (Layouts->empty()) {
220       delete Layouts;
221       Layouts = 0;
222     }
223   }
224 }
225
226 std::string TargetData::getStringRepresentation() const {
227   std::stringstream repr;
228   
229   if (LittleEndian)
230     repr << "e";
231   else
232     repr << "E";
233   
234   repr << "-p:" << (PointerMemSize * 8) << ":" << (PointerABIAlignment * 8);
235   repr << "-d:" << (DoubleABIAlignment * 8) << ":"
236        << (DoublePrefAlignment * 8);
237   repr << "-f:" << (FloatABIAlignment * 8) << ":"
238        << (FloatPrefAlignment * 8);
239   repr << "-l:" << (LongABIAlignment * 8) << ":"
240        << (LongPrefAlignment * 8);
241   repr << "-i:" << (IntABIAlignment * 8) << ":"
242        << (IntPrefAlignment * 8);
243   repr << "-s:" << (ShortABIAlignment * 8) << ":"
244        << (ShortPrefAlignment * 8);
245   repr << "-b:" << (ByteABIAlignment * 8) << ":"
246        << (BytePrefAlignment * 8);
247   repr << "-B:" << (BoolABIAlignment * 8) << ":"
248        << (BoolPrefAlignment * 8);
249   repr << "-A:" << (AggMinPrefAlignment * 8);
250   
251   return repr.str();
252 }
253
254 const StructLayout *TargetData::getStructLayout(const StructType *Ty) const {
255   if (Layouts == 0)
256     Layouts = new std::map<std::pair<const TargetData*,const StructType*>,
257                            StructLayout>();
258   std::map<std::pair<const TargetData*,const StructType*>,
259                      StructLayout>::iterator
260     I = Layouts->lower_bound(std::make_pair(this, Ty));
261   if (I != Layouts->end() && I->first.first == this && I->first.second == Ty)
262     return &I->second;
263   else {
264     return &Layouts->insert(I, std::make_pair(std::make_pair(this, Ty),
265                                               StructLayout(Ty, *this)))->second;
266   }
267 }
268
269 /// InvalidateStructLayoutInfo - TargetData speculatively caches StructLayout
270 /// objects.  If a TargetData object is alive when types are being refined and
271 /// removed, this method must be called whenever a StructType is removed to
272 /// avoid a dangling pointer in this cache.
273 void TargetData::InvalidateStructLayoutInfo(const StructType *Ty) const {
274   if (!Layouts) return;  // No cache.
275
276   std::map<std::pair<const TargetData*,const StructType*>,
277            StructLayout>::iterator I = Layouts->find(std::make_pair(this, Ty));
278   if (I != Layouts->end())
279     Layouts->erase(I);
280 }
281
282
283
284 static inline void getTypeInfoABI(const Type *Ty, const TargetData *TD,
285                                   uint64_t &Size, unsigned char &Alignment) {
286   assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!");
287   switch (Ty->getTypeID()) {
288   case Type::IntegerTyID: {
289     unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
290     if (BitWidth <= 8) {
291       Size = 1; Alignment = TD->getByteABIAlignment();
292     } else if (BitWidth <= 16) {
293       Size = 2; Alignment = TD->getShortABIAlignment();
294     } else if (BitWidth <= 32) {
295       Size = 4; Alignment = TD->getIntABIAlignment();
296     } else if (BitWidth <= 64) {
297       Size = 8; Alignment = TD->getLongABIAlignment();
298     } else {
299       Size = ((BitWidth + 7) / 8) & ~1;
300       Alignment = TD->getLongABIAlignment();
301     }
302     return;
303   }
304   case Type::VoidTyID:   Size = 1; Alignment = TD->getByteABIAlignment(); return;
305   case Type::FloatTyID:  Size = 4; Alignment = TD->getFloatABIAlignment(); return;
306   case Type::DoubleTyID: Size = 8; Alignment = TD->getDoubleABIAlignment(); return;
307   case Type::LabelTyID:
308   case Type::PointerTyID:
309     Size = TD->getPointerSize(); Alignment = TD->getPointerABIAlignment();
310     return;
311   case Type::ArrayTyID: {
312     const ArrayType *ATy = cast<ArrayType>(Ty);
313     getTypeInfoABI(ATy->getElementType(), TD, Size, Alignment);
314     unsigned AlignedSize = (Size + Alignment - 1)/Alignment*Alignment;
315     Size = AlignedSize*ATy->getNumElements();
316     return;
317   }
318   case Type::PackedTyID: {
319     const PackedType *PTy = cast<PackedType>(Ty);
320     getTypeInfoABI(PTy->getElementType(), TD, Size, Alignment);
321     unsigned AlignedSize = (Size + Alignment - 1)/Alignment*Alignment;
322     Size = AlignedSize*PTy->getNumElements();
323     // FIXME: The alignments of specific packed types are target dependent.
324     // For now, just set it to be equal to Size.
325     Alignment = Size;
326     return;
327   }
328   case Type::StructTyID: {
329     // Get the layout annotation... which is lazily created on demand.
330     const StructLayout *Layout = TD->getStructLayout(cast<StructType>(Ty));
331     Size = Layout->StructSize; Alignment = Layout->StructAlignment;
332     return;
333   }
334
335   default:
336     assert(0 && "Bad type for getTypeInfo!!!");
337     return;
338   }
339 }
340
341 static inline void getTypeInfoPref(const Type *Ty, const TargetData *TD,
342                                    uint64_t &Size, unsigned char &Alignment) {
343   assert(Ty->isSized() && "Cannot getTypeInfoPref() on a type that is unsized!");
344   switch (Ty->getTypeID()) {
345   case Type::IntegerTyID: {
346     unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
347     if (BitWidth <= 8) {
348       Size = 1; Alignment = TD->getBytePrefAlignment();
349     } else if (BitWidth <= 16) {
350       Size = 2; Alignment = TD->getShortPrefAlignment();
351     } else if (BitWidth <= 32) {
352       Size = 4; Alignment = TD->getIntPrefAlignment();
353     } else if (BitWidth <= 64) {
354       Size = 8; Alignment = TD->getLongPrefAlignment();
355     } else
356       assert(0 && "Integer types > 64 bits not supported.");
357     return;
358   }
359   case Type::VoidTyID:
360     Size = 1; Alignment = TD->getBytePrefAlignment();
361     return;
362   case Type::FloatTyID:
363     Size = 4; Alignment = TD->getFloatPrefAlignment();
364     return;
365   case Type::DoubleTyID:
366     Size = 8; Alignment = TD->getDoublePrefAlignment();
367     return;
368   case Type::LabelTyID:
369   case Type::PointerTyID:
370     Size = TD->getPointerSize(); Alignment = TD->getPointerPrefAlignment();
371     return;
372   case Type::ArrayTyID: {
373     const ArrayType *ATy = cast<ArrayType>(Ty);
374     getTypeInfoPref(ATy->getElementType(), TD, Size, Alignment);
375     unsigned AlignedSize = (Size + Alignment - 1)/Alignment*Alignment;
376     Size = AlignedSize*ATy->getNumElements();
377     return;
378   }
379   case Type::PackedTyID: {
380     const PackedType *PTy = cast<PackedType>(Ty);
381     getTypeInfoPref(PTy->getElementType(), TD, Size, Alignment);
382     unsigned AlignedSize = (Size + Alignment - 1)/Alignment*Alignment;
383     Size = AlignedSize*PTy->getNumElements();
384     // FIXME: The alignments of specific packed types are target dependent.
385     // For now, just set it to be equal to Size.
386     Alignment = Size;
387     return;
388   }
389   case Type::StructTyID: {
390     // Get the layout annotation... which is lazily created on demand;
391     // enforce minimum aggregate alignment.
392     const StructLayout *Layout = TD->getStructLayout(cast<StructType>(Ty));
393     Size = Layout->StructSize;
394     Alignment = std::max(Layout->StructAlignment,
395                          (const unsigned int) TD->getAggMinPrefAlignment());
396     return;
397   }
398
399   default:
400     assert(0 && "Bad type for getTypeInfoPref!!!");
401     return;
402   }
403 }
404
405
406 uint64_t TargetData::getTypeSize(const Type *Ty) const {
407   uint64_t Size;
408   unsigned char Align;
409   getTypeInfoABI(Ty, this, Size, Align);
410   return Size;
411 }
412
413 uint64_t TargetData::getTypeSizeInBits(const Type *Ty) const {
414   if (Ty->isInteger())
415     return cast<IntegerType>(Ty)->getBitWidth();
416
417   uint64_t Size;
418   unsigned char Align;
419   getTypeInfoABI(Ty, this, Size, Align);
420   return Size * 8;
421 }
422
423 unsigned char TargetData::getTypeAlignmentABI(const Type *Ty) const {
424   uint64_t Size;
425   unsigned char Align;
426   getTypeInfoABI(Ty, this, Size, Align);
427   return Align;
428 }
429
430 unsigned char TargetData::getTypeAlignmentPref(const Type *Ty) const {
431   uint64_t Size;
432   unsigned char Align;
433   getTypeInfoPref(Ty, this, Size, Align);
434   return Align;
435 }
436
437 unsigned char TargetData::getPreferredTypeAlignmentShift(const Type *Ty) const {
438   unsigned Align = getTypeAlignmentPref(Ty);
439   assert(!(Align & (Align-1)) && "Alignment is not a power of two!");
440   return Log2_32(Align);
441 }
442
443 /// getIntPtrType - Return an unsigned integer type that is the same size or
444 /// greater to the host pointer size.
445 const Type *TargetData::getIntPtrType() const {
446   switch (getPointerSize()) {
447   default: assert(0 && "Unknown pointer size!");
448   case 2: return Type::Int16Ty;
449   case 4: return Type::Int32Ty;
450   case 8: return Type::Int64Ty;
451   }
452 }
453
454
455 uint64_t TargetData::getIndexedOffset(const Type *ptrTy,
456                                       const std::vector<Value*> &Idx) const {
457   const Type *Ty = ptrTy;
458   assert(isa<PointerType>(Ty) && "Illegal argument for getIndexedOffset()");
459   uint64_t Result = 0;
460
461   generic_gep_type_iterator<std::vector<Value*>::const_iterator>
462     TI = gep_type_begin(ptrTy, Idx.begin(), Idx.end());
463   for (unsigned CurIDX = 0; CurIDX != Idx.size(); ++CurIDX, ++TI) {
464     if (const StructType *STy = dyn_cast<StructType>(*TI)) {
465       assert(Idx[CurIDX]->getType() == Type::Int32Ty && "Illegal struct idx");
466       unsigned FieldNo = cast<ConstantInt>(Idx[CurIDX])->getZExtValue();
467
468       // Get structure layout information...
469       const StructLayout *Layout = getStructLayout(STy);
470
471       // Add in the offset, as calculated by the structure layout info...
472       assert(FieldNo < Layout->MemberOffsets.size() &&"FieldNo out of range!");
473       Result += Layout->MemberOffsets[FieldNo];
474
475       // Update Ty to refer to current element
476       Ty = STy->getElementType(FieldNo);
477     } else {
478       // Update Ty to refer to current element
479       Ty = cast<SequentialType>(Ty)->getElementType();
480
481       // Get the array index and the size of each array element.
482       int64_t arrayIdx = cast<ConstantInt>(Idx[CurIDX])->getSExtValue();
483       Result += arrayIdx * (int64_t)getTypeSize(Ty);
484     }
485   }
486
487   return Result;
488 }
489
490 /// getPreferredAlignmentLog - Return the preferred alignment of the
491 /// specified global, returned in log form.  This includes an explicitly
492 /// requested alignment (if the global has one).
493 unsigned TargetData::getPreferredAlignmentLog(const GlobalVariable *GV) const {
494   const Type *ElemType = GV->getType()->getElementType();
495   unsigned Alignment = getPreferredTypeAlignmentShift(ElemType);
496   if (GV->getAlignment() > (1U << Alignment))
497     Alignment = Log2_32(GV->getAlignment());
498   
499   if (GV->hasInitializer()) {
500     if (Alignment < 4) {
501       // If the global is not external, see if it is large.  If so, give it a
502       // larger alignment.
503       if (getTypeSize(ElemType) > 128)
504         Alignment = 4;    // 16-byte alignment.
505     }
506   }
507   return Alignment;
508 }
509