blob: 94e0740663cc599b2a7f61a0c4e45bc793656f58 [file] [log] [blame]
Eugene Zelenkof53a7b42017-05-05 22:30:37 +00001//===- DataLayout.cpp - Data size & alignment routines ---------------------==//
Micah Villmowac34b5c2012-10-04 22:08:14 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Micah Villmowac34b5c2012-10-04 22:08:14 +00006//
7//===----------------------------------------------------------------------===//
8//
Micah Villmowb4faa152012-10-04 23:01:22 +00009// This file defines layout properties related to datatype size/offset/alignment
Micah Villmowac34b5c2012-10-04 22:08:14 +000010// information.
11//
12// This structure should be created once, filled in if the defaults are not
13// correct and then passed around by const&. None of the members functions
14// require modification to the object.
15//
16//===----------------------------------------------------------------------===//
17
Chandler Carruth6bda14b2017-06-06 11:49:48 +000018#include "llvm/IR/DataLayout.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/ADT/DenseMap.h"
Eugene Zelenkof53a7b42017-05-05 22:30:37 +000020#include "llvm/ADT/StringRef.h"
Rafael Espindola58873562014-01-03 19:21:54 +000021#include "llvm/ADT/Triple.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/Constants.h"
23#include "llvm/IR/DerivedTypes.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000024#include "llvm/IR/GetElementPtrTypeIterator.h"
Eugene Zelenkof53a7b42017-05-05 22:30:37 +000025#include "llvm/IR/GlobalVariable.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Module.h"
Eugene Zelenkof53a7b42017-05-05 22:30:37 +000027#include "llvm/IR/Type.h"
28#include "llvm/IR/Value.h"
29#include "llvm/Support/Casting.h"
Micah Villmowac34b5c2012-10-04 22:08:14 +000030#include "llvm/Support/ErrorHandling.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/Support/MathExtras.h"
Graham Hunterb3025612019-10-08 12:53:54 +000032#include "llvm/Support/TypeSize.h"
Micah Villmowac34b5c2012-10-04 22:08:14 +000033#include <algorithm>
Eugene Zelenkof53a7b42017-05-05 22:30:37 +000034#include <cassert>
35#include <cstdint>
Micah Villmowac34b5c2012-10-04 22:08:14 +000036#include <cstdlib>
Eugene Zelenkof53a7b42017-05-05 22:30:37 +000037#include <tuple>
38#include <utility>
39
Micah Villmowac34b5c2012-10-04 22:08:14 +000040using namespace llvm;
41
Micah Villmowac34b5c2012-10-04 22:08:14 +000042//===----------------------------------------------------------------------===//
43// Support for StructLayout
44//===----------------------------------------------------------------------===//
45
Pete Cooper0ae73932015-07-27 17:15:28 +000046StructLayout::StructLayout(StructType *ST, const DataLayout &DL) {
Micah Villmowac34b5c2012-10-04 22:08:14 +000047 assert(!ST->isOpaque() && "Cannot get layout of opaque structs");
Micah Villmowac34b5c2012-10-04 22:08:14 +000048 StructSize = 0;
Mehdi Amini1c131b32015-12-15 01:44:07 +000049 IsPadded = false;
Micah Villmowac34b5c2012-10-04 22:08:14 +000050 NumElements = ST->getNumElements();
51
52 // Loop over each of the elements, placing them in memory.
53 for (unsigned i = 0, e = NumElements; i != e; ++i) {
54 Type *Ty = ST->getElementType(i);
Guillaume Chatelet18f805a2019-09-27 12:54:21 +000055 const Align TyAlign(ST->isPacked() ? 1 : DL.getABITypeAlignment(Ty));
Micah Villmowac34b5c2012-10-04 22:08:14 +000056
57 // Add padding if necessary to align the data element properly.
Guillaume Chatelet6c127cd2019-09-20 13:40:31 +000058 if (!isAligned(TyAlign, StructSize)) {
Mehdi Amini1c131b32015-12-15 01:44:07 +000059 IsPadded = true;
Rui Ueyamada00f2f2016-01-14 21:06:47 +000060 StructSize = alignTo(StructSize, TyAlign);
Mehdi Amini1c131b32015-12-15 01:44:07 +000061 }
Micah Villmowac34b5c2012-10-04 22:08:14 +000062
63 // Keep track of maximum alignment constraint.
64 StructAlignment = std::max(TyAlign, StructAlignment);
65
66 MemberOffsets[i] = StructSize;
Eli Bendersky41913c72013-04-16 15:41:18 +000067 StructSize += DL.getTypeAllocSize(Ty); // Consume space for this data item
Micah Villmowac34b5c2012-10-04 22:08:14 +000068 }
69
Micah Villmowac34b5c2012-10-04 22:08:14 +000070 // Add padding to the end of the struct so that it could be put in an array
71 // and all array elements would be aligned correctly.
Guillaume Chatelet6c127cd2019-09-20 13:40:31 +000072 if (!isAligned(StructAlignment, StructSize)) {
Mehdi Amini1c131b32015-12-15 01:44:07 +000073 IsPadded = true;
Rui Ueyamada00f2f2016-01-14 21:06:47 +000074 StructSize = alignTo(StructSize, StructAlignment);
Mehdi Amini1c131b32015-12-15 01:44:07 +000075 }
Micah Villmowac34b5c2012-10-04 22:08:14 +000076}
77
Micah Villmowac34b5c2012-10-04 22:08:14 +000078/// getElementContainingOffset - Given a valid offset into the structure,
79/// return the structure index that contains it.
80unsigned StructLayout::getElementContainingOffset(uint64_t Offset) const {
81 const uint64_t *SI =
82 std::upper_bound(&MemberOffsets[0], &MemberOffsets[NumElements], Offset);
83 assert(SI != &MemberOffsets[0] && "Offset not in structure type!");
84 --SI;
85 assert(*SI <= Offset && "upper_bound didn't work");
86 assert((SI == &MemberOffsets[0] || *(SI-1) <= Offset) &&
87 (SI+1 == &MemberOffsets[NumElements] || *(SI+1) > Offset) &&
88 "Upper bound didn't work!");
89
90 // Multiple fields can have the same offset if any of them are zero sized.
91 // For example, in { i32, [0 x i32], i32 }, searching for offset 4 will stop
92 // at the i32 element, because it is the last element at that offset. This is
93 // the right one to return, because anything after it will have a higher
94 // offset, implying that this element is non-empty.
95 return SI-&MemberOffsets[0];
96}
97
98//===----------------------------------------------------------------------===//
Micah Villmowb4faa152012-10-04 23:01:22 +000099// LayoutAlignElem, LayoutAlign support
Micah Villmowac34b5c2012-10-04 22:08:14 +0000100//===----------------------------------------------------------------------===//
101
Guillaume Chatelet18f805a2019-09-27 12:54:21 +0000102LayoutAlignElem LayoutAlignElem::get(AlignTypeEnum align_type, Align abi_align,
103 Align pref_align, uint32_t bit_width) {
Micah Villmowac34b5c2012-10-04 22:08:14 +0000104 assert(abi_align <= pref_align && "Preferred alignment worse than ABI!");
Micah Villmowb4faa152012-10-04 23:01:22 +0000105 LayoutAlignElem retval;
Micah Villmowac34b5c2012-10-04 22:08:14 +0000106 retval.AlignType = align_type;
107 retval.ABIAlign = abi_align;
108 retval.PrefAlign = pref_align;
109 retval.TypeBitWidth = bit_width;
110 return retval;
111}
112
113bool
Micah Villmowb4faa152012-10-04 23:01:22 +0000114LayoutAlignElem::operator==(const LayoutAlignElem &rhs) const {
Micah Villmowac34b5c2012-10-04 22:08:14 +0000115 return (AlignType == rhs.AlignType
116 && ABIAlign == rhs.ABIAlign
117 && PrefAlign == rhs.PrefAlign
118 && TypeBitWidth == rhs.TypeBitWidth);
119}
120
Micah Villmow89021e42012-10-09 16:06:12 +0000121//===----------------------------------------------------------------------===//
122// PointerAlignElem, PointerAlign support
123//===----------------------------------------------------------------------===//
124
Guillaume Chatelet18f805a2019-09-27 12:54:21 +0000125PointerAlignElem PointerAlignElem::get(uint32_t AddressSpace, Align ABIAlign,
126 Align PrefAlign, uint32_t TypeByteWidth,
Guillaume Chatelet6c127cd2019-09-20 13:40:31 +0000127 uint32_t IndexWidth) {
Rafael Espindolaf39136c2013-12-13 23:15:20 +0000128 assert(ABIAlign <= PrefAlign && "Preferred alignment worse than ABI!");
Micah Villmow89021e42012-10-09 16:06:12 +0000129 PointerAlignElem retval;
Rafael Espindolaf39136c2013-12-13 23:15:20 +0000130 retval.AddressSpace = AddressSpace;
131 retval.ABIAlign = ABIAlign;
132 retval.PrefAlign = PrefAlign;
133 retval.TypeByteWidth = TypeByteWidth;
Elena Demikhovsky945b7e52018-02-14 06:58:08 +0000134 retval.IndexWidth = IndexWidth;
Micah Villmow89021e42012-10-09 16:06:12 +0000135 return retval;
136}
137
138bool
139PointerAlignElem::operator==(const PointerAlignElem &rhs) const {
140 return (ABIAlign == rhs.ABIAlign
141 && AddressSpace == rhs.AddressSpace
142 && PrefAlign == rhs.PrefAlign
Elena Demikhovsky945b7e52018-02-14 06:58:08 +0000143 && TypeByteWidth == rhs.TypeByteWidth
144 && IndexWidth == rhs.IndexWidth);
Micah Villmow89021e42012-10-09 16:06:12 +0000145}
146
Micah Villmowac34b5c2012-10-04 22:08:14 +0000147//===----------------------------------------------------------------------===//
Micah Villmowb4faa152012-10-04 23:01:22 +0000148// DataLayout Class Implementation
Micah Villmowac34b5c2012-10-04 22:08:14 +0000149//===----------------------------------------------------------------------===//
150
Rafael Espindola58873562014-01-03 19:21:54 +0000151const char *DataLayout::getManglingComponent(const Triple &T) {
152 if (T.isOSBinFormatMachO())
153 return "-m:o";
David Majnemer7db449a2015-03-17 23:54:51 +0000154 if (T.isOSWindows() && T.isOSBinFormatCOFF())
155 return T.getArch() == Triple::x86 ? "-m:x" : "-m:w";
Saleem Abdulrasoolcd130822014-04-02 20:32:05 +0000156 return "-m:e";
Rafael Espindola58873562014-01-03 19:21:54 +0000157}
158
Rafael Espindolae23b8772013-12-20 15:21:32 +0000159static const LayoutAlignElem DefaultAlignments[] = {
Guillaume Chatelet18f805a2019-09-27 12:54:21 +0000160 {INTEGER_ALIGN, 1, Align(1), Align(1)}, // i1
161 {INTEGER_ALIGN, 8, Align(1), Align(1)}, // i8
162 {INTEGER_ALIGN, 16, Align(2), Align(2)}, // i16
163 {INTEGER_ALIGN, 32, Align(4), Align(4)}, // i32
164 {INTEGER_ALIGN, 64, Align(4), Align(8)}, // i64
165 {FLOAT_ALIGN, 16, Align(2), Align(2)}, // half
166 {FLOAT_ALIGN, 32, Align(4), Align(4)}, // float
167 {FLOAT_ALIGN, 64, Align(8), Align(8)}, // double
168 {FLOAT_ALIGN, 128, Align(16), Align(16)}, // ppcf128, quad, ...
169 {VECTOR_ALIGN, 64, Align(8), Align(8)}, // v2i32, v1i64, ...
170 {VECTOR_ALIGN, 128, Align(16), Align(16)}, // v16i8, v8i16, v4i32, ...
171 {AGGREGATE_ALIGN, 0, Align(1), Align(8)} // struct
Rafael Espindola458a4852013-12-19 23:03:03 +0000172};
173
Rafael Espindola248ac132014-02-25 22:23:04 +0000174void DataLayout::reset(StringRef Desc) {
175 clear();
176
Craig Topperc6207612014-04-09 06:08:46 +0000177 LayoutMap = nullptr;
Chandler Carruthf67321c2014-10-20 10:41:29 +0000178 BigEndian = false;
Matt Arsenault3c1fc762017-04-10 22:27:50 +0000179 AllocaAddrSpace = 0;
Guillaume Chatelet65e4b472019-08-05 09:00:43 +0000180 StackNaturalAlign.reset();
Dylan McKayced2fe62018-02-19 09:56:22 +0000181 ProgramAddrSpace = 0;
Guillaume Chatelet65e4b472019-08-05 09:00:43 +0000182 FunctionPtrAlign.reset();
Michael Platings308e82e2019-03-08 10:44:06 +0000183 TheFunctionPtrAlignType = FunctionPtrAlignType::Independent;
Rafael Espindola58873562014-01-03 19:21:54 +0000184 ManglingMode = MM_None;
Sanjoy Dasc6af5ea2016-07-28 23:43:38 +0000185 NonIntegralAddressSpaces.clear();
Micah Villmowac34b5c2012-10-04 22:08:14 +0000186
187 // Default alignments
Benjamin Kramer3ad5c962014-03-10 15:03:06 +0000188 for (const LayoutAlignElem &E : DefaultAlignments) {
Rafael Espindola458a4852013-12-19 23:03:03 +0000189 setAlignment((AlignTypeEnum)E.AlignType, E.ABIAlign, E.PrefAlign,
190 E.TypeBitWidth);
191 }
Guillaume Chatelet18f805a2019-09-27 12:54:21 +0000192 setPointerAlignment(0, Align(8), Align(8), 8, 8);
Patrik Hägglund01860a62012-11-14 09:04:56 +0000193
Patrik Hagglund086ee1e2012-11-30 10:06:59 +0000194 parseSpecifier(Desc);
195}
196
197/// Checked version of split, to ensure mandatory subparts.
198static std::pair<StringRef, StringRef> split(StringRef Str, char Separator) {
199 assert(!Str.empty() && "parse error, string can't be empty here");
200 std::pair<StringRef, StringRef> Split = Str.split(Separator);
David Majnemer2dc1b0f2014-12-10 01:38:28 +0000201 if (Split.second.empty() && Split.first != Str)
202 report_fatal_error("Trailing separator in datalayout string");
David Majnemer612f3122014-12-10 02:36:41 +0000203 if (!Split.second.empty() && Split.first.empty())
204 report_fatal_error("Expected token before separator in datalayout string");
Patrik Hagglund086ee1e2012-11-30 10:06:59 +0000205 return Split;
Micah Villmowac34b5c2012-10-04 22:08:14 +0000206}
207
Cameron McInally8af9eac2014-01-07 19:51:38 +0000208/// Get an unsigned integer, including error checks.
Patrik Hägglund3eb16c52012-11-28 12:13:12 +0000209static unsigned getInt(StringRef R) {
Cameron McInallyf0379fa2014-01-13 22:04:55 +0000210 unsigned Result;
Patrik Hägglund504f4782012-11-28 14:32:52 +0000211 bool error = R.getAsInteger(10, Result); (void)error;
Cameron McInallyf0379fa2014-01-13 22:04:55 +0000212 if (error)
213 report_fatal_error("not a number, or does not fit in an unsigned int");
Patrik Hägglund3eb16c52012-11-28 12:13:12 +0000214 return Result;
215}
216
Patrik Hagglund086ee1e2012-11-30 10:06:59 +0000217/// Convert bits into bytes. Assert if not a byte width multiple.
218static unsigned inBytes(unsigned Bits) {
David Majnemer2dc1b0f2014-12-10 01:38:28 +0000219 if (Bits % 8)
220 report_fatal_error("number of bits must be a byte width multiple");
Patrik Hagglund086ee1e2012-11-30 10:06:59 +0000221 return Bits / 8;
222}
223
Dylan McKayced2fe62018-02-19 09:56:22 +0000224static unsigned getAddrSpace(StringRef R) {
225 unsigned AddrSpace = getInt(R);
226 if (!isUInt<24>(AddrSpace))
227 report_fatal_error("Invalid address space, must be a 24-bit integer");
228 return AddrSpace;
229}
230
Patrik Hagglund086ee1e2012-11-30 10:06:59 +0000231void DataLayout::parseSpecifier(StringRef Desc) {
Mehdi Amini46a43552015-03-04 18:43:29 +0000232 StringRepresentation = Desc;
Micah Villmowac34b5c2012-10-04 22:08:14 +0000233 while (!Desc.empty()) {
Patrik Hagglund086ee1e2012-11-30 10:06:59 +0000234 // Split at '-'.
235 std::pair<StringRef, StringRef> Split = split(Desc, '-');
Micah Villmowac34b5c2012-10-04 22:08:14 +0000236 Desc = Split.second;
237
Patrik Hagglund086ee1e2012-11-30 10:06:59 +0000238 // Split at ':'.
239 Split = split(Split.first, ':');
Micah Villmowac34b5c2012-10-04 22:08:14 +0000240
Patrik Hagglund086ee1e2012-11-30 10:06:59 +0000241 // Aliases used below.
242 StringRef &Tok = Split.first; // Current token.
243 StringRef &Rest = Split.second; // The rest of the string.
Micah Villmowac34b5c2012-10-04 22:08:14 +0000244
Sanjoy Dasc6af5ea2016-07-28 23:43:38 +0000245 if (Tok == "ni") {
246 do {
247 Split = split(Rest, ':');
248 Rest = Split.second;
249 unsigned AS = getInt(Split.first);
250 if (AS == 0)
251 report_fatal_error("Address space 0 can never be non-integral");
252 NonIntegralAddressSpaces.push_back(AS);
253 } while (!Rest.empty());
254
255 continue;
256 }
257
Patrik Hagglund086ee1e2012-11-30 10:06:59 +0000258 char Specifier = Tok.front();
259 Tok = Tok.substr(1);
260
261 switch (Specifier) {
Rafael Espindola6994fdf2014-01-01 22:29:43 +0000262 case 's':
263 // Ignored for backward compatibility.
264 // FIXME: remove this on LLVM 4.0.
265 break;
Micah Villmowac34b5c2012-10-04 22:08:14 +0000266 case 'E':
Chandler Carruthf67321c2014-10-20 10:41:29 +0000267 BigEndian = true;
Micah Villmowac34b5c2012-10-04 22:08:14 +0000268 break;
269 case 'e':
Chandler Carruthf67321c2014-10-20 10:41:29 +0000270 BigEndian = false;
Micah Villmowac34b5c2012-10-04 22:08:14 +0000271 break;
272 case 'p': {
Patrik Hagglund086ee1e2012-11-30 10:06:59 +0000273 // Address space.
274 unsigned AddrSpace = Tok.empty() ? 0 : getInt(Tok);
David Majnemer5330c692014-12-10 01:17:08 +0000275 if (!isUInt<24>(AddrSpace))
276 report_fatal_error("Invalid address space, must be a 24bit integer");
Micah Villmowac34b5c2012-10-04 22:08:14 +0000277
Patrik Hagglund086ee1e2012-11-30 10:06:59 +0000278 // Size.
David Majnemer2dc1b0f2014-12-10 01:38:28 +0000279 if (Rest.empty())
280 report_fatal_error(
281 "Missing size specification for pointer in datalayout string");
Patrik Hagglund086ee1e2012-11-30 10:06:59 +0000282 Split = split(Rest, ':');
283 unsigned PointerMemSize = inBytes(getInt(Tok));
Owen Anderson5bc2bbe2015-03-02 06:00:02 +0000284 if (!PointerMemSize)
285 report_fatal_error("Invalid pointer size of 0 bytes");
Patrik Hagglund086ee1e2012-11-30 10:06:59 +0000286
287 // ABI alignment.
David Majnemer2dc1b0f2014-12-10 01:38:28 +0000288 if (Rest.empty())
289 report_fatal_error(
290 "Missing alignment specification for pointer in datalayout string");
Patrik Hagglund086ee1e2012-11-30 10:06:59 +0000291 Split = split(Rest, ':');
292 unsigned PointerABIAlign = inBytes(getInt(Tok));
Owen Anderson040f2f82015-03-02 06:33:51 +0000293 if (!isPowerOf2_64(PointerABIAlign))
294 report_fatal_error(
295 "Pointer ABI alignment must be a power of 2");
Patrik Hagglund086ee1e2012-11-30 10:06:59 +0000296
Elena Demikhovsky945b7e52018-02-14 06:58:08 +0000297 // Size of index used in GEP for address calculation.
298 // The parameter is optional. By default it is equal to size of pointer.
299 unsigned IndexSize = PointerMemSize;
300
Patrik Hagglund086ee1e2012-11-30 10:06:59 +0000301 // Preferred alignment.
302 unsigned PointerPrefAlign = PointerABIAlign;
303 if (!Rest.empty()) {
304 Split = split(Rest, ':');
305 PointerPrefAlign = inBytes(getInt(Tok));
Owen Anderson040f2f82015-03-02 06:33:51 +0000306 if (!isPowerOf2_64(PointerPrefAlign))
307 report_fatal_error(
308 "Pointer preferred alignment must be a power of 2");
Micah Villmowac34b5c2012-10-04 22:08:14 +0000309
Elena Demikhovsky945b7e52018-02-14 06:58:08 +0000310 // Now read the index. It is the second optional parameter here.
311 if (!Rest.empty()) {
312 Split = split(Rest, ':');
313 IndexSize = inBytes(getInt(Tok));
314 if (!IndexSize)
315 report_fatal_error("Invalid index size of 0 bytes");
316 }
317 }
Guillaume Chatelet6c127cd2019-09-20 13:40:31 +0000318 setPointerAlignment(AddrSpace, assumeAligned(PointerABIAlign),
319 assumeAligned(PointerPrefAlign), PointerMemSize,
320 IndexSize);
Micah Villmowac34b5c2012-10-04 22:08:14 +0000321 break;
322 }
323 case 'i':
324 case 'v':
325 case 'f':
Rafael Espindola6994fdf2014-01-01 22:29:43 +0000326 case 'a': {
Micah Villmowac34b5c2012-10-04 22:08:14 +0000327 AlignTypeEnum AlignType;
Patrik Hagglund086ee1e2012-11-30 10:06:59 +0000328 switch (Specifier) {
Craig Topper64a65ec2017-05-22 19:28:36 +0000329 default: llvm_unreachable("Unexpected specifier!");
Micah Villmowac34b5c2012-10-04 22:08:14 +0000330 case 'i': AlignType = INTEGER_ALIGN; break;
331 case 'v': AlignType = VECTOR_ALIGN; break;
332 case 'f': AlignType = FLOAT_ALIGN; break;
333 case 'a': AlignType = AGGREGATE_ALIGN; break;
Micah Villmowac34b5c2012-10-04 22:08:14 +0000334 }
Micah Villmowac34b5c2012-10-04 22:08:14 +0000335
Patrik Hagglund086ee1e2012-11-30 10:06:59 +0000336 // Bit size.
337 unsigned Size = Tok.empty() ? 0 : getInt(Tok);
338
David Majnemer5330c692014-12-10 01:17:08 +0000339 if (AlignType == AGGREGATE_ALIGN && Size != 0)
340 report_fatal_error(
341 "Sized aggregate specification in datalayout string");
Rafael Espindolaabdd7262014-01-06 21:40:24 +0000342
Patrik Hagglund086ee1e2012-11-30 10:06:59 +0000343 // ABI alignment.
David Majnemer612f3122014-12-10 02:36:41 +0000344 if (Rest.empty())
345 report_fatal_error(
346 "Missing alignment specification in datalayout string");
Patrik Hagglund086ee1e2012-11-30 10:06:59 +0000347 Split = split(Rest, ':');
Guillaume Chatelet6c127cd2019-09-20 13:40:31 +0000348 const unsigned ABIAlign = inBytes(getInt(Tok));
Owen Andersonab1c7a72015-03-02 09:34:59 +0000349 if (AlignType != AGGREGATE_ALIGN && !ABIAlign)
350 report_fatal_error(
351 "ABI alignment specification must be >0 for non-aggregate types");
Patrik Hagglund086ee1e2012-11-30 10:06:59 +0000352
Guillaume Chatelet6c127cd2019-09-20 13:40:31 +0000353 if (!isUInt<16>(ABIAlign))
354 report_fatal_error("Invalid ABI alignment, must be a 16bit integer");
355 if (ABIAlign != 0 && !isPowerOf2_64(ABIAlign))
356 report_fatal_error("Invalid ABI alignment, must be a power of 2");
357
Patrik Hagglund086ee1e2012-11-30 10:06:59 +0000358 // Preferred alignment.
359 unsigned PrefAlign = ABIAlign;
360 if (!Rest.empty()) {
361 Split = split(Rest, ':');
362 PrefAlign = inBytes(getInt(Tok));
Micah Villmowac34b5c2012-10-04 22:08:14 +0000363 }
Micah Villmowac34b5c2012-10-04 22:08:14 +0000364
Guillaume Chatelet6c127cd2019-09-20 13:40:31 +0000365 if (!isUInt<16>(PrefAlign))
366 report_fatal_error(
367 "Invalid preferred alignment, must be a 16bit integer");
368 if (PrefAlign != 0 && !isPowerOf2_64(PrefAlign))
369 report_fatal_error("Invalid preferred alignment, must be a power of 2");
370
371 setAlignment(AlignType, assumeAligned(ABIAlign), assumeAligned(PrefAlign),
372 Size);
Micah Villmowb4faa152012-10-04 23:01:22 +0000373
Micah Villmowac34b5c2012-10-04 22:08:14 +0000374 break;
375 }
376 case 'n': // Native integer types.
Eugene Zelenkof53a7b42017-05-05 22:30:37 +0000377 while (true) {
Patrik Hagglund086ee1e2012-11-30 10:06:59 +0000378 unsigned Width = getInt(Tok);
David Majnemer5330c692014-12-10 01:17:08 +0000379 if (Width == 0)
380 report_fatal_error(
381 "Zero width native integer type in datalayout string");
Patrik Hägglund3eb16c52012-11-28 12:13:12 +0000382 LegalIntWidths.push_back(Width);
Patrik Hagglund086ee1e2012-11-30 10:06:59 +0000383 if (Rest.empty())
384 break;
385 Split = split(Rest, ':');
386 }
Micah Villmowac34b5c2012-10-04 22:08:14 +0000387 break;
388 case 'S': { // Stack natural alignment.
Florian Hahnd8c3c172019-08-07 17:20:55 +0000389 uint64_t Alignment = inBytes(getInt(Tok));
390 if (Alignment != 0 && !llvm::isPowerOf2_64(Alignment))
391 report_fatal_error("Alignment is neither 0 nor a power of 2");
392 StackNaturalAlign = MaybeAlign(Alignment);
Micah Villmowac34b5c2012-10-04 22:08:14 +0000393 break;
394 }
Michael Platings308e82e2019-03-08 10:44:06 +0000395 case 'F': {
396 switch (Tok.front()) {
397 case 'i':
398 TheFunctionPtrAlignType = FunctionPtrAlignType::Independent;
399 break;
400 case 'n':
401 TheFunctionPtrAlignType = FunctionPtrAlignType::MultipleOfFunctionAlign;
402 break;
403 default:
404 report_fatal_error("Unknown function pointer alignment type in "
405 "datalayout string");
406 }
407 Tok = Tok.substr(1);
Florian Hahnd8c3c172019-08-07 17:20:55 +0000408 uint64_t Alignment = inBytes(getInt(Tok));
409 if (Alignment != 0 && !llvm::isPowerOf2_64(Alignment))
410 report_fatal_error("Alignment is neither 0 nor a power of 2");
411 FunctionPtrAlign = MaybeAlign(Alignment);
Michael Platings308e82e2019-03-08 10:44:06 +0000412 break;
413 }
Dylan McKayced2fe62018-02-19 09:56:22 +0000414 case 'P': { // Function address space.
415 ProgramAddrSpace = getAddrSpace(Tok);
416 break;
417 }
Matt Arsenault3c1fc762017-04-10 22:27:50 +0000418 case 'A': { // Default stack/alloca address space.
Dylan McKayced2fe62018-02-19 09:56:22 +0000419 AllocaAddrSpace = getAddrSpace(Tok);
Matt Arsenault3c1fc762017-04-10 22:27:50 +0000420 break;
421 }
Rafael Espindola58873562014-01-03 19:21:54 +0000422 case 'm':
David Majnemer612f3122014-12-10 02:36:41 +0000423 if (!Tok.empty())
424 report_fatal_error("Unexpected trailing characters after mangling specifier in datalayout string");
425 if (Rest.empty())
426 report_fatal_error("Expected mangling specifier in datalayout string");
427 if (Rest.size() > 1)
428 report_fatal_error("Unknown mangling specifier in datalayout string");
Rafael Espindola58873562014-01-03 19:21:54 +0000429 switch(Rest[0]) {
430 default:
David Majnemer5330c692014-12-10 01:17:08 +0000431 report_fatal_error("Unknown mangling in datalayout string");
Rafael Espindola58873562014-01-03 19:21:54 +0000432 case 'e':
433 ManglingMode = MM_ELF;
434 break;
435 case 'o':
436 ManglingMode = MM_MachO;
437 break;
438 case 'm':
439 ManglingMode = MM_Mips;
440 break;
Rafael Espindolaaf77e122014-01-10 13:42:12 +0000441 case 'w':
David Majnemer7db449a2015-03-17 23:54:51 +0000442 ManglingMode = MM_WinCOFF;
443 break;
444 case 'x':
445 ManglingMode = MM_WinCOFFX86;
Rafael Espindola58873562014-01-03 19:21:54 +0000446 break;
447 }
448 break;
Micah Villmowac34b5c2012-10-04 22:08:14 +0000449 default:
David Majnemer5330c692014-12-10 01:17:08 +0000450 report_fatal_error("Unknown specifier in datalayout string");
Micah Villmowac34b5c2012-10-04 22:08:14 +0000451 break;
452 }
453 }
Micah Villmowac34b5c2012-10-04 22:08:14 +0000454}
455
Eugene Zelenkof53a7b42017-05-05 22:30:37 +0000456DataLayout::DataLayout(const Module *M) {
Rafael Espindolac435adc2014-09-10 21:27:43 +0000457 init(M);
458}
459
Mehdi Amini46a43552015-03-04 18:43:29 +0000460void DataLayout::init(const Module *M) { *this = M->getDataLayout(); }
Micah Villmowac34b5c2012-10-04 22:08:14 +0000461
Rafael Espindolaae593f12014-02-26 17:02:08 +0000462bool DataLayout::operator==(const DataLayout &Other) const {
Chandler Carruthf67321c2014-10-20 10:41:29 +0000463 bool Ret = BigEndian == Other.BigEndian &&
Matt Arsenault3c1fc762017-04-10 22:27:50 +0000464 AllocaAddrSpace == Other.AllocaAddrSpace &&
Rafael Espindolaae593f12014-02-26 17:02:08 +0000465 StackNaturalAlign == Other.StackNaturalAlign &&
Dylan McKayced2fe62018-02-19 09:56:22 +0000466 ProgramAddrSpace == Other.ProgramAddrSpace &&
Michael Platings308e82e2019-03-08 10:44:06 +0000467 FunctionPtrAlign == Other.FunctionPtrAlign &&
468 TheFunctionPtrAlignType == Other.TheFunctionPtrAlignType &&
Rafael Espindolaae593f12014-02-26 17:02:08 +0000469 ManglingMode == Other.ManglingMode &&
470 LegalIntWidths == Other.LegalIntWidths &&
Rafael Espindola89992b02014-04-22 17:47:03 +0000471 Alignments == Other.Alignments && Pointers == Other.Pointers;
Mehdi Amini46a43552015-03-04 18:43:29 +0000472 // Note: getStringRepresentation() might differs, it is not canonicalized
Rafael Espindolaae593f12014-02-26 17:02:08 +0000473 return Ret;
474}
475
Craig Topper490889c2017-03-23 06:15:56 +0000476DataLayout::AlignmentsTy::iterator
477DataLayout::findAlignmentLowerBound(AlignTypeEnum AlignType,
478 uint32_t BitWidth) {
479 auto Pair = std::make_pair((unsigned)AlignType, BitWidth);
Fangrui Song78ee2fb2019-06-30 11:19:56 +0000480 return partition_point(Alignments, [=](const LayoutAlignElem &E) {
481 return std::make_pair(E.AlignType, E.TypeBitWidth) < Pair;
Fangrui Songdc8de602019-06-21 05:40:31 +0000482 });
Craig Topper490889c2017-03-23 06:15:56 +0000483}
484
Guillaume Chatelet18f805a2019-09-27 12:54:21 +0000485void DataLayout::setAlignment(AlignTypeEnum align_type, Align abi_align,
486 Align pref_align, uint32_t bit_width) {
Guillaume Chatelet6c127cd2019-09-20 13:40:31 +0000487 // AlignmentsTy::ABIAlign and AlignmentsTy::PrefAlign were once stored as
488 // uint16_t, it is unclear if there are requirements for alignment to be less
489 // than 2^16 other than storage. In the meantime we leave the restriction as
490 // an assert. See D67400 for context.
491 assert(Log2(abi_align) < 16 && Log2(pref_align) < 16 && "Alignment too big");
David Majnemer1b9fc3a2015-02-16 05:41:53 +0000492 if (!isUInt<24>(bit_width))
493 report_fatal_error("Invalid bit width, must be a 24bit integer");
David Majnemer1b9fc3a2015-02-16 05:41:53 +0000494 if (pref_align < abi_align)
495 report_fatal_error(
496 "Preferred alignment cannot be less than the ABI alignment");
497
Craig Topper490889c2017-03-23 06:15:56 +0000498 AlignmentsTy::iterator I = findAlignmentLowerBound(align_type, bit_width);
499 if (I != Alignments.end() &&
500 I->AlignType == (unsigned)align_type && I->TypeBitWidth == bit_width) {
501 // Update the abi, preferred alignments.
502 I->ABIAlign = abi_align;
503 I->PrefAlign = pref_align;
504 } else {
505 // Insert before I to keep the vector sorted.
506 Alignments.insert(I, LayoutAlignElem::get(align_type, abi_align,
507 pref_align, bit_width));
Micah Villmowac34b5c2012-10-04 22:08:14 +0000508 }
Micah Villmowac34b5c2012-10-04 22:08:14 +0000509}
510
Rafael Espindola667fcb82014-02-26 16:58:35 +0000511DataLayout::PointersTy::iterator
Rafael Espindolae8ae0db2014-02-26 17:05:38 +0000512DataLayout::findPointerLowerBound(uint32_t AddressSpace) {
Rafael Espindola667fcb82014-02-26 16:58:35 +0000513 return std::lower_bound(Pointers.begin(), Pointers.end(), AddressSpace,
Benjamin Kramer3ad5c962014-03-10 15:03:06 +0000514 [](const PointerAlignElem &A, uint32_t AddressSpace) {
515 return A.AddressSpace < AddressSpace;
516 });
Rafael Espindola667fcb82014-02-26 16:58:35 +0000517}
518
Guillaume Chatelet18f805a2019-09-27 12:54:21 +0000519void DataLayout::setPointerAlignment(uint32_t AddrSpace, Align ABIAlign,
520 Align PrefAlign, uint32_t TypeByteWidth,
Elena Demikhovsky945b7e52018-02-14 06:58:08 +0000521 uint32_t IndexWidth) {
David Majnemer4b042922015-02-16 05:41:55 +0000522 if (PrefAlign < ABIAlign)
523 report_fatal_error(
524 "Preferred alignment cannot be less than the ABI alignment");
525
Rafael Espindolae8ae0db2014-02-26 17:05:38 +0000526 PointersTy::iterator I = findPointerLowerBound(AddrSpace);
Rafael Espindola667fcb82014-02-26 16:58:35 +0000527 if (I == Pointers.end() || I->AddressSpace != AddrSpace) {
528 Pointers.insert(I, PointerAlignElem::get(AddrSpace, ABIAlign, PrefAlign,
Elena Demikhovsky945b7e52018-02-14 06:58:08 +0000529 TypeByteWidth, IndexWidth));
Micah Villmow89021e42012-10-09 16:06:12 +0000530 } else {
Rafael Espindola667fcb82014-02-26 16:58:35 +0000531 I->ABIAlign = ABIAlign;
532 I->PrefAlign = PrefAlign;
533 I->TypeByteWidth = TypeByteWidth;
Elena Demikhovsky945b7e52018-02-14 06:58:08 +0000534 I->IndexWidth = IndexWidth;
Micah Villmow89021e42012-10-09 16:06:12 +0000535 }
536}
537
Micah Villmowac34b5c2012-10-04 22:08:14 +0000538/// getAlignmentInfo - Return the alignment (either ABI if ABIInfo = true or
Micah Villmowb4faa152012-10-04 23:01:22 +0000539/// preferred if ABIInfo = false) the layout wants for the specified datatype.
Guillaume Chatelet18f805a2019-09-27 12:54:21 +0000540Align DataLayout::getAlignmentInfo(AlignTypeEnum AlignType, uint32_t BitWidth,
541 bool ABIInfo, Type *Ty) const {
Craig Topper490889c2017-03-23 06:15:56 +0000542 AlignmentsTy::const_iterator I = findAlignmentLowerBound(AlignType, BitWidth);
543 // See if we found an exact match. Of if we are looking for an integer type,
544 // but don't have an exact match take the next largest integer. This is where
545 // the lower_bound will point to when it fails an exact match.
546 if (I != Alignments.end() && I->AlignType == (unsigned)AlignType &&
547 (I->TypeBitWidth == BitWidth || AlignType == INTEGER_ALIGN))
Guillaume Chatelet046a16b2019-09-23 08:38:36 +0000548 return ABIInfo ? I->ABIAlign : I->PrefAlign;
Micah Villmowac34b5c2012-10-04 22:08:14 +0000549
Craig Topper490889c2017-03-23 06:15:56 +0000550 if (AlignType == INTEGER_ALIGN) {
551 // If we didn't have a larger value try the largest value we have.
552 if (I != Alignments.begin()) {
553 --I; // Go to the previous entry and see if its an integer.
554 if (I->AlignType == INTEGER_ALIGN)
Guillaume Chatelet046a16b2019-09-23 08:38:36 +0000555 return ABIInfo ? I->ABIAlign : I->PrefAlign;
Micah Villmowac34b5c2012-10-04 22:08:14 +0000556 }
Craig Topper490889c2017-03-23 06:15:56 +0000557 } else if (AlignType == VECTOR_ALIGN) {
558 // By default, use natural alignment for vector types. This is consistent
559 // with what clang and llvm-gcc do.
Guillaume Chatelet18f805a2019-09-27 12:54:21 +0000560 unsigned Alignment =
561 getTypeAllocSize(cast<VectorType>(Ty)->getElementType());
562 Alignment *= cast<VectorType>(Ty)->getNumElements();
563 Alignment = PowerOf2Ceil(Alignment);
564 return Align(Alignment);
Craig Topper490889c2017-03-23 06:15:56 +0000565 }
Micah Villmowac34b5c2012-10-04 22:08:14 +0000566
Owen Anderson7e621e92015-03-08 21:53:59 +0000567 // If we still couldn't find a reasonable default alignment, fall back
568 // to a simple heuristic that the alignment is the first power of two
569 // greater-or-equal to the store size of the type. This is a reasonable
570 // approximation of reality, and if the user wanted something less
571 // less conservative, they should have specified it explicitly in the data
572 // layout.
Guillaume Chatelet18f805a2019-09-27 12:54:21 +0000573 unsigned Alignment = getTypeStoreSize(Ty);
574 Alignment = PowerOf2Ceil(Alignment);
575 return Align(Alignment);
Micah Villmowac34b5c2012-10-04 22:08:14 +0000576}
577
578namespace {
579
580class StructLayoutMap {
Eugene Zelenkof53a7b42017-05-05 22:30:37 +0000581 using LayoutInfoTy = DenseMap<StructType*, StructLayout*>;
Micah Villmowac34b5c2012-10-04 22:08:14 +0000582 LayoutInfoTy LayoutInfo;
583
584public:
Benjamin Kramer3ad5c962014-03-10 15:03:06 +0000585 ~StructLayoutMap() {
Micah Villmowac34b5c2012-10-04 22:08:14 +0000586 // Remove any layouts.
Benjamin Kramer3ad5c962014-03-10 15:03:06 +0000587 for (const auto &I : LayoutInfo) {
588 StructLayout *Value = I.second;
Micah Villmowac34b5c2012-10-04 22:08:14 +0000589 Value->~StructLayout();
590 free(Value);
591 }
592 }
593
Pete Cooper0ae73932015-07-27 17:15:28 +0000594 StructLayout *&operator[](StructType *STy) {
Micah Villmowac34b5c2012-10-04 22:08:14 +0000595 return LayoutInfo[STy];
596 }
Micah Villmowac34b5c2012-10-04 22:08:14 +0000597};
598
599} // end anonymous namespace
600
Rafael Espindola248ac132014-02-25 22:23:04 +0000601void DataLayout::clear() {
602 LegalIntWidths.clear();
603 Alignments.clear();
604 Pointers.clear();
605 delete static_cast<StructLayoutMap *>(LayoutMap);
Craig Topperc6207612014-04-09 06:08:46 +0000606 LayoutMap = nullptr;
Rafael Espindola248ac132014-02-25 22:23:04 +0000607}
608
Micah Villmowb4faa152012-10-04 23:01:22 +0000609DataLayout::~DataLayout() {
Rafael Espindola248ac132014-02-25 22:23:04 +0000610 clear();
Micah Villmowac34b5c2012-10-04 22:08:14 +0000611}
612
Pete Cooper0ae73932015-07-27 17:15:28 +0000613const StructLayout *DataLayout::getStructLayout(StructType *Ty) const {
Micah Villmowac34b5c2012-10-04 22:08:14 +0000614 if (!LayoutMap)
615 LayoutMap = new StructLayoutMap();
616
617 StructLayoutMap *STM = static_cast<StructLayoutMap*>(LayoutMap);
618 StructLayout *&SL = (*STM)[Ty];
619 if (SL) return SL;
620
621 // Otherwise, create the struct layout. Because it is variable length, we
622 // malloc it, then use placement new.
623 int NumElts = Ty->getNumElements();
Serge Pavlov15681ad2018-06-09 05:19:45 +0000624 StructLayout *L = (StructLayout *)
625 safe_malloc(sizeof(StructLayout)+(NumElts-1) * sizeof(uint64_t));
Micah Villmowac34b5c2012-10-04 22:08:14 +0000626
627 // Set SL before calling StructLayout's ctor. The ctor could cause other
628 // entries to be added to TheMap, invalidating our reference.
629 SL = L;
630
631 new (L) StructLayout(Ty, *this);
632
633 return L;
634}
635
Guillaume Chatelet18f805a2019-09-27 12:54:21 +0000636Align DataLayout::getPointerABIAlignment(unsigned AS) const {
Rafael Espindolae8ae0db2014-02-26 17:05:38 +0000637 PointersTy::const_iterator I = findPointerLowerBound(AS);
Rafael Espindola667fcb82014-02-26 16:58:35 +0000638 if (I == Pointers.end() || I->AddressSpace != AS) {
Rafael Espindolae8ae0db2014-02-26 17:05:38 +0000639 I = findPointerLowerBound(0);
Rafael Espindola667fcb82014-02-26 16:58:35 +0000640 assert(I->AddressSpace == 0);
Rafael Espindola5109fcc2014-02-26 16:49:40 +0000641 }
Guillaume Chatelet1ae79052019-09-23 12:41:36 +0000642 return I->ABIAlign;
Rafael Espindola5109fcc2014-02-26 16:49:40 +0000643}
644
Guillaume Chatelet18f805a2019-09-27 12:54:21 +0000645Align DataLayout::getPointerPrefAlignment(unsigned AS) const {
Rafael Espindolae8ae0db2014-02-26 17:05:38 +0000646 PointersTy::const_iterator I = findPointerLowerBound(AS);
Rafael Espindola667fcb82014-02-26 16:58:35 +0000647 if (I == Pointers.end() || I->AddressSpace != AS) {
Rafael Espindolae8ae0db2014-02-26 17:05:38 +0000648 I = findPointerLowerBound(0);
Rafael Espindola667fcb82014-02-26 16:58:35 +0000649 assert(I->AddressSpace == 0);
Rafael Espindola5109fcc2014-02-26 16:49:40 +0000650 }
Guillaume Chatelet1ae79052019-09-23 12:41:36 +0000651 return I->PrefAlign;
Rafael Espindola5109fcc2014-02-26 16:49:40 +0000652}
653
654unsigned DataLayout::getPointerSize(unsigned AS) const {
Rafael Espindolae8ae0db2014-02-26 17:05:38 +0000655 PointersTy::const_iterator I = findPointerLowerBound(AS);
Rafael Espindola667fcb82014-02-26 16:58:35 +0000656 if (I == Pointers.end() || I->AddressSpace != AS) {
Rafael Espindolae8ae0db2014-02-26 17:05:38 +0000657 I = findPointerLowerBound(0);
Rafael Espindola667fcb82014-02-26 16:58:35 +0000658 assert(I->AddressSpace == 0);
Rafael Espindola5109fcc2014-02-26 16:49:40 +0000659 }
Rafael Espindola667fcb82014-02-26 16:58:35 +0000660 return I->TypeByteWidth;
Rafael Espindola5109fcc2014-02-26 16:49:40 +0000661}
662
Hal Finkel4f238142019-01-02 16:28:09 +0000663unsigned DataLayout::getMaxPointerSize() const {
664 unsigned MaxPointerSize = 0;
665 for (auto &P : Pointers)
666 MaxPointerSize = std::max(MaxPointerSize, P.TypeByteWidth);
667
668 return MaxPointerSize;
669}
670
Pete Cooper0ae73932015-07-27 17:15:28 +0000671unsigned DataLayout::getPointerTypeSizeInBits(Type *Ty) const {
Matt Arsenault6f4be902013-07-26 17:37:20 +0000672 assert(Ty->isPtrOrPtrVectorTy() &&
673 "This should only be called with a pointer or pointer vector type");
Craig Topper5b4f5b02017-04-17 18:22:36 +0000674 Ty = Ty->getScalarType();
675 return getPointerSizeInBits(cast<PointerType>(Ty)->getAddressSpace());
Matt Arsenault6f4be902013-07-26 17:37:20 +0000676}
Micah Villmowac34b5c2012-10-04 22:08:14 +0000677
Elena Demikhovsky945b7e52018-02-14 06:58:08 +0000678unsigned DataLayout::getIndexSize(unsigned AS) const {
679 PointersTy::const_iterator I = findPointerLowerBound(AS);
680 if (I == Pointers.end() || I->AddressSpace != AS) {
681 I = findPointerLowerBound(0);
682 assert(I->AddressSpace == 0);
683 }
684 return I->IndexWidth;
685}
686
687unsigned DataLayout::getIndexTypeSizeInBits(Type *Ty) const {
688 assert(Ty->isPtrOrPtrVectorTy() &&
689 "This should only be called with a pointer or pointer vector type");
690 Ty = Ty->getScalarType();
691 return getIndexSizeInBits(cast<PointerType>(Ty)->getAddressSpace());
692}
693
Micah Villmowac34b5c2012-10-04 22:08:14 +0000694/*!
695 \param abi_or_pref Flag that determines which alignment is returned. true
696 returns the ABI alignment, false returns the preferred alignment.
697 \param Ty The underlying type for which alignment is determined.
698
699 Get the ABI (\a abi_or_pref == true) or preferred alignment (\a abi_or_pref
700 == false) for the requested type \a Ty.
701 */
Guillaume Chatelet18f805a2019-09-27 12:54:21 +0000702Align DataLayout::getAlignment(Type *Ty, bool abi_or_pref) const {
Craig Topperff6922a2017-04-19 00:31:38 +0000703 AlignTypeEnum AlignType;
Micah Villmowac34b5c2012-10-04 22:08:14 +0000704
705 assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!");
706 switch (Ty->getTypeID()) {
707 // Early escape for the non-numeric types.
708 case Type::LabelTyID:
Guillaume Chatelet1ae79052019-09-23 12:41:36 +0000709 return abi_or_pref ? getPointerABIAlignment(0) : getPointerPrefAlignment(0);
Micah Villmow89021e42012-10-09 16:06:12 +0000710 case Type::PointerTyID: {
Matt Arsenaultc1728972014-09-18 22:28:56 +0000711 unsigned AS = cast<PointerType>(Ty)->getAddressSpace();
Guillaume Chatelet1ae79052019-09-23 12:41:36 +0000712 return abi_or_pref ? getPointerABIAlignment(AS)
713 : getPointerPrefAlignment(AS);
Micah Villmow89021e42012-10-09 16:06:12 +0000714 }
Micah Villmowac34b5c2012-10-04 22:08:14 +0000715 case Type::ArrayTyID:
716 return getAlignment(cast<ArrayType>(Ty)->getElementType(), abi_or_pref);
717
718 case Type::StructTyID: {
719 // Packed structure types always have an ABI alignment of one.
720 if (cast<StructType>(Ty)->isPacked() && abi_or_pref)
Guillaume Chatelet18f805a2019-09-27 12:54:21 +0000721 return Align::None();
Micah Villmowac34b5c2012-10-04 22:08:14 +0000722
723 // Get the layout annotation... which is lazily created on demand.
724 const StructLayout *Layout = getStructLayout(cast<StructType>(Ty));
Guillaume Chatelet18f805a2019-09-27 12:54:21 +0000725 const Align Align = getAlignmentInfo(AGGREGATE_ALIGN, 0, abi_or_pref, Ty);
Micah Villmowac34b5c2012-10-04 22:08:14 +0000726 return std::max(Align, Layout->getAlignment());
727 }
728 case Type::IntegerTyID:
Micah Villmowac34b5c2012-10-04 22:08:14 +0000729 AlignType = INTEGER_ALIGN;
730 break;
731 case Type::HalfTyID:
732 case Type::FloatTyID:
733 case Type::DoubleTyID:
734 // PPC_FP128TyID and FP128TyID have different data contents, but the
735 // same size and alignment, so they look the same here.
736 case Type::PPC_FP128TyID:
737 case Type::FP128TyID:
738 case Type::X86_FP80TyID:
739 AlignType = FLOAT_ALIGN;
740 break;
741 case Type::X86_MMXTyID:
742 case Type::VectorTyID:
743 AlignType = VECTOR_ALIGN;
744 break;
745 default:
746 llvm_unreachable("Bad type for getAlignment!!!");
747 }
748
Graham Hunterb3025612019-10-08 12:53:54 +0000749 // If we're dealing with a scalable vector, we just need the known minimum
750 // size for determining alignment. If not, we'll get the exact size.
751 return getAlignmentInfo(AlignType, getTypeSizeInBits(Ty).getKnownMinSize(),
752 abi_or_pref, Ty);
Micah Villmowac34b5c2012-10-04 22:08:14 +0000753}
754
Pete Cooper0ae73932015-07-27 17:15:28 +0000755unsigned DataLayout::getABITypeAlignment(Type *Ty) const {
Guillaume Chatelet046a16b2019-09-23 08:38:36 +0000756 return getAlignment(Ty, true).value();
Micah Villmowac34b5c2012-10-04 22:08:14 +0000757}
758
759/// getABIIntegerTypeAlignment - Return the minimum ABI-required alignment for
760/// an integer type of the specified bitwidth.
Guillaume Chatelet18f805a2019-09-27 12:54:21 +0000761Align DataLayout::getABIIntegerTypeAlignment(unsigned BitWidth) const {
Guillaume Chatelet1ae79052019-09-23 12:41:36 +0000762 return getAlignmentInfo(INTEGER_ALIGN, BitWidth, true, nullptr);
Micah Villmowac34b5c2012-10-04 22:08:14 +0000763}
764
Pete Cooper0ae73932015-07-27 17:15:28 +0000765unsigned DataLayout::getPrefTypeAlignment(Type *Ty) const {
Guillaume Chatelet046a16b2019-09-23 08:38:36 +0000766 return getAlignment(Ty, false).value();
Micah Villmowac34b5c2012-10-04 22:08:14 +0000767}
768
Micah Villmow89021e42012-10-09 16:06:12 +0000769IntegerType *DataLayout::getIntPtrType(LLVMContext &C,
770 unsigned AddressSpace) const {
Nicola Zaghen97572772019-12-13 09:55:45 +0000771 return IntegerType::get(C, getPointerSizeInBits(AddressSpace));
Micah Villmowac34b5c2012-10-04 22:08:14 +0000772}
773
Pete Cooper0ae73932015-07-27 17:15:28 +0000774Type *DataLayout::getIntPtrType(Type *Ty) const {
Chandler Carruth7ec50852012-11-01 08:07:29 +0000775 assert(Ty->isPtrOrPtrVectorTy() &&
776 "Expected a pointer or pointer vector type.");
Nicola Zaghen97572772019-12-13 09:55:45 +0000777 unsigned NumBits = getPointerTypeSizeInBits(Ty);
Duncan Sands5bdd9dd2012-10-29 17:31:46 +0000778 IntegerType *IntTy = IntegerType::get(Ty->getContext(), NumBits);
Pete Cooper0ae73932015-07-27 17:15:28 +0000779 if (VectorType *VecTy = dyn_cast<VectorType>(Ty))
Duncan Sands5bdd9dd2012-10-29 17:31:46 +0000780 return VectorType::get(IntTy, VecTy->getNumElements());
781 return IntTy;
Micah Villmow12d91272012-10-24 15:52:52 +0000782}
783
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000784Type *DataLayout::getSmallestLegalIntType(LLVMContext &C, unsigned Width) const {
Benjamin Kramer3ad5c962014-03-10 15:03:06 +0000785 for (unsigned LegalIntWidth : LegalIntWidths)
786 if (Width <= LegalIntWidth)
787 return Type::getIntNTy(C, LegalIntWidth);
Craig Topperc6207612014-04-09 06:08:46 +0000788 return nullptr;
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000789}
790
Jun Bum Limbe11bdc2016-05-13 18:38:35 +0000791unsigned DataLayout::getLargestLegalIntTypeSizeInBits() const {
Benjamin Kramer3ad5c962014-03-10 15:03:06 +0000792 auto Max = std::max_element(LegalIntWidths.begin(), LegalIntWidths.end());
793 return Max != LegalIntWidths.end() ? *Max : 0;
Matt Arsenault899f7d22013-09-16 22:43:16 +0000794}
795
Elena Demikhovsky945b7e52018-02-14 06:58:08 +0000796Type *DataLayout::getIndexType(Type *Ty) const {
797 assert(Ty->isPtrOrPtrVectorTy() &&
798 "Expected a pointer or pointer vector type.");
799 unsigned NumBits = getIndexTypeSizeInBits(Ty);
800 IntegerType *IntTy = IntegerType::get(Ty->getContext(), NumBits);
801 if (VectorType *VecTy = dyn_cast<VectorType>(Ty))
802 return VectorType::get(IntTy, VecTy->getNumElements());
803 return IntTy;
804}
805
David Majnemer17bdf442016-07-13 03:42:38 +0000806int64_t DataLayout::getIndexedOffsetInType(Type *ElemTy,
807 ArrayRef<Value *> Indices) const {
808 int64_t Result = 0;
Micah Villmowac34b5c2012-10-04 22:08:14 +0000809
810 generic_gep_type_iterator<Value* const*>
Peter Collingbourneab85225b2016-12-02 02:24:42 +0000811 GTI = gep_type_begin(ElemTy, Indices),
812 GTE = gep_type_end(ElemTy, Indices);
Eduard Burtescu68e7f492016-01-22 03:08:27 +0000813 for (; GTI != GTE; ++GTI) {
814 Value *Idx = GTI.getOperand();
Peter Collingbourneab85225b2016-12-02 02:24:42 +0000815 if (StructType *STy = GTI.getStructTypeOrNull()) {
Manuel Jacobcc13c2c2016-01-22 03:30:27 +0000816 assert(Idx->getType()->isIntegerTy(32) && "Illegal struct idx");
Eduard Burtescu68e7f492016-01-22 03:08:27 +0000817 unsigned FieldNo = cast<ConstantInt>(Idx)->getZExtValue();
Micah Villmowac34b5c2012-10-04 22:08:14 +0000818
819 // Get structure layout information...
820 const StructLayout *Layout = getStructLayout(STy);
821
822 // Add in the offset, as calculated by the structure layout info...
823 Result += Layout->getElementOffset(FieldNo);
Micah Villmowac34b5c2012-10-04 22:08:14 +0000824 } else {
Micah Villmowac34b5c2012-10-04 22:08:14 +0000825 // Get the array index and the size of each array element.
Eduard Burtescu68e7f492016-01-22 03:08:27 +0000826 if (int64_t arrayIdx = cast<ConstantInt>(Idx)->getSExtValue())
David Majnemer17bdf442016-07-13 03:42:38 +0000827 Result += arrayIdx * getTypeAllocSize(GTI.getIndexedType());
Micah Villmowac34b5c2012-10-04 22:08:14 +0000828 }
829 }
830
831 return Result;
832}
833
834/// getPreferredAlignment - Return the preferred alignment of the specified
835/// global. This includes an explicitly requested alignment (if the global
836/// has one).
Micah Villmowb4faa152012-10-04 23:01:22 +0000837unsigned DataLayout::getPreferredAlignment(const GlobalVariable *GV) const {
Eli Friedman37696392018-08-29 23:46:26 +0000838 unsigned GVAlignment = GV->getAlignment();
839 // If a section is specified, always precisely honor explicit alignment,
840 // so we don't insert padding into a section we don't control.
841 if (GVAlignment && GV->hasSection())
842 return GVAlignment;
843
844 // If no explicit alignment is specified, compute the alignment based on
845 // the IR type. If an alignment is specified, increase it to match the ABI
846 // alignment of the IR type.
847 //
848 // FIXME: Not sure it makes sense to use the alignment of the type if
849 // there's already an explicit alignment specification.
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000850 Type *ElemType = GV->getValueType();
Micah Villmowac34b5c2012-10-04 22:08:14 +0000851 unsigned Alignment = getPrefTypeAlignment(ElemType);
Micah Villmowac34b5c2012-10-04 22:08:14 +0000852 if (GVAlignment >= Alignment) {
853 Alignment = GVAlignment;
854 } else if (GVAlignment != 0) {
855 Alignment = std::max(GVAlignment, getABITypeAlignment(ElemType));
856 }
857
Eli Friedman37696392018-08-29 23:46:26 +0000858 // If no explicit alignment is specified, and the global is large, increase
859 // the alignment to 16.
860 // FIXME: Why 16, specifically?
Micah Villmowac34b5c2012-10-04 22:08:14 +0000861 if (GV->hasInitializer() && GVAlignment == 0) {
862 if (Alignment < 16) {
863 // If the global is not external, see if it is large. If so, give it a
864 // larger alignment.
865 if (getTypeSizeInBits(ElemType) > 128)
866 Alignment = 16; // 16-byte alignment.
867 }
868 }
869 return Alignment;
870}
871
872/// getPreferredAlignmentLog - Return the preferred alignment of the
873/// specified global, returned in log form. This includes an explicitly
874/// requested alignment (if the global has one).
Micah Villmowb4faa152012-10-04 23:01:22 +0000875unsigned DataLayout::getPreferredAlignmentLog(const GlobalVariable *GV) const {
Micah Villmowac34b5c2012-10-04 22:08:14 +0000876 return Log2_32(getPreferredAlignment(GV));
877}