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