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