LLVM 24.0.0git
X86.cpp
Go to the documentation of this file.
1//===- X86.cpp ------------------------------------------------------------===//
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
10#include "llvm/ABI/TargetInfo.h"
11#include "llvm/ABI/Types.h"
17#include <algorithm>
18#include <cassert>
19#include <cstdint>
20
21namespace llvm {
22namespace abi {
23
25 switch (AVXLevel) {
27 return 512;
29 return 256;
31 return 128;
32 }
33 llvm_unreachable("Unknown AVXLevel");
34}
35
36// The width of an integer's storage container, mirroring Clang's
37// ASTContext::getTypeSize. For a plain integer this is its bit width; for a
38// _BitInt(N) it is N rounded up to the type's alignment. The x86-64 _BitInt
39// max alignment is 64, so this clamp is target-specific and kept file-local.
41 uint64_t NumBits = IT->getSizeInBits().getFixedValue();
42 if (!IT->isBitInt())
43 return NumBits;
44 uint64_t BitAlign =
45 std::max<uint64_t>(8, std::min<uint64_t>(64, llvm::bit_ceil(NumBits)));
46 return llvm::alignTo(NumBits, BitAlign);
47}
48
50 const Type *EltTy = VT->getElementType();
51 uint64_t EltWidth = EltTy->getSizeInBits().getFixedValue();
52 if (const auto *IT = dyn_cast<IntegerType>(EltTy))
54 uint64_t Width =
55 std::max<uint64_t>(8, EltWidth * VT->getNumElements().getKnownMinValue());
56 if (Width & (Width - 1))
57 Width = llvm::alignTo(Width, llvm::bit_ceil(Width));
58 return Width;
59}
60
61// The storage-container width of a type, mirroring Clang's getTypeSize. Used on
62// the stack path so a _BitInt or illegal vector coerces to the integer covering
63// its storage, not its raw iN width.
65 if (const auto *VT = dyn_cast<VectorType>(Ty))
67 if (const auto *IT = dyn_cast<IntegerType>(Ty))
69 return Ty->getSizeInBits().getFixedValue();
70}
71
73public:
75
76private:
77 TypeBuilder &TB;
78 X86AVXABILevel AVXLevel;
79 bool Has64BitPointers;
80
81 static Class merge(Class Accum, Class Field);
82
83 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
84
85 void classify(const Type *T, uint64_t OffsetBase, Class &Lo, Class &Hi,
86 bool IsNamedArg, bool IsRegCall = false) const;
87
88 const Type *getIntegerTypeAtOffset(const Type *IRType, unsigned IROffset,
89 const Type *SourceTy,
90 unsigned SourceOffset,
91 bool InMemory = false) const;
92
93 const Type *getSSETypeAtOffset(const Type *ABIType, unsigned ABIOffset,
94 const Type *SourceTy,
95 unsigned SourceOffset) const;
96 bool isIllegalVectorType(const Type *Ty) const;
97 bool containsMatrixField(const RecordType *RT) const;
98
99 void computeInfo(FunctionInfo &FI) const override;
100 ArgInfo getIndirectReturnResult(const Type *Ty) const;
101 const Type *getFPTypeAtOffset(const Type *Ty, unsigned Offset) const;
102
103 const Type *isSingleElementStruct(const Type *Ty) const;
104 const Type *getByteVectorType(const Type *Ty) const;
105
106 const Type *createPairType(const Type *Lo, const Type *Hi) const;
107 ArgInfo getIndirectResult(const Type *Ty, unsigned FreeIntRegs) const;
108
109 ArgInfo classifyReturnType(const Type *RetTy) const;
110
111 ArgInfo classifyArgumentType(const Type *Ty, unsigned FreeIntRegs,
112 unsigned &NeededInt, unsigned &NeededSse,
113 bool IsNamedArg, bool IsRegCall = false) const;
114
115public:
117 bool Has64BitPtrs, const ABICompatInfo &Compat)
118 : TargetInfo(Compat), TB(TypeBuilder), AVXLevel(AVXABILevel),
119 Has64BitPointers(Has64BitPtrs) {}
120
121 bool has64BitPointers() const { return Has64BitPointers; }
122};
123
124static bool bitsContainNoUserData(const Type *Ty, unsigned StartBit,
125 unsigned EndBit);
126
127// Gets the "best" type to represent the union.
128static const Type *reduceUnionForX8664(const RecordType *UnionType,
129 TypeBuilder &TB) {
130 assert(UnionType->isUnion() && "Expected union type");
131
132 ArrayRef<FieldInfo> Fields = UnionType->getFields();
133 if (Fields.empty()) {
134 return nullptr;
135 }
136
137 const Type *StorageType = nullptr;
138
139 for (const auto &Field : Fields) {
140 if (Field.IsBitField && Field.IsUnnamedBitfield &&
141 Field.BitFieldWidth == 0) {
142 continue;
143 }
144
145 const Type *FieldType = Field.FieldType;
146
147 if (UnionType->isTransparentUnion() && !StorageType) {
148 StorageType = FieldType;
149 break;
150 }
151
152 // A member that holds no user data supplies no bytes for a coercion to
153 // read, so it must not become the storage type however wide or aligned it
154 // is declared. Clang compares lowered types instead, where an empty class
155 // is a byte array whose i8 leaf lets getIntegerTypeAtOffset narrow the
156 // coercion. A record mapped here holds no fields, so there is no such
157 // leaf and the eightbyte would be sized from the union.
158 if (bitsContainNoUserData(FieldType, 0,
159 FieldType->getSizeInBits().getFixedValue()))
160 continue;
161
162 if (!StorageType ||
163 FieldType->getAlignment() > StorageType->getAlignment() ||
164 (FieldType->getAlignment() == StorageType->getAlignment() &&
165 TypeSize::isKnownGT(FieldType->getSizeInBits(),
166 StorageType->getSizeInBits()))) {
167 StorageType = FieldType;
168 }
169 }
170 return StorageType;
171}
172
173void X86_64TargetInfo::postMerge(unsigned AggregateSize, Class &Lo,
174 Class &Hi) const {
175 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
176 //
177 // (a) If one of the classes is Memory, the whole argument is passed in
178 // memory.
179 //
180 // (b) If X87Up is not preceded by X87, the whole argument is passed in
181 // memory.
182 //
183 // (c) If the size of the aggregate exceeds two eightbytes and the first
184 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
185 // argument is passed in memory. NOTE: This is necessary to keep the
186 // ABI working for processors that don't support the __m256 type.
187 //
188 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
189 //
190 // Some of these are enforced by the merging logic. Others can arise
191 // only with unions; for example:
192 // union { _Complex double; unsigned; }
193 //
194 // Note that clauses (b) and (c) were added in 0.98.
195
196 if (Hi == Memory)
197 Lo = Memory;
198 if (Hi == X87Up && Lo != X87 && getABICompatInfo().HonorsRevision98)
199 Lo = Memory;
200 if (AggregateSize > 128 && (Lo != Sse || Hi != SseUp))
201 Lo = Memory;
202 if (Hi == SseUp && Lo != Sse)
203 Hi = Sse;
204}
205X86_64TargetInfo::Class X86_64TargetInfo::merge(Class Accum, Class Field) {
206 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
207 // classified recursively so that always two fields are
208 // considered. The resulting class is calculated according to
209 // the classes of the fields in the eightbyte:
210 //
211 // (a) If both classes are equal, this is the resulting class.
212 //
213 // (b) If one of the classes is NO_CLASS, the resulting class is
214 // the other class.
215 //
216 // (c) If one of the classes is MEMORY, the result is the MEMORY
217 // class.
218 //
219 // (d) If one of the classes is INTEGER, the result is the
220 // INTEGER.
221 //
222 // (e) If one of the classes is X87, X87Up, COMPLEX_X87 class,
223 // MEMORY is used as class.
224 //
225 // (f) Otherwise class SSE is used.
226
227 // Accum should never be memory (we should have returned) or
228 // ComplexX87 (because this cannot be passed in a structure).
229 assert((Accum != Memory && Accum != ComplexX87) &&
230 "Invalid accumulated classification during merge.");
231
232 if (Accum == Field || Field == NoClass)
233 return Accum;
234 if (Field == Memory)
235 return Memory;
236 if (Accum == NoClass)
237 return Field;
238 if (Accum == Integer || Field == Integer)
239 return Integer;
240 if (Field == X87 || Field == X87Up || Field == ComplexX87 || Accum == X87 ||
241 Accum == X87Up)
242 return Memory;
243
244 return Sse;
245}
246
247// A record with a matrix-extension field is passed in memory. clang has no
248// matrix-specific ABI code: a matrix falls through X86_64ABIInfo::classify to
249// the default MEMORY class. We model matrices as arrays, so this check
250// reproduces that record-with-matrix -> MEMORY result.
251bool X86_64TargetInfo::containsMatrixField(const RecordType *RT) const {
252 for (const auto &Field : RT->getFields()) {
253 const Type *FieldType = Field.FieldType;
254
255 if (const auto *AT = dyn_cast<ArrayType>(FieldType)) {
256 if (AT->isMatrixType())
257 return true;
258 continue;
259 }
260
261 if (const auto *NestedRT = dyn_cast<RecordType>(FieldType))
262 if (containsMatrixField(NestedRT))
263 return true;
264 }
265 return false;
266}
267
268void X86_64TargetInfo::classify(const Type *T, uint64_t OffsetBase, Class &Lo,
269 Class &Hi, bool IsNamedArg,
270 bool IsRegCall) const {
271 Lo = Hi = NoClass;
272 Class &Current = OffsetBase < 64 ? Lo : Hi;
273 Current = Memory;
274
275 if (T->isVoid()) {
276 Current = NoClass;
277 return;
278 }
279
280 if (const auto *IT = dyn_cast<IntegerType>(T)) {
281 auto BitWidth = IT->getSizeInBits().getFixedValue();
282
283 if (BitWidth == 128 ||
284 (IT->isBitInt() && BitWidth > 64 && BitWidth <= 128)) {
285 Lo = Integer;
286 Hi = Integer;
287 } else if (BitWidth <= 64) {
288 Current = Integer;
289 }
290
291 return;
292 }
293
294 if (const auto *FT = dyn_cast<FloatType>(T)) {
295 const auto *FltSem = FT->getSemantics();
296
297 if (FltSem == &llvm::APFloat::IEEEsingle() ||
298 FltSem == &llvm::APFloat::IEEEdouble() ||
299 FltSem == &llvm::APFloat::IEEEhalf() ||
300 FltSem == &llvm::APFloat::BFloat()) {
301 Current = Sse;
302 } else if (FltSem == &llvm::APFloat::IEEEquad()) {
303 Lo = Sse;
304 Hi = SseUp;
305 } else if (FltSem == &llvm::APFloat::x87DoubleExtended()) {
306 Lo = X87;
307 Hi = X87Up;
308 } else {
309 Current = Sse;
310 }
311 return;
312 }
313 if (T->isPointer()) {
314 Current = Integer;
315 return;
316 }
317
318 if (const auto *MPT = dyn_cast<MemberPointerType>(T)) {
319 if (MPT->isFunctionPointer()) {
320 if (Has64BitPointers) {
321 Lo = Hi = Integer;
322 } else {
323 uint64_t EbFuncPtr = OffsetBase / 64;
324 uint64_t EbThisAdj = (OffsetBase + 64 - 1) / 64;
325 if (EbFuncPtr != EbThisAdj) {
326 Lo = Hi = Integer;
327 } else {
328 Current = Integer;
329 }
330 }
331 } else {
332 Current = Integer;
333 }
334 return;
335 }
336
337 if (const auto *VT = dyn_cast<VectorType>(T)) {
338 auto Size = VT->getSizeInBits().getFixedValue();
339 const Type *ElementType = VT->getElementType();
340
341 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
342 // gcc passes the following as integer:
343 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
344 // 2 bytes - <2 x char>, <1 x short>
345 // 1 byte - <1 x char>
346 Current = Integer;
347 // If this type crosses an eightbyte boundary, it should be
348 // split.
349 uint64_t EbLo = (OffsetBase) / 64;
350 uint64_t EbHi = (OffsetBase + Size - 1) / 64;
351 if (EbLo != EbHi)
352 Hi = Lo;
353 } else if (Size == 64) {
354 if (const auto *FT = dyn_cast<FloatType>(ElementType)) {
355 // gcc passes <1 x double> in memory. :(
356 if (FT->getSemantics() == &llvm::APFloat::IEEEdouble())
357 return;
358 }
359
360 // gcc passes <1 x long long> as SSE but clang used to unconditionally
361 // pass them as integer. For platforms where clang is the de facto
362 // platform compiler, we must continue to use integer.
363 if (const auto *IT = dyn_cast<IntegerType>(ElementType)) {
364 uint64_t ElemBits = IT->getSizeInBits().getFixedValue();
365 if (!getABICompatInfo().ClassifyIntegerMMXAsSSE && ElemBits == 64 &&
366 !IT->isBitInt()) {
367 Current = Integer;
368 } else {
369 Current = Sse;
370 }
371 } else {
372 Current = Sse;
373 }
374 // If this type crosses an eightbyte boundary, it should be
375 // split.
376 if (OffsetBase && OffsetBase != 64)
377 Hi = Lo;
378 } else if (Size == 128 ||
379 (IsNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
380 if (const auto *IT = dyn_cast<IntegerType>(ElementType)) {
381 uint64_t ElemBits = IT->getSizeInBits().getFixedValue();
382 // gcc passes 256 and 512 bit <X x __int128> vectors in memory. :(
383 if (getABICompatInfo().PassInt128VectorsInMem && Size != 128 &&
384 ElemBits == 128 && !IT->isBitInt())
385 return;
386 }
387
388 // Arguments of 256-bits are split into four eightbyte chunks. The
389 // least significant one belongs to class SSE and all the others to class
390 // SSEUP. The original Lo and Hi design considers that types can't be
391 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
392 // This design isn't correct for 256-bits, but since there're no cases
393 // where the upper parts would need to be inspected, avoid adding
394 // complexity and just consider Hi to match the 64-256 part.
395 //
396 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
397 // registers if they are "named", i.e. not part of the "..." of a
398 // variadic function.
399 //
400 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
401 // split into eight eightbyte chunks, one SSE and seven SSEUP.
402 Lo = Sse;
403 Hi = SseUp;
404 }
405 return;
406 }
407
408 if (const auto *CT = dyn_cast<ComplexType>(T)) {
409 const Type *ElementType = CT->getElementType();
410 uint64_t Size = T->getSizeInBits().getFixedValue();
411
412 if (isa<IntegerType>(ElementType)) {
413 if (Size <= 64)
414 Current = Integer;
415 else if (Size <= 128)
416 Lo = Hi = Integer;
417 } else if (const auto *EFT = dyn_cast<FloatType>(ElementType)) {
418 const auto *FltSem = EFT->getSemantics();
419 if (FltSem == &llvm::APFloat::IEEEhalf() ||
420 FltSem == &llvm::APFloat::IEEEsingle() ||
421 FltSem == &llvm::APFloat::BFloat())
422 Current = Sse;
423 else if (FltSem == &llvm::APFloat::IEEEquad())
424 Current = Memory;
425 else if (FltSem == &llvm::APFloat::x87DoubleExtended())
426 Current = ComplexX87;
427 else if (FltSem == &llvm::APFloat::IEEEdouble())
428 Lo = Hi = Sse;
429 else
430 llvm_unreachable("Unexpected long double representation!");
431 }
432
433 uint64_t ElementSize = ElementType->getSizeInBits().getFixedValue();
434 // If this complex type crosses an eightbyte boundary then it
435 // should be split.
436 uint64_t EbReal = OffsetBase / 64;
437 uint64_t EbImag = (OffsetBase + ElementSize) / 64;
438 if (Hi == NoClass && EbReal != EbImag)
439 Hi = Lo;
440
441 return;
442 }
443
444 if (const auto *AT = dyn_cast<ArrayType>(T)) {
445 // A matrix type is modeled as an array but, like Clang, is treated as a
446 // non-aggregate scalar: it matches no class here and stays in the Memory
447 // class, so classify*Type later returns it Direct (coerced to its
448 // flattened vector) rather than classifying it field-by-field.
449 if (AT->isMatrixType())
450 return;
451
452 // Arrays are treated like structures.
453 uint64_t Size = AT->getSizeInBits().getFixedValue();
454
455 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
456 // than eight eightbytes, ..., it has class MEMORY.
457 // regcall ABI doesn't have limitation to an object. The only limitation
458 // is the free registers, which will be checked in computeInfo.
459 if (!IsRegCall && Size > 512)
460 return;
461
462 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
463 // fields, it has class MEMORY.
464 //
465 // Only need to check alignment of array base.
466 const Type *ElementType = AT->getElementType();
467 uint64_t ElemAlign = ElementType->getAlignment().value() * 8;
468 if (OffsetBase % ElemAlign)
469 return;
470
471 // Otherwise implement simplified merge. We could be smarter about
472 // this, but it isn't worth it and would be harder to verify.
473 Current = NoClass;
474 uint64_t EltSize = ElementType->getSizeInBits().getFixedValue();
475 uint64_t ArraySize = AT->getNumElements();
476
477 // The only case a 256-bit wide vector could be used is when the array
478 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
479 // to work for sizes wider than 128, early check and fallback to memory.
480 //
481 if (Size > 128 &&
482 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
483 return;
484
485 for (uint64_t I = 0, Offset = OffsetBase; I < ArraySize;
486 ++I, Offset += EltSize) {
487 Class FieldLo, FieldHi;
488 classify(ElementType, Offset, FieldLo, FieldHi, IsNamedArg);
489 Lo = merge(Lo, FieldLo);
490 Hi = merge(Hi, FieldHi);
491 if (Lo == Memory || Hi == Memory)
492 break;
493 }
494 postMerge(Size, Lo, Hi);
495 assert((Hi != SseUp || Lo == Sse) && "Invalid SseUp array classification.");
496 return;
497 }
498
499 if (const auto *RT = dyn_cast<RecordType>(T)) {
500 uint64_t Size = RT->getSizeInBits().getFixedValue();
501
502 if (containsMatrixField(RT)) {
503 Lo = Memory;
504 return;
505 }
506
507 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
508 // than eight eightbytes, ..., it has class MEMORY.
509 if (Size > 512)
510 return;
511
512 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
513 // copy constructor or a non-trivial destructor, it is passed by invisible
514 // reference.
515 if (getRecordArgABI(RT))
516 return;
517
518 // Assume variable sized types are passed in memory.
519 if (RT->hasFlexibleArrayMember())
520 return;
521
522 // Reset Lo class, this will be recomputed.
523 Current = NoClass;
524
525 // If this is a C++ record, classify the bases first.
526 if (RT->isCXXRecord()) {
527 for (const auto &Base : RT->getBaseClasses()) {
528
529 // Classify this field.
530 //
531 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
532 // single eightbyte, each is classified separately. Each eightbyte gets
533 // initialized to class NO_CLASS.
534 Class FieldLo, FieldHi;
535 uint64_t Offset = OffsetBase + Base.OffsetInBits;
536 classify(Base.FieldType, Offset, FieldLo, FieldHi, IsNamedArg);
537 Lo = merge(Lo, FieldLo);
538 Hi = merge(Hi, FieldHi);
539
540 if (getABICompatInfo().ReturnCXXRecordGreaterThan128InMem &&
541 (Size > 128 &&
542 (Size != Base.FieldType->getSizeInBits().getFixedValue() ||
544 Lo = Memory;
545
546 if (Lo == Memory || Hi == Memory) {
547 postMerge(Size, Lo, Hi);
548 return;
549 }
550 }
551 }
552
553 // Classify the fields one at a time, merging the results.
554
555 bool IsUnion = RT->isUnion() && !getABICompatInfo().Clang11Compat;
556 for (const auto &Field : RT->getFields()) {
557 uint64_t Offset = OffsetBase + Field.OffsetInBits;
558 bool BitField = Field.IsBitField;
559
560 // Ignore padding bit-fields. Normally only zero-length bit-fields are
561 // padding, but under Clang 23 compatibility every unnamed bit-field is,
562 // faithfully reproducing Clang 23.
563 if (BitField && (getABICompatInfo().ClassifyUnnamedBitFields
564 ? Field.BitFieldWidth == 0
565 : Field.IsUnnamedBitfield))
566 continue;
567
568 if (Size > 128 &&
569 ((!IsUnion &&
570 Size != Field.FieldType->getSizeInBits().getFixedValue()) ||
571 Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
572 Lo = Memory;
573 postMerge(Size, Lo, Hi);
574 return;
575 }
576
577 bool IsInMemory = Offset % (Field.FieldType->getAlignment().value() * 8);
578 if (!BitField && IsInMemory) {
579 Lo = Memory;
580 postMerge(Size, Lo, Hi);
581 return;
582 }
583
584 Class FieldLo, FieldHi;
585
586 if (BitField) {
587 uint64_t BitFieldSize = Field.BitFieldWidth;
588 uint64_t EbLo = Offset / 64;
589 uint64_t EbHi = (Offset + BitFieldSize - 1) / 64;
590
591 if (EbLo) {
592 assert(EbHi == EbLo && "Invalid classification, type > 16 bytes.");
593 FieldLo = NoClass;
594 FieldHi = Integer;
595 } else {
596 FieldLo = Integer;
597 FieldHi = EbHi ? Integer : NoClass;
598 }
599 } else {
600 classify(Field.FieldType, Offset, FieldLo, FieldHi, IsNamedArg);
601 }
602
603 Lo = merge(Lo, FieldLo);
604 Hi = merge(Hi, FieldHi);
605 if (Lo == Memory || Hi == Memory)
606 break;
607 }
608 postMerge(Size, Lo, Hi);
609 return;
610 }
611
612 Lo = Memory;
613 Hi = NoClass;
614}
615
617X86_64TargetInfo::classifyArgumentType(const Type *Ty, unsigned FreeIntRegs,
618 unsigned &NeededInt, unsigned &NeededSSE,
619 bool IsNamedArg, bool IsRegCall) const {
620
622
624 classify(Ty, 0, Lo, Hi, IsNamedArg, IsRegCall);
625
626 // Check some invariants
627 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
628 assert((Hi != SseUp || Lo == Sse) && "Invalid SseUp classification.");
629
630 NeededInt = 0;
631 NeededSSE = 0;
632 const Type *ResType = nullptr;
633
634 switch (Lo) {
635 case NoClass:
636 if (Hi == NoClass)
637 return ArgInfo::getIgnore();
638 // If the low part is just padding, it takes no register, leave ResType
639 // null.
640 assert((Hi == Sse || Hi == Integer || Hi == X87Up) &&
641 "Unknown missing lo part");
642 break;
643
644 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
645 // on the stack.
646 case Memory:
647 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87Up or
648 // COMPLEX_X87, it is passed in memory.
649 case X87:
650 case ComplexX87:
651 if (getRecordArgABI(Ty) == RAA_Indirect)
652 ++NeededInt;
653 return getIndirectResult(Ty, FreeIntRegs);
654
655 case SseUp:
656 case X87Up:
657 llvm_unreachable("Invalid classification for lo word.");
658
659 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
660 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
661 // and %r9 is used.
662 case Integer:
663 ++NeededInt;
664
665 // Pick an 8-byte type based on the preferred type.
666 ResType = getIntegerTypeAtOffset(Ty, 0, Ty, 0);
667
668 // If we have a sign or zero extended integer, make sure to return Extend
669 // so that the parameter gets the right LLVM IR attributes.
670 if (Hi == NoClass && ResType->isInteger()) {
671 if (Ty->isInteger() && isPromotableInteger(cast<IntegerType>(Ty)))
672 return ArgInfo::getExtend(Ty);
673 }
674
675 if (ResType->isInteger() && ResType->getSizeInBits() == 128) {
676 assert(Hi == Integer);
677 ++NeededInt;
678 return ArgInfo::getDirect(ResType);
679 }
680 break;
681
682 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
683 // available SSE register is used, the registers are taken in the
684 // order from %xmm0 to %xmm7.
685 case Sse:
686 ResType = getSSETypeAtOffset(Ty, 0, Ty, 0);
687 ++NeededSSE;
688 break;
689 }
690
691 const Type *HighPart = nullptr;
692 switch (Hi) {
693 // Memory was handled previously, ComplexX87 and X87 should
694 // never occur as hi classes, and X87Up must be preceded by X87,
695 // which is passed in memory.
696 case Memory:
697 case X87:
698 case ComplexX87:
699 llvm_unreachable("Invalid classification for hi word.");
700
701 case NoClass:
702 break;
703
704 case Integer:
705 ++NeededInt;
706 // Pick an 8-byte type based on the preferred type.
707 HighPart = getIntegerTypeAtOffset(Ty, 8, Ty, 8);
708
709 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
710 return ArgInfo::getDirect(HighPart, 8);
711 break;
712
713 // X87Up generally doesn't occur here (long double is passed in
714 // memory), except in situations involving unions.
715 case X87Up:
716 case Sse:
717 ++NeededSSE;
718 HighPart = getSSETypeAtOffset(Ty, 8, Ty, 8);
719
720 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
721 return ArgInfo::getDirect(HighPart, 8);
722 break;
723
724 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
725 // eightbyte is passed in the upper half of the last used SSE
726 // register. This only happens when 128-bit vectors are passed.
727 case SseUp:
728 assert(Lo == Sse && "Unexpected SseUp classification");
729 ResType = getByteVectorType(Ty);
730 break;
731 }
732
733 // If a high part was specified, merge it together with the low part. It is
734 // known to pass in the high eightbyte of the result. We do this by forming a
735 // first class struct aggregate with the high and low part: {low, high}
736 if (HighPart)
737 ResType = createPairType(ResType, HighPart);
738
739 return ArgInfo::getDirect(ResType);
740}
741
742ArgInfo X86_64TargetInfo::classifyReturnType(const Type *RetTy) const {
743 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
744 // classification algorithm.
745
747 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
748
749 // Check some invariants
750 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
751 assert((Hi != SseUp || Lo == Sse) && "Invalid SseUp classification.");
752
753 const Type *ResType = nullptr;
754 switch (Lo) {
755 case NoClass:
756 if (Hi == NoClass)
757 return ArgInfo::getIgnore();
758 // If the low part is just padding, it takes no register, leave ResType
759 // null.
760 assert((Hi == Sse || Hi == Integer || Hi == X87Up) &&
761 "Unknown missing lo part");
762 break;
763 case SseUp:
764 case X87Up:
765 llvm_unreachable("Invalid classification for lo word.");
766
767 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
768 // hidden argument.
769 case Memory:
770 return getIndirectReturnResult(RetTy);
771
772 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
773 // available register of the sequence %rax, %rdx is used.
774 case Integer:
775 ResType = getIntegerTypeAtOffset(RetTy, 0, RetTy, 0);
776 // If we have a sign or zero extended integer, make sure to return Extend
777 // so that the parameter gets the right LLVM IR attributes.
778 if (Hi == NoClass && ResType->isInteger()) {
779 if (const IntegerType *IntTy = dyn_cast<IntegerType>(RetTy)) {
780 if (isPromotableInteger(IntTy))
781 return ArgInfo::getExtend(RetTy);
782 }
783 }
784 if (ResType->isInteger() && ResType->getSizeInBits() == 128) {
785 assert(Hi == Integer);
786 return ArgInfo::getDirect(ResType);
787 }
788 break;
789
790 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
791 // available SSE register of the sequence %xmm0, %xmm1 is used.
792 case Sse:
793 ResType = getSSETypeAtOffset(RetTy, 0, RetTy, 0);
794 break;
795
796 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
797 // returned on the X87 stack in %st0 as 80-bit x87 number.
798 case X87:
799 ResType = TB.getFloatType(APFloat::x87DoubleExtended(), Align(16));
800 break;
801
802 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
803 // part of the value is returned in %st0 and the imaginary part in
804 // %st1.
805 case ComplexX87:
806 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
807 {
808 const Type *X87Type =
809 TB.getFloatType(APFloat::x87DoubleExtended(), Align(16));
810 FieldInfo Fields[] = {FieldInfo(X87Type, 0), FieldInfo(X87Type, 80)};
811 ResType = TB.getRecordType(Fields, TypeSize::getFixed(160), Align(16));
812 }
813 break;
814 }
815
816 const Type *HighPart = nullptr;
817 switch (Hi) {
818 // Memory was handled previously and X87 should
819 // never occur as a hi class.
820 case Memory:
821 case X87:
822 llvm_unreachable("Invalid classification for hi word.");
823
824 case ComplexX87:
825 case NoClass:
826 break;
827
828 case Integer:
829 HighPart = getIntegerTypeAtOffset(RetTy, 8, RetTy, 8);
830 if (Lo == NoClass)
831 return ArgInfo::getDirect(HighPart, 8);
832 break;
833
834 case Sse:
835 HighPart = getSSETypeAtOffset(RetTy, 8, RetTy, 8);
836 if (Lo == NoClass)
837 return ArgInfo::getDirect(HighPart, 8);
838 break;
839
840 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
841 // is passed in the next available eightbyte chunk if the last used
842 // vector register.
843 //
844 // SSEUP should always be preceded by SSE, just widen.
845 case SseUp:
846 assert(Lo == Sse && "Unexpected SseUp classification.");
847 ResType = getByteVectorType(RetTy);
848 break;
849
850 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87Up, the value is
851 // returned together with the previous X87 value in %st0.
852 case X87Up:
853 // If X87Up is preceded by X87, we don't need to do
854 // anything. However, in some cases with unions it may not be
855 // preceded by X87. In such situations we follow gcc and pass the
856 // extra bits in an SSE reg.
857 if (Lo != X87) {
858 HighPart = getSSETypeAtOffset(RetTy, 8, RetTy, 8);
859 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
860 return ArgInfo::getDirect(HighPart, 8);
861 }
862 break;
863 }
864
865 // If a high part was specified, merge it together with the low part. It is
866 // known to pass in the high eightbyte of the result. We do this by forming a
867 // first class struct aggregate with the high and low part: {low, high}
868 if (HighPart)
869 ResType = createPairType(ResType, HighPart);
870
871 return ArgInfo::getDirect(ResType);
872}
873
874/// Given a high and low type that can ideally
875/// be used as elements of a two register pair to pass or return, return a
876/// first class aggregate to represent them. For example, if the low part of
877/// a by-value argument should be passed as i32* and the high part as float,
878/// return {i32*, float}.
879const Type *X86_64TargetInfo::createPairType(const Type *Lo,
880 const Type *Hi) const {
881 // In order to correctly satisfy the ABI, we need to the high part to start
882 // at offset 8. If the high and low parts we inferred are both 4-byte types
883 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
884 // the second element at offset 8. Check for this:
885 unsigned LoSize = (unsigned)Lo->getTypeAllocSize();
886 llvm::Align HiAlign = Hi->getAlignment();
887 unsigned HiStart = alignTo(LoSize, HiAlign);
888
889 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
890
891 // To handle this, we have to increase the size of the low part so that the
892 // second element will start at an 8 byte offset. We can't increase the size
893 // of the second element because it might make us access off the end of the
894 // struct.
895 const Type *AdjustedLo = Lo;
896 if (HiStart != 8) {
897 // There are usually two sorts of types the ABI generation code can produce
898 // for the low part of a pair that aren't 8 bytes in size: half, float or
899 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
900 // NaCl).
901 // Promote these to a larger type.
902 if (Lo->isFloat()) {
903 const FloatType *FT = cast<FloatType>(Lo);
904 if (FT->getSemantics() == &APFloat::IEEEhalf() ||
905 FT->getSemantics() == &APFloat::IEEEsingle() ||
906 FT->getSemantics() == &APFloat::BFloat())
907 AdjustedLo = TB.getFloatType(APFloat::IEEEdouble(), Align(8));
908 }
909 // Promote integers and pointers to i64
910 else if (Lo->isInteger() || Lo->isPointer())
911 AdjustedLo = TB.getIntegerType(64, Align(8), /*Signed=*/false);
912 else
913 assert((Lo->isInteger() || Lo->isPointer()) &&
914 "Invalid/unknown low type in pair");
915 unsigned AdjustedLoSize = AdjustedLo->getSizeInBits().getFixedValue() / 8;
916 HiStart = alignTo(AdjustedLoSize, HiAlign);
917 }
918
919 // Create the pair struct
920 FieldInfo Fields[] = {FieldInfo(AdjustedLo, 0), FieldInfo(Hi, HiStart * 8)};
921
922 // Verify the high part is at offset 8
923 assert((8 * 8) == Fields[1].OffsetInBits &&
924 "High part must be at offset 8 bytes");
925
926 uint64_t PairSizeInBits =
927 Fields[1].OffsetInBits + Hi->getSizeInBits().getFixedValue();
928 return TB.getRecordType(Fields, TypeSize::getFixed(PairSizeInBits), Align(8),
930}
931
932static bool bitsContainNoUserData(const Type *Ty, unsigned StartBit,
933 unsigned EndBit) {
934 // If range is completely beyond type size, it's definitely padding
935 unsigned TySize = Ty->getSizeInBits().getFixedValue();
936 if (TySize <= StartBit)
937 return true;
938
939 // Handle arrays - check each element
940 if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
941 const Type *EltTy = AT->getElementType();
942 unsigned EltSize = EltTy->getSizeInBits().getFixedValue();
943
944 for (unsigned I = 0; I < AT->getNumElements(); ++I) {
945 unsigned EltOffset = I * EltSize;
946 if (EltOffset >= EndBit)
947 break;
948
949 unsigned EltStart = (EltOffset < StartBit) ? StartBit - EltOffset : 0;
950 if (!bitsContainNoUserData(EltTy, EltStart, EndBit - EltOffset))
951 return false;
952 }
953 return true;
954 }
955
956 // Handle records - check all fields and base classes. getUnionType places a
957 // union's members at offset zero, so the field loop covers a union too.
958 if (const RecordType *RT = dyn_cast<RecordType>(Ty)) {
959 // Check base classes first (for C++ records)
960 if (RT->isCXXRecord()) {
961 for (unsigned I = 0; I < RT->getNumBaseClasses(); ++I) {
962 const FieldInfo &Base = RT->getBaseClasses()[I];
963 if (Base.OffsetInBits >= EndBit)
964 continue;
965
966 unsigned BaseStart =
967 (Base.OffsetInBits < StartBit) ? StartBit - Base.OffsetInBits : 0;
968 if (!bitsContainNoUserData(Base.FieldType, BaseStart,
969 EndBit - Base.OffsetInBits))
970 return false;
971 }
972 }
973
974 for (unsigned I = 0; I < RT->getNumFields(); ++I) {
975 const FieldInfo &Field = RT->getFields()[I];
976 if (Field.OffsetInBits >= EndBit)
977 break;
978
979 unsigned FieldStart =
980 (Field.OffsetInBits < StartBit) ? StartBit - Field.OffsetInBits : 0;
981 if (!bitsContainNoUserData(Field.FieldType, FieldStart,
982 EndBit - Field.OffsetInBits))
983 return false;
984 }
985 return true;
986 }
987
988 // For any other type - assume all bits are user data
989 return false;
990}
991
992const Type *X86_64TargetInfo::getIntegerTypeAtOffset(const Type *ABIType,
993 unsigned ABIOffset,
994 const Type *SourceTy,
995 unsigned SourceOffset,
996 bool InMemory) const {
997
998 const Type *WorkingType = ABIType;
999 if (InMemory && ABIType->isInteger()) {
1000 const auto *IT = cast<IntegerType>(ABIType);
1001 unsigned OriginalBitWidth = IT->getSizeInBits().getFixedValue();
1002
1003 unsigned WidenedBitWidth = OriginalBitWidth;
1004 if (OriginalBitWidth <= 8) {
1005 WidenedBitWidth = 8;
1006 } else {
1007 WidenedBitWidth = llvm::bit_ceil(OriginalBitWidth);
1008 }
1009
1010 if (WidenedBitWidth != OriginalBitWidth) {
1011 WorkingType = TB.getIntegerType(WidenedBitWidth, ABIType->getAlignment(),
1012 IT->isSigned());
1013 }
1014 }
1015 // If we're dealing with an un-offset ABI type, then it means that we're
1016 // returning an 8-byte unit starting with it. See if we can safely use it.
1017 if (ABIOffset == 0) {
1018 // Pointers and int64's always fill the 8-byte unit. Return WorkingType,
1019 // which is the in-memory-widened type (e.g. a _BitInt(37) field widened to
1020 // i64): returning the raw ABIType here would coerce the eightbyte to the
1021 // narrow iN instead of the storage integer clang uses.
1022 if ((WorkingType->isPointer() && Has64BitPointers) ||
1023 (WorkingType->isInteger() &&
1024 cast<IntegerType>(WorkingType)->getSizeInBits() == 64))
1025 return WorkingType;
1026
1027 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
1028 // goodness in the source type is just tail padding. This is allowed to
1029 // kick in for struct {double,int} on the int, but not on
1030 // struct{double,int,int} because we wouldn't return the second int. We
1031 // have to do this analysis on the source type because we can't depend on
1032 // unions being lowered a specific way etc.
1033 if ((WorkingType->isInteger() &&
1034 (cast<IntegerType>(WorkingType)->getSizeInBits() == 1 ||
1035 cast<IntegerType>(WorkingType)->getSizeInBits() == 8 ||
1036 cast<IntegerType>(WorkingType)->getSizeInBits() == 16 ||
1037 cast<IntegerType>(WorkingType)->getSizeInBits() == 32)) ||
1038 (WorkingType->isPointer() && !Has64BitPointers)) {
1039
1040 unsigned BitWidth = WorkingType->isPointer()
1041 ? 32
1042 : cast<IntegerType>(WorkingType)->getSizeInBits();
1043
1044 if (bitsContainNoUserData(SourceTy, SourceOffset * 8 + BitWidth,
1045 SourceOffset * 8 + 64))
1046 return WorkingType;
1047 }
1048 }
1049
1050 if (const auto *RTy = dyn_cast<RecordType>(ABIType)) {
1051 if (RTy->isUnion()) {
1052 const Type *ReducedType = reduceUnionForX8664(RTy, TB);
1053 if (ReducedType)
1054 return getIntegerTypeAtOffset(ReducedType, ABIOffset, SourceTy,
1055 SourceOffset, true);
1056 }
1057 if (const FieldInfo *Element =
1058 RTy->getElementContainingOffset(ABIOffset * 8)) {
1059
1060 unsigned ElementOffsetBytes = Element->OffsetInBits / 8;
1061 return getIntegerTypeAtOffset(Element->FieldType,
1062 ABIOffset - ElementOffsetBytes, SourceTy,
1063 SourceOffset, true);
1064 }
1065 }
1066
1067 if (const auto *ATy = dyn_cast<ArrayType>(ABIType)) {
1068 const Type *EltTy = ATy->getElementType();
1069 unsigned EltSize = EltTy->getSizeInBits() / 8;
1070 if (EltSize > 0) {
1071 unsigned EltOffset = (ABIOffset / EltSize) * EltSize;
1072 return getIntegerTypeAtOffset(EltTy, ABIOffset - EltOffset, SourceTy,
1073 SourceOffset, true);
1074 }
1075 }
1076
1077 // If we have a 128-bit integer, we can pass it safely using an i128
1078 // so we return that
1079 if (ABIType->isInteger() && ABIType->getSizeInBits() == 128) {
1080 assert(ABIOffset == 0);
1081 return ABIType;
1082 }
1083
1084 unsigned TySizeInBytes =
1085 llvm::divideCeil(SourceTy->getSizeInBits().getFixedValue(), 8);
1086 if (auto *IT = dyn_cast<IntegerType>(SourceTy)) {
1087 if (IT->isBitInt())
1088 TySizeInBytes =
1089 alignTo(SourceTy->getSizeInBits().getFixedValue(), 64) / 8;
1090 }
1091 assert(TySizeInBytes != SourceOffset && "Empty field?");
1092 unsigned AvailableSize = TySizeInBytes - SourceOffset;
1093 return TB.getIntegerType(std::min(AvailableSize, 8U) * 8, Align(1), false);
1094}
1095/// Returns the floating point type at the specified offset within a type, or
1096/// nullptr if no floating point type is found at that offset.
1097const Type *X86_64TargetInfo::getFPTypeAtOffset(const Type *Ty,
1098 unsigned Offset) const {
1099 // Check for direct match at offset 0
1100 if (Offset == 0 && Ty->isFloat())
1101 return Ty;
1102
1103 if (const ComplexType *CT = dyn_cast<ComplexType>(Ty)) {
1104 const Type *ElementType = CT->getElementType();
1105 unsigned ElementSize = ElementType->getSizeInBits().getFixedValue() / 8;
1106
1107 if (Offset == 0 || Offset == ElementSize)
1108 return ElementType;
1109 return nullptr;
1110 }
1111
1112 // Handle struct types by checking each field
1113 if (const RecordType *RT = dyn_cast<RecordType>(Ty)) {
1114 if (const FieldInfo *Element = RT->getElementContainingOffset(Offset * 8)) {
1115 unsigned ElementOffsetBytes = Element->OffsetInBits / 8;
1116 return getFPTypeAtOffset(Element->FieldType, Offset - ElementOffsetBytes);
1117 }
1118 }
1119
1120 // Handle array types
1121 if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
1122 const Type *EltTy = AT->getElementType();
1123 unsigned EltSize = EltTy->getSizeInBits() / 8;
1124 unsigned EltIndex = Offset / EltSize;
1125
1126 return getFPTypeAtOffset(EltTy, Offset - (EltIndex * EltSize));
1127 }
1128
1129 // No floating point type found at this offset
1130 return nullptr;
1131}
1132
1133/// Helper to check if a floating point type matches specific semantics
1134static bool isFloatTypeWithSemantics(const Type *Ty,
1135 const fltSemantics &Semantics) {
1136 if (!Ty->isFloat())
1137 return false;
1138 const FloatType *FT = cast<FloatType>(Ty);
1139 return FT->getSemantics() == &Semantics;
1140}
1141
1142/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
1143/// low 8 bytes of an XMM register, corresponding to the SSE class.
1144const Type *X86_64TargetInfo::getSSETypeAtOffset(const Type *ABIType,
1145 unsigned ABIOffset,
1146 const Type *SourceTy,
1147 unsigned SourceOffset) const {
1148
1149 if (const auto *RTy = dyn_cast<RecordType>(ABIType)) {
1150 if (RTy->isUnion()) {
1151 const Type *ReducedType = reduceUnionForX8664(RTy, TB);
1152 if (ReducedType) {
1153 return getSSETypeAtOffset(ReducedType, ABIOffset, SourceTy,
1154 SourceOffset);
1155 }
1156 }
1157 }
1158
1159 auto Is16bitFpTy = [](const Type *T) {
1162 };
1163
1164 // Get the floating point type at the requested offset
1165 const Type *T0 = getFPTypeAtOffset(ABIType, ABIOffset);
1167 return TB.getFloatType(APFloat::IEEEdouble(), Align(8));
1168
1169 // Calculate remaining source size in bytes
1170 unsigned SourceSize =
1171 (SourceTy->getSizeInBits().getFixedValue() / 8) - SourceOffset;
1172
1173 // Try to get adjacent FP type
1174 const Type *T1 = nullptr;
1175 unsigned T0Size =
1176 alignTo(T0->getSizeInBits().getFixedValue(), T0->getAlignment().value()) /
1177 8;
1178 if (SourceSize > T0Size)
1179 T1 = getFPTypeAtOffset(ABIType, ABIOffset + T0Size);
1180
1181 if (T1 == nullptr) {
1182 if (Is16bitFpTy(T0) && SourceSize > 4)
1183 T1 = getFPTypeAtOffset(ABIType, ABIOffset + 4);
1184
1185 if (T1 == nullptr)
1186 return T0;
1187 }
1188 // Handle vector cases
1191 return TB.getVectorType(T0, ElementCount::getFixed(2), Align(8));
1192
1193 if (Is16bitFpTy(T0) && Is16bitFpTy(T1)) {
1194 const Type *T2 = nullptr;
1195 if (SourceSize > 4)
1196 T2 = getFPTypeAtOffset(ABIType, ABIOffset + 4);
1197 if (!T2)
1198 return TB.getVectorType(T0, ElementCount::getFixed(2), Align(8));
1199 return TB.getVectorType(T0, ElementCount::getFixed(4), Align(8));
1200 }
1201
1202 // Mixed half-float cases
1203 if (Is16bitFpTy(T0) || Is16bitFpTy(T1))
1204 return TB.getVectorType(TB.getFloatType(APFloat::IEEEhalf(), Align(2)),
1206
1207 // Default to double
1208 return TB.getFloatType(APFloat::IEEEdouble(), Align(8));
1209}
1210
1211/// The ABI specifies that a value should be passed in a full vector XMM/YMM
1212/// register. Pick an LLVM IR type that will be passed as a vector register.
1213const Type *X86_64TargetInfo::getByteVectorType(const Type *Ty) const {
1214 // Wrapper structs/arrays that only contain vectors are passed just like
1215 // vectors; strip them off if present.
1216 if (const Type *InnerTy = isSingleElementStruct(Ty))
1217 Ty = InnerTy;
1218
1219 // Handle vector types
1220 if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
1221 // Don't pass vXi128 vectors in their native type, the backend can't
1222 // legalize them.
1223 if (getABICompatInfo().PassInt128VectorsInMem &&
1224 VT->getElementType()->isInteger() &&
1225 cast<IntegerType>(VT->getElementType())->getSizeInBits() == 128) {
1226 unsigned Size = VT->getSizeInBits().getFixedValue();
1227 return TB.getVectorType(TB.getIntegerType(64, Align(8), /*Signed=*/false),
1229 Align(Size / 8));
1230 }
1231 return VT;
1232 }
1233
1234 // Handle fp128
1236 return Ty;
1237
1238 // We couldn't find the preferred IR vector type for 'Ty'.
1239 unsigned Size = Ty->getSizeInBits().getFixedValue();
1240 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid vector size");
1241
1242 return TB.getVectorType(TB.getFloatType(APFloat::IEEEdouble(), Align(8)),
1244}
1245
1246// Returns the single element if this is a single-element struct wrapper
1247const Type *X86_64TargetInfo::isSingleElementStruct(const Type *Ty) const {
1248 const auto *RT = dyn_cast<RecordType>(Ty);
1249 if (!RT)
1250 return nullptr;
1251
1252 if (RT->hasFlexibleArrayMember())
1253 return nullptr;
1254
1255 const Type *Found = nullptr;
1256
1257 for (const auto &Base : RT->getBaseClasses()) {
1258 const Type *BaseTy = Base.FieldType;
1259 auto *BaseRT = dyn_cast<RecordType>(BaseTy);
1260
1261 if (!BaseRT || BaseRT->isEmpty())
1262 continue;
1263
1264 const Type *Elem = isSingleElementStruct(BaseTy);
1265 if (!Elem || Found)
1266 return nullptr;
1267 Found = Elem;
1268 }
1269
1270 for (const auto &FI : RT->getFields()) {
1271 if (FI.isEmpty())
1272 continue;
1273
1274 const Type *FTy = FI.FieldType;
1275
1276 while (auto *AT = dyn_cast<ArrayType>(FTy)) {
1277 if (AT->getNumElements() != 1)
1278 break;
1279 FTy = AT->getElementType();
1280 }
1281
1282 const Type *Elem;
1283 if (auto *InnerRT = dyn_cast<RecordType>(FTy))
1284 Elem = isSingleElementStruct(InnerRT);
1285 else
1286 Elem = FTy;
1287 if (!Elem || Found)
1288 return nullptr;
1289 Found = Elem;
1290 }
1291
1292 if (!Found)
1293 return nullptr;
1294 if (Found->getSizeInBits() != Ty->getSizeInBits())
1295 return nullptr;
1296
1297 return Found;
1298}
1299
1300bool X86_64TargetInfo::isIllegalVectorType(const Type *Ty) const {
1301 if (const auto *VecTy = dyn_cast<VectorType>(Ty)) {
1302 uint64_t Size = VecTy->getSizeInBits().getFixedValue();
1303 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
1304
1305 // Vectors <= 64 bits or > largest supported vector size are illegal
1306 if (Size <= 64 || Size > LargestVector)
1307 return true;
1308
1309 // Check for 128-bit integer element vectors that should be passed in memory
1310 const Type *EltTy = VecTy->getElementType();
1311 if (getABICompatInfo().PassInt128VectorsInMem && EltTy->isInteger()) {
1312 const auto *IntTy = cast<IntegerType>(EltTy);
1313 if (IntTy->getSizeInBits().getFixedValue() == 128)
1314 return true;
1315 }
1316 }
1317 return false;
1318}
1319
1320ArgInfo X86_64TargetInfo::getIndirectResult(const Type *Ty,
1321 unsigned FreeIntRegs) const {
1322 // If this is a scalar LLVM value then assume LLVM will pass it in the right
1323 // place naturally.
1324 //
1325 // This assumption is optimistic, as there could be free registers available
1326 // when we need to pass this argument in memory, and LLVM could try to pass
1327 // the argument in the free register. This does not seem to happen currently,
1328 // but this code would be much safer if we could mark the argument with
1329 // 'onstack'. See PR12193.
1330 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty) &&
1331 !(Ty->isInteger() && cast<IntegerType>(Ty)->isBitInt())) {
1332 return (Ty->isInteger() && isPromotableInteger(cast<IntegerType>(Ty))
1333 ? ArgInfo::getExtend(Ty)
1334 : ArgInfo::getDirect());
1335 }
1336
1337 // Check if this is a record type that needs special handling
1338 if (auto RecordRAA = getRecordArgABI(Ty))
1339 return getNaturalAlignIndirect(Ty, RecordRAA ==
1341
1342 // Compute the byval alignment. We specify the alignment of the byval in all
1343 // cases so that the mid-level optimizer knows the alignment of the byval.
1344 uint64_t AlignVal = std::max<uint64_t>(Ty->getAlignment().value(), 8u);
1345
1346 // Attempt to avoid passing indirect results using byval when possible. This
1347 // is important for good codegen.
1348 //
1349 // We do this by coercing the value into a scalar type which the backend can
1350 // handle naturally (i.e., without using byval).
1351 //
1352 // For simplicity, we currently only do this when we have exhausted all of the
1353 // free integer registers. Doing this when there are free integer registers
1354 // would require more care, as we would have to ensure that the coerced value
1355 // did not claim the unused register. That would require either reording the
1356 // arguments to the function (so that any subsequent inreg values came first),
1357 // or only doing this optimization when there were no following arguments that
1358 // might be inreg.
1359 //
1360 // We currently expect it to be rare (particularly in well written code) for
1361 // arguments to be passed on the stack when there are still free integer
1362 // registers available (this would typically imply large structs being passed
1363 // by value), so this seems like a fair tradeoff for now.
1364 //
1365 // We can revisit this if the backend grows support for 'onstack' parameter
1366 // attributes. See PR12193.
1367 if (FreeIntRegs == 0) {
1368 // Use the storage-container width (like Clang's getTypeSize) so a stack
1369 // _BitInt or illegal vector coerces to the integer covering its storage,
1370 // not its raw iN width.
1372
1373 // If this type fits in an eightbyte, coerce it into the matching integral
1374 // type, which will end up on the stack (with alignment 8).
1375 if (AlignVal == 8 && Size <= 64) {
1376 const Type *IntTy =
1377 TB.getIntegerType(Size, llvm::Align(8), /*Signed=*/false);
1378 return ArgInfo::getDirect(IntTy);
1379 }
1380 }
1381
1382 return ArgInfo::getIndirect(llvm::Align(AlignVal), /*ByVal=*/true);
1383}
1384
1385ArgInfo X86_64TargetInfo::getIndirectReturnResult(const Type *Ty) const {
1386 if (!isAggregateTypeForABI(Ty)) {
1387 // Bit-precise integers are returned indirectly regardless of size.
1388 if (const auto *IntTy = dyn_cast<IntegerType>(Ty)) {
1389 if (IntTy->isBitInt())
1390 return getNaturalAlignIndirect(IntTy, /*ByVal=*/true);
1391 if (isPromotableInteger(IntTy))
1392 return ArgInfo::getExtend(Ty);
1393 }
1394 return ArgInfo::getDirect();
1395 }
1396
1397 return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
1398}
1399
1400void X86_64TargetInfo::computeInfo(FunctionInfo &FI) const {
1401 CallingConv::ID CallingConv = FI.getCallingConvention();
1402
1403 // Only the standard SysV (C) calling convention is classified here. Any other
1404 // convention must be added explicitly once it has been verified against this
1405 // classifier rather than silently taking the SysV path.
1406 switch (CallingConv) {
1407 case CallingConv::C:
1408 break;
1409 default:
1411 "calling convention not supported by the LLVMABI X86_64 classifier");
1412 }
1413
1414 unsigned FreeIntRegs = 6;
1415 unsigned FreeSSERegs = 8;
1416 unsigned NeededInt = 0, NeededSSE = 0;
1417
1419 const Type *RetTy = FI.getReturnType();
1420 FI.getReturnInfo() = classifyReturnType(RetTy);
1421 }
1422
1423 if (FI.getReturnInfo().isIndirect())
1424 --FreeIntRegs;
1425
1426 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
1427
1428 unsigned ArgNo = 0;
1429 for (auto IT = FI.arg_begin(), IE = FI.arg_end(); IT != IE; ++IT, ++ArgNo) {
1430 bool IsNamedArg = ArgNo < NumRequiredArgs;
1431 const Type *ArgTy = IT->ABIType;
1432 NeededInt = 0;
1433 NeededSSE = 0;
1434
1435 ArgInfo AI = classifyArgumentType(ArgTy, FreeIntRegs, NeededInt, NeededSSE,
1436 IsNamedArg);
1437
1438 // AMD64-ABI 3.2.3p3: If there are no registers available for any
1439 // eightbyte of an argument, the whole argument is passed on the
1440 // stack. If registers have already been assigned for some
1441 // eightbytes of such an argument, the assignments get reverted.
1442 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
1443 FreeIntRegs -= NeededInt;
1444 FreeSSERegs -= NeededSSE;
1445 IT->Info = AI;
1446 } else {
1447 // Not enough registers, pass on stack
1448 IT->Info = getIndirectResult(ArgTy, FreeIntRegs);
1449 }
1450 }
1451}
1452
1453std::unique_ptr<TargetInfo>
1455 bool Has64BitPointers, const ABICompatInfo &Compat) {
1456 return std::make_unique<X86_64TargetInfo>(TB, AVXLevel, Has64BitPointers,
1457 Compat);
1458}
1459
1460} // namespace abi
1461} // namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
static cl::opt< ITMode > IT(cl::desc("IT block support"), cl::Hidden, cl::init(DefaultIT), cl::values(clEnumValN(DefaultIT, "arm-default-it", "Generate any type of IT block"), clEnumValN(RestrictedIT, "arm-restrict-it", "Disallow complex IT blocks")))
static LoopDeletionResult merge(LoopDeletionResult A, LoopDeletionResult B)
#define I(x, y, z)
Definition MD5.cpp:57
#define T
#define T1
OptimizedStructLayoutField Field
FunctionLoweringInfo::StatepointRelocationRecord RecordType
Target-specific ABI information and factory functions.
static const fltSemantics & IEEEsingle()
Definition APFloat.h:304
static const fltSemantics & BFloat()
Definition APFloat.h:303
static const fltSemantics & IEEEquad()
Definition APFloat.h:306
static const fltSemantics & IEEEdouble()
Definition APFloat.h:305
static const fltSemantics & x87DoubleExtended()
Definition APFloat.h:326
static const fltSemantics & IEEEhalf()
Definition APFloat.h:302
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:305
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:339
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
Helper class to encapsulate information about how a specific type should be passed to or returned fro...
static ArgInfo getDirect(const Type *T=nullptr, unsigned Offset=0, MaybeAlign Align=std::nullopt)
static ArgInfo getIgnore()
static ArgInfo getExtend(const Type *T)
static ArgInfo getIndirect(Align Align, bool ByVal, unsigned AddrSpace=0, bool Realign=false)
Realign: the caller couldn't guarantee sufficient alignment - the callee must copy the argument to a ...
const fltSemantics * getSemantics() const
Definition Types.h:143
bool isUnion() const
Definition Types.h:285
ArrayRef< FieldInfo > getFields() const
Definition Types.h:308
bool isTransparentUnion() const
Definition Types.h:305
LLVM_ABI ArgInfo getNaturalAlignIndirect(const Type *Ty, bool ByVal=true) const
const ABICompatInfo & getABICompatInfo() const
Definition TargetInfo.h:77
LLVM_ABI bool isPromotableInteger(const IntegerType *IT) const
LLVM_ABI bool maybeCommonClassifyReturnType(FunctionInfo &FI) const
Apply rules for classifying return types that are common to all targets.
LLVM_ABI bool isAggregateTypeForABI(const Type *Ty) const
LLVM_ABI const Type * useFirstFieldIfTransparentUnion(const Type *Ty) const
If Ty is a transparent union, return its first field type; otherwise return Ty unchanged.
LLVM_ABI RecordArgABI getRecordArgABI(const RecordType *RT) const
TypeBuilder manages the lifecycle of ABI types using bump pointer allocation.
Definition Types.h:337
Represents the ABI-specific view of a type in LLVM.
Definition Types.h:44
TypeSize getTypeAllocSize() const
Definition Types.h:71
TypeSize getSizeInBits() const
Definition Types.h:68
Align getAlignment() const
Definition Types.h:69
ElementCount getNumElements() const
Definition Types.h:227
const Type * getElementType() const
Definition Types.h:226
X86_64TargetInfo(TypeBuilder &TypeBuilder, X86AVXABILevel AVXABILevel, bool Has64BitPtrs, const ABICompatInfo &Compat)
Definition X86.cpp:116
bool has64BitPointers() const
Definition X86.cpp:121
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
static constexpr bool isKnownGT(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:223
This class provides various memory handling functions that manipulate MemoryBlock instances.
Definition Memory.h:54
This file defines the type system for the LLVMABI library, which mirrors ABI-relevant aspects of fron...
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ IsUnion
Definition Types.h:258
static uint64_t getClangTypeWidthInBits(const Type *Ty)
Definition X86.cpp:64
static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel)
Definition X86.cpp:24
X86AVXABILevel
The AVX ABI level for X86 targets.
Definition TargetInfo.h:98
static const Type * reduceUnionForX8664(const RecordType *UnionType, TypeBuilder &TB)
Definition X86.cpp:128
static bool bitsContainNoUserData(const Type *Ty, unsigned StartBit, unsigned EndBit)
Definition X86.cpp:932
LLVM_ABI std::unique_ptr< TargetInfo > createX86_64TargetInfo(TypeBuilder &TB, X86AVXABILevel AVXLevel, bool Has64BitPointers, const ABICompatInfo &Compat)
Definition X86.cpp:1454
static uint64_t getClangVectorWidthInBits(const VectorType *VT)
Definition X86.cpp:49
static uint64_t getClangIntegerWidthInBits(const IntegerType *IT)
Definition X86.cpp:40
static bool isFloatTypeWithSemantics(const Type *Ty, const fltSemantics &Semantics)
Helper to check if a floating point type matches specific semantics.
Definition X86.cpp:1134
@ RAA_Indirect
Pass it as a pointer to temporary memory.
Definition TargetInfo.h:37
@ RAA_DirectInMemory
Pass it on the stack using its defined layout.
Definition TargetInfo.h:34
ElementType
The element type of an SRV or UAV resource.
Definition DXILABI.h:68
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
T bit_ceil(T Value)
Returns the smallest integral power of two no smaller than Value if Value is nonzero.
Definition bit.h:362
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:389
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
Flags controlling target-specific ABI compatibility behaviour.
Definition TargetInfo.h:43