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.
1347 if (getContext().getLangOpts().getClangABICompat() <=
1348 LangOptions::ClangABI::Ver20)
1349 return false;
1350
1351 return true;
1352 }
1353
1354 X86AVXABILevel AVXLevel;
1355 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1356 // 64-bit hardware.
1357 bool Has64BitPointers;
1358
1359public:
1360 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
1361 : ABIInfo(CGT), AVXLevel(AVXLevel),
1362 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {}
1363
1364 bool isPassedUsingAVXType(QualType type) const {
1365 unsigned neededInt, neededSSE;
1366 // The freeIntRegs argument doesn't matter here.
1367 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1368 /*isNamedArg*/true);
1369 if (info.isDirect()) {
1370 llvm::Type *ty = info.getCoerceToType();
1371 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1372 return vectorTy->getPrimitiveSizeInBits().getFixedValue() > 128;
1373 }
1374 return false;
1375 }
1376
1377 void computeInfo(CGFunctionInfo &FI) const override;
1378
1379 RValue EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
1380 AggValueSlot Slot) const override;
1381 RValue EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
1382 AggValueSlot Slot) const override;
1383
1384 bool has64BitPointers() const {
1385 return Has64BitPointers;
1386 }
1387};
1388
1389/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
1390class WinX86_64ABIInfo : public ABIInfo {
1391public:
1392 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
1393 : ABIInfo(CGT), AVXLevel(AVXLevel),
1394 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
1395
1396 void computeInfo(CGFunctionInfo &FI) const override;
1397
1398 RValue EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
1399 AggValueSlot Slot) const override;
1400
1401 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1402 // FIXME: Assumes vectorcall is in use.
1403 return isX86VectorTypeForVectorCall(getContext(), Ty);
1404 }
1405
1406 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1407 uint64_t NumMembers) const override {
1408 // FIXME: Assumes vectorcall is in use.
1409 return isX86VectorCallAggregateSmallEnough(NumMembers);
1410 }
1411
1412private:
1413 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
1414 bool IsVectorCall, bool IsRegCall) const;
1415 ABIArgInfo reclassifyHvaArgForVectorCall(QualType Ty, unsigned &FreeSSERegs,
1416 const ABIArgInfo &current) const;
1417
1418 X86AVXABILevel AVXLevel;
1419
1420 bool IsMingw64;
1421};
1422
1423class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1424public:
1425 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
1426 : TargetCodeGenInfo(std::make_unique<X86_64ABIInfo>(CGT, AVXLevel)) {
1427 SwiftInfo =
1428 std::make_unique<SwiftABIInfo>(CGT, /*SwiftErrorInRegister=*/true);
1429 }
1430
1431 /// Disable tail call on x86-64. The epilogue code before the tail jump blocks
1432 /// autoreleaseRV/retainRV and autoreleaseRV/unsafeClaimRV optimizations.
1433 bool markARCOptimizedReturnCallsAsNoTail() const override { return true; }
1434
1435 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
1436 return 7;
1437 }
1438
1439 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1440 llvm::Value *Address) const override {
1441 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
1442
1443 // 0-15 are the 16 integer registers.
1444 // 16 is %rip.
1445 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
1446 return false;
1447 }
1448
1449 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1450 StringRef Constraint,
1451 llvm::Type* Ty) const override {
1452 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1453 }
1454
1455 bool isNoProtoCallVariadic(const CallArgList &args,
1456 const FunctionNoProtoType *fnType) const override {
1457 // The default CC on x86-64 sets %al to the number of SSA
1458 // registers used, and GCC sets this when calling an unprototyped
1459 // function, so we override the default behavior. However, don't do
1460 // that when AVX types are involved: the ABI explicitly states it is
1461 // undefined, and it doesn't work in practice because of how the ABI
1462 // defines varargs anyway.
1463 if (fnType->getCallConv() == CC_C) {
1464 bool HasAVXType = false;
1465 for (const CallArg &arg : args) {
1466 if (getABIInfo<X86_64ABIInfo>().isPassedUsingAVXType(arg.Ty)) {
1467 HasAVXType = true;
1468 break;
1469 }
1470 }
1471
1472 if (!HasAVXType)
1473 return true;
1474 }
1475
1476 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
1477 }
1478
1479 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1480 CodeGen::CodeGenModule &CGM) const override {
1481 if (GV->isDeclaration())
1482 return;
1483 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
1484 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1485 llvm::Function *Fn = cast<llvm::Function>(GV);
1486 Fn->addFnAttr("stackrealign");
1487 }
1488
1489 addX86InterruptAttrs(FD, GV, CGM);
1490 }
1491 }
1492
1493 void checkFunctionCallABI(CodeGenModule &CGM, SourceLocation CallLoc,
1494 const FunctionDecl *Caller,
1495 const FunctionDecl *Callee, const CallArgList &Args,
1496 QualType ReturnType) const override;
1497};
1498} // namespace
1499
1500static void initFeatureMaps(const ASTContext &Ctx,
1501 llvm::StringMap<bool> &CallerMap,
1502 const FunctionDecl *Caller,
1503 llvm::StringMap<bool> &CalleeMap,
1504 const FunctionDecl *Callee) {
1505 if (CalleeMap.empty() && CallerMap.empty()) {
1506 // The caller is potentially nullptr in the case where the call isn't in a
1507 // function. In this case, the getFunctionFeatureMap ensures we just get
1508 // the TU level setting (since it cannot be modified by 'target'..
1509 Ctx.getFunctionFeatureMap(CallerMap, Caller);
1510 Ctx.getFunctionFeatureMap(CalleeMap, Callee);
1511 }
1512}
1513
1515 SourceLocation CallLoc,
1516 const FunctionDecl &Callee,
1517 const llvm::StringMap<bool> &CallerMap,
1518 const llvm::StringMap<bool> &CalleeMap,
1519 QualType Ty, StringRef Feature,
1520 bool IsArgument) {
1521 bool CallerHasFeat = CallerMap.lookup(Feature);
1522 bool CalleeHasFeat = CalleeMap.lookup(Feature);
1523 // No explicit features and the function is internal, be permissive.
1524 if (!CallerHasFeat && !CalleeHasFeat &&
1525 (!Callee.isExternallyVisible() || Callee.hasAttr<AlwaysInlineAttr>()))
1526 return false;
1527
1528 if (!CallerHasFeat && !CalleeHasFeat)
1529 return Diag.Report(CallLoc, diag::warn_avx_calling_convention)
1530 << IsArgument << Ty << Feature;
1531
1532 // Mixing calling conventions here is very clearly an error.
1533 if (!CallerHasFeat || !CalleeHasFeat)
1534 return Diag.Report(CallLoc, diag::err_avx_calling_convention)
1535 << IsArgument << Ty << Feature;
1536
1537 // Else, both caller and callee have the required feature, so there is no need
1538 // to diagnose.
1539 return false;
1540}
1541
1543 SourceLocation CallLoc, const FunctionDecl &Callee,
1544 const llvm::StringMap<bool> &CallerMap,
1545 const llvm::StringMap<bool> &CalleeMap, QualType Ty,
1546 bool IsArgument) {
1547 uint64_t Size = Ctx.getTypeSize(Ty);
1548 if (Size > 256)
1549 return checkAVXParamFeature(Diag, CallLoc, Callee, CallerMap, CalleeMap, Ty,
1550 "avx512f", IsArgument);
1551
1552 if (Size > 128)
1553 return checkAVXParamFeature(Diag, CallLoc, Callee, CallerMap, CalleeMap, Ty,
1554 "avx", IsArgument);
1555
1556 return false;
1557}
1558
1559void X86_64TargetCodeGenInfo::checkFunctionCallABI(CodeGenModule &CGM,
1560 SourceLocation CallLoc,
1561 const FunctionDecl *Caller,
1562 const FunctionDecl *Callee,
1563 const CallArgList &Args,
1564 QualType ReturnType) const {
1565 if (!Callee)
1566 return;
1567
1568 llvm::StringMap<bool> CallerMap;
1569 llvm::StringMap<bool> CalleeMap;
1570 unsigned ArgIndex = 0;
1571
1572 // We need to loop through the actual call arguments rather than the
1573 // function's parameters, in case this variadic.
1574 for (const CallArg &Arg : Args) {
1575 // The "avx" feature changes how vectors >128 in size are passed. "avx512f"
1576 // additionally changes how vectors >256 in size are passed. Like GCC, we
1577 // warn when a function is called with an argument where this will change.
1578 // Unlike GCC, we also error when it is an obvious ABI mismatch, that is,
1579 // the caller and callee features are mismatched.
1580 // Unfortunately, we cannot do this diagnostic in SEMA, since the callee can
1581 // change its ABI with attribute-target after this call.
1582 if (Arg.getType()->isVectorType() &&
1583 CGM.getContext().getTypeSize(Arg.getType()) > 128) {
1584 initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
1585 QualType Ty = Arg.getType();
1586 // The CallArg seems to have desugared the type already, so for clearer
1587 // diagnostics, replace it with the type in the FunctionDecl if possible.
1588 if (ArgIndex < Callee->getNumParams())
1589 Ty = Callee->getParamDecl(ArgIndex)->getType();
1590
1591 if (checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, *Callee,
1592 CallerMap, CalleeMap, Ty, /*IsArgument*/ true))
1593 return;
1594 }
1595 ++ArgIndex;
1596 }
1597
1598 // Check return always, as we don't have a good way of knowing in codegen
1599 // whether this value is used, tail-called, etc.
1600 if (Callee->getReturnType()->isVectorType() &&
1601 CGM.getContext().getTypeSize(Callee->getReturnType()) > 128) {
1602 initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
1603 checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, *Callee, CallerMap,
1604 CalleeMap, Callee->getReturnType(),
1605 /*IsArgument*/ false);
1606 }
1607}
1608
1610 // If the argument does not end in .lib, automatically add the suffix.
1611 // If the argument contains a space, enclose it in quotes.
1612 // This matches the behavior of MSVC.
1613 bool Quote = Lib.contains(' ');
1614 std::string ArgStr = Quote ? "\"" : "";
1615 ArgStr += Lib;
1616 if (!Lib.ends_with_insensitive(".lib") && !Lib.ends_with_insensitive(".a"))
1617 ArgStr += ".lib";
1618 ArgStr += Quote ? "\"" : "";
1619 return ArgStr;
1620}
1621
1622namespace {
1623class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1624public:
1625 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1626 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
1627 unsigned NumRegisterParameters)
1628 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
1629 Win32StructABI, NumRegisterParameters, false) {}
1630
1631 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1632 CodeGen::CodeGenModule &CGM) const override;
1633
1634 void getDependentLibraryOption(llvm::StringRef Lib,
1635 llvm::SmallString<24> &Opt) const override {
1636 Opt = "/DEFAULTLIB:";
1637 Opt += qualifyWindowsLibrary(Lib);
1638 }
1639
1640 void getDetectMismatchOption(llvm::StringRef Name,
1641 llvm::StringRef Value,
1642 llvm::SmallString<32> &Opt) const override {
1643 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
1644 }
1645};
1646} // namespace
1647
1648void WinX86_32TargetCodeGenInfo::setTargetAttributes(
1649 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
1650 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
1651 if (GV->isDeclaration())
1652 return;
1653 addStackProbeTargetAttributes(D, GV, CGM);
1654}
1655
1656namespace {
1657class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1658public:
1659 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1660 X86AVXABILevel AVXLevel)
1661 : TargetCodeGenInfo(std::make_unique<WinX86_64ABIInfo>(CGT, AVXLevel)) {
1662 SwiftInfo =
1663 std::make_unique<SwiftABIInfo>(CGT, /*SwiftErrorInRegister=*/true);
1664 }
1665
1666 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1667 CodeGen::CodeGenModule &CGM) const override;
1668
1669 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
1670 return 7;
1671 }
1672
1673 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1674 llvm::Value *Address) const override {
1675 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
1676
1677 // 0-15 are the 16 integer registers.
1678 // 16 is %rip.
1679 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
1680 return false;
1681 }
1682
1683 void getDependentLibraryOption(llvm::StringRef Lib,
1684 llvm::SmallString<24> &Opt) const override {
1685 Opt = "/DEFAULTLIB:";
1686 Opt += qualifyWindowsLibrary(Lib);
1687 }
1688
1689 void getDetectMismatchOption(llvm::StringRef Name,
1690 llvm::StringRef Value,
1691 llvm::SmallString<32> &Opt) const override {
1692 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
1693 }
1694};
1695} // namespace
1696
1697void WinX86_64TargetCodeGenInfo::setTargetAttributes(
1698 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
1700 if (GV->isDeclaration())
1701 return;
1702 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
1703 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1704 llvm::Function *Fn = cast<llvm::Function>(GV);
1705 Fn->addFnAttr("stackrealign");
1706 }
1707
1708 addX86InterruptAttrs(FD, GV, CGM);
1709 }
1710
1711 addStackProbeTargetAttributes(D, GV, CGM);
1712}
1713
1714void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
1715 Class &Hi) const {
1716 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1717 //
1718 // (a) If one of the classes is Memory, the whole argument is passed in
1719 // memory.
1720 //
1721 // (b) If X87UP is not preceded by X87, the whole argument is passed in
1722 // memory.
1723 //
1724 // (c) If the size of the aggregate exceeds two eightbytes and the first
1725 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
1726 // argument is passed in memory. NOTE: This is necessary to keep the
1727 // ABI working for processors that don't support the __m256 type.
1728 //
1729 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
1730 //
1731 // Some of these are enforced by the merging logic. Others can arise
1732 // only with unions; for example:
1733 // union { _Complex double; unsigned; }
1734 //
1735 // Note that clauses (b) and (c) were added in 0.98.
1736 //
1737 if (Hi == Memory)
1738 Lo = Memory;
1739 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
1740 Lo = Memory;
1741 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
1742 Lo = Memory;
1743 if (Hi == SSEUp && Lo != SSE)
1744 Hi = SSE;
1745}
1746
1747X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
1748 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
1749 // classified recursively so that always two fields are
1750 // considered. The resulting class is calculated according to
1751 // the classes of the fields in the eightbyte:
1752 //
1753 // (a) If both classes are equal, this is the resulting class.
1754 //
1755 // (b) If one of the classes is NO_CLASS, the resulting class is
1756 // the other class.
1757 //
1758 // (c) If one of the classes is MEMORY, the result is the MEMORY
1759 // class.
1760 //
1761 // (d) If one of the classes is INTEGER, the result is the
1762 // INTEGER.
1763 //
1764 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
1765 // MEMORY is used as class.
1766 //
1767 // (f) Otherwise class SSE is used.
1768
1769 // Accum should never be memory (we should have returned) or
1770 // ComplexX87 (because this cannot be passed in a structure).
1771 assert((Accum != Memory && Accum != ComplexX87) &&
1772 "Invalid accumulated classification during merge.");
1773 if (Accum == Field || Field == NoClass)
1774 return Accum;
1775 if (Field == Memory)
1776 return Memory;
1777 if (Accum == NoClass)
1778 return Field;
1779 if (Accum == Integer || Field == Integer)
1780 return Integer;
1781 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
1782 Accum == X87 || Accum == X87Up)
1783 return Memory;
1784 return SSE;
1785}
1786
1787void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase, Class &Lo,
1788 Class &Hi, bool isNamedArg, bool IsRegCall) const {
1789 // FIXME: This code can be simplified by introducing a simple value class for
1790 // Class pairs with appropriate constructor methods for the various
1791 // situations.
1792
1793 // FIXME: Some of the split computations are wrong; unaligned vectors
1794 // shouldn't be passed in registers for example, so there is no chance they
1795 // can straddle an eightbyte. Verify & simplify.
1796
1797 Lo = Hi = NoClass;
1798
1799 Class &Current = OffsetBase < 64 ? Lo : Hi;
1800 Current = Memory;
1801
1802 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
1803 BuiltinType::Kind k = BT->getKind();
1804
1805 if (k == BuiltinType::Void) {
1806 Current = NoClass;
1807 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
1808 Lo = Integer;
1809 Hi = Integer;
1810 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
1811 Current = Integer;
1812 } else if (k == BuiltinType::Float || k == BuiltinType::Double ||
1813 k == BuiltinType::Float16 || k == BuiltinType::BFloat16) {
1814 Current = SSE;
1815 } else if (k == BuiltinType::Float128) {
1816 Lo = SSE;
1817 Hi = SSEUp;
1818 } else if (k == BuiltinType::LongDouble) {
1819 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
1820 if (LDF == &llvm::APFloat::IEEEquad()) {
1821 Lo = SSE;
1822 Hi = SSEUp;
1823 } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
1824 Lo = X87;
1825 Hi = X87Up;
1826 } else if (LDF == &llvm::APFloat::IEEEdouble()) {
1827 Current = SSE;
1828 } else
1829 llvm_unreachable("unexpected long double representation!");
1830 }
1831 // FIXME: _Decimal32 and _Decimal64 are SSE.
1832 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
1833 return;
1834 }
1835
1836 if (const auto *ED = Ty->getAsEnumDecl()) {
1837 // Classify the underlying integer type.
1838 classify(ED->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
1839 return;
1840 }
1841
1842 if (Ty->hasPointerRepresentation()) {
1843 Current = Integer;
1844 return;
1845 }
1846
1847 if (Ty->isMemberPointerType()) {
1848 if (Ty->isMemberFunctionPointerType()) {
1849 if (Has64BitPointers) {
1850 // If Has64BitPointers, this is an {i64, i64}, so classify both
1851 // Lo and Hi now.
1852 Lo = Hi = Integer;
1853 } else {
1854 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
1855 // straddles an eightbyte boundary, Hi should be classified as well.
1856 uint64_t EB_FuncPtr = (OffsetBase) / 64;
1857 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
1858 if (EB_FuncPtr != EB_ThisAdj) {
1859 Lo = Hi = Integer;
1860 } else {
1861 Current = Integer;
1862 }
1863 }
1864 } else {
1865 Current = Integer;
1866 }
1867 return;
1868 }
1869
1870 if (const VectorType *VT = Ty->getAs<VectorType>()) {
1871 uint64_t Size = getContext().getTypeSize(VT);
1872 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
1873 // gcc passes the following as integer:
1874 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
1875 // 2 bytes - <2 x char>, <1 x short>
1876 // 1 byte - <1 x char>
1877 Current = Integer;
1878
1879 // If this type crosses an eightbyte boundary, it should be
1880 // split.
1881 uint64_t EB_Lo = (OffsetBase) / 64;
1882 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
1883 if (EB_Lo != EB_Hi)
1884 Hi = Lo;
1885 } else if (Size == 64) {
1886 QualType ElementType = VT->getElementType();
1887
1888 // gcc passes <1 x double> in memory. :(
1889 if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
1890 return;
1891
1892 // gcc passes <1 x long long> as SSE but clang used to unconditionally
1893 // pass them as integer. For platforms where clang is the de facto
1894 // platform compiler, we must continue to use integer.
1895 if (!classifyIntegerMMXAsSSE() &&
1896 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
1897 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
1898 ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
1899 ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
1900 Current = Integer;
1901 else
1902 Current = SSE;
1903
1904 // If this type crosses an eightbyte boundary, it should be
1905 // split.
1906 if (OffsetBase && OffsetBase != 64)
1907 Hi = Lo;
1908 } else if (Size == 128 ||
1909 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
1910 QualType ElementType = VT->getElementType();
1911
1912 // gcc passes 256 and 512 bit <X x __int128> vectors in memory. :(
1913 if (passInt128VectorsInMem() && Size != 128 &&
1914 (ElementType->isSpecificBuiltinType(BuiltinType::Int128) ||
1915 ElementType->isSpecificBuiltinType(BuiltinType::UInt128)))
1916 return;
1917
1918 // Arguments of 256-bits are split into four eightbyte chunks. The
1919 // least significant one belongs to class SSE and all the others to class
1920 // SSEUP. The original Lo and Hi design considers that types can't be
1921 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
1922 // This design isn't correct for 256-bits, but since there're no cases
1923 // where the upper parts would need to be inspected, avoid adding
1924 // complexity and just consider Hi to match the 64-256 part.
1925 //
1926 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
1927 // registers if they are "named", i.e. not part of the "..." of a
1928 // variadic function.
1929 //
1930 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
1931 // split into eight eightbyte chunks, one SSE and seven SSEUP.
1932 Lo = SSE;
1933 Hi = SSEUp;
1934 }
1935 return;
1936 }
1937
1938 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
1939 QualType ET = getContext().getCanonicalType(CT->getElementType());
1940
1941 uint64_t Size = getContext().getTypeSize(Ty);
1942 if (ET->isIntegralOrEnumerationType()) {
1943 if (Size <= 64)
1944 Current = Integer;
1945 else if (Size <= 128)
1946 Lo = Hi = Integer;
1947 } else if (ET->isFloat16Type() || ET == getContext().FloatTy ||
1948 ET->isBFloat16Type()) {
1949 Current = SSE;
1950 } else if (ET == getContext().DoubleTy) {
1951 Lo = Hi = SSE;
1952 } else if (ET == getContext().LongDoubleTy) {
1953 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
1954 if (LDF == &llvm::APFloat::IEEEquad())
1955 Current = Memory;
1956 else if (LDF == &llvm::APFloat::x87DoubleExtended())
1957 Current = ComplexX87;
1958 else if (LDF == &llvm::APFloat::IEEEdouble())
1959 Lo = Hi = SSE;
1960 else
1961 llvm_unreachable("unexpected long double representation!");
1962 }
1963
1964 // If this complex type crosses an eightbyte boundary then it
1965 // should be split.
1966 uint64_t EB_Real = (OffsetBase) / 64;
1967 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
1968 if (Hi == NoClass && EB_Real != EB_Imag)
1969 Hi = Lo;
1970
1971 return;
1972 }
1973
1974 if (const auto *EITy = Ty->getAs<BitIntType>()) {
1975 if (EITy->getNumBits() <= 64)
1976 Current = Integer;
1977 else if (EITy->getNumBits() <= 128)
1978 Lo = Hi = Integer;
1979 // Larger values need to get passed in memory.
1980 return;
1981 }
1982
1983 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
1984 // Arrays are treated like structures.
1985
1986 uint64_t Size = getContext().getTypeSize(Ty);
1987
1988 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
1989 // than eight eightbytes, ..., it has class MEMORY.
1990 // regcall ABI doesn't have limitation to an object. The only limitation
1991 // is the free registers, which will be checked in computeInfo.
1992 if (!IsRegCall && Size > 512)
1993 return;
1994
1995 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
1996 // fields, it has class MEMORY.
1997 //
1998 // Only need to check alignment of array base.
1999 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
2000 return;
2001
2002 // Otherwise implement simplified merge. We could be smarter about
2003 // this, but it isn't worth it and would be harder to verify.
2004 Current = NoClass;
2005 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
2006 uint64_t ArraySize = AT->getZExtSize();
2007
2008 // The only case a 256-bit wide vector could be used is when the array
2009 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2010 // to work for sizes wider than 128, early check and fallback to memory.
2011 //
2012 if (Size > 128 &&
2013 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
2014 return;
2015
2016 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2017 Class FieldLo, FieldHi;
2018 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
2019 Lo = merge(Lo, FieldLo);
2020 Hi = merge(Hi, FieldHi);
2021 if (Lo == Memory || Hi == Memory)
2022 break;
2023 }
2024
2025 postMerge(Size, Lo, Hi);
2026 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
2027 return;
2028 }
2029
2030 if (const RecordType *RT = Ty->getAsCanonical<RecordType>()) {
2031 uint64_t Size = getContext().getTypeSize(Ty);
2032
2033 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
2034 // than eight eightbytes, ..., it has class MEMORY.
2035 if (Size > 512)
2036 return;
2037
2038 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2039 // copy constructor or a non-trivial destructor, it is passed by invisible
2040 // reference.
2041 if (getRecordArgABI(RT, getCXXABI()))
2042 return;
2043
2044 const RecordDecl *RD = RT->getOriginalDecl()->getDefinitionOrSelf();
2045
2046 // Assume variable sized types are passed in memory.
2047 if (RD->hasFlexibleArrayMember())
2048 return;
2049
2050 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2051
2052 // Reset Lo class, this will be recomputed.
2053 Current = NoClass;
2054
2055 // If this is a C++ record, classify the bases first.
2056 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
2057 for (const auto &I : CXXRD->bases()) {
2058 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
2059 "Unexpected base class!");
2060 const auto *Base = I.getType()->castAsCXXRecordDecl();
2061 // Classify this field.
2062 //
2063 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2064 // single eightbyte, each is classified separately. Each eightbyte gets
2065 // initialized to class NO_CLASS.
2066 Class FieldLo, FieldHi;
2067 uint64_t Offset =
2068 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
2069 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
2070 Lo = merge(Lo, FieldLo);
2071 Hi = merge(Hi, FieldHi);
2072 if (returnCXXRecordGreaterThan128InMem() &&
2073 (Size > 128 && (Size != getContext().getTypeSize(I.getType()) ||
2074 Size > getNativeVectorSizeForAVXABI(AVXLevel)))) {
2075 // The only case a 256(or 512)-bit wide vector could be used to return
2076 // is when CXX record contains a single 256(or 512)-bit element.
2077 Lo = Memory;
2078 }
2079 if (Lo == Memory || Hi == Memory) {
2080 postMerge(Size, Lo, Hi);
2081 return;
2082 }
2083 }
2084 }
2085
2086 // Classify the fields one at a time, merging the results.
2087 unsigned idx = 0;
2088 bool UseClang11Compat = getContext().getLangOpts().getClangABICompat() <=
2089 LangOptions::ClangABI::Ver11 ||
2090 getContext().getTargetInfo().getTriple().isPS();
2091 bool IsUnion = RT->isUnionType() && !UseClang11Compat;
2092
2093 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2094 i != e; ++i, ++idx) {
2095 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2096 bool BitField = i->isBitField();
2097
2098 // Ignore padding bit-fields.
2099 if (BitField && i->isUnnamedBitField())
2100 continue;
2101
2102 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2103 // eight eightbytes, or it contains unaligned fields, it has class MEMORY.
2104 //
2105 // The only case a 256-bit or a 512-bit wide vector could be used is when
2106 // the struct contains a single 256-bit or 512-bit element. Early check
2107 // and fallback to memory.
2108 //
2109 // FIXME: Extended the Lo and Hi logic properly to work for size wider
2110 // than 128.
2111 if (Size > 128 &&
2112 ((!IsUnion && Size != getContext().getTypeSize(i->getType())) ||
2113 Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
2114 Lo = Memory;
2115 postMerge(Size, Lo, Hi);
2116 return;
2117 }
2118
2119 bool IsInMemory =
2120 Offset % getContext().getTypeAlign(i->getType().getCanonicalType());
2121 // Note, skip this test for bit-fields, see below.
2122 if (!BitField && IsInMemory) {
2123 Lo = Memory;
2124 postMerge(Size, Lo, Hi);
2125 return;
2126 }
2127
2128 // Classify this field.
2129 //
2130 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2131 // exceeds a single eightbyte, each is classified
2132 // separately. Each eightbyte gets initialized to class
2133 // NO_CLASS.
2134 Class FieldLo, FieldHi;
2135
2136 // Bit-fields require special handling, they do not force the
2137 // structure to be passed in memory even if unaligned, and
2138 // therefore they can straddle an eightbyte.
2139 if (BitField) {
2140 assert(!i->isUnnamedBitField());
2141 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2142 uint64_t Size = i->getBitWidthValue();
2143
2144 uint64_t EB_Lo = Offset / 64;
2145 uint64_t EB_Hi = (Offset + Size - 1) / 64;
2146
2147 if (EB_Lo) {
2148 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2149 FieldLo = NoClass;
2150 FieldHi = Integer;
2151 } else {
2152 FieldLo = Integer;
2153 FieldHi = EB_Hi ? Integer : NoClass;
2154 }
2155 } else
2156 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
2157 Lo = merge(Lo, FieldLo);
2158 Hi = merge(Hi, FieldHi);
2159 if (Lo == Memory || Hi == Memory)
2160 break;
2161 }
2162
2163 postMerge(Size, Lo, Hi);
2164 }
2165}
2166
2167ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
2168 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2169 // place naturally.
2170 if (!isAggregateTypeForABI(Ty)) {
2171 // Treat an enum type as its underlying type.
2172 if (const auto *ED = Ty->getAsEnumDecl())
2173 Ty = ED->getIntegerType();
2174
2175 if (Ty->isBitIntType())
2176 return getNaturalAlignIndirect(Ty, getDataLayout().getAllocaAddrSpace());
2177
2178 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
2180 }
2181
2182 return getNaturalAlignIndirect(Ty, getDataLayout().getAllocaAddrSpace());
2183}
2184
2185bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2186 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2187 uint64_t Size = getContext().getTypeSize(VecTy);
2188 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
2189 if (Size <= 64 || Size > LargestVector)
2190 return true;
2191 QualType EltTy = VecTy->getElementType();
2192 if (passInt128VectorsInMem() &&
2193 (EltTy->isSpecificBuiltinType(BuiltinType::Int128) ||
2194 EltTy->isSpecificBuiltinType(BuiltinType::UInt128)))
2195 return true;
2196 }
2197
2198 return false;
2199}
2200
2201ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2202 unsigned freeIntRegs) const {
2203 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2204 // place naturally.
2205 //
2206 // This assumption is optimistic, as there could be free registers available
2207 // when we need to pass this argument in memory, and LLVM could try to pass
2208 // the argument in the free register. This does not seem to happen currently,
2209 // but this code would be much safer if we could mark the argument with
2210 // 'onstack'. See PR12193.
2211 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty) &&
2212 !Ty->isBitIntType()) {
2213 // Treat an enum type as its underlying type.
2214 if (const auto *ED = Ty->getAsEnumDecl())
2215 Ty = ED->getIntegerType();
2216
2217 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
2219 }
2220
2221 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
2222 return getNaturalAlignIndirect(Ty, getDataLayout().getAllocaAddrSpace(),
2224
2225 // Compute the byval alignment. We specify the alignment of the byval in all
2226 // cases so that the mid-level optimizer knows the alignment of the byval.
2227 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
2228
2229 // Attempt to avoid passing indirect results using byval when possible. This
2230 // is important for good codegen.
2231 //
2232 // We do this by coercing the value into a scalar type which the backend can
2233 // handle naturally (i.e., without using byval).
2234 //
2235 // For simplicity, we currently only do this when we have exhausted all of the
2236 // free integer registers. Doing this when there are free integer registers
2237 // would require more care, as we would have to ensure that the coerced value
2238 // did not claim the unused register. That would require either reording the
2239 // arguments to the function (so that any subsequent inreg values came first),
2240 // or only doing this optimization when there were no following arguments that
2241 // might be inreg.
2242 //
2243 // We currently expect it to be rare (particularly in well written code) for
2244 // arguments to be passed on the stack when there are still free integer
2245 // registers available (this would typically imply large structs being passed
2246 // by value), so this seems like a fair tradeoff for now.
2247 //
2248 // We can revisit this if the backend grows support for 'onstack' parameter
2249 // attributes. See PR12193.
2250 if (freeIntRegs == 0) {
2251 uint64_t Size = getContext().getTypeSize(Ty);
2252
2253 // If this type fits in an eightbyte, coerce it into the matching integral
2254 // type, which will end up on the stack (with alignment 8).
2255 if (Align == 8 && Size <= 64)
2256 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2257 Size));
2258 }
2259
2261 getDataLayout().getAllocaAddrSpace());
2262}
2263
2264/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2265/// register. Pick an LLVM IR type that will be passed as a vector register.
2266llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
2267 // Wrapper structs/arrays that only contain vectors are passed just like
2268 // vectors; strip them off if present.
2269 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2270 Ty = QualType(InnerTy, 0);
2271
2272 llvm::Type *IRType = CGT.ConvertType(Ty);
2273 if (isa<llvm::VectorType>(IRType)) {
2274 // Don't pass vXi128 vectors in their native type, the backend can't
2275 // legalize them.
2276 if (passInt128VectorsInMem() &&
2277 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy(128)) {
2278 // Use a vXi64 vector.
2279 uint64_t Size = getContext().getTypeSize(Ty);
2280 return llvm::FixedVectorType::get(llvm::Type::getInt64Ty(getVMContext()),
2281 Size / 64);
2282 }
2283
2284 return IRType;
2285 }
2286
2287 if (IRType->getTypeID() == llvm::Type::FP128TyID)
2288 return IRType;
2289
2290 // We couldn't find the preferred IR vector type for 'Ty'.
2291 uint64_t Size = getContext().getTypeSize(Ty);
2292 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
2293
2294
2295 // Return a LLVM IR vector type based on the size of 'Ty'.
2296 return llvm::FixedVectorType::get(llvm::Type::getDoubleTy(getVMContext()),
2297 Size / 64);
2298}
2299
2300/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2301/// is known to either be off the end of the specified type or being in
2302/// alignment padding. The user type specified is known to be at most 128 bits
2303/// in size, and have passed through X86_64ABIInfo::classify with a successful
2304/// classification that put one of the two halves in the INTEGER class.
2305///
2306/// It is conservatively correct to return false.
2307static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2308 unsigned EndBit, ASTContext &Context) {
2309 // If the bytes being queried are off the end of the type, there is no user
2310 // data hiding here. This handles analysis of builtins, vectors and other
2311 // types that don't contain interesting padding.
2312 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2313 if (TySize <= StartBit)
2314 return true;
2315
2316 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2317 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2318 unsigned NumElts = (unsigned)AT->getZExtSize();
2319
2320 // Check each element to see if the element overlaps with the queried range.
2321 for (unsigned i = 0; i != NumElts; ++i) {
2322 // If the element is after the span we care about, then we're done..
2323 unsigned EltOffset = i*EltSize;
2324 if (EltOffset >= EndBit) break;
2325
2326 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2327 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2328 EndBit-EltOffset, Context))
2329 return false;
2330 }
2331 // If it overlaps no elements, then it is safe to process as padding.
2332 return true;
2333 }
2334
2335 if (const auto *RD = Ty->getAsRecordDecl()) {
2336 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2337
2338 // If this is a C++ record, check the bases first.
2339 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
2340 for (const auto &I : CXXRD->bases()) {
2341 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
2342 "Unexpected base class!");
2343 const auto *Base = I.getType()->castAsCXXRecordDecl();
2344
2345 // If the base is after the span we care about, ignore it.
2346 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
2347 if (BaseOffset >= EndBit) continue;
2348
2349 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
2350 if (!BitsContainNoUserData(I.getType(), BaseStart,
2351 EndBit-BaseOffset, Context))
2352 return false;
2353 }
2354 }
2355
2356 // Verify that no field has data that overlaps the region of interest. Yes
2357 // this could be sped up a lot by being smarter about queried fields,
2358 // however we're only looking at structs up to 16 bytes, so we don't care
2359 // much.
2360 unsigned idx = 0;
2361 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2362 i != e; ++i, ++idx) {
2363 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
2364
2365 // If we found a field after the region we care about, then we're done.
2366 if (FieldOffset >= EndBit) break;
2367
2368 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2369 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2370 Context))
2371 return false;
2372 }
2373
2374 // If nothing in this record overlapped the area of interest, then we're
2375 // clean.
2376 return true;
2377 }
2378
2379 return false;
2380}
2381
2382/// getFPTypeAtOffset - Return a floating point type at the specified offset.
2383static llvm::Type *getFPTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
2384 const llvm::DataLayout &TD) {
2385 if (IROffset == 0 && IRType->isFloatingPointTy())
2386 return IRType;
2387
2388 // If this is a struct, recurse into the field at the specified offset.
2389 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
2390 if (!STy->getNumContainedTypes())
2391 return nullptr;
2392
2393 const llvm::StructLayout *SL = TD.getStructLayout(STy);
2394 unsigned Elt = SL->getElementContainingOffset(IROffset);
2395 IROffset -= SL->getElementOffset(Elt);
2396 return getFPTypeAtOffset(STy->getElementType(Elt), IROffset, TD);
2397 }
2398
2399 // If this is an array, recurse into the field at the specified offset.
2400 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2401 llvm::Type *EltTy = ATy->getElementType();
2402 unsigned EltSize = TD.getTypeAllocSize(EltTy);
2403 IROffset -= IROffset / EltSize * EltSize;
2404 return getFPTypeAtOffset(EltTy, IROffset, TD);
2405 }
2406
2407 return nullptr;
2408}
2409
2410/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2411/// low 8 bytes of an XMM register, corresponding to the SSE class.
2412llvm::Type *X86_64ABIInfo::
2413GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
2414 QualType SourceTy, unsigned SourceOffset) const {
2415 const llvm::DataLayout &TD = getDataLayout();
2416 unsigned SourceSize =
2417 (unsigned)getContext().getTypeSize(SourceTy) / 8 - SourceOffset;
2418 llvm::Type *T0 = getFPTypeAtOffset(IRType, IROffset, TD);
2419 if (!T0 || T0->isDoubleTy())
2420 return llvm::Type::getDoubleTy(getVMContext());
2421
2422 // Get the adjacent FP type.
2423 llvm::Type *T1 = nullptr;
2424 unsigned T0Size = TD.getTypeAllocSize(T0);
2425 if (SourceSize > T0Size)
2426 T1 = getFPTypeAtOffset(IRType, IROffset + T0Size, TD);
2427 if (T1 == nullptr) {
2428 // Check if IRType is a half/bfloat + float. float type will be in IROffset+4 due
2429 // to its alignment.
2430 if (T0->is16bitFPTy() && SourceSize > 4)
2431 T1 = getFPTypeAtOffset(IRType, IROffset + 4, TD);
2432 // If we can't get a second FP type, return a simple half or float.
2433 // avx512fp16-abi.c:pr51813_2 shows it works to return float for
2434 // {float, i8} too.
2435 if (T1 == nullptr)
2436 return T0;
2437 }
2438
2439 if (T0->isFloatTy() && T1->isFloatTy())
2440 return llvm::FixedVectorType::get(T0, 2);
2441
2442 if (T0->is16bitFPTy() && T1->is16bitFPTy()) {
2443 llvm::Type *T2 = nullptr;
2444 if (SourceSize > 4)
2445 T2 = getFPTypeAtOffset(IRType, IROffset + 4, TD);
2446 if (T2 == nullptr)
2447 return llvm::FixedVectorType::get(T0, 2);
2448 return llvm::FixedVectorType::get(T0, 4);
2449 }
2450
2451 if (T0->is16bitFPTy() || T1->is16bitFPTy())
2452 return llvm::FixedVectorType::get(llvm::Type::getHalfTy(getVMContext()), 4);
2453
2454 return llvm::Type::getDoubleTy(getVMContext());
2455}
2456
2457/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2458/// one or more 8-byte GPRs. This means that we either have a scalar or we are
2459/// talking about the high and/or low part of an up-to-16-byte struct. This
2460/// routine picks the best LLVM IR type to represent this, which may be i64 or
2461/// may be anything else that the backend will pass in GPRs that works better
2462/// (e.g. i8, %foo*, etc).
2463///
2464/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2465/// the source type. IROffset is an offset in bytes into the LLVM IR type that
2466/// the 8-byte value references. PrefType may be null.
2467///
2468/// SourceTy is the source-level type for the entire argument. SourceOffset is
2469/// an offset into this that we're processing (which is always either 0 or 8).
2470///
2471llvm::Type *X86_64ABIInfo::
2472GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
2473 QualType SourceTy, unsigned SourceOffset) const {
2474 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2475 // returning an 8-byte unit starting with it. See if we can safely use it.
2476 if (IROffset == 0) {
2477 // Pointers and int64's always fill the 8-byte unit.
2478 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2479 IRType->isIntegerTy(64))
2480 return IRType;
2481
2482 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2483 // goodness in the source type is just tail padding. This is allowed to
2484 // kick in for struct {double,int} on the int, but not on
2485 // struct{double,int,int} because we wouldn't return the second int. We
2486 // have to do this analysis on the source type because we can't depend on
2487 // unions being lowered a specific way etc.
2488 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
2489 IRType->isIntegerTy(32) ||
2490 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2491 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2492 cast<llvm::IntegerType>(IRType)->getBitWidth();
2493
2494 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2495 SourceOffset*8+64, getContext()))
2496 return IRType;
2497 }
2498 }
2499
2500 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
2501 // If this is a struct, recurse into the field at the specified offset.
2502 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
2503 if (IROffset < SL->getSizeInBytes()) {
2504 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2505 IROffset -= SL->getElementOffset(FieldIdx);
2506
2507 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2508 SourceTy, SourceOffset);
2509 }
2510 }
2511
2512 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2513 llvm::Type *EltTy = ATy->getElementType();
2514 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
2515 unsigned EltOffset = IROffset/EltSize*EltSize;
2516 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2517 SourceOffset);
2518 }
2519
2520 // if we have a 128-bit integer, we can pass it safely using an i128
2521 // so we return that
2522 if (IRType->isIntegerTy(128)) {
2523 assert(IROffset == 0);
2524 return IRType;
2525 }
2526
2527 // Okay, we don't have any better idea of what to pass, so we pass this in an
2528 // integer register that isn't too big to fit the rest of the struct.
2529 unsigned TySizeInBytes =
2530 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
2531
2532 assert(TySizeInBytes != SourceOffset && "Empty field?");
2533
2534 // It is always safe to classify this as an integer type up to i64 that
2535 // isn't larger than the structure.
2536 return llvm::IntegerType::get(getVMContext(),
2537 std::min(TySizeInBytes-SourceOffset, 8U)*8);
2538}
2539
2540
2541/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2542/// be used as elements of a two register pair to pass or return, return a
2543/// first class aggregate to represent them. For example, if the low part of
2544/// a by-value argument should be passed as i32* and the high part as float,
2545/// return {i32*, float}.
2546static llvm::Type *
2547GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
2548 const llvm::DataLayout &TD) {
2549 // In order to correctly satisfy the ABI, we need to the high part to start
2550 // at offset 8. If the high and low parts we inferred are both 4-byte types
2551 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2552 // the second element at offset 8. Check for this:
2553 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2554 llvm::Align HiAlign = TD.getABITypeAlign(Hi);
2555 unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
2556 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
2557
2558 // To handle this, we have to increase the size of the low part so that the
2559 // second element will start at an 8 byte offset. We can't increase the size
2560 // of the second element because it might make us access off the end of the
2561 // struct.
2562 if (HiStart != 8) {
2563 // There are usually two sorts of types the ABI generation code can produce
2564 // for the low part of a pair that aren't 8 bytes in size: half, float or
2565 // i8/i16/i32. This can also include pointers when they are 32-bit (X32).
2566 // Promote these to a larger type.
2567 if (Lo->isHalfTy() || Lo->isFloatTy())
2568 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2569 else {
2570 assert((Lo->isIntegerTy() || Lo->isPointerTy())
2571 && "Invalid/unknown lo type");
2572 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2573 }
2574 }
2575
2576 llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
2577
2578 // Verify that the second element is at an 8-byte offset.
2579 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2580 "Invalid x86-64 argument pair!");
2581 return Result;
2582}
2583
2584ABIArgInfo X86_64ABIInfo::classifyReturnType(QualType RetTy) const {
2585 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2586 // classification algorithm.
2587 X86_64ABIInfo::Class Lo, Hi;
2588 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
2589
2590 // Check some invariants.
2591 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
2592 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2593
2594 llvm::Type *ResType = nullptr;
2595 switch (Lo) {
2596 case NoClass:
2597 if (Hi == NoClass)
2598 return ABIArgInfo::getIgnore();
2599 // If the low part is just padding, it takes no register, leave ResType
2600 // null.
2601 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2602 "Unknown missing lo part");
2603 break;
2604
2605 case SSEUp:
2606 case X87Up:
2607 llvm_unreachable("Invalid classification for lo word.");
2608
2609 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2610 // hidden argument.
2611 case Memory:
2612 return getIndirectReturnResult(RetTy);
2613
2614 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2615 // available register of the sequence %rax, %rdx is used.
2616 case Integer:
2617 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
2618
2619 // If we have a sign or zero extended integer, make sure to return Extend
2620 // so that the parameter gets the right LLVM IR attributes.
2621 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2622 // Treat an enum type as its underlying type.
2623 if (const auto *ED = RetTy->getAsEnumDecl())
2624 RetTy = ED->getIntegerType();
2625
2626 if (RetTy->isIntegralOrEnumerationType() &&
2627 isPromotableIntegerTypeForABI(RetTy))
2628 return ABIArgInfo::getExtend(RetTy);
2629 }
2630
2631 if (ResType->isIntegerTy(128)) {
2632 // i128 are passed directly
2633 assert(Hi == Integer);
2634 return ABIArgInfo::getDirect(ResType);
2635 }
2636 break;
2637
2638 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2639 // available SSE register of the sequence %xmm0, %xmm1 is used.
2640 case SSE:
2641 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
2642 break;
2643
2644 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2645 // returned on the X87 stack in %st0 as 80-bit x87 number.
2646 case X87:
2647 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
2648 break;
2649
2650 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2651 // part of the value is returned in %st0 and the imaginary part in
2652 // %st1.
2653 case ComplexX87:
2654 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
2655 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
2656 llvm::Type::getX86_FP80Ty(getVMContext()));
2657 break;
2658 }
2659
2660 llvm::Type *HighPart = nullptr;
2661 switch (Hi) {
2662 // Memory was handled previously and X87 should
2663 // never occur as a hi class.
2664 case Memory:
2665 case X87:
2666 llvm_unreachable("Invalid classification for hi word.");
2667
2668 case ComplexX87: // Previously handled.
2669 case NoClass:
2670 break;
2671
2672 case Integer:
2673 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
2674 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2675 return ABIArgInfo::getDirect(HighPart, 8);
2676 break;
2677 case SSE:
2678 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
2679 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2680 return ABIArgInfo::getDirect(HighPart, 8);
2681 break;
2682
2683 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
2684 // is passed in the next available eightbyte chunk if the last used
2685 // vector register.
2686 //
2687 // SSEUP should always be preceded by SSE, just widen.
2688 case SSEUp:
2689 assert(Lo == SSE && "Unexpected SSEUp classification.");
2690 ResType = GetByteVectorType(RetTy);
2691 break;
2692
2693 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2694 // returned together with the previous X87 value in %st0.
2695 case X87Up:
2696 // If X87Up is preceded by X87, we don't need to do
2697 // anything. However, in some cases with unions it may not be
2698 // preceded by X87. In such situations we follow gcc and pass the
2699 // extra bits in an SSE reg.
2700 if (Lo != X87) {
2701 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
2702 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2703 return ABIArgInfo::getDirect(HighPart, 8);
2704 }
2705 break;
2706 }
2707
2708 // If a high part was specified, merge it together with the low part. It is
2709 // known to pass in the high eightbyte of the result. We do this by forming a
2710 // first class struct aggregate with the high and low part: {low, high}
2711 if (HighPart)
2712 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
2713
2714 return ABIArgInfo::getDirect(ResType);
2715}
2716
2717ABIArgInfo
2718X86_64ABIInfo::classifyArgumentType(QualType Ty, unsigned freeIntRegs,
2719 unsigned &neededInt, unsigned &neededSSE,
2720 bool isNamedArg, bool IsRegCall) const {
2722
2723 X86_64ABIInfo::Class Lo, Hi;
2724 classify(Ty, 0, Lo, Hi, isNamedArg, IsRegCall);
2725
2726 // Check some invariants.
2727 // FIXME: Enforce these by construction.
2728 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
2729 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2730
2731 neededInt = 0;
2732 neededSSE = 0;
2733 llvm::Type *ResType = nullptr;
2734 switch (Lo) {
2735 case NoClass:
2736 if (Hi == NoClass)
2737 return ABIArgInfo::getIgnore();
2738 // If the low part is just padding, it takes no register, leave ResType
2739 // null.
2740 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2741 "Unknown missing lo part");
2742 break;
2743
2744 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2745 // on the stack.
2746 case Memory:
2747
2748 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
2749 // COMPLEX_X87, it is passed in memory.
2750 case X87:
2751 case ComplexX87:
2752 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
2753 ++neededInt;
2754 return getIndirectResult(Ty, freeIntRegs);
2755
2756 case SSEUp:
2757 case X87Up:
2758 llvm_unreachable("Invalid classification for lo word.");
2759
2760 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
2761 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
2762 // and %r9 is used.
2763 case Integer:
2764 ++neededInt;
2765
2766 // Pick an 8-byte type based on the preferred type.
2767 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
2768
2769 // If we have a sign or zero extended integer, make sure to return Extend
2770 // so that the parameter gets the right LLVM IR attributes.
2771 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2772 // Treat an enum type as its underlying type.
2773 if (const auto *ED = Ty->getAsEnumDecl())
2774 Ty = ED->getIntegerType();
2775
2776 if (Ty->isIntegralOrEnumerationType() &&
2777 isPromotableIntegerTypeForABI(Ty))
2778 return ABIArgInfo::getExtend(Ty, CGT.ConvertType(Ty));
2779 }
2780
2781 if (ResType->isIntegerTy(128)) {
2782 assert(Hi == Integer);
2783 ++neededInt;
2784 return ABIArgInfo::getDirect(ResType);
2785 }
2786 break;
2787
2788 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
2789 // available SSE register is used, the registers are taken in the
2790 // order from %xmm0 to %xmm7.
2791 case SSE: {
2792 llvm::Type *IRType = CGT.ConvertType(Ty);
2793 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
2794 ++neededSSE;
2795 break;
2796 }
2797 }
2798
2799 llvm::Type *HighPart = nullptr;
2800 switch (Hi) {
2801 // Memory was handled previously, ComplexX87 and X87 should
2802 // never occur as hi classes, and X87Up must be preceded by X87,
2803 // which is passed in memory.
2804 case Memory:
2805 case X87:
2806 case ComplexX87:
2807 llvm_unreachable("Invalid classification for hi word.");
2808
2809 case NoClass: break;
2810
2811 case Integer:
2812 ++neededInt;
2813 // Pick an 8-byte type based on the preferred type.
2814 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
2815
2816 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2817 return ABIArgInfo::getDirect(HighPart, 8);
2818 break;
2819
2820 // X87Up generally doesn't occur here (long double is passed in
2821 // memory), except in situations involving unions.
2822 case X87Up:
2823 case SSE:
2824 ++neededSSE;
2825 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
2826
2827 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2828 return ABIArgInfo::getDirect(HighPart, 8);
2829 break;
2830
2831 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
2832 // eightbyte is passed in the upper half of the last used SSE
2833 // register. This only happens when 128-bit vectors are passed.
2834 case SSEUp:
2835 assert(Lo == SSE && "Unexpected SSEUp classification");
2836 ResType = GetByteVectorType(Ty);
2837 break;
2838 }
2839
2840 // If a high part was specified, merge it together with the low part. It is
2841 // known to pass in the high eightbyte of the result. We do this by forming a
2842 // first class struct aggregate with the high and low part: {low, high}
2843 if (HighPart)
2844 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
2845
2846 return ABIArgInfo::getDirect(ResType);
2847}
2848
2849ABIArgInfo
2850X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
2851 unsigned &NeededSSE,
2852 unsigned &MaxVectorWidth) const {
2853 auto *RD = cast<RecordType>(Ty.getCanonicalType())
2854 ->getOriginalDecl()
2855 ->getDefinitionOrSelf();
2856
2857 if (RD->hasFlexibleArrayMember())
2858 return getIndirectReturnResult(Ty);
2859
2860 // Sum up bases
2861 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
2862 if (CXXRD->isDynamicClass()) {
2863 NeededInt = NeededSSE = 0;
2864 return getIndirectReturnResult(Ty);
2865 }
2866
2867 for (const auto &I : CXXRD->bases())
2868 if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE,
2869 MaxVectorWidth)
2870 .isIndirect()) {
2871 NeededInt = NeededSSE = 0;
2872 return getIndirectReturnResult(Ty);
2873 }
2874 }
2875
2876 // Sum up members
2877 for (const auto *FD : RD->fields()) {
2878 QualType MTy = FD->getType();
2879 if (MTy->isRecordType() && !MTy->isUnionType()) {
2880 if (classifyRegCallStructTypeImpl(MTy, NeededInt, NeededSSE,
2881 MaxVectorWidth)
2882 .isIndirect()) {
2883 NeededInt = NeededSSE = 0;
2884 return getIndirectReturnResult(Ty);
2885 }
2886 } else {
2887 unsigned LocalNeededInt, LocalNeededSSE;
2888 if (classifyArgumentType(MTy, UINT_MAX, LocalNeededInt, LocalNeededSSE,
2889 true, true)
2890 .isIndirect()) {
2891 NeededInt = NeededSSE = 0;
2892 return getIndirectReturnResult(Ty);
2893 }
2894 if (const auto *AT = getContext().getAsConstantArrayType(MTy))
2895 MTy = AT->getElementType();
2896 if (const auto *VT = MTy->getAs<VectorType>())
2897 if (getContext().getTypeSize(VT) > MaxVectorWidth)
2898 MaxVectorWidth = getContext().getTypeSize(VT);
2899 NeededInt += LocalNeededInt;
2900 NeededSSE += LocalNeededSSE;
2901 }
2902 }
2903
2904 return ABIArgInfo::getDirect();
2905}
2906
2907ABIArgInfo
2908X86_64ABIInfo::classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
2909 unsigned &NeededSSE,
2910 unsigned &MaxVectorWidth) const {
2911
2912 NeededInt = 0;
2913 NeededSSE = 0;
2914 MaxVectorWidth = 0;
2915
2916 return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE,
2917 MaxVectorWidth);
2918}
2919
2920void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2921
2922 const unsigned CallingConv = FI.getCallingConvention();
2923 // It is possible to force Win64 calling convention on any x86_64 target by
2924 // using __attribute__((ms_abi)). In such case to correctly emit Win64
2925 // compatible code delegate this call to WinX86_64ABIInfo::computeInfo.
2926 if (CallingConv == llvm::CallingConv::Win64) {
2927 WinX86_64ABIInfo Win64ABIInfo(CGT, AVXLevel);
2928 Win64ABIInfo.computeInfo(FI);
2929 return;
2930 }
2931
2932 bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall;
2933
2934 // Keep track of the number of assigned registers.
2935 unsigned FreeIntRegs = IsRegCall ? 11 : 6;
2936 unsigned FreeSSERegs = IsRegCall ? 16 : 8;
2937 unsigned NeededInt = 0, NeededSSE = 0, MaxVectorWidth = 0;
2938
2939 if (!::classifyReturnType(getCXXABI(), FI, *this)) {
2940 if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
2941 !FI.getReturnType()->getTypePtr()->isUnionType()) {
2942 FI.getReturnInfo() = classifyRegCallStructType(
2943 FI.getReturnType(), NeededInt, NeededSSE, MaxVectorWidth);
2944 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
2945 FreeIntRegs -= NeededInt;
2946 FreeSSERegs -= NeededSSE;
2947 } else {
2948 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
2949 }
2950 } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>() &&
2951 getContext().getCanonicalType(FI.getReturnType()
2952 ->getAs<ComplexType>()
2953 ->getElementType()) ==
2954 getContext().LongDoubleTy)
2955 // Complex Long Double Type is passed in Memory when Regcall
2956 // calling convention is used.
2957 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
2958 else
2960 }
2961
2962 // If the return value is indirect, then the hidden argument is consuming one
2963 // integer register.
2964 if (FI.getReturnInfo().isIndirect())
2965 --FreeIntRegs;
2966 else if (NeededSSE && MaxVectorWidth > 0)
2967 FI.setMaxVectorWidth(MaxVectorWidth);
2968
2969 // The chain argument effectively gives us another free register.
2970 if (FI.isChainCall())
2971 ++FreeIntRegs;
2972
2973 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
2974 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
2975 // get assigned (in left-to-right order) for passing as follows...
2976 unsigned ArgNo = 0;
2977 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2978 it != ie; ++it, ++ArgNo) {
2979 bool IsNamedArg = ArgNo < NumRequiredArgs;
2980
2981 if (IsRegCall && it->type->isStructureOrClassType())
2982 it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE,
2983 MaxVectorWidth);
2984 else
2985 it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
2986 NeededSSE, IsNamedArg);
2987
2988 // AMD64-ABI 3.2.3p3: If there are no registers available for any
2989 // eightbyte of an argument, the whole argument is passed on the
2990 // stack. If registers have already been assigned for some
2991 // eightbytes of such an argument, the assignments get reverted.
2992 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
2993 FreeIntRegs -= NeededInt;
2994 FreeSSERegs -= NeededSSE;
2995 if (MaxVectorWidth > FI.getMaxVectorWidth())
2996 FI.setMaxVectorWidth(MaxVectorWidth);
2997 } else {
2998 it->info = getIndirectResult(it->type, FreeIntRegs);
2999 }
3000 }
3001}
3002
3004 Address VAListAddr, QualType Ty) {
3005 Address overflow_arg_area_p =
3006 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
3007 llvm::Value *overflow_arg_area =
3008 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3009
3010 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3011 // byte boundary if alignment needed by type exceeds 8 byte boundary.
3012 // It isn't stated explicitly in the standard, but in practice we use
3013 // alignment greater than 16 where necessary.
3014 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3015 if (Align > CharUnits::fromQuantity(8)) {
3016 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3017 Align);
3018 }
3019
3020 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
3021 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
3022 llvm::Value *Res = overflow_arg_area;
3023
3024 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3025 // l->overflow_arg_area + sizeof(type).
3026 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3027 // an 8 byte boundary.
3028
3029 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
3030 llvm::Value *Offset =
3031 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
3032 overflow_arg_area = CGF.Builder.CreateGEP(CGF.Int8Ty, overflow_arg_area,
3033 Offset, "overflow_arg_area.next");
3034 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3035
3036 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
3037 return Address(Res, LTy, Align);
3038}
3039
3040RValue X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3041 QualType Ty, AggValueSlot Slot) const {
3042 // Assume that va_list type is correct; should be pointer to LLVM type:
3043 // struct {
3044 // i32 gp_offset;
3045 // i32 fp_offset;
3046 // i8* overflow_arg_area;
3047 // i8* reg_save_area;
3048 // };
3049 unsigned neededInt, neededSSE;
3050
3051 Ty = getContext().getCanonicalType(Ty);
3052 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
3053 /*isNamedArg*/false);
3054
3055 // Empty records are ignored for parameter passing purposes.
3056 if (AI.isIgnore())
3057 return Slot.asRValue();
3058
3059 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3060 // in the registers. If not go to step 7.
3061 if (!neededInt && !neededSSE)
3062 return CGF.EmitLoadOfAnyValue(
3063 CGF.MakeAddrLValue(EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty), Ty),
3064 Slot);
3065
3066 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3067 // general purpose registers needed to pass type and num_fp to hold
3068 // the number of floating point registers needed.
3069
3070 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3071 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3072 // l->fp_offset > 304 - num_fp * 16 go to step 7.
3073 //
3074 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3075 // register save space).
3076
3077 llvm::Value *InRegs = nullptr;
3078 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3079 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
3080 if (neededInt) {
3081 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
3082 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
3083 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3084 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
3085 }
3086
3087 if (neededSSE) {
3088 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
3089 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3090 llvm::Value *FitsInFP =
3091 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3092 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
3093 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3094 }
3095
3096 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3097 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3098 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3099 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3100
3101 // Emit code to load the value if it was passed in registers.
3102
3103 CGF.EmitBlock(InRegBlock);
3104
3105 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3106 // an offset of l->gp_offset and/or l->fp_offset. This may require
3107 // copying to a temporary location in case the parameter is passed
3108 // in different register classes or requires an alignment greater
3109 // than 8 for general purpose registers and 16 for XMM registers.
3110 //
3111 // FIXME: This really results in shameful code when we end up needing to
3112 // collect arguments from different places; often what should result in a
3113 // simple assembling of a structure from scattered addresses has many more
3114 // loads than necessary. Can we clean this up?
3115 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
3116 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
3117 CGF.Builder.CreateStructGEP(VAListAddr, 3), "reg_save_area");
3118
3119 Address RegAddr = Address::invalid();
3120 if (neededInt && neededSSE) {
3121 // FIXME: Cleanup.
3122 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
3123 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
3124 Address Tmp = CGF.CreateMemTemp(Ty);
3125 Tmp = Tmp.withElementType(ST);
3126 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
3127 llvm::Type *TyLo = ST->getElementType(0);
3128 llvm::Type *TyHi = ST->getElementType(1);
3129 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
3130 "Unexpected ABI info for mixed regs");
3131 llvm::Value *GPAddr =
3132 CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, gp_offset);
3133 llvm::Value *FPAddr =
3134 CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, fp_offset);
3135 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3136 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
3137
3138 // Copy the first element.
3139 // FIXME: Our choice of alignment here and below is probably pessimistic.
3140 llvm::Value *V = CGF.Builder.CreateAlignedLoad(
3141 TyLo, RegLoAddr,
3142 CharUnits::fromQuantity(getDataLayout().getABITypeAlign(TyLo)));
3143 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
3144
3145 // Copy the second element.
3147 TyHi, RegHiAddr,
3148 CharUnits::fromQuantity(getDataLayout().getABITypeAlign(TyHi)));
3149 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
3150
3151 RegAddr = Tmp.withElementType(LTy);
3152 } else if (neededInt || neededSSE == 1) {
3153 // Copy to a temporary if necessary to ensure the appropriate alignment.
3154 auto TInfo = getContext().getTypeInfoInChars(Ty);
3155 uint64_t TySize = TInfo.Width.getQuantity();
3156 CharUnits TyAlign = TInfo.Align;
3157 llvm::Type *CoTy = nullptr;
3158 if (AI.isDirect())
3159 CoTy = AI.getCoerceToType();
3160
3161 llvm::Value *GpOrFpOffset = neededInt ? gp_offset : fp_offset;
3162 uint64_t Alignment = neededInt ? 8 : 16;
3163 uint64_t RegSize = neededInt ? neededInt * 8 : 16;
3164 // There are two cases require special handling:
3165 // 1)
3166 // ```
3167 // struct {
3168 // struct {} a[8];
3169 // int b;
3170 // };
3171 // ```
3172 // The lower 8 bytes of the structure are not stored,
3173 // so an 8-byte offset is needed when accessing the structure.
3174 // 2)
3175 // ```
3176 // struct {
3177 // long long a;
3178 // struct {} b;
3179 // };
3180 // ```
3181 // The stored size of this structure is smaller than its actual size,
3182 // which may lead to reading past the end of the register save area.
3183 if (CoTy && (AI.getDirectOffset() == 8 || RegSize < TySize)) {
3184 Address Tmp = CGF.CreateMemTemp(Ty);
3185 llvm::Value *Addr =
3186 CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, GpOrFpOffset);
3187 llvm::Value *Src = CGF.Builder.CreateAlignedLoad(CoTy, Addr, TyAlign);
3188 llvm::Value *PtrOffset =
3189 llvm::ConstantInt::get(CGF.Int32Ty, AI.getDirectOffset());
3190 Address Dst = Address(
3191 CGF.Builder.CreateGEP(CGF.Int8Ty, Tmp.getBasePointer(), PtrOffset),
3192 LTy, TyAlign);
3193 CGF.Builder.CreateStore(Src, Dst);
3194 RegAddr = Tmp.withElementType(LTy);
3195 } else {
3196 RegAddr =
3197 Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, GpOrFpOffset),
3198 LTy, CharUnits::fromQuantity(Alignment));
3199
3200 // Copy into a temporary if the type is more aligned than the
3201 // register save area.
3202 if (neededInt && TyAlign.getQuantity() > 8) {
3203 Address Tmp = CGF.CreateMemTemp(Ty);
3204 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
3205 RegAddr = Tmp;
3206 }
3207 }
3208
3209 } else {
3210 assert(neededSSE == 2 && "Invalid number of needed registers!");
3211 // SSE registers are spaced 16 bytes apart in the register save
3212 // area, we need to collect the two eightbytes together.
3213 // The ABI isn't explicit about this, but it seems reasonable
3214 // to assume that the slots are 16-byte aligned, since the stack is
3215 // naturally 16-byte aligned and the prologue is expected to store
3216 // all the SSE registers to the RSA.
3217 Address RegAddrLo = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea,
3218 fp_offset),
3220 Address RegAddrHi =
3221 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3223 llvm::Type *ST = AI.canHaveCoerceToType()
3224 ? AI.getCoerceToType()
3225 : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy);
3226 llvm::Value *V;
3227 Address Tmp = CGF.CreateMemTemp(Ty);
3228 Tmp = Tmp.withElementType(ST);
3229 V = CGF.Builder.CreateLoad(
3230 RegAddrLo.withElementType(ST->getStructElementType(0)));
3231 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
3232 V = CGF.Builder.CreateLoad(
3233 RegAddrHi.withElementType(ST->getStructElementType(1)));
3234 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
3235
3236 RegAddr = Tmp.withElementType(LTy);
3237 }
3238
3239 // AMD64-ABI 3.5.7p5: Step 5. Set:
3240 // l->gp_offset = l->gp_offset + num_gp * 8
3241 // l->fp_offset = l->fp_offset + num_fp * 16.
3242 if (neededInt) {
3243 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
3244 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3245 gp_offset_p);
3246 }
3247 if (neededSSE) {
3248 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
3249 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3250 fp_offset_p);
3251 }
3252 CGF.EmitBranch(ContBlock);
3253
3254 // Emit code to load the value if it was passed in memory.
3255
3256 CGF.EmitBlock(InMemBlock);
3257 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
3258
3259 // Return the appropriate result.
3260
3261 CGF.EmitBlock(ContBlock);
3262 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
3263 "vaarg.addr");
3264 return CGF.EmitLoadOfAnyValue(CGF.MakeAddrLValue(ResAddr, Ty), Slot);
3265}
3266
3267RValue X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
3268 QualType Ty, AggValueSlot Slot) const {
3269 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3270 // not 1, 2, 4, or 8 bytes, must be passed by reference."
3271 uint64_t Width = getContext().getTypeSize(Ty);
3272 bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
3273
3274 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
3277 /*allowHigherAlign*/ false, Slot);
3278}
3279
3280ABIArgInfo WinX86_64ABIInfo::reclassifyHvaArgForVectorCall(
3281 QualType Ty, unsigned &FreeSSERegs, const ABIArgInfo &current) const {
3282 const Type *Base = nullptr;
3283 uint64_t NumElts = 0;
3284
3285 if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
3286 isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
3287 FreeSSERegs -= NumElts;
3288 return getDirectX86Hva();
3289 }
3290 return current;
3291}
3292
3293ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
3294 bool IsReturnType, bool IsVectorCall,
3295 bool IsRegCall) const {
3296
3297 if (Ty->isVoidType())
3298 return ABIArgInfo::getIgnore();
3299
3300 if (const auto *ED = Ty->getAsEnumDecl())
3301 Ty = ED->getIntegerType();
3302
3303 TypeInfo Info = getContext().getTypeInfo(Ty);
3304 uint64_t Width = Info.Width;
3305 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
3306
3307 const RecordType *RT = Ty->getAsCanonical<RecordType>();
3308 if (RT) {
3309 if (!IsReturnType) {
3310 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
3311 return getNaturalAlignIndirect(Ty, getDataLayout().getAllocaAddrSpace(),
3313 }
3314
3315 if (RT->getOriginalDecl()->getDefinitionOrSelf()->hasFlexibleArrayMember())
3316 return getNaturalAlignIndirect(Ty, getDataLayout().getAllocaAddrSpace(),
3317 /*ByVal=*/false);
3318 }
3319
3320 const Type *Base = nullptr;
3321 uint64_t NumElts = 0;
3322 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3323 // other targets.
3324 if ((IsVectorCall || IsRegCall) &&
3325 isHomogeneousAggregate(Ty, Base, NumElts)) {
3326 if (IsRegCall) {
3327 if (FreeSSERegs >= NumElts) {
3328 FreeSSERegs -= NumElts;
3329 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3330 return ABIArgInfo::getDirect();
3331 return ABIArgInfo::getExpand();
3332 }
3334 Align, /*AddrSpace=*/getDataLayout().getAllocaAddrSpace(),
3335 /*ByVal=*/false);
3336 } else if (IsVectorCall) {
3337 if (FreeSSERegs >= NumElts &&
3338 (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
3339 FreeSSERegs -= NumElts;
3340 return ABIArgInfo::getDirect();
3341 } else if (IsReturnType) {
3342 return ABIArgInfo::getExpand();
3343 } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
3344 // HVAs are delayed and reclassified in the 2nd step.
3346 Align, /*AddrSpace=*/getDataLayout().getAllocaAddrSpace(),
3347 /*ByVal=*/false);
3348 }
3349 }
3350 }
3351
3352 if (Ty->isMemberPointerType()) {
3353 // If the member pointer is represented by an LLVM int or ptr, pass it
3354 // directly.
3355 llvm::Type *LLTy = CGT.ConvertType(Ty);
3356 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3357 return ABIArgInfo::getDirect();
3358 }
3359
3360 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
3361 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3362 // not 1, 2, 4, or 8 bytes, must be passed by reference."
3363 if (Width > 64 || !llvm::isPowerOf2_64(Width))
3364 return getNaturalAlignIndirect(Ty, getDataLayout().getAllocaAddrSpace(),
3365 /*ByVal=*/false);
3366
3367 // Otherwise, coerce it to a small integer.
3368 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
3369 }
3370
3371 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3372 switch (BT->getKind()) {
3373 case BuiltinType::Bool:
3374 // Bool type is always extended to the ABI, other builtin types are not
3375 // extended.
3376 return ABIArgInfo::getExtend(Ty);
3377
3378 case BuiltinType::LongDouble:
3379 // Mingw64 GCC uses the old 80 bit extended precision floating point
3380 // unit. It passes them indirectly through memory.
3381 if (IsMingw64) {
3382 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
3383 if (LDF == &llvm::APFloat::x87DoubleExtended())
3385 Align, /*AddrSpace=*/getDataLayout().getAllocaAddrSpace(),
3386 /*ByVal=*/false);
3387 }
3388 break;
3389
3390 case BuiltinType::Int128:
3391 case BuiltinType::UInt128:
3392 case BuiltinType::Float128:
3393 // 128-bit float and integer types share the same ABI.
3394
3395 // If it's a parameter type, the normal ABI rule is that arguments larger
3396 // than 8 bytes are passed indirectly. GCC follows it. We follow it too,
3397 // even though it isn't particularly efficient.
3398 if (!IsReturnType)
3400 Align, /*AddrSpace=*/getDataLayout().getAllocaAddrSpace(),
3401 /*ByVal=*/false);
3402
3403 // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that.
3404 // Clang matches them for compatibility.
3405 // NOTE: GCC actually returns f128 indirectly but will hopefully change.
3406 // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=115054#c8.
3407 return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
3408 llvm::Type::getInt64Ty(getVMContext()), 2));
3409
3410 default:
3411 break;
3412 }
3413 }
3414
3415 if (Ty->isBitIntType()) {
3416 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3417 // not 1, 2, 4, or 8 bytes, must be passed by reference."
3418 // However, non-power-of-two bit-precise integers will be passed as 1, 2, 4,
3419 // or 8 bytes anyway as long is it fits in them, so we don't have to check
3420 // the power of 2.
3421 if (Width <= 64)
3422 return ABIArgInfo::getDirect();
3424 Align, /*AddrSpace=*/getDataLayout().getAllocaAddrSpace(),
3425 /*ByVal=*/false);
3426 }
3427
3428 return ABIArgInfo::getDirect();
3429}
3430
3431void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3432 const unsigned CC = FI.getCallingConvention();
3433 bool IsVectorCall = CC == llvm::CallingConv::X86_VectorCall;
3434 bool IsRegCall = CC == llvm::CallingConv::X86_RegCall;
3435
3436 // If __attribute__((sysv_abi)) is in use, use the SysV argument
3437 // classification rules.
3438 if (CC == llvm::CallingConv::X86_64_SysV) {
3439 X86_64ABIInfo SysVABIInfo(CGT, AVXLevel);
3440 SysVABIInfo.computeInfo(FI);
3441 return;
3442 }
3443
3444 unsigned FreeSSERegs = 0;
3445 if (IsVectorCall) {
3446 // We can use up to 4 SSE return registers with vectorcall.
3447 FreeSSERegs = 4;
3448 } else if (IsRegCall) {
3449 // RegCall gives us 16 SSE registers.
3450 FreeSSERegs = 16;
3451 }
3452
3453 if (!getCXXABI().classifyReturnType(FI))
3454 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
3455 IsVectorCall, IsRegCall);
3456
3457 if (IsVectorCall) {
3458 // We can use up to 6 SSE register parameters with vectorcall.
3459 FreeSSERegs = 6;
3460 } else if (IsRegCall) {
3461 // RegCall gives us 16 SSE registers, we can reuse the return registers.
3462 FreeSSERegs = 16;
3463 }
3464
3465 unsigned ArgNum = 0;
3466 unsigned ZeroSSERegs = 0;
3467 for (auto &I : FI.arguments()) {
3468 // Vectorcall in x64 only permits the first 6 arguments to be passed as
3469 // XMM/YMM registers. After the sixth argument, pretend no vector
3470 // registers are left.
3471 unsigned *MaybeFreeSSERegs =
3472 (IsVectorCall && ArgNum >= 6) ? &ZeroSSERegs : &FreeSSERegs;
3473 I.info =
3474 classify(I.type, *MaybeFreeSSERegs, false, IsVectorCall, IsRegCall);
3475 ++ArgNum;
3476 }
3477
3478 if (IsVectorCall) {
3479 // For vectorcall, assign aggregate HVAs to any free vector registers in a
3480 // second pass.
3481 for (auto &I : FI.arguments())
3482 I.info = reclassifyHvaArgForVectorCall(I.type, FreeSSERegs, I.info);
3483 }
3484}
3485
3486RValue WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3487 QualType Ty, AggValueSlot Slot) const {
3488 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3489 // not 1, 2, 4, or 8 bytes, must be passed by reference."
3490 uint64_t Width = getContext().getTypeSize(Ty);
3491 bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
3492
3493 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
3496 /*allowHigherAlign*/ false, Slot);
3497}
3498
3499std::unique_ptr<TargetCodeGenInfo> CodeGen::createX86_32TargetCodeGenInfo(
3500 CodeGenModule &CGM, bool DarwinVectorABI, bool Win32StructABI,
3501 unsigned NumRegisterParameters, bool SoftFloatABI) {
3502 bool RetSmallStructInRegABI = X86_32TargetCodeGenInfo::isStructReturnInRegABI(
3503 CGM.getTriple(), CGM.getCodeGenOpts());
3504 return std::make_unique<X86_32TargetCodeGenInfo>(
3505 CGM.getTypes(), DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
3506 NumRegisterParameters, SoftFloatABI);
3507}
3508
3509std::unique_ptr<TargetCodeGenInfo> CodeGen::createWinX86_32TargetCodeGenInfo(
3510 CodeGenModule &CGM, bool DarwinVectorABI, bool Win32StructABI,
3511 unsigned NumRegisterParameters) {
3512 bool RetSmallStructInRegABI = X86_32TargetCodeGenInfo::isStructReturnInRegABI(
3513 CGM.getTriple(), CGM.getCodeGenOpts());
3514 return std::make_unique<WinX86_32TargetCodeGenInfo>(
3515 CGM.getTypes(), DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
3516 NumRegisterParameters);
3517}
3518
3519std::unique_ptr<TargetCodeGenInfo>
3521 X86AVXABILevel AVXLevel) {
3522 return std::make_unique<X86_64TargetCodeGenInfo>(CGM.getTypes(), AVXLevel);
3523}
3524
3525std::unique_ptr<TargetCodeGenInfo>
3527 X86AVXABILevel AVXLevel) {
3528 return std::make_unique<WinX86_64TargetCodeGenInfo>(CGM.getTypes(), AVXLevel);
3529}
#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:1514
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:1500
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:2547
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:1542
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:2383
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:2307
static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF, Address VAListAddr, QualType Ty)
Definition X86.cpp:3003
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:188
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:2318
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:672
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:186
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:652
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:1609
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:3758
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:231
Represents a function declaration or definition.
Definition Decl.h:1999
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2794
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3767
CallingConv getCallConv() const
Definition TypeBase.h:4815
A (possibly-)qualified type.
Definition TypeBase.h:937
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8285
QualType getCanonicalType() const
Definition TypeBase.h:8337
Represents a struct/union/class.
Definition Decl.h:4309
bool hasFlexibleArrayMember() const
Definition Decl.h:4342
field_iterator field_end() const
Definition Decl.h:4515
field_range fields() const
Definition Decl.h:4512
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4509
field_iterator field_begin() const
Definition Decl.cpp:5154
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:8542
bool isVoidType() const
Definition TypeBase.h:8878
bool isFloat16Type() const
Definition TypeBase.h:8887
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isPointerType() const
Definition TypeBase.h:8522
bool isReferenceType() const
Definition TypeBase.h:8546
bool isEnumeralType() const
Definition TypeBase.h:8653
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:8996
bool isBitIntType() const
Definition TypeBase.h:8787
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:8847
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8645
bool isAnyComplexType() const
Definition TypeBase.h:8657
bool isMemberPointerType() const
Definition TypeBase.h:8603
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isBFloat16Type() const
Definition TypeBase.h:8899
bool isMemberFunctionPointerType() const
Definition TypeBase.h:8607
bool isVectorType() const
Definition TypeBase.h:8661
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:9098
bool isRecordType() const
Definition TypeBase.h:8649
bool isUnionType() const
Definition Type.cpp:718
bool hasPointerRepresentation() const
Whether this type is represented natively as a pointer.
Definition TypeBase.h:9042
QualType getType() const
Definition Decl.h:722
Represents a GCC generic vector type.
Definition TypeBase.h:4173
#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:3520
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:3509
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:3499
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:3526
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:5874
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:167