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