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