1 //===-- TargetData.cpp - Data size & alignment routines --------------------==//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This file defines target properties related to datatype size/offset/alignment
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.
17 //===----------------------------------------------------------------------===//
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"
31 // Handle the Pass registration stuff necessary to use TargetData's.
33 // Register the default SparcV9 implementation...
34 RegisterPass<TargetData> X("targetdata", "Target Data Layout");
37 static inline void getTypeInfoABI(const Type *Ty, const TargetData *TD,
38 uint64_t &Size, unsigned char &Alignment);
40 static inline void getTypeInfoPref(const Type *Ty, const TargetData *TD,
41 uint64_t &Size, unsigned char &Alignment);
43 //===----------------------------------------------------------------------===//
44 // Support for StructLayout
45 //===----------------------------------------------------------------------===//
47 StructLayout::StructLayout(const StructType *ST, const TargetData &TD) {
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) {
58 getTypeInfoABI(Ty, &TD, TySize, A);
59 TyAlign = ST->isPacked() ? 1 : A;
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...
65 // Keep track of maximum alignment constraint
66 StructAlignment = std::max(TyAlign, StructAlignment);
68 MemberOffsets.push_back(StructSize);
69 StructSize += TySize; // Consume space for this data item
72 // Empty structures have alignment of 1 byte.
73 if (StructAlignment == 0) StructAlignment = 1;
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;
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!");
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();
96 //===----------------------------------------------------------------------===//
97 // TargetData Class Implementation
98 //===----------------------------------------------------------------------===//
100 void TargetData::init(const std::string &TargetDescription) {
101 std::string temp = TargetDescription;
103 LittleEndian = false;
105 PointerABIAlignment = 8;
106 DoubleABIAlignment = 8;
107 FloatABIAlignment = 4;
108 LongABIAlignment = 8;
110 ShortABIAlignment = 2;
111 ByteABIAlignment = 1;
112 BoolABIAlignment = 1;
113 BoolPrefAlignment = BoolABIAlignment;
114 BytePrefAlignment = ByteABIAlignment;
115 ShortPrefAlignment = ShortABIAlignment;
116 IntPrefAlignment = IntABIAlignment;
117 LongPrefAlignment = LongABIAlignment;
118 FloatPrefAlignment = FloatABIAlignment;
119 DoublePrefAlignment = DoubleABIAlignment;
120 PointerPrefAlignment = PointerABIAlignment;
121 AggMinPrefAlignment = 0;
123 while (!temp.empty()) {
124 std::string token = getToken(temp, "-");
126 char signal = getToken(token, ":")[0];
130 LittleEndian = false;
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;
143 DoubleABIAlignment = atoi(getToken(token,":").c_str()) / 8;
144 DoublePrefAlignment = atoi(getToken(token,":").c_str()) / 8;
145 if (DoublePrefAlignment == 0)
146 DoublePrefAlignment = DoubleABIAlignment;
149 FloatABIAlignment = atoi(getToken(token, ":").c_str()) / 8;
150 FloatPrefAlignment = atoi(getToken(token,":").c_str()) / 8;
151 if (FloatPrefAlignment == 0)
152 FloatPrefAlignment = FloatABIAlignment;
155 LongABIAlignment = atoi(getToken(token, ":").c_str()) / 8;
156 LongPrefAlignment = atoi(getToken(token,":").c_str()) / 8;
157 if (LongPrefAlignment == 0)
158 LongPrefAlignment = LongABIAlignment;
161 IntABIAlignment = atoi(getToken(token, ":").c_str()) / 8;
162 IntPrefAlignment = atoi(getToken(token,":").c_str()) / 8;
163 if (IntPrefAlignment == 0)
164 IntPrefAlignment = IntABIAlignment;
167 ShortABIAlignment = atoi(getToken(token, ":").c_str()) / 8;
168 ShortPrefAlignment = atoi(getToken(token,":").c_str()) / 8;
169 if (ShortPrefAlignment == 0)
170 ShortPrefAlignment = ShortABIAlignment;
173 ByteABIAlignment = atoi(getToken(token, ":").c_str()) / 8;
174 BytePrefAlignment = atoi(getToken(token,":").c_str()) / 8;
175 if (BytePrefAlignment == 0)
176 BytePrefAlignment = ByteABIAlignment;
179 BoolABIAlignment = atoi(getToken(token, ":").c_str()) / 8;
180 BoolPrefAlignment = atoi(getToken(token,":").c_str()) / 8;
181 if (BoolPrefAlignment == 0)
182 BoolPrefAlignment = BoolABIAlignment;
185 AggMinPrefAlignment = atoi(getToken(token,":").c_str()) / 8;
193 TargetData::TargetData(const Module *M) {
194 LittleEndian = M->getEndianness() != Module::BigEndian;
195 PointerMemSize = M->getPointerSize() != Module::Pointer64 ? 4 : 8;
196 PointerABIAlignment = PointerMemSize;
197 DoubleABIAlignment = PointerMemSize;
198 FloatABIAlignment = 4;
199 LongABIAlignment = PointerMemSize;
201 ShortABIAlignment = 2;
202 ByteABIAlignment = 1;
203 BoolABIAlignment = 1;
204 BoolPrefAlignment = BoolABIAlignment;
205 BytePrefAlignment = ByteABIAlignment;
206 ShortPrefAlignment = ShortABIAlignment;
207 IntPrefAlignment = IntABIAlignment;
208 LongPrefAlignment = LongABIAlignment;
209 FloatPrefAlignment = FloatABIAlignment;
210 DoublePrefAlignment = DoubleABIAlignment;
211 PointerPrefAlignment = PointerABIAlignment;
212 AggMinPrefAlignment = 0;
215 /// Layouts - The lazy cache of structure layout information maintained by
218 static std::map<std::pair<const TargetData*,const StructType*>,
219 StructLayout> *Layouts = 0;
222 TargetData::~TargetData() {
224 // Remove any layouts for this TD.
225 std::map<std::pair<const TargetData*,
226 const StructType*>, StructLayout>::iterator
227 I = Layouts->lower_bound(std::make_pair(this, (const StructType*)0));
228 while (I != Layouts->end() && I->first.first == this)
230 if (Layouts->empty()) {
237 std::string TargetData::getStringRepresentation() const {
238 std::stringstream repr;
245 repr << "-p:" << (PointerMemSize * 8) << ":" << (PointerABIAlignment * 8);
246 repr << "-d:" << (DoubleABIAlignment * 8) << ":"
247 << (DoublePrefAlignment * 8);
248 repr << "-f:" << (FloatABIAlignment * 8) << ":"
249 << (FloatPrefAlignment * 8);
250 repr << "-l:" << (LongABIAlignment * 8) << ":"
251 << (LongPrefAlignment * 8);
252 repr << "-i:" << (IntABIAlignment * 8) << ":"
253 << (IntPrefAlignment * 8);
254 repr << "-s:" << (ShortABIAlignment * 8) << ":"
255 << (ShortPrefAlignment * 8);
256 repr << "-b:" << (ByteABIAlignment * 8) << ":"
257 << (BytePrefAlignment * 8);
258 repr << "-B:" << (BoolABIAlignment * 8) << ":"
259 << (BoolPrefAlignment * 8);
260 repr << "-A:" << (AggMinPrefAlignment * 8);
265 const StructLayout *TargetData::getStructLayout(const StructType *Ty) const {
267 Layouts = new std::map<std::pair<const TargetData*,const StructType*>,
269 std::map<std::pair<const TargetData*,const StructType*>,
270 StructLayout>::iterator
271 I = Layouts->lower_bound(std::make_pair(this, Ty));
272 if (I != Layouts->end() && I->first.first == this && I->first.second == Ty)
275 return &Layouts->insert(I, std::make_pair(std::make_pair(this, Ty),
276 StructLayout(Ty, *this)))->second;
280 /// InvalidateStructLayoutInfo - TargetData speculatively caches StructLayout
281 /// objects. If a TargetData object is alive when types are being refined and
282 /// removed, this method must be called whenever a StructType is removed to
283 /// avoid a dangling pointer in this cache.
284 void TargetData::InvalidateStructLayoutInfo(const StructType *Ty) const {
285 if (!Layouts) return; // No cache.
287 std::map<std::pair<const TargetData*,const StructType*>,
288 StructLayout>::iterator I = Layouts->find(std::make_pair(this, Ty));
289 if (I != Layouts->end())
295 static inline void getTypeInfoABI(const Type *Ty, const TargetData *TD,
296 uint64_t &Size, unsigned char &Alignment) {
297 assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!");
298 switch (Ty->getTypeID()) {
299 case Type::IntegerTyID: {
300 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
302 Size = 1; Alignment = TD->getByteABIAlignment();
303 } else if (BitWidth <= 16) {
304 Size = 2; Alignment = TD->getShortABIAlignment();
305 } else if (BitWidth <= 32) {
306 Size = 4; Alignment = TD->getIntABIAlignment();
307 } else if (BitWidth <= 64) {
308 Size = 8; Alignment = TD->getLongABIAlignment();
310 assert(0 && "Integer types > 64 bits not supported.");
313 case Type::VoidTyID: Size = 1; Alignment = TD->getByteABIAlignment(); return;
314 case Type::FloatTyID: Size = 4; Alignment = TD->getFloatABIAlignment(); return;
315 case Type::DoubleTyID: Size = 8; Alignment = TD->getDoubleABIAlignment(); return;
316 case Type::LabelTyID:
317 case Type::PointerTyID:
318 Size = TD->getPointerSize(); Alignment = TD->getPointerABIAlignment();
320 case Type::ArrayTyID: {
321 const ArrayType *ATy = cast<ArrayType>(Ty);
322 getTypeInfoABI(ATy->getElementType(), TD, Size, Alignment);
323 unsigned AlignedSize = (Size + Alignment - 1)/Alignment*Alignment;
324 Size = AlignedSize*ATy->getNumElements();
327 case Type::PackedTyID: {
328 const PackedType *PTy = cast<PackedType>(Ty);
329 getTypeInfoABI(PTy->getElementType(), TD, Size, Alignment);
330 unsigned AlignedSize = (Size + Alignment - 1)/Alignment*Alignment;
331 Size = AlignedSize*PTy->getNumElements();
332 // FIXME: The alignments of specific packed types are target dependent.
333 // For now, just set it to be equal to Size.
337 case Type::StructTyID: {
338 // Get the layout annotation... which is lazily created on demand.
339 const StructLayout *Layout = TD->getStructLayout(cast<StructType>(Ty));
340 Size = Layout->StructSize; Alignment = Layout->StructAlignment;
345 assert(0 && "Bad type for getTypeInfo!!!");
350 static inline void getTypeInfoPref(const Type *Ty, const TargetData *TD,
351 uint64_t &Size, unsigned char &Alignment) {
352 assert(Ty->isSized() && "Cannot getTypeInfoPref() on a type that is unsized!");
353 switch (Ty->getTypeID()) {
354 case Type::IntegerTyID: {
355 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
357 Size = 1; Alignment = TD->getBytePrefAlignment();
358 } else if (BitWidth <= 16) {
359 Size = 2; Alignment = TD->getShortPrefAlignment();
360 } else if (BitWidth <= 32) {
361 Size = 4; Alignment = TD->getIntPrefAlignment();
362 } else if (BitWidth <= 64) {
363 Size = 8; Alignment = TD->getLongPrefAlignment();
365 assert(0 && "Integer types > 64 bits not supported.");
369 Size = 1; Alignment = TD->getBytePrefAlignment();
371 case Type::FloatTyID:
372 Size = 4; Alignment = TD->getFloatPrefAlignment();
374 case Type::DoubleTyID:
375 Size = 8; Alignment = TD->getDoublePrefAlignment();
377 case Type::LabelTyID:
378 case Type::PointerTyID:
379 Size = TD->getPointerSize(); Alignment = TD->getPointerPrefAlignment();
381 case Type::ArrayTyID: {
382 const ArrayType *ATy = cast<ArrayType>(Ty);
383 getTypeInfoPref(ATy->getElementType(), TD, Size, Alignment);
384 unsigned AlignedSize = (Size + Alignment - 1)/Alignment*Alignment;
385 Size = AlignedSize*ATy->getNumElements();
388 case Type::PackedTyID: {
389 const PackedType *PTy = cast<PackedType>(Ty);
390 getTypeInfoPref(PTy->getElementType(), TD, Size, Alignment);
391 unsigned AlignedSize = (Size + Alignment - 1)/Alignment*Alignment;
392 Size = AlignedSize*PTy->getNumElements();
393 // FIXME: The alignments of specific packed types are target dependent.
394 // For now, just set it to be equal to Size.
398 case Type::StructTyID: {
399 // Get the layout annotation... which is lazily created on demand;
400 // enforce minimum aggregate alignment.
401 const StructLayout *Layout = TD->getStructLayout(cast<StructType>(Ty));
402 Size = Layout->StructSize;
403 Alignment = std::max(Layout->StructAlignment,
404 (const unsigned int) TD->getAggMinPrefAlignment());
409 assert(0 && "Bad type for getTypeInfoPref!!!");
415 uint64_t TargetData::getTypeSize(const Type *Ty) const {
418 getTypeInfoABI(Ty, this, Size, Align);
422 unsigned char TargetData::getTypeAlignmentABI(const Type *Ty) const {
425 getTypeInfoABI(Ty, this, Size, Align);
429 unsigned char TargetData::getTypeAlignmentPref(const Type *Ty) const {
432 getTypeInfoPref(Ty, this, Size, Align);
436 unsigned char TargetData::getTypeAlignmentShift(const Type *Ty) const {
437 unsigned Align = getTypeAlignmentABI(Ty);
438 assert(!(Align & (Align-1)) && "Alignment is not a power of two!");
439 return Log2_32(Align);
442 /// getIntPtrType - Return an unsigned integer type that is the same size or
443 /// greater to the host pointer size.
444 const Type *TargetData::getIntPtrType() const {
445 switch (getPointerSize()) {
446 default: assert(0 && "Unknown pointer size!");
447 case 2: return Type::Int16Ty;
448 case 4: return Type::Int32Ty;
449 case 8: return Type::Int64Ty;
454 uint64_t TargetData::getIndexedOffset(const Type *ptrTy,
455 const std::vector<Value*> &Idx) const {
456 const Type *Ty = ptrTy;
457 assert(isa<PointerType>(Ty) && "Illegal argument for getIndexedOffset()");
460 generic_gep_type_iterator<std::vector<Value*>::const_iterator>
461 TI = gep_type_begin(ptrTy, Idx.begin(), Idx.end());
462 for (unsigned CurIDX = 0; CurIDX != Idx.size(); ++CurIDX, ++TI) {
463 if (const StructType *STy = dyn_cast<StructType>(*TI)) {
464 assert(Idx[CurIDX]->getType() == Type::Int32Ty && "Illegal struct idx");
465 unsigned FieldNo = cast<ConstantInt>(Idx[CurIDX])->getZExtValue();
467 // Get structure layout information...
468 const StructLayout *Layout = getStructLayout(STy);
470 // Add in the offset, as calculated by the structure layout info...
471 assert(FieldNo < Layout->MemberOffsets.size() &&"FieldNo out of range!");
472 Result += Layout->MemberOffsets[FieldNo];
474 // Update Ty to refer to current element
475 Ty = STy->getElementType(FieldNo);
477 // Update Ty to refer to current element
478 Ty = cast<SequentialType>(Ty)->getElementType();
480 // Get the array index and the size of each array element.
481 int64_t arrayIdx = cast<ConstantInt>(Idx[CurIDX])->getSExtValue();
482 Result += arrayIdx * (int64_t)getTypeSize(Ty);
489 /// getPreferredAlignmentLog - Return the preferred alignment of the
490 /// specified global, returned in log form. This includes an explicitly
491 /// requested alignment (if the global has one).
492 unsigned TargetData::getPreferredAlignmentLog(const GlobalVariable *GV) const {
493 const Type *ElemType = GV->getType()->getElementType();
494 unsigned Alignment = getTypeAlignmentShift(ElemType);
495 if (GV->getAlignment() > (1U << Alignment))
496 Alignment = Log2_32(GV->getAlignment());
498 if (GV->hasInitializer()) {
499 // Always round up alignment of global doubles to 8 bytes.
500 if (GV->getType()->getElementType() == Type::DoubleTy && Alignment < 3)
503 // If the global is not external, see if it is large. If so, give it a
505 if (getTypeSize(ElemType) > 128)
506 Alignment = 4; // 16-byte alignment.