DataLayout.cpp 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016
  1. //===- DataLayout.cpp - Data size & alignment routines ---------------------==//
  2. //
  3. // 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
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines layout properties related to datatype size/offset/alignment
  10. // 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. #include "llvm/IR/DataLayout.h"
  18. #include "llvm/ADT/DenseMap.h"
  19. #include "llvm/ADT/StringRef.h"
  20. #include "llvm/ADT/Triple.h"
  21. #include "llvm/IR/Constants.h"
  22. #include "llvm/IR/DerivedTypes.h"
  23. #include "llvm/IR/GetElementPtrTypeIterator.h"
  24. #include "llvm/IR/GlobalVariable.h"
  25. #include "llvm/IR/Module.h"
  26. #include "llvm/IR/Type.h"
  27. #include "llvm/IR/Value.h"
  28. #include "llvm/Support/Casting.h"
  29. #include "llvm/Support/Error.h"
  30. #include "llvm/Support/ErrorHandling.h"
  31. #include "llvm/Support/MathExtras.h"
  32. #include "llvm/Support/MemAlloc.h"
  33. #include "llvm/Support/TypeSize.h"
  34. #include <algorithm>
  35. #include <cassert>
  36. #include <cstdint>
  37. #include <cstdlib>
  38. #include <new>
  39. #include <utility>
  40. using namespace llvm;
  41. //===----------------------------------------------------------------------===//
  42. // Support for StructLayout
  43. //===----------------------------------------------------------------------===//
  44. StructLayout::StructLayout(StructType *ST, const DataLayout &DL) {
  45. assert(!ST->isOpaque() && "Cannot get layout of opaque structs");
  46. StructSize = 0;
  47. IsPadded = false;
  48. NumElements = ST->getNumElements();
  49. // Loop over each of the elements, placing them in memory.
  50. for (unsigned i = 0, e = NumElements; i != e; ++i) {
  51. Type *Ty = ST->getElementType(i);
  52. const Align TyAlign = ST->isPacked() ? Align(1) : DL.getABITypeAlign(Ty);
  53. // Add padding if necessary to align the data element properly.
  54. if (!isAligned(TyAlign, StructSize)) {
  55. IsPadded = true;
  56. StructSize = alignTo(StructSize, TyAlign);
  57. }
  58. // Keep track of maximum alignment constraint.
  59. StructAlignment = std::max(TyAlign, StructAlignment);
  60. getMemberOffsets()[i] = StructSize;
  61. // Consume space for this data item
  62. StructSize += DL.getTypeAllocSize(Ty).getFixedValue();
  63. }
  64. // Add padding to the end of the struct so that it could be put in an array
  65. // and all array elements would be aligned correctly.
  66. if (!isAligned(StructAlignment, StructSize)) {
  67. IsPadded = true;
  68. StructSize = alignTo(StructSize, StructAlignment);
  69. }
  70. }
  71. /// getElementContainingOffset - Given a valid offset into the structure,
  72. /// return the structure index that contains it.
  73. unsigned StructLayout::getElementContainingOffset(uint64_t Offset) const {
  74. ArrayRef<uint64_t> MemberOffsets = getMemberOffsets();
  75. auto SI = llvm::upper_bound(MemberOffsets, Offset);
  76. assert(SI != MemberOffsets.begin() && "Offset not in structure type!");
  77. --SI;
  78. assert(*SI <= Offset && "upper_bound didn't work");
  79. assert((SI == MemberOffsets.begin() || *(SI - 1) <= Offset) &&
  80. (SI + 1 == MemberOffsets.end() || *(SI + 1) > Offset) &&
  81. "Upper bound didn't work!");
  82. // Multiple fields can have the same offset if any of them are zero sized.
  83. // For example, in { i32, [0 x i32], i32 }, searching for offset 4 will stop
  84. // at the i32 element, because it is the last element at that offset. This is
  85. // the right one to return, because anything after it will have a higher
  86. // offset, implying that this element is non-empty.
  87. return SI - MemberOffsets.begin();
  88. }
  89. //===----------------------------------------------------------------------===//
  90. // LayoutAlignElem, LayoutAlign support
  91. //===----------------------------------------------------------------------===//
  92. LayoutAlignElem LayoutAlignElem::get(AlignTypeEnum align_type, Align abi_align,
  93. Align pref_align, uint32_t bit_width) {
  94. assert(abi_align <= pref_align && "Preferred alignment worse than ABI!");
  95. LayoutAlignElem retval;
  96. retval.AlignType = align_type;
  97. retval.ABIAlign = abi_align;
  98. retval.PrefAlign = pref_align;
  99. retval.TypeBitWidth = bit_width;
  100. return retval;
  101. }
  102. bool
  103. LayoutAlignElem::operator==(const LayoutAlignElem &rhs) const {
  104. return (AlignType == rhs.AlignType
  105. && ABIAlign == rhs.ABIAlign
  106. && PrefAlign == rhs.PrefAlign
  107. && TypeBitWidth == rhs.TypeBitWidth);
  108. }
  109. //===----------------------------------------------------------------------===//
  110. // PointerAlignElem, PointerAlign support
  111. //===----------------------------------------------------------------------===//
  112. PointerAlignElem PointerAlignElem::getInBits(uint32_t AddressSpace,
  113. Align ABIAlign, Align PrefAlign,
  114. uint32_t TypeBitWidth,
  115. uint32_t IndexBitWidth) {
  116. assert(ABIAlign <= PrefAlign && "Preferred alignment worse than ABI!");
  117. PointerAlignElem retval;
  118. retval.AddressSpace = AddressSpace;
  119. retval.ABIAlign = ABIAlign;
  120. retval.PrefAlign = PrefAlign;
  121. retval.TypeBitWidth = TypeBitWidth;
  122. retval.IndexBitWidth = IndexBitWidth;
  123. return retval;
  124. }
  125. bool
  126. PointerAlignElem::operator==(const PointerAlignElem &rhs) const {
  127. return (ABIAlign == rhs.ABIAlign && AddressSpace == rhs.AddressSpace &&
  128. PrefAlign == rhs.PrefAlign && TypeBitWidth == rhs.TypeBitWidth &&
  129. IndexBitWidth == rhs.IndexBitWidth);
  130. }
  131. //===----------------------------------------------------------------------===//
  132. // DataLayout Class Implementation
  133. //===----------------------------------------------------------------------===//
  134. const char *DataLayout::getManglingComponent(const Triple &T) {
  135. if (T.isOSBinFormatGOFF())
  136. return "-m:l";
  137. if (T.isOSBinFormatMachO())
  138. return "-m:o";
  139. if (T.isOSWindows() && T.isOSBinFormatCOFF())
  140. return T.getArch() == Triple::x86 ? "-m:x" : "-m:w";
  141. if (T.isOSBinFormatXCOFF())
  142. return "-m:a";
  143. return "-m:e";
  144. }
  145. static const LayoutAlignElem DefaultAlignments[] = {
  146. {INTEGER_ALIGN, 1, Align(1), Align(1)}, // i1
  147. {INTEGER_ALIGN, 8, Align(1), Align(1)}, // i8
  148. {INTEGER_ALIGN, 16, Align(2), Align(2)}, // i16
  149. {INTEGER_ALIGN, 32, Align(4), Align(4)}, // i32
  150. {INTEGER_ALIGN, 64, Align(4), Align(8)}, // i64
  151. {FLOAT_ALIGN, 16, Align(2), Align(2)}, // half, bfloat
  152. {FLOAT_ALIGN, 32, Align(4), Align(4)}, // float
  153. {FLOAT_ALIGN, 64, Align(8), Align(8)}, // double
  154. {FLOAT_ALIGN, 128, Align(16), Align(16)}, // ppcf128, quad, ...
  155. {VECTOR_ALIGN, 64, Align(8), Align(8)}, // v2i32, v1i64, ...
  156. {VECTOR_ALIGN, 128, Align(16), Align(16)}, // v16i8, v8i16, v4i32, ...
  157. {AGGREGATE_ALIGN, 0, Align(1), Align(8)} // struct
  158. };
  159. void DataLayout::reset(StringRef Desc) {
  160. clear();
  161. LayoutMap = nullptr;
  162. BigEndian = false;
  163. AllocaAddrSpace = 0;
  164. StackNaturalAlign.reset();
  165. ProgramAddrSpace = 0;
  166. DefaultGlobalsAddrSpace = 0;
  167. FunctionPtrAlign.reset();
  168. TheFunctionPtrAlignType = FunctionPtrAlignType::Independent;
  169. ManglingMode = MM_None;
  170. NonIntegralAddressSpaces.clear();
  171. // Default alignments
  172. for (const LayoutAlignElem &E : DefaultAlignments) {
  173. if (Error Err = setAlignment((AlignTypeEnum)E.AlignType, E.ABIAlign,
  174. E.PrefAlign, E.TypeBitWidth))
  175. return report_fatal_error(std::move(Err));
  176. }
  177. if (Error Err = setPointerAlignmentInBits(0, Align(8), Align(8), 64, 64))
  178. return report_fatal_error(std::move(Err));
  179. if (Error Err = parseSpecifier(Desc))
  180. return report_fatal_error(std::move(Err));
  181. }
  182. Expected<DataLayout> DataLayout::parse(StringRef LayoutDescription) {
  183. DataLayout Layout("");
  184. if (Error Err = Layout.parseSpecifier(LayoutDescription))
  185. return std::move(Err);
  186. return Layout;
  187. }
  188. static Error reportError(const Twine &Message) {
  189. return createStringError(inconvertibleErrorCode(), Message);
  190. }
  191. /// Checked version of split, to ensure mandatory subparts.
  192. static Error split(StringRef Str, char Separator,
  193. std::pair<StringRef, StringRef> &Split) {
  194. assert(!Str.empty() && "parse error, string can't be empty here");
  195. Split = Str.split(Separator);
  196. if (Split.second.empty() && Split.first != Str)
  197. return reportError("Trailing separator in datalayout string");
  198. if (!Split.second.empty() && Split.first.empty())
  199. return reportError("Expected token before separator in datalayout string");
  200. return Error::success();
  201. }
  202. /// Get an unsigned integer, including error checks.
  203. template <typename IntTy> static Error getInt(StringRef R, IntTy &Result) {
  204. bool error = R.getAsInteger(10, Result); (void)error;
  205. if (error)
  206. return reportError("not a number, or does not fit in an unsigned int");
  207. return Error::success();
  208. }
  209. /// Get an unsigned integer representing the number of bits and convert it into
  210. /// bytes. Error out of not a byte width multiple.
  211. template <typename IntTy>
  212. static Error getIntInBytes(StringRef R, IntTy &Result) {
  213. if (Error Err = getInt<IntTy>(R, Result))
  214. return Err;
  215. if (Result % 8)
  216. return reportError("number of bits must be a byte width multiple");
  217. Result /= 8;
  218. return Error::success();
  219. }
  220. static Error getAddrSpace(StringRef R, unsigned &AddrSpace) {
  221. if (Error Err = getInt(R, AddrSpace))
  222. return Err;
  223. if (!isUInt<24>(AddrSpace))
  224. return reportError("Invalid address space, must be a 24-bit integer");
  225. return Error::success();
  226. }
  227. Error DataLayout::parseSpecifier(StringRef Desc) {
  228. StringRepresentation = std::string(Desc);
  229. while (!Desc.empty()) {
  230. // Split at '-'.
  231. std::pair<StringRef, StringRef> Split;
  232. if (Error Err = ::split(Desc, '-', Split))
  233. return Err;
  234. Desc = Split.second;
  235. // Split at ':'.
  236. if (Error Err = ::split(Split.first, ':', Split))
  237. return Err;
  238. // Aliases used below.
  239. StringRef &Tok = Split.first; // Current token.
  240. StringRef &Rest = Split.second; // The rest of the string.
  241. if (Tok == "ni") {
  242. do {
  243. if (Error Err = ::split(Rest, ':', Split))
  244. return Err;
  245. Rest = Split.second;
  246. unsigned AS;
  247. if (Error Err = getInt(Split.first, AS))
  248. return Err;
  249. if (AS == 0)
  250. return reportError("Address space 0 can never be non-integral");
  251. NonIntegralAddressSpaces.push_back(AS);
  252. } while (!Rest.empty());
  253. continue;
  254. }
  255. char Specifier = Tok.front();
  256. Tok = Tok.substr(1);
  257. switch (Specifier) {
  258. case 's':
  259. // Deprecated, but ignoring here to preserve loading older textual llvm
  260. // ASM file
  261. break;
  262. case 'E':
  263. BigEndian = true;
  264. break;
  265. case 'e':
  266. BigEndian = false;
  267. break;
  268. case 'p': {
  269. // Address space.
  270. unsigned AddrSpace = 0;
  271. if (!Tok.empty())
  272. if (Error Err = getInt(Tok, AddrSpace))
  273. return Err;
  274. if (!isUInt<24>(AddrSpace))
  275. return reportError("Invalid address space, must be a 24bit integer");
  276. // Size.
  277. if (Rest.empty())
  278. return reportError(
  279. "Missing size specification for pointer in datalayout string");
  280. if (Error Err = ::split(Rest, ':', Split))
  281. return Err;
  282. unsigned PointerMemSize;
  283. if (Error Err = getInt(Tok, PointerMemSize))
  284. return Err;
  285. if (!PointerMemSize)
  286. return reportError("Invalid pointer size of 0 bytes");
  287. // ABI alignment.
  288. if (Rest.empty())
  289. return reportError(
  290. "Missing alignment specification for pointer in datalayout string");
  291. if (Error Err = ::split(Rest, ':', Split))
  292. return Err;
  293. unsigned PointerABIAlign;
  294. if (Error Err = getIntInBytes(Tok, PointerABIAlign))
  295. return Err;
  296. if (!isPowerOf2_64(PointerABIAlign))
  297. return reportError("Pointer ABI alignment must be a power of 2");
  298. // Size of index used in GEP for address calculation.
  299. // The parameter is optional. By default it is equal to size of pointer.
  300. unsigned IndexSize = PointerMemSize;
  301. // Preferred alignment.
  302. unsigned PointerPrefAlign = PointerABIAlign;
  303. if (!Rest.empty()) {
  304. if (Error Err = ::split(Rest, ':', Split))
  305. return Err;
  306. if (Error Err = getIntInBytes(Tok, PointerPrefAlign))
  307. return Err;
  308. if (!isPowerOf2_64(PointerPrefAlign))
  309. return reportError(
  310. "Pointer preferred alignment must be a power of 2");
  311. // Now read the index. It is the second optional parameter here.
  312. if (!Rest.empty()) {
  313. if (Error Err = ::split(Rest, ':', Split))
  314. return Err;
  315. if (Error Err = getInt(Tok, IndexSize))
  316. return Err;
  317. if (!IndexSize)
  318. return reportError("Invalid index size of 0 bytes");
  319. }
  320. }
  321. if (Error Err = setPointerAlignmentInBits(
  322. AddrSpace, assumeAligned(PointerABIAlign),
  323. assumeAligned(PointerPrefAlign), PointerMemSize, IndexSize))
  324. return Err;
  325. break;
  326. }
  327. case 'i':
  328. case 'v':
  329. case 'f':
  330. case 'a': {
  331. AlignTypeEnum AlignType;
  332. switch (Specifier) {
  333. default: llvm_unreachable("Unexpected specifier!");
  334. case 'i': AlignType = INTEGER_ALIGN; break;
  335. case 'v': AlignType = VECTOR_ALIGN; break;
  336. case 'f': AlignType = FLOAT_ALIGN; break;
  337. case 'a': AlignType = AGGREGATE_ALIGN; break;
  338. }
  339. // Bit size.
  340. unsigned Size = 0;
  341. if (!Tok.empty())
  342. if (Error Err = getInt(Tok, Size))
  343. return Err;
  344. if (AlignType == AGGREGATE_ALIGN && Size != 0)
  345. return reportError(
  346. "Sized aggregate specification in datalayout string");
  347. // ABI alignment.
  348. if (Rest.empty())
  349. return reportError(
  350. "Missing alignment specification in datalayout string");
  351. if (Error Err = ::split(Rest, ':', Split))
  352. return Err;
  353. unsigned ABIAlign;
  354. if (Error Err = getIntInBytes(Tok, ABIAlign))
  355. return Err;
  356. if (AlignType != AGGREGATE_ALIGN && !ABIAlign)
  357. return reportError(
  358. "ABI alignment specification must be >0 for non-aggregate types");
  359. if (!isUInt<16>(ABIAlign))
  360. return reportError("Invalid ABI alignment, must be a 16bit integer");
  361. if (ABIAlign != 0 && !isPowerOf2_64(ABIAlign))
  362. return reportError("Invalid ABI alignment, must be a power of 2");
  363. if (AlignType == INTEGER_ALIGN && Size == 8 && ABIAlign != 1)
  364. return reportError(
  365. "Invalid ABI alignment, i8 must be naturally aligned");
  366. // Preferred alignment.
  367. unsigned PrefAlign = ABIAlign;
  368. if (!Rest.empty()) {
  369. if (Error Err = ::split(Rest, ':', Split))
  370. return Err;
  371. if (Error Err = getIntInBytes(Tok, PrefAlign))
  372. return Err;
  373. }
  374. if (!isUInt<16>(PrefAlign))
  375. return reportError(
  376. "Invalid preferred alignment, must be a 16bit integer");
  377. if (PrefAlign != 0 && !isPowerOf2_64(PrefAlign))
  378. return reportError("Invalid preferred alignment, must be a power of 2");
  379. if (Error Err = setAlignment(AlignType, assumeAligned(ABIAlign),
  380. assumeAligned(PrefAlign), Size))
  381. return Err;
  382. break;
  383. }
  384. case 'n': // Native integer types.
  385. while (true) {
  386. unsigned Width;
  387. if (Error Err = getInt(Tok, Width))
  388. return Err;
  389. if (Width == 0)
  390. return reportError(
  391. "Zero width native integer type in datalayout string");
  392. LegalIntWidths.push_back(Width);
  393. if (Rest.empty())
  394. break;
  395. if (Error Err = ::split(Rest, ':', Split))
  396. return Err;
  397. }
  398. break;
  399. case 'S': { // Stack natural alignment.
  400. uint64_t Alignment;
  401. if (Error Err = getIntInBytes(Tok, Alignment))
  402. return Err;
  403. if (Alignment != 0 && !llvm::isPowerOf2_64(Alignment))
  404. return reportError("Alignment is neither 0 nor a power of 2");
  405. StackNaturalAlign = MaybeAlign(Alignment);
  406. break;
  407. }
  408. case 'F': {
  409. switch (Tok.front()) {
  410. case 'i':
  411. TheFunctionPtrAlignType = FunctionPtrAlignType::Independent;
  412. break;
  413. case 'n':
  414. TheFunctionPtrAlignType = FunctionPtrAlignType::MultipleOfFunctionAlign;
  415. break;
  416. default:
  417. return reportError("Unknown function pointer alignment type in "
  418. "datalayout string");
  419. }
  420. Tok = Tok.substr(1);
  421. uint64_t Alignment;
  422. if (Error Err = getIntInBytes(Tok, Alignment))
  423. return Err;
  424. if (Alignment != 0 && !llvm::isPowerOf2_64(Alignment))
  425. return reportError("Alignment is neither 0 nor a power of 2");
  426. FunctionPtrAlign = MaybeAlign(Alignment);
  427. break;
  428. }
  429. case 'P': { // Function address space.
  430. if (Error Err = getAddrSpace(Tok, ProgramAddrSpace))
  431. return Err;
  432. break;
  433. }
  434. case 'A': { // Default stack/alloca address space.
  435. if (Error Err = getAddrSpace(Tok, AllocaAddrSpace))
  436. return Err;
  437. break;
  438. }
  439. case 'G': { // Default address space for global variables.
  440. if (Error Err = getAddrSpace(Tok, DefaultGlobalsAddrSpace))
  441. return Err;
  442. break;
  443. }
  444. case 'm':
  445. if (!Tok.empty())
  446. return reportError("Unexpected trailing characters after mangling "
  447. "specifier in datalayout string");
  448. if (Rest.empty())
  449. return reportError("Expected mangling specifier in datalayout string");
  450. if (Rest.size() > 1)
  451. return reportError("Unknown mangling specifier in datalayout string");
  452. switch(Rest[0]) {
  453. default:
  454. return reportError("Unknown mangling in datalayout string");
  455. case 'e':
  456. ManglingMode = MM_ELF;
  457. break;
  458. case 'l':
  459. ManglingMode = MM_GOFF;
  460. break;
  461. case 'o':
  462. ManglingMode = MM_MachO;
  463. break;
  464. case 'm':
  465. ManglingMode = MM_Mips;
  466. break;
  467. case 'w':
  468. ManglingMode = MM_WinCOFF;
  469. break;
  470. case 'x':
  471. ManglingMode = MM_WinCOFFX86;
  472. break;
  473. case 'a':
  474. ManglingMode = MM_XCOFF;
  475. break;
  476. }
  477. break;
  478. default:
  479. return reportError("Unknown specifier in datalayout string");
  480. break;
  481. }
  482. }
  483. return Error::success();
  484. }
  485. DataLayout::DataLayout(const Module *M) {
  486. init(M);
  487. }
  488. void DataLayout::init(const Module *M) { *this = M->getDataLayout(); }
  489. bool DataLayout::operator==(const DataLayout &Other) const {
  490. bool Ret = BigEndian == Other.BigEndian &&
  491. AllocaAddrSpace == Other.AllocaAddrSpace &&
  492. StackNaturalAlign == Other.StackNaturalAlign &&
  493. ProgramAddrSpace == Other.ProgramAddrSpace &&
  494. DefaultGlobalsAddrSpace == Other.DefaultGlobalsAddrSpace &&
  495. FunctionPtrAlign == Other.FunctionPtrAlign &&
  496. TheFunctionPtrAlignType == Other.TheFunctionPtrAlignType &&
  497. ManglingMode == Other.ManglingMode &&
  498. LegalIntWidths == Other.LegalIntWidths &&
  499. Alignments == Other.Alignments && Pointers == Other.Pointers;
  500. // Note: getStringRepresentation() might differs, it is not canonicalized
  501. return Ret;
  502. }
  503. DataLayout::AlignmentsTy::iterator
  504. DataLayout::findAlignmentLowerBound(AlignTypeEnum AlignType,
  505. uint32_t BitWidth) {
  506. auto Pair = std::make_pair((unsigned)AlignType, BitWidth);
  507. return partition_point(Alignments, [=](const LayoutAlignElem &E) {
  508. return std::make_pair(E.AlignType, E.TypeBitWidth) < Pair;
  509. });
  510. }
  511. Error DataLayout::setAlignment(AlignTypeEnum align_type, Align abi_align,
  512. Align pref_align, uint32_t bit_width) {
  513. // AlignmentsTy::ABIAlign and AlignmentsTy::PrefAlign were once stored as
  514. // uint16_t, it is unclear if there are requirements for alignment to be less
  515. // than 2^16 other than storage. In the meantime we leave the restriction as
  516. // an assert. See D67400 for context.
  517. assert(Log2(abi_align) < 16 && Log2(pref_align) < 16 && "Alignment too big");
  518. if (!isUInt<24>(bit_width))
  519. return reportError("Invalid bit width, must be a 24bit integer");
  520. if (pref_align < abi_align)
  521. return reportError(
  522. "Preferred alignment cannot be less than the ABI alignment");
  523. AlignmentsTy::iterator I = findAlignmentLowerBound(align_type, bit_width);
  524. if (I != Alignments.end() &&
  525. I->AlignType == (unsigned)align_type && I->TypeBitWidth == bit_width) {
  526. // Update the abi, preferred alignments.
  527. I->ABIAlign = abi_align;
  528. I->PrefAlign = pref_align;
  529. } else {
  530. // Insert before I to keep the vector sorted.
  531. Alignments.insert(I, LayoutAlignElem::get(align_type, abi_align,
  532. pref_align, bit_width));
  533. }
  534. return Error::success();
  535. }
  536. const PointerAlignElem &
  537. DataLayout::getPointerAlignElem(uint32_t AddressSpace) const {
  538. if (AddressSpace != 0) {
  539. auto I = lower_bound(Pointers, AddressSpace,
  540. [](const PointerAlignElem &A, uint32_t AddressSpace) {
  541. return A.AddressSpace < AddressSpace;
  542. });
  543. if (I != Pointers.end() && I->AddressSpace == AddressSpace)
  544. return *I;
  545. }
  546. assert(Pointers[0].AddressSpace == 0);
  547. return Pointers[0];
  548. }
  549. Error DataLayout::setPointerAlignmentInBits(uint32_t AddrSpace, Align ABIAlign,
  550. Align PrefAlign,
  551. uint32_t TypeBitWidth,
  552. uint32_t IndexBitWidth) {
  553. if (PrefAlign < ABIAlign)
  554. return reportError(
  555. "Preferred alignment cannot be less than the ABI alignment");
  556. auto I = lower_bound(Pointers, AddrSpace,
  557. [](const PointerAlignElem &A, uint32_t AddressSpace) {
  558. return A.AddressSpace < AddressSpace;
  559. });
  560. if (I == Pointers.end() || I->AddressSpace != AddrSpace) {
  561. Pointers.insert(I,
  562. PointerAlignElem::getInBits(AddrSpace, ABIAlign, PrefAlign,
  563. TypeBitWidth, IndexBitWidth));
  564. } else {
  565. I->ABIAlign = ABIAlign;
  566. I->PrefAlign = PrefAlign;
  567. I->TypeBitWidth = TypeBitWidth;
  568. I->IndexBitWidth = IndexBitWidth;
  569. }
  570. return Error::success();
  571. }
  572. Align DataLayout::getIntegerAlignment(uint32_t BitWidth,
  573. bool abi_or_pref) const {
  574. auto I = findAlignmentLowerBound(INTEGER_ALIGN, BitWidth);
  575. // If we don't have an exact match, use alignment of next larger integer
  576. // type. If there is none, use alignment of largest integer type by going
  577. // back one element.
  578. if (I == Alignments.end() || I->AlignType != INTEGER_ALIGN)
  579. --I;
  580. assert(I->AlignType == INTEGER_ALIGN && "Must be integer alignment");
  581. return abi_or_pref ? I->ABIAlign : I->PrefAlign;
  582. }
  583. namespace {
  584. class StructLayoutMap {
  585. using LayoutInfoTy = DenseMap<StructType*, StructLayout*>;
  586. LayoutInfoTy LayoutInfo;
  587. public:
  588. ~StructLayoutMap() {
  589. // Remove any layouts.
  590. for (const auto &I : LayoutInfo) {
  591. StructLayout *Value = I.second;
  592. Value->~StructLayout();
  593. free(Value);
  594. }
  595. }
  596. StructLayout *&operator[](StructType *STy) {
  597. return LayoutInfo[STy];
  598. }
  599. };
  600. } // end anonymous namespace
  601. void DataLayout::clear() {
  602. LegalIntWidths.clear();
  603. Alignments.clear();
  604. Pointers.clear();
  605. delete static_cast<StructLayoutMap *>(LayoutMap);
  606. LayoutMap = nullptr;
  607. }
  608. DataLayout::~DataLayout() {
  609. clear();
  610. }
  611. const StructLayout *DataLayout::getStructLayout(StructType *Ty) const {
  612. if (!LayoutMap)
  613. LayoutMap = new StructLayoutMap();
  614. StructLayoutMap *STM = static_cast<StructLayoutMap*>(LayoutMap);
  615. StructLayout *&SL = (*STM)[Ty];
  616. if (SL) return SL;
  617. // Otherwise, create the struct layout. Because it is variable length, we
  618. // malloc it, then use placement new.
  619. StructLayout *L = (StructLayout *)safe_malloc(
  620. StructLayout::totalSizeToAlloc<uint64_t>(Ty->getNumElements()));
  621. // Set SL before calling StructLayout's ctor. The ctor could cause other
  622. // entries to be added to TheMap, invalidating our reference.
  623. SL = L;
  624. new (L) StructLayout(Ty, *this);
  625. return L;
  626. }
  627. Align DataLayout::getPointerABIAlignment(unsigned AS) const {
  628. return getPointerAlignElem(AS).ABIAlign;
  629. }
  630. Align DataLayout::getPointerPrefAlignment(unsigned AS) const {
  631. return getPointerAlignElem(AS).PrefAlign;
  632. }
  633. unsigned DataLayout::getPointerSize(unsigned AS) const {
  634. return divideCeil(getPointerAlignElem(AS).TypeBitWidth, 8);
  635. }
  636. unsigned DataLayout::getMaxIndexSize() const {
  637. unsigned MaxIndexSize = 0;
  638. for (auto &P : Pointers)
  639. MaxIndexSize =
  640. std::max(MaxIndexSize, (unsigned)divideCeil(P.TypeBitWidth, 8));
  641. return MaxIndexSize;
  642. }
  643. unsigned DataLayout::getPointerTypeSizeInBits(Type *Ty) const {
  644. assert(Ty->isPtrOrPtrVectorTy() &&
  645. "This should only be called with a pointer or pointer vector type");
  646. Ty = Ty->getScalarType();
  647. return getPointerSizeInBits(cast<PointerType>(Ty)->getAddressSpace());
  648. }
  649. unsigned DataLayout::getIndexSize(unsigned AS) const {
  650. return divideCeil(getPointerAlignElem(AS).IndexBitWidth, 8);
  651. }
  652. unsigned DataLayout::getIndexTypeSizeInBits(Type *Ty) const {
  653. assert(Ty->isPtrOrPtrVectorTy() &&
  654. "This should only be called with a pointer or pointer vector type");
  655. Ty = Ty->getScalarType();
  656. return getIndexSizeInBits(cast<PointerType>(Ty)->getAddressSpace());
  657. }
  658. /*!
  659. \param abi_or_pref Flag that determines which alignment is returned. true
  660. returns the ABI alignment, false returns the preferred alignment.
  661. \param Ty The underlying type for which alignment is determined.
  662. Get the ABI (\a abi_or_pref == true) or preferred alignment (\a abi_or_pref
  663. == false) for the requested type \a Ty.
  664. */
  665. Align DataLayout::getAlignment(Type *Ty, bool abi_or_pref) const {
  666. assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!");
  667. switch (Ty->getTypeID()) {
  668. // Early escape for the non-numeric types.
  669. case Type::LabelTyID:
  670. return abi_or_pref ? getPointerABIAlignment(0) : getPointerPrefAlignment(0);
  671. case Type::PointerTyID: {
  672. unsigned AS = cast<PointerType>(Ty)->getAddressSpace();
  673. return abi_or_pref ? getPointerABIAlignment(AS)
  674. : getPointerPrefAlignment(AS);
  675. }
  676. case Type::ArrayTyID:
  677. return getAlignment(cast<ArrayType>(Ty)->getElementType(), abi_or_pref);
  678. case Type::StructTyID: {
  679. // Packed structure types always have an ABI alignment of one.
  680. if (cast<StructType>(Ty)->isPacked() && abi_or_pref)
  681. return Align(1);
  682. // Get the layout annotation... which is lazily created on demand.
  683. const StructLayout *Layout = getStructLayout(cast<StructType>(Ty));
  684. const LayoutAlignElem &AggregateAlign = Alignments[0];
  685. assert(AggregateAlign.AlignType == AGGREGATE_ALIGN &&
  686. "Aggregate alignment must be first alignment entry");
  687. const Align Align =
  688. abi_or_pref ? AggregateAlign.ABIAlign : AggregateAlign.PrefAlign;
  689. return std::max(Align, Layout->getAlignment());
  690. }
  691. case Type::IntegerTyID:
  692. return getIntegerAlignment(Ty->getIntegerBitWidth(), abi_or_pref);
  693. case Type::HalfTyID:
  694. case Type::BFloatTyID:
  695. case Type::FloatTyID:
  696. case Type::DoubleTyID:
  697. // PPC_FP128TyID and FP128TyID have different data contents, but the
  698. // same size and alignment, so they look the same here.
  699. case Type::PPC_FP128TyID:
  700. case Type::FP128TyID:
  701. case Type::X86_FP80TyID: {
  702. unsigned BitWidth = getTypeSizeInBits(Ty).getFixedValue();
  703. auto I = findAlignmentLowerBound(FLOAT_ALIGN, BitWidth);
  704. if (I != Alignments.end() && I->AlignType == FLOAT_ALIGN &&
  705. I->TypeBitWidth == BitWidth)
  706. return abi_or_pref ? I->ABIAlign : I->PrefAlign;
  707. // If we still couldn't find a reasonable default alignment, fall back
  708. // to a simple heuristic that the alignment is the first power of two
  709. // greater-or-equal to the store size of the type. This is a reasonable
  710. // approximation of reality, and if the user wanted something less
  711. // less conservative, they should have specified it explicitly in the data
  712. // layout.
  713. return Align(PowerOf2Ceil(BitWidth / 8));
  714. }
  715. case Type::X86_MMXTyID:
  716. case Type::FixedVectorTyID:
  717. case Type::ScalableVectorTyID: {
  718. unsigned BitWidth = getTypeSizeInBits(Ty).getKnownMinValue();
  719. auto I = findAlignmentLowerBound(VECTOR_ALIGN, BitWidth);
  720. if (I != Alignments.end() && I->AlignType == VECTOR_ALIGN &&
  721. I->TypeBitWidth == BitWidth)
  722. return abi_or_pref ? I->ABIAlign : I->PrefAlign;
  723. // By default, use natural alignment for vector types. This is consistent
  724. // with what clang and llvm-gcc do.
  725. //
  726. // We're only calculating a natural alignment, so it doesn't have to be
  727. // based on the full size for scalable vectors. Using the minimum element
  728. // count should be enough here.
  729. return Align(PowerOf2Ceil(getTypeStoreSize(Ty).getKnownMinValue()));
  730. }
  731. case Type::X86_AMXTyID:
  732. return Align(64);
  733. case Type::TargetExtTyID: {
  734. Type *LayoutTy = cast<TargetExtType>(Ty)->getLayoutType();
  735. return getAlignment(LayoutTy, abi_or_pref);
  736. }
  737. default:
  738. llvm_unreachable("Bad type for getAlignment!!!");
  739. }
  740. }
  741. /// TODO: Remove this function once the transition to Align is over.
  742. uint64_t DataLayout::getABITypeAlignment(Type *Ty) const {
  743. return getABITypeAlign(Ty).value();
  744. }
  745. Align DataLayout::getABITypeAlign(Type *Ty) const {
  746. return getAlignment(Ty, true);
  747. }
  748. /// TODO: Remove this function once the transition to Align is over.
  749. uint64_t DataLayout::getPrefTypeAlignment(Type *Ty) const {
  750. return getPrefTypeAlign(Ty).value();
  751. }
  752. Align DataLayout::getPrefTypeAlign(Type *Ty) const {
  753. return getAlignment(Ty, false);
  754. }
  755. IntegerType *DataLayout::getIntPtrType(LLVMContext &C,
  756. unsigned AddressSpace) const {
  757. return IntegerType::get(C, getPointerSizeInBits(AddressSpace));
  758. }
  759. Type *DataLayout::getIntPtrType(Type *Ty) const {
  760. assert(Ty->isPtrOrPtrVectorTy() &&
  761. "Expected a pointer or pointer vector type.");
  762. unsigned NumBits = getPointerTypeSizeInBits(Ty);
  763. IntegerType *IntTy = IntegerType::get(Ty->getContext(), NumBits);
  764. if (VectorType *VecTy = dyn_cast<VectorType>(Ty))
  765. return VectorType::get(IntTy, VecTy);
  766. return IntTy;
  767. }
  768. Type *DataLayout::getSmallestLegalIntType(LLVMContext &C, unsigned Width) const {
  769. for (unsigned LegalIntWidth : LegalIntWidths)
  770. if (Width <= LegalIntWidth)
  771. return Type::getIntNTy(C, LegalIntWidth);
  772. return nullptr;
  773. }
  774. unsigned DataLayout::getLargestLegalIntTypeSizeInBits() const {
  775. auto Max = std::max_element(LegalIntWidths.begin(), LegalIntWidths.end());
  776. return Max != LegalIntWidths.end() ? *Max : 0;
  777. }
  778. Type *DataLayout::getIndexType(Type *Ty) const {
  779. assert(Ty->isPtrOrPtrVectorTy() &&
  780. "Expected a pointer or pointer vector type.");
  781. unsigned NumBits = getIndexTypeSizeInBits(Ty);
  782. IntegerType *IntTy = IntegerType::get(Ty->getContext(), NumBits);
  783. if (VectorType *VecTy = dyn_cast<VectorType>(Ty))
  784. return VectorType::get(IntTy, VecTy);
  785. return IntTy;
  786. }
  787. int64_t DataLayout::getIndexedOffsetInType(Type *ElemTy,
  788. ArrayRef<Value *> Indices) const {
  789. int64_t Result = 0;
  790. generic_gep_type_iterator<Value* const*>
  791. GTI = gep_type_begin(ElemTy, Indices),
  792. GTE = gep_type_end(ElemTy, Indices);
  793. for (; GTI != GTE; ++GTI) {
  794. Value *Idx = GTI.getOperand();
  795. if (StructType *STy = GTI.getStructTypeOrNull()) {
  796. assert(Idx->getType()->isIntegerTy(32) && "Illegal struct idx");
  797. unsigned FieldNo = cast<ConstantInt>(Idx)->getZExtValue();
  798. // Get structure layout information...
  799. const StructLayout *Layout = getStructLayout(STy);
  800. // Add in the offset, as calculated by the structure layout info...
  801. Result += Layout->getElementOffset(FieldNo);
  802. } else {
  803. // Get the array index and the size of each array element.
  804. if (int64_t arrayIdx = cast<ConstantInt>(Idx)->getSExtValue())
  805. Result += arrayIdx * getTypeAllocSize(GTI.getIndexedType());
  806. }
  807. }
  808. return Result;
  809. }
  810. static APInt getElementIndex(TypeSize ElemSize, APInt &Offset) {
  811. // Skip over scalable or zero size elements. Also skip element sizes larger
  812. // than the positive index space, because the arithmetic below may not be
  813. // correct in that case.
  814. unsigned BitWidth = Offset.getBitWidth();
  815. if (ElemSize.isScalable() || ElemSize == 0 ||
  816. !isUIntN(BitWidth - 1, ElemSize)) {
  817. return APInt::getZero(BitWidth);
  818. }
  819. APInt Index = Offset.sdiv(ElemSize);
  820. Offset -= Index * ElemSize;
  821. if (Offset.isNegative()) {
  822. // Prefer a positive remaining offset to allow struct indexing.
  823. --Index;
  824. Offset += ElemSize;
  825. assert(Offset.isNonNegative() && "Remaining offset shouldn't be negative");
  826. }
  827. return Index;
  828. }
  829. std::optional<APInt> DataLayout::getGEPIndexForOffset(Type *&ElemTy,
  830. APInt &Offset) const {
  831. if (auto *ArrTy = dyn_cast<ArrayType>(ElemTy)) {
  832. ElemTy = ArrTy->getElementType();
  833. return getElementIndex(getTypeAllocSize(ElemTy), Offset);
  834. }
  835. if (isa<VectorType>(ElemTy)) {
  836. // Vector GEPs are partially broken (e.g. for overaligned element types),
  837. // and may be forbidden in the future, so avoid generating GEPs into
  838. // vectors. See https://discourse.llvm.org/t/67497
  839. return std::nullopt;
  840. }
  841. if (auto *STy = dyn_cast<StructType>(ElemTy)) {
  842. const StructLayout *SL = getStructLayout(STy);
  843. uint64_t IntOffset = Offset.getZExtValue();
  844. if (IntOffset >= SL->getSizeInBytes())
  845. return std::nullopt;
  846. unsigned Index = SL->getElementContainingOffset(IntOffset);
  847. Offset -= SL->getElementOffset(Index);
  848. ElemTy = STy->getElementType(Index);
  849. return APInt(32, Index);
  850. }
  851. // Non-aggregate type.
  852. return std::nullopt;
  853. }
  854. SmallVector<APInt> DataLayout::getGEPIndicesForOffset(Type *&ElemTy,
  855. APInt &Offset) const {
  856. assert(ElemTy->isSized() && "Element type must be sized");
  857. SmallVector<APInt> Indices;
  858. Indices.push_back(getElementIndex(getTypeAllocSize(ElemTy), Offset));
  859. while (Offset != 0) {
  860. std::optional<APInt> Index = getGEPIndexForOffset(ElemTy, Offset);
  861. if (!Index)
  862. break;
  863. Indices.push_back(*Index);
  864. }
  865. return Indices;
  866. }
  867. /// getPreferredAlign - Return the preferred alignment of the specified global.
  868. /// This includes an explicitly requested alignment (if the global has one).
  869. Align DataLayout::getPreferredAlign(const GlobalVariable *GV) const {
  870. MaybeAlign GVAlignment = GV->getAlign();
  871. // If a section is specified, always precisely honor explicit alignment,
  872. // so we don't insert padding into a section we don't control.
  873. if (GVAlignment && GV->hasSection())
  874. return *GVAlignment;
  875. // If no explicit alignment is specified, compute the alignment based on
  876. // the IR type. If an alignment is specified, increase it to match the ABI
  877. // alignment of the IR type.
  878. //
  879. // FIXME: Not sure it makes sense to use the alignment of the type if
  880. // there's already an explicit alignment specification.
  881. Type *ElemType = GV->getValueType();
  882. Align Alignment = getPrefTypeAlign(ElemType);
  883. if (GVAlignment) {
  884. if (*GVAlignment >= Alignment)
  885. Alignment = *GVAlignment;
  886. else
  887. Alignment = std::max(*GVAlignment, getABITypeAlign(ElemType));
  888. }
  889. // If no explicit alignment is specified, and the global is large, increase
  890. // the alignment to 16.
  891. // FIXME: Why 16, specifically?
  892. if (GV->hasInitializer() && !GVAlignment) {
  893. if (Alignment < Align(16)) {
  894. // If the global is not external, see if it is large. If so, give it a
  895. // larger alignment.
  896. if (getTypeSizeInBits(ElemType) > 128)
  897. Alignment = Align(16); // 16-byte alignment.
  898. }
  899. }
  900. return Alignment;
  901. }