DataLayout.cpp 31 KB

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