blob: e21868be4420b91ffd47fd9dfbee79983829c7ed [file] [log] [blame]
Micah Villmowb4faa152012-10-04 23:01:22 +00001//===-- DataLayout.cpp - Data size & alignment routines --------------------==//
Micah Villmowac34b5c2012-10-04 22:08:14 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Micah Villmowb4faa152012-10-04 23:01:22 +000010// This file defines layout properties related to datatype size/offset/alignment
Micah Villmowac34b5c2012-10-04 22:08:14 +000011// 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
Micah Villmowb4faa152012-10-04 23:01:22 +000019#include "llvm/DataLayout.h"
Micah Villmowac34b5c2012-10-04 22:08:14 +000020#include "llvm/Constants.h"
21#include "llvm/DerivedTypes.h"
22#include "llvm/Module.h"
23#include "llvm/Support/GetElementPtrTypeIterator.h"
24#include "llvm/Support/MathExtras.h"
25#include "llvm/Support/ManagedStatic.h"
26#include "llvm/Support/ErrorHandling.h"
27#include "llvm/Support/raw_ostream.h"
28#include "llvm/Support/Mutex.h"
29#include "llvm/ADT/DenseMap.h"
30#include <algorithm>
31#include <cstdlib>
32using namespace llvm;
33
Micah Villmowb4faa152012-10-04 23:01:22 +000034// Handle the Pass registration stuff necessary to use DataLayout's.
Micah Villmowac34b5c2012-10-04 22:08:14 +000035
36// Register the default SparcV9 implementation...
Micah Villmowb4faa152012-10-04 23:01:22 +000037INITIALIZE_PASS(DataLayout, "datalayout", "Data Layout", false, true)
38char DataLayout::ID = 0;
Micah Villmowac34b5c2012-10-04 22:08:14 +000039
40//===----------------------------------------------------------------------===//
41// Support for StructLayout
42//===----------------------------------------------------------------------===//
43
Micah Villmowb4faa152012-10-04 23:01:22 +000044StructLayout::StructLayout(StructType *ST, const DataLayout &TD) {
Micah Villmowac34b5c2012-10-04 22:08:14 +000045 assert(!ST->isOpaque() && "Cannot get layout of opaque structs");
46 StructAlignment = 0;
47 StructSize = 0;
48 NumElements = ST->getNumElements();
49
50 // Loop over each of the elements, placing them in memory.
51 for (unsigned i = 0, e = NumElements; i != e; ++i) {
52 Type *Ty = ST->getElementType(i);
53 unsigned TyAlign = ST->isPacked() ? 1 : TD.getABITypeAlignment(Ty);
54
55 // Add padding if necessary to align the data element properly.
56 if ((StructSize & (TyAlign-1)) != 0)
Micah Villmowb4faa152012-10-04 23:01:22 +000057 StructSize = DataLayout::RoundUpAlignment(StructSize, TyAlign);
Micah Villmowac34b5c2012-10-04 22:08:14 +000058
59 // Keep track of maximum alignment constraint.
60 StructAlignment = std::max(TyAlign, StructAlignment);
61
62 MemberOffsets[i] = StructSize;
63 StructSize += TD.getTypeAllocSize(Ty); // Consume space for this data item
64 }
65
66 // Empty structures have alignment of 1 byte.
67 if (StructAlignment == 0) StructAlignment = 1;
68
69 // Add padding to the end of the struct so that it could be put in an array
70 // and all array elements would be aligned correctly.
71 if ((StructSize & (StructAlignment-1)) != 0)
Micah Villmowb4faa152012-10-04 23:01:22 +000072 StructSize = DataLayout::RoundUpAlignment(StructSize, StructAlignment);
Micah Villmowac34b5c2012-10-04 22:08:14 +000073}
74
75
76/// getElementContainingOffset - Given a valid offset into the structure,
77/// return the structure index that contains it.
78unsigned StructLayout::getElementContainingOffset(uint64_t Offset) const {
79 const uint64_t *SI =
80 std::upper_bound(&MemberOffsets[0], &MemberOffsets[NumElements], Offset);
81 assert(SI != &MemberOffsets[0] && "Offset not in structure type!");
82 --SI;
83 assert(*SI <= Offset && "upper_bound didn't work");
84 assert((SI == &MemberOffsets[0] || *(SI-1) <= Offset) &&
85 (SI+1 == &MemberOffsets[NumElements] || *(SI+1) > Offset) &&
86 "Upper bound didn't work!");
87
88 // Multiple fields can have the same offset if any of them are zero sized.
89 // For example, in { i32, [0 x i32], i32 }, searching for offset 4 will stop
90 // at the i32 element, because it is the last element at that offset. This is
91 // the right one to return, because anything after it will have a higher
92 // offset, implying that this element is non-empty.
93 return SI-&MemberOffsets[0];
94}
95
96//===----------------------------------------------------------------------===//
Micah Villmowb4faa152012-10-04 23:01:22 +000097// LayoutAlignElem, LayoutAlign support
Micah Villmowac34b5c2012-10-04 22:08:14 +000098//===----------------------------------------------------------------------===//
99
Micah Villmowb4faa152012-10-04 23:01:22 +0000100LayoutAlignElem
101LayoutAlignElem::get(AlignTypeEnum align_type, unsigned abi_align,
Micah Villmowac34b5c2012-10-04 22:08:14 +0000102 unsigned pref_align, uint32_t bit_width) {
103 assert(abi_align <= pref_align && "Preferred alignment worse than ABI!");
Micah Villmowb4faa152012-10-04 23:01:22 +0000104 LayoutAlignElem retval;
Micah Villmowac34b5c2012-10-04 22:08:14 +0000105 retval.AlignType = align_type;
106 retval.ABIAlign = abi_align;
107 retval.PrefAlign = pref_align;
108 retval.TypeBitWidth = bit_width;
109 return retval;
110}
111
112bool
Micah Villmowb4faa152012-10-04 23:01:22 +0000113LayoutAlignElem::operator==(const LayoutAlignElem &rhs) const {
Micah Villmowac34b5c2012-10-04 22:08:14 +0000114 return (AlignType == rhs.AlignType
115 && ABIAlign == rhs.ABIAlign
116 && PrefAlign == rhs.PrefAlign
117 && TypeBitWidth == rhs.TypeBitWidth);
118}
119
Micah Villmowb4faa152012-10-04 23:01:22 +0000120const LayoutAlignElem
Micah Villmow89021e42012-10-09 16:06:12 +0000121DataLayout::InvalidAlignmentElem =
122 LayoutAlignElem::get((AlignTypeEnum) -1, 0, 0, 0);
123
124//===----------------------------------------------------------------------===//
125// PointerAlignElem, PointerAlign support
126//===----------------------------------------------------------------------===//
127
128PointerAlignElem
129PointerAlignElem::get(uint32_t addr_space, unsigned abi_align,
130 unsigned pref_align, uint32_t bit_width) {
131 assert(abi_align <= pref_align && "Preferred alignment worse than ABI!");
132 PointerAlignElem retval;
133 retval.AddressSpace = addr_space;
134 retval.ABIAlign = abi_align;
135 retval.PrefAlign = pref_align;
136 retval.TypeBitWidth = bit_width;
137 return retval;
138}
139
140bool
141PointerAlignElem::operator==(const PointerAlignElem &rhs) const {
142 return (ABIAlign == rhs.ABIAlign
143 && AddressSpace == rhs.AddressSpace
144 && PrefAlign == rhs.PrefAlign
145 && TypeBitWidth == rhs.TypeBitWidth);
146}
147
148const PointerAlignElem
149DataLayout::InvalidPointerElem = PointerAlignElem::get(~0U, 0U, 0U, 0U);
Micah Villmowac34b5c2012-10-04 22:08:14 +0000150
151//===----------------------------------------------------------------------===//
Micah Villmowb4faa152012-10-04 23:01:22 +0000152// DataLayout Class Implementation
Micah Villmowac34b5c2012-10-04 22:08:14 +0000153//===----------------------------------------------------------------------===//
154
155/// getInt - Get an integer ignoring errors.
156static int getInt(StringRef R) {
157 int Result = 0;
158 R.getAsInteger(10, Result);
159 return Result;
160}
161
Patrik Hägglund01860a62012-11-14 09:04:56 +0000162void DataLayout::init(StringRef Desc) {
Micah Villmowb4faa152012-10-04 23:01:22 +0000163 initializeDataLayoutPass(*PassRegistry::getPassRegistry());
Micah Villmowac34b5c2012-10-04 22:08:14 +0000164
165 LayoutMap = 0;
166 LittleEndian = false;
Micah Villmowac34b5c2012-10-04 22:08:14 +0000167 StackNaturalAlign = 0;
168
169 // Default alignments
170 setAlignment(INTEGER_ALIGN, 1, 1, 1); // i1
171 setAlignment(INTEGER_ALIGN, 1, 1, 8); // i8
172 setAlignment(INTEGER_ALIGN, 2, 2, 16); // i16
173 setAlignment(INTEGER_ALIGN, 4, 4, 32); // i32
174 setAlignment(INTEGER_ALIGN, 4, 8, 64); // i64
175 setAlignment(FLOAT_ALIGN, 2, 2, 16); // half
176 setAlignment(FLOAT_ALIGN, 4, 4, 32); // float
177 setAlignment(FLOAT_ALIGN, 8, 8, 64); // double
178 setAlignment(FLOAT_ALIGN, 16, 16, 128); // ppcf128, quad, ...
179 setAlignment(VECTOR_ALIGN, 8, 8, 64); // v2i32, v1i64, ...
180 setAlignment(VECTOR_ALIGN, 16, 16, 128); // v16i8, v8i16, v4i32, ...
181 setAlignment(AGGREGATE_ALIGN, 0, 8, 0); // struct
Micah Villmow89021e42012-10-09 16:06:12 +0000182 setPointerAlignment(0, 8, 8, 8);
Patrik Hägglund01860a62012-11-14 09:04:56 +0000183
184 std::string errMsg = parseSpecifier(Desc);
185 assert(errMsg == "" && "Invalid target data layout string.");
186 (void)errMsg;
Micah Villmowac34b5c2012-10-04 22:08:14 +0000187}
188
Patrik Hägglund01860a62012-11-14 09:04:56 +0000189std::string DataLayout::parseSpecifier(StringRef Desc) {
Micah Villmowac34b5c2012-10-04 22:08:14 +0000190
191 while (!Desc.empty()) {
192 std::pair<StringRef, StringRef> Split = Desc.split('-');
193 StringRef Token = Split.first;
194 Desc = Split.second;
195
Micah Villmowac34b5c2012-10-04 22:08:14 +0000196 Split = Token.split(':');
197 StringRef Specifier = Split.first;
198 Token = Split.second;
199
200 assert(!Specifier.empty() && "Can't be empty here");
201
202 switch (Specifier[0]) {
203 case 'E':
Patrik Hägglund01860a62012-11-14 09:04:56 +0000204 LittleEndian = false;
Micah Villmowac34b5c2012-10-04 22:08:14 +0000205 break;
206 case 'e':
Patrik Hägglund01860a62012-11-14 09:04:56 +0000207 LittleEndian = true;
Micah Villmowac34b5c2012-10-04 22:08:14 +0000208 break;
209 case 'p': {
Micah Villmow89021e42012-10-09 16:06:12 +0000210 int AddrSpace = 0;
211 if (Specifier.size() > 1) {
212 AddrSpace = getInt(Specifier.substr(1));
213 if (AddrSpace < 0 || AddrSpace > (1 << 24))
214 return "Invalid address space, must be a positive 24bit integer";
215 }
Micah Villmowac34b5c2012-10-04 22:08:14 +0000216 Split = Token.split(':');
217 int PointerMemSizeBits = getInt(Split.first);
218 if (PointerMemSizeBits < 0 || PointerMemSizeBits % 8 != 0)
219 return "invalid pointer size, must be a positive 8-bit multiple";
Micah Villmowac34b5c2012-10-04 22:08:14 +0000220
221 // Pointer ABI alignment.
222 Split = Split.second.split(':');
223 int PointerABIAlignBits = getInt(Split.first);
224 if (PointerABIAlignBits < 0 || PointerABIAlignBits % 8 != 0) {
225 return "invalid pointer ABI alignment, "
226 "must be a positive 8-bit multiple";
227 }
Micah Villmowac34b5c2012-10-04 22:08:14 +0000228
229 // Pointer preferred alignment.
230 Split = Split.second.split(':');
231 int PointerPrefAlignBits = getInt(Split.first);
232 if (PointerPrefAlignBits < 0 || PointerPrefAlignBits % 8 != 0) {
233 return "invalid pointer preferred alignment, "
234 "must be a positive 8-bit multiple";
235 }
Micah Villmow89021e42012-10-09 16:06:12 +0000236
237 if (PointerPrefAlignBits == 0)
238 PointerPrefAlignBits = PointerABIAlignBits;
Patrik Hägglund01860a62012-11-14 09:04:56 +0000239 setPointerAlignment(AddrSpace, PointerABIAlignBits/8,
240 PointerPrefAlignBits/8, PointerMemSizeBits/8);
Micah Villmowac34b5c2012-10-04 22:08:14 +0000241 break;
242 }
243 case 'i':
244 case 'v':
245 case 'f':
246 case 'a':
247 case 's': {
248 AlignTypeEnum AlignType;
249 char field = Specifier[0];
250 switch (field) {
251 default:
252 case 'i': AlignType = INTEGER_ALIGN; break;
253 case 'v': AlignType = VECTOR_ALIGN; break;
254 case 'f': AlignType = FLOAT_ALIGN; break;
255 case 'a': AlignType = AGGREGATE_ALIGN; break;
256 case 's': AlignType = STACK_ALIGN; break;
257 }
258 int Size = getInt(Specifier.substr(1));
259 if (Size < 0) {
260 return std::string("invalid ") + field + "-size field, "
261 "must be positive";
262 }
263
264 Split = Token.split(':');
265 int ABIAlignBits = getInt(Split.first);
266 if (ABIAlignBits < 0 || ABIAlignBits % 8 != 0) {
267 return std::string("invalid ") + field +"-abi-alignment field, "
268 "must be a positive 8-bit multiple";
269 }
270 unsigned ABIAlign = ABIAlignBits / 8;
271
272 Split = Split.second.split(':');
273
274 int PrefAlignBits = getInt(Split.first);
275 if (PrefAlignBits < 0 || PrefAlignBits % 8 != 0) {
276 return std::string("invalid ") + field +"-preferred-alignment field, "
277 "must be a positive 8-bit multiple";
278 }
279 unsigned PrefAlign = PrefAlignBits / 8;
280 if (PrefAlign == 0)
281 PrefAlign = ABIAlign;
Patrik Hägglund01860a62012-11-14 09:04:56 +0000282 setAlignment(AlignType, ABIAlign, PrefAlign, Size);
Micah Villmowb4faa152012-10-04 23:01:22 +0000283
Micah Villmowac34b5c2012-10-04 22:08:14 +0000284 break;
285 }
286 case 'n': // Native integer types.
287 Specifier = Specifier.substr(1);
288 do {
289 int Width = getInt(Specifier);
290 if (Width <= 0) {
Micah Villmowb4faa152012-10-04 23:01:22 +0000291 return std::string("invalid native integer size \'") +
292 Specifier.str() + "\', must be a positive integer.";
Micah Villmowac34b5c2012-10-04 22:08:14 +0000293 }
Patrik Hägglund01860a62012-11-14 09:04:56 +0000294 if (Width != 0)
295 LegalIntWidths.push_back(Width);
Micah Villmowac34b5c2012-10-04 22:08:14 +0000296 Split = Token.split(':');
297 Specifier = Split.first;
298 Token = Split.second;
299 } while (!Specifier.empty() || !Token.empty());
300 break;
301 case 'S': { // Stack natural alignment.
302 int StackNaturalAlignBits = getInt(Specifier.substr(1));
303 if (StackNaturalAlignBits < 0 || StackNaturalAlignBits % 8 != 0) {
304 return "invalid natural stack alignment (S-field), "
305 "must be a positive 8-bit multiple";
306 }
Patrik Hägglund01860a62012-11-14 09:04:56 +0000307 StackNaturalAlign = StackNaturalAlignBits / 8;
Micah Villmowac34b5c2012-10-04 22:08:14 +0000308 break;
309 }
310 default:
311 break;
312 }
313 }
314
315 return "";
316}
317
318/// Default ctor.
319///
320/// @note This has to exist, because this is a pass, but it should never be
321/// used.
Micah Villmowb4faa152012-10-04 23:01:22 +0000322DataLayout::DataLayout() : ImmutablePass(ID) {
323 report_fatal_error("Bad DataLayout ctor used. "
324 "Tool did not specify a DataLayout to use?");
Micah Villmowac34b5c2012-10-04 22:08:14 +0000325}
326
Micah Villmowb4faa152012-10-04 23:01:22 +0000327DataLayout::DataLayout(const Module *M)
Micah Villmowac34b5c2012-10-04 22:08:14 +0000328 : ImmutablePass(ID) {
Patrik Hägglund01860a62012-11-14 09:04:56 +0000329 init(M->getDataLayout());
Micah Villmowac34b5c2012-10-04 22:08:14 +0000330}
331
332void
Micah Villmowb4faa152012-10-04 23:01:22 +0000333DataLayout::setAlignment(AlignTypeEnum align_type, unsigned abi_align,
Micah Villmowac34b5c2012-10-04 22:08:14 +0000334 unsigned pref_align, uint32_t bit_width) {
335 assert(abi_align <= pref_align && "Preferred alignment worse than ABI!");
336 assert(pref_align < (1 << 16) && "Alignment doesn't fit in bitfield");
337 assert(bit_width < (1 << 24) && "Bit width doesn't fit in bitfield");
338 for (unsigned i = 0, e = Alignments.size(); i != e; ++i) {
Micah Villmow6d05e692012-10-05 17:02:14 +0000339 if (Alignments[i].AlignType == (unsigned)align_type &&
Micah Villmowac34b5c2012-10-04 22:08:14 +0000340 Alignments[i].TypeBitWidth == bit_width) {
341 // Update the abi, preferred alignments.
342 Alignments[i].ABIAlign = abi_align;
343 Alignments[i].PrefAlign = pref_align;
344 return;
345 }
346 }
347
Micah Villmowb4faa152012-10-04 23:01:22 +0000348 Alignments.push_back(LayoutAlignElem::get(align_type, abi_align,
Micah Villmowac34b5c2012-10-04 22:08:14 +0000349 pref_align, bit_width));
350}
351
Micah Villmow89021e42012-10-09 16:06:12 +0000352void
353DataLayout::setPointerAlignment(uint32_t addr_space, unsigned abi_align,
354 unsigned pref_align, uint32_t bit_width) {
355 assert(abi_align <= pref_align && "Preferred alignment worse than ABI!");
356 DenseMap<unsigned,PointerAlignElem>::iterator val = Pointers.find(addr_space);
357 if (val == Pointers.end()) {
358 Pointers[addr_space] = PointerAlignElem::get(addr_space,
359 abi_align, pref_align, bit_width);
360 } else {
361 val->second.ABIAlign = abi_align;
362 val->second.PrefAlign = pref_align;
363 val->second.TypeBitWidth = bit_width;
364 }
365}
366
Micah Villmowac34b5c2012-10-04 22:08:14 +0000367/// getAlignmentInfo - Return the alignment (either ABI if ABIInfo = true or
Micah Villmowb4faa152012-10-04 23:01:22 +0000368/// preferred if ABIInfo = false) the layout wants for the specified datatype.
369unsigned DataLayout::getAlignmentInfo(AlignTypeEnum AlignType,
Micah Villmowac34b5c2012-10-04 22:08:14 +0000370 uint32_t BitWidth, bool ABIInfo,
371 Type *Ty) const {
372 // Check to see if we have an exact match and remember the best match we see.
373 int BestMatchIdx = -1;
374 int LargestInt = -1;
375 for (unsigned i = 0, e = Alignments.size(); i != e; ++i) {
Micah Villmow6d05e692012-10-05 17:02:14 +0000376 if (Alignments[i].AlignType == (unsigned)AlignType &&
Micah Villmowac34b5c2012-10-04 22:08:14 +0000377 Alignments[i].TypeBitWidth == BitWidth)
378 return ABIInfo ? Alignments[i].ABIAlign : Alignments[i].PrefAlign;
379
380 // The best match so far depends on what we're looking for.
381 if (AlignType == INTEGER_ALIGN &&
382 Alignments[i].AlignType == INTEGER_ALIGN) {
383 // The "best match" for integers is the smallest size that is larger than
384 // the BitWidth requested.
385 if (Alignments[i].TypeBitWidth > BitWidth && (BestMatchIdx == -1 ||
386 Alignments[i].TypeBitWidth < Alignments[BestMatchIdx].TypeBitWidth))
387 BestMatchIdx = i;
388 // However, if there isn't one that's larger, then we must use the
389 // largest one we have (see below)
390 if (LargestInt == -1 ||
391 Alignments[i].TypeBitWidth > Alignments[LargestInt].TypeBitWidth)
392 LargestInt = i;
393 }
394 }
395
396 // Okay, we didn't find an exact solution. Fall back here depending on what
397 // is being looked for.
398 if (BestMatchIdx == -1) {
399 // If we didn't find an integer alignment, fall back on most conservative.
400 if (AlignType == INTEGER_ALIGN) {
401 BestMatchIdx = LargestInt;
402 } else {
403 assert(AlignType == VECTOR_ALIGN && "Unknown alignment type!");
404
405 // By default, use natural alignment for vector types. This is consistent
406 // with what clang and llvm-gcc do.
407 unsigned Align = getTypeAllocSize(cast<VectorType>(Ty)->getElementType());
408 Align *= cast<VectorType>(Ty)->getNumElements();
409 // If the alignment is not a power of 2, round up to the next power of 2.
410 // This happens for non-power-of-2 length vectors.
411 if (Align & (Align-1))
412 Align = NextPowerOf2(Align);
413 return Align;
414 }
415 }
416
417 // Since we got a "best match" index, just return it.
418 return ABIInfo ? Alignments[BestMatchIdx].ABIAlign
419 : Alignments[BestMatchIdx].PrefAlign;
420}
421
422namespace {
423
424class StructLayoutMap {
425 typedef DenseMap<StructType*, StructLayout*> LayoutInfoTy;
426 LayoutInfoTy LayoutInfo;
427
428public:
429 virtual ~StructLayoutMap() {
430 // Remove any layouts.
431 for (LayoutInfoTy::iterator I = LayoutInfo.begin(), E = LayoutInfo.end();
432 I != E; ++I) {
433 StructLayout *Value = I->second;
434 Value->~StructLayout();
435 free(Value);
436 }
437 }
438
439 StructLayout *&operator[](StructType *STy) {
440 return LayoutInfo[STy];
441 }
442
443 // for debugging...
444 virtual void dump() const {}
445};
446
447} // end anonymous namespace
448
Micah Villmowb4faa152012-10-04 23:01:22 +0000449DataLayout::~DataLayout() {
Micah Villmowac34b5c2012-10-04 22:08:14 +0000450 delete static_cast<StructLayoutMap*>(LayoutMap);
451}
452
Micah Villmowb4faa152012-10-04 23:01:22 +0000453const StructLayout *DataLayout::getStructLayout(StructType *Ty) const {
Micah Villmowac34b5c2012-10-04 22:08:14 +0000454 if (!LayoutMap)
455 LayoutMap = new StructLayoutMap();
456
457 StructLayoutMap *STM = static_cast<StructLayoutMap*>(LayoutMap);
458 StructLayout *&SL = (*STM)[Ty];
459 if (SL) return SL;
460
461 // Otherwise, create the struct layout. Because it is variable length, we
462 // malloc it, then use placement new.
463 int NumElts = Ty->getNumElements();
464 StructLayout *L =
465 (StructLayout *)malloc(sizeof(StructLayout)+(NumElts-1) * sizeof(uint64_t));
466
467 // Set SL before calling StructLayout's ctor. The ctor could cause other
468 // entries to be added to TheMap, invalidating our reference.
469 SL = L;
470
471 new (L) StructLayout(Ty, *this);
472
473 return L;
474}
475
Micah Villmowb4faa152012-10-04 23:01:22 +0000476std::string DataLayout::getStringRepresentation() const {
Micah Villmowac34b5c2012-10-04 22:08:14 +0000477 std::string Result;
478 raw_string_ostream OS(Result);
479
Micah Villmow89021e42012-10-09 16:06:12 +0000480 OS << (LittleEndian ? "e" : "E");
481 SmallVector<unsigned, 8> addrSpaces;
482 // Lets get all of the known address spaces and sort them
483 // into increasing order so that we can emit the string
484 // in a cleaner format.
485 for (DenseMap<unsigned, PointerAlignElem>::const_iterator
486 pib = Pointers.begin(), pie = Pointers.end();
487 pib != pie; ++pib) {
488 addrSpaces.push_back(pib->first);
489 }
490 std::sort(addrSpaces.begin(), addrSpaces.end());
491 for (SmallVector<unsigned, 8>::iterator asb = addrSpaces.begin(),
492 ase = addrSpaces.end(); asb != ase; ++asb) {
493 const PointerAlignElem &PI = Pointers.find(*asb)->second;
494 OS << "-p";
495 if (PI.AddressSpace) {
496 OS << PI.AddressSpace;
497 }
498 OS << ":" << PI.TypeBitWidth*8 << ':' << PI.ABIAlign*8
499 << ':' << PI.PrefAlign*8;
500 }
501 OS << "-S" << StackNaturalAlign*8;
Micah Villmowac34b5c2012-10-04 22:08:14 +0000502
503 for (unsigned i = 0, e = Alignments.size(); i != e; ++i) {
Micah Villmowb4faa152012-10-04 23:01:22 +0000504 const LayoutAlignElem &AI = Alignments[i];
Micah Villmowac34b5c2012-10-04 22:08:14 +0000505 OS << '-' << (char)AI.AlignType << AI.TypeBitWidth << ':'
506 << AI.ABIAlign*8 << ':' << AI.PrefAlign*8;
507 }
508
509 if (!LegalIntWidths.empty()) {
510 OS << "-n" << (unsigned)LegalIntWidths[0];
511
512 for (unsigned i = 1, e = LegalIntWidths.size(); i != e; ++i)
513 OS << ':' << (unsigned)LegalIntWidths[i];
514 }
515 return OS.str();
516}
517
518
Micah Villmowb4faa152012-10-04 23:01:22 +0000519uint64_t DataLayout::getTypeSizeInBits(Type *Ty) const {
Micah Villmowac34b5c2012-10-04 22:08:14 +0000520 assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!");
521 switch (Ty->getTypeID()) {
522 case Type::LabelTyID:
Micah Villmow89021e42012-10-09 16:06:12 +0000523 return getPointerSizeInBits(0);
524 case Type::PointerTyID: {
525 unsigned AS = dyn_cast<PointerType>(Ty)->getAddressSpace();
526 return getPointerSizeInBits(AS);
527 }
Micah Villmowac34b5c2012-10-04 22:08:14 +0000528 case Type::ArrayTyID: {
529 ArrayType *ATy = cast<ArrayType>(Ty);
530 return getTypeAllocSizeInBits(ATy->getElementType())*ATy->getNumElements();
531 }
532 case Type::StructTyID:
533 // Get the layout annotation... which is lazily created on demand.
534 return getStructLayout(cast<StructType>(Ty))->getSizeInBits();
535 case Type::IntegerTyID:
536 return cast<IntegerType>(Ty)->getBitWidth();
Micah Villmowac34b5c2012-10-04 22:08:14 +0000537 case Type::HalfTyID:
538 return 16;
539 case Type::FloatTyID:
540 return 32;
541 case Type::DoubleTyID:
542 case Type::X86_MMXTyID:
543 return 64;
544 case Type::PPC_FP128TyID:
545 case Type::FP128TyID:
546 return 128;
547 // In memory objects this is always aligned to a higher boundary, but
548 // only 80 bits contain information.
549 case Type::X86_FP80TyID:
550 return 80;
Hal Finkel8884dc32012-10-21 20:38:03 +0000551 case Type::VectorTyID: {
552 VectorType *VTy = cast<VectorType>(Ty);
553 return VTy->getNumElements()*getTypeSizeInBits(VTy->getElementType());
554 }
Micah Villmowac34b5c2012-10-04 22:08:14 +0000555 default:
Micah Villmowb4faa152012-10-04 23:01:22 +0000556 llvm_unreachable("DataLayout::getTypeSizeInBits(): Unsupported type");
Micah Villmowac34b5c2012-10-04 22:08:14 +0000557 }
558}
559
560/*!
561 \param abi_or_pref Flag that determines which alignment is returned. true
562 returns the ABI alignment, false returns the preferred alignment.
563 \param Ty The underlying type for which alignment is determined.
564
565 Get the ABI (\a abi_or_pref == true) or preferred alignment (\a abi_or_pref
566 == false) for the requested type \a Ty.
567 */
Micah Villmowb4faa152012-10-04 23:01:22 +0000568unsigned DataLayout::getAlignment(Type *Ty, bool abi_or_pref) const {
Micah Villmowac34b5c2012-10-04 22:08:14 +0000569 int AlignType = -1;
570
571 assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!");
572 switch (Ty->getTypeID()) {
573 // Early escape for the non-numeric types.
574 case Type::LabelTyID:
Micah Villmowac34b5c2012-10-04 22:08:14 +0000575 return (abi_or_pref
Micah Villmow89021e42012-10-09 16:06:12 +0000576 ? getPointerABIAlignment(0)
577 : getPointerPrefAlignment(0));
578 case Type::PointerTyID: {
579 unsigned AS = dyn_cast<PointerType>(Ty)->getAddressSpace();
580 return (abi_or_pref
581 ? getPointerABIAlignment(AS)
582 : getPointerPrefAlignment(AS));
583 }
Micah Villmowac34b5c2012-10-04 22:08:14 +0000584 case Type::ArrayTyID:
585 return getAlignment(cast<ArrayType>(Ty)->getElementType(), abi_or_pref);
586
587 case Type::StructTyID: {
588 // Packed structure types always have an ABI alignment of one.
589 if (cast<StructType>(Ty)->isPacked() && abi_or_pref)
590 return 1;
591
592 // Get the layout annotation... which is lazily created on demand.
593 const StructLayout *Layout = getStructLayout(cast<StructType>(Ty));
594 unsigned Align = getAlignmentInfo(AGGREGATE_ALIGN, 0, abi_or_pref, Ty);
595 return std::max(Align, Layout->getAlignment());
596 }
597 case Type::IntegerTyID:
Micah Villmowac34b5c2012-10-04 22:08:14 +0000598 AlignType = INTEGER_ALIGN;
599 break;
600 case Type::HalfTyID:
601 case Type::FloatTyID:
602 case Type::DoubleTyID:
603 // PPC_FP128TyID and FP128TyID have different data contents, but the
604 // same size and alignment, so they look the same here.
605 case Type::PPC_FP128TyID:
606 case Type::FP128TyID:
607 case Type::X86_FP80TyID:
608 AlignType = FLOAT_ALIGN;
609 break;
610 case Type::X86_MMXTyID:
611 case Type::VectorTyID:
612 AlignType = VECTOR_ALIGN;
613 break;
614 default:
615 llvm_unreachable("Bad type for getAlignment!!!");
616 }
617
618 return getAlignmentInfo((AlignTypeEnum)AlignType, getTypeSizeInBits(Ty),
619 abi_or_pref, Ty);
620}
621
Micah Villmowb4faa152012-10-04 23:01:22 +0000622unsigned DataLayout::getABITypeAlignment(Type *Ty) const {
Micah Villmowac34b5c2012-10-04 22:08:14 +0000623 return getAlignment(Ty, true);
624}
625
626/// getABIIntegerTypeAlignment - Return the minimum ABI-required alignment for
627/// an integer type of the specified bitwidth.
Micah Villmowb4faa152012-10-04 23:01:22 +0000628unsigned DataLayout::getABIIntegerTypeAlignment(unsigned BitWidth) const {
Micah Villmowac34b5c2012-10-04 22:08:14 +0000629 return getAlignmentInfo(INTEGER_ALIGN, BitWidth, true, 0);
630}
631
632
Micah Villmowb4faa152012-10-04 23:01:22 +0000633unsigned DataLayout::getCallFrameTypeAlignment(Type *Ty) const {
Micah Villmowac34b5c2012-10-04 22:08:14 +0000634 for (unsigned i = 0, e = Alignments.size(); i != e; ++i)
635 if (Alignments[i].AlignType == STACK_ALIGN)
636 return Alignments[i].ABIAlign;
637
638 return getABITypeAlignment(Ty);
639}
640
Micah Villmowb4faa152012-10-04 23:01:22 +0000641unsigned DataLayout::getPrefTypeAlignment(Type *Ty) const {
Micah Villmowac34b5c2012-10-04 22:08:14 +0000642 return getAlignment(Ty, false);
643}
644
Micah Villmowb4faa152012-10-04 23:01:22 +0000645unsigned DataLayout::getPreferredTypeAlignmentShift(Type *Ty) const {
Micah Villmowac34b5c2012-10-04 22:08:14 +0000646 unsigned Align = getPrefTypeAlignment(Ty);
647 assert(!(Align & (Align-1)) && "Alignment is not a power of two!");
648 return Log2_32(Align);
649}
650
Duncan Sands5bdd9dd2012-10-29 17:31:46 +0000651/// getIntPtrType - Return an integer type with size at least as big as that
652/// of a pointer in the given address space.
Micah Villmow89021e42012-10-09 16:06:12 +0000653IntegerType *DataLayout::getIntPtrType(LLVMContext &C,
654 unsigned AddressSpace) const {
655 return IntegerType::get(C, getPointerSizeInBits(AddressSpace));
Micah Villmowac34b5c2012-10-04 22:08:14 +0000656}
657
Duncan Sands5bdd9dd2012-10-29 17:31:46 +0000658/// getIntPtrType - Return an integer (vector of integer) type with size at
659/// least as big as that of a pointer of the given pointer (vector of pointer)
660/// type.
661Type *DataLayout::getIntPtrType(Type *Ty) const {
Chandler Carruth7ec50852012-11-01 08:07:29 +0000662 assert(Ty->isPtrOrPtrVectorTy() &&
663 "Expected a pointer or pointer vector type.");
Chandler Carruth7ec50852012-11-01 08:07:29 +0000664 unsigned NumBits = getTypeSizeInBits(Ty->getScalarType());
Duncan Sands5bdd9dd2012-10-29 17:31:46 +0000665 IntegerType *IntTy = IntegerType::get(Ty->getContext(), NumBits);
666 if (VectorType *VecTy = dyn_cast<VectorType>(Ty))
667 return VectorType::get(IntTy, VecTy->getNumElements());
668 return IntTy;
Micah Villmow12d91272012-10-24 15:52:52 +0000669}
670
Micah Villmowb4faa152012-10-04 23:01:22 +0000671uint64_t DataLayout::getIndexedOffset(Type *ptrTy,
Micah Villmowac34b5c2012-10-04 22:08:14 +0000672 ArrayRef<Value *> Indices) const {
673 Type *Ty = ptrTy;
674 assert(Ty->isPointerTy() && "Illegal argument for getIndexedOffset()");
675 uint64_t Result = 0;
676
677 generic_gep_type_iterator<Value* const*>
678 TI = gep_type_begin(ptrTy, Indices);
679 for (unsigned CurIDX = 0, EndIDX = Indices.size(); CurIDX != EndIDX;
680 ++CurIDX, ++TI) {
681 if (StructType *STy = dyn_cast<StructType>(*TI)) {
682 assert(Indices[CurIDX]->getType() ==
683 Type::getInt32Ty(ptrTy->getContext()) &&
684 "Illegal struct idx");
685 unsigned FieldNo = cast<ConstantInt>(Indices[CurIDX])->getZExtValue();
686
687 // Get structure layout information...
688 const StructLayout *Layout = getStructLayout(STy);
689
690 // Add in the offset, as calculated by the structure layout info...
691 Result += Layout->getElementOffset(FieldNo);
692
693 // Update Ty to refer to current element
694 Ty = STy->getElementType(FieldNo);
695 } else {
696 // Update Ty to refer to current element
697 Ty = cast<SequentialType>(Ty)->getElementType();
698
699 // Get the array index and the size of each array element.
700 if (int64_t arrayIdx = cast<ConstantInt>(Indices[CurIDX])->getSExtValue())
701 Result += (uint64_t)arrayIdx * getTypeAllocSize(Ty);
702 }
703 }
704
705 return Result;
706}
707
708/// getPreferredAlignment - Return the preferred alignment of the specified
709/// global. This includes an explicitly requested alignment (if the global
710/// has one).
Micah Villmowb4faa152012-10-04 23:01:22 +0000711unsigned DataLayout::getPreferredAlignment(const GlobalVariable *GV) const {
Micah Villmowac34b5c2012-10-04 22:08:14 +0000712 Type *ElemType = GV->getType()->getElementType();
713 unsigned Alignment = getPrefTypeAlignment(ElemType);
714 unsigned GVAlignment = GV->getAlignment();
715 if (GVAlignment >= Alignment) {
716 Alignment = GVAlignment;
717 } else if (GVAlignment != 0) {
718 Alignment = std::max(GVAlignment, getABITypeAlignment(ElemType));
719 }
720
721 if (GV->hasInitializer() && GVAlignment == 0) {
722 if (Alignment < 16) {
723 // If the global is not external, see if it is large. If so, give it a
724 // larger alignment.
725 if (getTypeSizeInBits(ElemType) > 128)
726 Alignment = 16; // 16-byte alignment.
727 }
728 }
729 return Alignment;
730}
731
732/// getPreferredAlignmentLog - Return the preferred alignment of the
733/// specified global, returned in log form. This includes an explicitly
734/// requested alignment (if the global has one).
Micah Villmowb4faa152012-10-04 23:01:22 +0000735unsigned DataLayout::getPreferredAlignmentLog(const GlobalVariable *GV) const {
Micah Villmowac34b5c2012-10-04 22:08:14 +0000736 return Log2_32(getPreferredAlignment(GV));
737}