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/Support/ManagedStatic.h"
26 #include "llvm/ADT/StringExtras.h"
32 // Handle the Pass registration stuff necessary to use TargetData's.
34 // Register the default SparcV9 implementation...
35 RegisterPass<TargetData> X("targetdata", "Target Data Layout");
38 static inline void getTypeInfoABI(const Type *Ty, const TargetData *TD,
39 uint64_t &Size, unsigned char &Alignment);
41 static inline void getTypeInfoPref(const Type *Ty, const TargetData *TD,
42 uint64_t &Size, unsigned char &Alignment);
44 //===----------------------------------------------------------------------===//
45 // Support for StructLayout
46 //===----------------------------------------------------------------------===//
48 StructLayout::StructLayout(const StructType *ST, const TargetData &TD) {
51 NumElements = ST->getNumElements();
53 // Loop over each of the elements, placing them in memory...
54 for (unsigned i = 0, e = NumElements; i != e; ++i) {
55 const Type *Ty = ST->getElementType(i);
59 getTypeInfoABI(Ty, &TD, TySize, A);
60 TyAlign = ST->isPacked() ? 1 : A;
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...
66 // Keep track of maximum alignment constraint
67 StructAlignment = std::max(TyAlign, StructAlignment);
69 MemberOffsets[i] = StructSize;
70 StructSize += TySize; // Consume space for this data item
73 // Empty structures have alignment of 1 byte.
74 if (StructAlignment == 0) StructAlignment = 1;
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;
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 {
87 std::upper_bound(&MemberOffsets[0], &MemberOffsets[NumElements], Offset);
88 assert(SI != &MemberOffsets[0] && "Offset not in structure type!");
90 assert(*SI <= Offset && "upper_bound didn't work");
91 assert((SI == &MemberOffsets[0] || *(SI-1) < Offset) &&
92 (SI+1 == &MemberOffsets[NumElements] || *(SI+1) > Offset) &&
93 "Upper bound didn't work!");
94 return SI-&MemberOffsets[0];
97 //===----------------------------------------------------------------------===//
98 // TargetData Class Implementation
99 //===----------------------------------------------------------------------===//
101 void TargetData::init(const std::string &TargetDescription) {
102 std::string temp = TargetDescription;
104 LittleEndian = false;
106 PointerABIAlignment = 8;
107 DoubleABIAlignment = 0;
108 FloatABIAlignment = 4;
109 LongABIAlignment = 0;
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;
124 while (!temp.empty()) {
125 std::string token = getToken(temp, "-");
127 char signal = getToken(token, ":")[0];
131 LittleEndian = false;
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;
144 DoubleABIAlignment = atoi(getToken(token,":").c_str()) / 8;
145 DoublePrefAlignment = atoi(getToken(token,":").c_str()) / 8;
146 if (DoublePrefAlignment == 0)
147 DoublePrefAlignment = DoubleABIAlignment;
150 FloatABIAlignment = atoi(getToken(token, ":").c_str()) / 8;
151 FloatPrefAlignment = atoi(getToken(token,":").c_str()) / 8;
152 if (FloatPrefAlignment == 0)
153 FloatPrefAlignment = FloatABIAlignment;
156 LongABIAlignment = atoi(getToken(token, ":").c_str()) / 8;
157 LongPrefAlignment = atoi(getToken(token,":").c_str()) / 8;
158 if (LongPrefAlignment == 0)
159 LongPrefAlignment = LongABIAlignment;
162 IntABIAlignment = atoi(getToken(token, ":").c_str()) / 8;
163 IntPrefAlignment = atoi(getToken(token,":").c_str()) / 8;
164 if (IntPrefAlignment == 0)
165 IntPrefAlignment = IntABIAlignment;
168 ShortABIAlignment = atoi(getToken(token, ":").c_str()) / 8;
169 ShortPrefAlignment = atoi(getToken(token,":").c_str()) / 8;
170 if (ShortPrefAlignment == 0)
171 ShortPrefAlignment = ShortABIAlignment;
174 ByteABIAlignment = atoi(getToken(token, ":").c_str()) / 8;
175 BytePrefAlignment = atoi(getToken(token,":").c_str()) / 8;
176 if (BytePrefAlignment == 0)
177 BytePrefAlignment = ByteABIAlignment;
180 BoolABIAlignment = atoi(getToken(token, ":").c_str()) / 8;
181 BoolPrefAlignment = atoi(getToken(token,":").c_str()) / 8;
182 if (BoolPrefAlignment == 0)
183 BoolPrefAlignment = BoolABIAlignment;
186 AggMinPrefAlignment = atoi(getToken(token,":").c_str()) / 8;
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;
201 TargetData::TargetData(const Module *M) {
202 init(M->getDataLayout());
205 /// LayoutInfo - The lazy cache of structure layout information maintained by
206 /// TargetData. Note that the struct types must have been free'd before
207 /// llvm_shutdown is called (and thus this is deallocated) because all the
208 /// targets with cached elements should have been destroyed.
210 typedef std::pair<const TargetData*,const StructType*> LayoutKey;
211 static ManagedStatic<std::map<LayoutKey, StructLayout*> > LayoutInfo;
214 TargetData::~TargetData() {
215 if (LayoutInfo.isConstructed()) {
216 // Remove any layouts for this TD.
217 std::map<LayoutKey, StructLayout*> &TheMap = *LayoutInfo;
218 std::map<LayoutKey, StructLayout*>::iterator
219 I = TheMap.lower_bound(LayoutKey(this, (const StructType*)0));
221 for (std::map<LayoutKey, StructLayout*>::iterator E = TheMap.end();
222 I != E && I->first.first == this; ) {
223 I->second->~StructLayout();
230 const StructLayout *TargetData::getStructLayout(const StructType *Ty) const {
231 std::map<LayoutKey, StructLayout*> &TheMap = *LayoutInfo;
233 std::map<LayoutKey, StructLayout*>::iterator
234 I = TheMap.lower_bound(LayoutKey(this, Ty));
235 if (I != TheMap.end() && I->first.first == this && I->first.second == Ty)
238 // Otherwise, create the struct layout. Because it is variable length, we
239 // malloc it, then use placement new.
240 unsigned NumElts = Ty->getNumElements();
242 (StructLayout *)malloc(sizeof(StructLayout)+(NumElts-1)*sizeof(uint64_t));
243 new (L) StructLayout(Ty, *this);
245 TheMap.insert(I, std::make_pair(LayoutKey(this, Ty), L));
249 /// InvalidateStructLayoutInfo - TargetData speculatively caches StructLayout
250 /// objects. If a TargetData object is alive when types are being refined and
251 /// removed, this method must be called whenever a StructType is removed to
252 /// avoid a dangling pointer in this cache.
253 void TargetData::InvalidateStructLayoutInfo(const StructType *Ty) const {
254 if (!LayoutInfo.isConstructed()) return; // No cache.
256 std::map<LayoutKey, StructLayout*>::iterator I =
257 LayoutInfo->find(LayoutKey(this, Ty));
258 if (I != LayoutInfo->end()) {
259 I->second->~StructLayout();
261 LayoutInfo->erase(I);
266 std::string TargetData::getStringRepresentation() const {
267 std::stringstream repr;
274 repr << "-p:" << (PointerMemSize * 8) << ":" << (PointerABIAlignment * 8);
275 repr << "-d:" << (DoubleABIAlignment * 8) << ":"
276 << (DoublePrefAlignment * 8);
277 repr << "-f:" << (FloatABIAlignment * 8) << ":"
278 << (FloatPrefAlignment * 8);
279 repr << "-l:" << (LongABIAlignment * 8) << ":"
280 << (LongPrefAlignment * 8);
281 repr << "-i:" << (IntABIAlignment * 8) << ":"
282 << (IntPrefAlignment * 8);
283 repr << "-s:" << (ShortABIAlignment * 8) << ":"
284 << (ShortPrefAlignment * 8);
285 repr << "-b:" << (ByteABIAlignment * 8) << ":"
286 << (BytePrefAlignment * 8);
287 repr << "-B:" << (BoolABIAlignment * 8) << ":"
288 << (BoolPrefAlignment * 8);
289 repr << "-A:" << (AggMinPrefAlignment * 8);
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 Size = ((BitWidth + 7) / 8) & ~1;
311 Alignment = TD->getLongABIAlignment();
315 case Type::VoidTyID: Size = 1; Alignment = TD->getByteABIAlignment(); return;
316 case Type::FloatTyID: Size = 4; Alignment = TD->getFloatABIAlignment(); return;
317 case Type::DoubleTyID: Size = 8; Alignment = TD->getDoubleABIAlignment(); return;
318 case Type::LabelTyID:
319 case Type::PointerTyID:
320 Size = TD->getPointerSize(); Alignment = TD->getPointerABIAlignment();
322 case Type::ArrayTyID: {
323 const ArrayType *ATy = cast<ArrayType>(Ty);
324 getTypeInfoABI(ATy->getElementType(), TD, Size, Alignment);
325 unsigned AlignedSize = (Size + Alignment - 1)/Alignment*Alignment;
326 Size = AlignedSize*ATy->getNumElements();
329 case Type::PackedTyID: {
330 const PackedType *PTy = cast<PackedType>(Ty);
331 getTypeInfoABI(PTy->getElementType(), TD, Size, Alignment);
332 unsigned AlignedSize = (Size + Alignment - 1)/Alignment*Alignment;
333 Size = AlignedSize*PTy->getNumElements();
334 // FIXME: The alignments of specific packed types are target dependent.
335 // For now, just set it to be equal to Size.
339 case Type::StructTyID: {
340 // Get the layout annotation... which is lazily created on demand.
341 const StructLayout *Layout = TD->getStructLayout(cast<StructType>(Ty));
342 Size = Layout->getSizeInBytes(); Alignment = Layout->getAlignment();
347 assert(0 && "Bad type for getTypeInfo!!!");
352 static inline void getTypeInfoPref(const Type *Ty, const TargetData *TD,
353 uint64_t &Size, unsigned char &Alignment) {
354 assert(Ty->isSized() && "Cannot getTypeInfoPref() on a type that is unsized!");
355 switch (Ty->getTypeID()) {
356 case Type::IntegerTyID: {
357 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
359 Size = 1; Alignment = TD->getBytePrefAlignment();
360 } else if (BitWidth <= 16) {
361 Size = 2; Alignment = TD->getShortPrefAlignment();
362 } else if (BitWidth <= 32) {
363 Size = 4; Alignment = TD->getIntPrefAlignment();
364 } else if (BitWidth <= 64) {
365 Size = 8; Alignment = TD->getLongPrefAlignment();
367 assert(0 && "Integer types > 64 bits not supported.");
371 Size = 1; Alignment = TD->getBytePrefAlignment();
373 case Type::FloatTyID:
374 Size = 4; Alignment = TD->getFloatPrefAlignment();
376 case Type::DoubleTyID:
377 Size = 8; Alignment = TD->getDoublePrefAlignment();
379 case Type::LabelTyID:
380 case Type::PointerTyID:
381 Size = TD->getPointerSize(); Alignment = TD->getPointerPrefAlignment();
383 case Type::ArrayTyID: {
384 const ArrayType *ATy = cast<ArrayType>(Ty);
385 getTypeInfoPref(ATy->getElementType(), TD, Size, Alignment);
386 unsigned AlignedSize = (Size + Alignment - 1)/Alignment*Alignment;
387 Size = AlignedSize*ATy->getNumElements();
390 case Type::PackedTyID: {
391 const PackedType *PTy = cast<PackedType>(Ty);
392 getTypeInfoPref(PTy->getElementType(), TD, Size, Alignment);
393 unsigned AlignedSize = (Size + Alignment - 1)/Alignment*Alignment;
394 Size = AlignedSize*PTy->getNumElements();
395 // FIXME: The alignments of specific packed types are target dependent.
396 // For now, just set it to be equal to Size.
400 case Type::StructTyID: {
401 // Get the layout annotation... which is lazily created on demand;
402 // enforce minimum aggregate alignment.
403 const StructLayout *Layout = TD->getStructLayout(cast<StructType>(Ty));
404 Size = Layout->getSizeInBytes();
405 Alignment = std::max(Layout->getAlignment(),
406 (const unsigned int)TD->getAggMinPrefAlignment());
411 assert(0 && "Bad type for getTypeInfoPref!!!");
417 uint64_t TargetData::getTypeSize(const Type *Ty) const {
420 getTypeInfoABI(Ty, this, Size, Align);
424 uint64_t TargetData::getTypeSizeInBits(const Type *Ty) const {
426 return cast<IntegerType>(Ty)->getBitWidth();
430 getTypeInfoABI(Ty, this, Size, Align);
434 unsigned char TargetData::getTypeAlignmentABI(const Type *Ty) const {
437 getTypeInfoABI(Ty, this, Size, Align);
441 unsigned char TargetData::getTypeAlignmentPref(const Type *Ty) const {
444 getTypeInfoPref(Ty, this, Size, Align);
448 unsigned char TargetData::getPreferredTypeAlignmentShift(const Type *Ty) const {
449 unsigned Align = getTypeAlignmentPref(Ty);
450 assert(!(Align & (Align-1)) && "Alignment is not a power of two!");
451 return Log2_32(Align);
454 /// getIntPtrType - Return an unsigned integer type that is the same size or
455 /// greater to the host pointer size.
456 const Type *TargetData::getIntPtrType() const {
457 switch (getPointerSize()) {
458 default: assert(0 && "Unknown pointer size!");
459 case 2: return Type::Int16Ty;
460 case 4: return Type::Int32Ty;
461 case 8: return Type::Int64Ty;
466 uint64_t TargetData::getIndexedOffset(const Type *ptrTy, Value* const* Indices,
467 unsigned NumIndices) const {
468 const Type *Ty = ptrTy;
469 assert(isa<PointerType>(Ty) && "Illegal argument for getIndexedOffset()");
472 generic_gep_type_iterator<Value* const*>
473 TI = gep_type_begin(ptrTy, Indices, Indices+NumIndices);
474 for (unsigned CurIDX = 0; CurIDX != NumIndices; ++CurIDX, ++TI) {
475 if (const StructType *STy = dyn_cast<StructType>(*TI)) {
476 assert(Indices[CurIDX]->getType() == Type::Int32Ty &&"Illegal struct idx");
477 unsigned FieldNo = cast<ConstantInt>(Indices[CurIDX])->getZExtValue();
479 // Get structure layout information...
480 const StructLayout *Layout = getStructLayout(STy);
482 // Add in the offset, as calculated by the structure layout info...
483 Result += Layout->getElementOffset(FieldNo);
485 // Update Ty to refer to current element
486 Ty = STy->getElementType(FieldNo);
488 // Update Ty to refer to current element
489 Ty = cast<SequentialType>(Ty)->getElementType();
491 // Get the array index and the size of each array element.
492 int64_t arrayIdx = cast<ConstantInt>(Indices[CurIDX])->getSExtValue();
493 Result += arrayIdx * (int64_t)getTypeSize(Ty);
500 /// getPreferredAlignmentLog - Return the preferred alignment of the
501 /// specified global, returned in log form. This includes an explicitly
502 /// requested alignment (if the global has one).
503 unsigned TargetData::getPreferredAlignmentLog(const GlobalVariable *GV) const {
504 const Type *ElemType = GV->getType()->getElementType();
505 unsigned Alignment = getPreferredTypeAlignmentShift(ElemType);
506 if (GV->getAlignment() > (1U << Alignment))
507 Alignment = Log2_32(GV->getAlignment());
509 if (GV->hasInitializer()) {
511 // If the global is not external, see if it is large. If so, give it a
513 if (getTypeSize(ElemType) > 128)
514 Alignment = 4; // 16-byte alignment.