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