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