SwiftCallingConv.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833
  1. //===--- SwiftCallingConv.cpp - Lowering for the Swift calling convention -===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // Implementation of the abstract lowering for the Swift calling convention.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/CodeGen/SwiftCallingConv.h"
  14. #include "clang/Basic/TargetInfo.h"
  15. #include "CodeGenModule.h"
  16. #include "TargetInfo.h"
  17. using namespace clang;
  18. using namespace CodeGen;
  19. using namespace swiftcall;
  20. static const SwiftABIInfo &getSwiftABIInfo(CodeGenModule &CGM) {
  21. return cast<SwiftABIInfo>(CGM.getTargetCodeGenInfo().getABIInfo());
  22. }
  23. static bool isPowerOf2(unsigned n) {
  24. return n == (n & -n);
  25. }
  26. /// Given two types with the same size, try to find a common type.
  27. static llvm::Type *getCommonType(llvm::Type *first, llvm::Type *second) {
  28. assert(first != second);
  29. // Allow pointers to merge with integers, but prefer the integer type.
  30. if (first->isIntegerTy()) {
  31. if (second->isPointerTy()) return first;
  32. } else if (first->isPointerTy()) {
  33. if (second->isIntegerTy()) return second;
  34. if (second->isPointerTy()) return first;
  35. // Allow two vectors to be merged (given that they have the same size).
  36. // This assumes that we never have two different vector register sets.
  37. } else if (auto firstVecTy = dyn_cast<llvm::VectorType>(first)) {
  38. if (auto secondVecTy = dyn_cast<llvm::VectorType>(second)) {
  39. if (auto commonTy = getCommonType(firstVecTy->getElementType(),
  40. secondVecTy->getElementType())) {
  41. return (commonTy == firstVecTy->getElementType() ? first : second);
  42. }
  43. }
  44. }
  45. return nullptr;
  46. }
  47. static CharUnits getTypeStoreSize(CodeGenModule &CGM, llvm::Type *type) {
  48. return CharUnits::fromQuantity(CGM.getDataLayout().getTypeStoreSize(type));
  49. }
  50. static CharUnits getTypeAllocSize(CodeGenModule &CGM, llvm::Type *type) {
  51. return CharUnits::fromQuantity(CGM.getDataLayout().getTypeAllocSize(type));
  52. }
  53. void SwiftAggLowering::addTypedData(QualType type, CharUnits begin) {
  54. // Deal with various aggregate types as special cases:
  55. // Record types.
  56. if (auto recType = type->getAs<RecordType>()) {
  57. addTypedData(recType->getDecl(), begin);
  58. // Array types.
  59. } else if (type->isArrayType()) {
  60. // Incomplete array types (flexible array members?) don't provide
  61. // data to lay out, and the other cases shouldn't be possible.
  62. auto arrayType = CGM.getContext().getAsConstantArrayType(type);
  63. if (!arrayType) return;
  64. QualType eltType = arrayType->getElementType();
  65. auto eltSize = CGM.getContext().getTypeSizeInChars(eltType);
  66. for (uint64_t i = 0, e = arrayType->getSize().getZExtValue(); i != e; ++i) {
  67. addTypedData(eltType, begin + i * eltSize);
  68. }
  69. // Complex types.
  70. } else if (auto complexType = type->getAs<ComplexType>()) {
  71. auto eltType = complexType->getElementType();
  72. auto eltSize = CGM.getContext().getTypeSizeInChars(eltType);
  73. auto eltLLVMType = CGM.getTypes().ConvertType(eltType);
  74. addTypedData(eltLLVMType, begin, begin + eltSize);
  75. addTypedData(eltLLVMType, begin + eltSize, begin + 2 * eltSize);
  76. // Member pointer types.
  77. } else if (type->getAs<MemberPointerType>()) {
  78. // Just add it all as opaque.
  79. addOpaqueData(begin, begin + CGM.getContext().getTypeSizeInChars(type));
  80. // Everything else is scalar and should not convert as an LLVM aggregate.
  81. } else {
  82. // We intentionally convert as !ForMem because we want to preserve
  83. // that a type was an i1.
  84. auto llvmType = CGM.getTypes().ConvertType(type);
  85. addTypedData(llvmType, begin);
  86. }
  87. }
  88. void SwiftAggLowering::addTypedData(const RecordDecl *record, CharUnits begin) {
  89. addTypedData(record, begin, CGM.getContext().getASTRecordLayout(record));
  90. }
  91. void SwiftAggLowering::addTypedData(const RecordDecl *record, CharUnits begin,
  92. const ASTRecordLayout &layout) {
  93. // Unions are a special case.
  94. if (record->isUnion()) {
  95. for (auto field : record->fields()) {
  96. if (field->isBitField()) {
  97. addBitFieldData(field, begin, 0);
  98. } else {
  99. addTypedData(field->getType(), begin);
  100. }
  101. }
  102. return;
  103. }
  104. // Note that correctness does not rely on us adding things in
  105. // their actual order of layout; it's just somewhat more efficient
  106. // for the builder.
  107. // With that in mind, add "early" C++ data.
  108. auto cxxRecord = dyn_cast<CXXRecordDecl>(record);
  109. if (cxxRecord) {
  110. // - a v-table pointer, if the class adds its own
  111. if (layout.hasOwnVFPtr()) {
  112. addTypedData(CGM.Int8PtrTy, begin);
  113. }
  114. // - non-virtual bases
  115. for (auto &baseSpecifier : cxxRecord->bases()) {
  116. if (baseSpecifier.isVirtual()) continue;
  117. auto baseRecord = baseSpecifier.getType()->getAsCXXRecordDecl();
  118. addTypedData(baseRecord, begin + layout.getBaseClassOffset(baseRecord));
  119. }
  120. // - a vbptr if the class adds its own
  121. if (layout.hasOwnVBPtr()) {
  122. addTypedData(CGM.Int8PtrTy, begin + layout.getVBPtrOffset());
  123. }
  124. }
  125. // Add fields.
  126. for (auto field : record->fields()) {
  127. auto fieldOffsetInBits = layout.getFieldOffset(field->getFieldIndex());
  128. if (field->isBitField()) {
  129. addBitFieldData(field, begin, fieldOffsetInBits);
  130. } else {
  131. addTypedData(field->getType(),
  132. begin + CGM.getContext().toCharUnitsFromBits(fieldOffsetInBits));
  133. }
  134. }
  135. // Add "late" C++ data:
  136. if (cxxRecord) {
  137. // - virtual bases
  138. for (auto &vbaseSpecifier : cxxRecord->vbases()) {
  139. auto baseRecord = vbaseSpecifier.getType()->getAsCXXRecordDecl();
  140. addTypedData(baseRecord, begin + layout.getVBaseClassOffset(baseRecord));
  141. }
  142. }
  143. }
  144. void SwiftAggLowering::addBitFieldData(const FieldDecl *bitfield,
  145. CharUnits recordBegin,
  146. uint64_t bitfieldBitBegin) {
  147. assert(bitfield->isBitField());
  148. auto &ctx = CGM.getContext();
  149. auto width = bitfield->getBitWidthValue(ctx);
  150. // We can ignore zero-width bit-fields.
  151. if (width == 0) return;
  152. // toCharUnitsFromBits rounds down.
  153. CharUnits bitfieldByteBegin = ctx.toCharUnitsFromBits(bitfieldBitBegin);
  154. // Find the offset of the last byte that is partially occupied by the
  155. // bit-field; since we otherwise expect exclusive ends, the end is the
  156. // next byte.
  157. uint64_t bitfieldBitLast = bitfieldBitBegin + width - 1;
  158. CharUnits bitfieldByteEnd =
  159. ctx.toCharUnitsFromBits(bitfieldBitLast) + CharUnits::One();
  160. addOpaqueData(recordBegin + bitfieldByteBegin,
  161. recordBegin + bitfieldByteEnd);
  162. }
  163. void SwiftAggLowering::addTypedData(llvm::Type *type, CharUnits begin) {
  164. assert(type && "didn't provide type for typed data");
  165. addTypedData(type, begin, begin + getTypeStoreSize(CGM, type));
  166. }
  167. void SwiftAggLowering::addTypedData(llvm::Type *type,
  168. CharUnits begin, CharUnits end) {
  169. assert(type && "didn't provide type for typed data");
  170. assert(getTypeStoreSize(CGM, type) == end - begin);
  171. // Legalize vector types.
  172. if (auto vecTy = dyn_cast<llvm::VectorType>(type)) {
  173. SmallVector<llvm::Type*, 4> componentTys;
  174. legalizeVectorType(CGM, end - begin, vecTy, componentTys);
  175. assert(componentTys.size() >= 1);
  176. // Walk the initial components.
  177. for (size_t i = 0, e = componentTys.size(); i != e - 1; ++i) {
  178. llvm::Type *componentTy = componentTys[i];
  179. auto componentSize = getTypeStoreSize(CGM, componentTy);
  180. assert(componentSize < end - begin);
  181. addLegalTypedData(componentTy, begin, begin + componentSize);
  182. begin += componentSize;
  183. }
  184. return addLegalTypedData(componentTys.back(), begin, end);
  185. }
  186. // Legalize integer types.
  187. if (auto intTy = dyn_cast<llvm::IntegerType>(type)) {
  188. if (!isLegalIntegerType(CGM, intTy))
  189. return addOpaqueData(begin, end);
  190. }
  191. // All other types should be legal.
  192. return addLegalTypedData(type, begin, end);
  193. }
  194. void SwiftAggLowering::addLegalTypedData(llvm::Type *type,
  195. CharUnits begin, CharUnits end) {
  196. // Require the type to be naturally aligned.
  197. if (!begin.isZero() && !begin.isMultipleOf(getNaturalAlignment(CGM, type))) {
  198. // Try splitting vector types.
  199. if (auto vecTy = dyn_cast<llvm::VectorType>(type)) {
  200. auto split = splitLegalVectorType(CGM, end - begin, vecTy);
  201. auto eltTy = split.first;
  202. auto numElts = split.second;
  203. auto eltSize = (end - begin) / numElts;
  204. assert(eltSize == getTypeStoreSize(CGM, eltTy));
  205. for (size_t i = 0, e = numElts; i != e; ++i) {
  206. addLegalTypedData(eltTy, begin, begin + eltSize);
  207. begin += eltSize;
  208. }
  209. assert(begin == end);
  210. return;
  211. }
  212. return addOpaqueData(begin, end);
  213. }
  214. addEntry(type, begin, end);
  215. }
  216. void SwiftAggLowering::addEntry(llvm::Type *type,
  217. CharUnits begin, CharUnits end) {
  218. assert((!type ||
  219. (!isa<llvm::StructType>(type) && !isa<llvm::ArrayType>(type))) &&
  220. "cannot add aggregate-typed data");
  221. assert(!type || begin.isMultipleOf(getNaturalAlignment(CGM, type)));
  222. // Fast path: we can just add entries to the end.
  223. if (Entries.empty() || Entries.back().End <= begin) {
  224. Entries.push_back({begin, end, type});
  225. return;
  226. }
  227. // Find the first existing entry that ends after the start of the new data.
  228. // TODO: do a binary search if Entries is big enough for it to matter.
  229. size_t index = Entries.size() - 1;
  230. while (index != 0) {
  231. if (Entries[index - 1].End <= begin) break;
  232. --index;
  233. }
  234. // The entry ends after the start of the new data.
  235. // If the entry starts after the end of the new data, there's no conflict.
  236. if (Entries[index].Begin >= end) {
  237. // This insertion is potentially O(n), but the way we generally build
  238. // these layouts makes that unlikely to matter: we'd need a union of
  239. // several very large types.
  240. Entries.insert(Entries.begin() + index, {begin, end, type});
  241. return;
  242. }
  243. // Otherwise, the ranges overlap. The new range might also overlap
  244. // with later ranges.
  245. restartAfterSplit:
  246. // Simplest case: an exact overlap.
  247. if (Entries[index].Begin == begin && Entries[index].End == end) {
  248. // If the types match exactly, great.
  249. if (Entries[index].Type == type) return;
  250. // If either type is opaque, make the entry opaque and return.
  251. if (Entries[index].Type == nullptr) {
  252. return;
  253. } else if (type == nullptr) {
  254. Entries[index].Type = nullptr;
  255. return;
  256. }
  257. // If they disagree in an ABI-agnostic way, just resolve the conflict
  258. // arbitrarily.
  259. if (auto entryType = getCommonType(Entries[index].Type, type)) {
  260. Entries[index].Type = entryType;
  261. return;
  262. }
  263. // Otherwise, make the entry opaque.
  264. Entries[index].Type = nullptr;
  265. return;
  266. }
  267. // Okay, we have an overlapping conflict of some sort.
  268. // If we have a vector type, split it.
  269. if (auto vecTy = dyn_cast_or_null<llvm::VectorType>(type)) {
  270. auto eltTy = vecTy->getElementType();
  271. CharUnits eltSize = (end - begin) / vecTy->getNumElements();
  272. assert(eltSize == getTypeStoreSize(CGM, eltTy));
  273. for (unsigned i = 0, e = vecTy->getNumElements(); i != e; ++i) {
  274. addEntry(eltTy, begin, begin + eltSize);
  275. begin += eltSize;
  276. }
  277. assert(begin == end);
  278. return;
  279. }
  280. // If the entry is a vector type, split it and try again.
  281. if (Entries[index].Type && Entries[index].Type->isVectorTy()) {
  282. splitVectorEntry(index);
  283. goto restartAfterSplit;
  284. }
  285. // Okay, we have no choice but to make the existing entry opaque.
  286. Entries[index].Type = nullptr;
  287. // Stretch the start of the entry to the beginning of the range.
  288. if (begin < Entries[index].Begin) {
  289. Entries[index].Begin = begin;
  290. assert(index == 0 || begin >= Entries[index - 1].End);
  291. }
  292. // Stretch the end of the entry to the end of the range; but if we run
  293. // into the start of the next entry, just leave the range there and repeat.
  294. while (end > Entries[index].End) {
  295. assert(Entries[index].Type == nullptr);
  296. // If the range doesn't overlap the next entry, we're done.
  297. if (index == Entries.size() - 1 || end <= Entries[index + 1].Begin) {
  298. Entries[index].End = end;
  299. break;
  300. }
  301. // Otherwise, stretch to the start of the next entry.
  302. Entries[index].End = Entries[index + 1].Begin;
  303. // Continue with the next entry.
  304. index++;
  305. // This entry needs to be made opaque if it is not already.
  306. if (Entries[index].Type == nullptr)
  307. continue;
  308. // Split vector entries unless we completely subsume them.
  309. if (Entries[index].Type->isVectorTy() &&
  310. end < Entries[index].End) {
  311. splitVectorEntry(index);
  312. }
  313. // Make the entry opaque.
  314. Entries[index].Type = nullptr;
  315. }
  316. }
  317. /// Replace the entry of vector type at offset 'index' with a sequence
  318. /// of its component vectors.
  319. void SwiftAggLowering::splitVectorEntry(unsigned index) {
  320. auto vecTy = cast<llvm::VectorType>(Entries[index].Type);
  321. auto split = splitLegalVectorType(CGM, Entries[index].getWidth(), vecTy);
  322. auto eltTy = split.first;
  323. CharUnits eltSize = getTypeStoreSize(CGM, eltTy);
  324. auto numElts = split.second;
  325. Entries.insert(Entries.begin() + index + 1, numElts - 1, StorageEntry());
  326. CharUnits begin = Entries[index].Begin;
  327. for (unsigned i = 0; i != numElts; ++i) {
  328. Entries[index].Type = eltTy;
  329. Entries[index].Begin = begin;
  330. Entries[index].End = begin + eltSize;
  331. begin += eltSize;
  332. }
  333. }
  334. /// Given a power-of-two unit size, return the offset of the aligned unit
  335. /// of that size which contains the given offset.
  336. ///
  337. /// In other words, round down to the nearest multiple of the unit size.
  338. static CharUnits getOffsetAtStartOfUnit(CharUnits offset, CharUnits unitSize) {
  339. assert(isPowerOf2(unitSize.getQuantity()));
  340. auto unitMask = ~(unitSize.getQuantity() - 1);
  341. return CharUnits::fromQuantity(offset.getQuantity() & unitMask);
  342. }
  343. static bool areBytesInSameUnit(CharUnits first, CharUnits second,
  344. CharUnits chunkSize) {
  345. return getOffsetAtStartOfUnit(first, chunkSize)
  346. == getOffsetAtStartOfUnit(second, chunkSize);
  347. }
  348. void SwiftAggLowering::finish() {
  349. if (Entries.empty()) {
  350. Finished = true;
  351. return;
  352. }
  353. // We logically split the layout down into a series of chunks of this size,
  354. // which is generally the size of a pointer.
  355. const CharUnits chunkSize = getMaximumVoluntaryIntegerSize(CGM);
  356. // First pass: if two entries share a chunk, make them both opaque
  357. // and stretch one to meet the next.
  358. bool hasOpaqueEntries = (Entries[0].Type == nullptr);
  359. for (size_t i = 1, e = Entries.size(); i != e; ++i) {
  360. if (areBytesInSameUnit(Entries[i - 1].End - CharUnits::One(),
  361. Entries[i].Begin, chunkSize)) {
  362. Entries[i - 1].Type = nullptr;
  363. Entries[i].Type = nullptr;
  364. Entries[i - 1].End = Entries[i].Begin;
  365. hasOpaqueEntries = true;
  366. } else if (Entries[i].Type == nullptr) {
  367. hasOpaqueEntries = true;
  368. }
  369. }
  370. // The rest of the algorithm leaves non-opaque entries alone, so if we
  371. // have no opaque entries, we're done.
  372. if (!hasOpaqueEntries) {
  373. Finished = true;
  374. return;
  375. }
  376. // Okay, move the entries to a temporary and rebuild Entries.
  377. auto orig = std::move(Entries);
  378. assert(Entries.empty());
  379. for (size_t i = 0, e = orig.size(); i != e; ++i) {
  380. // Just copy over non-opaque entries.
  381. if (orig[i].Type != nullptr) {
  382. Entries.push_back(orig[i]);
  383. continue;
  384. }
  385. // Scan forward to determine the full extent of the next opaque range.
  386. // We know from the first pass that only contiguous ranges will overlap
  387. // the same aligned chunk.
  388. auto begin = orig[i].Begin;
  389. auto end = orig[i].End;
  390. while (i + 1 != e &&
  391. orig[i + 1].Type == nullptr &&
  392. end == orig[i + 1].Begin) {
  393. end = orig[i + 1].End;
  394. i++;
  395. }
  396. // Add an entry per intersected chunk.
  397. do {
  398. // Find the smallest aligned storage unit in the maximal aligned
  399. // storage unit containing 'begin' that contains all the bytes in
  400. // the intersection between the range and this chunk.
  401. CharUnits localBegin = begin;
  402. CharUnits chunkBegin = getOffsetAtStartOfUnit(localBegin, chunkSize);
  403. CharUnits chunkEnd = chunkBegin + chunkSize;
  404. CharUnits localEnd = std::min(end, chunkEnd);
  405. // Just do a simple loop over ever-increasing unit sizes.
  406. CharUnits unitSize = CharUnits::One();
  407. CharUnits unitBegin, unitEnd;
  408. for (; ; unitSize *= 2) {
  409. assert(unitSize <= chunkSize);
  410. unitBegin = getOffsetAtStartOfUnit(localBegin, unitSize);
  411. unitEnd = unitBegin + unitSize;
  412. if (unitEnd >= localEnd) break;
  413. }
  414. // Add an entry for this unit.
  415. auto entryTy =
  416. llvm::IntegerType::get(CGM.getLLVMContext(),
  417. CGM.getContext().toBits(unitSize));
  418. Entries.push_back({unitBegin, unitEnd, entryTy});
  419. // The next chunk starts where this chunk left off.
  420. begin = localEnd;
  421. } while (begin != end);
  422. }
  423. // Okay, finally finished.
  424. Finished = true;
  425. }
  426. void SwiftAggLowering::enumerateComponents(EnumerationCallback callback) const {
  427. assert(Finished && "haven't yet finished lowering");
  428. for (auto &entry : Entries) {
  429. callback(entry.Begin, entry.End, entry.Type);
  430. }
  431. }
  432. std::pair<llvm::StructType*, llvm::Type*>
  433. SwiftAggLowering::getCoerceAndExpandTypes() const {
  434. assert(Finished && "haven't yet finished lowering");
  435. auto &ctx = CGM.getLLVMContext();
  436. if (Entries.empty()) {
  437. auto type = llvm::StructType::get(ctx);
  438. return { type, type };
  439. }
  440. SmallVector<llvm::Type*, 8> elts;
  441. CharUnits lastEnd = CharUnits::Zero();
  442. bool hasPadding = false;
  443. bool packed = false;
  444. for (auto &entry : Entries) {
  445. if (entry.Begin != lastEnd) {
  446. auto paddingSize = entry.Begin - lastEnd;
  447. assert(!paddingSize.isNegative());
  448. auto padding = llvm::ArrayType::get(llvm::Type::getInt8Ty(ctx),
  449. paddingSize.getQuantity());
  450. elts.push_back(padding);
  451. hasPadding = true;
  452. }
  453. if (!packed && !entry.Begin.isMultipleOf(
  454. CharUnits::fromQuantity(
  455. CGM.getDataLayout().getABITypeAlignment(entry.Type))))
  456. packed = true;
  457. elts.push_back(entry.Type);
  458. lastEnd = entry.Begin + getTypeAllocSize(CGM, entry.Type);
  459. assert(entry.End <= lastEnd);
  460. }
  461. // We don't need to adjust 'packed' to deal with possible tail padding
  462. // because we never do that kind of access through the coercion type.
  463. auto coercionType = llvm::StructType::get(ctx, elts, packed);
  464. llvm::Type *unpaddedType = coercionType;
  465. if (hasPadding) {
  466. elts.clear();
  467. for (auto &entry : Entries) {
  468. elts.push_back(entry.Type);
  469. }
  470. if (elts.size() == 1) {
  471. unpaddedType = elts[0];
  472. } else {
  473. unpaddedType = llvm::StructType::get(ctx, elts, /*packed*/ false);
  474. }
  475. } else if (Entries.size() == 1) {
  476. unpaddedType = Entries[0].Type;
  477. }
  478. return { coercionType, unpaddedType };
  479. }
  480. bool SwiftAggLowering::shouldPassIndirectly(bool asReturnValue) const {
  481. assert(Finished && "haven't yet finished lowering");
  482. // Empty types don't need to be passed indirectly.
  483. if (Entries.empty()) return false;
  484. // Avoid copying the array of types when there's just a single element.
  485. if (Entries.size() == 1) {
  486. return getSwiftABIInfo(CGM).shouldPassIndirectlyForSwift(
  487. Entries.back().Type,
  488. asReturnValue);
  489. }
  490. SmallVector<llvm::Type*, 8> componentTys;
  491. componentTys.reserve(Entries.size());
  492. for (auto &entry : Entries) {
  493. componentTys.push_back(entry.Type);
  494. }
  495. return getSwiftABIInfo(CGM).shouldPassIndirectlyForSwift(componentTys,
  496. asReturnValue);
  497. }
  498. bool swiftcall::shouldPassIndirectly(CodeGenModule &CGM,
  499. ArrayRef<llvm::Type*> componentTys,
  500. bool asReturnValue) {
  501. return getSwiftABIInfo(CGM).shouldPassIndirectlyForSwift(componentTys,
  502. asReturnValue);
  503. }
  504. CharUnits swiftcall::getMaximumVoluntaryIntegerSize(CodeGenModule &CGM) {
  505. // Currently always the size of an ordinary pointer.
  506. return CGM.getContext().toCharUnitsFromBits(
  507. CGM.getContext().getTargetInfo().getPointerWidth(0));
  508. }
  509. CharUnits swiftcall::getNaturalAlignment(CodeGenModule &CGM, llvm::Type *type) {
  510. // For Swift's purposes, this is always just the store size of the type
  511. // rounded up to a power of 2.
  512. auto size = (unsigned long long) getTypeStoreSize(CGM, type).getQuantity();
  513. if (!isPowerOf2(size)) {
  514. size = 1ULL << (llvm::findLastSet(size, llvm::ZB_Undefined) + 1);
  515. }
  516. assert(size >= CGM.getDataLayout().getABITypeAlignment(type));
  517. return CharUnits::fromQuantity(size);
  518. }
  519. bool swiftcall::isLegalIntegerType(CodeGenModule &CGM,
  520. llvm::IntegerType *intTy) {
  521. auto size = intTy->getBitWidth();
  522. switch (size) {
  523. case 1:
  524. case 8:
  525. case 16:
  526. case 32:
  527. case 64:
  528. // Just assume that the above are always legal.
  529. return true;
  530. case 128:
  531. return CGM.getContext().getTargetInfo().hasInt128Type();
  532. default:
  533. return false;
  534. }
  535. }
  536. bool swiftcall::isLegalVectorType(CodeGenModule &CGM, CharUnits vectorSize,
  537. llvm::VectorType *vectorTy) {
  538. return isLegalVectorType(CGM, vectorSize, vectorTy->getElementType(),
  539. vectorTy->getNumElements());
  540. }
  541. bool swiftcall::isLegalVectorType(CodeGenModule &CGM, CharUnits vectorSize,
  542. llvm::Type *eltTy, unsigned numElts) {
  543. assert(numElts > 1 && "illegal vector length");
  544. return getSwiftABIInfo(CGM)
  545. .isLegalVectorTypeForSwift(vectorSize, eltTy, numElts);
  546. }
  547. std::pair<llvm::Type*, unsigned>
  548. swiftcall::splitLegalVectorType(CodeGenModule &CGM, CharUnits vectorSize,
  549. llvm::VectorType *vectorTy) {
  550. auto numElts = vectorTy->getNumElements();
  551. auto eltTy = vectorTy->getElementType();
  552. // Try to split the vector type in half.
  553. if (numElts >= 4 && isPowerOf2(numElts)) {
  554. if (isLegalVectorType(CGM, vectorSize / 2, eltTy, numElts / 2))
  555. return {llvm::VectorType::get(eltTy, numElts / 2), 2};
  556. }
  557. return {eltTy, numElts};
  558. }
  559. void swiftcall::legalizeVectorType(CodeGenModule &CGM, CharUnits origVectorSize,
  560. llvm::VectorType *origVectorTy,
  561. llvm::SmallVectorImpl<llvm::Type*> &components) {
  562. // If it's already a legal vector type, use it.
  563. if (isLegalVectorType(CGM, origVectorSize, origVectorTy)) {
  564. components.push_back(origVectorTy);
  565. return;
  566. }
  567. // Try to split the vector into legal subvectors.
  568. auto numElts = origVectorTy->getNumElements();
  569. auto eltTy = origVectorTy->getElementType();
  570. assert(numElts != 1);
  571. // The largest size that we're still considering making subvectors of.
  572. // Always a power of 2.
  573. unsigned logCandidateNumElts = llvm::findLastSet(numElts, llvm::ZB_Undefined);
  574. unsigned candidateNumElts = 1U << logCandidateNumElts;
  575. assert(candidateNumElts <= numElts && candidateNumElts * 2 > numElts);
  576. // Minor optimization: don't check the legality of this exact size twice.
  577. if (candidateNumElts == numElts) {
  578. logCandidateNumElts--;
  579. candidateNumElts >>= 1;
  580. }
  581. CharUnits eltSize = (origVectorSize / numElts);
  582. CharUnits candidateSize = eltSize * candidateNumElts;
  583. // The sensibility of this algorithm relies on the fact that we never
  584. // have a legal non-power-of-2 vector size without having the power of 2
  585. // also be legal.
  586. while (logCandidateNumElts > 0) {
  587. assert(candidateNumElts == 1U << logCandidateNumElts);
  588. assert(candidateNumElts <= numElts);
  589. assert(candidateSize == eltSize * candidateNumElts);
  590. // Skip illegal vector sizes.
  591. if (!isLegalVectorType(CGM, candidateSize, eltTy, candidateNumElts)) {
  592. logCandidateNumElts--;
  593. candidateNumElts /= 2;
  594. candidateSize /= 2;
  595. continue;
  596. }
  597. // Add the right number of vectors of this size.
  598. auto numVecs = numElts >> logCandidateNumElts;
  599. components.append(numVecs, llvm::VectorType::get(eltTy, candidateNumElts));
  600. numElts -= (numVecs << logCandidateNumElts);
  601. if (numElts == 0) return;
  602. // It's possible that the number of elements remaining will be legal.
  603. // This can happen with e.g. <7 x float> when <3 x float> is legal.
  604. // This only needs to be separately checked if it's not a power of 2.
  605. if (numElts > 2 && !isPowerOf2(numElts) &&
  606. isLegalVectorType(CGM, eltSize * numElts, eltTy, numElts)) {
  607. components.push_back(llvm::VectorType::get(eltTy, numElts));
  608. return;
  609. }
  610. // Bring vecSize down to something no larger than numElts.
  611. do {
  612. logCandidateNumElts--;
  613. candidateNumElts /= 2;
  614. candidateSize /= 2;
  615. } while (candidateNumElts > numElts);
  616. }
  617. // Otherwise, just append a bunch of individual elements.
  618. components.append(numElts, eltTy);
  619. }
  620. bool swiftcall::shouldPassCXXRecordIndirectly(CodeGenModule &CGM,
  621. const CXXRecordDecl *record) {
  622. // FIXME: should we not rely on the standard computation in Sema, just in
  623. // case we want to diverge from the platform ABI (e.g. on targets where
  624. // that uses the MSVC rule)?
  625. return !record->canPassInRegisters();
  626. }
  627. static ABIArgInfo classifyExpandedType(SwiftAggLowering &lowering,
  628. bool forReturn,
  629. CharUnits alignmentForIndirect) {
  630. if (lowering.empty()) {
  631. return ABIArgInfo::getIgnore();
  632. } else if (lowering.shouldPassIndirectly(forReturn)) {
  633. return ABIArgInfo::getIndirect(alignmentForIndirect, /*byval*/ false);
  634. } else {
  635. auto types = lowering.getCoerceAndExpandTypes();
  636. return ABIArgInfo::getCoerceAndExpand(types.first, types.second);
  637. }
  638. }
  639. static ABIArgInfo classifyType(CodeGenModule &CGM, CanQualType type,
  640. bool forReturn) {
  641. if (auto recordType = dyn_cast<RecordType>(type)) {
  642. auto record = recordType->getDecl();
  643. auto &layout = CGM.getContext().getASTRecordLayout(record);
  644. if (auto cxxRecord = dyn_cast<CXXRecordDecl>(record)) {
  645. if (shouldPassCXXRecordIndirectly(CGM, cxxRecord))
  646. return ABIArgInfo::getIndirect(layout.getAlignment(), /*byval*/ false);
  647. }
  648. SwiftAggLowering lowering(CGM);
  649. lowering.addTypedData(recordType->getDecl(), CharUnits::Zero(), layout);
  650. lowering.finish();
  651. return classifyExpandedType(lowering, forReturn, layout.getAlignment());
  652. }
  653. // Just assume that all of our target ABIs can support returning at least
  654. // two integer or floating-point values.
  655. if (isa<ComplexType>(type)) {
  656. return (forReturn ? ABIArgInfo::getDirect() : ABIArgInfo::getExpand());
  657. }
  658. // Vector types may need to be legalized.
  659. if (isa<VectorType>(type)) {
  660. SwiftAggLowering lowering(CGM);
  661. lowering.addTypedData(type, CharUnits::Zero());
  662. lowering.finish();
  663. CharUnits alignment = CGM.getContext().getTypeAlignInChars(type);
  664. return classifyExpandedType(lowering, forReturn, alignment);
  665. }
  666. // Member pointer types need to be expanded, but it's a simple form of
  667. // expansion that 'Direct' can handle. Note that CanBeFlattened should be
  668. // true for this to work.
  669. // 'void' needs to be ignored.
  670. if (type->isVoidType()) {
  671. return ABIArgInfo::getIgnore();
  672. }
  673. // Everything else can be passed directly.
  674. return ABIArgInfo::getDirect();
  675. }
  676. ABIArgInfo swiftcall::classifyReturnType(CodeGenModule &CGM, CanQualType type) {
  677. return classifyType(CGM, type, /*forReturn*/ true);
  678. }
  679. ABIArgInfo swiftcall::classifyArgumentType(CodeGenModule &CGM,
  680. CanQualType type) {
  681. return classifyType(CGM, type, /*forReturn*/ false);
  682. }
  683. void swiftcall::computeABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) {
  684. auto &retInfo = FI.getReturnInfo();
  685. retInfo = classifyReturnType(CGM, FI.getReturnType());
  686. for (unsigned i = 0, e = FI.arg_size(); i != e; ++i) {
  687. auto &argInfo = FI.arg_begin()[i];
  688. argInfo.info = classifyArgumentType(CGM, argInfo.type);
  689. }
  690. }
  691. // Is swifterror lowered to a register by the target ABI.
  692. bool swiftcall::isSwiftErrorLoweredInRegister(CodeGenModule &CGM) {
  693. return getSwiftABIInfo(CGM).isSwiftErrorInRegister();
  694. }