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