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 // A class with a virtual base has a non-trivial copy constructor, so
529 // getRecordArgABI() above returned before we got here.
530 assert(!Base.IsVirtualBase && "Unexpected base class!");
531
532 // Classify this field.
533 //
534 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
535 // single eightbyte, each is classified separately. Each eightbyte gets
536 // initialized to class NO_CLASS.
537 Class FieldLo, FieldHi;
538 uint64_t Offset = OffsetBase + Base.OffsetInBits;
539 classify(Base.FieldType, Offset, FieldLo, FieldHi, IsNamedArg);
540 Lo = merge(Lo, FieldLo);
541 Hi = merge(Hi, FieldHi);
542
543 if (getABICompatInfo().ReturnCXXRecordGreaterThan128InMem &&
544 (Size > 128 &&
545 (Size != Base.FieldType->getSizeInBits().getFixedValue() ||
547 Lo = Memory;
548
549 if (Lo == Memory || Hi == Memory) {
550 postMerge(Size, Lo, Hi);
551 return;
552 }
553 }
554 }
555
556 // Classify the fields one at a time, merging the results.
557
558 bool IsUnion = RT->isUnion() && !getABICompatInfo().Clang11Compat;
559 for (const auto &Field : RT->getFields()) {
560 uint64_t Offset = OffsetBase + Field.OffsetInBits;
561 bool BitField = Field.IsBitField;
562
563 if (BitField && Field.IsUnnamedBitfield)
564 continue;
565
566 if (Size > 128 &&
567 ((!IsUnion &&
568 Size != Field.FieldType->getSizeInBits().getFixedValue()) ||
569 Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
570 Lo = Memory;
571 postMerge(Size, Lo, Hi);
572 return;
573 }
574
575 bool IsInMemory = Offset % (Field.FieldType->getAlignment().value() * 8);
576 if (!BitField && IsInMemory) {
577 Lo = Memory;
578 postMerge(Size, Lo, Hi);
579 return;
580 }
581
582 Class FieldLo, FieldHi;
583
584 if (BitField) {
585 uint64_t BitFieldSize = Field.BitFieldWidth;
586 uint64_t EbLo = Offset / 64;
587 uint64_t EbHi = (Offset + BitFieldSize - 1) / 64;
588
589 if (EbLo) {
590 assert(EbHi == EbLo && "Invalid classification, type > 16 bytes.");
591 FieldLo = NoClass;
592 FieldHi = Integer;
593 } else {
594 FieldLo = Integer;
595 FieldHi = EbHi ? Integer : NoClass;
596 }
597 } else {
598 classify(Field.FieldType, Offset, FieldLo, FieldHi, IsNamedArg);
599 }
600
601 Lo = merge(Lo, FieldLo);
602 Hi = merge(Hi, FieldHi);
603 if (Lo == Memory || Hi == Memory)
604 break;
605 }
606 postMerge(Size, Lo, Hi);
607 return;
608 }
609
610 Lo = Memory;
611 Hi = NoClass;
612}
613
615X86_64TargetInfo::classifyArgumentType(const Type *Ty, unsigned FreeIntRegs,
616 unsigned &NeededInt, unsigned &NeededSSE,
617 bool IsNamedArg, bool IsRegCall) const {
618
620
622 classify(Ty, 0, Lo, Hi, IsNamedArg, IsRegCall);
623
624 // Check some invariants
625 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
626 assert((Hi != SseUp || Lo == Sse) && "Invalid SseUp classification.");
627
628 NeededInt = 0;
629 NeededSSE = 0;
630 const Type *ResType = nullptr;
631
632 switch (Lo) {
633 case NoClass:
634 if (Hi == NoClass)
635 return ArgInfo::getIgnore();
636 // If the low part is just padding, it takes no register, leave ResType
637 // null.
638 assert((Hi == Sse || Hi == Integer || Hi == X87Up) &&
639 "Unknown missing lo part");
640 break;
641
642 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
643 // on the stack.
644 case Memory:
645 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87Up or
646 // COMPLEX_X87, it is passed in memory.
647 case X87:
648 case ComplexX87:
649 if (getRecordArgABI(Ty) == RAA_Indirect)
650 ++NeededInt;
651 return getIndirectResult(Ty, FreeIntRegs);
652
653 case SseUp:
654 case X87Up:
655 llvm_unreachable("Invalid classification for lo word.");
656
657 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
658 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
659 // and %r9 is used.
660 case Integer:
661 ++NeededInt;
662
663 // Pick an 8-byte type based on the preferred type.
664 ResType = getIntegerTypeAtOffset(Ty, 0, Ty, 0);
665
666 // If we have a sign or zero extended integer, make sure to return Extend
667 // so that the parameter gets the right LLVM IR attributes.
668 if (Hi == NoClass && ResType->isInteger()) {
669 if (Ty->isInteger() && isPromotableInteger(cast<IntegerType>(Ty)))
670 return ArgInfo::getExtend(Ty);
671 }
672
673 if (ResType->isInteger() && ResType->getSizeInBits() == 128) {
674 assert(Hi == Integer);
675 ++NeededInt;
676 return ArgInfo::getDirect(ResType);
677 }
678 break;
679
680 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
681 // available SSE register is used, the registers are taken in the
682 // order from %xmm0 to %xmm7.
683 case Sse:
684 ResType = getSSETypeAtOffset(Ty, 0, Ty, 0);
685 ++NeededSSE;
686 break;
687 }
688
689 const Type *HighPart = nullptr;
690 switch (Hi) {
691 // Memory was handled previously, ComplexX87 and X87 should
692 // never occur as hi classes, and X87Up must be preceded by X87,
693 // which is passed in memory.
694 case Memory:
695 case X87:
696 case ComplexX87:
697 llvm_unreachable("Invalid classification for hi word.");
698
699 case NoClass:
700 break;
701
702 case Integer:
703 ++NeededInt;
704 // Pick an 8-byte type based on the preferred type.
705 HighPart = getIntegerTypeAtOffset(Ty, 8, Ty, 8);
706
707 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
708 return ArgInfo::getDirect(HighPart, 8);
709 break;
710
711 // X87Up generally doesn't occur here (long double is passed in
712 // memory), except in situations involving unions.
713 case X87Up:
714 case Sse:
715 ++NeededSSE;
716 HighPart = getSSETypeAtOffset(Ty, 8, Ty, 8);
717
718 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
719 return ArgInfo::getDirect(HighPart, 8);
720 break;
721
722 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
723 // eightbyte is passed in the upper half of the last used SSE
724 // register. This only happens when 128-bit vectors are passed.
725 case SseUp:
726 assert(Lo == Sse && "Unexpected SseUp classification");
727 ResType = getByteVectorType(Ty);
728 break;
729 }
730
731 // If a high part was specified, merge it together with the low part. It is
732 // known to pass in the high eightbyte of the result. We do this by forming a
733 // first class struct aggregate with the high and low part: {low, high}
734 if (HighPart)
735 ResType = createPairType(ResType, HighPart);
736
737 return ArgInfo::getDirect(ResType);
738}
739
740ArgInfo X86_64TargetInfo::classifyReturnType(const Type *RetTy) const {
741 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
742 // classification algorithm.
743
745 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
746
747 // Check some invariants
748 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
749 assert((Hi != SseUp || Lo == Sse) && "Invalid SseUp classification.");
750
751 const Type *ResType = nullptr;
752 switch (Lo) {
753 case NoClass:
754 if (Hi == NoClass)
755 return ArgInfo::getIgnore();
756 // If the low part is just padding, it takes no register, leave ResType
757 // null.
758 assert((Hi == Sse || Hi == Integer || Hi == X87Up) &&
759 "Unknown missing lo part");
760 break;
761 case SseUp:
762 case X87Up:
763 llvm_unreachable("Invalid classification for lo word.");
764
765 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
766 // hidden argument.
767 case Memory:
768 return getIndirectReturnResult(RetTy);
769
770 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
771 // available register of the sequence %rax, %rdx is used.
772 case Integer:
773 ResType = getIntegerTypeAtOffset(RetTy, 0, RetTy, 0);
774 // If we have a sign or zero extended integer, make sure to return Extend
775 // so that the parameter gets the right LLVM IR attributes.
776 if (Hi == NoClass && ResType->isInteger()) {
777 if (const IntegerType *IntTy = dyn_cast<IntegerType>(RetTy)) {
778 if (isPromotableInteger(IntTy))
779 return ArgInfo::getExtend(RetTy);
780 }
781 }
782 if (ResType->isInteger() && ResType->getSizeInBits() == 128) {
783 assert(Hi == Integer);
784 return ArgInfo::getDirect(ResType);
785 }
786 break;
787
788 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
789 // available SSE register of the sequence %xmm0, %xmm1 is used.
790 case Sse:
791 ResType = getSSETypeAtOffset(RetTy, 0, RetTy, 0);
792 break;
793
794 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
795 // returned on the X87 stack in %st0 as 80-bit x87 number.
796 case X87:
797 ResType = TB.getFloatType(APFloat::x87DoubleExtended(), Align(16));
798 break;
799
800 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
801 // part of the value is returned in %st0 and the imaginary part in
802 // %st1.
803 case ComplexX87:
804 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
805 {
806 const Type *X87Type =
807 TB.getFloatType(APFloat::x87DoubleExtended(), Align(16));
808 FieldInfo Fields[] = {FieldInfo(X87Type, 0), FieldInfo(X87Type, 80)};
809 ResType = TB.getRecordType(Fields, TypeSize::getFixed(160), Align(16));
810 }
811 break;
812 }
813
814 const Type *HighPart = nullptr;
815 switch (Hi) {
816 // Memory was handled previously and X87 should
817 // never occur as a hi class.
818 case Memory:
819 case X87:
820 llvm_unreachable("Invalid classification for hi word.");
821
822 case ComplexX87:
823 case NoClass:
824 break;
825
826 case Integer:
827 HighPart = getIntegerTypeAtOffset(RetTy, 8, RetTy, 8);
828 if (Lo == NoClass)
829 return ArgInfo::getDirect(HighPart, 8);
830 break;
831
832 case Sse:
833 HighPart = getSSETypeAtOffset(RetTy, 8, RetTy, 8);
834 if (Lo == NoClass)
835 return ArgInfo::getDirect(HighPart, 8);
836 break;
837
838 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
839 // is passed in the next available eightbyte chunk if the last used
840 // vector register.
841 //
842 // SSEUP should always be preceded by SSE, just widen.
843 case SseUp:
844 assert(Lo == Sse && "Unexpected SseUp classification.");
845 ResType = getByteVectorType(RetTy);
846 break;
847
848 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87Up, the value is
849 // returned together with the previous X87 value in %st0.
850 case X87Up:
851 // If X87Up is preceded by X87, we don't need to do
852 // anything. However, in some cases with unions it may not be
853 // preceded by X87. In such situations we follow gcc and pass the
854 // extra bits in an SSE reg.
855 if (Lo != X87) {
856 HighPart = getSSETypeAtOffset(RetTy, 8, RetTy, 8);
857 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
858 return ArgInfo::getDirect(HighPart, 8);
859 }
860 break;
861 }
862
863 // If a high part was specified, merge it together with the low part. It is
864 // known to pass in the high eightbyte of the result. We do this by forming a
865 // first class struct aggregate with the high and low part: {low, high}
866 if (HighPart)
867 ResType = createPairType(ResType, HighPart);
868
869 return ArgInfo::getDirect(ResType);
870}
871
872/// Given a high and low type that can ideally
873/// be used as elements of a two register pair to pass or return, return a
874/// first class aggregate to represent them. For example, if the low part of
875/// a by-value argument should be passed as i32* and the high part as float,
876/// return {i32*, float}.
877const Type *X86_64TargetInfo::createPairType(const Type *Lo,
878 const Type *Hi) const {
879 // In order to correctly satisfy the ABI, we need to the high part to start
880 // at offset 8. If the high and low parts we inferred are both 4-byte types
881 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
882 // the second element at offset 8. Check for this:
883 unsigned LoSize = (unsigned)Lo->getTypeAllocSize();
884 llvm::Align HiAlign = Hi->getAlignment();
885 unsigned HiStart = alignTo(LoSize, HiAlign);
886
887 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
888
889 // To handle this, we have to increase the size of the low part so that the
890 // second element will start at an 8 byte offset. We can't increase the size
891 // of the second element because it might make us access off the end of the
892 // struct.
893 const Type *AdjustedLo = Lo;
894 if (HiStart != 8) {
895 // There are usually two sorts of types the ABI generation code can produce
896 // for the low part of a pair that aren't 8 bytes in size: half, float or
897 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
898 // NaCl).
899 // Promote these to a larger type.
900 if (Lo->isFloat()) {
901 const FloatType *FT = cast<FloatType>(Lo);
902 if (FT->getSemantics() == &APFloat::IEEEhalf() ||
903 FT->getSemantics() == &APFloat::IEEEsingle() ||
904 FT->getSemantics() == &APFloat::BFloat())
905 AdjustedLo = TB.getFloatType(APFloat::IEEEdouble(), Align(8));
906 }
907 // Promote integers and pointers to i64
908 else if (Lo->isInteger() || Lo->isPointer())
909 AdjustedLo = TB.getIntegerType(64, Align(8), /*Signed=*/false);
910 else
911 assert((Lo->isInteger() || Lo->isPointer()) &&
912 "Invalid/unknown low type in pair");
913 unsigned AdjustedLoSize = AdjustedLo->getSizeInBits().getFixedValue() / 8;
914 HiStart = alignTo(AdjustedLoSize, HiAlign);
915 }
916
917 // Create the pair struct
918 FieldInfo Fields[] = {FieldInfo(AdjustedLo, 0), FieldInfo(Hi, HiStart * 8)};
919
920 // Verify the high part is at offset 8
921 assert((8 * 8) == Fields[1].OffsetInBits &&
922 "High part must be at offset 8 bytes");
923
924 uint64_t PairSizeInBits =
925 Fields[1].OffsetInBits + Hi->getSizeInBits().getFixedValue();
926 return TB.getRecordType(Fields, TypeSize::getFixed(PairSizeInBits), Align(8),
928}
929
930static bool bitsContainNoUserData(const Type *Ty, unsigned StartBit,
931 unsigned EndBit) {
932 // If range is completely beyond type size, it's definitely padding
933 unsigned TySize = Ty->getSizeInBits().getFixedValue();
934 if (TySize <= StartBit)
935 return true;
936
937 // Handle arrays - check each element
938 if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
939 const Type *EltTy = AT->getElementType();
940 unsigned EltSize = EltTy->getSizeInBits().getFixedValue();
941
942 for (unsigned I = 0; I < AT->getNumElements(); ++I) {
943 unsigned EltOffset = I * EltSize;
944 if (EltOffset >= EndBit)
945 break;
946
947 unsigned EltStart = (EltOffset < StartBit) ? StartBit - EltOffset : 0;
948 if (!bitsContainNoUserData(EltTy, EltStart, EndBit - EltOffset))
949 return false;
950 }
951 return true;
952 }
953
954 // Handle records - check all fields and base classes. getUnionType places a
955 // union's members at offset zero, so the field loop covers a union too.
956 if (const RecordType *RT = dyn_cast<RecordType>(Ty)) {
957 // Check base classes first (for C++ records)
958 if (RT->isCXXRecord()) {
959 for (unsigned I = 0; I < RT->getNumBaseClasses(); ++I) {
960 const FieldInfo &Base = RT->getBaseClasses()[I];
961 // This only runs for types being passed in registers, which cannot
962 // have virtual bases.
963 assert(!Base.IsVirtualBase && "Unexpected base class!");
964 if (Base.OffsetInBits >= EndBit)
965 continue;
966
967 unsigned BaseStart =
968 (Base.OffsetInBits < StartBit) ? StartBit - Base.OffsetInBits : 0;
969 if (!bitsContainNoUserData(Base.FieldType, BaseStart,
970 EndBit - Base.OffsetInBits))
971 return false;
972 }
973 }
974
975 for (unsigned I = 0; I < RT->getNumFields(); ++I) {
976 const FieldInfo &Field = RT->getFields()[I];
977 if (Field.OffsetInBits >= EndBit)
978 break;
979
980 unsigned FieldStart =
981 (Field.OffsetInBits < StartBit) ? StartBit - Field.OffsetInBits : 0;
982 if (!bitsContainNoUserData(Field.FieldType, FieldStart,
983 EndBit - Field.OffsetInBits))
984 return false;
985 }
986 return true;
987 }
988
989 // For any other type - assume all bits are user data
990 return false;
991}
992
993const Type *X86_64TargetInfo::getIntegerTypeAtOffset(const Type *ABIType,
994 unsigned ABIOffset,
995 const Type *SourceTy,
996 unsigned SourceOffset,
997 bool InMemory) const {
998
999 const Type *WorkingType = ABIType;
1000 if (InMemory && ABIType->isInteger()) {
1001 const auto *IT = cast<IntegerType>(ABIType);
1002 unsigned OriginalBitWidth = IT->getSizeInBits().getFixedValue();
1003
1004 unsigned WidenedBitWidth = OriginalBitWidth;
1005 if (OriginalBitWidth <= 8) {
1006 WidenedBitWidth = 8;
1007 } else {
1008 WidenedBitWidth = llvm::bit_ceil(OriginalBitWidth);
1009 }
1010
1011 if (WidenedBitWidth != OriginalBitWidth) {
1012 WorkingType = TB.getIntegerType(WidenedBitWidth, ABIType->getAlignment(),
1013 IT->isSigned());
1014 }
1015 }
1016 // If we're dealing with an un-offset ABI type, then it means that we're
1017 // returning an 8-byte unit starting with it. See if we can safely use it.
1018 if (ABIOffset == 0) {
1019 // Pointers and int64's always fill the 8-byte unit. Return WorkingType,
1020 // which is the in-memory-widened type (e.g. a _BitInt(37) field widened to
1021 // i64): returning the raw ABIType here would coerce the eightbyte to the
1022 // narrow iN instead of the storage integer clang uses.
1023 if ((WorkingType->isPointer() && Has64BitPointers) ||
1024 (WorkingType->isInteger() &&
1025 cast<IntegerType>(WorkingType)->getSizeInBits() == 64))
1026 return WorkingType;
1027
1028 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
1029 // goodness in the source type is just tail padding. This is allowed to
1030 // kick in for struct {double,int} on the int, but not on
1031 // struct{double,int,int} because we wouldn't return the second int. We
1032 // have to do this analysis on the source type because we can't depend on
1033 // unions being lowered a specific way etc.
1034 if ((WorkingType->isInteger() &&
1035 (cast<IntegerType>(WorkingType)->getSizeInBits() == 1 ||
1036 cast<IntegerType>(WorkingType)->getSizeInBits() == 8 ||
1037 cast<IntegerType>(WorkingType)->getSizeInBits() == 16 ||
1038 cast<IntegerType>(WorkingType)->getSizeInBits() == 32)) ||
1039 (WorkingType->isPointer() && !Has64BitPointers)) {
1040
1041 unsigned BitWidth = WorkingType->isPointer()
1042 ? 32
1043 : cast<IntegerType>(WorkingType)->getSizeInBits();
1044
1045 if (bitsContainNoUserData(SourceTy, SourceOffset * 8 + BitWidth,
1046 SourceOffset * 8 + 64))
1047 return WorkingType;
1048 }
1049 }
1050
1051 if (const auto *RTy = dyn_cast<RecordType>(ABIType)) {
1052 if (RTy->isUnion()) {
1053 const Type *ReducedType = reduceUnionForX8664(RTy, TB);
1054 if (ReducedType)
1055 return getIntegerTypeAtOffset(ReducedType, ABIOffset, SourceTy,
1056 SourceOffset, true);
1057 }
1058 if (const FieldInfo *Element =
1059 RTy->getElementContainingOffset(ABIOffset * 8)) {
1060
1061 unsigned ElementOffsetBytes = Element->OffsetInBits / 8;
1062 return getIntegerTypeAtOffset(Element->FieldType,
1063 ABIOffset - ElementOffsetBytes, SourceTy,
1064 SourceOffset, true);
1065 }
1066 }
1067
1068 if (const auto *ATy = dyn_cast<ArrayType>(ABIType)) {
1069 const Type *EltTy = ATy->getElementType();
1070 unsigned EltSize = EltTy->getSizeInBits() / 8;
1071 if (EltSize > 0) {
1072 unsigned EltOffset = (ABIOffset / EltSize) * EltSize;
1073 return getIntegerTypeAtOffset(EltTy, ABIOffset - EltOffset, SourceTy,
1074 SourceOffset, true);
1075 }
1076 }
1077
1078 // If we have a 128-bit integer, we can pass it safely using an i128
1079 // so we return that
1080 if (ABIType->isInteger() && ABIType->getSizeInBits() == 128) {
1081 assert(ABIOffset == 0);
1082 return ABIType;
1083 }
1084
1085 unsigned TySizeInBytes =
1086 llvm::divideCeil(SourceTy->getSizeInBits().getFixedValue(), 8);
1087 if (auto *IT = dyn_cast<IntegerType>(SourceTy)) {
1088 if (IT->isBitInt())
1089 TySizeInBytes =
1090 alignTo(SourceTy->getSizeInBits().getFixedValue(), 64) / 8;
1091 }
1092 assert(TySizeInBytes != SourceOffset && "Empty field?");
1093 unsigned AvailableSize = TySizeInBytes - SourceOffset;
1094 return TB.getIntegerType(std::min(AvailableSize, 8U) * 8, Align(1), false);
1095}
1096/// Returns the floating point type at the specified offset within a type, or
1097/// nullptr if no floating point type is found at that offset.
1098const Type *X86_64TargetInfo::getFPTypeAtOffset(const Type *Ty,
1099 unsigned Offset) const {
1100 // Check for direct match at offset 0
1101 if (Offset == 0 && Ty->isFloat())
1102 return Ty;
1103
1104 if (const ComplexType *CT = dyn_cast<ComplexType>(Ty)) {
1105 const Type *ElementType = CT->getElementType();
1106 unsigned ElementSize = ElementType->getSizeInBits().getFixedValue() / 8;
1107
1108 if (Offset == 0 || Offset == ElementSize)
1109 return ElementType;
1110 return nullptr;
1111 }
1112
1113 // Handle struct types by checking each field
1114 if (const RecordType *RT = dyn_cast<RecordType>(Ty)) {
1115 if (const FieldInfo *Element = RT->getElementContainingOffset(Offset * 8)) {
1116 unsigned ElementOffsetBytes = Element->OffsetInBits / 8;
1117 return getFPTypeAtOffset(Element->FieldType, Offset - ElementOffsetBytes);
1118 }
1119 }
1120
1121 // Handle array types
1122 if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
1123 const Type *EltTy = AT->getElementType();
1124 unsigned EltSize = EltTy->getSizeInBits() / 8;
1125 unsigned EltIndex = Offset / EltSize;
1126
1127 return getFPTypeAtOffset(EltTy, Offset - (EltIndex * EltSize));
1128 }
1129
1130 // No floating point type found at this offset
1131 return nullptr;
1132}
1133
1134/// Helper to check if a floating point type matches specific semantics
1135static bool isFloatTypeWithSemantics(const Type *Ty,
1136 const fltSemantics &Semantics) {
1137 if (!Ty->isFloat())
1138 return false;
1139 const FloatType *FT = cast<FloatType>(Ty);
1140 return FT->getSemantics() == &Semantics;
1141}
1142
1143/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
1144/// low 8 bytes of an XMM register, corresponding to the SSE class.
1145const Type *X86_64TargetInfo::getSSETypeAtOffset(const Type *ABIType,
1146 unsigned ABIOffset,
1147 const Type *SourceTy,
1148 unsigned SourceOffset) const {
1149
1150 if (const auto *RTy = dyn_cast<RecordType>(ABIType)) {
1151 if (RTy->isUnion()) {
1152 const Type *ReducedType = reduceUnionForX8664(RTy, TB);
1153 if (ReducedType) {
1154 return getSSETypeAtOffset(ReducedType, ABIOffset, SourceTy,
1155 SourceOffset);
1156 }
1157 }
1158 }
1159
1160 auto Is16bitFpTy = [](const Type *T) {
1163 };
1164
1165 // Get the floating point type at the requested offset
1166 const Type *T0 = getFPTypeAtOffset(ABIType, ABIOffset);
1168 return TB.getFloatType(APFloat::IEEEdouble(), Align(8));
1169
1170 // Calculate remaining source size in bytes
1171 unsigned SourceSize =
1172 (SourceTy->getSizeInBits().getFixedValue() / 8) - SourceOffset;
1173
1174 // Try to get adjacent FP type
1175 const Type *T1 = nullptr;
1176 unsigned T0Size =
1177 alignTo(T0->getSizeInBits().getFixedValue(), T0->getAlignment().value()) /
1178 8;
1179 if (SourceSize > T0Size)
1180 T1 = getFPTypeAtOffset(ABIType, ABIOffset + T0Size);
1181
1182 if (T1 == nullptr) {
1183 if (Is16bitFpTy(T0) && SourceSize > 4)
1184 T1 = getFPTypeAtOffset(ABIType, ABIOffset + 4);
1185
1186 if (T1 == nullptr)
1187 return T0;
1188 }
1189 // Handle vector cases
1192 return TB.getVectorType(T0, ElementCount::getFixed(2), Align(8));
1193
1194 if (Is16bitFpTy(T0) && Is16bitFpTy(T1)) {
1195 const Type *T2 = nullptr;
1196 if (SourceSize > 4)
1197 T2 = getFPTypeAtOffset(ABIType, ABIOffset + 4);
1198 if (!T2)
1199 return TB.getVectorType(T0, ElementCount::getFixed(2), Align(8));
1200 return TB.getVectorType(T0, ElementCount::getFixed(4), Align(8));
1201 }
1202
1203 // Mixed half-float cases
1204 if (Is16bitFpTy(T0) || Is16bitFpTy(T1))
1205 return TB.getVectorType(TB.getFloatType(APFloat::IEEEhalf(), Align(2)),
1207
1208 // Default to double
1209 return TB.getFloatType(APFloat::IEEEdouble(), Align(8));
1210}
1211
1212/// The ABI specifies that a value should be passed in a full vector XMM/YMM
1213/// register. Pick an LLVM IR type that will be passed as a vector register.
1214const Type *X86_64TargetInfo::getByteVectorType(const Type *Ty) const {
1215 // Wrapper structs/arrays that only contain vectors are passed just like
1216 // vectors; strip them off if present.
1217 if (const Type *InnerTy = isSingleElementStruct(Ty))
1218 Ty = InnerTy;
1219
1220 // Handle vector types
1221 if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
1222 // Don't pass vXi128 vectors in their native type, the backend can't
1223 // legalize them.
1224 if (getABICompatInfo().PassInt128VectorsInMem &&
1225 VT->getElementType()->isInteger() &&
1226 cast<IntegerType>(VT->getElementType())->getSizeInBits() == 128) {
1227 unsigned Size = VT->getSizeInBits().getFixedValue();
1228 return TB.getVectorType(TB.getIntegerType(64, Align(8), /*Signed=*/false),
1230 Align(Size / 8));
1231 }
1232 return VT;
1233 }
1234
1235 // Handle fp128
1237 return Ty;
1238
1239 // We couldn't find the preferred IR vector type for 'Ty'.
1240 unsigned Size = Ty->getSizeInBits().getFixedValue();
1241 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid vector size");
1242
1243 return TB.getVectorType(TB.getFloatType(APFloat::IEEEdouble(), Align(8)),
1245}
1246
1247// Returns the single element if this is a single-element struct wrapper
1248const Type *X86_64TargetInfo::isSingleElementStruct(const Type *Ty) const {
1249 const auto *RT = dyn_cast<RecordType>(Ty);
1250 if (!RT)
1251 return nullptr;
1252
1253 if (RT->hasFlexibleArrayMember())
1254 return nullptr;
1255
1256 const Type *Found = nullptr;
1257
1258 for (const auto &Base : RT->getBaseClasses()) {
1259 const Type *BaseTy = Base.FieldType;
1260 auto *BaseRT = dyn_cast<RecordType>(BaseTy);
1261
1262 if (!BaseRT || BaseRT->isEmpty())
1263 continue;
1264
1265 const Type *Elem = isSingleElementStruct(BaseTy);
1266 if (!Elem || Found)
1267 return nullptr;
1268 Found = Elem;
1269 }
1270
1271 for (const auto &FI : RT->getFields()) {
1272 if (FI.isEmpty())
1273 continue;
1274
1275 const Type *FTy = FI.FieldType;
1276
1277 while (auto *AT = dyn_cast<ArrayType>(FTy)) {
1278 if (AT->getNumElements() != 1)
1279 break;
1280 FTy = AT->getElementType();
1281 }
1282
1283 const Type *Elem;
1284 if (auto *InnerRT = dyn_cast<RecordType>(FTy))
1285 Elem = isSingleElementStruct(InnerRT);
1286 else
1287 Elem = FTy;
1288 if (!Elem || Found)
1289 return nullptr;
1290 Found = Elem;
1291 }
1292
1293 if (!Found)
1294 return nullptr;
1295 if (Found->getSizeInBits() != Ty->getSizeInBits())
1296 return nullptr;
1297
1298 return Found;
1299}
1300
1301bool X86_64TargetInfo::isIllegalVectorType(const Type *Ty) const {
1302 if (const auto *VecTy = dyn_cast<VectorType>(Ty)) {
1303 uint64_t Size = VecTy->getSizeInBits().getFixedValue();
1304 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
1305
1306 // Vectors <= 64 bits or > largest supported vector size are illegal
1307 if (Size <= 64 || Size > LargestVector)
1308 return true;
1309
1310 // Check for 128-bit integer element vectors that should be passed in memory
1311 const Type *EltTy = VecTy->getElementType();
1312 if (getABICompatInfo().PassInt128VectorsInMem && EltTy->isInteger()) {
1313 const auto *IntTy = cast<IntegerType>(EltTy);
1314 if (IntTy->getSizeInBits().getFixedValue() == 128)
1315 return true;
1316 }
1317 }
1318 return false;
1319}
1320
1321ArgInfo X86_64TargetInfo::getIndirectResult(const Type *Ty,
1322 unsigned FreeIntRegs) const {
1323 // If this is a scalar LLVM value then assume LLVM will pass it in the right
1324 // place naturally.
1325 //
1326 // This assumption is optimistic, as there could be free registers available
1327 // when we need to pass this argument in memory, and LLVM could try to pass
1328 // the argument in the free register. This does not seem to happen currently,
1329 // but this code would be much safer if we could mark the argument with
1330 // 'onstack'. See PR12193.
1331 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty) &&
1332 !(Ty->isInteger() && cast<IntegerType>(Ty)->isBitInt())) {
1333 return (Ty->isInteger() && isPromotableInteger(cast<IntegerType>(Ty))
1334 ? ArgInfo::getExtend(Ty)
1335 : ArgInfo::getDirect());
1336 }
1337
1338 // Check if this is a record type that needs special handling
1339 if (auto RecordRAA = getRecordArgABI(Ty))
1340 return getNaturalAlignIndirect(Ty, RecordRAA ==
1342
1343 // Compute the byval alignment. We specify the alignment of the byval in all
1344 // cases so that the mid-level optimizer knows the alignment of the byval.
1345 uint64_t AlignVal = std::max<uint64_t>(Ty->getAlignment().value(), 8u);
1346
1347 // Attempt to avoid passing indirect results using byval when possible. This
1348 // is important for good codegen.
1349 //
1350 // We do this by coercing the value into a scalar type which the backend can
1351 // handle naturally (i.e., without using byval).
1352 //
1353 // For simplicity, we currently only do this when we have exhausted all of the
1354 // free integer registers. Doing this when there are free integer registers
1355 // would require more care, as we would have to ensure that the coerced value
1356 // did not claim the unused register. That would require either reording the
1357 // arguments to the function (so that any subsequent inreg values came first),
1358 // or only doing this optimization when there were no following arguments that
1359 // might be inreg.
1360 //
1361 // We currently expect it to be rare (particularly in well written code) for
1362 // arguments to be passed on the stack when there are still free integer
1363 // registers available (this would typically imply large structs being passed
1364 // by value), so this seems like a fair tradeoff for now.
1365 //
1366 // We can revisit this if the backend grows support for 'onstack' parameter
1367 // attributes. See PR12193.
1368 if (FreeIntRegs == 0) {
1369 // Use the storage-container width (like Clang's getTypeSize) so a stack
1370 // _BitInt or illegal vector coerces to the integer covering its storage,
1371 // not its raw iN width.
1373
1374 // If this type fits in an eightbyte, coerce it into the matching integral
1375 // type, which will end up on the stack (with alignment 8).
1376 if (AlignVal == 8 && Size <= 64) {
1377 const Type *IntTy =
1378 TB.getIntegerType(Size, llvm::Align(8), /*Signed=*/false);
1379 return ArgInfo::getDirect(IntTy);
1380 }
1381 }
1382
1383 return ArgInfo::getIndirect(llvm::Align(AlignVal), /*ByVal=*/true);
1384}
1385
1386ArgInfo X86_64TargetInfo::getIndirectReturnResult(const Type *Ty) const {
1387 if (!isAggregateTypeForABI(Ty)) {
1388 // Bit-precise integers are returned indirectly regardless of size.
1389 if (const auto *IntTy = dyn_cast<IntegerType>(Ty)) {
1390 if (IntTy->isBitInt())
1391 return getNaturalAlignIndirect(IntTy, /*ByVal=*/true);
1392 if (isPromotableInteger(IntTy))
1393 return ArgInfo::getExtend(Ty);
1394 }
1395 return ArgInfo::getDirect();
1396 }
1397
1398 return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
1399}
1400
1401void X86_64TargetInfo::computeInfo(FunctionInfo &FI) const {
1402 CallingConv::ID CallingConv = FI.getCallingConvention();
1403
1404 // Only the standard SysV (C) calling convention is classified here. Any other
1405 // convention must be added explicitly once it has been verified against this
1406 // classifier rather than silently taking the SysV path.
1407 switch (CallingConv) {
1408 case CallingConv::C:
1409 break;
1410 default:
1412 "calling convention not supported by the LLVMABI X86_64 classifier");
1413 }
1414
1415 unsigned FreeIntRegs = 6;
1416 unsigned FreeSSERegs = 8;
1417 unsigned NeededInt = 0, NeededSSE = 0;
1418
1420 const Type *RetTy = FI.getReturnType();
1421 FI.getReturnInfo() = classifyReturnType(RetTy);
1422 }
1423
1424 if (FI.getReturnInfo().isIndirect())
1425 --FreeIntRegs;
1426
1427 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
1428
1429 unsigned ArgNo = 0;
1430 for (auto IT = FI.arg_begin(), IE = FI.arg_end(); IT != IE; ++IT, ++ArgNo) {
1431 bool IsNamedArg = ArgNo < NumRequiredArgs;
1432 const Type *ArgTy = IT->ABIType;
1433 NeededInt = 0;
1434 NeededSSE = 0;
1435
1436 ArgInfo AI = classifyArgumentType(ArgTy, FreeIntRegs, NeededInt, NeededSSE,
1437 IsNamedArg);
1438
1439 // AMD64-ABI 3.2.3p3: If there are no registers available for any
1440 // eightbyte of an argument, the whole argument is passed on the
1441 // stack. If registers have already been assigned for some
1442 // eightbytes of such an argument, the assignments get reverted.
1443 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
1444 FreeIntRegs -= NeededInt;
1445 FreeSSERegs -= NeededSSE;
1446 IT->Info = AI;
1447 } else {
1448 // Not enough registers, pass on stack
1449 IT->Info = getIndirectResult(ArgTy, FreeIntRegs);
1450 }
1451 }
1452}
1453
1454std::unique_ptr<TargetInfo>
1456 bool Has64BitPointers, const ABICompatInfo &Compat) {
1457 return std::make_unique<X86_64TargetInfo>(TB, AVXLevel, Has64BitPointers,
1458 Compat);
1459}
1460
1461} // namespace abi
1462} // 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:284
ArrayRef< FieldInfo > getFields() const
Definition Types.h:307
bool isTransparentUnion() const
Definition Types.h:304
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:345
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:257
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:128
static bool bitsContainNoUserData(const Type *Ty, unsigned StartBit, unsigned EndBit)
Definition X86.cpp:930
LLVM_ABI std::unique_ptr< TargetInfo > createX86_64TargetInfo(TypeBuilder &TB, X86AVXABILevel AVXLevel, bool Has64BitPointers, const ABICompatInfo &Compat)
Definition X86.cpp:1455
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:1135
@ 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