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
9#include "ABIInfoImpl.h"
10#include "TargetInfo.h"
11#include "clang/Basic/DiagnosticFrontend.h"
12#include "clang/Basic/SourceLocation.h"
13#include "llvm/ADT/SmallBitVector.h"
14
15using namespace clang;
16using namespace clang::CodeGen;
17
18namespace {
19
20/// IsX86_MMXType - Return true if this is an MMX type.
21bool IsX86_MMXType(llvm::Type *IRType) {
22 // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
23 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
24 cast<llvm::VectorType>(Val: IRType)->getElementType()->isIntegerTy() &&
25 IRType->getScalarSizeInBits() != 64;
26}
27
28static llvm::Type *X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
29 StringRef Constraint,
30 llvm::Type *Ty) {
31 bool IsMMXCons = llvm::StringSwitch<bool>(Constraint)
32 .Cases(CaseStrings: {"y", "&y", "^Ym"}, Value: true)
33 .Default(Value: false);
34 if (IsMMXCons && Ty->isVectorTy() &&
35 cast<llvm::VectorType>(Val: Ty)->getPrimitiveSizeInBits().getFixedValue() !=
36 64)
37 return nullptr; // Invalid MMX constraint
38
39 if (Constraint == "k") {
40 llvm::Type *Int1Ty = llvm::Type::getInt1Ty(C&: CGF.getLLVMContext());
41 return llvm::FixedVectorType::get(ElementType: Int1Ty, NumElts: Ty->getScalarSizeInBits());
42 }
43
44 // No operation needed
45 return Ty;
46}
47
48/// Returns true if this type can be passed in SSE registers with the
49/// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
50static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
51 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
52 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) {
53 if (BT->getKind() == BuiltinType::LongDouble) {
54 if (&Context.getTargetInfo().getLongDoubleFormat() ==
55 &llvm::APFloat::x87DoubleExtended())
56 return false;
57 }
58 return true;
59 }
60 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
61 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
62 // registers specially.
63 unsigned VecSize = Context.getTypeSize(T: VT);
64 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
65 return true;
66 }
67 return false;
68}
69
70/// Returns true if this aggregate is small enough to be passed in SSE registers
71/// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
72static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
73 return NumMembers <= 4;
74}
75
76/// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
77static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
78 auto AI = ABIArgInfo::getDirect(T);
79 AI.setInReg(true);
80 AI.setCanBeFlattened(false);
81 return AI;
82}
83
84//===----------------------------------------------------------------------===//
85// X86-32 ABI Implementation
86//===----------------------------------------------------------------------===//
87
88/// Similar to llvm::CCState, but for Clang.
89struct CCState {
90 CCState(CGFunctionInfo &FI)
91 : IsPreassigned(FI.arg_size()), CC(FI.getCallingConvention()),
92 Required(FI.getRequiredArgs()), IsDelegateCall(FI.isDelegateCall()) {}
93
94 llvm::SmallBitVector IsPreassigned;
95 unsigned CC = CallingConv::CC_C;
96 unsigned FreeRegs = 0;
97 unsigned FreeSSERegs = 0;
98 RequiredArgs Required;
99 bool IsDelegateCall = false;
100};
101
102/// X86_32ABIInfo - The X86-32 ABI information.
103class X86_32ABIInfo : public ABIInfo {
104 enum Class {
105 Integer,
106 Float
107 };
108
109 static const unsigned MinABIStackAlignInBytes = 4;
110
111 bool IsDarwinVectorABI;
112 bool IsRetSmallStructInRegABI;
113 bool IsWin32StructABI;
114 bool IsSoftFloatABI;
115 bool IsMCUABI;
116 bool IsLinuxABI;
117 unsigned DefaultNumRegisterParameters;
118
119 static bool isRegisterSize(unsigned Size) {
120 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
121 }
122
123 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
124 // FIXME: Assumes vectorcall is in use.
125 return isX86VectorTypeForVectorCall(Context&: getContext(), Ty);
126 }
127
128 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
129 uint64_t NumMembers) const override {
130 // FIXME: Assumes vectorcall is in use.
131 return isX86VectorCallAggregateSmallEnough(NumMembers);
132 }
133
134 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
135
136 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
137 /// such that the argument will be passed in memory.
138 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
139
140 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
141
142 /// Return the alignment to use for the given type on the stack.
143 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
144
145 Class classify(QualType Ty) const;
146 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
147 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State,
148 unsigned ArgIndex) const;
149
150 /// Updates the number of available free registers, returns
151 /// true if any registers were allocated.
152 bool updateFreeRegs(QualType Ty, CCState &State) const;
153
154 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
155 bool &NeedsPadding) const;
156 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
157
158 bool canExpandIndirectArgument(QualType Ty) const;
159
160 /// Rewrite the function info so that all memory arguments use
161 /// inalloca.
162 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
163
164 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
165 CharUnits &StackOffset, ABIArgInfo &Info,
166 QualType Type) const;
167 void runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const;
168
169public:
170
171 void computeInfo(CGFunctionInfo &FI) const override;
172 RValue EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
173 AggValueSlot Slot) const override;
174
175 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
176 bool RetSmallStructInRegABI, bool Win32StructABI,
177 unsigned NumRegisterParameters, bool SoftFloatABI)
178 : ABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
179 IsRetSmallStructInRegABI(RetSmallStructInRegABI),
180 IsWin32StructABI(Win32StructABI), IsSoftFloatABI(SoftFloatABI),
181 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
182 IsLinuxABI(CGT.getTarget().getTriple().isOSLinux() ||
183 CGT.getTarget().getTriple().isOSCygMing()),
184 DefaultNumRegisterParameters(NumRegisterParameters) {}
185};
186
187class X86_32SwiftABIInfo : public SwiftABIInfo {
188public:
189 explicit X86_32SwiftABIInfo(CodeGenTypes &CGT)
190 : SwiftABIInfo(CGT, /*SwiftErrorInRegister=*/false) {}
191
192 bool shouldPassIndirectly(ArrayRef<llvm::Type *> ComponentTys,
193 bool AsReturnValue) const override {
194 // LLVM's x86-32 lowering currently only assigns up to three
195 // integer registers and three fp registers. Oddly, it'll use up to
196 // four vector registers for vectors, but those can overlap with the
197 // scalar registers.
198 return occupiesMoreThan(scalarTypes: ComponentTys, /*total=*/maxAllRegisters: 3);
199 }
200};
201
202class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
203public:
204 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
205 bool RetSmallStructInRegABI, bool Win32StructABI,
206 unsigned NumRegisterParameters, bool SoftFloatABI)
207 : TargetCodeGenInfo(std::make_unique<X86_32ABIInfo>(
208 args&: CGT, args&: DarwinVectorABI, args&: RetSmallStructInRegABI, args&: Win32StructABI,
209 args&: NumRegisterParameters, args&: SoftFloatABI)) {
210 SwiftInfo = std::make_unique<X86_32SwiftABIInfo>(args&: CGT);
211 }
212
213 static bool isStructReturnInRegABI(
214 const llvm::Triple &Triple, const CodeGenOptions &Opts);
215
216 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
217 CodeGen::CodeGenModule &CGM) const override;
218
219 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
220 // Darwin uses different dwarf register numbers for EH.
221 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
222 return 4;
223 }
224
225 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
226 llvm::Value *Address) const override;
227
228 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
229 StringRef Constraint,
230 llvm::Type* Ty) const override {
231 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
232 }
233
234 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
235 std::string &Constraints,
236 std::vector<llvm::Type *> &ResultRegTypes,
237 std::vector<llvm::Type *> &ResultTruncRegTypes,
238 std::vector<LValue> &ResultRegDests,
239 std::string &AsmString,
240 unsigned NumOutputs) const override;
241
242 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
243 return "movl\t%ebp, %ebp"
244 "\t\t// marker for objc_retainAutoreleaseReturnValue";
245 }
246};
247
248}
249
250/// Rewrite input constraint references after adding some output constraints.
251/// In the case where there is one output and one input and we add one output,
252/// we need to replace all operand references greater than or equal to 1:
253/// mov $0, $1
254/// mov eax, $1
255/// The result will be:
256/// mov $0, $2
257/// mov eax, $2
258static void rewriteInputConstraintReferences(unsigned FirstIn,
259 unsigned NumNewOuts,
260 std::string &AsmString) {
261 std::string Buf;
262 llvm::raw_string_ostream OS(Buf);
263 size_t Pos = 0;
264 while (Pos < AsmString.size()) {
265 size_t DollarStart = AsmString.find(c: '$', pos: Pos);
266 if (DollarStart == std::string::npos)
267 DollarStart = AsmString.size();
268 size_t DollarEnd = AsmString.find_first_not_of(c: '$', pos: DollarStart);
269 if (DollarEnd == std::string::npos)
270 DollarEnd = AsmString.size();
271 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
272 Pos = DollarEnd;
273 size_t NumDollars = DollarEnd - DollarStart;
274 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
275 // We have an operand reference.
276 size_t DigitStart = Pos;
277 if (AsmString[DigitStart] == '{') {
278 OS << '{';
279 ++DigitStart;
280 }
281 size_t DigitEnd = AsmString.find_first_not_of(s: "0123456789", pos: DigitStart);
282 if (DigitEnd == std::string::npos)
283 DigitEnd = AsmString.size();
284 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
285 unsigned OperandIndex;
286 if (!OperandStr.getAsInteger(Radix: 10, Result&: OperandIndex)) {
287 if (OperandIndex >= FirstIn)
288 OperandIndex += NumNewOuts;
289 OS << OperandIndex;
290 } else {
291 OS << OperandStr;
292 }
293 Pos = DigitEnd;
294 }
295 }
296 AsmString = std::move(Buf);
297}
298
299/// Add output constraints for EAX:EDX because they are return registers.
300void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
301 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
302 std::vector<llvm::Type *> &ResultRegTypes,
303 std::vector<llvm::Type *> &ResultTruncRegTypes,
304 std::vector<LValue> &ResultRegDests, std::string &AsmString,
305 unsigned NumOutputs) const {
306 uint64_t RetWidth = CGF.getContext().getTypeSize(T: ReturnSlot.getType());
307
308 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
309 // larger.
310 if (!Constraints.empty())
311 Constraints += ',';
312 if (RetWidth <= 32) {
313 Constraints += "={eax}";
314 ResultRegTypes.push_back(x: CGF.Int32Ty);
315 } else {
316 // Use the 'A' constraint for EAX:EDX.
317 Constraints += "=A";
318 ResultRegTypes.push_back(x: CGF.Int64Ty);
319 }
320
321 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
322 llvm::Type *CoerceTy = llvm::IntegerType::get(C&: CGF.getLLVMContext(), NumBits: RetWidth);
323 ResultTruncRegTypes.push_back(x: CoerceTy);
324
325 // Coerce the integer by bitcasting the return slot pointer.
326 ReturnSlot.setAddress(ReturnSlot.getAddress().withElementType(ElemTy: CoerceTy));
327 ResultRegDests.push_back(x: ReturnSlot);
328
329 rewriteInputConstraintReferences(FirstIn: NumOutputs, NumNewOuts: 1, AsmString);
330}
331
332/// shouldReturnTypeInRegister - Determine if the given type should be
333/// returned in a register (for the Darwin and MCU ABI).
334bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
335 ASTContext &Context) const {
336 uint64_t Size = Context.getTypeSize(T: Ty);
337
338 // For i386, type must be register sized.
339 // For the MCU ABI, it only needs to be <= 8-byte
340 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
341 return false;
342
343 if (Ty->isVectorType()) {
344 // 64- and 128- bit vectors inside structures are not returned in
345 // registers.
346 if (Size == 64 || Size == 128)
347 return false;
348
349 return true;
350 }
351
352 // If this is a builtin, pointer, enum, complex type, member pointer, or
353 // member function pointer it is ok.
354 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
355 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
356 Ty->isBlockPointerType() || Ty->isMemberPointerType())
357 return true;
358
359 // Arrays are treated like records.
360 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T: Ty))
361 return shouldReturnTypeInRegister(Ty: AT->getElementType(), Context);
362
363 // Otherwise, it must be a record type.
364 const auto *RD = Ty->getAsRecordDecl();
365 if (!RD)
366 return false;
367
368 // FIXME: Traverse bases here too.
369
370 // Structure types are passed in register if all fields would be
371 // passed in a register.
372 for (const auto *FD : RD->fields()) {
373 // Empty fields are ignored.
374 if (isEmptyField(Context, FD, AllowArrays: true))
375 continue;
376
377 // Check fields recursively.
378 if (!shouldReturnTypeInRegister(Ty: FD->getType(), Context))
379 return false;
380 }
381 return true;
382}
383
384static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
385 // Treat complex types as the element type.
386 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
387 Ty = CTy->getElementType();
388
389 // Check for a type which we know has a simple scalar argument-passing
390 // convention without any padding. (We're specifically looking for 32
391 // and 64-bit integer and integer-equivalents, float, and double.)
392 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
393 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
394 return false;
395
396 uint64_t Size = Context.getTypeSize(T: Ty);
397 return Size == 32 || Size == 64;
398}
399
400static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
401 uint64_t &Size) {
402 for (const auto *FD : RD->fields()) {
403 // Scalar arguments on the stack get 4 byte alignment on x86. If the
404 // argument is smaller than 32-bits, expanding the struct will create
405 // alignment padding.
406 if (!is32Or64BitBasicType(Ty: FD->getType(), Context))
407 return false;
408
409 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
410 // how to expand them yet, and the predicate for telling if a bitfield still
411 // counts as "basic" is more complicated than what we were doing previously.
412 if (FD->isBitField())
413 return false;
414
415 Size += Context.getTypeSize(T: FD->getType());
416 }
417 return true;
418}
419
420static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
421 uint64_t &Size) {
422 // Don't do this if there are any non-empty bases.
423 for (const CXXBaseSpecifier &Base : RD->bases()) {
424 if (!addBaseAndFieldSizes(Context, RD: Base.getType()->getAsCXXRecordDecl(),
425 Size))
426 return false;
427 }
428 if (!addFieldSizes(Context, RD, Size))
429 return false;
430 return true;
431}
432
433/// Test whether an argument type which is to be passed indirectly (on the
434/// stack) would have the equivalent layout if it was expanded into separate
435/// arguments. If so, we prefer to do the latter to avoid inhibiting
436/// optimizations.
437bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
438 // We can only expand structure types.
439 const RecordDecl *RD = Ty->getAsRecordDecl();
440 if (!RD)
441 return false;
442 uint64_t Size = 0;
443 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
444 if (!IsWin32StructABI) {
445 // On non-Windows, we have to conservatively match our old bitcode
446 // prototypes in order to be ABI-compatible at the bitcode level.
447 if (!CXXRD->isCLike())
448 return false;
449 } else {
450 // Don't do this for dynamic classes.
451 if (CXXRD->isDynamicClass())
452 return false;
453 }
454 if (!addBaseAndFieldSizes(Context&: getContext(), RD: CXXRD, Size))
455 return false;
456 } else {
457 if (!addFieldSizes(Context&: getContext(), RD, Size))
458 return false;
459 }
460
461 // We can do this if there was no alignment padding.
462 return Size == getContext().getTypeSize(T: Ty);
463}
464
465ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
466 // If the return value is indirect, then the hidden argument is consuming one
467 // integer register.
468 if (State.CC != llvm::CallingConv::X86_FastCall &&
469 State.CC != llvm::CallingConv::X86_VectorCall && State.FreeRegs) {
470 --State.FreeRegs;
471 if (!IsMCUABI)
472 return getNaturalAlignIndirectInReg(Ty: RetTy);
473 }
474 return getNaturalAlignIndirect(
475 Ty: RetTy, /*AddrSpace=*/getDataLayout().getAllocaAddrSpace(),
476 /*ByVal=*/false);
477}
478
479ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
480 CCState &State) const {
481 if (RetTy->isVoidType())
482 return ABIArgInfo::getIgnore();
483
484 const Type *Base = nullptr;
485 uint64_t NumElts = 0;
486 if ((State.CC == llvm::CallingConv::X86_VectorCall ||
487 State.CC == llvm::CallingConv::X86_RegCall) &&
488 isHomogeneousAggregate(Ty: RetTy, Base, Members&: NumElts)) {
489 // The LLVM struct type for such an aggregate should lower properly.
490 return ABIArgInfo::getDirect();
491 }
492
493 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
494 // On Darwin, some vectors are returned in registers.
495 if (IsDarwinVectorABI) {
496 uint64_t Size = getContext().getTypeSize(T: RetTy);
497
498 // 128-bit vectors are a special case; they are returned in
499 // registers and we need to make sure to pick a type the LLVM
500 // backend will like.
501 if (Size == 128)
502 return ABIArgInfo::getDirect(T: llvm::FixedVectorType::get(
503 ElementType: llvm::Type::getInt64Ty(C&: getVMContext()), NumElts: 2));
504
505 // Always return in register if it fits in a general purpose
506 // register, or if it is 64 bits and has a single element.
507 if ((Size == 8 || Size == 16 || Size == 32) ||
508 (Size == 64 && VT->getNumElements() == 1))
509 return ABIArgInfo::getDirect(T: llvm::IntegerType::get(C&: getVMContext(),
510 NumBits: Size));
511
512 return getIndirectReturnResult(RetTy, State);
513 }
514
515 return ABIArgInfo::getDirect();
516 }
517
518 if (isAggregateTypeForABI(T: RetTy)) {
519 if (const auto *RD = RetTy->getAsRecordDecl();
520 RD && RD->hasFlexibleArrayMember())
521 // Structures with flexible arrays are always indirect.
522 return getIndirectReturnResult(RetTy, State);
523
524 // If specified, structs and unions are always indirect.
525 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
526 return getIndirectReturnResult(RetTy, State);
527
528 // Ignore empty structs/unions.
529 if (isEmptyRecord(Context&: getContext(), T: RetTy, AllowArrays: true))
530 return ABIArgInfo::getIgnore();
531
532 // Return complex of _Float16 as <2 x half> so the backend will use xmm0.
533 if (const ComplexType *CT = RetTy->getAs<ComplexType>()) {
534 QualType ET = getContext().getCanonicalType(T: CT->getElementType());
535 if (ET->isFloat16Type())
536 return ABIArgInfo::getDirect(T: llvm::FixedVectorType::get(
537 ElementType: llvm::Type::getHalfTy(C&: getVMContext()), NumElts: 2));
538 }
539
540 // Small structures which are register sized are generally returned
541 // in a register.
542 if (shouldReturnTypeInRegister(Ty: RetTy, Context&: getContext())) {
543 uint64_t Size = getContext().getTypeSize(T: RetTy);
544
545 // As a special-case, if the struct is a "single-element" struct, and
546 // the field is of type "float" or "double", return it in a
547 // floating-point register. (MSVC does not apply this special case.)
548 // We apply a similar transformation for pointer types to improve the
549 // quality of the generated IR.
550 if (const Type *SeltTy = isSingleElementStruct(T: RetTy, Context&: getContext()))
551 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
552 || SeltTy->hasPointerRepresentation())
553 return ABIArgInfo::getDirect(T: CGT.ConvertType(T: QualType(SeltTy, 0)));
554
555 // FIXME: We should be able to narrow this integer in cases with dead
556 // padding.
557 return ABIArgInfo::getDirect(T: llvm::IntegerType::get(C&: getVMContext(),NumBits: Size));
558 }
559
560 return getIndirectReturnResult(RetTy, State);
561 }
562
563 // Treat an enum type as its underlying type.
564 if (const auto *ED = RetTy->getAsEnumDecl())
565 RetTy = ED->getIntegerType();
566
567 if (const auto *EIT = RetTy->getAs<BitIntType>())
568 if (EIT->getNumBits() > 64)
569 return getIndirectReturnResult(RetTy, State);
570
571 return (isPromotableIntegerTypeForABI(Ty: RetTy) ? ABIArgInfo::getExtend(Ty: RetTy)
572 : ABIArgInfo::getDirect());
573}
574
575unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
576 unsigned Align) const {
577 // Otherwise, if the alignment is less than or equal to the minimum ABI
578 // alignment, just use the default; the backend will handle this.
579 if (Align <= MinABIStackAlignInBytes)
580 return 0; // Use default alignment.
581
582 if (Ty->isFloat128Type())
583 return 16;
584
585 if (IsLinuxABI) {
586 // Exclude other System V OS (e.g Darwin, PS4 and FreeBSD) since we don't
587 // want to spend any effort dealing with the ramifications of ABI breaks.
588 //
589 // If the vector type is __m128/__m256/__m512, return the default alignment.
590 if (Ty->isVectorType() && (Align == 16 || Align == 32 || Align == 64))
591 return Align;
592 }
593 // On non-Darwin, the stack type alignment is always 4.
594 if (!IsDarwinVectorABI) {
595 // Set explicit alignment, since we may need to realign the top.
596 return MinABIStackAlignInBytes;
597 }
598
599 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
600 if (Align >= 16 && (isSIMDVectorType(Context&: getContext(), Ty) ||
601 isRecordWithSIMDVectorType(Context&: getContext(), Ty)))
602 return 16;
603
604 return MinABIStackAlignInBytes;
605}
606
607ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
608 CCState &State) const {
609 if (!ByVal) {
610 if (State.FreeRegs) {
611 --State.FreeRegs; // Non-byval indirects just use one pointer.
612 if (!IsMCUABI)
613 return getNaturalAlignIndirectInReg(Ty);
614 }
615 return getNaturalAlignIndirect(Ty, AddrSpace: getDataLayout().getAllocaAddrSpace(),
616 ByVal: false);
617 }
618
619 // Compute the byval alignment.
620 unsigned TypeAlign = getContext().getTypeAlign(T: Ty) / 8;
621 unsigned StackAlign = getTypeStackAlignInBytes(Ty, Align: TypeAlign);
622 if (StackAlign == 0)
623 return ABIArgInfo::getIndirect(
624 Alignment: CharUnits::fromQuantity(Quantity: 4),
625 /*AddrSpace=*/getDataLayout().getAllocaAddrSpace(),
626 /*ByVal=*/true);
627
628 // If the stack alignment is less than the type alignment, realign the
629 // argument.
630 bool Realign = TypeAlign > StackAlign;
631 return ABIArgInfo::getIndirect(
632 Alignment: CharUnits::fromQuantity(Quantity: StackAlign),
633 /*AddrSpace=*/getDataLayout().getAllocaAddrSpace(), /*ByVal=*/true,
634 Realign);
635}
636
637X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
638 const Type *T = isSingleElementStruct(T: Ty, Context&: getContext());
639 if (!T)
640 T = Ty.getTypePtr();
641
642 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
643 BuiltinType::Kind K = BT->getKind();
644 if (K == BuiltinType::Float || K == BuiltinType::Double)
645 return Float;
646 }
647 return Integer;
648}
649
650bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
651 if (!IsSoftFloatABI) {
652 Class C = classify(Ty);
653 if (C == Float)
654 return false;
655 }
656
657 unsigned Size = getContext().getTypeSize(T: Ty);
658 unsigned SizeInRegs = (Size + 31) / 32;
659
660 if (SizeInRegs == 0)
661 return false;
662
663 if (!IsMCUABI) {
664 if (SizeInRegs > State.FreeRegs) {
665 State.FreeRegs = 0;
666 return false;
667 }
668 } else {
669 // The MCU psABI allows passing parameters in-reg even if there are
670 // earlier parameters that are passed on the stack. Also,
671 // it does not allow passing >8-byte structs in-register,
672 // even if there are 3 free registers available.
673 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
674 return false;
675 }
676
677 State.FreeRegs -= SizeInRegs;
678 return true;
679}
680
681bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
682 bool &InReg,
683 bool &NeedsPadding) const {
684 // On Windows, aggregates other than HFAs are never passed in registers, and
685 // they do not consume register slots. Homogenous floating-point aggregates
686 // (HFAs) have already been dealt with at this point.
687 if (IsWin32StructABI && isAggregateTypeForABI(T: Ty))
688 return false;
689
690 NeedsPadding = false;
691 InReg = !IsMCUABI;
692
693 if (!updateFreeRegs(Ty, State))
694 return false;
695
696 if (IsMCUABI)
697 return true;
698
699 if (State.CC == llvm::CallingConv::X86_FastCall ||
700 State.CC == llvm::CallingConv::X86_VectorCall ||
701 State.CC == llvm::CallingConv::X86_RegCall) {
702 if (getContext().getTypeSize(T: Ty) <= 32 && State.FreeRegs)
703 NeedsPadding = true;
704
705 return false;
706 }
707
708 return true;
709}
710
711bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
712 bool IsPtrOrInt = (getContext().getTypeSize(T: Ty) <= 32) &&
713 (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
714 Ty->isReferenceType());
715
716 if (!IsPtrOrInt && (State.CC == llvm::CallingConv::X86_FastCall ||
717 State.CC == llvm::CallingConv::X86_VectorCall))
718 return false;
719
720 if (!updateFreeRegs(Ty, State))
721 return false;
722
723 if (!IsPtrOrInt && State.CC == llvm::CallingConv::X86_RegCall)
724 return false;
725
726 // Return true to apply inreg to all legal parameters except for MCU targets.
727 return !IsMCUABI;
728}
729
730void X86_32ABIInfo::runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const {
731 // Vectorcall x86 works subtly different than in x64, so the format is
732 // a bit different than the x64 version. First, all vector types (not HVAs)
733 // are assigned, with the first 6 ending up in the [XYZ]MM0-5 registers.
734 // This differs from the x64 implementation, where the first 6 by INDEX get
735 // registers.
736 // In the second pass over the arguments, HVAs are passed in the remaining
737 // vector registers if possible, or indirectly by address. The address will be
738 // passed in ECX/EDX if available. Any other arguments are passed according to
739 // the usual fastcall rules.
740 MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
741 for (int I = 0, E = Args.size(); I < E; ++I) {
742 const Type *Base = nullptr;
743 uint64_t NumElts = 0;
744 const QualType &Ty = Args[I].type;
745 if ((Ty->isVectorType() || Ty->isBuiltinType()) &&
746 isHomogeneousAggregate(Ty, Base, Members&: NumElts)) {
747 if (State.FreeSSERegs >= NumElts) {
748 State.FreeSSERegs -= NumElts;
749 Args[I].info = ABIArgInfo::getDirectInReg();
750 State.IsPreassigned.set(I);
751 }
752 }
753 }
754}
755
756ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty, CCState &State,
757 unsigned ArgIndex) const {
758 // FIXME: Set alignment on indirect arguments.
759 bool IsFastCall = State.CC == llvm::CallingConv::X86_FastCall;
760 bool IsRegCall = State.CC == llvm::CallingConv::X86_RegCall;
761 bool IsVectorCall = State.CC == llvm::CallingConv::X86_VectorCall;
762
763 Ty = useFirstFieldIfTransparentUnion(Ty);
764 TypeInfo TI = getContext().getTypeInfo(T: Ty);
765
766 // Check with the C++ ABI first.
767 const RecordType *RT = Ty->getAsCanonical<RecordType>();
768 if (RT) {
769 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, CXXABI&: getCXXABI());
770 if (RAA == CGCXXABI::RAA_Indirect) {
771 return getIndirectResult(Ty, ByVal: false, State);
772 } else if (State.IsDelegateCall) {
773 // Avoid having different alignments on delegate call args by always
774 // setting the alignment to 4, which is what we do for inallocas.
775 ABIArgInfo Res = getIndirectResult(Ty, ByVal: false, State);
776 Res.setIndirectAlign(CharUnits::fromQuantity(Quantity: 4));
777 return Res;
778 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
779 // The field index doesn't matter, we'll fix it up later.
780 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
781 }
782 }
783
784 // Regcall uses the concept of a homogenous vector aggregate, similar
785 // to other targets.
786 const Type *Base = nullptr;
787 uint64_t NumElts = 0;
788 if ((IsRegCall || IsVectorCall) &&
789 isHomogeneousAggregate(Ty, Base, Members&: NumElts)) {
790 if (State.FreeSSERegs >= NumElts) {
791 State.FreeSSERegs -= NumElts;
792
793 // Vectorcall passes HVAs directly and does not flatten them, but regcall
794 // does.
795 if (IsVectorCall)
796 return getDirectX86Hva();
797
798 if (Ty->isBuiltinType() || Ty->isVectorType())
799 return ABIArgInfo::getDirect();
800 return ABIArgInfo::getExpand();
801 }
802 if (IsVectorCall && Ty->isBuiltinType())
803 return ABIArgInfo::getDirect();
804 return getIndirectResult(Ty, /*ByVal=*/false, State);
805 }
806
807 if (isAggregateTypeForABI(T: Ty)) {
808 // Structures with flexible arrays are always indirect.
809 // FIXME: This should not be byval!
810 if (RT && RT->getDecl()->getDefinitionOrSelf()->hasFlexibleArrayMember())
811 return getIndirectResult(Ty, ByVal: true, State);
812
813 // Ignore empty structs/unions on non-Windows.
814 if (!IsWin32StructABI && isEmptyRecord(Context&: getContext(), T: Ty, AllowArrays: true))
815 return ABIArgInfo::getIgnore();
816
817 // Ignore 0 sized structs.
818 if (TI.Width == 0)
819 return ABIArgInfo::getIgnore();
820
821 llvm::LLVMContext &LLVMContext = getVMContext();
822 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(C&: LLVMContext);
823 bool NeedsPadding = false;
824 bool InReg;
825 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
826 unsigned SizeInRegs = (TI.Width + 31) / 32;
827 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
828 llvm::Type *Result = llvm::StructType::get(Context&: LLVMContext, Elements);
829 if (InReg)
830 return ABIArgInfo::getDirectInReg(T: Result);
831 else
832 return ABIArgInfo::getDirect(T: Result);
833 }
834 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
835
836 // Pass over-aligned aggregates to non-variadic functions on Windows
837 // indirectly. This behavior was added in MSVC 2015. Use the required
838 // alignment from the record layout, since that may be less than the
839 // regular type alignment, and types with required alignment of less than 4
840 // bytes are not passed indirectly.
841 if (IsWin32StructABI && State.Required.isRequiredArg(argIdx: ArgIndex)) {
842 unsigned AlignInBits = 0;
843 if (RT) {
844 const ASTRecordLayout &Layout =
845 getContext().getASTRecordLayout(D: RT->getDecl());
846 AlignInBits = getContext().toBits(CharSize: Layout.getRequiredAlignment());
847 } else if (TI.isAlignRequired()) {
848 AlignInBits = TI.Align;
849 }
850 if (AlignInBits > 32)
851 return getIndirectResult(Ty, /*ByVal=*/false, State);
852 }
853
854 // Expand small (<= 128-bit) record types when we know that the stack layout
855 // of those arguments will match the struct. This is important because the
856 // LLVM backend isn't smart enough to remove byval, which inhibits many
857 // optimizations.
858 // Don't do this for the MCU if there are still free integer registers
859 // (see X86_64 ABI for full explanation).
860 if (TI.Width <= 4 * 32 && (!IsMCUABI || State.FreeRegs == 0) &&
861 canExpandIndirectArgument(Ty))
862 return ABIArgInfo::getExpandWithPadding(
863 PaddingInReg: IsFastCall || IsVectorCall || IsRegCall, Padding: PaddingType);
864
865 return getIndirectResult(Ty, ByVal: true, State);
866 }
867
868 if (const VectorType *VT = Ty->getAs<VectorType>()) {
869 // On Windows, vectors are passed directly if registers are available, or
870 // indirectly if not. This avoids the need to align argument memory. Pass
871 // user-defined vector types larger than 512 bits indirectly for simplicity.
872 if (IsWin32StructABI) {
873 if (TI.Width <= 512 && State.FreeSSERegs > 0) {
874 --State.FreeSSERegs;
875 return ABIArgInfo::getDirectInReg();
876 }
877 return getIndirectResult(Ty, /*ByVal=*/false, State);
878 }
879
880 // On Darwin, some vectors are passed in memory, we handle this by passing
881 // it as an i8/i16/i32/i64.
882 if (IsDarwinVectorABI) {
883 if ((TI.Width == 8 || TI.Width == 16 || TI.Width == 32) ||
884 (TI.Width == 64 && VT->getNumElements() == 1))
885 return ABIArgInfo::getDirect(
886 T: llvm::IntegerType::get(C&: getVMContext(), NumBits: TI.Width));
887 }
888
889 if (IsX86_MMXType(IRType: CGT.ConvertType(T: Ty)))
890 return ABIArgInfo::getDirect(T: llvm::IntegerType::get(C&: getVMContext(), NumBits: 64));
891
892 return ABIArgInfo::getDirect();
893 }
894
895 if (const auto *ED = Ty->getAsEnumDecl())
896 Ty = ED->getIntegerType();
897
898 bool InReg = shouldPrimitiveUseInReg(Ty, State);
899
900 if (isPromotableIntegerTypeForABI(Ty)) {
901 if (InReg)
902 return ABIArgInfo::getExtendInReg(Ty, T: CGT.ConvertType(T: Ty));
903 return ABIArgInfo::getExtend(Ty, T: CGT.ConvertType(T: Ty));
904 }
905
906 if (const auto *EIT = Ty->getAs<BitIntType>()) {
907 if (EIT->getNumBits() <= 64) {
908 if (InReg)
909 return ABIArgInfo::getDirectInReg();
910 return ABIArgInfo::getDirect();
911 }
912 return getIndirectResult(Ty, /*ByVal=*/false, State);
913 }
914
915 if (InReg)
916 return ABIArgInfo::getDirectInReg();
917 return ABIArgInfo::getDirect();
918}
919
920void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
921 CCState State(FI);
922 if (IsMCUABI)
923 State.FreeRegs = 3;
924 else if (State.CC == llvm::CallingConv::X86_FastCall) {
925 State.FreeRegs = 2;
926 State.FreeSSERegs = 3;
927 } else if (State.CC == llvm::CallingConv::X86_VectorCall) {
928 State.FreeRegs = 2;
929 State.FreeSSERegs = 6;
930 } else if (FI.getHasRegParm())
931 State.FreeRegs = FI.getRegParm();
932 else if (State.CC == llvm::CallingConv::X86_RegCall) {
933 State.FreeRegs = 5;
934 State.FreeSSERegs = 8;
935 } else if (IsWin32StructABI) {
936 // Since MSVC 2015, the first three SSE vectors have been passed in
937 // registers. The rest are passed indirectly.
938 State.FreeRegs = DefaultNumRegisterParameters;
939 State.FreeSSERegs = 3;
940 } else
941 State.FreeRegs = DefaultNumRegisterParameters;
942
943 if (!::classifyReturnType(CXXABI: getCXXABI(), FI, Info: *this)) {
944 FI.getReturnInfo() = classifyReturnType(RetTy: FI.getReturnType(), State);
945 } else if (FI.getReturnInfo().isIndirect()) {
946 // The C++ ABI is not aware of register usage, so we have to check if the
947 // return value was sret and put it in a register ourselves if appropriate.
948 if (State.FreeRegs) {
949 --State.FreeRegs; // The sret parameter consumes a register.
950 if (!IsMCUABI)
951 FI.getReturnInfo().setInReg(true);
952 }
953 }
954
955 // The chain argument effectively gives us another free register.
956 if (FI.isChainCall())
957 ++State.FreeRegs;
958
959 // For vectorcall, do a first pass over the arguments, assigning FP and vector
960 // arguments to XMM registers as available.
961 if (State.CC == llvm::CallingConv::X86_VectorCall)
962 runVectorCallFirstPass(FI, State);
963
964 bool UsedInAlloca = false;
965 MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
966 for (unsigned I = 0, E = Args.size(); I < E; ++I) {
967 // Skip arguments that have already been assigned.
968 if (State.IsPreassigned.test(Idx: I))
969 continue;
970
971 Args[I].info =
972 classifyArgumentType(Ty: Args[I].type, State, ArgIndex: I);
973 UsedInAlloca |= (Args[I].info.getKind() == ABIArgInfo::InAlloca);
974 }
975
976 // If we needed to use inalloca for any argument, do a second pass and rewrite
977 // all the memory arguments to use inalloca.
978 if (UsedInAlloca)
979 rewriteWithInAlloca(FI);
980}
981
982void
983X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
984 CharUnits &StackOffset, ABIArgInfo &Info,
985 QualType Type) const {
986 // Arguments are always 4-byte-aligned.
987 CharUnits WordSize = CharUnits::fromQuantity(Quantity: 4);
988 assert(StackOffset.isMultipleOf(WordSize) && "unaligned inalloca struct");
989
990 // sret pointers and indirect things will require an extra pointer
991 // indirection, unless they are byval. Most things are byval, and will not
992 // require this indirection.
993 bool IsIndirect = false;
994 if (Info.isIndirect() && !Info.getIndirectByVal())
995 IsIndirect = true;
996 Info = ABIArgInfo::getInAlloca(FieldIndex: FrameFields.size(), Indirect: IsIndirect);
997 llvm::Type *LLTy = CGT.ConvertTypeForMem(T: Type);
998 if (IsIndirect)
999 LLTy = llvm::PointerType::getUnqual(C&: getVMContext());
1000 FrameFields.push_back(Elt: LLTy);
1001 StackOffset += IsIndirect ? WordSize : getContext().getTypeSizeInChars(T: Type);
1002
1003 // Insert padding bytes to respect alignment.
1004 CharUnits FieldEnd = StackOffset;
1005 StackOffset = FieldEnd.alignTo(Align: WordSize);
1006 if (StackOffset != FieldEnd) {
1007 CharUnits NumBytes = StackOffset - FieldEnd;
1008 llvm::Type *Ty = llvm::Type::getInt8Ty(C&: getVMContext());
1009 Ty = llvm::ArrayType::get(ElementType: Ty, NumElements: NumBytes.getQuantity());
1010 FrameFields.push_back(Elt: Ty);
1011 }
1012}
1013
1014static bool isArgInAlloca(const ABIArgInfo &Info) {
1015 // Leave ignored and inreg arguments alone.
1016 switch (Info.getKind()) {
1017 case ABIArgInfo::InAlloca:
1018 return true;
1019 case ABIArgInfo::Ignore:
1020 case ABIArgInfo::IndirectAliased:
1021 case ABIArgInfo::TargetSpecific:
1022 return false;
1023 case ABIArgInfo::Indirect:
1024 case ABIArgInfo::Direct:
1025 case ABIArgInfo::Extend:
1026 return !Info.getInReg();
1027 case ABIArgInfo::Expand:
1028 case ABIArgInfo::CoerceAndExpand:
1029 // These are aggregate types which are never passed in registers when
1030 // inalloca is involved.
1031 return true;
1032 }
1033 llvm_unreachable("invalid enum");
1034}
1035
1036void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1037 assert(IsWin32StructABI && "inalloca only supported on win32");
1038
1039 // Build a packed struct type for all of the arguments in memory.
1040 SmallVector<llvm::Type *, 6> FrameFields;
1041
1042 // The stack alignment is always 4.
1043 CharUnits StackAlign = CharUnits::fromQuantity(Quantity: 4);
1044
1045 CharUnits StackOffset;
1046 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1047
1048 // Put 'this' into the struct before 'sret', if necessary.
1049 bool IsThisCall =
1050 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1051 ABIArgInfo &Ret = FI.getReturnInfo();
1052 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1053 isArgInAlloca(Info: I->info)) {
1054 addFieldToArgStruct(FrameFields, StackOffset, Info&: I->info, Type: I->type);
1055 ++I;
1056 }
1057
1058 // Put the sret parameter into the inalloca struct if it's in memory.
1059 if (Ret.isIndirect() && !Ret.getInReg()) {
1060 addFieldToArgStruct(FrameFields, StackOffset, Info&: Ret, Type: FI.getReturnType());
1061 // On Windows, the hidden sret parameter is always returned in eax.
1062 Ret.setInAllocaSRet(IsWin32StructABI);
1063 }
1064
1065 // Skip the 'this' parameter in ecx.
1066 if (IsThisCall)
1067 ++I;
1068
1069 // Put arguments passed in memory into the struct.
1070 for (; I != E; ++I) {
1071 if (isArgInAlloca(Info: I->info))
1072 addFieldToArgStruct(FrameFields, StackOffset, Info&: I->info, Type: I->type);
1073 }
1074
1075 FI.setArgStruct(Ty: llvm::StructType::get(Context&: getVMContext(), Elements: FrameFields,
1076 /*isPacked=*/true),
1077 Align: StackAlign);
1078}
1079
1080RValue X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1081 QualType Ty, AggValueSlot Slot) const {
1082
1083 auto TypeInfo = getContext().getTypeInfoInChars(T: Ty);
1084
1085 CCState State(*const_cast<CGFunctionInfo *>(CGF.CurFnInfo));
1086 ABIArgInfo AI = classifyArgumentType(Ty, State, /*ArgIndex*/ 0);
1087 // Empty records are ignored for parameter passing purposes.
1088 if (AI.isIgnore())
1089 return Slot.asRValue();
1090
1091 // x86-32 changes the alignment of certain arguments on the stack.
1092 //
1093 // Just messing with TypeInfo like this works because we never pass
1094 // anything indirectly.
1095 TypeInfo.Align = CharUnits::fromQuantity(
1096 Quantity: getTypeStackAlignInBytes(Ty, Align: TypeInfo.Align.getQuantity()));
1097
1098 return emitVoidPtrVAArg(CGF, VAListAddr, ValueTy: Ty, /*Indirect*/ IsIndirect: false, ValueInfo: TypeInfo,
1099 SlotSizeAndAlign: CharUnits::fromQuantity(Quantity: 4),
1100 /*AllowHigherAlign*/ true, Slot);
1101}
1102
1103bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1104 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1105 assert(Triple.getArch() == llvm::Triple::x86);
1106
1107 switch (Opts.getStructReturnConvention()) {
1108 case CodeGenOptions::SRCK_Default:
1109 break;
1110 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1111 return false;
1112 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1113 return true;
1114 }
1115
1116 if (Triple.isOSDarwin() || Triple.isOSIAMCU())
1117 return true;
1118
1119 switch (Triple.getOS()) {
1120 case llvm::Triple::DragonFly:
1121 case llvm::Triple::FreeBSD:
1122 case llvm::Triple::OpenBSD:
1123 case llvm::Triple::Win32:
1124 return true;
1125 default:
1126 return false;
1127 }
1128}
1129
1130static void addX86InterruptAttrs(const FunctionDecl *FD, llvm::GlobalValue *GV,
1131 CodeGen::CodeGenModule &CGM) {
1132 if (!FD->hasAttr<AnyX86InterruptAttr>())
1133 return;
1134
1135 llvm::Function *Fn = cast<llvm::Function>(Val: GV);
1136 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
1137 if (FD->getNumParams() == 0)
1138 return;
1139
1140 auto PtrTy = cast<PointerType>(Val: FD->getParamDecl(i: 0)->getType());
1141 llvm::Type *ByValTy = CGM.getTypes().ConvertType(T: PtrTy->getPointeeType());
1142 llvm::Attribute NewAttr = llvm::Attribute::getWithByValType(
1143 Context&: Fn->getContext(), Ty: ByValTy);
1144 Fn->addParamAttr(ArgNo: 0, Attr: NewAttr);
1145}
1146
1147void X86_32TargetCodeGenInfo::setTargetAttributes(
1148 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
1149 if (GV->isDeclaration())
1150 return;
1151 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: D)) {
1152 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1153 llvm::Function *Fn = cast<llvm::Function>(Val: GV);
1154 Fn->addFnAttr(Kind: "stackrealign");
1155 }
1156
1157 addX86InterruptAttrs(FD, GV, CGM);
1158 }
1159}
1160
1161bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1162 CodeGen::CodeGenFunction &CGF,
1163 llvm::Value *Address) const {
1164 CodeGen::CGBuilderTy &Builder = CGF.Builder;
1165
1166 llvm::Value *Four8 = llvm::ConstantInt::get(Ty: CGF.Int8Ty, V: 4);
1167
1168 // 0-7 are the eight integer registers; the order is different
1169 // on Darwin (for EH), but the range is the same.
1170 // 8 is %eip.
1171 AssignToArrayRange(Builder, Array: Address, Value: Four8, FirstIndex: 0, LastIndex: 8);
1172
1173 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
1174 // 12-16 are st(0..4). Not sure why we stop at 4.
1175 // These have size 16, which is sizeof(long double) on
1176 // platforms with 8-byte alignment for that type.
1177 llvm::Value *Sixteen8 = llvm::ConstantInt::get(Ty: CGF.Int8Ty, V: 16);
1178 AssignToArrayRange(Builder, Array: Address, Value: Sixteen8, FirstIndex: 12, LastIndex: 16);
1179
1180 } else {
1181 // 9 is %eflags, which doesn't get a size on Darwin for some
1182 // reason.
1183 Builder.CreateAlignedStore(
1184 Val: Four8, Addr: Builder.CreateConstInBoundsGEP1_32(Ty: CGF.Int8Ty, Ptr: Address, Idx0: 9),
1185 Align: CharUnits::One());
1186
1187 // 11-16 are st(0..5). Not sure why we stop at 5.
1188 // These have size 12, which is sizeof(long double) on
1189 // platforms with 4-byte alignment for that type.
1190 llvm::Value *Twelve8 = llvm::ConstantInt::get(Ty: CGF.Int8Ty, V: 12);
1191 AssignToArrayRange(Builder, Array: Address, Value: Twelve8, FirstIndex: 11, LastIndex: 16);
1192 }
1193
1194 return false;
1195}
1196
1197//===----------------------------------------------------------------------===//
1198// X86-64 ABI Implementation
1199//===----------------------------------------------------------------------===//
1200
1201
1202namespace {
1203
1204/// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
1205static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
1206 switch (AVXLevel) {
1207 case X86AVXABILevel::AVX512:
1208 return 512;
1209 case X86AVXABILevel::AVX:
1210 return 256;
1211 case X86AVXABILevel::None:
1212 return 128;
1213 }
1214 llvm_unreachable("Unknown AVXLevel");
1215}
1216
1217/// X86_64ABIInfo - The X86_64 ABI information.
1218class X86_64ABIInfo : public ABIInfo {
1219 enum Class {
1220 Integer = 0,
1221 SSE,
1222 SSEUp,
1223 X87,
1224 X87Up,
1225 ComplexX87,
1226 NoClass,
1227 Memory
1228 };
1229
1230 /// merge - Implement the X86_64 ABI merging algorithm.
1231 ///
1232 /// Merge an accumulating classification \arg Accum with a field
1233 /// classification \arg Field.
1234 ///
1235 /// \param Accum - The accumulating classification. This should
1236 /// always be either NoClass or the result of a previous merge
1237 /// call. In addition, this should never be Memory (the caller
1238 /// should just return Memory for the aggregate).
1239 static Class merge(Class Accum, Class Field);
1240
1241 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1242 ///
1243 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1244 /// final MEMORY or SSE classes when necessary.
1245 ///
1246 /// \param AggregateSize - The size of the current aggregate in
1247 /// the classification process.
1248 ///
1249 /// \param Lo - The classification for the parts of the type
1250 /// residing in the low word of the containing object.
1251 ///
1252 /// \param Hi - The classification for the parts of the type
1253 /// residing in the higher words of the containing object.
1254 ///
1255 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1256
1257 /// classify - Determine the x86_64 register classes in which the
1258 /// given type T should be passed.
1259 ///
1260 /// \param Lo - The classification for the parts of the type
1261 /// residing in the low word of the containing object.
1262 ///
1263 /// \param Hi - The classification for the parts of the type
1264 /// residing in the high word of the containing object.
1265 ///
1266 /// \param OffsetBase - The bit offset of this type in the
1267 /// containing object. Some parameters are classified different
1268 /// depending on whether they straddle an eightbyte boundary.
1269 ///
1270 /// \param isNamedArg - Whether the argument in question is a "named"
1271 /// argument, as used in AMD64-ABI 3.5.7.
1272 ///
1273 /// \param IsRegCall - Whether the calling conversion is regcall.
1274 ///
1275 /// If a word is unused its result will be NoClass; if a type should
1276 /// be passed in Memory then at least the classification of \arg Lo
1277 /// will be Memory.
1278 ///
1279 /// The \arg Lo class will be NoClass iff the argument is ignored.
1280 ///
1281 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1282 /// also be ComplexX87.
1283 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1284 bool isNamedArg, bool IsRegCall = false) const;
1285
1286 llvm::Type *GetByteVectorType(QualType Ty) const;
1287 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1288 unsigned IROffset, QualType SourceTy,
1289 unsigned SourceOffset) const;
1290 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1291 unsigned IROffset, QualType SourceTy,
1292 unsigned SourceOffset) const;
1293
1294 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
1295 /// such that the argument will be returned in memory.
1296 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
1297
1298 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
1299 /// such that the argument will be passed in memory.
1300 ///
1301 /// \param freeIntRegs - The number of free integer registers remaining
1302 /// available.
1303 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
1304
1305 ABIArgInfo classifyReturnType(QualType RetTy) const;
1306
1307 ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
1308 unsigned &neededInt, unsigned &neededSSE,
1309 bool isNamedArg,
1310 bool IsRegCall = false) const;
1311
1312 ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
1313 unsigned &NeededSSE,
1314 unsigned &MaxVectorWidth) const;
1315
1316 bool passRegCallStructTypeDirectly(QualType Ty,
1317 SmallVectorImpl<llvm::Type *> &CoerceElts,
1318 unsigned &NeededInt, unsigned &NeededSSE,
1319 unsigned &MaxVectorWidth) const;
1320
1321 bool IsIllegalVectorType(QualType Ty) const;
1322
1323 /// The 0.98 ABI revision clarified a lot of ambiguities,
1324 /// unfortunately in ways that were not always consistent with
1325 /// certain previous compilers. In particular, platforms which
1326 /// required strict binary compatibility with older versions of GCC
1327 /// may need to exempt themselves.
1328 bool honorsRevision0_98() const {
1329 return !getTarget().getTriple().isOSDarwin();
1330 }
1331
1332 /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to
1333 /// classify it as INTEGER (for compatibility with older clang compilers).
1334 bool classifyIntegerMMXAsSSE() const {
1335 // Clang <= 3.8 did not do this.
1336 if (getContext().getLangOpts().isCompatibleWith(
1337 Version: LangOptions::ClangABI::Ver3_8))
1338 return false;
1339
1340 const llvm::Triple &Triple = getTarget().getTriple();
1341 if (Triple.isOSDarwin() || Triple.isPS() || Triple.isOSFreeBSD())
1342 return false;
1343 return true;
1344 }
1345
1346 // GCC classifies vectors of __int128 as memory.
1347 bool passInt128VectorsInMem() const {
1348 // Clang <= 9.0 did not do this.
1349 if (getContext().getLangOpts().isCompatibleWith(
1350 Version: LangOptions::ClangABI::Ver9))
1351 return false;
1352
1353 const llvm::Triple &T = getTarget().getTriple();
1354 return T.isOSLinux() || T.isOSNetBSD();
1355 }
1356
1357 bool returnCXXRecordGreaterThan128InMem() const {
1358 // Clang <= 20.0 did not do this, and PlayStation does not do this.
1359 if (getContext().getLangOpts().isCompatibleWith(
1360 Version: LangOptions::ClangABI::Ver20) ||
1361 getTarget().getTriple().isPS())
1362 return false;
1363
1364 return true;
1365 }
1366
1367 X86AVXABILevel AVXLevel;
1368 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1369 // 64-bit hardware.
1370 bool Has64BitPointers;
1371
1372public:
1373 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
1374 : ABIInfo(CGT), AVXLevel(AVXLevel),
1375 Has64BitPointers(CGT.getDataLayout().getPointerSize(AS: 0) == 8) {}
1376
1377 bool isPassedUsingAVXType(QualType type) const {
1378 unsigned neededInt, neededSSE;
1379 // The freeIntRegs argument doesn't matter here.
1380 ABIArgInfo info = classifyArgumentType(Ty: type, freeIntRegs: 0, neededInt, neededSSE,
1381 /*isNamedArg*/true);
1382 if (info.isDirect()) {
1383 llvm::Type *ty = info.getCoerceToType();
1384 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(Val: ty))
1385 return vectorTy->getPrimitiveSizeInBits().getFixedValue() > 128;
1386 }
1387 return false;
1388 }
1389
1390 void computeInfo(CGFunctionInfo &FI) const override;
1391 unsigned getX86ABIAVXLevel(const FunctionDecl *FD,
1392 const FunctionType::ExtInfo &Info) const override;
1393
1394 RValue EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
1395 AggValueSlot Slot) const override;
1396 RValue EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
1397 AggValueSlot Slot) const override;
1398
1399 bool has64BitPointers() const {
1400 return Has64BitPointers;
1401 }
1402};
1403
1404/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
1405class WinX86_64ABIInfo : public ABIInfo {
1406public:
1407 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
1408 : ABIInfo(CGT), AVXLevel(AVXLevel),
1409 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
1410
1411 void computeInfo(CGFunctionInfo &FI) const override;
1412 unsigned getX86ABIAVXLevel(const FunctionDecl *FD,
1413 const FunctionType::ExtInfo &Info) const override;
1414
1415 RValue EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
1416 AggValueSlot Slot) const override;
1417
1418 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1419 // FIXME: Assumes vectorcall is in use.
1420 return isX86VectorTypeForVectorCall(Context&: getContext(), Ty);
1421 }
1422
1423 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1424 uint64_t NumMembers) const override {
1425 // FIXME: Assumes vectorcall is in use.
1426 return isX86VectorCallAggregateSmallEnough(NumMembers);
1427 }
1428
1429 ABIArgInfo classifyArgForArm64ECVarArg(QualType Ty) const override {
1430 unsigned FreeSSERegs = 0;
1431 return classify(Ty, FreeSSERegs, /*IsReturnType=*/false,
1432 CC: llvm::CallingConv::C);
1433 }
1434
1435private:
1436 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
1437 unsigned CC) const;
1438 ABIArgInfo reclassifyHvaArgForVectorCall(QualType Ty, unsigned &FreeSSERegs,
1439 const ABIArgInfo &current) const;
1440
1441 X86AVXABILevel AVXLevel;
1442
1443 bool IsMingw64;
1444};
1445
1446class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1447public:
1448 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
1449 : TargetCodeGenInfo(std::make_unique<X86_64ABIInfo>(args&: CGT, args&: AVXLevel)) {
1450 SwiftInfo =
1451 std::make_unique<SwiftABIInfo>(args&: CGT, /*SwiftErrorInRegister=*/args: true);
1452 }
1453
1454 /// Disable tail call on x86-64. The epilogue code before the tail jump blocks
1455 /// autoreleaseRV/retainRV and autoreleaseRV/unsafeClaimRV optimizations.
1456 bool markARCOptimizedReturnCallsAsNoTail() const override { return true; }
1457
1458 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
1459 return 7;
1460 }
1461
1462 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1463 llvm::Value *Address) const override {
1464 llvm::Value *Eight8 = llvm::ConstantInt::get(Ty: CGF.Int8Ty, V: 8);
1465
1466 // 0-15 are the 16 integer registers.
1467 // 16 is %rip.
1468 AssignToArrayRange(Builder&: CGF.Builder, Array: Address, Value: Eight8, FirstIndex: 0, LastIndex: 16);
1469 return false;
1470 }
1471
1472 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1473 StringRef Constraint,
1474 llvm::Type* Ty) const override {
1475 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1476 }
1477
1478 bool isNoProtoCallVariadic(const CallArgList &args,
1479 const FunctionNoProtoType *fnType) const override {
1480 // The default CC on x86-64 sets %al to the number of SSA
1481 // registers used, and GCC sets this when calling an unprototyped
1482 // function, so we override the default behavior. However, don't do
1483 // that when AVX types are involved: the ABI explicitly states it is
1484 // undefined, and it doesn't work in practice because of how the ABI
1485 // defines varargs anyway.
1486 if (fnType->getCallConv() == CC_C) {
1487 bool HasAVXType = false;
1488 for (const CallArg &arg : args) {
1489 if (getABIInfo<X86_64ABIInfo>().isPassedUsingAVXType(type: arg.Ty)) {
1490 HasAVXType = true;
1491 break;
1492 }
1493 }
1494
1495 if (!HasAVXType)
1496 return true;
1497 }
1498
1499 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
1500 }
1501
1502 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1503 CodeGen::CodeGenModule &CGM) const override {
1504 if (GV->isDeclaration())
1505 return;
1506 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: D)) {
1507 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1508 llvm::Function *Fn = cast<llvm::Function>(Val: GV);
1509 Fn->addFnAttr(Kind: "stackrealign");
1510 }
1511
1512 addX86InterruptAttrs(FD, GV, CGM);
1513 }
1514 }
1515
1516 void checkFunctionCallABI(CodeGenModule &CGM, SourceLocation CallLoc,
1517 const FunctionDecl *Caller,
1518 const FunctionDecl *Callee, const CallArgList &Args,
1519 QualType ReturnType) const override;
1520
1521 void checkFunctionABI(CodeGenModule &CGM,
1522 const FunctionDecl *FD) const override;
1523};
1524} // namespace
1525
1526static void initFeatureMaps(const ASTContext &Ctx,
1527 llvm::StringMap<bool> &CallerMap,
1528 const FunctionDecl *Caller,
1529 llvm::StringMap<bool> &CalleeMap,
1530 const FunctionDecl *Callee) {
1531 if (CalleeMap.empty() && CallerMap.empty()) {
1532 // The caller is potentially nullptr in the case where the call isn't in a
1533 // function. In this case, the getFunctionFeatureMap ensures we just get
1534 // the TU level setting (since it cannot be modified by 'target'..
1535 Ctx.getFunctionFeatureMap(FeatureMap&: CallerMap, Caller);
1536 Ctx.getFunctionFeatureMap(FeatureMap&: CalleeMap, Callee);
1537 }
1538}
1539
1540static bool checkAVXParamFeature(DiagnosticsEngine &Diag,
1541 SourceLocation CallLoc,
1542 const FunctionDecl &Callee,
1543 const llvm::StringMap<bool> &CallerMap,
1544 const llvm::StringMap<bool> &CalleeMap,
1545 QualType Ty, StringRef Feature,
1546 bool IsArgument) {
1547 bool CallerHasFeat = CallerMap.lookup(Key: Feature);
1548 bool CalleeHasFeat = CalleeMap.lookup(Key: Feature);
1549 // No explicit features and the function is internal, be permissive.
1550 if (!CallerHasFeat && !CalleeHasFeat &&
1551 (!Callee.isExternallyVisible() || Callee.hasAttr<AlwaysInlineAttr>()))
1552 return false;
1553
1554 if (!CallerHasFeat && !CalleeHasFeat)
1555 return Diag.Report(Loc: CallLoc, DiagID: diag::warn_avx_calling_convention)
1556 << IsArgument << Ty << Feature;
1557
1558 // Mixing calling conventions here is very clearly an error.
1559 if (!CallerHasFeat || !CalleeHasFeat)
1560 return Diag.Report(Loc: CallLoc, DiagID: diag::err_avx_calling_convention)
1561 << IsArgument << Ty << Feature;
1562
1563 // Else, both caller and callee have the required feature, so there is no need
1564 // to diagnose.
1565 return false;
1566}
1567
1568static bool checkAVXParam(DiagnosticsEngine &Diag, ASTContext &Ctx,
1569 SourceLocation CallLoc, const FunctionDecl &Callee,
1570 const llvm::StringMap<bool> &CallerMap,
1571 const llvm::StringMap<bool> &CalleeMap, QualType Ty,
1572 bool IsArgument) {
1573 uint64_t Size = Ctx.getTypeSize(T: Ty);
1574 if (Size > 256)
1575 return checkAVXParamFeature(Diag, CallLoc, Callee, CallerMap, CalleeMap, Ty,
1576 Feature: "avx512f", IsArgument);
1577
1578 if (Size > 128)
1579 return checkAVXParamFeature(Diag, CallLoc, Callee, CallerMap, CalleeMap, Ty,
1580 Feature: "avx", IsArgument);
1581
1582 return false;
1583}
1584
1585void X86_64TargetCodeGenInfo::checkFunctionABI(CodeGenModule &CGM,
1586 const FunctionDecl *FD) const {
1587 auto GetReturnTypeLoc = [](const FunctionDecl *FD) {
1588 if (const TypeSourceInfo *TSI = FD->getTypeSourceInfo()) {
1589 TypeLoc TL = TSI->getTypeLoc();
1590
1591 if (auto FTL = TL.IgnoreParens().getAs<FunctionTypeLoc>()) {
1592 SourceLocation Loc = FTL.getReturnLoc().getBeginLoc();
1593 if (Loc.isValid())
1594 return Loc;
1595 }
1596 }
1597
1598 SourceLocation Loc = FD->getLocation();
1599 if (Loc.isValid())
1600 return Loc;
1601
1602 return FD->getBeginLoc();
1603 };
1604
1605 auto Check = [&](QualType Ty, SourceLocation Loc, bool IsReturn) {
1606 if (!Ty->isVectorType())
1607 return false;
1608 if (CGM.getContext().getTypeSize(T: Ty) <= 128)
1609 return false;
1610
1611 StringRef Feature =
1612 CGM.getContext().getTypeSize(T: Ty) > 256 ? "avx512f" : "avx";
1613
1614 llvm::StringMap<bool> FeatureMap;
1615 CGM.getContext().getFunctionFeatureMap(FeatureMap, FD);
1616 if (!FeatureMap.lookup(Key: Feature)) {
1617 CGM.getDiags().Report(Loc, DiagID: diag::warn_avx_calling_convention)
1618 << !IsReturn << Ty << Feature;
1619 return true;
1620 }
1621
1622 return false;
1623 };
1624
1625 // psABI warnings & errors for function definitions that are only visible
1626 // in this translation unit are handled at call site by checkFunctionCallABI.
1627 if (!FD->isExternallyVisible())
1628 return;
1629
1630 // First check the return type and emit diagnostic if required.
1631 Check(FD->getReturnType(), GetReturnTypeLoc(FD), true);
1632
1633 // Go through the parameters and emit a warning for the first vector found
1634 // without the matching function AVX level attribute.
1635 for (const ParmVarDecl *P : FD->parameters()) {
1636 SourceLocation Loc = P->getLocation();
1637 if (Loc.isInvalid())
1638 Loc = P->getBeginLoc();
1639 if (Check(P->getType(), Loc, false))
1640 return;
1641 }
1642}
1643
1644void X86_64TargetCodeGenInfo::checkFunctionCallABI(CodeGenModule &CGM,
1645 SourceLocation CallLoc,
1646 const FunctionDecl *Caller,
1647 const FunctionDecl *Callee,
1648 const CallArgList &Args,
1649 QualType ReturnType) const {
1650 if (!Callee)
1651 return;
1652
1653 llvm::StringMap<bool> CallerMap;
1654 llvm::StringMap<bool> CalleeMap;
1655 unsigned ArgIndex = 0;
1656
1657 // We need to loop through the actual call arguments rather than the
1658 // function's parameters, in case this variadic.
1659 for (const CallArg &Arg : Args) {
1660 // The "avx" feature changes how vectors >128 in size are passed. "avx512f"
1661 // additionally changes how vectors >256 in size are passed. Like GCC, we
1662 // warn when a function is called with an argument where this will change.
1663 // Unlike GCC, we also error when it is an obvious ABI mismatch, that is,
1664 // the caller and callee features are mismatched.
1665 // Unfortunately, we cannot do this diagnostic in SEMA, since the callee can
1666 // change its ABI with attribute-target after this call.
1667 if (Arg.getType()->isVectorType() &&
1668 CGM.getContext().getTypeSize(T: Arg.getType()) > 128) {
1669 initFeatureMaps(Ctx: CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
1670 QualType Ty = Arg.getType();
1671 // The CallArg seems to have desugared the type already, so for clearer
1672 // diagnostics, replace it with the type in the FunctionDecl if possible.
1673 if (ArgIndex < Callee->getNumParams())
1674 Ty = Callee->getParamDecl(i: ArgIndex)->getType();
1675
1676 if (checkAVXParam(Diag&: CGM.getDiags(), Ctx&: CGM.getContext(), CallLoc, Callee: *Callee,
1677 CallerMap, CalleeMap, Ty, /*IsArgument*/ true))
1678 return;
1679 }
1680 ++ArgIndex;
1681 }
1682
1683 // Check return always, as we don't have a good way of knowing in codegen
1684 // whether this value is used, tail-called, etc.
1685 if (Callee->getReturnType()->isVectorType() &&
1686 CGM.getContext().getTypeSize(T: Callee->getReturnType()) > 128) {
1687 initFeatureMaps(Ctx: CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
1688 checkAVXParam(Diag&: CGM.getDiags(), Ctx&: CGM.getContext(), CallLoc, Callee: *Callee, CallerMap,
1689 CalleeMap, Ty: Callee->getReturnType(),
1690 /*IsArgument*/ false);
1691 }
1692}
1693
1694std::string TargetCodeGenInfo::qualifyWindowsLibrary(StringRef Lib) {
1695 // If the argument does not end in .lib, automatically add the suffix.
1696 // If the argument contains a space, enclose it in quotes.
1697 // This matches the behavior of MSVC.
1698 bool Quote = Lib.contains(C: ' ');
1699 std::string ArgStr = Quote ? "\"" : "";
1700 ArgStr += Lib;
1701 if (!Lib.ends_with_insensitive(Suffix: ".lib") && !Lib.ends_with_insensitive(Suffix: ".a"))
1702 ArgStr += ".lib";
1703 ArgStr += Quote ? "\"" : "";
1704 return ArgStr;
1705}
1706
1707namespace {
1708class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1709public:
1710 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1711 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
1712 unsigned NumRegisterParameters)
1713 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
1714 Win32StructABI, NumRegisterParameters, false) {}
1715
1716 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1717 CodeGen::CodeGenModule &CGM) const override;
1718
1719 void getDependentLibraryOption(llvm::StringRef Lib,
1720 llvm::SmallString<24> &Opt) const override {
1721 Opt = "/DEFAULTLIB:";
1722 Opt += qualifyWindowsLibrary(Lib);
1723 }
1724
1725 void getDetectMismatchOption(llvm::StringRef Name,
1726 llvm::StringRef Value,
1727 llvm::SmallString<32> &Opt) const override {
1728 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
1729 }
1730};
1731} // namespace
1732
1733void WinX86_32TargetCodeGenInfo::setTargetAttributes(
1734 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
1735 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
1736 if (GV->isDeclaration())
1737 return;
1738 addStackProbeTargetAttributes(D, GV, CGM);
1739}
1740
1741namespace {
1742class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1743public:
1744 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1745 X86AVXABILevel AVXLevel)
1746 : TargetCodeGenInfo(std::make_unique<WinX86_64ABIInfo>(args&: CGT, args&: AVXLevel)) {
1747 SwiftInfo =
1748 std::make_unique<SwiftABIInfo>(args&: CGT, /*SwiftErrorInRegister=*/args: true);
1749 }
1750
1751 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1752 CodeGen::CodeGenModule &CGM) const override;
1753
1754 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
1755 return 7;
1756 }
1757
1758 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1759 llvm::Value *Address) const override {
1760 llvm::Value *Eight8 = llvm::ConstantInt::get(Ty: CGF.Int8Ty, V: 8);
1761
1762 // 0-15 are the 16 integer registers.
1763 // 16 is %rip.
1764 AssignToArrayRange(Builder&: CGF.Builder, Array: Address, Value: Eight8, FirstIndex: 0, LastIndex: 16);
1765 return false;
1766 }
1767
1768 void getDependentLibraryOption(llvm::StringRef Lib,
1769 llvm::SmallString<24> &Opt) const override {
1770 Opt = "/DEFAULTLIB:";
1771 Opt += qualifyWindowsLibrary(Lib);
1772 }
1773
1774 void getDetectMismatchOption(llvm::StringRef Name,
1775 llvm::StringRef Value,
1776 llvm::SmallString<32> &Opt) const override {
1777 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
1778 }
1779};
1780} // namespace
1781
1782void WinX86_64TargetCodeGenInfo::setTargetAttributes(
1783 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
1784 TargetCodeGenInfo::setTargetAttributes(D, GV, M&: CGM);
1785 if (GV->isDeclaration())
1786 return;
1787 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: D)) {
1788 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1789 llvm::Function *Fn = cast<llvm::Function>(Val: GV);
1790 Fn->addFnAttr(Kind: "stackrealign");
1791 }
1792
1793 addX86InterruptAttrs(FD, GV, CGM);
1794 }
1795
1796 addStackProbeTargetAttributes(D, GV, CGM);
1797}
1798
1799void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
1800 Class &Hi) const {
1801 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1802 //
1803 // (a) If one of the classes is Memory, the whole argument is passed in
1804 // memory.
1805 //
1806 // (b) If X87UP is not preceded by X87, the whole argument is passed in
1807 // memory.
1808 //
1809 // (c) If the size of the aggregate exceeds two eightbytes and the first
1810 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
1811 // argument is passed in memory. NOTE: This is necessary to keep the
1812 // ABI working for processors that don't support the __m256 type.
1813 //
1814 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
1815 //
1816 // Some of these are enforced by the merging logic. Others can arise
1817 // only with unions; for example:
1818 // union { _Complex double; unsigned; }
1819 //
1820 // Note that clauses (b) and (c) were added in 0.98.
1821 //
1822 if (Hi == Memory)
1823 Lo = Memory;
1824 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
1825 Lo = Memory;
1826 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
1827 Lo = Memory;
1828 if (Hi == SSEUp && Lo != SSE)
1829 Hi = SSE;
1830}
1831
1832static X86AVXABILevel getEffectiveX86AVXABILevel(CodeGenTypes &CGT,
1833 X86AVXABILevel GlobalAVXLevel,
1834 const FunctionDecl *FD) {
1835 // Always return global AVX level on PlayStation.
1836 if (CGT.getTarget().getTriple().isPS() ||
1837 CGT.getContext().getLangOpts().getClangABICompat() <=
1838 LangOptions::ClangABI::Ver23) {
1839 return GlobalAVXLevel;
1840 }
1841
1842 X86AVXABILevel Level = GlobalAVXLevel;
1843 // TargetVersionAttr does not apply to x86.
1844 // FIXME: Handling TargetClonesAttr and CPUSpecificAttr is intentionally
1845 // deferred to a follow-up.
1846 if (!FD || !FD->hasAttr<TargetAttr>())
1847 return Level;
1848
1849 llvm::StringMap<bool> FeatureMap;
1850 CGT.getCGM().getContext().getFunctionFeatureMap(FeatureMap, FD);
1851 if (FeatureMap.lookup(Key: "avx512f"))
1852 return std::max(a: Level, b: X86AVXABILevel::AVX512);
1853 if (FeatureMap.lookup(Key: "avx"))
1854 return std::max(a: Level, b: X86AVXABILevel::AVX);
1855 return Level;
1856}
1857
1858X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
1859 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
1860 // classified recursively so that always two fields are
1861 // considered. The resulting class is calculated according to
1862 // the classes of the fields in the eightbyte:
1863 //
1864 // (a) If both classes are equal, this is the resulting class.
1865 //
1866 // (b) If one of the classes is NO_CLASS, the resulting class is
1867 // the other class.
1868 //
1869 // (c) If one of the classes is MEMORY, the result is the MEMORY
1870 // class.
1871 //
1872 // (d) If one of the classes is INTEGER, the result is the
1873 // INTEGER.
1874 //
1875 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
1876 // MEMORY is used as class.
1877 //
1878 // (f) Otherwise class SSE is used.
1879
1880 // Accum should never be memory (we should have returned) or
1881 // ComplexX87 (because this cannot be passed in a structure).
1882 assert((Accum != Memory && Accum != ComplexX87) &&
1883 "Invalid accumulated classification during merge.");
1884 if (Accum == Field || Field == NoClass)
1885 return Accum;
1886 if (Field == Memory)
1887 return Memory;
1888 if (Accum == NoClass)
1889 return Field;
1890 if (Accum == Integer || Field == Integer)
1891 return Integer;
1892 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
1893 Accum == X87 || Accum == X87Up)
1894 return Memory;
1895 return SSE;
1896}
1897
1898void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase, Class &Lo,
1899 Class &Hi, bool isNamedArg, bool IsRegCall) const {
1900 // FIXME: This code can be simplified by introducing a simple value class for
1901 // Class pairs with appropriate constructor methods for the various
1902 // situations.
1903
1904 // FIXME: Some of the split computations are wrong; unaligned vectors
1905 // shouldn't be passed in registers for example, so there is no chance they
1906 // can straddle an eightbyte. Verify & simplify.
1907
1908 Lo = Hi = NoClass;
1909
1910 Class &Current = OffsetBase < 64 ? Lo : Hi;
1911 Current = Memory;
1912
1913 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
1914 BuiltinType::Kind k = BT->getKind();
1915
1916 if (k == BuiltinType::Void) {
1917 Current = NoClass;
1918 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
1919 Lo = Integer;
1920 Hi = Integer;
1921 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
1922 Current = Integer;
1923 } else if (k == BuiltinType::Float || k == BuiltinType::Double ||
1924 k == BuiltinType::Float16 || k == BuiltinType::BFloat16) {
1925 Current = SSE;
1926 } else if (k == BuiltinType::Float128) {
1927 Lo = SSE;
1928 Hi = SSEUp;
1929 } else if (k == BuiltinType::LongDouble) {
1930 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
1931 if (LDF == &llvm::APFloat::IEEEquad()) {
1932 Lo = SSE;
1933 Hi = SSEUp;
1934 } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
1935 Lo = X87;
1936 Hi = X87Up;
1937 } else if (LDF == &llvm::APFloat::IEEEdouble()) {
1938 Current = SSE;
1939 } else
1940 llvm_unreachable("unexpected long double representation!");
1941 }
1942 // FIXME: _Decimal32 and _Decimal64 are SSE.
1943 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
1944 return;
1945 }
1946
1947 if (const auto *ED = Ty->getAsEnumDecl()) {
1948 // Classify the underlying integer type.
1949 classify(Ty: ED->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
1950 return;
1951 }
1952
1953 if (Ty->hasPointerRepresentation()) {
1954 Current = Integer;
1955 return;
1956 }
1957
1958 if (Ty->isMemberPointerType()) {
1959 if (Ty->isMemberFunctionPointerType()) {
1960 if (Has64BitPointers) {
1961 // If Has64BitPointers, this is an {i64, i64}, so classify both
1962 // Lo and Hi now.
1963 Lo = Hi = Integer;
1964 } else {
1965 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
1966 // straddles an eightbyte boundary, Hi should be classified as well.
1967 uint64_t EB_FuncPtr = (OffsetBase) / 64;
1968 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
1969 if (EB_FuncPtr != EB_ThisAdj) {
1970 Lo = Hi = Integer;
1971 } else {
1972 Current = Integer;
1973 }
1974 }
1975 } else {
1976 Current = Integer;
1977 }
1978 return;
1979 }
1980
1981 if (const VectorType *VT = Ty->getAs<VectorType>()) {
1982 uint64_t Size = getContext().getTypeSize(T: VT);
1983 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
1984 // gcc passes the following as integer:
1985 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
1986 // 2 bytes - <2 x char>, <1 x short>
1987 // 1 byte - <1 x char>
1988 Current = Integer;
1989
1990 // If this type crosses an eightbyte boundary, it should be
1991 // split.
1992 uint64_t EB_Lo = (OffsetBase) / 64;
1993 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
1994 if (EB_Lo != EB_Hi)
1995 Hi = Lo;
1996 } else if (Size == 64) {
1997 QualType ElementType = VT->getElementType();
1998
1999 // gcc passes <1 x double> in memory. :(
2000 if (ElementType->isSpecificBuiltinType(K: BuiltinType::Double))
2001 return;
2002
2003 // gcc passes <1 x long long> as SSE but clang used to unconditionally
2004 // pass them as integer. For platforms where clang is the de facto
2005 // platform compiler, we must continue to use integer.
2006 if (!classifyIntegerMMXAsSSE() &&
2007 (ElementType->isSpecificBuiltinType(K: BuiltinType::LongLong) ||
2008 ElementType->isSpecificBuiltinType(K: BuiltinType::ULongLong) ||
2009 ElementType->isSpecificBuiltinType(K: BuiltinType::Long) ||
2010 ElementType->isSpecificBuiltinType(K: BuiltinType::ULong)))
2011 Current = Integer;
2012 else
2013 Current = SSE;
2014
2015 // If this type crosses an eightbyte boundary, it should be
2016 // split.
2017 if (OffsetBase && OffsetBase != 64)
2018 Hi = Lo;
2019 } else if (Size == 128 ||
2020 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
2021 QualType ElementType = VT->getElementType();
2022
2023 // gcc passes 256 and 512 bit <X x __int128> vectors in memory. :(
2024 if (passInt128VectorsInMem() && Size != 128 &&
2025 (ElementType->isSpecificBuiltinType(K: BuiltinType::Int128) ||
2026 ElementType->isSpecificBuiltinType(K: BuiltinType::UInt128)))
2027 return;
2028
2029 // Arguments of 256-bits are split into four eightbyte chunks. The
2030 // least significant one belongs to class SSE and all the others to class
2031 // SSEUP. The original Lo and Hi design considers that types can't be
2032 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2033 // This design isn't correct for 256-bits, but since there're no cases
2034 // where the upper parts would need to be inspected, avoid adding
2035 // complexity and just consider Hi to match the 64-256 part.
2036 //
2037 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2038 // registers if they are "named", i.e. not part of the "..." of a
2039 // variadic function.
2040 //
2041 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2042 // split into eight eightbyte chunks, one SSE and seven SSEUP.
2043 Lo = SSE;
2044 Hi = SSEUp;
2045 }
2046 return;
2047 }
2048
2049 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
2050 QualType ET = getContext().getCanonicalType(T: CT->getElementType());
2051
2052 uint64_t Size = getContext().getTypeSize(T: Ty);
2053 if (ET->isIntegralOrEnumerationType()) {
2054 if (Size <= 64)
2055 Current = Integer;
2056 else if (Size <= 128)
2057 Lo = Hi = Integer;
2058 } else if (ET->isFloat16Type() || ET == getContext().FloatTy ||
2059 ET->isBFloat16Type()) {
2060 Current = SSE;
2061 } else if (ET == getContext().DoubleTy) {
2062 Lo = Hi = SSE;
2063 } else if (ET == getContext().LongDoubleTy) {
2064 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2065 if (LDF == &llvm::APFloat::IEEEquad())
2066 Current = Memory;
2067 else if (LDF == &llvm::APFloat::x87DoubleExtended())
2068 Current = ComplexX87;
2069 else if (LDF == &llvm::APFloat::IEEEdouble())
2070 Lo = Hi = SSE;
2071 else
2072 llvm_unreachable("unexpected long double representation!");
2073 }
2074
2075 // If this complex type crosses an eightbyte boundary then it
2076 // should be split.
2077 uint64_t EB_Real = (OffsetBase) / 64;
2078 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(T: ET)) / 64;
2079 if (Hi == NoClass && EB_Real != EB_Imag)
2080 Hi = Lo;
2081
2082 return;
2083 }
2084
2085 if (const auto *EITy = Ty->getAs<BitIntType>()) {
2086 if (EITy->getNumBits() <= 64)
2087 Current = Integer;
2088 else if (EITy->getNumBits() <= 128)
2089 Lo = Hi = Integer;
2090 // Larger values need to get passed in memory.
2091 return;
2092 }
2093
2094 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(T: Ty)) {
2095 // Arrays are treated like structures.
2096
2097 uint64_t Size = getContext().getTypeSize(T: Ty);
2098
2099 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
2100 // than eight eightbytes, ..., it has class MEMORY.
2101 // regcall ABI doesn't have limitation to an object. The only limitation
2102 // is the free registers, which will be checked in computeInfo.
2103 if (!IsRegCall && Size > 512)
2104 return;
2105
2106 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2107 // fields, it has class MEMORY.
2108 //
2109 // Only need to check alignment of array base.
2110 if (OffsetBase % getContext().getTypeAlign(T: AT->getElementType()))
2111 return;
2112
2113 // Otherwise implement simplified merge. We could be smarter about
2114 // this, but it isn't worth it and would be harder to verify.
2115 Current = NoClass;
2116 uint64_t EltSize = getContext().getTypeSize(T: AT->getElementType());
2117 uint64_t ArraySize = AT->getZExtSize();
2118
2119 // The only case a 256-bit wide vector could be used is when the array
2120 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2121 // to work for sizes wider than 128, early check and fallback to memory.
2122 //
2123 if (Size > 128 &&
2124 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
2125 return;
2126
2127 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2128 Class FieldLo, FieldHi;
2129 classify(Ty: AT->getElementType(), OffsetBase: Offset, Lo&: FieldLo, Hi&: FieldHi, isNamedArg);
2130 Lo = merge(Accum: Lo, Field: FieldLo);
2131 Hi = merge(Accum: Hi, Field: FieldHi);
2132 if (Lo == Memory || Hi == Memory)
2133 break;
2134 }
2135
2136 postMerge(AggregateSize: Size, Lo, Hi);
2137 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
2138 return;
2139 }
2140
2141 if (const RecordType *RT = Ty->getAsCanonical<RecordType>()) {
2142 uint64_t Size = getContext().getTypeSize(T: Ty);
2143
2144 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
2145 // than eight eightbytes, ..., it has class MEMORY.
2146 if (Size > 512)
2147 return;
2148
2149 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2150 // copy constructor or a non-trivial destructor, it is passed by invisible
2151 // reference.
2152 if (getRecordArgABI(RT, CXXABI&: getCXXABI()))
2153 return;
2154
2155 const RecordDecl *RD = RT->getDecl()->getDefinitionOrSelf();
2156
2157 // Assume variable sized types are passed in memory.
2158 if (RD->hasFlexibleArrayMember())
2159 return;
2160
2161 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(D: RD);
2162
2163 // Reset Lo class, this will be recomputed.
2164 Current = NoClass;
2165
2166 // If this is a C++ record, classify the bases first.
2167 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
2168 for (const auto &I : CXXRD->bases()) {
2169 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
2170 "Unexpected base class!");
2171 const auto *Base = I.getType()->castAsCXXRecordDecl();
2172 // Classify this field.
2173 //
2174 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2175 // single eightbyte, each is classified separately. Each eightbyte gets
2176 // initialized to class NO_CLASS.
2177 Class FieldLo, FieldHi;
2178 uint64_t Offset =
2179 OffsetBase + getContext().toBits(CharSize: Layout.getBaseClassOffset(Base));
2180 classify(Ty: I.getType(), OffsetBase: Offset, Lo&: FieldLo, Hi&: FieldHi, isNamedArg);
2181 Lo = merge(Accum: Lo, Field: FieldLo);
2182 Hi = merge(Accum: Hi, Field: FieldHi);
2183 if (returnCXXRecordGreaterThan128InMem() &&
2184 !isEmptyRecord(Context&: getContext(), T: I.getType(), AllowArrays: true) &&
2185 (Size > 128 && (Size != getContext().getTypeSize(T: I.getType()) ||
2186 Size > getNativeVectorSizeForAVXABI(AVXLevel)))) {
2187 // The only case a 256(or 512)-bit wide vector could be used to return
2188 // is when CXX record contains a single 256(or 512)-bit element.
2189 Lo = Memory;
2190 }
2191 if (Lo == Memory || Hi == Memory) {
2192 postMerge(AggregateSize: Size, Lo, Hi);
2193 return;
2194 }
2195 }
2196 }
2197
2198 // Classify the fields one at a time, merging the results.
2199 unsigned idx = 0;
2200 bool UseClang11Compat = getContext().getLangOpts().isCompatibleWith(
2201 Version: LangOptions::ClangABI::Ver11) ||
2202 getContext().getTargetInfo().getTriple().isPS();
2203 bool IsUnion = RT->isUnionType() && !UseClang11Compat;
2204
2205 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2206 i != e; ++i, ++idx) {
2207 uint64_t Offset = OffsetBase + Layout.getFieldOffset(FieldNo: idx);
2208 bool BitField = i->isBitField();
2209
2210 // Ignore padding bit-fields.
2211 if (BitField && i->isUnnamedBitField())
2212 continue;
2213
2214 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2215 // eight eightbytes, or it contains unaligned fields, it has class MEMORY.
2216 //
2217 // The only case a 256-bit or a 512-bit wide vector could be used is when
2218 // the struct contains a single 256-bit or 512-bit element. Early check
2219 // and fallback to memory.
2220 //
2221 // FIXME: Extended the Lo and Hi logic properly to work for size wider
2222 // than 128.
2223 if (Size > 128 &&
2224 ((!IsUnion && Size != getContext().getTypeSize(T: i->getType())) ||
2225 Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
2226 Lo = Memory;
2227 postMerge(AggregateSize: Size, Lo, Hi);
2228 return;
2229 }
2230
2231 bool IsInMemory =
2232 Offset % getContext().getTypeAlign(T: i->getType().getCanonicalType());
2233 // Note, skip this test for bit-fields, see below.
2234 if (!BitField && IsInMemory) {
2235 Lo = Memory;
2236 postMerge(AggregateSize: Size, Lo, Hi);
2237 return;
2238 }
2239
2240 // Classify this field.
2241 //
2242 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2243 // exceeds a single eightbyte, each is classified
2244 // separately. Each eightbyte gets initialized to class
2245 // NO_CLASS.
2246 Class FieldLo, FieldHi;
2247
2248 // Bit-fields require special handling, they do not force the
2249 // structure to be passed in memory even if unaligned, and
2250 // therefore they can straddle an eightbyte.
2251 if (BitField) {
2252 assert(!i->isUnnamedBitField());
2253 uint64_t Offset = OffsetBase + Layout.getFieldOffset(FieldNo: idx);
2254 uint64_t Size = i->getBitWidthValue();
2255
2256 uint64_t EB_Lo = Offset / 64;
2257 uint64_t EB_Hi = (Offset + Size - 1) / 64;
2258
2259 if (EB_Lo) {
2260 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2261 FieldLo = NoClass;
2262 FieldHi = Integer;
2263 } else {
2264 FieldLo = Integer;
2265 FieldHi = EB_Hi ? Integer : NoClass;
2266 }
2267 } else
2268 classify(Ty: i->getType(), OffsetBase: Offset, Lo&: FieldLo, Hi&: FieldHi, isNamedArg);
2269 Lo = merge(Accum: Lo, Field: FieldLo);
2270 Hi = merge(Accum: Hi, Field: FieldHi);
2271 if (Lo == Memory || Hi == Memory)
2272 break;
2273 }
2274
2275 postMerge(AggregateSize: Size, Lo, Hi);
2276 }
2277}
2278
2279ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
2280 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2281 // place naturally.
2282 if (!isAggregateTypeForABI(T: Ty)) {
2283 // Treat an enum type as its underlying type.
2284 if (const auto *ED = Ty->getAsEnumDecl())
2285 Ty = ED->getIntegerType();
2286
2287 if (Ty->isBitIntType())
2288 return getNaturalAlignIndirect(Ty, AddrSpace: getDataLayout().getAllocaAddrSpace());
2289
2290 llvm::Type *IRTy = CGT.ConvertType(T: Ty);
2291 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty, T: IRTy)
2292 : ABIArgInfo::getDirect(T: IRTy));
2293 }
2294
2295 return getNaturalAlignIndirect(Ty, AddrSpace: getDataLayout().getAllocaAddrSpace());
2296}
2297
2298bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2299 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2300 uint64_t Size = getContext().getTypeSize(T: VecTy);
2301 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
2302 if (Size <= 64 || Size > LargestVector)
2303 return true;
2304 QualType EltTy = VecTy->getElementType();
2305 if (passInt128VectorsInMem() &&
2306 (EltTy->isSpecificBuiltinType(K: BuiltinType::Int128) ||
2307 EltTy->isSpecificBuiltinType(K: BuiltinType::UInt128)))
2308 return true;
2309 }
2310
2311 return false;
2312}
2313
2314ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2315 unsigned freeIntRegs) const {
2316 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2317 // place naturally.
2318 //
2319 // This assumption is optimistic, as there could be free registers available
2320 // when we need to pass this argument in memory, and LLVM could try to pass
2321 // the argument in the free register. This does not seem to happen currently,
2322 // but this code would be much safer if we could mark the argument with
2323 // 'onstack'. See PR12193.
2324 if (!isAggregateTypeForABI(T: Ty) && !IsIllegalVectorType(Ty) &&
2325 !Ty->isBitIntType()) {
2326 // Treat an enum type as its underlying type.
2327 if (const auto *ED = Ty->getAsEnumDecl())
2328 Ty = ED->getIntegerType();
2329
2330 llvm::Type *IRTy = CGT.ConvertType(T: Ty);
2331 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty, T: IRTy)
2332 : ABIArgInfo::getDirect(T: IRTy));
2333 }
2334
2335 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(T: Ty, CXXABI&: getCXXABI()))
2336 return getNaturalAlignIndirect(Ty, AddrSpace: getDataLayout().getAllocaAddrSpace(),
2337 ByVal: RAA == CGCXXABI::RAA_DirectInMemory);
2338
2339 // Compute the byval alignment. We specify the alignment of the byval in all
2340 // cases so that the mid-level optimizer knows the alignment of the byval.
2341 unsigned Align = std::max(a: getContext().getTypeAlign(T: Ty) / 8, b: 8U);
2342
2343 // Attempt to avoid passing indirect results using byval when possible. This
2344 // is important for good codegen.
2345 //
2346 // We do this by coercing the value into a scalar type which the backend can
2347 // handle naturally (i.e., without using byval).
2348 //
2349 // For simplicity, we currently only do this when we have exhausted all of the
2350 // free integer registers. Doing this when there are free integer registers
2351 // would require more care, as we would have to ensure that the coerced value
2352 // did not claim the unused register. That would require either reording the
2353 // arguments to the function (so that any subsequent inreg values came first),
2354 // or only doing this optimization when there were no following arguments that
2355 // might be inreg.
2356 //
2357 // We currently expect it to be rare (particularly in well written code) for
2358 // arguments to be passed on the stack when there are still free integer
2359 // registers available (this would typically imply large structs being passed
2360 // by value), so this seems like a fair tradeoff for now.
2361 //
2362 // We can revisit this if the backend grows support for 'onstack' parameter
2363 // attributes. See PR12193.
2364 if (freeIntRegs == 0) {
2365 uint64_t Size = getContext().getTypeSize(T: Ty);
2366
2367 // If this type fits in an eightbyte, coerce it into the matching integral
2368 // type, which will end up on the stack (with alignment 8).
2369 if (Align == 8 && Size <= 64)
2370 return ABIArgInfo::getDirect(T: llvm::IntegerType::get(C&: getVMContext(),
2371 NumBits: Size));
2372 }
2373
2374 return ABIArgInfo::getIndirect(Alignment: CharUnits::fromQuantity(Quantity: Align),
2375 AddrSpace: getDataLayout().getAllocaAddrSpace());
2376}
2377
2378/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2379/// register. Pick an LLVM IR type that will be passed as a vector register.
2380llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
2381 // Wrapper structs/arrays that only contain vectors are passed just like
2382 // vectors; strip them off if present.
2383 if (const Type *InnerTy = isSingleElementStruct(T: Ty, Context&: getContext()))
2384 Ty = QualType(InnerTy, 0);
2385
2386 llvm::Type *IRType = CGT.ConvertType(T: Ty);
2387 if (isa<llvm::VectorType>(Val: IRType)) {
2388 // Don't pass vXi128 vectors in their native type, the backend can't
2389 // legalize them.
2390 if (passInt128VectorsInMem() &&
2391 cast<llvm::VectorType>(Val: IRType)->getElementType()->isIntegerTy(BitWidth: 128)) {
2392 // Use a vXi64 vector.
2393 uint64_t Size = getContext().getTypeSize(T: Ty);
2394 return llvm::FixedVectorType::get(ElementType: llvm::Type::getInt64Ty(C&: getVMContext()),
2395 NumElts: Size / 64);
2396 }
2397
2398 return IRType;
2399 }
2400
2401 if (IRType->getTypeID() == llvm::Type::FP128TyID)
2402 return IRType;
2403
2404 // We couldn't find the preferred IR vector type for 'Ty'.
2405 uint64_t Size = getContext().getTypeSize(T: Ty);
2406 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
2407
2408
2409 // Return a LLVM IR vector type based on the size of 'Ty'.
2410 return llvm::FixedVectorType::get(ElementType: llvm::Type::getDoubleTy(C&: getVMContext()),
2411 NumElts: Size / 64);
2412}
2413
2414/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2415/// is known to either be off the end of the specified type or being in
2416/// alignment padding. The user type specified is known to be at most 128 bits
2417/// in size, and have passed through X86_64ABIInfo::classify with a successful
2418/// classification that put one of the two halves in the INTEGER class.
2419///
2420/// It is conservatively correct to return false.
2421static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2422 unsigned EndBit, ASTContext &Context) {
2423 // If the bytes being queried are off the end of the type, there is no user
2424 // data hiding here. This handles analysis of builtins, vectors and other
2425 // types that don't contain interesting padding.
2426 unsigned TySize = (unsigned)Context.getTypeSize(T: Ty);
2427 if (TySize <= StartBit)
2428 return true;
2429
2430 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T: Ty)) {
2431 unsigned EltSize = (unsigned)Context.getTypeSize(T: AT->getElementType());
2432 unsigned NumElts = (unsigned)AT->getZExtSize();
2433
2434 // Check each element to see if the element overlaps with the queried range.
2435 for (unsigned i = 0; i != NumElts; ++i) {
2436 // If the element is after the span we care about, then we're done..
2437 unsigned EltOffset = i*EltSize;
2438 if (EltOffset >= EndBit) break;
2439
2440 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2441 if (!BitsContainNoUserData(Ty: AT->getElementType(), StartBit: EltStart,
2442 EndBit: EndBit-EltOffset, Context))
2443 return false;
2444 }
2445 // If it overlaps no elements, then it is safe to process as padding.
2446 return true;
2447 }
2448
2449 if (const auto *RD = Ty->getAsRecordDecl()) {
2450 const ASTRecordLayout &Layout = Context.getASTRecordLayout(D: RD);
2451
2452 // If this is a C++ record, check the bases first.
2453 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
2454 for (const auto &I : CXXRD->bases()) {
2455 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
2456 "Unexpected base class!");
2457 const auto *Base = I.getType()->castAsCXXRecordDecl();
2458
2459 // If the base is after the span we care about, ignore it.
2460 unsigned BaseOffset = Context.toBits(CharSize: Layout.getBaseClassOffset(Base));
2461 if (BaseOffset >= EndBit) continue;
2462
2463 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
2464 if (!BitsContainNoUserData(Ty: I.getType(), StartBit: BaseStart,
2465 EndBit: EndBit-BaseOffset, Context))
2466 return false;
2467 }
2468 }
2469
2470 // Verify that no field has data that overlaps the region of interest. Yes
2471 // this could be sped up a lot by being smarter about queried fields,
2472 // however we're only looking at structs up to 16 bytes, so we don't care
2473 // much.
2474 unsigned idx = 0;
2475 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2476 i != e; ++i, ++idx) {
2477 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(FieldNo: idx);
2478
2479 // If we found a field after the region we care about, then we're done.
2480 if (FieldOffset >= EndBit) break;
2481
2482 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2483 if (!BitsContainNoUserData(Ty: i->getType(), StartBit: FieldStart, EndBit: EndBit-FieldOffset,
2484 Context))
2485 return false;
2486 }
2487
2488 // If nothing in this record overlapped the area of interest, then we're
2489 // clean.
2490 return true;
2491 }
2492
2493 return false;
2494}
2495
2496/// getFPTypeAtOffset - Return a floating point type at the specified offset.
2497static llvm::Type *getFPTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
2498 const llvm::DataLayout &TD) {
2499 if (IROffset == 0 && IRType->isFloatingPointTy())
2500 return IRType;
2501
2502 // If this is a struct, recurse into the field at the specified offset.
2503 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(Val: IRType)) {
2504 if (!STy->getNumContainedTypes())
2505 return nullptr;
2506
2507 const llvm::StructLayout *SL = TD.getStructLayout(Ty: STy);
2508 unsigned Elt = SL->getElementContainingOffset(FixedOffset: IROffset);
2509 IROffset -= SL->getElementOffset(Idx: Elt);
2510 return getFPTypeAtOffset(IRType: STy->getElementType(N: Elt), IROffset, TD);
2511 }
2512
2513 // If this is an array, recurse into the field at the specified offset.
2514 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(Val: IRType)) {
2515 llvm::Type *EltTy = ATy->getElementType();
2516 unsigned EltSize = TD.getTypeAllocSize(Ty: EltTy);
2517 IROffset -= IROffset / EltSize * EltSize;
2518 return getFPTypeAtOffset(IRType: EltTy, IROffset, TD);
2519 }
2520
2521 return nullptr;
2522}
2523
2524/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2525/// low 8 bytes of an XMM register, corresponding to the SSE class.
2526llvm::Type *X86_64ABIInfo::
2527GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
2528 QualType SourceTy, unsigned SourceOffset) const {
2529 const llvm::DataLayout &TD = getDataLayout();
2530 unsigned SourceSize =
2531 (unsigned)getContext().getTypeSize(T: SourceTy) / 8 - SourceOffset;
2532 llvm::Type *T0 = getFPTypeAtOffset(IRType, IROffset, TD);
2533 if (!T0 || T0->isDoubleTy())
2534 return llvm::Type::getDoubleTy(C&: getVMContext());
2535
2536 // Get the adjacent FP type.
2537 llvm::Type *T1 = nullptr;
2538 unsigned T0Size = TD.getTypeAllocSize(Ty: T0);
2539 if (SourceSize > T0Size)
2540 T1 = getFPTypeAtOffset(IRType, IROffset: IROffset + T0Size, TD);
2541 if (T1 == nullptr) {
2542 // Check if IRType is a half/bfloat + float. float type will be in IROffset+4 due
2543 // to its alignment.
2544 if (T0->is16bitFPTy() && SourceSize > 4)
2545 T1 = getFPTypeAtOffset(IRType, IROffset: IROffset + 4, TD);
2546 // If we can't get a second FP type, return a simple half or float.
2547 // avx512fp16-abi.c:pr51813_2 shows it works to return float for
2548 // {float, i8} too.
2549 if (T1 == nullptr)
2550 return T0;
2551 }
2552
2553 if (T0->isFloatTy() && T1->isFloatTy())
2554 return llvm::FixedVectorType::get(ElementType: T0, NumElts: 2);
2555
2556 if (T0->is16bitFPTy() && T1->is16bitFPTy()) {
2557 llvm::Type *T2 = nullptr;
2558 if (SourceSize > 4)
2559 T2 = getFPTypeAtOffset(IRType, IROffset: IROffset + 4, TD);
2560 if (T2 == nullptr)
2561 return llvm::FixedVectorType::get(ElementType: T0, NumElts: 2);
2562 return llvm::FixedVectorType::get(ElementType: T0, NumElts: 4);
2563 }
2564
2565 if (T0->is16bitFPTy() || T1->is16bitFPTy())
2566 return llvm::FixedVectorType::get(ElementType: llvm::Type::getHalfTy(C&: getVMContext()), NumElts: 4);
2567
2568 return llvm::Type::getDoubleTy(C&: getVMContext());
2569}
2570
2571/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2572/// one or more 8-byte GPRs. This means that we either have a scalar or we are
2573/// talking about the high and/or low part of an up-to-16-byte struct. This
2574/// routine picks the best LLVM IR type to represent this, which may be i64 or
2575/// may be anything else that the backend will pass in GPRs that works better
2576/// (e.g. i8, %foo*, etc).
2577///
2578/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2579/// the source type. IROffset is an offset in bytes into the LLVM IR type that
2580/// the 8-byte value references. PrefType may be null.
2581///
2582/// SourceTy is the source-level type for the entire argument. SourceOffset is
2583/// an offset into this that we're processing (which is always either 0 or 8).
2584///
2585llvm::Type *X86_64ABIInfo::
2586GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
2587 QualType SourceTy, unsigned SourceOffset) const {
2588 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2589 // returning an 8-byte unit starting with it. See if we can safely use it.
2590 if (IROffset == 0) {
2591 // Pointers and int64's always fill the 8-byte unit.
2592 if ((isa<llvm::PointerType>(Val: IRType) && Has64BitPointers) ||
2593 IRType->isIntegerTy(BitWidth: 64))
2594 return IRType;
2595
2596 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2597 // goodness in the source type is just tail padding. This is allowed to
2598 // kick in for struct {double,int} on the int, but not on
2599 // struct{double,int,int} because we wouldn't return the second int. We
2600 // have to do this analysis on the source type because we can't depend on
2601 // unions being lowered a specific way etc.
2602 if (IRType->isIntegerTy(BitWidth: 8) || IRType->isIntegerTy(BitWidth: 16) ||
2603 IRType->isIntegerTy(BitWidth: 32) ||
2604 (isa<llvm::PointerType>(Val: IRType) && !Has64BitPointers)) {
2605 unsigned BitWidth = isa<llvm::PointerType>(Val: IRType) ? 32 :
2606 cast<llvm::IntegerType>(Val: IRType)->getBitWidth();
2607
2608 if (BitsContainNoUserData(Ty: SourceTy, StartBit: SourceOffset*8+BitWidth,
2609 EndBit: SourceOffset*8+64, Context&: getContext()))
2610 return IRType;
2611 }
2612 }
2613
2614 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(Val: IRType)) {
2615 // If this is a struct, recurse into the field at the specified offset.
2616 const llvm::StructLayout *SL = getDataLayout().getStructLayout(Ty: STy);
2617 if (IROffset < SL->getSizeInBytes()) {
2618 unsigned FieldIdx = SL->getElementContainingOffset(FixedOffset: IROffset);
2619 IROffset -= SL->getElementOffset(Idx: FieldIdx);
2620
2621 return GetINTEGERTypeAtOffset(IRType: STy->getElementType(N: FieldIdx), IROffset,
2622 SourceTy, SourceOffset);
2623 }
2624 }
2625
2626 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(Val: IRType)) {
2627 llvm::Type *EltTy = ATy->getElementType();
2628 unsigned EltSize = getDataLayout().getTypeAllocSize(Ty: EltTy);
2629 unsigned EltOffset = IROffset/EltSize*EltSize;
2630 return GetINTEGERTypeAtOffset(IRType: EltTy, IROffset: IROffset-EltOffset, SourceTy,
2631 SourceOffset);
2632 }
2633
2634 // if we have a 128-bit integer, we can pass it safely using an i128
2635 // so we return that
2636 if (IRType->isIntegerTy(BitWidth: 128)) {
2637 assert(IROffset == 0);
2638 return IRType;
2639 }
2640
2641 // Okay, we don't have any better idea of what to pass, so we pass this in an
2642 // integer register that isn't too big to fit the rest of the struct.
2643 unsigned TySizeInBytes =
2644 (unsigned)getContext().getTypeSizeInChars(T: SourceTy).getQuantity();
2645
2646 assert(TySizeInBytes != SourceOffset && "Empty field?");
2647
2648 // It is always safe to classify this as an integer type up to i64 that
2649 // isn't larger than the structure.
2650 return llvm::IntegerType::get(C&: getVMContext(),
2651 NumBits: std::min(a: TySizeInBytes-SourceOffset, b: 8U)*8);
2652}
2653
2654
2655/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2656/// be used as elements of a two register pair to pass or return, return a
2657/// first class aggregate to represent them. For example, if the low part of
2658/// a by-value argument should be passed as i32* and the high part as float,
2659/// return {i32*, float}.
2660static llvm::Type *
2661GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
2662 const llvm::DataLayout &TD) {
2663 // In order to correctly satisfy the ABI, we need to the high part to start
2664 // at offset 8. If the high and low parts we inferred are both 4-byte types
2665 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2666 // the second element at offset 8. Check for this:
2667 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Ty: Lo);
2668 llvm::Align HiAlign = TD.getABITypeAlign(Ty: Hi);
2669 unsigned HiStart = llvm::alignTo(Size: LoSize, A: HiAlign);
2670 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
2671
2672 // To handle this, we have to increase the size of the low part so that the
2673 // second element will start at an 8 byte offset. We can't increase the size
2674 // of the second element because it might make us access off the end of the
2675 // struct.
2676 if (HiStart != 8) {
2677 // There are usually two sorts of types the ABI generation code can produce
2678 // for the low part of a pair that aren't 8 bytes in size: half, float or
2679 // i8/i16/i32. This can also include pointers when they are 32-bit (X32).
2680 // Promote these to a larger type.
2681 if (Lo->isHalfTy() || Lo->isFloatTy())
2682 Lo = llvm::Type::getDoubleTy(C&: Lo->getContext());
2683 else {
2684 assert((Lo->isIntegerTy() || Lo->isPointerTy())
2685 && "Invalid/unknown lo type");
2686 Lo = llvm::Type::getInt64Ty(C&: Lo->getContext());
2687 }
2688 }
2689
2690 llvm::StructType *Result = llvm::StructType::get(elt1: Lo, elts: Hi);
2691
2692 // Verify that the second element is at an 8-byte offset.
2693 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2694 "Invalid x86-64 argument pair!");
2695 return Result;
2696}
2697
2698ABIArgInfo X86_64ABIInfo::classifyReturnType(QualType RetTy) const {
2699 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2700 // classification algorithm.
2701 X86_64ABIInfo::Class Lo, Hi;
2702 classify(Ty: RetTy, OffsetBase: 0, Lo, Hi, /*isNamedArg*/ true);
2703
2704 // Check some invariants.
2705 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
2706 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2707
2708 llvm::Type *ResType = nullptr;
2709 switch (Lo) {
2710 case NoClass:
2711 if (Hi == NoClass)
2712 return ABIArgInfo::getIgnore();
2713 // If the low part is just padding, it takes no register, leave ResType
2714 // null.
2715 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2716 "Unknown missing lo part");
2717 break;
2718
2719 case SSEUp:
2720 case X87Up:
2721 llvm_unreachable("Invalid classification for lo word.");
2722
2723 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2724 // hidden argument.
2725 case Memory:
2726 return getIndirectReturnResult(Ty: RetTy);
2727
2728 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2729 // available register of the sequence %rax, %rdx is used.
2730 case Integer:
2731 ResType = GetINTEGERTypeAtOffset(IRType: CGT.ConvertType(T: RetTy), IROffset: 0, SourceTy: RetTy, SourceOffset: 0);
2732
2733 // If we have a sign or zero extended integer, make sure to return Extend
2734 // so that the parameter gets the right LLVM IR attributes.
2735 if (Hi == NoClass && isa<llvm::IntegerType>(Val: ResType)) {
2736 // Treat an enum type as its underlying type.
2737 if (const auto *ED = RetTy->getAsEnumDecl())
2738 RetTy = ED->getIntegerType();
2739
2740 if (RetTy->isIntegralOrEnumerationType() &&
2741 isPromotableIntegerTypeForABI(Ty: RetTy))
2742 return ABIArgInfo::getExtend(Ty: RetTy);
2743 }
2744
2745 if (ResType->isIntegerTy(BitWidth: 128)) {
2746 // i128 are passed directly
2747 assert(Hi == Integer);
2748 return ABIArgInfo::getDirect(T: ResType);
2749 }
2750 break;
2751
2752 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2753 // available SSE register of the sequence %xmm0, %xmm1 is used.
2754 case SSE:
2755 ResType = GetSSETypeAtOffset(IRType: CGT.ConvertType(T: RetTy), IROffset: 0, SourceTy: RetTy, SourceOffset: 0);
2756 break;
2757
2758 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2759 // returned on the X87 stack in %st0 as 80-bit x87 number.
2760 case X87:
2761 ResType = llvm::Type::getX86_FP80Ty(C&: getVMContext());
2762 break;
2763
2764 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2765 // part of the value is returned in %st0 and the imaginary part in
2766 // %st1.
2767 case ComplexX87:
2768 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
2769 ResType = llvm::StructType::get(elt1: llvm::Type::getX86_FP80Ty(C&: getVMContext()),
2770 elts: llvm::Type::getX86_FP80Ty(C&: getVMContext()));
2771 break;
2772 }
2773
2774 llvm::Type *HighPart = nullptr;
2775 switch (Hi) {
2776 // Memory was handled previously and X87 should
2777 // never occur as a hi class.
2778 case Memory:
2779 case X87:
2780 llvm_unreachable("Invalid classification for hi word.");
2781
2782 case ComplexX87: // Previously handled.
2783 case NoClass:
2784 break;
2785
2786 case Integer:
2787 HighPart = GetINTEGERTypeAtOffset(IRType: CGT.ConvertType(T: RetTy), IROffset: 8, SourceTy: RetTy, SourceOffset: 8);
2788 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2789 return ABIArgInfo::getDirect(T: HighPart, Offset: 8);
2790 break;
2791 case SSE:
2792 HighPart = GetSSETypeAtOffset(IRType: CGT.ConvertType(T: RetTy), IROffset: 8, SourceTy: RetTy, SourceOffset: 8);
2793 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2794 return ABIArgInfo::getDirect(T: HighPart, Offset: 8);
2795 break;
2796
2797 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
2798 // is passed in the next available eightbyte chunk if the last used
2799 // vector register.
2800 //
2801 // SSEUP should always be preceded by SSE, just widen.
2802 case SSEUp:
2803 assert(Lo == SSE && "Unexpected SSEUp classification.");
2804 ResType = GetByteVectorType(Ty: RetTy);
2805 break;
2806
2807 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2808 // returned together with the previous X87 value in %st0.
2809 case X87Up:
2810 // If X87Up is preceded by X87, we don't need to do
2811 // anything. However, in some cases with unions it may not be
2812 // preceded by X87. In such situations we follow gcc and pass the
2813 // extra bits in an SSE reg.
2814 if (Lo != X87) {
2815 HighPart = GetSSETypeAtOffset(IRType: CGT.ConvertType(T: RetTy), IROffset: 8, SourceTy: RetTy, SourceOffset: 8);
2816 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2817 return ABIArgInfo::getDirect(T: HighPart, Offset: 8);
2818 }
2819 break;
2820 }
2821
2822 // If a high part was specified, merge it together with the low part. It is
2823 // known to pass in the high eightbyte of the result. We do this by forming a
2824 // first class struct aggregate with the high and low part: {low, high}
2825 if (HighPart)
2826 ResType = GetX86_64ByValArgumentPair(Lo: ResType, Hi: HighPart, TD: getDataLayout());
2827
2828 return ABIArgInfo::getDirect(T: ResType);
2829}
2830
2831ABIArgInfo
2832X86_64ABIInfo::classifyArgumentType(QualType Ty, unsigned freeIntRegs,
2833 unsigned &neededInt, unsigned &neededSSE,
2834 bool isNamedArg, bool IsRegCall) const {
2835 Ty = useFirstFieldIfTransparentUnion(Ty);
2836
2837 X86_64ABIInfo::Class Lo, Hi;
2838 classify(Ty, OffsetBase: 0, Lo, Hi, isNamedArg, IsRegCall);
2839
2840 // Check some invariants.
2841 // FIXME: Enforce these by construction.
2842 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
2843 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2844
2845 neededInt = 0;
2846 neededSSE = 0;
2847 llvm::Type *ResType = nullptr;
2848 switch (Lo) {
2849 case NoClass:
2850 if (Hi == NoClass)
2851 return ABIArgInfo::getIgnore();
2852 // If the low part is just padding, it takes no register, leave ResType
2853 // null.
2854 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2855 "Unknown missing lo part");
2856 break;
2857
2858 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2859 // on the stack.
2860 case Memory:
2861
2862 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
2863 // COMPLEX_X87, it is passed in memory.
2864 case X87:
2865 case ComplexX87:
2866 if (getRecordArgABI(T: Ty, CXXABI&: getCXXABI()) == CGCXXABI::RAA_Indirect)
2867 ++neededInt;
2868 return getIndirectResult(Ty, freeIntRegs);
2869
2870 case SSEUp:
2871 case X87Up:
2872 llvm_unreachable("Invalid classification for lo word.");
2873
2874 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
2875 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
2876 // and %r9 is used.
2877 case Integer:
2878 ++neededInt;
2879
2880 // Pick an 8-byte type based on the preferred type.
2881 ResType = GetINTEGERTypeAtOffset(IRType: CGT.ConvertType(T: Ty), IROffset: 0, SourceTy: Ty, SourceOffset: 0);
2882
2883 // If we have a sign or zero extended integer, make sure to return Extend
2884 // so that the parameter gets the right LLVM IR attributes.
2885 if (Hi == NoClass && isa<llvm::IntegerType>(Val: ResType)) {
2886 // Treat an enum type as its underlying type.
2887 if (const auto *ED = Ty->getAsEnumDecl())
2888 Ty = ED->getIntegerType();
2889
2890 if (Ty->isIntegralOrEnumerationType() &&
2891 isPromotableIntegerTypeForABI(Ty))
2892 return ABIArgInfo::getExtend(Ty, T: CGT.ConvertType(T: Ty));
2893 }
2894
2895 if (ResType->isIntegerTy(BitWidth: 128)) {
2896 assert(Hi == Integer);
2897 ++neededInt;
2898 return ABIArgInfo::getDirect(T: ResType);
2899 }
2900 break;
2901
2902 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
2903 // available SSE register is used, the registers are taken in the
2904 // order from %xmm0 to %xmm7.
2905 case SSE: {
2906 llvm::Type *IRType = CGT.ConvertType(T: Ty);
2907 ResType = GetSSETypeAtOffset(IRType, IROffset: 0, SourceTy: Ty, SourceOffset: 0);
2908 ++neededSSE;
2909 break;
2910 }
2911 }
2912
2913 llvm::Type *HighPart = nullptr;
2914 switch (Hi) {
2915 // Memory was handled previously, ComplexX87 and X87 should
2916 // never occur as hi classes, and X87Up must be preceded by X87,
2917 // which is passed in memory.
2918 case Memory:
2919 case X87:
2920 case ComplexX87:
2921 llvm_unreachable("Invalid classification for hi word.");
2922
2923 case NoClass: break;
2924
2925 case Integer:
2926 ++neededInt;
2927 // Pick an 8-byte type based on the preferred type.
2928 HighPart = GetINTEGERTypeAtOffset(IRType: CGT.ConvertType(T: Ty), IROffset: 8, SourceTy: Ty, SourceOffset: 8);
2929
2930 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2931 return ABIArgInfo::getDirect(T: HighPart, Offset: 8);
2932 break;
2933
2934 // X87Up generally doesn't occur here (long double is passed in
2935 // memory), except in situations involving unions.
2936 case X87Up:
2937 case SSE:
2938 ++neededSSE;
2939 HighPart = GetSSETypeAtOffset(IRType: CGT.ConvertType(T: Ty), IROffset: 8, SourceTy: Ty, SourceOffset: 8);
2940
2941 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2942 return ABIArgInfo::getDirect(T: HighPart, Offset: 8);
2943 break;
2944
2945 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
2946 // eightbyte is passed in the upper half of the last used SSE
2947 // register. This only happens when 128-bit vectors are passed.
2948 case SSEUp:
2949 assert(Lo == SSE && "Unexpected SSEUp classification");
2950 ResType = GetByteVectorType(Ty);
2951 break;
2952 }
2953
2954 // If a high part was specified, merge it together with the low part. It is
2955 // known to pass in the high eightbyte of the result. We do this by forming a
2956 // first class struct aggregate with the high and low part: {low, high}
2957 if (HighPart)
2958 ResType = GetX86_64ByValArgumentPair(Lo: ResType, Hi: HighPart, TD: getDataLayout());
2959
2960 return ABIArgInfo::getDirect(T: ResType);
2961}
2962
2963// Returns true if the struct can be passed directly in registers. If so, the
2964// number of registers required will be returned in `NeededInt` and `NeededSSE`,
2965// and `CoerceElts` will contain an expanded sequence of LLVM IR types that each
2966// field should coerce to.
2967bool X86_64ABIInfo::passRegCallStructTypeDirectly(
2968 QualType Ty, SmallVectorImpl<llvm::Type *> &CoerceElts, unsigned &NeededInt,
2969 unsigned &NeededSSE, unsigned &MaxVectorWidth) const {
2970
2971 auto *RD =
2972 cast<RecordType>(Val: Ty.getCanonicalType())->getDecl()->getDefinitionOrSelf();
2973 if (RD->hasFlexibleArrayMember())
2974 return false;
2975
2976 // Classify the bases.
2977 if (auto CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
2978 if (CXXRD->isDynamicClass())
2979 return false;
2980
2981 for (const auto &I : CXXRD->bases()) {
2982 QualType BaseTy = I.getType();
2983 if (isEmptyRecord(Context&: getContext(), T: BaseTy, AllowArrays: true))
2984 continue;
2985 if (!passRegCallStructTypeDirectly(Ty: BaseTy, CoerceElts, NeededInt,
2986 NeededSSE, MaxVectorWidth))
2987 return false;
2988 }
2989 }
2990
2991 // Classify the members.
2992 for (const auto *FD : RD->fields()) {
2993 QualType MTy = FD->getType();
2994 if (MTy->isRecordType() && !MTy->isUnionType()) {
2995 if (isEmptyRecord(Context&: getContext(), T: MTy, AllowArrays: true))
2996 continue;
2997 if (!passRegCallStructTypeDirectly(Ty: MTy, CoerceElts, NeededInt, NeededSSE,
2998 MaxVectorWidth))
2999 return false;
3000 continue;
3001 }
3002
3003 const auto *AT = getContext().getAsConstantArrayType(T: MTy);
3004 if (AT)
3005 MTy = AT->getElementType();
3006
3007 unsigned LocalNeededInt, LocalNeededSSE;
3008 ABIArgInfo AI = classifyArgumentType(Ty: MTy, UINT_MAX, neededInt&: LocalNeededInt,
3009 neededSSE&: LocalNeededSSE, isNamedArg: true, IsRegCall: true);
3010 if (AI.isIgnore())
3011 continue;
3012 if (AI.isIndirect())
3013 return false;
3014
3015 llvm::Type *CoerceTy = AI.getCoerceToType();
3016 assert(CoerceTy && "ABI info for struct member has no coerce type");
3017 if (AT) {
3018 uint64_t NumElts = AT->getZExtSize();
3019 LocalNeededInt *= NumElts;
3020 LocalNeededSSE *= NumElts;
3021 CoerceElts.push_back(Elt: llvm::ArrayType::get(ElementType: CoerceTy, NumElements: NumElts));
3022 } else {
3023 CoerceElts.push_back(Elt: CoerceTy);
3024 }
3025
3026 if (const auto *VT = MTy->getAs<VectorType>())
3027 if (getContext().getTypeSize(T: VT) > MaxVectorWidth)
3028 MaxVectorWidth = getContext().getTypeSize(T: VT);
3029
3030 NeededInt += LocalNeededInt;
3031 NeededSSE += LocalNeededSSE;
3032 }
3033
3034 return true;
3035}
3036
3037ABIArgInfo
3038X86_64ABIInfo::classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
3039 unsigned &NeededSSE,
3040 unsigned &MaxVectorWidth) const {
3041 NeededInt = 0;
3042 NeededSSE = 0;
3043 MaxVectorWidth = 0;
3044
3045 if (isEmptyRecord(Context&: getContext(), T: Ty, AllowArrays: true))
3046 return ABIArgInfo::getIgnore();
3047
3048 SmallVector<llvm::Type *, 16> CoerceElts;
3049 if (!passRegCallStructTypeDirectly(Ty, CoerceElts, NeededInt, NeededSSE,
3050 MaxVectorWidth)) {
3051 NeededInt = NeededSSE = 0;
3052 return getIndirectReturnResult(Ty);
3053 }
3054
3055 assert(!CoerceElts.empty() && "Non-empty struct produced no element types");
3056 return ABIArgInfo::getDirect(
3057 T: llvm::StructType::get(Context&: getVMContext(), Elements: CoerceElts));
3058}
3059
3060unsigned
3061X86_64ABIInfo::getX86ABIAVXLevel(const FunctionDecl *FD,
3062 const FunctionType::ExtInfo &Info) const {
3063 return static_cast<unsigned>(getEffectiveX86AVXABILevel(CGT, GlobalAVXLevel: AVXLevel, FD));
3064}
3065
3066void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3067 const unsigned CallingConv = FI.getCallingConvention();
3068 // It is possible to force Win64 calling convention on any x86_64 target by
3069 // using __attribute__((ms_abi)). In such case to correctly emit Win64
3070 // compatible code delegate this call to WinX86_64ABIInfo::computeInfo.
3071 if (CallingConv == llvm::CallingConv::Win64) {
3072 WinX86_64ABIInfo Win64ABIInfo(CGT, AVXLevel);
3073 Win64ABIInfo.computeInfo(FI);
3074 return;
3075 }
3076
3077 assert(FI.getX86ABIAVXLevel() <=
3078 static_cast<unsigned>(X86AVXABILevel::AVX512) &&
3079 "Unexpected X86 AVX ABI level");
3080 X86AVXABILevel EffectiveAVXLevel =
3081 static_cast<X86AVXABILevel>(FI.getX86ABIAVXLevel());
3082 if (EffectiveAVXLevel != AVXLevel) {
3083 X86_64ABIInfo EffectiveABIInfo(CGT, EffectiveAVXLevel);
3084 EffectiveABIInfo.computeInfo(FI);
3085 return;
3086 }
3087
3088 bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall;
3089
3090 // Keep track of the number of assigned registers.
3091 unsigned FreeIntRegs = IsRegCall ? 11 : 6;
3092 unsigned FreeSSERegs = IsRegCall ? 16 : 8;
3093 unsigned NeededInt = 0, NeededSSE = 0, MaxVectorWidth = 0;
3094
3095 if (!::classifyReturnType(CXXABI: getCXXABI(), FI, Info: *this)) {
3096 if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
3097 !FI.getReturnType()->getTypePtr()->isUnionType()) {
3098 FI.getReturnInfo() = classifyRegCallStructType(
3099 Ty: FI.getReturnType(), NeededInt, NeededSSE, MaxVectorWidth);
3100 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3101 FreeIntRegs -= NeededInt;
3102 FreeSSERegs -= NeededSSE;
3103 } else {
3104 FI.getReturnInfo() = getIndirectReturnResult(Ty: FI.getReturnType());
3105 }
3106 } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>() &&
3107 getContext().getCanonicalType(T: FI.getReturnType()
3108 ->getAs<ComplexType>()
3109 ->getElementType()) ==
3110 getContext().LongDoubleTy)
3111 // Complex Long Double Type is passed in Memory when Regcall
3112 // calling convention is used.
3113 FI.getReturnInfo() = getIndirectReturnResult(Ty: FI.getReturnType());
3114 else
3115 FI.getReturnInfo() = classifyReturnType(RetTy: FI.getReturnType());
3116 }
3117
3118 // If the return value is indirect, then the hidden argument is consuming one
3119 // integer register.
3120 if (FI.getReturnInfo().isIndirect())
3121 --FreeIntRegs;
3122 else if (NeededSSE && MaxVectorWidth > 0)
3123 FI.setMaxVectorWidth(MaxVectorWidth);
3124
3125 // The chain argument effectively gives us another free register.
3126 if (FI.isChainCall())
3127 ++FreeIntRegs;
3128
3129 // RegCall lets us reuse the return registers.
3130 if (IsRegCall)
3131 FreeSSERegs = 16;
3132
3133 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
3134 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3135 // get assigned (in left-to-right order) for passing as follows...
3136 unsigned ArgNo = 0;
3137 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3138 it != ie; ++it, ++ArgNo) {
3139 bool IsNamedArg = ArgNo < NumRequiredArgs;
3140
3141 if (IsRegCall && it->type->isStructureOrClassType())
3142 it->info = classifyRegCallStructType(Ty: it->type, NeededInt, NeededSSE,
3143 MaxVectorWidth);
3144 else
3145 it->info = classifyArgumentType(Ty: it->type, freeIntRegs: FreeIntRegs, neededInt&: NeededInt,
3146 neededSSE&: NeededSSE, isNamedArg: IsNamedArg);
3147
3148 // AMD64-ABI 3.2.3p3: If there are no registers available for any
3149 // eightbyte of an argument, the whole argument is passed on the
3150 // stack. If registers have already been assigned for some
3151 // eightbytes of such an argument, the assignments get reverted.
3152 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3153 FreeIntRegs -= NeededInt;
3154 FreeSSERegs -= NeededSSE;
3155 if (MaxVectorWidth > FI.getMaxVectorWidth())
3156 FI.setMaxVectorWidth(MaxVectorWidth);
3157 } else {
3158 it->info = getIndirectResult(Ty: it->type, freeIntRegs: FreeIntRegs);
3159 }
3160 }
3161}
3162
3163static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3164 Address VAListAddr, QualType Ty) {
3165 Address overflow_arg_area_p =
3166 CGF.Builder.CreateStructGEP(Addr: VAListAddr, Index: 2, Name: "overflow_arg_area_p");
3167 llvm::Value *overflow_arg_area =
3168 CGF.Builder.CreateLoad(Addr: overflow_arg_area_p, Name: "overflow_arg_area");
3169
3170 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3171 // byte boundary if alignment needed by type exceeds 8 byte boundary.
3172 // It isn't stated explicitly in the standard, but in practice we use
3173 // alignment greater than 16 where necessary.
3174 CharUnits Align = CGF.getContext().getTypeAlignInChars(T: Ty);
3175 if (Align > CharUnits::fromQuantity(Quantity: 8)) {
3176 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, Ptr: overflow_arg_area,
3177 Align);
3178 }
3179
3180 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
3181 llvm::Type *LTy = CGF.ConvertTypeForMem(T: Ty);
3182 llvm::Value *Res = overflow_arg_area;
3183
3184 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3185 // l->overflow_arg_area + sizeof(type).
3186 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3187 // an 8 byte boundary.
3188
3189 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(T: Ty) + 7) / 8;
3190 llvm::Value *Offset =
3191 llvm::ConstantInt::get(Ty: CGF.Int32Ty, V: (SizeInBytes + 7) & ~7);
3192 overflow_arg_area = CGF.Builder.CreateGEP(Ty: CGF.Int8Ty, Ptr: overflow_arg_area,
3193 IdxList: Offset, Name: "overflow_arg_area.next");
3194 CGF.Builder.CreateStore(Val: overflow_arg_area, Addr: overflow_arg_area_p);
3195
3196 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
3197 return Address(Res, LTy, Align);
3198}
3199
3200RValue X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3201 QualType Ty, AggValueSlot Slot) const {
3202 // Assume that va_list type is correct; should be pointer to LLVM type:
3203 // struct {
3204 // i32 gp_offset;
3205 // i32 fp_offset;
3206 // i8* overflow_arg_area;
3207 // i8* reg_save_area;
3208 // };
3209 unsigned neededInt, neededSSE;
3210
3211 Ty = getContext().getCanonicalType(T: Ty);
3212 ABIArgInfo AI = classifyArgumentType(Ty, freeIntRegs: 0, neededInt, neededSSE,
3213 /*isNamedArg*/false);
3214
3215 // Empty records are ignored for parameter passing purposes.
3216 if (AI.isIgnore())
3217 return Slot.asRValue();
3218
3219 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3220 // in the registers. If not go to step 7.
3221 if (!neededInt && !neededSSE)
3222 return CGF.EmitLoadOfAnyValue(
3223 V: CGF.MakeAddrLValue(Addr: EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty), T: Ty),
3224 Slot);
3225
3226 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3227 // general purpose registers needed to pass type and num_fp to hold
3228 // the number of floating point registers needed.
3229
3230 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3231 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3232 // l->fp_offset > 304 - num_fp * 16 go to step 7.
3233 //
3234 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3235 // register save space).
3236
3237 llvm::Value *InRegs = nullptr;
3238 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3239 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
3240 if (neededInt) {
3241 gp_offset_p = CGF.Builder.CreateStructGEP(Addr: VAListAddr, Index: 0, Name: "gp_offset_p");
3242 gp_offset = CGF.Builder.CreateLoad(Addr: gp_offset_p, Name: "gp_offset");
3243 InRegs = llvm::ConstantInt::get(Ty: CGF.Int32Ty, V: 48 - neededInt * 8);
3244 InRegs = CGF.Builder.CreateICmpULE(LHS: gp_offset, RHS: InRegs, Name: "fits_in_gp");
3245 }
3246
3247 if (neededSSE) {
3248 fp_offset_p = CGF.Builder.CreateStructGEP(Addr: VAListAddr, Index: 1, Name: "fp_offset_p");
3249 fp_offset = CGF.Builder.CreateLoad(Addr: fp_offset_p, Name: "fp_offset");
3250 llvm::Value *FitsInFP =
3251 llvm::ConstantInt::get(Ty: CGF.Int32Ty, V: 176 - neededSSE * 16);
3252 FitsInFP = CGF.Builder.CreateICmpULE(LHS: fp_offset, RHS: FitsInFP, Name: "fits_in_fp");
3253 InRegs = InRegs ? CGF.Builder.CreateAnd(LHS: InRegs, RHS: FitsInFP) : FitsInFP;
3254 }
3255
3256 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock(name: "vaarg.in_reg");
3257 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock(name: "vaarg.in_mem");
3258 llvm::BasicBlock *ContBlock = CGF.createBasicBlock(name: "vaarg.end");
3259 CGF.Builder.CreateCondBr(Cond: InRegs, True: InRegBlock, False: InMemBlock);
3260
3261 // Emit code to load the value if it was passed in registers.
3262
3263 CGF.EmitBlock(BB: InRegBlock);
3264
3265 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3266 // an offset of l->gp_offset and/or l->fp_offset. This may require
3267 // copying to a temporary location in case the parameter is passed
3268 // in different register classes or requires an alignment greater
3269 // than 8 for general purpose registers and 16 for XMM registers.
3270 //
3271 // FIXME: This really results in shameful code when we end up needing to
3272 // collect arguments from different places; often what should result in a
3273 // simple assembling of a structure from scattered addresses has many more
3274 // loads than necessary. Can we clean this up?
3275 llvm::Type *LTy = CGF.ConvertTypeForMem(T: Ty);
3276 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
3277 Addr: CGF.Builder.CreateStructGEP(Addr: VAListAddr, Index: 3), Name: "reg_save_area");
3278
3279 Address RegAddr = Address::invalid();
3280 if (neededInt && neededSSE) {
3281 // FIXME: Cleanup.
3282 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
3283 llvm::StructType *ST = cast<llvm::StructType>(Val: AI.getCoerceToType());
3284 Address Tmp = CGF.CreateMemTempWithoutCast(T: Ty);
3285 Tmp = Tmp.withElementType(ElemTy: ST);
3286 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
3287 llvm::Type *TyLo = ST->getElementType(N: 0);
3288 llvm::Type *TyHi = ST->getElementType(N: 1);
3289 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
3290 "Unexpected ABI info for mixed regs");
3291 llvm::Value *GPAddr =
3292 CGF.Builder.CreateGEP(Ty: CGF.Int8Ty, Ptr: RegSaveArea, IdxList: gp_offset);
3293 llvm::Value *FPAddr =
3294 CGF.Builder.CreateGEP(Ty: CGF.Int8Ty, Ptr: RegSaveArea, IdxList: fp_offset);
3295 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3296 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
3297
3298 // Copy the first element.
3299 // FIXME: Our choice of alignment here and below is probably pessimistic.
3300 llvm::Value *V = CGF.Builder.CreateAlignedLoad(
3301 Ty: TyLo, Addr: RegLoAddr,
3302 Align: CharUnits::fromQuantity(Quantity: getDataLayout().getABITypeAlign(Ty: TyLo)));
3303 CGF.Builder.CreateStore(Val: V, Addr: CGF.Builder.CreateStructGEP(Addr: Tmp, Index: 0));
3304
3305 // Copy the second element.
3306 V = CGF.Builder.CreateAlignedLoad(
3307 Ty: TyHi, Addr: RegHiAddr,
3308 Align: CharUnits::fromQuantity(Quantity: getDataLayout().getABITypeAlign(Ty: TyHi)));
3309 CGF.Builder.CreateStore(Val: V, Addr: CGF.Builder.CreateStructGEP(Addr: Tmp, Index: 1));
3310
3311 RegAddr = Tmp.withElementType(ElemTy: LTy);
3312 } else if (neededInt || neededSSE == 1) {
3313 // Copy to a temporary if necessary to ensure the appropriate alignment.
3314 auto TInfo = getContext().getTypeInfoInChars(T: Ty);
3315 uint64_t TySize = TInfo.Width.getQuantity();
3316 CharUnits TyAlign = TInfo.Align;
3317 llvm::Type *CoTy = nullptr;
3318 if (AI.isDirect())
3319 CoTy = AI.getCoerceToType();
3320
3321 llvm::Value *GpOrFpOffset = neededInt ? gp_offset : fp_offset;
3322 uint64_t Alignment = neededInt ? 8 : 16;
3323 uint64_t RegSize = neededInt ? neededInt * 8 : 16;
3324 // There are two cases require special handling:
3325 // 1)
3326 // ```
3327 // struct {
3328 // struct {} a[8];
3329 // int b;
3330 // };
3331 // ```
3332 // The lower 8 bytes of the structure are not stored,
3333 // so an 8-byte offset is needed when accessing the structure.
3334 // 2)
3335 // ```
3336 // struct {
3337 // long long a;
3338 // struct {} b;
3339 // };
3340 // ```
3341 // The stored size of this structure is smaller than its actual size,
3342 // which may lead to reading past the end of the register save area.
3343 if (CoTy && (AI.getDirectOffset() == 8 || RegSize < TySize)) {
3344 Address Tmp = CGF.CreateMemTempWithoutCast(T: Ty);
3345 llvm::Value *Addr =
3346 CGF.Builder.CreateGEP(Ty: CGF.Int8Ty, Ptr: RegSaveArea, IdxList: GpOrFpOffset);
3347 llvm::Value *Src = CGF.Builder.CreateAlignedLoad(Ty: CoTy, Addr, Align: TyAlign);
3348 llvm::Value *PtrOffset =
3349 llvm::ConstantInt::get(Ty: CGF.Int32Ty, V: AI.getDirectOffset());
3350 Address Dst = Address(
3351 CGF.Builder.CreateGEP(Ty: CGF.Int8Ty, Ptr: Tmp.getBasePointer(), IdxList: PtrOffset),
3352 LTy, TyAlign);
3353 CGF.Builder.CreateStore(Val: Src, Addr: Dst);
3354 RegAddr = Tmp.withElementType(ElemTy: LTy);
3355 } else {
3356 RegAddr =
3357 Address(CGF.Builder.CreateGEP(Ty: CGF.Int8Ty, Ptr: RegSaveArea, IdxList: GpOrFpOffset),
3358 LTy, CharUnits::fromQuantity(Quantity: Alignment));
3359
3360 // Copy into a temporary if the type is more aligned than the
3361 // register save area.
3362 if (neededInt && TyAlign.getQuantity() > 8) {
3363 Address Tmp = CGF.CreateMemTempWithoutCast(T: Ty);
3364 CGF.Builder.CreateMemCpy(Dest: Tmp, Src: RegAddr, Size: TySize, IsVolatile: false);
3365 RegAddr = Tmp;
3366 }
3367 }
3368
3369 } else {
3370 assert(neededSSE == 2 && "Invalid number of needed registers!");
3371 // SSE registers are spaced 16 bytes apart in the register save
3372 // area, we need to collect the two eightbytes together.
3373 // The ABI isn't explicit about this, but it seems reasonable
3374 // to assume that the slots are 16-byte aligned, since the stack is
3375 // naturally 16-byte aligned and the prologue is expected to store
3376 // all the SSE registers to the RSA.
3377 Address RegAddrLo = Address(CGF.Builder.CreateGEP(Ty: CGF.Int8Ty, Ptr: RegSaveArea,
3378 IdxList: fp_offset),
3379 CGF.Int8Ty, CharUnits::fromQuantity(Quantity: 16));
3380 Address RegAddrHi =
3381 CGF.Builder.CreateConstInBoundsByteGEP(Addr: RegAddrLo,
3382 Offset: CharUnits::fromQuantity(Quantity: 16));
3383 llvm::Type *ST = AI.canHaveCoerceToType()
3384 ? AI.getCoerceToType()
3385 : llvm::StructType::get(elt1: CGF.DoubleTy, elts: CGF.DoubleTy);
3386 llvm::Value *V;
3387 Address Tmp = CGF.CreateMemTempWithoutCast(T: Ty);
3388 Tmp = Tmp.withElementType(ElemTy: ST);
3389 V = CGF.Builder.CreateLoad(
3390 Addr: RegAddrLo.withElementType(ElemTy: ST->getStructElementType(N: 0)));
3391 CGF.Builder.CreateStore(Val: V, Addr: CGF.Builder.CreateStructGEP(Addr: Tmp, Index: 0));
3392 V = CGF.Builder.CreateLoad(
3393 Addr: RegAddrHi.withElementType(ElemTy: ST->getStructElementType(N: 1)));
3394 CGF.Builder.CreateStore(Val: V, Addr: CGF.Builder.CreateStructGEP(Addr: Tmp, Index: 1));
3395
3396 RegAddr = Tmp.withElementType(ElemTy: LTy);
3397 }
3398
3399 // AMD64-ABI 3.5.7p5: Step 5. Set:
3400 // l->gp_offset = l->gp_offset + num_gp * 8
3401 // l->fp_offset = l->fp_offset + num_fp * 16.
3402 if (neededInt) {
3403 llvm::Value *Offset = llvm::ConstantInt::get(Ty: CGF.Int32Ty, V: neededInt * 8);
3404 CGF.Builder.CreateStore(Val: CGF.Builder.CreateAdd(LHS: gp_offset, RHS: Offset),
3405 Addr: gp_offset_p);
3406 }
3407 if (neededSSE) {
3408 llvm::Value *Offset = llvm::ConstantInt::get(Ty: CGF.Int32Ty, V: neededSSE * 16);
3409 CGF.Builder.CreateStore(Val: CGF.Builder.CreateAdd(LHS: fp_offset, RHS: Offset),
3410 Addr: fp_offset_p);
3411 }
3412 CGF.EmitBranch(Block: ContBlock);
3413
3414 // Emit code to load the value if it was passed in memory.
3415
3416 CGF.EmitBlock(BB: InMemBlock);
3417 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
3418
3419 // Return the appropriate result.
3420
3421 CGF.EmitBlock(BB: ContBlock);
3422 Address ResAddr = emitMergePHI(CGF, Addr1: RegAddr, Block1: InRegBlock, Addr2: MemAddr, Block2: InMemBlock,
3423 Name: "vaarg.addr");
3424 return CGF.EmitLoadOfAnyValue(V: CGF.MakeAddrLValue(Addr: ResAddr, T: Ty), Slot);
3425}
3426
3427RValue X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
3428 QualType Ty, AggValueSlot Slot) const {
3429 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3430 // not 1, 2, 4, or 8 bytes, must be passed by reference."
3431 uint64_t Width = getContext().getTypeSize(T: Ty);
3432 bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Value: Width);
3433
3434 return emitVoidPtrVAArg(CGF, VAListAddr, ValueTy: Ty, IsIndirect,
3435 ValueInfo: CGF.getContext().getTypeInfoInChars(T: Ty),
3436 SlotSizeAndAlign: CharUnits::fromQuantity(Quantity: 8),
3437 /*allowHigherAlign*/ AllowHigherAlign: false, Slot);
3438}
3439
3440ABIArgInfo WinX86_64ABIInfo::reclassifyHvaArgForVectorCall(
3441 QualType Ty, unsigned &FreeSSERegs, const ABIArgInfo &current) const {
3442 const Type *Base = nullptr;
3443 uint64_t NumElts = 0;
3444
3445 if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
3446 isHomogeneousAggregate(Ty, Base, Members&: NumElts) && FreeSSERegs >= NumElts) {
3447 FreeSSERegs -= NumElts;
3448 return getDirectX86Hva();
3449 }
3450 return current;
3451}
3452
3453ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
3454 bool IsReturnType, unsigned CC) const {
3455 bool IsVectorCall = CC == llvm::CallingConv::X86_VectorCall;
3456 bool IsRegCall = CC == llvm::CallingConv::X86_RegCall;
3457
3458 if (Ty->isVoidType())
3459 return ABIArgInfo::getIgnore();
3460
3461 if (const auto *ED = Ty->getAsEnumDecl())
3462 Ty = ED->getIntegerType();
3463
3464 TypeInfo Info = getContext().getTypeInfo(T: Ty);
3465 uint64_t Width = Info.Width;
3466 CharUnits Align = getContext().toCharUnitsFromBits(BitSize: Info.Align);
3467
3468 const RecordType *RT = Ty->getAsCanonical<RecordType>();
3469 if (RT) {
3470 if (!IsReturnType) {
3471 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, CXXABI&: getCXXABI()))
3472 return getNaturalAlignIndirect(Ty, AddrSpace: getDataLayout().getAllocaAddrSpace(),
3473 ByVal: RAA == CGCXXABI::RAA_DirectInMemory);
3474 }
3475
3476 if (RT->getDecl()->getDefinitionOrSelf()->hasFlexibleArrayMember())
3477 return getNaturalAlignIndirect(Ty, AddrSpace: getDataLayout().getAllocaAddrSpace(),
3478 /*ByVal=*/false);
3479 }
3480
3481 const Type *Base = nullptr;
3482 uint64_t NumElts = 0;
3483 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3484 // other targets.
3485 if ((IsVectorCall || IsRegCall) &&
3486 isHomogeneousAggregate(Ty, Base, Members&: NumElts)) {
3487 if (IsRegCall) {
3488 if (FreeSSERegs >= NumElts) {
3489 FreeSSERegs -= NumElts;
3490 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3491 return ABIArgInfo::getDirect();
3492 return ABIArgInfo::getExpand();
3493 }
3494 return ABIArgInfo::getIndirect(
3495 Alignment: Align, /*AddrSpace=*/getDataLayout().getAllocaAddrSpace(),
3496 /*ByVal=*/false);
3497 } else if (IsVectorCall) {
3498 if (FreeSSERegs >= NumElts &&
3499 (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
3500 FreeSSERegs -= NumElts;
3501 return ABIArgInfo::getDirect();
3502 } else if (IsReturnType) {
3503 return ABIArgInfo::getExpand();
3504 } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
3505 // HVAs are delayed and reclassified in the 2nd step.
3506 return ABIArgInfo::getIndirect(
3507 Alignment: Align, /*AddrSpace=*/getDataLayout().getAllocaAddrSpace(),
3508 /*ByVal=*/false);
3509 }
3510 }
3511 }
3512
3513 if (Ty->isMemberPointerType()) {
3514 // If the member pointer is represented by an LLVM int or ptr, pass it
3515 // directly.
3516 llvm::Type *LLTy = CGT.ConvertType(T: Ty);
3517 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3518 return ABIArgInfo::getDirect();
3519 }
3520
3521 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
3522 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3523 // not 1, 2, 4, or 8 bytes, must be passed by reference."
3524 if (Width > 64 || !llvm::isPowerOf2_64(Value: Width))
3525 return getNaturalAlignIndirect(Ty, AddrSpace: getDataLayout().getAllocaAddrSpace(),
3526 /*ByVal=*/false);
3527
3528 // Otherwise, coerce it to a small integer.
3529 return ABIArgInfo::getDirect(T: llvm::IntegerType::get(C&: getVMContext(), NumBits: Width));
3530 }
3531
3532 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3533 switch (BT->getKind()) {
3534 case BuiltinType::Bool:
3535 // Bool type is always extended to the ABI, other builtin types are not
3536 // extended.
3537 return ABIArgInfo::getExtend(Ty);
3538
3539 case BuiltinType::LongDouble:
3540 // Mingw64 GCC uses the old 80 bit extended precision floating point
3541 // unit. It passes them indirectly through memory.
3542 if (IsMingw64) {
3543 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
3544 if (LDF == &llvm::APFloat::x87DoubleExtended())
3545 return ABIArgInfo::getIndirect(
3546 Alignment: Align, /*AddrSpace=*/getDataLayout().getAllocaAddrSpace(),
3547 /*ByVal=*/false);
3548 }
3549 break;
3550
3551 case BuiltinType::Int128:
3552 case BuiltinType::UInt128:
3553 case BuiltinType::Float128:
3554 // If it's a parameter type, the normal ABI rule is that arguments larger
3555 // than 8 bytes are passed indirectly. GCC follows it. We follow it too,
3556 // even though it isn't particularly efficient.
3557 if (!IsReturnType)
3558 return ABIArgInfo::getIndirect(
3559 Alignment: Align, /*AddrSpace=*/getDataLayout().getAllocaAddrSpace(),
3560 /*ByVal=*/false);
3561
3562 // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that.
3563 // Clang matches them for compatibility.
3564 if (BT->getKind() == BuiltinType::Int128 ||
3565 BT->getKind() == BuiltinType::UInt128)
3566 return ABIArgInfo::getDirect(T: llvm::FixedVectorType::get(
3567 ElementType: llvm::Type::getInt64Ty(C&: getVMContext()), NumElts: 2));
3568
3569 // Mingw64 GCC returns f128 via sret, and Clang matches that for
3570 // compatibility. This mirrors the X86 backend's CanLowerReturn logic.
3571 if (BT->getKind() == BuiltinType::Float128) {
3572 auto IsWin64F128StackCC = [this](unsigned CC) -> bool {
3573 switch (CC) {
3574 case llvm::CallingConv::Win64:
3575 return true;
3576 case llvm::CallingConv::C:
3577 return getTarget().getTriple().isOSWindowsOrUEFI();
3578 default:
3579 return false;
3580 }
3581 };
3582
3583 if (IsWin64F128StackCC(CC))
3584 return getNaturalAlignIndirect(
3585 Ty, AddrSpace: getDataLayout().getAllocaAddrSpace(), /*ByVal=*/false);
3586 }
3587 break;
3588
3589 default:
3590 break;
3591 }
3592 }
3593
3594 if (Ty->isBitIntType()) {
3595 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3596 // not 1, 2, 4, or 8 bytes, must be passed by reference."
3597 // However, non-power-of-two bit-precise integers will be passed as 1, 2, 4,
3598 // or 8 bytes anyway as long is it fits in them, so we don't have to check
3599 // the power of 2.
3600 if (Width <= 64)
3601 return ABIArgInfo::getDirect();
3602 return ABIArgInfo::getIndirect(
3603 Alignment: Align, /*AddrSpace=*/getDataLayout().getAllocaAddrSpace(),
3604 /*ByVal=*/false);
3605 }
3606
3607 return ABIArgInfo::getDirect();
3608}
3609
3610unsigned
3611WinX86_64ABIInfo::getX86ABIAVXLevel(const FunctionDecl *FD,
3612 const FunctionType::ExtInfo &Info) const {
3613 if (Info.getCC() == CC_X86_64SysV) {
3614 return static_cast<unsigned>(getEffectiveX86AVXABILevel(CGT, GlobalAVXLevel: AVXLevel, FD));
3615 }
3616
3617 return static_cast<unsigned>(AVXLevel);
3618}
3619
3620void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3621 const unsigned CC = FI.getCallingConvention();
3622 bool IsVectorCall = CC == llvm::CallingConv::X86_VectorCall;
3623 bool IsRegCall = CC == llvm::CallingConv::X86_RegCall;
3624
3625 // If __attribute__((sysv_abi)) is in use, use the SysV argument
3626 // classification rules.
3627 if (CC == llvm::CallingConv::X86_64_SysV) {
3628 X86_64ABIInfo SysVABIInfo(CGT, AVXLevel);
3629 SysVABIInfo.computeInfo(FI);
3630 return;
3631 }
3632
3633 unsigned FreeSSERegs = 0;
3634 if (IsVectorCall) {
3635 // We can use up to 4 SSE return registers with vectorcall.
3636 FreeSSERegs = 4;
3637 } else if (IsRegCall) {
3638 // RegCall gives us 16 SSE registers.
3639 FreeSSERegs = 16;
3640 }
3641
3642 if (!getCXXABI().classifyReturnType(FI))
3643 FI.getReturnInfo() = classify(Ty: FI.getReturnType(), FreeSSERegs, IsReturnType: true, CC);
3644
3645 if (IsVectorCall) {
3646 // We can use up to 6 SSE register parameters with vectorcall.
3647 FreeSSERegs = 6;
3648 } else if (IsRegCall) {
3649 // RegCall gives us 16 SSE registers, we can reuse the return registers.
3650 FreeSSERegs = 16;
3651 }
3652
3653 unsigned ArgNum = 0;
3654 unsigned ZeroSSERegs = 0;
3655 for (auto &I : FI.arguments()) {
3656 // Vectorcall in x64 only permits the first 6 arguments to be passed as
3657 // XMM/YMM registers. After the sixth argument, pretend no vector
3658 // registers are left.
3659 unsigned *MaybeFreeSSERegs =
3660 (IsVectorCall && ArgNum >= 6) ? &ZeroSSERegs : &FreeSSERegs;
3661 I.info = classify(Ty: I.type, FreeSSERegs&: *MaybeFreeSSERegs, IsReturnType: false, CC);
3662 ++ArgNum;
3663 }
3664
3665 if (IsVectorCall) {
3666 // For vectorcall, assign aggregate HVAs to any free vector registers in a
3667 // second pass.
3668 for (auto &I : FI.arguments())
3669 I.info = reclassifyHvaArgForVectorCall(Ty: I.type, FreeSSERegs, current: I.info);
3670 }
3671}
3672
3673RValue WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3674 QualType Ty, AggValueSlot Slot) const {
3675 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3676 // not 1, 2, 4, or 8 bytes, must be passed by reference."
3677 uint64_t Width = getContext().getTypeSize(T: Ty);
3678 bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Value: Width);
3679
3680 return emitVoidPtrVAArg(CGF, VAListAddr, ValueTy: Ty, IsIndirect,
3681 ValueInfo: CGF.getContext().getTypeInfoInChars(T: Ty),
3682 SlotSizeAndAlign: CharUnits::fromQuantity(Quantity: 8),
3683 /*allowHigherAlign*/ AllowHigherAlign: false, Slot);
3684}
3685
3686std::unique_ptr<TargetCodeGenInfo> CodeGen::createX86_32TargetCodeGenInfo(
3687 CodeGenModule &CGM, bool DarwinVectorABI, bool Win32StructABI,
3688 unsigned NumRegisterParameters, bool SoftFloatABI) {
3689 bool RetSmallStructInRegABI = X86_32TargetCodeGenInfo::isStructReturnInRegABI(
3690 Triple: CGM.getTriple(), Opts: CGM.getCodeGenOpts());
3691 return std::make_unique<X86_32TargetCodeGenInfo>(
3692 args&: CGM.getTypes(), args&: DarwinVectorABI, args&: RetSmallStructInRegABI, args&: Win32StructABI,
3693 args&: NumRegisterParameters, args&: SoftFloatABI);
3694}
3695
3696std::unique_ptr<TargetCodeGenInfo> CodeGen::createWinX86_32TargetCodeGenInfo(
3697 CodeGenModule &CGM, bool DarwinVectorABI, bool Win32StructABI,
3698 unsigned NumRegisterParameters) {
3699 bool RetSmallStructInRegABI = X86_32TargetCodeGenInfo::isStructReturnInRegABI(
3700 Triple: CGM.getTriple(), Opts: CGM.getCodeGenOpts());
3701 return std::make_unique<WinX86_32TargetCodeGenInfo>(
3702 args&: CGM.getTypes(), args&: DarwinVectorABI, args&: RetSmallStructInRegABI, args&: Win32StructABI,
3703 args&: NumRegisterParameters);
3704}
3705
3706std::unique_ptr<TargetCodeGenInfo>
3707CodeGen::createX86_64TargetCodeGenInfo(CodeGenModule &CGM,
3708 X86AVXABILevel AVXLevel) {
3709 return std::make_unique<X86_64TargetCodeGenInfo>(args&: CGM.getTypes(), args&: AVXLevel);
3710}
3711
3712std::unique_ptr<TargetCodeGenInfo>
3713CodeGen::createWinX86_64TargetCodeGenInfo(CodeGenModule &CGM,
3714 X86AVXABILevel AVXLevel) {
3715 return std::make_unique<WinX86_64TargetCodeGenInfo>(args&: CGM.getTypes(), args&: AVXLevel);
3716}
3717