xref: /freebsd-src/contrib/llvm-project/clang/lib/CodeGen/Targets/X86.cpp (revision 1db9f3b21e39176dd5b67cf8ac378633b172463e)
106c3fb27SDimitry Andric //===- X86.cpp ------------------------------------------------------------===//
206c3fb27SDimitry Andric //
306c3fb27SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
406c3fb27SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
506c3fb27SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
606c3fb27SDimitry Andric //
706c3fb27SDimitry Andric //===----------------------------------------------------------------------===//
806c3fb27SDimitry Andric 
906c3fb27SDimitry Andric #include "ABIInfoImpl.h"
1006c3fb27SDimitry Andric #include "TargetInfo.h"
1106c3fb27SDimitry Andric #include "clang/Basic/DiagnosticFrontend.h"
1206c3fb27SDimitry Andric #include "llvm/ADT/SmallBitVector.h"
1306c3fb27SDimitry Andric 
1406c3fb27SDimitry Andric using namespace clang;
1506c3fb27SDimitry Andric using namespace clang::CodeGen;
1606c3fb27SDimitry Andric 
1706c3fb27SDimitry Andric namespace {
1806c3fb27SDimitry Andric 
1906c3fb27SDimitry Andric /// IsX86_MMXType - Return true if this is an MMX type.
2006c3fb27SDimitry Andric bool IsX86_MMXType(llvm::Type *IRType) {
2106c3fb27SDimitry Andric   // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
2206c3fb27SDimitry Andric   return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
2306c3fb27SDimitry Andric     cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
2406c3fb27SDimitry Andric     IRType->getScalarSizeInBits() != 64;
2506c3fb27SDimitry Andric }
2606c3fb27SDimitry Andric 
2706c3fb27SDimitry Andric static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
2806c3fb27SDimitry Andric                                           StringRef Constraint,
2906c3fb27SDimitry Andric                                           llvm::Type* Ty) {
3006c3fb27SDimitry Andric   bool IsMMXCons = llvm::StringSwitch<bool>(Constraint)
3106c3fb27SDimitry Andric                      .Cases("y", "&y", "^Ym", true)
3206c3fb27SDimitry Andric                      .Default(false);
3306c3fb27SDimitry Andric   if (IsMMXCons && Ty->isVectorTy()) {
3406c3fb27SDimitry Andric     if (cast<llvm::VectorType>(Ty)->getPrimitiveSizeInBits().getFixedValue() !=
3506c3fb27SDimitry Andric         64) {
3606c3fb27SDimitry Andric       // Invalid MMX constraint
3706c3fb27SDimitry Andric       return nullptr;
3806c3fb27SDimitry Andric     }
3906c3fb27SDimitry Andric 
4006c3fb27SDimitry Andric     return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
4106c3fb27SDimitry Andric   }
4206c3fb27SDimitry Andric 
4306c3fb27SDimitry Andric   // No operation needed
4406c3fb27SDimitry Andric   return Ty;
4506c3fb27SDimitry Andric }
4606c3fb27SDimitry Andric 
4706c3fb27SDimitry Andric /// Returns true if this type can be passed in SSE registers with the
4806c3fb27SDimitry Andric /// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
4906c3fb27SDimitry Andric static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
5006c3fb27SDimitry Andric   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5106c3fb27SDimitry Andric     if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) {
5206c3fb27SDimitry Andric       if (BT->getKind() == BuiltinType::LongDouble) {
5306c3fb27SDimitry Andric         if (&Context.getTargetInfo().getLongDoubleFormat() ==
5406c3fb27SDimitry Andric             &llvm::APFloat::x87DoubleExtended())
5506c3fb27SDimitry Andric           return false;
5606c3fb27SDimitry Andric       }
5706c3fb27SDimitry Andric       return true;
5806c3fb27SDimitry Andric     }
5906c3fb27SDimitry Andric   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
6006c3fb27SDimitry Andric     // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
6106c3fb27SDimitry Andric     // registers specially.
6206c3fb27SDimitry Andric     unsigned VecSize = Context.getTypeSize(VT);
6306c3fb27SDimitry Andric     if (VecSize == 128 || VecSize == 256 || VecSize == 512)
6406c3fb27SDimitry Andric       return true;
6506c3fb27SDimitry Andric   }
6606c3fb27SDimitry Andric   return false;
6706c3fb27SDimitry Andric }
6806c3fb27SDimitry Andric 
6906c3fb27SDimitry Andric /// Returns true if this aggregate is small enough to be passed in SSE registers
7006c3fb27SDimitry Andric /// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
7106c3fb27SDimitry Andric static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
7206c3fb27SDimitry Andric   return NumMembers <= 4;
7306c3fb27SDimitry Andric }
7406c3fb27SDimitry Andric 
7506c3fb27SDimitry Andric /// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
7606c3fb27SDimitry Andric static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
7706c3fb27SDimitry Andric   auto AI = ABIArgInfo::getDirect(T);
7806c3fb27SDimitry Andric   AI.setInReg(true);
7906c3fb27SDimitry Andric   AI.setCanBeFlattened(false);
8006c3fb27SDimitry Andric   return AI;
8106c3fb27SDimitry Andric }
8206c3fb27SDimitry Andric 
8306c3fb27SDimitry Andric //===----------------------------------------------------------------------===//
8406c3fb27SDimitry Andric // X86-32 ABI Implementation
8506c3fb27SDimitry Andric //===----------------------------------------------------------------------===//
8606c3fb27SDimitry Andric 
8706c3fb27SDimitry Andric /// Similar to llvm::CCState, but for Clang.
8806c3fb27SDimitry Andric struct CCState {
8906c3fb27SDimitry Andric   CCState(CGFunctionInfo &FI)
905f757f3fSDimitry Andric       : IsPreassigned(FI.arg_size()), CC(FI.getCallingConvention()),
915f757f3fSDimitry Andric 	Required(FI.getRequiredArgs()), IsDelegateCall(FI.isDelegateCall()) {}
9206c3fb27SDimitry Andric 
9306c3fb27SDimitry Andric   llvm::SmallBitVector IsPreassigned;
9406c3fb27SDimitry Andric   unsigned CC = CallingConv::CC_C;
9506c3fb27SDimitry Andric   unsigned FreeRegs = 0;
9606c3fb27SDimitry Andric   unsigned FreeSSERegs = 0;
975f757f3fSDimitry Andric   RequiredArgs Required;
985f757f3fSDimitry Andric   bool IsDelegateCall = false;
9906c3fb27SDimitry Andric };
10006c3fb27SDimitry Andric 
10106c3fb27SDimitry Andric /// X86_32ABIInfo - The X86-32 ABI information.
10206c3fb27SDimitry Andric class X86_32ABIInfo : public ABIInfo {
10306c3fb27SDimitry Andric   enum Class {
10406c3fb27SDimitry Andric     Integer,
10506c3fb27SDimitry Andric     Float
10606c3fb27SDimitry Andric   };
10706c3fb27SDimitry Andric 
10806c3fb27SDimitry Andric   static const unsigned MinABIStackAlignInBytes = 4;
10906c3fb27SDimitry Andric 
11006c3fb27SDimitry Andric   bool IsDarwinVectorABI;
11106c3fb27SDimitry Andric   bool IsRetSmallStructInRegABI;
11206c3fb27SDimitry Andric   bool IsWin32StructABI;
11306c3fb27SDimitry Andric   bool IsSoftFloatABI;
11406c3fb27SDimitry Andric   bool IsMCUABI;
11506c3fb27SDimitry Andric   bool IsLinuxABI;
11606c3fb27SDimitry Andric   unsigned DefaultNumRegisterParameters;
11706c3fb27SDimitry Andric 
11806c3fb27SDimitry Andric   static bool isRegisterSize(unsigned Size) {
11906c3fb27SDimitry Andric     return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
12006c3fb27SDimitry Andric   }
12106c3fb27SDimitry Andric 
12206c3fb27SDimitry Andric   bool isHomogeneousAggregateBaseType(QualType Ty) const override {
12306c3fb27SDimitry Andric     // FIXME: Assumes vectorcall is in use.
12406c3fb27SDimitry Andric     return isX86VectorTypeForVectorCall(getContext(), Ty);
12506c3fb27SDimitry Andric   }
12606c3fb27SDimitry Andric 
12706c3fb27SDimitry Andric   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
12806c3fb27SDimitry Andric                                          uint64_t NumMembers) const override {
12906c3fb27SDimitry Andric     // FIXME: Assumes vectorcall is in use.
13006c3fb27SDimitry Andric     return isX86VectorCallAggregateSmallEnough(NumMembers);
13106c3fb27SDimitry Andric   }
13206c3fb27SDimitry Andric 
13306c3fb27SDimitry Andric   bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
13406c3fb27SDimitry Andric 
13506c3fb27SDimitry Andric   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
13606c3fb27SDimitry Andric   /// such that the argument will be passed in memory.
13706c3fb27SDimitry Andric   ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
13806c3fb27SDimitry Andric 
13906c3fb27SDimitry Andric   ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
14006c3fb27SDimitry Andric 
14106c3fb27SDimitry Andric   /// Return the alignment to use for the given type on the stack.
14206c3fb27SDimitry Andric   unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
14306c3fb27SDimitry Andric 
14406c3fb27SDimitry Andric   Class classify(QualType Ty) const;
14506c3fb27SDimitry Andric   ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
1468a4dda33SDimitry Andric   ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State,
1475f757f3fSDimitry Andric                                   unsigned ArgIndex) const;
14806c3fb27SDimitry Andric 
14906c3fb27SDimitry Andric   /// Updates the number of available free registers, returns
15006c3fb27SDimitry Andric   /// true if any registers were allocated.
15106c3fb27SDimitry Andric   bool updateFreeRegs(QualType Ty, CCState &State) const;
15206c3fb27SDimitry Andric 
15306c3fb27SDimitry Andric   bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
15406c3fb27SDimitry Andric                                 bool &NeedsPadding) const;
15506c3fb27SDimitry Andric   bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
15606c3fb27SDimitry Andric 
15706c3fb27SDimitry Andric   bool canExpandIndirectArgument(QualType Ty) const;
15806c3fb27SDimitry Andric 
15906c3fb27SDimitry Andric   /// Rewrite the function info so that all memory arguments use
16006c3fb27SDimitry Andric   /// inalloca.
16106c3fb27SDimitry Andric   void rewriteWithInAlloca(CGFunctionInfo &FI) const;
16206c3fb27SDimitry Andric 
16306c3fb27SDimitry Andric   void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
16406c3fb27SDimitry Andric                            CharUnits &StackOffset, ABIArgInfo &Info,
16506c3fb27SDimitry Andric                            QualType Type) const;
16606c3fb27SDimitry Andric   void runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const;
16706c3fb27SDimitry Andric 
16806c3fb27SDimitry Andric public:
16906c3fb27SDimitry Andric 
17006c3fb27SDimitry Andric   void computeInfo(CGFunctionInfo &FI) const override;
17106c3fb27SDimitry Andric   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
17206c3fb27SDimitry Andric                     QualType Ty) const override;
17306c3fb27SDimitry Andric 
17406c3fb27SDimitry Andric   X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
17506c3fb27SDimitry Andric                 bool RetSmallStructInRegABI, bool Win32StructABI,
17606c3fb27SDimitry Andric                 unsigned NumRegisterParameters, bool SoftFloatABI)
17706c3fb27SDimitry Andric       : ABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
17806c3fb27SDimitry Andric         IsRetSmallStructInRegABI(RetSmallStructInRegABI),
17906c3fb27SDimitry Andric         IsWin32StructABI(Win32StructABI), IsSoftFloatABI(SoftFloatABI),
18006c3fb27SDimitry Andric         IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
18106c3fb27SDimitry Andric         IsLinuxABI(CGT.getTarget().getTriple().isOSLinux() ||
18206c3fb27SDimitry Andric                    CGT.getTarget().getTriple().isOSCygMing()),
18306c3fb27SDimitry Andric         DefaultNumRegisterParameters(NumRegisterParameters) {}
18406c3fb27SDimitry Andric };
18506c3fb27SDimitry Andric 
18606c3fb27SDimitry Andric class X86_32SwiftABIInfo : public SwiftABIInfo {
18706c3fb27SDimitry Andric public:
18806c3fb27SDimitry Andric   explicit X86_32SwiftABIInfo(CodeGenTypes &CGT)
18906c3fb27SDimitry Andric       : SwiftABIInfo(CGT, /*SwiftErrorInRegister=*/false) {}
19006c3fb27SDimitry Andric 
19106c3fb27SDimitry Andric   bool shouldPassIndirectly(ArrayRef<llvm::Type *> ComponentTys,
19206c3fb27SDimitry Andric                             bool AsReturnValue) const override {
19306c3fb27SDimitry Andric     // LLVM's x86-32 lowering currently only assigns up to three
19406c3fb27SDimitry Andric     // integer registers and three fp registers.  Oddly, it'll use up to
19506c3fb27SDimitry Andric     // four vector registers for vectors, but those can overlap with the
19606c3fb27SDimitry Andric     // scalar registers.
19706c3fb27SDimitry Andric     return occupiesMoreThan(ComponentTys, /*total=*/3);
19806c3fb27SDimitry Andric   }
19906c3fb27SDimitry Andric };
20006c3fb27SDimitry Andric 
20106c3fb27SDimitry Andric class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
20206c3fb27SDimitry Andric public:
20306c3fb27SDimitry Andric   X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
20406c3fb27SDimitry Andric                           bool RetSmallStructInRegABI, bool Win32StructABI,
20506c3fb27SDimitry Andric                           unsigned NumRegisterParameters, bool SoftFloatABI)
20606c3fb27SDimitry Andric       : TargetCodeGenInfo(std::make_unique<X86_32ABIInfo>(
20706c3fb27SDimitry Andric             CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
20806c3fb27SDimitry Andric             NumRegisterParameters, SoftFloatABI)) {
20906c3fb27SDimitry Andric     SwiftInfo = std::make_unique<X86_32SwiftABIInfo>(CGT);
21006c3fb27SDimitry Andric   }
21106c3fb27SDimitry Andric 
21206c3fb27SDimitry Andric   static bool isStructReturnInRegABI(
21306c3fb27SDimitry Andric       const llvm::Triple &Triple, const CodeGenOptions &Opts);
21406c3fb27SDimitry Andric 
21506c3fb27SDimitry Andric   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
21606c3fb27SDimitry Andric                            CodeGen::CodeGenModule &CGM) const override;
21706c3fb27SDimitry Andric 
21806c3fb27SDimitry Andric   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
21906c3fb27SDimitry Andric     // Darwin uses different dwarf register numbers for EH.
22006c3fb27SDimitry Andric     if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
22106c3fb27SDimitry Andric     return 4;
22206c3fb27SDimitry Andric   }
22306c3fb27SDimitry Andric 
22406c3fb27SDimitry Andric   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
22506c3fb27SDimitry Andric                                llvm::Value *Address) const override;
22606c3fb27SDimitry Andric 
22706c3fb27SDimitry Andric   llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
22806c3fb27SDimitry Andric                                   StringRef Constraint,
22906c3fb27SDimitry Andric                                   llvm::Type* Ty) const override {
23006c3fb27SDimitry Andric     return X86AdjustInlineAsmType(CGF, Constraint, Ty);
23106c3fb27SDimitry Andric   }
23206c3fb27SDimitry Andric 
23306c3fb27SDimitry Andric   void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
23406c3fb27SDimitry Andric                                 std::string &Constraints,
23506c3fb27SDimitry Andric                                 std::vector<llvm::Type *> &ResultRegTypes,
23606c3fb27SDimitry Andric                                 std::vector<llvm::Type *> &ResultTruncRegTypes,
23706c3fb27SDimitry Andric                                 std::vector<LValue> &ResultRegDests,
23806c3fb27SDimitry Andric                                 std::string &AsmString,
23906c3fb27SDimitry Andric                                 unsigned NumOutputs) const override;
24006c3fb27SDimitry Andric 
24106c3fb27SDimitry Andric   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
24206c3fb27SDimitry Andric     return "movl\t%ebp, %ebp"
24306c3fb27SDimitry Andric            "\t\t// marker for objc_retainAutoreleaseReturnValue";
24406c3fb27SDimitry Andric   }
24506c3fb27SDimitry Andric };
24606c3fb27SDimitry Andric 
24706c3fb27SDimitry Andric }
24806c3fb27SDimitry Andric 
24906c3fb27SDimitry Andric /// Rewrite input constraint references after adding some output constraints.
25006c3fb27SDimitry Andric /// In the case where there is one output and one input and we add one output,
25106c3fb27SDimitry Andric /// we need to replace all operand references greater than or equal to 1:
25206c3fb27SDimitry Andric ///     mov $0, $1
25306c3fb27SDimitry Andric ///     mov eax, $1
25406c3fb27SDimitry Andric /// The result will be:
25506c3fb27SDimitry Andric ///     mov $0, $2
25606c3fb27SDimitry Andric ///     mov eax, $2
25706c3fb27SDimitry Andric static void rewriteInputConstraintReferences(unsigned FirstIn,
25806c3fb27SDimitry Andric                                              unsigned NumNewOuts,
25906c3fb27SDimitry Andric                                              std::string &AsmString) {
26006c3fb27SDimitry Andric   std::string Buf;
26106c3fb27SDimitry Andric   llvm::raw_string_ostream OS(Buf);
26206c3fb27SDimitry Andric   size_t Pos = 0;
26306c3fb27SDimitry Andric   while (Pos < AsmString.size()) {
26406c3fb27SDimitry Andric     size_t DollarStart = AsmString.find('$', Pos);
26506c3fb27SDimitry Andric     if (DollarStart == std::string::npos)
26606c3fb27SDimitry Andric       DollarStart = AsmString.size();
26706c3fb27SDimitry Andric     size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
26806c3fb27SDimitry Andric     if (DollarEnd == std::string::npos)
26906c3fb27SDimitry Andric       DollarEnd = AsmString.size();
27006c3fb27SDimitry Andric     OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
27106c3fb27SDimitry Andric     Pos = DollarEnd;
27206c3fb27SDimitry Andric     size_t NumDollars = DollarEnd - DollarStart;
27306c3fb27SDimitry Andric     if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
27406c3fb27SDimitry Andric       // We have an operand reference.
27506c3fb27SDimitry Andric       size_t DigitStart = Pos;
27606c3fb27SDimitry Andric       if (AsmString[DigitStart] == '{') {
27706c3fb27SDimitry Andric         OS << '{';
27806c3fb27SDimitry Andric         ++DigitStart;
27906c3fb27SDimitry Andric       }
28006c3fb27SDimitry Andric       size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
28106c3fb27SDimitry Andric       if (DigitEnd == std::string::npos)
28206c3fb27SDimitry Andric         DigitEnd = AsmString.size();
28306c3fb27SDimitry Andric       StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
28406c3fb27SDimitry Andric       unsigned OperandIndex;
28506c3fb27SDimitry Andric       if (!OperandStr.getAsInteger(10, OperandIndex)) {
28606c3fb27SDimitry Andric         if (OperandIndex >= FirstIn)
28706c3fb27SDimitry Andric           OperandIndex += NumNewOuts;
28806c3fb27SDimitry Andric         OS << OperandIndex;
28906c3fb27SDimitry Andric       } else {
29006c3fb27SDimitry Andric         OS << OperandStr;
29106c3fb27SDimitry Andric       }
29206c3fb27SDimitry Andric       Pos = DigitEnd;
29306c3fb27SDimitry Andric     }
29406c3fb27SDimitry Andric   }
29506c3fb27SDimitry Andric   AsmString = std::move(OS.str());
29606c3fb27SDimitry Andric }
29706c3fb27SDimitry Andric 
29806c3fb27SDimitry Andric /// Add output constraints for EAX:EDX because they are return registers.
29906c3fb27SDimitry Andric void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
30006c3fb27SDimitry Andric     CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
30106c3fb27SDimitry Andric     std::vector<llvm::Type *> &ResultRegTypes,
30206c3fb27SDimitry Andric     std::vector<llvm::Type *> &ResultTruncRegTypes,
30306c3fb27SDimitry Andric     std::vector<LValue> &ResultRegDests, std::string &AsmString,
30406c3fb27SDimitry Andric     unsigned NumOutputs) const {
30506c3fb27SDimitry Andric   uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
30606c3fb27SDimitry Andric 
30706c3fb27SDimitry Andric   // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
30806c3fb27SDimitry Andric   // larger.
30906c3fb27SDimitry Andric   if (!Constraints.empty())
31006c3fb27SDimitry Andric     Constraints += ',';
31106c3fb27SDimitry Andric   if (RetWidth <= 32) {
31206c3fb27SDimitry Andric     Constraints += "={eax}";
31306c3fb27SDimitry Andric     ResultRegTypes.push_back(CGF.Int32Ty);
31406c3fb27SDimitry Andric   } else {
31506c3fb27SDimitry Andric     // Use the 'A' constraint for EAX:EDX.
31606c3fb27SDimitry Andric     Constraints += "=A";
31706c3fb27SDimitry Andric     ResultRegTypes.push_back(CGF.Int64Ty);
31806c3fb27SDimitry Andric   }
31906c3fb27SDimitry Andric 
32006c3fb27SDimitry Andric   // Truncate EAX or EAX:EDX to an integer of the appropriate size.
32106c3fb27SDimitry Andric   llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
32206c3fb27SDimitry Andric   ResultTruncRegTypes.push_back(CoerceTy);
32306c3fb27SDimitry Andric 
32406c3fb27SDimitry Andric   // Coerce the integer by bitcasting the return slot pointer.
32506c3fb27SDimitry Andric   ReturnSlot.setAddress(ReturnSlot.getAddress(CGF).withElementType(CoerceTy));
32606c3fb27SDimitry Andric   ResultRegDests.push_back(ReturnSlot);
32706c3fb27SDimitry Andric 
32806c3fb27SDimitry Andric   rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
32906c3fb27SDimitry Andric }
33006c3fb27SDimitry Andric 
33106c3fb27SDimitry Andric /// shouldReturnTypeInRegister - Determine if the given type should be
33206c3fb27SDimitry Andric /// returned in a register (for the Darwin and MCU ABI).
33306c3fb27SDimitry Andric bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
33406c3fb27SDimitry Andric                                                ASTContext &Context) const {
33506c3fb27SDimitry Andric   uint64_t Size = Context.getTypeSize(Ty);
33606c3fb27SDimitry Andric 
33706c3fb27SDimitry Andric   // For i386, type must be register sized.
33806c3fb27SDimitry Andric   // For the MCU ABI, it only needs to be <= 8-byte
33906c3fb27SDimitry Andric   if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
34006c3fb27SDimitry Andric    return false;
34106c3fb27SDimitry Andric 
34206c3fb27SDimitry Andric   if (Ty->isVectorType()) {
34306c3fb27SDimitry Andric     // 64- and 128- bit vectors inside structures are not returned in
34406c3fb27SDimitry Andric     // registers.
34506c3fb27SDimitry Andric     if (Size == 64 || Size == 128)
34606c3fb27SDimitry Andric       return false;
34706c3fb27SDimitry Andric 
34806c3fb27SDimitry Andric     return true;
34906c3fb27SDimitry Andric   }
35006c3fb27SDimitry Andric 
35106c3fb27SDimitry Andric   // If this is a builtin, pointer, enum, complex type, member pointer, or
35206c3fb27SDimitry Andric   // member function pointer it is ok.
35306c3fb27SDimitry Andric   if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
35406c3fb27SDimitry Andric       Ty->isAnyComplexType() || Ty->isEnumeralType() ||
35506c3fb27SDimitry Andric       Ty->isBlockPointerType() || Ty->isMemberPointerType())
35606c3fb27SDimitry Andric     return true;
35706c3fb27SDimitry Andric 
35806c3fb27SDimitry Andric   // Arrays are treated like records.
35906c3fb27SDimitry Andric   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
36006c3fb27SDimitry Andric     return shouldReturnTypeInRegister(AT->getElementType(), Context);
36106c3fb27SDimitry Andric 
36206c3fb27SDimitry Andric   // Otherwise, it must be a record type.
36306c3fb27SDimitry Andric   const RecordType *RT = Ty->getAs<RecordType>();
36406c3fb27SDimitry Andric   if (!RT) return false;
36506c3fb27SDimitry Andric 
36606c3fb27SDimitry Andric   // FIXME: Traverse bases here too.
36706c3fb27SDimitry Andric 
36806c3fb27SDimitry Andric   // Structure types are passed in register if all fields would be
36906c3fb27SDimitry Andric   // passed in a register.
37006c3fb27SDimitry Andric   for (const auto *FD : RT->getDecl()->fields()) {
37106c3fb27SDimitry Andric     // Empty fields are ignored.
37206c3fb27SDimitry Andric     if (isEmptyField(Context, FD, true))
37306c3fb27SDimitry Andric       continue;
37406c3fb27SDimitry Andric 
37506c3fb27SDimitry Andric     // Check fields recursively.
37606c3fb27SDimitry Andric     if (!shouldReturnTypeInRegister(FD->getType(), Context))
37706c3fb27SDimitry Andric       return false;
37806c3fb27SDimitry Andric   }
37906c3fb27SDimitry Andric   return true;
38006c3fb27SDimitry Andric }
38106c3fb27SDimitry Andric 
38206c3fb27SDimitry Andric static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
38306c3fb27SDimitry Andric   // Treat complex types as the element type.
38406c3fb27SDimitry Andric   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
38506c3fb27SDimitry Andric     Ty = CTy->getElementType();
38606c3fb27SDimitry Andric 
38706c3fb27SDimitry Andric   // Check for a type which we know has a simple scalar argument-passing
38806c3fb27SDimitry Andric   // convention without any padding.  (We're specifically looking for 32
38906c3fb27SDimitry Andric   // and 64-bit integer and integer-equivalents, float, and double.)
39006c3fb27SDimitry Andric   if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
39106c3fb27SDimitry Andric       !Ty->isEnumeralType() && !Ty->isBlockPointerType())
39206c3fb27SDimitry Andric     return false;
39306c3fb27SDimitry Andric 
39406c3fb27SDimitry Andric   uint64_t Size = Context.getTypeSize(Ty);
39506c3fb27SDimitry Andric   return Size == 32 || Size == 64;
39606c3fb27SDimitry Andric }
39706c3fb27SDimitry Andric 
39806c3fb27SDimitry Andric static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
39906c3fb27SDimitry Andric                           uint64_t &Size) {
40006c3fb27SDimitry Andric   for (const auto *FD : RD->fields()) {
40106c3fb27SDimitry Andric     // Scalar arguments on the stack get 4 byte alignment on x86. If the
40206c3fb27SDimitry Andric     // argument is smaller than 32-bits, expanding the struct will create
40306c3fb27SDimitry Andric     // alignment padding.
40406c3fb27SDimitry Andric     if (!is32Or64BitBasicType(FD->getType(), Context))
40506c3fb27SDimitry Andric       return false;
40606c3fb27SDimitry Andric 
40706c3fb27SDimitry Andric     // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
40806c3fb27SDimitry Andric     // how to expand them yet, and the predicate for telling if a bitfield still
40906c3fb27SDimitry Andric     // counts as "basic" is more complicated than what we were doing previously.
41006c3fb27SDimitry Andric     if (FD->isBitField())
41106c3fb27SDimitry Andric       return false;
41206c3fb27SDimitry Andric 
41306c3fb27SDimitry Andric     Size += Context.getTypeSize(FD->getType());
41406c3fb27SDimitry Andric   }
41506c3fb27SDimitry Andric   return true;
41606c3fb27SDimitry Andric }
41706c3fb27SDimitry Andric 
41806c3fb27SDimitry Andric static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
41906c3fb27SDimitry Andric                                  uint64_t &Size) {
42006c3fb27SDimitry Andric   // Don't do this if there are any non-empty bases.
42106c3fb27SDimitry Andric   for (const CXXBaseSpecifier &Base : RD->bases()) {
42206c3fb27SDimitry Andric     if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
42306c3fb27SDimitry Andric                               Size))
42406c3fb27SDimitry Andric       return false;
42506c3fb27SDimitry Andric   }
42606c3fb27SDimitry Andric   if (!addFieldSizes(Context, RD, Size))
42706c3fb27SDimitry Andric     return false;
42806c3fb27SDimitry Andric   return true;
42906c3fb27SDimitry Andric }
43006c3fb27SDimitry Andric 
43106c3fb27SDimitry Andric /// Test whether an argument type which is to be passed indirectly (on the
43206c3fb27SDimitry Andric /// stack) would have the equivalent layout if it was expanded into separate
43306c3fb27SDimitry Andric /// arguments. If so, we prefer to do the latter to avoid inhibiting
43406c3fb27SDimitry Andric /// optimizations.
43506c3fb27SDimitry Andric bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
43606c3fb27SDimitry Andric   // We can only expand structure types.
43706c3fb27SDimitry Andric   const RecordType *RT = Ty->getAs<RecordType>();
43806c3fb27SDimitry Andric   if (!RT)
43906c3fb27SDimitry Andric     return false;
44006c3fb27SDimitry Andric   const RecordDecl *RD = RT->getDecl();
44106c3fb27SDimitry Andric   uint64_t Size = 0;
44206c3fb27SDimitry Andric   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
44306c3fb27SDimitry Andric     if (!IsWin32StructABI) {
44406c3fb27SDimitry Andric       // On non-Windows, we have to conservatively match our old bitcode
44506c3fb27SDimitry Andric       // prototypes in order to be ABI-compatible at the bitcode level.
44606c3fb27SDimitry Andric       if (!CXXRD->isCLike())
44706c3fb27SDimitry Andric         return false;
44806c3fb27SDimitry Andric     } else {
44906c3fb27SDimitry Andric       // Don't do this for dynamic classes.
45006c3fb27SDimitry Andric       if (CXXRD->isDynamicClass())
45106c3fb27SDimitry Andric         return false;
45206c3fb27SDimitry Andric     }
45306c3fb27SDimitry Andric     if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
45406c3fb27SDimitry Andric       return false;
45506c3fb27SDimitry Andric   } else {
45606c3fb27SDimitry Andric     if (!addFieldSizes(getContext(), RD, Size))
45706c3fb27SDimitry Andric       return false;
45806c3fb27SDimitry Andric   }
45906c3fb27SDimitry Andric 
46006c3fb27SDimitry Andric   // We can do this if there was no alignment padding.
46106c3fb27SDimitry Andric   return Size == getContext().getTypeSize(Ty);
46206c3fb27SDimitry Andric }
46306c3fb27SDimitry Andric 
46406c3fb27SDimitry Andric ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
46506c3fb27SDimitry Andric   // If the return value is indirect, then the hidden argument is consuming one
46606c3fb27SDimitry Andric   // integer register.
46706c3fb27SDimitry Andric   if (State.FreeRegs) {
46806c3fb27SDimitry Andric     --State.FreeRegs;
46906c3fb27SDimitry Andric     if (!IsMCUABI)
47006c3fb27SDimitry Andric       return getNaturalAlignIndirectInReg(RetTy);
47106c3fb27SDimitry Andric   }
47206c3fb27SDimitry Andric   return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
47306c3fb27SDimitry Andric }
47406c3fb27SDimitry Andric 
47506c3fb27SDimitry Andric ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
47606c3fb27SDimitry Andric                                              CCState &State) const {
47706c3fb27SDimitry Andric   if (RetTy->isVoidType())
47806c3fb27SDimitry Andric     return ABIArgInfo::getIgnore();
47906c3fb27SDimitry Andric 
48006c3fb27SDimitry Andric   const Type *Base = nullptr;
48106c3fb27SDimitry Andric   uint64_t NumElts = 0;
48206c3fb27SDimitry Andric   if ((State.CC == llvm::CallingConv::X86_VectorCall ||
48306c3fb27SDimitry Andric        State.CC == llvm::CallingConv::X86_RegCall) &&
48406c3fb27SDimitry Andric       isHomogeneousAggregate(RetTy, Base, NumElts)) {
48506c3fb27SDimitry Andric     // The LLVM struct type for such an aggregate should lower properly.
48606c3fb27SDimitry Andric     return ABIArgInfo::getDirect();
48706c3fb27SDimitry Andric   }
48806c3fb27SDimitry Andric 
48906c3fb27SDimitry Andric   if (const VectorType *VT = RetTy->getAs<VectorType>()) {
49006c3fb27SDimitry Andric     // On Darwin, some vectors are returned in registers.
49106c3fb27SDimitry Andric     if (IsDarwinVectorABI) {
49206c3fb27SDimitry Andric       uint64_t Size = getContext().getTypeSize(RetTy);
49306c3fb27SDimitry Andric 
49406c3fb27SDimitry Andric       // 128-bit vectors are a special case; they are returned in
49506c3fb27SDimitry Andric       // registers and we need to make sure to pick a type the LLVM
49606c3fb27SDimitry Andric       // backend will like.
49706c3fb27SDimitry Andric       if (Size == 128)
49806c3fb27SDimitry Andric         return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
49906c3fb27SDimitry Andric             llvm::Type::getInt64Ty(getVMContext()), 2));
50006c3fb27SDimitry Andric 
50106c3fb27SDimitry Andric       // Always return in register if it fits in a general purpose
50206c3fb27SDimitry Andric       // register, or if it is 64 bits and has a single element.
50306c3fb27SDimitry Andric       if ((Size == 8 || Size == 16 || Size == 32) ||
50406c3fb27SDimitry Andric           (Size == 64 && VT->getNumElements() == 1))
50506c3fb27SDimitry Andric         return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
50606c3fb27SDimitry Andric                                                             Size));
50706c3fb27SDimitry Andric 
50806c3fb27SDimitry Andric       return getIndirectReturnResult(RetTy, State);
50906c3fb27SDimitry Andric     }
51006c3fb27SDimitry Andric 
51106c3fb27SDimitry Andric     return ABIArgInfo::getDirect();
51206c3fb27SDimitry Andric   }
51306c3fb27SDimitry Andric 
51406c3fb27SDimitry Andric   if (isAggregateTypeForABI(RetTy)) {
51506c3fb27SDimitry Andric     if (const RecordType *RT = RetTy->getAs<RecordType>()) {
51606c3fb27SDimitry Andric       // Structures with flexible arrays are always indirect.
51706c3fb27SDimitry Andric       if (RT->getDecl()->hasFlexibleArrayMember())
51806c3fb27SDimitry Andric         return getIndirectReturnResult(RetTy, State);
51906c3fb27SDimitry Andric     }
52006c3fb27SDimitry Andric 
52106c3fb27SDimitry Andric     // If specified, structs and unions are always indirect.
52206c3fb27SDimitry Andric     if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
52306c3fb27SDimitry Andric       return getIndirectReturnResult(RetTy, State);
52406c3fb27SDimitry Andric 
52506c3fb27SDimitry Andric     // Ignore empty structs/unions.
52606c3fb27SDimitry Andric     if (isEmptyRecord(getContext(), RetTy, true))
52706c3fb27SDimitry Andric       return ABIArgInfo::getIgnore();
52806c3fb27SDimitry Andric 
52906c3fb27SDimitry Andric     // Return complex of _Float16 as <2 x half> so the backend will use xmm0.
53006c3fb27SDimitry Andric     if (const ComplexType *CT = RetTy->getAs<ComplexType>()) {
53106c3fb27SDimitry Andric       QualType ET = getContext().getCanonicalType(CT->getElementType());
53206c3fb27SDimitry Andric       if (ET->isFloat16Type())
53306c3fb27SDimitry Andric         return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
53406c3fb27SDimitry Andric             llvm::Type::getHalfTy(getVMContext()), 2));
53506c3fb27SDimitry Andric     }
53606c3fb27SDimitry Andric 
53706c3fb27SDimitry Andric     // Small structures which are register sized are generally returned
53806c3fb27SDimitry Andric     // in a register.
53906c3fb27SDimitry Andric     if (shouldReturnTypeInRegister(RetTy, getContext())) {
54006c3fb27SDimitry Andric       uint64_t Size = getContext().getTypeSize(RetTy);
54106c3fb27SDimitry Andric 
54206c3fb27SDimitry Andric       // As a special-case, if the struct is a "single-element" struct, and
54306c3fb27SDimitry Andric       // the field is of type "float" or "double", return it in a
54406c3fb27SDimitry Andric       // floating-point register. (MSVC does not apply this special case.)
54506c3fb27SDimitry Andric       // We apply a similar transformation for pointer types to improve the
54606c3fb27SDimitry Andric       // quality of the generated IR.
54706c3fb27SDimitry Andric       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
54806c3fb27SDimitry Andric         if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
54906c3fb27SDimitry Andric             || SeltTy->hasPointerRepresentation())
55006c3fb27SDimitry Andric           return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
55106c3fb27SDimitry Andric 
55206c3fb27SDimitry Andric       // FIXME: We should be able to narrow this integer in cases with dead
55306c3fb27SDimitry Andric       // padding.
55406c3fb27SDimitry Andric       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
55506c3fb27SDimitry Andric     }
55606c3fb27SDimitry Andric 
55706c3fb27SDimitry Andric     return getIndirectReturnResult(RetTy, State);
55806c3fb27SDimitry Andric   }
55906c3fb27SDimitry Andric 
56006c3fb27SDimitry Andric   // Treat an enum type as its underlying type.
56106c3fb27SDimitry Andric   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
56206c3fb27SDimitry Andric     RetTy = EnumTy->getDecl()->getIntegerType();
56306c3fb27SDimitry Andric 
56406c3fb27SDimitry Andric   if (const auto *EIT = RetTy->getAs<BitIntType>())
56506c3fb27SDimitry Andric     if (EIT->getNumBits() > 64)
56606c3fb27SDimitry Andric       return getIndirectReturnResult(RetTy, State);
56706c3fb27SDimitry Andric 
56806c3fb27SDimitry Andric   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
56906c3fb27SDimitry Andric                                                : ABIArgInfo::getDirect());
57006c3fb27SDimitry Andric }
57106c3fb27SDimitry Andric 
57206c3fb27SDimitry Andric unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
57306c3fb27SDimitry Andric                                                  unsigned Align) const {
57406c3fb27SDimitry Andric   // Otherwise, if the alignment is less than or equal to the minimum ABI
57506c3fb27SDimitry Andric   // alignment, just use the default; the backend will handle this.
57606c3fb27SDimitry Andric   if (Align <= MinABIStackAlignInBytes)
57706c3fb27SDimitry Andric     return 0; // Use default alignment.
57806c3fb27SDimitry Andric 
57906c3fb27SDimitry Andric   if (IsLinuxABI) {
58006c3fb27SDimitry Andric     // Exclude other System V OS (e.g Darwin, PS4 and FreeBSD) since we don't
58106c3fb27SDimitry Andric     // want to spend any effort dealing with the ramifications of ABI breaks.
58206c3fb27SDimitry Andric     //
58306c3fb27SDimitry Andric     // If the vector type is __m128/__m256/__m512, return the default alignment.
58406c3fb27SDimitry Andric     if (Ty->isVectorType() && (Align == 16 || Align == 32 || Align == 64))
58506c3fb27SDimitry Andric       return Align;
58606c3fb27SDimitry Andric   }
58706c3fb27SDimitry Andric   // On non-Darwin, the stack type alignment is always 4.
58806c3fb27SDimitry Andric   if (!IsDarwinVectorABI) {
58906c3fb27SDimitry Andric     // Set explicit alignment, since we may need to realign the top.
59006c3fb27SDimitry Andric     return MinABIStackAlignInBytes;
59106c3fb27SDimitry Andric   }
59206c3fb27SDimitry Andric 
59306c3fb27SDimitry Andric   // Otherwise, if the type contains an SSE vector type, the alignment is 16.
59406c3fb27SDimitry Andric   if (Align >= 16 && (isSIMDVectorType(getContext(), Ty) ||
59506c3fb27SDimitry Andric                       isRecordWithSIMDVectorType(getContext(), Ty)))
59606c3fb27SDimitry Andric     return 16;
59706c3fb27SDimitry Andric 
59806c3fb27SDimitry Andric   return MinABIStackAlignInBytes;
59906c3fb27SDimitry Andric }
60006c3fb27SDimitry Andric 
60106c3fb27SDimitry Andric ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
60206c3fb27SDimitry Andric                                             CCState &State) const {
60306c3fb27SDimitry Andric   if (!ByVal) {
60406c3fb27SDimitry Andric     if (State.FreeRegs) {
60506c3fb27SDimitry Andric       --State.FreeRegs; // Non-byval indirects just use one pointer.
60606c3fb27SDimitry Andric       if (!IsMCUABI)
60706c3fb27SDimitry Andric         return getNaturalAlignIndirectInReg(Ty);
60806c3fb27SDimitry Andric     }
60906c3fb27SDimitry Andric     return getNaturalAlignIndirect(Ty, false);
61006c3fb27SDimitry Andric   }
61106c3fb27SDimitry Andric 
61206c3fb27SDimitry Andric   // Compute the byval alignment.
61306c3fb27SDimitry Andric   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
61406c3fb27SDimitry Andric   unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
61506c3fb27SDimitry Andric   if (StackAlign == 0)
61606c3fb27SDimitry Andric     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
61706c3fb27SDimitry Andric 
61806c3fb27SDimitry Andric   // If the stack alignment is less than the type alignment, realign the
61906c3fb27SDimitry Andric   // argument.
62006c3fb27SDimitry Andric   bool Realign = TypeAlign > StackAlign;
62106c3fb27SDimitry Andric   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
62206c3fb27SDimitry Andric                                  /*ByVal=*/true, Realign);
62306c3fb27SDimitry Andric }
62406c3fb27SDimitry Andric 
62506c3fb27SDimitry Andric X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
62606c3fb27SDimitry Andric   const Type *T = isSingleElementStruct(Ty, getContext());
62706c3fb27SDimitry Andric   if (!T)
62806c3fb27SDimitry Andric     T = Ty.getTypePtr();
62906c3fb27SDimitry Andric 
63006c3fb27SDimitry Andric   if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
63106c3fb27SDimitry Andric     BuiltinType::Kind K = BT->getKind();
63206c3fb27SDimitry Andric     if (K == BuiltinType::Float || K == BuiltinType::Double)
63306c3fb27SDimitry Andric       return Float;
63406c3fb27SDimitry Andric   }
63506c3fb27SDimitry Andric   return Integer;
63606c3fb27SDimitry Andric }
63706c3fb27SDimitry Andric 
63806c3fb27SDimitry Andric bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
63906c3fb27SDimitry Andric   if (!IsSoftFloatABI) {
64006c3fb27SDimitry Andric     Class C = classify(Ty);
64106c3fb27SDimitry Andric     if (C == Float)
64206c3fb27SDimitry Andric       return false;
64306c3fb27SDimitry Andric   }
64406c3fb27SDimitry Andric 
64506c3fb27SDimitry Andric   unsigned Size = getContext().getTypeSize(Ty);
64606c3fb27SDimitry Andric   unsigned SizeInRegs = (Size + 31) / 32;
64706c3fb27SDimitry Andric 
64806c3fb27SDimitry Andric   if (SizeInRegs == 0)
64906c3fb27SDimitry Andric     return false;
65006c3fb27SDimitry Andric 
65106c3fb27SDimitry Andric   if (!IsMCUABI) {
65206c3fb27SDimitry Andric     if (SizeInRegs > State.FreeRegs) {
65306c3fb27SDimitry Andric       State.FreeRegs = 0;
65406c3fb27SDimitry Andric       return false;
65506c3fb27SDimitry Andric     }
65606c3fb27SDimitry Andric   } else {
65706c3fb27SDimitry Andric     // The MCU psABI allows passing parameters in-reg even if there are
65806c3fb27SDimitry Andric     // earlier parameters that are passed on the stack. Also,
65906c3fb27SDimitry Andric     // it does not allow passing >8-byte structs in-register,
66006c3fb27SDimitry Andric     // even if there are 3 free registers available.
66106c3fb27SDimitry Andric     if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
66206c3fb27SDimitry Andric       return false;
66306c3fb27SDimitry Andric   }
66406c3fb27SDimitry Andric 
66506c3fb27SDimitry Andric   State.FreeRegs -= SizeInRegs;
66606c3fb27SDimitry Andric   return true;
66706c3fb27SDimitry Andric }
66806c3fb27SDimitry Andric 
66906c3fb27SDimitry Andric bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
67006c3fb27SDimitry Andric                                              bool &InReg,
67106c3fb27SDimitry Andric                                              bool &NeedsPadding) const {
67206c3fb27SDimitry Andric   // On Windows, aggregates other than HFAs are never passed in registers, and
67306c3fb27SDimitry Andric   // they do not consume register slots. Homogenous floating-point aggregates
67406c3fb27SDimitry Andric   // (HFAs) have already been dealt with at this point.
67506c3fb27SDimitry Andric   if (IsWin32StructABI && isAggregateTypeForABI(Ty))
67606c3fb27SDimitry Andric     return false;
67706c3fb27SDimitry Andric 
67806c3fb27SDimitry Andric   NeedsPadding = false;
67906c3fb27SDimitry Andric   InReg = !IsMCUABI;
68006c3fb27SDimitry Andric 
68106c3fb27SDimitry Andric   if (!updateFreeRegs(Ty, State))
68206c3fb27SDimitry Andric     return false;
68306c3fb27SDimitry Andric 
68406c3fb27SDimitry Andric   if (IsMCUABI)
68506c3fb27SDimitry Andric     return true;
68606c3fb27SDimitry Andric 
68706c3fb27SDimitry Andric   if (State.CC == llvm::CallingConv::X86_FastCall ||
68806c3fb27SDimitry Andric       State.CC == llvm::CallingConv::X86_VectorCall ||
68906c3fb27SDimitry Andric       State.CC == llvm::CallingConv::X86_RegCall) {
69006c3fb27SDimitry Andric     if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
69106c3fb27SDimitry Andric       NeedsPadding = true;
69206c3fb27SDimitry Andric 
69306c3fb27SDimitry Andric     return false;
69406c3fb27SDimitry Andric   }
69506c3fb27SDimitry Andric 
69606c3fb27SDimitry Andric   return true;
69706c3fb27SDimitry Andric }
69806c3fb27SDimitry Andric 
69906c3fb27SDimitry Andric bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
70006c3fb27SDimitry Andric   bool IsPtrOrInt = (getContext().getTypeSize(Ty) <= 32) &&
70106c3fb27SDimitry Andric                     (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
70206c3fb27SDimitry Andric                      Ty->isReferenceType());
70306c3fb27SDimitry Andric 
70406c3fb27SDimitry Andric   if (!IsPtrOrInt && (State.CC == llvm::CallingConv::X86_FastCall ||
70506c3fb27SDimitry Andric                       State.CC == llvm::CallingConv::X86_VectorCall))
70606c3fb27SDimitry Andric     return false;
70706c3fb27SDimitry Andric 
70806c3fb27SDimitry Andric   if (!updateFreeRegs(Ty, State))
70906c3fb27SDimitry Andric     return false;
71006c3fb27SDimitry Andric 
71106c3fb27SDimitry Andric   if (!IsPtrOrInt && State.CC == llvm::CallingConv::X86_RegCall)
71206c3fb27SDimitry Andric     return false;
71306c3fb27SDimitry Andric 
71406c3fb27SDimitry Andric   // Return true to apply inreg to all legal parameters except for MCU targets.
71506c3fb27SDimitry Andric   return !IsMCUABI;
71606c3fb27SDimitry Andric }
71706c3fb27SDimitry Andric 
71806c3fb27SDimitry Andric void X86_32ABIInfo::runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const {
71906c3fb27SDimitry Andric   // Vectorcall x86 works subtly different than in x64, so the format is
72006c3fb27SDimitry Andric   // a bit different than the x64 version.  First, all vector types (not HVAs)
72106c3fb27SDimitry Andric   // are assigned, with the first 6 ending up in the [XYZ]MM0-5 registers.
72206c3fb27SDimitry Andric   // This differs from the x64 implementation, where the first 6 by INDEX get
72306c3fb27SDimitry Andric   // registers.
72406c3fb27SDimitry Andric   // In the second pass over the arguments, HVAs are passed in the remaining
72506c3fb27SDimitry Andric   // vector registers if possible, or indirectly by address. The address will be
72606c3fb27SDimitry Andric   // passed in ECX/EDX if available. Any other arguments are passed according to
72706c3fb27SDimitry Andric   // the usual fastcall rules.
72806c3fb27SDimitry Andric   MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
72906c3fb27SDimitry Andric   for (int I = 0, E = Args.size(); I < E; ++I) {
73006c3fb27SDimitry Andric     const Type *Base = nullptr;
73106c3fb27SDimitry Andric     uint64_t NumElts = 0;
73206c3fb27SDimitry Andric     const QualType &Ty = Args[I].type;
73306c3fb27SDimitry Andric     if ((Ty->isVectorType() || Ty->isBuiltinType()) &&
73406c3fb27SDimitry Andric         isHomogeneousAggregate(Ty, Base, NumElts)) {
73506c3fb27SDimitry Andric       if (State.FreeSSERegs >= NumElts) {
73606c3fb27SDimitry Andric         State.FreeSSERegs -= NumElts;
73706c3fb27SDimitry Andric         Args[I].info = ABIArgInfo::getDirectInReg();
73806c3fb27SDimitry Andric         State.IsPreassigned.set(I);
73906c3fb27SDimitry Andric       }
74006c3fb27SDimitry Andric     }
74106c3fb27SDimitry Andric   }
74206c3fb27SDimitry Andric }
74306c3fb27SDimitry Andric 
7448a4dda33SDimitry Andric ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty, CCState &State,
7455f757f3fSDimitry Andric                                                unsigned ArgIndex) const {
74606c3fb27SDimitry Andric   // FIXME: Set alignment on indirect arguments.
74706c3fb27SDimitry Andric   bool IsFastCall = State.CC == llvm::CallingConv::X86_FastCall;
74806c3fb27SDimitry Andric   bool IsRegCall = State.CC == llvm::CallingConv::X86_RegCall;
74906c3fb27SDimitry Andric   bool IsVectorCall = State.CC == llvm::CallingConv::X86_VectorCall;
75006c3fb27SDimitry Andric 
75106c3fb27SDimitry Andric   Ty = useFirstFieldIfTransparentUnion(Ty);
75206c3fb27SDimitry Andric   TypeInfo TI = getContext().getTypeInfo(Ty);
75306c3fb27SDimitry Andric 
75406c3fb27SDimitry Andric   // Check with the C++ ABI first.
75506c3fb27SDimitry Andric   const RecordType *RT = Ty->getAs<RecordType>();
75606c3fb27SDimitry Andric   if (RT) {
75706c3fb27SDimitry Andric     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
75806c3fb27SDimitry Andric     if (RAA == CGCXXABI::RAA_Indirect) {
75906c3fb27SDimitry Andric       return getIndirectResult(Ty, false, State);
7605f757f3fSDimitry Andric     } else if (State.IsDelegateCall) {
7618a4dda33SDimitry Andric       // Avoid having different alignments on delegate call args by always
7628a4dda33SDimitry Andric       // setting the alignment to 4, which is what we do for inallocas.
7638a4dda33SDimitry Andric       ABIArgInfo Res = getIndirectResult(Ty, false, State);
7648a4dda33SDimitry Andric       Res.setIndirectAlign(CharUnits::fromQuantity(4));
7658a4dda33SDimitry Andric       return Res;
76606c3fb27SDimitry Andric     } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
76706c3fb27SDimitry Andric       // The field index doesn't matter, we'll fix it up later.
76806c3fb27SDimitry Andric       return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
76906c3fb27SDimitry Andric     }
77006c3fb27SDimitry Andric   }
77106c3fb27SDimitry Andric 
77206c3fb27SDimitry Andric   // Regcall uses the concept of a homogenous vector aggregate, similar
77306c3fb27SDimitry Andric   // to other targets.
77406c3fb27SDimitry Andric   const Type *Base = nullptr;
77506c3fb27SDimitry Andric   uint64_t NumElts = 0;
77606c3fb27SDimitry Andric   if ((IsRegCall || IsVectorCall) &&
77706c3fb27SDimitry Andric       isHomogeneousAggregate(Ty, Base, NumElts)) {
77806c3fb27SDimitry Andric     if (State.FreeSSERegs >= NumElts) {
77906c3fb27SDimitry Andric       State.FreeSSERegs -= NumElts;
78006c3fb27SDimitry Andric 
78106c3fb27SDimitry Andric       // Vectorcall passes HVAs directly and does not flatten them, but regcall
78206c3fb27SDimitry Andric       // does.
78306c3fb27SDimitry Andric       if (IsVectorCall)
78406c3fb27SDimitry Andric         return getDirectX86Hva();
78506c3fb27SDimitry Andric 
78606c3fb27SDimitry Andric       if (Ty->isBuiltinType() || Ty->isVectorType())
78706c3fb27SDimitry Andric         return ABIArgInfo::getDirect();
78806c3fb27SDimitry Andric       return ABIArgInfo::getExpand();
78906c3fb27SDimitry Andric     }
79006c3fb27SDimitry Andric     return getIndirectResult(Ty, /*ByVal=*/false, State);
79106c3fb27SDimitry Andric   }
79206c3fb27SDimitry Andric 
79306c3fb27SDimitry Andric   if (isAggregateTypeForABI(Ty)) {
79406c3fb27SDimitry Andric     // Structures with flexible arrays are always indirect.
79506c3fb27SDimitry Andric     // FIXME: This should not be byval!
79606c3fb27SDimitry Andric     if (RT && RT->getDecl()->hasFlexibleArrayMember())
79706c3fb27SDimitry Andric       return getIndirectResult(Ty, true, State);
79806c3fb27SDimitry Andric 
79906c3fb27SDimitry Andric     // Ignore empty structs/unions on non-Windows.
80006c3fb27SDimitry Andric     if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
80106c3fb27SDimitry Andric       return ABIArgInfo::getIgnore();
80206c3fb27SDimitry Andric 
80306c3fb27SDimitry Andric     llvm::LLVMContext &LLVMContext = getVMContext();
80406c3fb27SDimitry Andric     llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
80506c3fb27SDimitry Andric     bool NeedsPadding = false;
80606c3fb27SDimitry Andric     bool InReg;
80706c3fb27SDimitry Andric     if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
80806c3fb27SDimitry Andric       unsigned SizeInRegs = (TI.Width + 31) / 32;
80906c3fb27SDimitry Andric       SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
81006c3fb27SDimitry Andric       llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
81106c3fb27SDimitry Andric       if (InReg)
81206c3fb27SDimitry Andric         return ABIArgInfo::getDirectInReg(Result);
81306c3fb27SDimitry Andric       else
81406c3fb27SDimitry Andric         return ABIArgInfo::getDirect(Result);
81506c3fb27SDimitry Andric     }
81606c3fb27SDimitry Andric     llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
81706c3fb27SDimitry Andric 
8185f757f3fSDimitry Andric     // Pass over-aligned aggregates to non-variadic functions on Windows
8195f757f3fSDimitry Andric     // indirectly. This behavior was added in MSVC 2015. Use the required
8205f757f3fSDimitry Andric     // alignment from the record layout, since that may be less than the
8215f757f3fSDimitry Andric     // regular type alignment, and types with required alignment of less than 4
8225f757f3fSDimitry Andric     // bytes are not passed indirectly.
8235f757f3fSDimitry Andric     if (IsWin32StructABI && State.Required.isRequiredArg(ArgIndex)) {
82406c3fb27SDimitry Andric       unsigned AlignInBits = 0;
82506c3fb27SDimitry Andric       if (RT) {
82606c3fb27SDimitry Andric         const ASTRecordLayout &Layout =
82706c3fb27SDimitry Andric           getContext().getASTRecordLayout(RT->getDecl());
82806c3fb27SDimitry Andric         AlignInBits = getContext().toBits(Layout.getRequiredAlignment());
82906c3fb27SDimitry Andric       } else if (TI.isAlignRequired()) {
83006c3fb27SDimitry Andric         AlignInBits = TI.Align;
83106c3fb27SDimitry Andric       }
83206c3fb27SDimitry Andric       if (AlignInBits > 32)
83306c3fb27SDimitry Andric         return getIndirectResult(Ty, /*ByVal=*/false, State);
83406c3fb27SDimitry Andric     }
83506c3fb27SDimitry Andric 
83606c3fb27SDimitry Andric     // Expand small (<= 128-bit) record types when we know that the stack layout
83706c3fb27SDimitry Andric     // of those arguments will match the struct. This is important because the
83806c3fb27SDimitry Andric     // LLVM backend isn't smart enough to remove byval, which inhibits many
83906c3fb27SDimitry Andric     // optimizations.
84006c3fb27SDimitry Andric     // Don't do this for the MCU if there are still free integer registers
84106c3fb27SDimitry Andric     // (see X86_64 ABI for full explanation).
84206c3fb27SDimitry Andric     if (TI.Width <= 4 * 32 && (!IsMCUABI || State.FreeRegs == 0) &&
84306c3fb27SDimitry Andric         canExpandIndirectArgument(Ty))
84406c3fb27SDimitry Andric       return ABIArgInfo::getExpandWithPadding(
84506c3fb27SDimitry Andric           IsFastCall || IsVectorCall || IsRegCall, PaddingType);
84606c3fb27SDimitry Andric 
84706c3fb27SDimitry Andric     return getIndirectResult(Ty, true, State);
84806c3fb27SDimitry Andric   }
84906c3fb27SDimitry Andric 
85006c3fb27SDimitry Andric   if (const VectorType *VT = Ty->getAs<VectorType>()) {
85106c3fb27SDimitry Andric     // On Windows, vectors are passed directly if registers are available, or
85206c3fb27SDimitry Andric     // indirectly if not. This avoids the need to align argument memory. Pass
85306c3fb27SDimitry Andric     // user-defined vector types larger than 512 bits indirectly for simplicity.
85406c3fb27SDimitry Andric     if (IsWin32StructABI) {
85506c3fb27SDimitry Andric       if (TI.Width <= 512 && State.FreeSSERegs > 0) {
85606c3fb27SDimitry Andric         --State.FreeSSERegs;
85706c3fb27SDimitry Andric         return ABIArgInfo::getDirectInReg();
85806c3fb27SDimitry Andric       }
85906c3fb27SDimitry Andric       return getIndirectResult(Ty, /*ByVal=*/false, State);
86006c3fb27SDimitry Andric     }
86106c3fb27SDimitry Andric 
86206c3fb27SDimitry Andric     // On Darwin, some vectors are passed in memory, we handle this by passing
86306c3fb27SDimitry Andric     // it as an i8/i16/i32/i64.
86406c3fb27SDimitry Andric     if (IsDarwinVectorABI) {
86506c3fb27SDimitry Andric       if ((TI.Width == 8 || TI.Width == 16 || TI.Width == 32) ||
86606c3fb27SDimitry Andric           (TI.Width == 64 && VT->getNumElements() == 1))
86706c3fb27SDimitry Andric         return ABIArgInfo::getDirect(
86806c3fb27SDimitry Andric             llvm::IntegerType::get(getVMContext(), TI.Width));
86906c3fb27SDimitry Andric     }
87006c3fb27SDimitry Andric 
87106c3fb27SDimitry Andric     if (IsX86_MMXType(CGT.ConvertType(Ty)))
87206c3fb27SDimitry Andric       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
87306c3fb27SDimitry Andric 
87406c3fb27SDimitry Andric     return ABIArgInfo::getDirect();
87506c3fb27SDimitry Andric   }
87606c3fb27SDimitry Andric 
87706c3fb27SDimitry Andric 
87806c3fb27SDimitry Andric   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
87906c3fb27SDimitry Andric     Ty = EnumTy->getDecl()->getIntegerType();
88006c3fb27SDimitry Andric 
88106c3fb27SDimitry Andric   bool InReg = shouldPrimitiveUseInReg(Ty, State);
88206c3fb27SDimitry Andric 
88306c3fb27SDimitry Andric   if (isPromotableIntegerTypeForABI(Ty)) {
88406c3fb27SDimitry Andric     if (InReg)
88506c3fb27SDimitry Andric       return ABIArgInfo::getExtendInReg(Ty);
88606c3fb27SDimitry Andric     return ABIArgInfo::getExtend(Ty);
88706c3fb27SDimitry Andric   }
88806c3fb27SDimitry Andric 
88906c3fb27SDimitry Andric   if (const auto *EIT = Ty->getAs<BitIntType>()) {
89006c3fb27SDimitry Andric     if (EIT->getNumBits() <= 64) {
89106c3fb27SDimitry Andric       if (InReg)
89206c3fb27SDimitry Andric         return ABIArgInfo::getDirectInReg();
89306c3fb27SDimitry Andric       return ABIArgInfo::getDirect();
89406c3fb27SDimitry Andric     }
89506c3fb27SDimitry Andric     return getIndirectResult(Ty, /*ByVal=*/false, State);
89606c3fb27SDimitry Andric   }
89706c3fb27SDimitry Andric 
89806c3fb27SDimitry Andric   if (InReg)
89906c3fb27SDimitry Andric     return ABIArgInfo::getDirectInReg();
90006c3fb27SDimitry Andric   return ABIArgInfo::getDirect();
90106c3fb27SDimitry Andric }
90206c3fb27SDimitry Andric 
90306c3fb27SDimitry Andric void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
90406c3fb27SDimitry Andric   CCState State(FI);
90506c3fb27SDimitry Andric   if (IsMCUABI)
90606c3fb27SDimitry Andric     State.FreeRegs = 3;
90706c3fb27SDimitry Andric   else if (State.CC == llvm::CallingConv::X86_FastCall) {
90806c3fb27SDimitry Andric     State.FreeRegs = 2;
90906c3fb27SDimitry Andric     State.FreeSSERegs = 3;
91006c3fb27SDimitry Andric   } else if (State.CC == llvm::CallingConv::X86_VectorCall) {
91106c3fb27SDimitry Andric     State.FreeRegs = 2;
91206c3fb27SDimitry Andric     State.FreeSSERegs = 6;
91306c3fb27SDimitry Andric   } else if (FI.getHasRegParm())
91406c3fb27SDimitry Andric     State.FreeRegs = FI.getRegParm();
91506c3fb27SDimitry Andric   else if (State.CC == llvm::CallingConv::X86_RegCall) {
91606c3fb27SDimitry Andric     State.FreeRegs = 5;
91706c3fb27SDimitry Andric     State.FreeSSERegs = 8;
91806c3fb27SDimitry Andric   } else if (IsWin32StructABI) {
91906c3fb27SDimitry Andric     // Since MSVC 2015, the first three SSE vectors have been passed in
92006c3fb27SDimitry Andric     // registers. The rest are passed indirectly.
92106c3fb27SDimitry Andric     State.FreeRegs = DefaultNumRegisterParameters;
92206c3fb27SDimitry Andric     State.FreeSSERegs = 3;
92306c3fb27SDimitry Andric   } else
92406c3fb27SDimitry Andric     State.FreeRegs = DefaultNumRegisterParameters;
92506c3fb27SDimitry Andric 
92606c3fb27SDimitry Andric   if (!::classifyReturnType(getCXXABI(), FI, *this)) {
92706c3fb27SDimitry Andric     FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
92806c3fb27SDimitry Andric   } else if (FI.getReturnInfo().isIndirect()) {
92906c3fb27SDimitry Andric     // The C++ ABI is not aware of register usage, so we have to check if the
93006c3fb27SDimitry Andric     // return value was sret and put it in a register ourselves if appropriate.
93106c3fb27SDimitry Andric     if (State.FreeRegs) {
93206c3fb27SDimitry Andric       --State.FreeRegs;  // The sret parameter consumes a register.
93306c3fb27SDimitry Andric       if (!IsMCUABI)
93406c3fb27SDimitry Andric         FI.getReturnInfo().setInReg(true);
93506c3fb27SDimitry Andric     }
93606c3fb27SDimitry Andric   }
93706c3fb27SDimitry Andric 
93806c3fb27SDimitry Andric   // The chain argument effectively gives us another free register.
93906c3fb27SDimitry Andric   if (FI.isChainCall())
94006c3fb27SDimitry Andric     ++State.FreeRegs;
94106c3fb27SDimitry Andric 
94206c3fb27SDimitry Andric   // For vectorcall, do a first pass over the arguments, assigning FP and vector
94306c3fb27SDimitry Andric   // arguments to XMM registers as available.
94406c3fb27SDimitry Andric   if (State.CC == llvm::CallingConv::X86_VectorCall)
94506c3fb27SDimitry Andric     runVectorCallFirstPass(FI, State);
94606c3fb27SDimitry Andric 
94706c3fb27SDimitry Andric   bool UsedInAlloca = false;
94806c3fb27SDimitry Andric   MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
9495f757f3fSDimitry Andric   for (unsigned I = 0, E = Args.size(); I < E; ++I) {
95006c3fb27SDimitry Andric     // Skip arguments that have already been assigned.
95106c3fb27SDimitry Andric     if (State.IsPreassigned.test(I))
95206c3fb27SDimitry Andric       continue;
95306c3fb27SDimitry Andric 
9548a4dda33SDimitry Andric     Args[I].info =
9555f757f3fSDimitry Andric         classifyArgumentType(Args[I].type, State, I);
95606c3fb27SDimitry Andric     UsedInAlloca |= (Args[I].info.getKind() == ABIArgInfo::InAlloca);
95706c3fb27SDimitry Andric   }
95806c3fb27SDimitry Andric 
95906c3fb27SDimitry Andric   // If we needed to use inalloca for any argument, do a second pass and rewrite
96006c3fb27SDimitry Andric   // all the memory arguments to use inalloca.
96106c3fb27SDimitry Andric   if (UsedInAlloca)
96206c3fb27SDimitry Andric     rewriteWithInAlloca(FI);
96306c3fb27SDimitry Andric }
96406c3fb27SDimitry Andric 
96506c3fb27SDimitry Andric void
96606c3fb27SDimitry Andric X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
96706c3fb27SDimitry Andric                                    CharUnits &StackOffset, ABIArgInfo &Info,
96806c3fb27SDimitry Andric                                    QualType Type) const {
96906c3fb27SDimitry Andric   // Arguments are always 4-byte-aligned.
97006c3fb27SDimitry Andric   CharUnits WordSize = CharUnits::fromQuantity(4);
97106c3fb27SDimitry Andric   assert(StackOffset.isMultipleOf(WordSize) && "unaligned inalloca struct");
97206c3fb27SDimitry Andric 
97306c3fb27SDimitry Andric   // sret pointers and indirect things will require an extra pointer
97406c3fb27SDimitry Andric   // indirection, unless they are byval. Most things are byval, and will not
97506c3fb27SDimitry Andric   // require this indirection.
97606c3fb27SDimitry Andric   bool IsIndirect = false;
97706c3fb27SDimitry Andric   if (Info.isIndirect() && !Info.getIndirectByVal())
97806c3fb27SDimitry Andric     IsIndirect = true;
97906c3fb27SDimitry Andric   Info = ABIArgInfo::getInAlloca(FrameFields.size(), IsIndirect);
98006c3fb27SDimitry Andric   llvm::Type *LLTy = CGT.ConvertTypeForMem(Type);
98106c3fb27SDimitry Andric   if (IsIndirect)
98206c3fb27SDimitry Andric     LLTy = llvm::PointerType::getUnqual(getVMContext());
98306c3fb27SDimitry Andric   FrameFields.push_back(LLTy);
98406c3fb27SDimitry Andric   StackOffset += IsIndirect ? WordSize : getContext().getTypeSizeInChars(Type);
98506c3fb27SDimitry Andric 
98606c3fb27SDimitry Andric   // Insert padding bytes to respect alignment.
98706c3fb27SDimitry Andric   CharUnits FieldEnd = StackOffset;
98806c3fb27SDimitry Andric   StackOffset = FieldEnd.alignTo(WordSize);
98906c3fb27SDimitry Andric   if (StackOffset != FieldEnd) {
99006c3fb27SDimitry Andric     CharUnits NumBytes = StackOffset - FieldEnd;
99106c3fb27SDimitry Andric     llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
99206c3fb27SDimitry Andric     Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
99306c3fb27SDimitry Andric     FrameFields.push_back(Ty);
99406c3fb27SDimitry Andric   }
99506c3fb27SDimitry Andric }
99606c3fb27SDimitry Andric 
99706c3fb27SDimitry Andric static bool isArgInAlloca(const ABIArgInfo &Info) {
99806c3fb27SDimitry Andric   // Leave ignored and inreg arguments alone.
99906c3fb27SDimitry Andric   switch (Info.getKind()) {
100006c3fb27SDimitry Andric   case ABIArgInfo::InAlloca:
100106c3fb27SDimitry Andric     return true;
100206c3fb27SDimitry Andric   case ABIArgInfo::Ignore:
100306c3fb27SDimitry Andric   case ABIArgInfo::IndirectAliased:
100406c3fb27SDimitry Andric     return false;
100506c3fb27SDimitry Andric   case ABIArgInfo::Indirect:
100606c3fb27SDimitry Andric   case ABIArgInfo::Direct:
100706c3fb27SDimitry Andric   case ABIArgInfo::Extend:
100806c3fb27SDimitry Andric     return !Info.getInReg();
100906c3fb27SDimitry Andric   case ABIArgInfo::Expand:
101006c3fb27SDimitry Andric   case ABIArgInfo::CoerceAndExpand:
101106c3fb27SDimitry Andric     // These are aggregate types which are never passed in registers when
101206c3fb27SDimitry Andric     // inalloca is involved.
101306c3fb27SDimitry Andric     return true;
101406c3fb27SDimitry Andric   }
101506c3fb27SDimitry Andric   llvm_unreachable("invalid enum");
101606c3fb27SDimitry Andric }
101706c3fb27SDimitry Andric 
101806c3fb27SDimitry Andric void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
101906c3fb27SDimitry Andric   assert(IsWin32StructABI && "inalloca only supported on win32");
102006c3fb27SDimitry Andric 
102106c3fb27SDimitry Andric   // Build a packed struct type for all of the arguments in memory.
102206c3fb27SDimitry Andric   SmallVector<llvm::Type *, 6> FrameFields;
102306c3fb27SDimitry Andric 
102406c3fb27SDimitry Andric   // The stack alignment is always 4.
102506c3fb27SDimitry Andric   CharUnits StackAlign = CharUnits::fromQuantity(4);
102606c3fb27SDimitry Andric 
102706c3fb27SDimitry Andric   CharUnits StackOffset;
102806c3fb27SDimitry Andric   CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
102906c3fb27SDimitry Andric 
103006c3fb27SDimitry Andric   // Put 'this' into the struct before 'sret', if necessary.
103106c3fb27SDimitry Andric   bool IsThisCall =
103206c3fb27SDimitry Andric       FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
103306c3fb27SDimitry Andric   ABIArgInfo &Ret = FI.getReturnInfo();
103406c3fb27SDimitry Andric   if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
103506c3fb27SDimitry Andric       isArgInAlloca(I->info)) {
103606c3fb27SDimitry Andric     addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
103706c3fb27SDimitry Andric     ++I;
103806c3fb27SDimitry Andric   }
103906c3fb27SDimitry Andric 
104006c3fb27SDimitry Andric   // Put the sret parameter into the inalloca struct if it's in memory.
104106c3fb27SDimitry Andric   if (Ret.isIndirect() && !Ret.getInReg()) {
104206c3fb27SDimitry Andric     addFieldToArgStruct(FrameFields, StackOffset, Ret, FI.getReturnType());
104306c3fb27SDimitry Andric     // On Windows, the hidden sret parameter is always returned in eax.
104406c3fb27SDimitry Andric     Ret.setInAllocaSRet(IsWin32StructABI);
104506c3fb27SDimitry Andric   }
104606c3fb27SDimitry Andric 
104706c3fb27SDimitry Andric   // Skip the 'this' parameter in ecx.
104806c3fb27SDimitry Andric   if (IsThisCall)
104906c3fb27SDimitry Andric     ++I;
105006c3fb27SDimitry Andric 
105106c3fb27SDimitry Andric   // Put arguments passed in memory into the struct.
105206c3fb27SDimitry Andric   for (; I != E; ++I) {
105306c3fb27SDimitry Andric     if (isArgInAlloca(I->info))
105406c3fb27SDimitry Andric       addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
105506c3fb27SDimitry Andric   }
105606c3fb27SDimitry Andric 
105706c3fb27SDimitry Andric   FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
105806c3fb27SDimitry Andric                                         /*isPacked=*/true),
105906c3fb27SDimitry Andric                   StackAlign);
106006c3fb27SDimitry Andric }
106106c3fb27SDimitry Andric 
106206c3fb27SDimitry Andric Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
106306c3fb27SDimitry Andric                                  Address VAListAddr, QualType Ty) const {
106406c3fb27SDimitry Andric 
106506c3fb27SDimitry Andric   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
106606c3fb27SDimitry Andric 
106706c3fb27SDimitry Andric   // x86-32 changes the alignment of certain arguments on the stack.
106806c3fb27SDimitry Andric   //
106906c3fb27SDimitry Andric   // Just messing with TypeInfo like this works because we never pass
107006c3fb27SDimitry Andric   // anything indirectly.
107106c3fb27SDimitry Andric   TypeInfo.Align = CharUnits::fromQuantity(
107206c3fb27SDimitry Andric                 getTypeStackAlignInBytes(Ty, TypeInfo.Align.getQuantity()));
107306c3fb27SDimitry Andric 
107406c3fb27SDimitry Andric   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
107506c3fb27SDimitry Andric                           TypeInfo, CharUnits::fromQuantity(4),
107606c3fb27SDimitry Andric                           /*AllowHigherAlign*/ true);
107706c3fb27SDimitry Andric }
107806c3fb27SDimitry Andric 
107906c3fb27SDimitry Andric bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
108006c3fb27SDimitry Andric     const llvm::Triple &Triple, const CodeGenOptions &Opts) {
108106c3fb27SDimitry Andric   assert(Triple.getArch() == llvm::Triple::x86);
108206c3fb27SDimitry Andric 
108306c3fb27SDimitry Andric   switch (Opts.getStructReturnConvention()) {
108406c3fb27SDimitry Andric   case CodeGenOptions::SRCK_Default:
108506c3fb27SDimitry Andric     break;
108606c3fb27SDimitry Andric   case CodeGenOptions::SRCK_OnStack:  // -fpcc-struct-return
108706c3fb27SDimitry Andric     return false;
108806c3fb27SDimitry Andric   case CodeGenOptions::SRCK_InRegs:  // -freg-struct-return
108906c3fb27SDimitry Andric     return true;
109006c3fb27SDimitry Andric   }
109106c3fb27SDimitry Andric 
109206c3fb27SDimitry Andric   if (Triple.isOSDarwin() || Triple.isOSIAMCU())
109306c3fb27SDimitry Andric     return true;
109406c3fb27SDimitry Andric 
109506c3fb27SDimitry Andric   switch (Triple.getOS()) {
109606c3fb27SDimitry Andric   case llvm::Triple::DragonFly:
109706c3fb27SDimitry Andric   case llvm::Triple::FreeBSD:
109806c3fb27SDimitry Andric   case llvm::Triple::OpenBSD:
109906c3fb27SDimitry Andric   case llvm::Triple::Win32:
110006c3fb27SDimitry Andric     return true;
110106c3fb27SDimitry Andric   default:
110206c3fb27SDimitry Andric     return false;
110306c3fb27SDimitry Andric   }
110406c3fb27SDimitry Andric }
110506c3fb27SDimitry Andric 
110606c3fb27SDimitry Andric static void addX86InterruptAttrs(const FunctionDecl *FD, llvm::GlobalValue *GV,
110706c3fb27SDimitry Andric                                  CodeGen::CodeGenModule &CGM) {
110806c3fb27SDimitry Andric   if (!FD->hasAttr<AnyX86InterruptAttr>())
110906c3fb27SDimitry Andric     return;
111006c3fb27SDimitry Andric 
111106c3fb27SDimitry Andric   llvm::Function *Fn = cast<llvm::Function>(GV);
111206c3fb27SDimitry Andric   Fn->setCallingConv(llvm::CallingConv::X86_INTR);
111306c3fb27SDimitry Andric   if (FD->getNumParams() == 0)
111406c3fb27SDimitry Andric     return;
111506c3fb27SDimitry Andric 
111606c3fb27SDimitry Andric   auto PtrTy = cast<PointerType>(FD->getParamDecl(0)->getType());
111706c3fb27SDimitry Andric   llvm::Type *ByValTy = CGM.getTypes().ConvertType(PtrTy->getPointeeType());
111806c3fb27SDimitry Andric   llvm::Attribute NewAttr = llvm::Attribute::getWithByValType(
111906c3fb27SDimitry Andric     Fn->getContext(), ByValTy);
112006c3fb27SDimitry Andric   Fn->addParamAttr(0, NewAttr);
112106c3fb27SDimitry Andric }
112206c3fb27SDimitry Andric 
112306c3fb27SDimitry Andric void X86_32TargetCodeGenInfo::setTargetAttributes(
112406c3fb27SDimitry Andric     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
112506c3fb27SDimitry Andric   if (GV->isDeclaration())
112606c3fb27SDimitry Andric     return;
112706c3fb27SDimitry Andric   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
112806c3fb27SDimitry Andric     if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
112906c3fb27SDimitry Andric       llvm::Function *Fn = cast<llvm::Function>(GV);
113006c3fb27SDimitry Andric       Fn->addFnAttr("stackrealign");
113106c3fb27SDimitry Andric     }
113206c3fb27SDimitry Andric 
113306c3fb27SDimitry Andric     addX86InterruptAttrs(FD, GV, CGM);
113406c3fb27SDimitry Andric   }
113506c3fb27SDimitry Andric }
113606c3fb27SDimitry Andric 
113706c3fb27SDimitry Andric bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
113806c3fb27SDimitry Andric                                                CodeGen::CodeGenFunction &CGF,
113906c3fb27SDimitry Andric                                                llvm::Value *Address) const {
114006c3fb27SDimitry Andric   CodeGen::CGBuilderTy &Builder = CGF.Builder;
114106c3fb27SDimitry Andric 
114206c3fb27SDimitry Andric   llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
114306c3fb27SDimitry Andric 
114406c3fb27SDimitry Andric   // 0-7 are the eight integer registers;  the order is different
114506c3fb27SDimitry Andric   //   on Darwin (for EH), but the range is the same.
114606c3fb27SDimitry Andric   // 8 is %eip.
114706c3fb27SDimitry Andric   AssignToArrayRange(Builder, Address, Four8, 0, 8);
114806c3fb27SDimitry Andric 
114906c3fb27SDimitry Andric   if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
115006c3fb27SDimitry Andric     // 12-16 are st(0..4).  Not sure why we stop at 4.
115106c3fb27SDimitry Andric     // These have size 16, which is sizeof(long double) on
115206c3fb27SDimitry Andric     // platforms with 8-byte alignment for that type.
115306c3fb27SDimitry Andric     llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
115406c3fb27SDimitry Andric     AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
115506c3fb27SDimitry Andric 
115606c3fb27SDimitry Andric   } else {
115706c3fb27SDimitry Andric     // 9 is %eflags, which doesn't get a size on Darwin for some
115806c3fb27SDimitry Andric     // reason.
115906c3fb27SDimitry Andric     Builder.CreateAlignedStore(
116006c3fb27SDimitry Andric         Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
116106c3fb27SDimitry Andric                                CharUnits::One());
116206c3fb27SDimitry Andric 
116306c3fb27SDimitry Andric     // 11-16 are st(0..5).  Not sure why we stop at 5.
116406c3fb27SDimitry Andric     // These have size 12, which is sizeof(long double) on
116506c3fb27SDimitry Andric     // platforms with 4-byte alignment for that type.
116606c3fb27SDimitry Andric     llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
116706c3fb27SDimitry Andric     AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
116806c3fb27SDimitry Andric   }
116906c3fb27SDimitry Andric 
117006c3fb27SDimitry Andric   return false;
117106c3fb27SDimitry Andric }
117206c3fb27SDimitry Andric 
117306c3fb27SDimitry Andric //===----------------------------------------------------------------------===//
117406c3fb27SDimitry Andric // X86-64 ABI Implementation
117506c3fb27SDimitry Andric //===----------------------------------------------------------------------===//
117606c3fb27SDimitry Andric 
117706c3fb27SDimitry Andric 
117806c3fb27SDimitry Andric namespace {
117906c3fb27SDimitry Andric 
118006c3fb27SDimitry Andric /// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
118106c3fb27SDimitry Andric static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
118206c3fb27SDimitry Andric   switch (AVXLevel) {
118306c3fb27SDimitry Andric   case X86AVXABILevel::AVX512:
118406c3fb27SDimitry Andric     return 512;
118506c3fb27SDimitry Andric   case X86AVXABILevel::AVX:
118606c3fb27SDimitry Andric     return 256;
118706c3fb27SDimitry Andric   case X86AVXABILevel::None:
118806c3fb27SDimitry Andric     return 128;
118906c3fb27SDimitry Andric   }
119006c3fb27SDimitry Andric   llvm_unreachable("Unknown AVXLevel");
119106c3fb27SDimitry Andric }
119206c3fb27SDimitry Andric 
119306c3fb27SDimitry Andric /// X86_64ABIInfo - The X86_64 ABI information.
119406c3fb27SDimitry Andric class X86_64ABIInfo : public ABIInfo {
119506c3fb27SDimitry Andric   enum Class {
119606c3fb27SDimitry Andric     Integer = 0,
119706c3fb27SDimitry Andric     SSE,
119806c3fb27SDimitry Andric     SSEUp,
119906c3fb27SDimitry Andric     X87,
120006c3fb27SDimitry Andric     X87Up,
120106c3fb27SDimitry Andric     ComplexX87,
120206c3fb27SDimitry Andric     NoClass,
120306c3fb27SDimitry Andric     Memory
120406c3fb27SDimitry Andric   };
120506c3fb27SDimitry Andric 
120606c3fb27SDimitry Andric   /// merge - Implement the X86_64 ABI merging algorithm.
120706c3fb27SDimitry Andric   ///
120806c3fb27SDimitry Andric   /// Merge an accumulating classification \arg Accum with a field
120906c3fb27SDimitry Andric   /// classification \arg Field.
121006c3fb27SDimitry Andric   ///
121106c3fb27SDimitry Andric   /// \param Accum - The accumulating classification. This should
121206c3fb27SDimitry Andric   /// always be either NoClass or the result of a previous merge
121306c3fb27SDimitry Andric   /// call. In addition, this should never be Memory (the caller
121406c3fb27SDimitry Andric   /// should just return Memory for the aggregate).
121506c3fb27SDimitry Andric   static Class merge(Class Accum, Class Field);
121606c3fb27SDimitry Andric 
121706c3fb27SDimitry Andric   /// postMerge - Implement the X86_64 ABI post merging algorithm.
121806c3fb27SDimitry Andric   ///
121906c3fb27SDimitry Andric   /// Post merger cleanup, reduces a malformed Hi and Lo pair to
122006c3fb27SDimitry Andric   /// final MEMORY or SSE classes when necessary.
122106c3fb27SDimitry Andric   ///
122206c3fb27SDimitry Andric   /// \param AggregateSize - The size of the current aggregate in
122306c3fb27SDimitry Andric   /// the classification process.
122406c3fb27SDimitry Andric   ///
122506c3fb27SDimitry Andric   /// \param Lo - The classification for the parts of the type
122606c3fb27SDimitry Andric   /// residing in the low word of the containing object.
122706c3fb27SDimitry Andric   ///
122806c3fb27SDimitry Andric   /// \param Hi - The classification for the parts of the type
122906c3fb27SDimitry Andric   /// residing in the higher words of the containing object.
123006c3fb27SDimitry Andric   ///
123106c3fb27SDimitry Andric   void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
123206c3fb27SDimitry Andric 
123306c3fb27SDimitry Andric   /// classify - Determine the x86_64 register classes in which the
123406c3fb27SDimitry Andric   /// given type T should be passed.
123506c3fb27SDimitry Andric   ///
123606c3fb27SDimitry Andric   /// \param Lo - The classification for the parts of the type
123706c3fb27SDimitry Andric   /// residing in the low word of the containing object.
123806c3fb27SDimitry Andric   ///
123906c3fb27SDimitry Andric   /// \param Hi - The classification for the parts of the type
124006c3fb27SDimitry Andric   /// residing in the high word of the containing object.
124106c3fb27SDimitry Andric   ///
124206c3fb27SDimitry Andric   /// \param OffsetBase - The bit offset of this type in the
124306c3fb27SDimitry Andric   /// containing object.  Some parameters are classified different
124406c3fb27SDimitry Andric   /// depending on whether they straddle an eightbyte boundary.
124506c3fb27SDimitry Andric   ///
124606c3fb27SDimitry Andric   /// \param isNamedArg - Whether the argument in question is a "named"
124706c3fb27SDimitry Andric   /// argument, as used in AMD64-ABI 3.5.7.
124806c3fb27SDimitry Andric   ///
124906c3fb27SDimitry Andric   /// \param IsRegCall - Whether the calling conversion is regcall.
125006c3fb27SDimitry Andric   ///
125106c3fb27SDimitry Andric   /// If a word is unused its result will be NoClass; if a type should
125206c3fb27SDimitry Andric   /// be passed in Memory then at least the classification of \arg Lo
125306c3fb27SDimitry Andric   /// will be Memory.
125406c3fb27SDimitry Andric   ///
125506c3fb27SDimitry Andric   /// The \arg Lo class will be NoClass iff the argument is ignored.
125606c3fb27SDimitry Andric   ///
125706c3fb27SDimitry Andric   /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
125806c3fb27SDimitry Andric   /// also be ComplexX87.
125906c3fb27SDimitry Andric   void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
126006c3fb27SDimitry Andric                 bool isNamedArg, bool IsRegCall = false) const;
126106c3fb27SDimitry Andric 
126206c3fb27SDimitry Andric   llvm::Type *GetByteVectorType(QualType Ty) const;
126306c3fb27SDimitry Andric   llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
126406c3fb27SDimitry Andric                                  unsigned IROffset, QualType SourceTy,
126506c3fb27SDimitry Andric                                  unsigned SourceOffset) const;
126606c3fb27SDimitry Andric   llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
126706c3fb27SDimitry Andric                                      unsigned IROffset, QualType SourceTy,
126806c3fb27SDimitry Andric                                      unsigned SourceOffset) const;
126906c3fb27SDimitry Andric 
127006c3fb27SDimitry Andric   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
127106c3fb27SDimitry Andric   /// such that the argument will be returned in memory.
127206c3fb27SDimitry Andric   ABIArgInfo getIndirectReturnResult(QualType Ty) const;
127306c3fb27SDimitry Andric 
127406c3fb27SDimitry Andric   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
127506c3fb27SDimitry Andric   /// such that the argument will be passed in memory.
127606c3fb27SDimitry Andric   ///
127706c3fb27SDimitry Andric   /// \param freeIntRegs - The number of free integer registers remaining
127806c3fb27SDimitry Andric   /// available.
127906c3fb27SDimitry Andric   ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
128006c3fb27SDimitry Andric 
128106c3fb27SDimitry Andric   ABIArgInfo classifyReturnType(QualType RetTy) const;
128206c3fb27SDimitry Andric 
128306c3fb27SDimitry Andric   ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
128406c3fb27SDimitry Andric                                   unsigned &neededInt, unsigned &neededSSE,
128506c3fb27SDimitry Andric                                   bool isNamedArg,
128606c3fb27SDimitry Andric                                   bool IsRegCall = false) const;
128706c3fb27SDimitry Andric 
128806c3fb27SDimitry Andric   ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
128906c3fb27SDimitry Andric                                        unsigned &NeededSSE,
129006c3fb27SDimitry Andric                                        unsigned &MaxVectorWidth) const;
129106c3fb27SDimitry Andric 
129206c3fb27SDimitry Andric   ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
129306c3fb27SDimitry Andric                                            unsigned &NeededSSE,
129406c3fb27SDimitry Andric                                            unsigned &MaxVectorWidth) const;
129506c3fb27SDimitry Andric 
129606c3fb27SDimitry Andric   bool IsIllegalVectorType(QualType Ty) const;
129706c3fb27SDimitry Andric 
129806c3fb27SDimitry Andric   /// The 0.98 ABI revision clarified a lot of ambiguities,
129906c3fb27SDimitry Andric   /// unfortunately in ways that were not always consistent with
130006c3fb27SDimitry Andric   /// certain previous compilers.  In particular, platforms which
130106c3fb27SDimitry Andric   /// required strict binary compatibility with older versions of GCC
130206c3fb27SDimitry Andric   /// may need to exempt themselves.
130306c3fb27SDimitry Andric   bool honorsRevision0_98() const {
130406c3fb27SDimitry Andric     return !getTarget().getTriple().isOSDarwin();
130506c3fb27SDimitry Andric   }
130606c3fb27SDimitry Andric 
130706c3fb27SDimitry Andric   /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to
130806c3fb27SDimitry Andric   /// classify it as INTEGER (for compatibility with older clang compilers).
130906c3fb27SDimitry Andric   bool classifyIntegerMMXAsSSE() const {
131006c3fb27SDimitry Andric     // Clang <= 3.8 did not do this.
131106c3fb27SDimitry Andric     if (getContext().getLangOpts().getClangABICompat() <=
131206c3fb27SDimitry Andric         LangOptions::ClangABI::Ver3_8)
131306c3fb27SDimitry Andric       return false;
131406c3fb27SDimitry Andric 
131506c3fb27SDimitry Andric     const llvm::Triple &Triple = getTarget().getTriple();
131606c3fb27SDimitry Andric     if (Triple.isOSDarwin() || Triple.isPS() || Triple.isOSFreeBSD())
131706c3fb27SDimitry Andric       return false;
131806c3fb27SDimitry Andric     return true;
131906c3fb27SDimitry Andric   }
132006c3fb27SDimitry Andric 
132106c3fb27SDimitry Andric   // GCC classifies vectors of __int128 as memory.
132206c3fb27SDimitry Andric   bool passInt128VectorsInMem() const {
132306c3fb27SDimitry Andric     // Clang <= 9.0 did not do this.
132406c3fb27SDimitry Andric     if (getContext().getLangOpts().getClangABICompat() <=
132506c3fb27SDimitry Andric         LangOptions::ClangABI::Ver9)
132606c3fb27SDimitry Andric       return false;
132706c3fb27SDimitry Andric 
132806c3fb27SDimitry Andric     const llvm::Triple &T = getTarget().getTriple();
132906c3fb27SDimitry Andric     return T.isOSLinux() || T.isOSNetBSD();
133006c3fb27SDimitry Andric   }
133106c3fb27SDimitry Andric 
133206c3fb27SDimitry Andric   X86AVXABILevel AVXLevel;
133306c3fb27SDimitry Andric   // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
133406c3fb27SDimitry Andric   // 64-bit hardware.
133506c3fb27SDimitry Andric   bool Has64BitPointers;
133606c3fb27SDimitry Andric 
133706c3fb27SDimitry Andric public:
133806c3fb27SDimitry Andric   X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
133906c3fb27SDimitry Andric       : ABIInfo(CGT), AVXLevel(AVXLevel),
134006c3fb27SDimitry Andric         Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {}
134106c3fb27SDimitry Andric 
134206c3fb27SDimitry Andric   bool isPassedUsingAVXType(QualType type) const {
134306c3fb27SDimitry Andric     unsigned neededInt, neededSSE;
134406c3fb27SDimitry Andric     // The freeIntRegs argument doesn't matter here.
134506c3fb27SDimitry Andric     ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
134606c3fb27SDimitry Andric                                            /*isNamedArg*/true);
134706c3fb27SDimitry Andric     if (info.isDirect()) {
134806c3fb27SDimitry Andric       llvm::Type *ty = info.getCoerceToType();
134906c3fb27SDimitry Andric       if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
135006c3fb27SDimitry Andric         return vectorTy->getPrimitiveSizeInBits().getFixedValue() > 128;
135106c3fb27SDimitry Andric     }
135206c3fb27SDimitry Andric     return false;
135306c3fb27SDimitry Andric   }
135406c3fb27SDimitry Andric 
135506c3fb27SDimitry Andric   void computeInfo(CGFunctionInfo &FI) const override;
135606c3fb27SDimitry Andric 
135706c3fb27SDimitry Andric   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
135806c3fb27SDimitry Andric                     QualType Ty) const override;
135906c3fb27SDimitry Andric   Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
136006c3fb27SDimitry Andric                       QualType Ty) const override;
136106c3fb27SDimitry Andric 
136206c3fb27SDimitry Andric   bool has64BitPointers() const {
136306c3fb27SDimitry Andric     return Has64BitPointers;
136406c3fb27SDimitry Andric   }
136506c3fb27SDimitry Andric };
136606c3fb27SDimitry Andric 
136706c3fb27SDimitry Andric /// WinX86_64ABIInfo - The Windows X86_64 ABI information.
136806c3fb27SDimitry Andric class WinX86_64ABIInfo : public ABIInfo {
136906c3fb27SDimitry Andric public:
137006c3fb27SDimitry Andric   WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
137106c3fb27SDimitry Andric       : ABIInfo(CGT), AVXLevel(AVXLevel),
137206c3fb27SDimitry Andric         IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
137306c3fb27SDimitry Andric 
137406c3fb27SDimitry Andric   void computeInfo(CGFunctionInfo &FI) const override;
137506c3fb27SDimitry Andric 
137606c3fb27SDimitry Andric   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
137706c3fb27SDimitry Andric                     QualType Ty) const override;
137806c3fb27SDimitry Andric 
137906c3fb27SDimitry Andric   bool isHomogeneousAggregateBaseType(QualType Ty) const override {
138006c3fb27SDimitry Andric     // FIXME: Assumes vectorcall is in use.
138106c3fb27SDimitry Andric     return isX86VectorTypeForVectorCall(getContext(), Ty);
138206c3fb27SDimitry Andric   }
138306c3fb27SDimitry Andric 
138406c3fb27SDimitry Andric   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
138506c3fb27SDimitry Andric                                          uint64_t NumMembers) const override {
138606c3fb27SDimitry Andric     // FIXME: Assumes vectorcall is in use.
138706c3fb27SDimitry Andric     return isX86VectorCallAggregateSmallEnough(NumMembers);
138806c3fb27SDimitry Andric   }
138906c3fb27SDimitry Andric 
139006c3fb27SDimitry Andric private:
139106c3fb27SDimitry Andric   ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
139206c3fb27SDimitry Andric                       bool IsVectorCall, bool IsRegCall) const;
139306c3fb27SDimitry Andric   ABIArgInfo reclassifyHvaArgForVectorCall(QualType Ty, unsigned &FreeSSERegs,
139406c3fb27SDimitry Andric                                            const ABIArgInfo &current) const;
139506c3fb27SDimitry Andric 
139606c3fb27SDimitry Andric   X86AVXABILevel AVXLevel;
139706c3fb27SDimitry Andric 
139806c3fb27SDimitry Andric   bool IsMingw64;
139906c3fb27SDimitry Andric };
140006c3fb27SDimitry Andric 
140106c3fb27SDimitry Andric class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
140206c3fb27SDimitry Andric public:
140306c3fb27SDimitry Andric   X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
140406c3fb27SDimitry Andric       : TargetCodeGenInfo(std::make_unique<X86_64ABIInfo>(CGT, AVXLevel)) {
140506c3fb27SDimitry Andric     SwiftInfo =
140606c3fb27SDimitry Andric         std::make_unique<SwiftABIInfo>(CGT, /*SwiftErrorInRegister=*/true);
140706c3fb27SDimitry Andric   }
140806c3fb27SDimitry Andric 
140906c3fb27SDimitry Andric   /// Disable tail call on x86-64. The epilogue code before the tail jump blocks
141006c3fb27SDimitry Andric   /// autoreleaseRV/retainRV and autoreleaseRV/unsafeClaimRV optimizations.
141106c3fb27SDimitry Andric   bool markARCOptimizedReturnCallsAsNoTail() const override { return true; }
141206c3fb27SDimitry Andric 
141306c3fb27SDimitry Andric   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
141406c3fb27SDimitry Andric     return 7;
141506c3fb27SDimitry Andric   }
141606c3fb27SDimitry Andric 
141706c3fb27SDimitry Andric   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
141806c3fb27SDimitry Andric                                llvm::Value *Address) const override {
141906c3fb27SDimitry Andric     llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
142006c3fb27SDimitry Andric 
142106c3fb27SDimitry Andric     // 0-15 are the 16 integer registers.
142206c3fb27SDimitry Andric     // 16 is %rip.
142306c3fb27SDimitry Andric     AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
142406c3fb27SDimitry Andric     return false;
142506c3fb27SDimitry Andric   }
142606c3fb27SDimitry Andric 
142706c3fb27SDimitry Andric   llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
142806c3fb27SDimitry Andric                                   StringRef Constraint,
142906c3fb27SDimitry Andric                                   llvm::Type* Ty) const override {
143006c3fb27SDimitry Andric     return X86AdjustInlineAsmType(CGF, Constraint, Ty);
143106c3fb27SDimitry Andric   }
143206c3fb27SDimitry Andric 
143306c3fb27SDimitry Andric   bool isNoProtoCallVariadic(const CallArgList &args,
143406c3fb27SDimitry Andric                              const FunctionNoProtoType *fnType) const override {
143506c3fb27SDimitry Andric     // The default CC on x86-64 sets %al to the number of SSA
143606c3fb27SDimitry Andric     // registers used, and GCC sets this when calling an unprototyped
143706c3fb27SDimitry Andric     // function, so we override the default behavior.  However, don't do
143806c3fb27SDimitry Andric     // that when AVX types are involved: the ABI explicitly states it is
143906c3fb27SDimitry Andric     // undefined, and it doesn't work in practice because of how the ABI
144006c3fb27SDimitry Andric     // defines varargs anyway.
144106c3fb27SDimitry Andric     if (fnType->getCallConv() == CC_C) {
144206c3fb27SDimitry Andric       bool HasAVXType = false;
144306c3fb27SDimitry Andric       for (CallArgList::const_iterator
144406c3fb27SDimitry Andric              it = args.begin(), ie = args.end(); it != ie; ++it) {
144506c3fb27SDimitry Andric         if (getABIInfo<X86_64ABIInfo>().isPassedUsingAVXType(it->Ty)) {
144606c3fb27SDimitry Andric           HasAVXType = true;
144706c3fb27SDimitry Andric           break;
144806c3fb27SDimitry Andric         }
144906c3fb27SDimitry Andric       }
145006c3fb27SDimitry Andric 
145106c3fb27SDimitry Andric       if (!HasAVXType)
145206c3fb27SDimitry Andric         return true;
145306c3fb27SDimitry Andric     }
145406c3fb27SDimitry Andric 
145506c3fb27SDimitry Andric     return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
145606c3fb27SDimitry Andric   }
145706c3fb27SDimitry Andric 
145806c3fb27SDimitry Andric   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
145906c3fb27SDimitry Andric                            CodeGen::CodeGenModule &CGM) const override {
146006c3fb27SDimitry Andric     if (GV->isDeclaration())
146106c3fb27SDimitry Andric       return;
146206c3fb27SDimitry Andric     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
146306c3fb27SDimitry Andric       if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
146406c3fb27SDimitry Andric         llvm::Function *Fn = cast<llvm::Function>(GV);
146506c3fb27SDimitry Andric         Fn->addFnAttr("stackrealign");
146606c3fb27SDimitry Andric       }
146706c3fb27SDimitry Andric 
146806c3fb27SDimitry Andric       addX86InterruptAttrs(FD, GV, CGM);
146906c3fb27SDimitry Andric     }
147006c3fb27SDimitry Andric   }
147106c3fb27SDimitry Andric 
147206c3fb27SDimitry Andric   void checkFunctionCallABI(CodeGenModule &CGM, SourceLocation CallLoc,
147306c3fb27SDimitry Andric                             const FunctionDecl *Caller,
147406c3fb27SDimitry Andric                             const FunctionDecl *Callee,
147506c3fb27SDimitry Andric                             const CallArgList &Args) const override;
147606c3fb27SDimitry Andric };
147706c3fb27SDimitry Andric } // namespace
147806c3fb27SDimitry Andric 
147906c3fb27SDimitry Andric static void initFeatureMaps(const ASTContext &Ctx,
148006c3fb27SDimitry Andric                             llvm::StringMap<bool> &CallerMap,
148106c3fb27SDimitry Andric                             const FunctionDecl *Caller,
148206c3fb27SDimitry Andric                             llvm::StringMap<bool> &CalleeMap,
148306c3fb27SDimitry Andric                             const FunctionDecl *Callee) {
148406c3fb27SDimitry Andric   if (CalleeMap.empty() && CallerMap.empty()) {
148506c3fb27SDimitry Andric     // The caller is potentially nullptr in the case where the call isn't in a
148606c3fb27SDimitry Andric     // function.  In this case, the getFunctionFeatureMap ensures we just get
148706c3fb27SDimitry Andric     // the TU level setting (since it cannot be modified by 'target'..
148806c3fb27SDimitry Andric     Ctx.getFunctionFeatureMap(CallerMap, Caller);
148906c3fb27SDimitry Andric     Ctx.getFunctionFeatureMap(CalleeMap, Callee);
149006c3fb27SDimitry Andric   }
149106c3fb27SDimitry Andric }
149206c3fb27SDimitry Andric 
149306c3fb27SDimitry Andric static bool checkAVXParamFeature(DiagnosticsEngine &Diag,
149406c3fb27SDimitry Andric                                  SourceLocation CallLoc,
149506c3fb27SDimitry Andric                                  const llvm::StringMap<bool> &CallerMap,
149606c3fb27SDimitry Andric                                  const llvm::StringMap<bool> &CalleeMap,
149706c3fb27SDimitry Andric                                  QualType Ty, StringRef Feature,
149806c3fb27SDimitry Andric                                  bool IsArgument) {
149906c3fb27SDimitry Andric   bool CallerHasFeat = CallerMap.lookup(Feature);
150006c3fb27SDimitry Andric   bool CalleeHasFeat = CalleeMap.lookup(Feature);
150106c3fb27SDimitry Andric   if (!CallerHasFeat && !CalleeHasFeat)
150206c3fb27SDimitry Andric     return Diag.Report(CallLoc, diag::warn_avx_calling_convention)
150306c3fb27SDimitry Andric            << IsArgument << Ty << Feature;
150406c3fb27SDimitry Andric 
150506c3fb27SDimitry Andric   // Mixing calling conventions here is very clearly an error.
150606c3fb27SDimitry Andric   if (!CallerHasFeat || !CalleeHasFeat)
150706c3fb27SDimitry Andric     return Diag.Report(CallLoc, diag::err_avx_calling_convention)
150806c3fb27SDimitry Andric            << IsArgument << Ty << Feature;
150906c3fb27SDimitry Andric 
151006c3fb27SDimitry Andric   // Else, both caller and callee have the required feature, so there is no need
151106c3fb27SDimitry Andric   // to diagnose.
151206c3fb27SDimitry Andric   return false;
151306c3fb27SDimitry Andric }
151406c3fb27SDimitry Andric 
15155f757f3fSDimitry Andric static bool checkAVX512ParamFeature(DiagnosticsEngine &Diag,
15165f757f3fSDimitry Andric                                     SourceLocation CallLoc,
15175f757f3fSDimitry Andric                                     const llvm::StringMap<bool> &CallerMap,
15185f757f3fSDimitry Andric                                     const llvm::StringMap<bool> &CalleeMap,
15195f757f3fSDimitry Andric                                     QualType Ty, bool IsArgument) {
15205f757f3fSDimitry Andric   bool Caller256 = CallerMap.lookup("avx512f") && !CallerMap.lookup("evex512");
15215f757f3fSDimitry Andric   bool Callee256 = CalleeMap.lookup("avx512f") && !CalleeMap.lookup("evex512");
15225f757f3fSDimitry Andric 
15235f757f3fSDimitry Andric   // Forbid 512-bit or larger vector pass or return when we disabled ZMM
15245f757f3fSDimitry Andric   // instructions.
15255f757f3fSDimitry Andric   if (Caller256 || Callee256)
15265f757f3fSDimitry Andric     return Diag.Report(CallLoc, diag::err_avx_calling_convention)
15275f757f3fSDimitry Andric            << IsArgument << Ty << "evex512";
15285f757f3fSDimitry Andric 
15295f757f3fSDimitry Andric   return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty,
15305f757f3fSDimitry Andric                               "avx512f", IsArgument);
15315f757f3fSDimitry Andric }
15325f757f3fSDimitry Andric 
153306c3fb27SDimitry Andric static bool checkAVXParam(DiagnosticsEngine &Diag, ASTContext &Ctx,
153406c3fb27SDimitry Andric                           SourceLocation CallLoc,
153506c3fb27SDimitry Andric                           const llvm::StringMap<bool> &CallerMap,
153606c3fb27SDimitry Andric                           const llvm::StringMap<bool> &CalleeMap, QualType Ty,
153706c3fb27SDimitry Andric                           bool IsArgument) {
153806c3fb27SDimitry Andric   uint64_t Size = Ctx.getTypeSize(Ty);
153906c3fb27SDimitry Andric   if (Size > 256)
15405f757f3fSDimitry Andric     return checkAVX512ParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty,
15415f757f3fSDimitry Andric                                    IsArgument);
154206c3fb27SDimitry Andric 
154306c3fb27SDimitry Andric   if (Size > 128)
154406c3fb27SDimitry Andric     return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty, "avx",
154506c3fb27SDimitry Andric                                 IsArgument);
154606c3fb27SDimitry Andric 
154706c3fb27SDimitry Andric   return false;
154806c3fb27SDimitry Andric }
154906c3fb27SDimitry Andric 
155006c3fb27SDimitry Andric void X86_64TargetCodeGenInfo::checkFunctionCallABI(
155106c3fb27SDimitry Andric     CodeGenModule &CGM, SourceLocation CallLoc, const FunctionDecl *Caller,
155206c3fb27SDimitry Andric     const FunctionDecl *Callee, const CallArgList &Args) const {
155306c3fb27SDimitry Andric   llvm::StringMap<bool> CallerMap;
155406c3fb27SDimitry Andric   llvm::StringMap<bool> CalleeMap;
155506c3fb27SDimitry Andric   unsigned ArgIndex = 0;
155606c3fb27SDimitry Andric 
155706c3fb27SDimitry Andric   // We need to loop through the actual call arguments rather than the
155806c3fb27SDimitry Andric   // function's parameters, in case this variadic.
155906c3fb27SDimitry Andric   for (const CallArg &Arg : Args) {
156006c3fb27SDimitry Andric     // The "avx" feature changes how vectors >128 in size are passed. "avx512f"
156106c3fb27SDimitry Andric     // additionally changes how vectors >256 in size are passed. Like GCC, we
156206c3fb27SDimitry Andric     // warn when a function is called with an argument where this will change.
156306c3fb27SDimitry Andric     // Unlike GCC, we also error when it is an obvious ABI mismatch, that is,
156406c3fb27SDimitry Andric     // the caller and callee features are mismatched.
156506c3fb27SDimitry Andric     // Unfortunately, we cannot do this diagnostic in SEMA, since the callee can
156606c3fb27SDimitry Andric     // change its ABI with attribute-target after this call.
156706c3fb27SDimitry Andric     if (Arg.getType()->isVectorType() &&
156806c3fb27SDimitry Andric         CGM.getContext().getTypeSize(Arg.getType()) > 128) {
156906c3fb27SDimitry Andric       initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
157006c3fb27SDimitry Andric       QualType Ty = Arg.getType();
157106c3fb27SDimitry Andric       // The CallArg seems to have desugared the type already, so for clearer
157206c3fb27SDimitry Andric       // diagnostics, replace it with the type in the FunctionDecl if possible.
157306c3fb27SDimitry Andric       if (ArgIndex < Callee->getNumParams())
157406c3fb27SDimitry Andric         Ty = Callee->getParamDecl(ArgIndex)->getType();
157506c3fb27SDimitry Andric 
157606c3fb27SDimitry Andric       if (checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap,
157706c3fb27SDimitry Andric                         CalleeMap, Ty, /*IsArgument*/ true))
157806c3fb27SDimitry Andric         return;
157906c3fb27SDimitry Andric     }
158006c3fb27SDimitry Andric     ++ArgIndex;
158106c3fb27SDimitry Andric   }
158206c3fb27SDimitry Andric 
158306c3fb27SDimitry Andric   // Check return always, as we don't have a good way of knowing in codegen
158406c3fb27SDimitry Andric   // whether this value is used, tail-called, etc.
158506c3fb27SDimitry Andric   if (Callee->getReturnType()->isVectorType() &&
158606c3fb27SDimitry Andric       CGM.getContext().getTypeSize(Callee->getReturnType()) > 128) {
158706c3fb27SDimitry Andric     initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
158806c3fb27SDimitry Andric     checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap,
158906c3fb27SDimitry Andric                   CalleeMap, Callee->getReturnType(),
159006c3fb27SDimitry Andric                   /*IsArgument*/ false);
159106c3fb27SDimitry Andric   }
159206c3fb27SDimitry Andric }
159306c3fb27SDimitry Andric 
159406c3fb27SDimitry Andric std::string TargetCodeGenInfo::qualifyWindowsLibrary(StringRef Lib) {
159506c3fb27SDimitry Andric   // If the argument does not end in .lib, automatically add the suffix.
159606c3fb27SDimitry Andric   // If the argument contains a space, enclose it in quotes.
159706c3fb27SDimitry Andric   // This matches the behavior of MSVC.
159806c3fb27SDimitry Andric   bool Quote = Lib.contains(' ');
159906c3fb27SDimitry Andric   std::string ArgStr = Quote ? "\"" : "";
160006c3fb27SDimitry Andric   ArgStr += Lib;
160106c3fb27SDimitry Andric   if (!Lib.ends_with_insensitive(".lib") && !Lib.ends_with_insensitive(".a"))
160206c3fb27SDimitry Andric     ArgStr += ".lib";
160306c3fb27SDimitry Andric   ArgStr += Quote ? "\"" : "";
160406c3fb27SDimitry Andric   return ArgStr;
160506c3fb27SDimitry Andric }
160606c3fb27SDimitry Andric 
160706c3fb27SDimitry Andric namespace {
160806c3fb27SDimitry Andric class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
160906c3fb27SDimitry Andric public:
161006c3fb27SDimitry Andric   WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
161106c3fb27SDimitry Andric         bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
161206c3fb27SDimitry Andric         unsigned NumRegisterParameters)
161306c3fb27SDimitry Andric     : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
161406c3fb27SDimitry Andric         Win32StructABI, NumRegisterParameters, false) {}
161506c3fb27SDimitry Andric 
161606c3fb27SDimitry Andric   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
161706c3fb27SDimitry Andric                            CodeGen::CodeGenModule &CGM) const override;
161806c3fb27SDimitry Andric 
161906c3fb27SDimitry Andric   void getDependentLibraryOption(llvm::StringRef Lib,
162006c3fb27SDimitry Andric                                  llvm::SmallString<24> &Opt) const override {
162106c3fb27SDimitry Andric     Opt = "/DEFAULTLIB:";
162206c3fb27SDimitry Andric     Opt += qualifyWindowsLibrary(Lib);
162306c3fb27SDimitry Andric   }
162406c3fb27SDimitry Andric 
162506c3fb27SDimitry Andric   void getDetectMismatchOption(llvm::StringRef Name,
162606c3fb27SDimitry Andric                                llvm::StringRef Value,
162706c3fb27SDimitry Andric                                llvm::SmallString<32> &Opt) const override {
162806c3fb27SDimitry Andric     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
162906c3fb27SDimitry Andric   }
163006c3fb27SDimitry Andric };
163106c3fb27SDimitry Andric } // namespace
163206c3fb27SDimitry Andric 
163306c3fb27SDimitry Andric void WinX86_32TargetCodeGenInfo::setTargetAttributes(
163406c3fb27SDimitry Andric     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
163506c3fb27SDimitry Andric   X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
163606c3fb27SDimitry Andric   if (GV->isDeclaration())
163706c3fb27SDimitry Andric     return;
163806c3fb27SDimitry Andric   addStackProbeTargetAttributes(D, GV, CGM);
163906c3fb27SDimitry Andric }
164006c3fb27SDimitry Andric 
164106c3fb27SDimitry Andric namespace {
164206c3fb27SDimitry Andric class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
164306c3fb27SDimitry Andric public:
164406c3fb27SDimitry Andric   WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
164506c3fb27SDimitry Andric                              X86AVXABILevel AVXLevel)
164606c3fb27SDimitry Andric       : TargetCodeGenInfo(std::make_unique<WinX86_64ABIInfo>(CGT, AVXLevel)) {
164706c3fb27SDimitry Andric     SwiftInfo =
164806c3fb27SDimitry Andric         std::make_unique<SwiftABIInfo>(CGT, /*SwiftErrorInRegister=*/true);
164906c3fb27SDimitry Andric   }
165006c3fb27SDimitry Andric 
165106c3fb27SDimitry Andric   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
165206c3fb27SDimitry Andric                            CodeGen::CodeGenModule &CGM) const override;
165306c3fb27SDimitry Andric 
165406c3fb27SDimitry Andric   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
165506c3fb27SDimitry Andric     return 7;
165606c3fb27SDimitry Andric   }
165706c3fb27SDimitry Andric 
165806c3fb27SDimitry Andric   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
165906c3fb27SDimitry Andric                                llvm::Value *Address) const override {
166006c3fb27SDimitry Andric     llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
166106c3fb27SDimitry Andric 
166206c3fb27SDimitry Andric     // 0-15 are the 16 integer registers.
166306c3fb27SDimitry Andric     // 16 is %rip.
166406c3fb27SDimitry Andric     AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
166506c3fb27SDimitry Andric     return false;
166606c3fb27SDimitry Andric   }
166706c3fb27SDimitry Andric 
166806c3fb27SDimitry Andric   void getDependentLibraryOption(llvm::StringRef Lib,
166906c3fb27SDimitry Andric                                  llvm::SmallString<24> &Opt) const override {
167006c3fb27SDimitry Andric     Opt = "/DEFAULTLIB:";
167106c3fb27SDimitry Andric     Opt += qualifyWindowsLibrary(Lib);
167206c3fb27SDimitry Andric   }
167306c3fb27SDimitry Andric 
167406c3fb27SDimitry Andric   void getDetectMismatchOption(llvm::StringRef Name,
167506c3fb27SDimitry Andric                                llvm::StringRef Value,
167606c3fb27SDimitry Andric                                llvm::SmallString<32> &Opt) const override {
167706c3fb27SDimitry Andric     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
167806c3fb27SDimitry Andric   }
167906c3fb27SDimitry Andric };
168006c3fb27SDimitry Andric } // namespace
168106c3fb27SDimitry Andric 
168206c3fb27SDimitry Andric void WinX86_64TargetCodeGenInfo::setTargetAttributes(
168306c3fb27SDimitry Andric     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
168406c3fb27SDimitry Andric   TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
168506c3fb27SDimitry Andric   if (GV->isDeclaration())
168606c3fb27SDimitry Andric     return;
168706c3fb27SDimitry Andric   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
168806c3fb27SDimitry Andric     if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
168906c3fb27SDimitry Andric       llvm::Function *Fn = cast<llvm::Function>(GV);
169006c3fb27SDimitry Andric       Fn->addFnAttr("stackrealign");
169106c3fb27SDimitry Andric     }
169206c3fb27SDimitry Andric 
169306c3fb27SDimitry Andric     addX86InterruptAttrs(FD, GV, CGM);
169406c3fb27SDimitry Andric   }
169506c3fb27SDimitry Andric 
169606c3fb27SDimitry Andric   addStackProbeTargetAttributes(D, GV, CGM);
169706c3fb27SDimitry Andric }
169806c3fb27SDimitry Andric 
169906c3fb27SDimitry Andric void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
170006c3fb27SDimitry Andric                               Class &Hi) const {
170106c3fb27SDimitry Andric   // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
170206c3fb27SDimitry Andric   //
170306c3fb27SDimitry Andric   // (a) If one of the classes is Memory, the whole argument is passed in
170406c3fb27SDimitry Andric   //     memory.
170506c3fb27SDimitry Andric   //
170606c3fb27SDimitry Andric   // (b) If X87UP is not preceded by X87, the whole argument is passed in
170706c3fb27SDimitry Andric   //     memory.
170806c3fb27SDimitry Andric   //
170906c3fb27SDimitry Andric   // (c) If the size of the aggregate exceeds two eightbytes and the first
171006c3fb27SDimitry Andric   //     eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
171106c3fb27SDimitry Andric   //     argument is passed in memory. NOTE: This is necessary to keep the
171206c3fb27SDimitry Andric   //     ABI working for processors that don't support the __m256 type.
171306c3fb27SDimitry Andric   //
171406c3fb27SDimitry Andric   // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
171506c3fb27SDimitry Andric   //
171606c3fb27SDimitry Andric   // Some of these are enforced by the merging logic.  Others can arise
171706c3fb27SDimitry Andric   // only with unions; for example:
171806c3fb27SDimitry Andric   //   union { _Complex double; unsigned; }
171906c3fb27SDimitry Andric   //
172006c3fb27SDimitry Andric   // Note that clauses (b) and (c) were added in 0.98.
172106c3fb27SDimitry Andric   //
172206c3fb27SDimitry Andric   if (Hi == Memory)
172306c3fb27SDimitry Andric     Lo = Memory;
172406c3fb27SDimitry Andric   if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
172506c3fb27SDimitry Andric     Lo = Memory;
172606c3fb27SDimitry Andric   if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
172706c3fb27SDimitry Andric     Lo = Memory;
172806c3fb27SDimitry Andric   if (Hi == SSEUp && Lo != SSE)
172906c3fb27SDimitry Andric     Hi = SSE;
173006c3fb27SDimitry Andric }
173106c3fb27SDimitry Andric 
173206c3fb27SDimitry Andric X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
173306c3fb27SDimitry Andric   // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
173406c3fb27SDimitry Andric   // classified recursively so that always two fields are
173506c3fb27SDimitry Andric   // considered. The resulting class is calculated according to
173606c3fb27SDimitry Andric   // the classes of the fields in the eightbyte:
173706c3fb27SDimitry Andric   //
173806c3fb27SDimitry Andric   // (a) If both classes are equal, this is the resulting class.
173906c3fb27SDimitry Andric   //
174006c3fb27SDimitry Andric   // (b) If one of the classes is NO_CLASS, the resulting class is
174106c3fb27SDimitry Andric   // the other class.
174206c3fb27SDimitry Andric   //
174306c3fb27SDimitry Andric   // (c) If one of the classes is MEMORY, the result is the MEMORY
174406c3fb27SDimitry Andric   // class.
174506c3fb27SDimitry Andric   //
174606c3fb27SDimitry Andric   // (d) If one of the classes is INTEGER, the result is the
174706c3fb27SDimitry Andric   // INTEGER.
174806c3fb27SDimitry Andric   //
174906c3fb27SDimitry Andric   // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
175006c3fb27SDimitry Andric   // MEMORY is used as class.
175106c3fb27SDimitry Andric   //
175206c3fb27SDimitry Andric   // (f) Otherwise class SSE is used.
175306c3fb27SDimitry Andric 
175406c3fb27SDimitry Andric   // Accum should never be memory (we should have returned) or
175506c3fb27SDimitry Andric   // ComplexX87 (because this cannot be passed in a structure).
175606c3fb27SDimitry Andric   assert((Accum != Memory && Accum != ComplexX87) &&
175706c3fb27SDimitry Andric          "Invalid accumulated classification during merge.");
175806c3fb27SDimitry Andric   if (Accum == Field || Field == NoClass)
175906c3fb27SDimitry Andric     return Accum;
176006c3fb27SDimitry Andric   if (Field == Memory)
176106c3fb27SDimitry Andric     return Memory;
176206c3fb27SDimitry Andric   if (Accum == NoClass)
176306c3fb27SDimitry Andric     return Field;
176406c3fb27SDimitry Andric   if (Accum == Integer || Field == Integer)
176506c3fb27SDimitry Andric     return Integer;
176606c3fb27SDimitry Andric   if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
176706c3fb27SDimitry Andric       Accum == X87 || Accum == X87Up)
176806c3fb27SDimitry Andric     return Memory;
176906c3fb27SDimitry Andric   return SSE;
177006c3fb27SDimitry Andric }
177106c3fb27SDimitry Andric 
177206c3fb27SDimitry Andric void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase, Class &Lo,
177306c3fb27SDimitry Andric                              Class &Hi, bool isNamedArg, bool IsRegCall) const {
177406c3fb27SDimitry Andric   // FIXME: This code can be simplified by introducing a simple value class for
177506c3fb27SDimitry Andric   // Class pairs with appropriate constructor methods for the various
177606c3fb27SDimitry Andric   // situations.
177706c3fb27SDimitry Andric 
177806c3fb27SDimitry Andric   // FIXME: Some of the split computations are wrong; unaligned vectors
177906c3fb27SDimitry Andric   // shouldn't be passed in registers for example, so there is no chance they
178006c3fb27SDimitry Andric   // can straddle an eightbyte. Verify & simplify.
178106c3fb27SDimitry Andric 
178206c3fb27SDimitry Andric   Lo = Hi = NoClass;
178306c3fb27SDimitry Andric 
178406c3fb27SDimitry Andric   Class &Current = OffsetBase < 64 ? Lo : Hi;
178506c3fb27SDimitry Andric   Current = Memory;
178606c3fb27SDimitry Andric 
178706c3fb27SDimitry Andric   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
178806c3fb27SDimitry Andric     BuiltinType::Kind k = BT->getKind();
178906c3fb27SDimitry Andric 
179006c3fb27SDimitry Andric     if (k == BuiltinType::Void) {
179106c3fb27SDimitry Andric       Current = NoClass;
179206c3fb27SDimitry Andric     } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
179306c3fb27SDimitry Andric       Lo = Integer;
179406c3fb27SDimitry Andric       Hi = Integer;
179506c3fb27SDimitry Andric     } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
179606c3fb27SDimitry Andric       Current = Integer;
179706c3fb27SDimitry Andric     } else if (k == BuiltinType::Float || k == BuiltinType::Double ||
179806c3fb27SDimitry Andric                k == BuiltinType::Float16 || k == BuiltinType::BFloat16) {
179906c3fb27SDimitry Andric       Current = SSE;
1800*1db9f3b2SDimitry Andric     } else if (k == BuiltinType::Float128) {
1801*1db9f3b2SDimitry Andric       Lo = SSE;
1802*1db9f3b2SDimitry Andric       Hi = SSEUp;
180306c3fb27SDimitry Andric     } else if (k == BuiltinType::LongDouble) {
180406c3fb27SDimitry Andric       const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
180506c3fb27SDimitry Andric       if (LDF == &llvm::APFloat::IEEEquad()) {
180606c3fb27SDimitry Andric         Lo = SSE;
180706c3fb27SDimitry Andric         Hi = SSEUp;
180806c3fb27SDimitry Andric       } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
180906c3fb27SDimitry Andric         Lo = X87;
181006c3fb27SDimitry Andric         Hi = X87Up;
181106c3fb27SDimitry Andric       } else if (LDF == &llvm::APFloat::IEEEdouble()) {
181206c3fb27SDimitry Andric         Current = SSE;
181306c3fb27SDimitry Andric       } else
181406c3fb27SDimitry Andric         llvm_unreachable("unexpected long double representation!");
181506c3fb27SDimitry Andric     }
181606c3fb27SDimitry Andric     // FIXME: _Decimal32 and _Decimal64 are SSE.
181706c3fb27SDimitry Andric     // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
181806c3fb27SDimitry Andric     return;
181906c3fb27SDimitry Andric   }
182006c3fb27SDimitry Andric 
182106c3fb27SDimitry Andric   if (const EnumType *ET = Ty->getAs<EnumType>()) {
182206c3fb27SDimitry Andric     // Classify the underlying integer type.
182306c3fb27SDimitry Andric     classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
182406c3fb27SDimitry Andric     return;
182506c3fb27SDimitry Andric   }
182606c3fb27SDimitry Andric 
182706c3fb27SDimitry Andric   if (Ty->hasPointerRepresentation()) {
182806c3fb27SDimitry Andric     Current = Integer;
182906c3fb27SDimitry Andric     return;
183006c3fb27SDimitry Andric   }
183106c3fb27SDimitry Andric 
183206c3fb27SDimitry Andric   if (Ty->isMemberPointerType()) {
183306c3fb27SDimitry Andric     if (Ty->isMemberFunctionPointerType()) {
183406c3fb27SDimitry Andric       if (Has64BitPointers) {
183506c3fb27SDimitry Andric         // If Has64BitPointers, this is an {i64, i64}, so classify both
183606c3fb27SDimitry Andric         // Lo and Hi now.
183706c3fb27SDimitry Andric         Lo = Hi = Integer;
183806c3fb27SDimitry Andric       } else {
183906c3fb27SDimitry Andric         // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
184006c3fb27SDimitry Andric         // straddles an eightbyte boundary, Hi should be classified as well.
184106c3fb27SDimitry Andric         uint64_t EB_FuncPtr = (OffsetBase) / 64;
184206c3fb27SDimitry Andric         uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
184306c3fb27SDimitry Andric         if (EB_FuncPtr != EB_ThisAdj) {
184406c3fb27SDimitry Andric           Lo = Hi = Integer;
184506c3fb27SDimitry Andric         } else {
184606c3fb27SDimitry Andric           Current = Integer;
184706c3fb27SDimitry Andric         }
184806c3fb27SDimitry Andric       }
184906c3fb27SDimitry Andric     } else {
185006c3fb27SDimitry Andric       Current = Integer;
185106c3fb27SDimitry Andric     }
185206c3fb27SDimitry Andric     return;
185306c3fb27SDimitry Andric   }
185406c3fb27SDimitry Andric 
185506c3fb27SDimitry Andric   if (const VectorType *VT = Ty->getAs<VectorType>()) {
185606c3fb27SDimitry Andric     uint64_t Size = getContext().getTypeSize(VT);
185706c3fb27SDimitry Andric     if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
185806c3fb27SDimitry Andric       // gcc passes the following as integer:
185906c3fb27SDimitry Andric       // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
186006c3fb27SDimitry Andric       // 2 bytes - <2 x char>, <1 x short>
186106c3fb27SDimitry Andric       // 1 byte  - <1 x char>
186206c3fb27SDimitry Andric       Current = Integer;
186306c3fb27SDimitry Andric 
186406c3fb27SDimitry Andric       // If this type crosses an eightbyte boundary, it should be
186506c3fb27SDimitry Andric       // split.
186606c3fb27SDimitry Andric       uint64_t EB_Lo = (OffsetBase) / 64;
186706c3fb27SDimitry Andric       uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
186806c3fb27SDimitry Andric       if (EB_Lo != EB_Hi)
186906c3fb27SDimitry Andric         Hi = Lo;
187006c3fb27SDimitry Andric     } else if (Size == 64) {
187106c3fb27SDimitry Andric       QualType ElementType = VT->getElementType();
187206c3fb27SDimitry Andric 
187306c3fb27SDimitry Andric       // gcc passes <1 x double> in memory. :(
187406c3fb27SDimitry Andric       if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
187506c3fb27SDimitry Andric         return;
187606c3fb27SDimitry Andric 
187706c3fb27SDimitry Andric       // gcc passes <1 x long long> as SSE but clang used to unconditionally
187806c3fb27SDimitry Andric       // pass them as integer.  For platforms where clang is the de facto
187906c3fb27SDimitry Andric       // platform compiler, we must continue to use integer.
188006c3fb27SDimitry Andric       if (!classifyIntegerMMXAsSSE() &&
188106c3fb27SDimitry Andric           (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
188206c3fb27SDimitry Andric            ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
188306c3fb27SDimitry Andric            ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
188406c3fb27SDimitry Andric            ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
188506c3fb27SDimitry Andric         Current = Integer;
188606c3fb27SDimitry Andric       else
188706c3fb27SDimitry Andric         Current = SSE;
188806c3fb27SDimitry Andric 
188906c3fb27SDimitry Andric       // If this type crosses an eightbyte boundary, it should be
189006c3fb27SDimitry Andric       // split.
189106c3fb27SDimitry Andric       if (OffsetBase && OffsetBase != 64)
189206c3fb27SDimitry Andric         Hi = Lo;
189306c3fb27SDimitry Andric     } else if (Size == 128 ||
189406c3fb27SDimitry Andric                (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
189506c3fb27SDimitry Andric       QualType ElementType = VT->getElementType();
189606c3fb27SDimitry Andric 
189706c3fb27SDimitry Andric       // gcc passes 256 and 512 bit <X x __int128> vectors in memory. :(
189806c3fb27SDimitry Andric       if (passInt128VectorsInMem() && Size != 128 &&
189906c3fb27SDimitry Andric           (ElementType->isSpecificBuiltinType(BuiltinType::Int128) ||
190006c3fb27SDimitry Andric            ElementType->isSpecificBuiltinType(BuiltinType::UInt128)))
190106c3fb27SDimitry Andric         return;
190206c3fb27SDimitry Andric 
190306c3fb27SDimitry Andric       // Arguments of 256-bits are split into four eightbyte chunks. The
190406c3fb27SDimitry Andric       // least significant one belongs to class SSE and all the others to class
190506c3fb27SDimitry Andric       // SSEUP. The original Lo and Hi design considers that types can't be
190606c3fb27SDimitry Andric       // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
190706c3fb27SDimitry Andric       // This design isn't correct for 256-bits, but since there're no cases
190806c3fb27SDimitry Andric       // where the upper parts would need to be inspected, avoid adding
190906c3fb27SDimitry Andric       // complexity and just consider Hi to match the 64-256 part.
191006c3fb27SDimitry Andric       //
191106c3fb27SDimitry Andric       // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
191206c3fb27SDimitry Andric       // registers if they are "named", i.e. not part of the "..." of a
191306c3fb27SDimitry Andric       // variadic function.
191406c3fb27SDimitry Andric       //
191506c3fb27SDimitry Andric       // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
191606c3fb27SDimitry Andric       // split into eight eightbyte chunks, one SSE and seven SSEUP.
191706c3fb27SDimitry Andric       Lo = SSE;
191806c3fb27SDimitry Andric       Hi = SSEUp;
191906c3fb27SDimitry Andric     }
192006c3fb27SDimitry Andric     return;
192106c3fb27SDimitry Andric   }
192206c3fb27SDimitry Andric 
192306c3fb27SDimitry Andric   if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
192406c3fb27SDimitry Andric     QualType ET = getContext().getCanonicalType(CT->getElementType());
192506c3fb27SDimitry Andric 
192606c3fb27SDimitry Andric     uint64_t Size = getContext().getTypeSize(Ty);
192706c3fb27SDimitry Andric     if (ET->isIntegralOrEnumerationType()) {
192806c3fb27SDimitry Andric       if (Size <= 64)
192906c3fb27SDimitry Andric         Current = Integer;
193006c3fb27SDimitry Andric       else if (Size <= 128)
193106c3fb27SDimitry Andric         Lo = Hi = Integer;
193206c3fb27SDimitry Andric     } else if (ET->isFloat16Type() || ET == getContext().FloatTy ||
193306c3fb27SDimitry Andric                ET->isBFloat16Type()) {
193406c3fb27SDimitry Andric       Current = SSE;
193506c3fb27SDimitry Andric     } else if (ET == getContext().DoubleTy) {
193606c3fb27SDimitry Andric       Lo = Hi = SSE;
193706c3fb27SDimitry Andric     } else if (ET == getContext().LongDoubleTy) {
193806c3fb27SDimitry Andric       const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
193906c3fb27SDimitry Andric       if (LDF == &llvm::APFloat::IEEEquad())
194006c3fb27SDimitry Andric         Current = Memory;
194106c3fb27SDimitry Andric       else if (LDF == &llvm::APFloat::x87DoubleExtended())
194206c3fb27SDimitry Andric         Current = ComplexX87;
194306c3fb27SDimitry Andric       else if (LDF == &llvm::APFloat::IEEEdouble())
194406c3fb27SDimitry Andric         Lo = Hi = SSE;
194506c3fb27SDimitry Andric       else
194606c3fb27SDimitry Andric         llvm_unreachable("unexpected long double representation!");
194706c3fb27SDimitry Andric     }
194806c3fb27SDimitry Andric 
194906c3fb27SDimitry Andric     // If this complex type crosses an eightbyte boundary then it
195006c3fb27SDimitry Andric     // should be split.
195106c3fb27SDimitry Andric     uint64_t EB_Real = (OffsetBase) / 64;
195206c3fb27SDimitry Andric     uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
195306c3fb27SDimitry Andric     if (Hi == NoClass && EB_Real != EB_Imag)
195406c3fb27SDimitry Andric       Hi = Lo;
195506c3fb27SDimitry Andric 
195606c3fb27SDimitry Andric     return;
195706c3fb27SDimitry Andric   }
195806c3fb27SDimitry Andric 
195906c3fb27SDimitry Andric   if (const auto *EITy = Ty->getAs<BitIntType>()) {
196006c3fb27SDimitry Andric     if (EITy->getNumBits() <= 64)
196106c3fb27SDimitry Andric       Current = Integer;
196206c3fb27SDimitry Andric     else if (EITy->getNumBits() <= 128)
196306c3fb27SDimitry Andric       Lo = Hi = Integer;
196406c3fb27SDimitry Andric     // Larger values need to get passed in memory.
196506c3fb27SDimitry Andric     return;
196606c3fb27SDimitry Andric   }
196706c3fb27SDimitry Andric 
196806c3fb27SDimitry Andric   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
196906c3fb27SDimitry Andric     // Arrays are treated like structures.
197006c3fb27SDimitry Andric 
197106c3fb27SDimitry Andric     uint64_t Size = getContext().getTypeSize(Ty);
197206c3fb27SDimitry Andric 
197306c3fb27SDimitry Andric     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
197406c3fb27SDimitry Andric     // than eight eightbytes, ..., it has class MEMORY.
197506c3fb27SDimitry Andric     // regcall ABI doesn't have limitation to an object. The only limitation
197606c3fb27SDimitry Andric     // is the free registers, which will be checked in computeInfo.
197706c3fb27SDimitry Andric     if (!IsRegCall && Size > 512)
197806c3fb27SDimitry Andric       return;
197906c3fb27SDimitry Andric 
198006c3fb27SDimitry Andric     // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
198106c3fb27SDimitry Andric     // fields, it has class MEMORY.
198206c3fb27SDimitry Andric     //
198306c3fb27SDimitry Andric     // Only need to check alignment of array base.
198406c3fb27SDimitry Andric     if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
198506c3fb27SDimitry Andric       return;
198606c3fb27SDimitry Andric 
198706c3fb27SDimitry Andric     // Otherwise implement simplified merge. We could be smarter about
198806c3fb27SDimitry Andric     // this, but it isn't worth it and would be harder to verify.
198906c3fb27SDimitry Andric     Current = NoClass;
199006c3fb27SDimitry Andric     uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
199106c3fb27SDimitry Andric     uint64_t ArraySize = AT->getSize().getZExtValue();
199206c3fb27SDimitry Andric 
199306c3fb27SDimitry Andric     // The only case a 256-bit wide vector could be used is when the array
199406c3fb27SDimitry Andric     // contains a single 256-bit element. Since Lo and Hi logic isn't extended
199506c3fb27SDimitry Andric     // to work for sizes wider than 128, early check and fallback to memory.
199606c3fb27SDimitry Andric     //
199706c3fb27SDimitry Andric     if (Size > 128 &&
199806c3fb27SDimitry Andric         (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
199906c3fb27SDimitry Andric       return;
200006c3fb27SDimitry Andric 
200106c3fb27SDimitry Andric     for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
200206c3fb27SDimitry Andric       Class FieldLo, FieldHi;
200306c3fb27SDimitry Andric       classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
200406c3fb27SDimitry Andric       Lo = merge(Lo, FieldLo);
200506c3fb27SDimitry Andric       Hi = merge(Hi, FieldHi);
200606c3fb27SDimitry Andric       if (Lo == Memory || Hi == Memory)
200706c3fb27SDimitry Andric         break;
200806c3fb27SDimitry Andric     }
200906c3fb27SDimitry Andric 
201006c3fb27SDimitry Andric     postMerge(Size, Lo, Hi);
201106c3fb27SDimitry Andric     assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
201206c3fb27SDimitry Andric     return;
201306c3fb27SDimitry Andric   }
201406c3fb27SDimitry Andric 
201506c3fb27SDimitry Andric   if (const RecordType *RT = Ty->getAs<RecordType>()) {
201606c3fb27SDimitry Andric     uint64_t Size = getContext().getTypeSize(Ty);
201706c3fb27SDimitry Andric 
201806c3fb27SDimitry Andric     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
201906c3fb27SDimitry Andric     // than eight eightbytes, ..., it has class MEMORY.
202006c3fb27SDimitry Andric     if (Size > 512)
202106c3fb27SDimitry Andric       return;
202206c3fb27SDimitry Andric 
202306c3fb27SDimitry Andric     // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
202406c3fb27SDimitry Andric     // copy constructor or a non-trivial destructor, it is passed by invisible
202506c3fb27SDimitry Andric     // reference.
202606c3fb27SDimitry Andric     if (getRecordArgABI(RT, getCXXABI()))
202706c3fb27SDimitry Andric       return;
202806c3fb27SDimitry Andric 
202906c3fb27SDimitry Andric     const RecordDecl *RD = RT->getDecl();
203006c3fb27SDimitry Andric 
203106c3fb27SDimitry Andric     // Assume variable sized types are passed in memory.
203206c3fb27SDimitry Andric     if (RD->hasFlexibleArrayMember())
203306c3fb27SDimitry Andric       return;
203406c3fb27SDimitry Andric 
203506c3fb27SDimitry Andric     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
203606c3fb27SDimitry Andric 
203706c3fb27SDimitry Andric     // Reset Lo class, this will be recomputed.
203806c3fb27SDimitry Andric     Current = NoClass;
203906c3fb27SDimitry Andric 
204006c3fb27SDimitry Andric     // If this is a C++ record, classify the bases first.
204106c3fb27SDimitry Andric     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
204206c3fb27SDimitry Andric       for (const auto &I : CXXRD->bases()) {
204306c3fb27SDimitry Andric         assert(!I.isVirtual() && !I.getType()->isDependentType() &&
204406c3fb27SDimitry Andric                "Unexpected base class!");
204506c3fb27SDimitry Andric         const auto *Base =
204606c3fb27SDimitry Andric             cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
204706c3fb27SDimitry Andric 
204806c3fb27SDimitry Andric         // Classify this field.
204906c3fb27SDimitry Andric         //
205006c3fb27SDimitry Andric         // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
205106c3fb27SDimitry Andric         // single eightbyte, each is classified separately. Each eightbyte gets
205206c3fb27SDimitry Andric         // initialized to class NO_CLASS.
205306c3fb27SDimitry Andric         Class FieldLo, FieldHi;
205406c3fb27SDimitry Andric         uint64_t Offset =
205506c3fb27SDimitry Andric           OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
205606c3fb27SDimitry Andric         classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
205706c3fb27SDimitry Andric         Lo = merge(Lo, FieldLo);
205806c3fb27SDimitry Andric         Hi = merge(Hi, FieldHi);
205906c3fb27SDimitry Andric         if (Lo == Memory || Hi == Memory) {
206006c3fb27SDimitry Andric           postMerge(Size, Lo, Hi);
206106c3fb27SDimitry Andric           return;
206206c3fb27SDimitry Andric         }
206306c3fb27SDimitry Andric       }
206406c3fb27SDimitry Andric     }
206506c3fb27SDimitry Andric 
206606c3fb27SDimitry Andric     // Classify the fields one at a time, merging the results.
206706c3fb27SDimitry Andric     unsigned idx = 0;
206806c3fb27SDimitry Andric     bool UseClang11Compat = getContext().getLangOpts().getClangABICompat() <=
206906c3fb27SDimitry Andric                                 LangOptions::ClangABI::Ver11 ||
207006c3fb27SDimitry Andric                             getContext().getTargetInfo().getTriple().isPS();
207106c3fb27SDimitry Andric     bool IsUnion = RT->isUnionType() && !UseClang11Compat;
207206c3fb27SDimitry Andric 
207306c3fb27SDimitry Andric     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
207406c3fb27SDimitry Andric            i != e; ++i, ++idx) {
207506c3fb27SDimitry Andric       uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
207606c3fb27SDimitry Andric       bool BitField = i->isBitField();
207706c3fb27SDimitry Andric 
207806c3fb27SDimitry Andric       // Ignore padding bit-fields.
207906c3fb27SDimitry Andric       if (BitField && i->isUnnamedBitfield())
208006c3fb27SDimitry Andric         continue;
208106c3fb27SDimitry Andric 
208206c3fb27SDimitry Andric       // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
208306c3fb27SDimitry Andric       // eight eightbytes, or it contains unaligned fields, it has class MEMORY.
208406c3fb27SDimitry Andric       //
208506c3fb27SDimitry Andric       // The only case a 256-bit or a 512-bit wide vector could be used is when
208606c3fb27SDimitry Andric       // the struct contains a single 256-bit or 512-bit element. Early check
208706c3fb27SDimitry Andric       // and fallback to memory.
208806c3fb27SDimitry Andric       //
208906c3fb27SDimitry Andric       // FIXME: Extended the Lo and Hi logic properly to work for size wider
209006c3fb27SDimitry Andric       // than 128.
209106c3fb27SDimitry Andric       if (Size > 128 &&
209206c3fb27SDimitry Andric           ((!IsUnion && Size != getContext().getTypeSize(i->getType())) ||
209306c3fb27SDimitry Andric            Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
209406c3fb27SDimitry Andric         Lo = Memory;
209506c3fb27SDimitry Andric         postMerge(Size, Lo, Hi);
209606c3fb27SDimitry Andric         return;
209706c3fb27SDimitry Andric       }
209806c3fb27SDimitry Andric       // Note, skip this test for bit-fields, see below.
209906c3fb27SDimitry Andric       if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
210006c3fb27SDimitry Andric         Lo = Memory;
210106c3fb27SDimitry Andric         postMerge(Size, Lo, Hi);
210206c3fb27SDimitry Andric         return;
210306c3fb27SDimitry Andric       }
210406c3fb27SDimitry Andric 
210506c3fb27SDimitry Andric       // Classify this field.
210606c3fb27SDimitry Andric       //
210706c3fb27SDimitry Andric       // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
210806c3fb27SDimitry Andric       // exceeds a single eightbyte, each is classified
210906c3fb27SDimitry Andric       // separately. Each eightbyte gets initialized to class
211006c3fb27SDimitry Andric       // NO_CLASS.
211106c3fb27SDimitry Andric       Class FieldLo, FieldHi;
211206c3fb27SDimitry Andric 
211306c3fb27SDimitry Andric       // Bit-fields require special handling, they do not force the
211406c3fb27SDimitry Andric       // structure to be passed in memory even if unaligned, and
211506c3fb27SDimitry Andric       // therefore they can straddle an eightbyte.
211606c3fb27SDimitry Andric       if (BitField) {
211706c3fb27SDimitry Andric         assert(!i->isUnnamedBitfield());
211806c3fb27SDimitry Andric         uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
211906c3fb27SDimitry Andric         uint64_t Size = i->getBitWidthValue(getContext());
212006c3fb27SDimitry Andric 
212106c3fb27SDimitry Andric         uint64_t EB_Lo = Offset / 64;
212206c3fb27SDimitry Andric         uint64_t EB_Hi = (Offset + Size - 1) / 64;
212306c3fb27SDimitry Andric 
212406c3fb27SDimitry Andric         if (EB_Lo) {
212506c3fb27SDimitry Andric           assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
212606c3fb27SDimitry Andric           FieldLo = NoClass;
212706c3fb27SDimitry Andric           FieldHi = Integer;
212806c3fb27SDimitry Andric         } else {
212906c3fb27SDimitry Andric           FieldLo = Integer;
213006c3fb27SDimitry Andric           FieldHi = EB_Hi ? Integer : NoClass;
213106c3fb27SDimitry Andric         }
213206c3fb27SDimitry Andric       } else
213306c3fb27SDimitry Andric         classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
213406c3fb27SDimitry Andric       Lo = merge(Lo, FieldLo);
213506c3fb27SDimitry Andric       Hi = merge(Hi, FieldHi);
213606c3fb27SDimitry Andric       if (Lo == Memory || Hi == Memory)
213706c3fb27SDimitry Andric         break;
213806c3fb27SDimitry Andric     }
213906c3fb27SDimitry Andric 
214006c3fb27SDimitry Andric     postMerge(Size, Lo, Hi);
214106c3fb27SDimitry Andric   }
214206c3fb27SDimitry Andric }
214306c3fb27SDimitry Andric 
214406c3fb27SDimitry Andric ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
214506c3fb27SDimitry Andric   // If this is a scalar LLVM value then assume LLVM will pass it in the right
214606c3fb27SDimitry Andric   // place naturally.
214706c3fb27SDimitry Andric   if (!isAggregateTypeForABI(Ty)) {
214806c3fb27SDimitry Andric     // Treat an enum type as its underlying type.
214906c3fb27SDimitry Andric     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
215006c3fb27SDimitry Andric       Ty = EnumTy->getDecl()->getIntegerType();
215106c3fb27SDimitry Andric 
215206c3fb27SDimitry Andric     if (Ty->isBitIntType())
215306c3fb27SDimitry Andric       return getNaturalAlignIndirect(Ty);
215406c3fb27SDimitry Andric 
215506c3fb27SDimitry Andric     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
215606c3fb27SDimitry Andric                                               : ABIArgInfo::getDirect());
215706c3fb27SDimitry Andric   }
215806c3fb27SDimitry Andric 
215906c3fb27SDimitry Andric   return getNaturalAlignIndirect(Ty);
216006c3fb27SDimitry Andric }
216106c3fb27SDimitry Andric 
216206c3fb27SDimitry Andric bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
216306c3fb27SDimitry Andric   if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
216406c3fb27SDimitry Andric     uint64_t Size = getContext().getTypeSize(VecTy);
216506c3fb27SDimitry Andric     unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
216606c3fb27SDimitry Andric     if (Size <= 64 || Size > LargestVector)
216706c3fb27SDimitry Andric       return true;
216806c3fb27SDimitry Andric     QualType EltTy = VecTy->getElementType();
216906c3fb27SDimitry Andric     if (passInt128VectorsInMem() &&
217006c3fb27SDimitry Andric         (EltTy->isSpecificBuiltinType(BuiltinType::Int128) ||
217106c3fb27SDimitry Andric          EltTy->isSpecificBuiltinType(BuiltinType::UInt128)))
217206c3fb27SDimitry Andric       return true;
217306c3fb27SDimitry Andric   }
217406c3fb27SDimitry Andric 
217506c3fb27SDimitry Andric   return false;
217606c3fb27SDimitry Andric }
217706c3fb27SDimitry Andric 
217806c3fb27SDimitry Andric ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
217906c3fb27SDimitry Andric                                             unsigned freeIntRegs) const {
218006c3fb27SDimitry Andric   // If this is a scalar LLVM value then assume LLVM will pass it in the right
218106c3fb27SDimitry Andric   // place naturally.
218206c3fb27SDimitry Andric   //
218306c3fb27SDimitry Andric   // This assumption is optimistic, as there could be free registers available
218406c3fb27SDimitry Andric   // when we need to pass this argument in memory, and LLVM could try to pass
218506c3fb27SDimitry Andric   // the argument in the free register. This does not seem to happen currently,
218606c3fb27SDimitry Andric   // but this code would be much safer if we could mark the argument with
218706c3fb27SDimitry Andric   // 'onstack'. See PR12193.
218806c3fb27SDimitry Andric   if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty) &&
218906c3fb27SDimitry Andric       !Ty->isBitIntType()) {
219006c3fb27SDimitry Andric     // Treat an enum type as its underlying type.
219106c3fb27SDimitry Andric     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
219206c3fb27SDimitry Andric       Ty = EnumTy->getDecl()->getIntegerType();
219306c3fb27SDimitry Andric 
219406c3fb27SDimitry Andric     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
219506c3fb27SDimitry Andric                                               : ABIArgInfo::getDirect());
219606c3fb27SDimitry Andric   }
219706c3fb27SDimitry Andric 
219806c3fb27SDimitry Andric   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
219906c3fb27SDimitry Andric     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
220006c3fb27SDimitry Andric 
220106c3fb27SDimitry Andric   // Compute the byval alignment. We specify the alignment of the byval in all
220206c3fb27SDimitry Andric   // cases so that the mid-level optimizer knows the alignment of the byval.
220306c3fb27SDimitry Andric   unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
220406c3fb27SDimitry Andric 
220506c3fb27SDimitry Andric   // Attempt to avoid passing indirect results using byval when possible. This
220606c3fb27SDimitry Andric   // is important for good codegen.
220706c3fb27SDimitry Andric   //
220806c3fb27SDimitry Andric   // We do this by coercing the value into a scalar type which the backend can
220906c3fb27SDimitry Andric   // handle naturally (i.e., without using byval).
221006c3fb27SDimitry Andric   //
221106c3fb27SDimitry Andric   // For simplicity, we currently only do this when we have exhausted all of the
221206c3fb27SDimitry Andric   // free integer registers. Doing this when there are free integer registers
221306c3fb27SDimitry Andric   // would require more care, as we would have to ensure that the coerced value
221406c3fb27SDimitry Andric   // did not claim the unused register. That would require either reording the
221506c3fb27SDimitry Andric   // arguments to the function (so that any subsequent inreg values came first),
221606c3fb27SDimitry Andric   // or only doing this optimization when there were no following arguments that
221706c3fb27SDimitry Andric   // might be inreg.
221806c3fb27SDimitry Andric   //
221906c3fb27SDimitry Andric   // We currently expect it to be rare (particularly in well written code) for
222006c3fb27SDimitry Andric   // arguments to be passed on the stack when there are still free integer
222106c3fb27SDimitry Andric   // registers available (this would typically imply large structs being passed
222206c3fb27SDimitry Andric   // by value), so this seems like a fair tradeoff for now.
222306c3fb27SDimitry Andric   //
222406c3fb27SDimitry Andric   // We can revisit this if the backend grows support for 'onstack' parameter
222506c3fb27SDimitry Andric   // attributes. See PR12193.
222606c3fb27SDimitry Andric   if (freeIntRegs == 0) {
222706c3fb27SDimitry Andric     uint64_t Size = getContext().getTypeSize(Ty);
222806c3fb27SDimitry Andric 
222906c3fb27SDimitry Andric     // If this type fits in an eightbyte, coerce it into the matching integral
223006c3fb27SDimitry Andric     // type, which will end up on the stack (with alignment 8).
223106c3fb27SDimitry Andric     if (Align == 8 && Size <= 64)
223206c3fb27SDimitry Andric       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
223306c3fb27SDimitry Andric                                                           Size));
223406c3fb27SDimitry Andric   }
223506c3fb27SDimitry Andric 
223606c3fb27SDimitry Andric   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
223706c3fb27SDimitry Andric }
223806c3fb27SDimitry Andric 
223906c3fb27SDimitry Andric /// The ABI specifies that a value should be passed in a full vector XMM/YMM
224006c3fb27SDimitry Andric /// register. Pick an LLVM IR type that will be passed as a vector register.
224106c3fb27SDimitry Andric llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
224206c3fb27SDimitry Andric   // Wrapper structs/arrays that only contain vectors are passed just like
224306c3fb27SDimitry Andric   // vectors; strip them off if present.
224406c3fb27SDimitry Andric   if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
224506c3fb27SDimitry Andric     Ty = QualType(InnerTy, 0);
224606c3fb27SDimitry Andric 
224706c3fb27SDimitry Andric   llvm::Type *IRType = CGT.ConvertType(Ty);
224806c3fb27SDimitry Andric   if (isa<llvm::VectorType>(IRType)) {
224906c3fb27SDimitry Andric     // Don't pass vXi128 vectors in their native type, the backend can't
225006c3fb27SDimitry Andric     // legalize them.
225106c3fb27SDimitry Andric     if (passInt128VectorsInMem() &&
225206c3fb27SDimitry Andric         cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy(128)) {
225306c3fb27SDimitry Andric       // Use a vXi64 vector.
225406c3fb27SDimitry Andric       uint64_t Size = getContext().getTypeSize(Ty);
225506c3fb27SDimitry Andric       return llvm::FixedVectorType::get(llvm::Type::getInt64Ty(getVMContext()),
225606c3fb27SDimitry Andric                                         Size / 64);
225706c3fb27SDimitry Andric     }
225806c3fb27SDimitry Andric 
225906c3fb27SDimitry Andric     return IRType;
226006c3fb27SDimitry Andric   }
226106c3fb27SDimitry Andric 
226206c3fb27SDimitry Andric   if (IRType->getTypeID() == llvm::Type::FP128TyID)
226306c3fb27SDimitry Andric     return IRType;
226406c3fb27SDimitry Andric 
226506c3fb27SDimitry Andric   // We couldn't find the preferred IR vector type for 'Ty'.
226606c3fb27SDimitry Andric   uint64_t Size = getContext().getTypeSize(Ty);
226706c3fb27SDimitry Andric   assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
226806c3fb27SDimitry Andric 
226906c3fb27SDimitry Andric 
227006c3fb27SDimitry Andric   // Return a LLVM IR vector type based on the size of 'Ty'.
227106c3fb27SDimitry Andric   return llvm::FixedVectorType::get(llvm::Type::getDoubleTy(getVMContext()),
227206c3fb27SDimitry Andric                                     Size / 64);
227306c3fb27SDimitry Andric }
227406c3fb27SDimitry Andric 
227506c3fb27SDimitry Andric /// BitsContainNoUserData - Return true if the specified [start,end) bit range
227606c3fb27SDimitry Andric /// is known to either be off the end of the specified type or being in
227706c3fb27SDimitry Andric /// alignment padding.  The user type specified is known to be at most 128 bits
227806c3fb27SDimitry Andric /// in size, and have passed through X86_64ABIInfo::classify with a successful
227906c3fb27SDimitry Andric /// classification that put one of the two halves in the INTEGER class.
228006c3fb27SDimitry Andric ///
228106c3fb27SDimitry Andric /// It is conservatively correct to return false.
228206c3fb27SDimitry Andric static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
228306c3fb27SDimitry Andric                                   unsigned EndBit, ASTContext &Context) {
228406c3fb27SDimitry Andric   // If the bytes being queried are off the end of the type, there is no user
228506c3fb27SDimitry Andric   // data hiding here.  This handles analysis of builtins, vectors and other
228606c3fb27SDimitry Andric   // types that don't contain interesting padding.
228706c3fb27SDimitry Andric   unsigned TySize = (unsigned)Context.getTypeSize(Ty);
228806c3fb27SDimitry Andric   if (TySize <= StartBit)
228906c3fb27SDimitry Andric     return true;
229006c3fb27SDimitry Andric 
229106c3fb27SDimitry Andric   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
229206c3fb27SDimitry Andric     unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
229306c3fb27SDimitry Andric     unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
229406c3fb27SDimitry Andric 
229506c3fb27SDimitry Andric     // Check each element to see if the element overlaps with the queried range.
229606c3fb27SDimitry Andric     for (unsigned i = 0; i != NumElts; ++i) {
229706c3fb27SDimitry Andric       // If the element is after the span we care about, then we're done..
229806c3fb27SDimitry Andric       unsigned EltOffset = i*EltSize;
229906c3fb27SDimitry Andric       if (EltOffset >= EndBit) break;
230006c3fb27SDimitry Andric 
230106c3fb27SDimitry Andric       unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
230206c3fb27SDimitry Andric       if (!BitsContainNoUserData(AT->getElementType(), EltStart,
230306c3fb27SDimitry Andric                                  EndBit-EltOffset, Context))
230406c3fb27SDimitry Andric         return false;
230506c3fb27SDimitry Andric     }
230606c3fb27SDimitry Andric     // If it overlaps no elements, then it is safe to process as padding.
230706c3fb27SDimitry Andric     return true;
230806c3fb27SDimitry Andric   }
230906c3fb27SDimitry Andric 
231006c3fb27SDimitry Andric   if (const RecordType *RT = Ty->getAs<RecordType>()) {
231106c3fb27SDimitry Andric     const RecordDecl *RD = RT->getDecl();
231206c3fb27SDimitry Andric     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
231306c3fb27SDimitry Andric 
231406c3fb27SDimitry Andric     // If this is a C++ record, check the bases first.
231506c3fb27SDimitry Andric     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
231606c3fb27SDimitry Andric       for (const auto &I : CXXRD->bases()) {
231706c3fb27SDimitry Andric         assert(!I.isVirtual() && !I.getType()->isDependentType() &&
231806c3fb27SDimitry Andric                "Unexpected base class!");
231906c3fb27SDimitry Andric         const auto *Base =
232006c3fb27SDimitry Andric             cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
232106c3fb27SDimitry Andric 
232206c3fb27SDimitry Andric         // If the base is after the span we care about, ignore it.
232306c3fb27SDimitry Andric         unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
232406c3fb27SDimitry Andric         if (BaseOffset >= EndBit) continue;
232506c3fb27SDimitry Andric 
232606c3fb27SDimitry Andric         unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
232706c3fb27SDimitry Andric         if (!BitsContainNoUserData(I.getType(), BaseStart,
232806c3fb27SDimitry Andric                                    EndBit-BaseOffset, Context))
232906c3fb27SDimitry Andric           return false;
233006c3fb27SDimitry Andric       }
233106c3fb27SDimitry Andric     }
233206c3fb27SDimitry Andric 
233306c3fb27SDimitry Andric     // Verify that no field has data that overlaps the region of interest.  Yes
233406c3fb27SDimitry Andric     // this could be sped up a lot by being smarter about queried fields,
233506c3fb27SDimitry Andric     // however we're only looking at structs up to 16 bytes, so we don't care
233606c3fb27SDimitry Andric     // much.
233706c3fb27SDimitry Andric     unsigned idx = 0;
233806c3fb27SDimitry Andric     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
233906c3fb27SDimitry Andric          i != e; ++i, ++idx) {
234006c3fb27SDimitry Andric       unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
234106c3fb27SDimitry Andric 
234206c3fb27SDimitry Andric       // If we found a field after the region we care about, then we're done.
234306c3fb27SDimitry Andric       if (FieldOffset >= EndBit) break;
234406c3fb27SDimitry Andric 
234506c3fb27SDimitry Andric       unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
234606c3fb27SDimitry Andric       if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
234706c3fb27SDimitry Andric                                  Context))
234806c3fb27SDimitry Andric         return false;
234906c3fb27SDimitry Andric     }
235006c3fb27SDimitry Andric 
235106c3fb27SDimitry Andric     // If nothing in this record overlapped the area of interest, then we're
235206c3fb27SDimitry Andric     // clean.
235306c3fb27SDimitry Andric     return true;
235406c3fb27SDimitry Andric   }
235506c3fb27SDimitry Andric 
235606c3fb27SDimitry Andric   return false;
235706c3fb27SDimitry Andric }
235806c3fb27SDimitry Andric 
235906c3fb27SDimitry Andric /// getFPTypeAtOffset - Return a floating point type at the specified offset.
236006c3fb27SDimitry Andric static llvm::Type *getFPTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
236106c3fb27SDimitry Andric                                      const llvm::DataLayout &TD) {
236206c3fb27SDimitry Andric   if (IROffset == 0 && IRType->isFloatingPointTy())
236306c3fb27SDimitry Andric     return IRType;
236406c3fb27SDimitry Andric 
236506c3fb27SDimitry Andric   // If this is a struct, recurse into the field at the specified offset.
236606c3fb27SDimitry Andric   if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
236706c3fb27SDimitry Andric     if (!STy->getNumContainedTypes())
236806c3fb27SDimitry Andric       return nullptr;
236906c3fb27SDimitry Andric 
237006c3fb27SDimitry Andric     const llvm::StructLayout *SL = TD.getStructLayout(STy);
237106c3fb27SDimitry Andric     unsigned Elt = SL->getElementContainingOffset(IROffset);
237206c3fb27SDimitry Andric     IROffset -= SL->getElementOffset(Elt);
237306c3fb27SDimitry Andric     return getFPTypeAtOffset(STy->getElementType(Elt), IROffset, TD);
237406c3fb27SDimitry Andric   }
237506c3fb27SDimitry Andric 
237606c3fb27SDimitry Andric   // If this is an array, recurse into the field at the specified offset.
237706c3fb27SDimitry Andric   if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
237806c3fb27SDimitry Andric     llvm::Type *EltTy = ATy->getElementType();
237906c3fb27SDimitry Andric     unsigned EltSize = TD.getTypeAllocSize(EltTy);
238006c3fb27SDimitry Andric     IROffset -= IROffset / EltSize * EltSize;
238106c3fb27SDimitry Andric     return getFPTypeAtOffset(EltTy, IROffset, TD);
238206c3fb27SDimitry Andric   }
238306c3fb27SDimitry Andric 
238406c3fb27SDimitry Andric   return nullptr;
238506c3fb27SDimitry Andric }
238606c3fb27SDimitry Andric 
238706c3fb27SDimitry Andric /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
238806c3fb27SDimitry Andric /// low 8 bytes of an XMM register, corresponding to the SSE class.
238906c3fb27SDimitry Andric llvm::Type *X86_64ABIInfo::
239006c3fb27SDimitry Andric GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
239106c3fb27SDimitry Andric                    QualType SourceTy, unsigned SourceOffset) const {
239206c3fb27SDimitry Andric   const llvm::DataLayout &TD = getDataLayout();
239306c3fb27SDimitry Andric   unsigned SourceSize =
239406c3fb27SDimitry Andric       (unsigned)getContext().getTypeSize(SourceTy) / 8 - SourceOffset;
239506c3fb27SDimitry Andric   llvm::Type *T0 = getFPTypeAtOffset(IRType, IROffset, TD);
239606c3fb27SDimitry Andric   if (!T0 || T0->isDoubleTy())
239706c3fb27SDimitry Andric     return llvm::Type::getDoubleTy(getVMContext());
239806c3fb27SDimitry Andric 
239906c3fb27SDimitry Andric   // Get the adjacent FP type.
240006c3fb27SDimitry Andric   llvm::Type *T1 = nullptr;
240106c3fb27SDimitry Andric   unsigned T0Size = TD.getTypeAllocSize(T0);
240206c3fb27SDimitry Andric   if (SourceSize > T0Size)
240306c3fb27SDimitry Andric       T1 = getFPTypeAtOffset(IRType, IROffset + T0Size, TD);
240406c3fb27SDimitry Andric   if (T1 == nullptr) {
240506c3fb27SDimitry Andric     // Check if IRType is a half/bfloat + float. float type will be in IROffset+4 due
240606c3fb27SDimitry Andric     // to its alignment.
240706c3fb27SDimitry Andric     if (T0->is16bitFPTy() && SourceSize > 4)
240806c3fb27SDimitry Andric       T1 = getFPTypeAtOffset(IRType, IROffset + 4, TD);
240906c3fb27SDimitry Andric     // If we can't get a second FP type, return a simple half or float.
241006c3fb27SDimitry Andric     // avx512fp16-abi.c:pr51813_2 shows it works to return float for
241106c3fb27SDimitry Andric     // {float, i8} too.
241206c3fb27SDimitry Andric     if (T1 == nullptr)
241306c3fb27SDimitry Andric       return T0;
241406c3fb27SDimitry Andric   }
241506c3fb27SDimitry Andric 
241606c3fb27SDimitry Andric   if (T0->isFloatTy() && T1->isFloatTy())
241706c3fb27SDimitry Andric     return llvm::FixedVectorType::get(T0, 2);
241806c3fb27SDimitry Andric 
241906c3fb27SDimitry Andric   if (T0->is16bitFPTy() && T1->is16bitFPTy()) {
242006c3fb27SDimitry Andric     llvm::Type *T2 = nullptr;
242106c3fb27SDimitry Andric     if (SourceSize > 4)
242206c3fb27SDimitry Andric       T2 = getFPTypeAtOffset(IRType, IROffset + 4, TD);
242306c3fb27SDimitry Andric     if (T2 == nullptr)
242406c3fb27SDimitry Andric       return llvm::FixedVectorType::get(T0, 2);
242506c3fb27SDimitry Andric     return llvm::FixedVectorType::get(T0, 4);
242606c3fb27SDimitry Andric   }
242706c3fb27SDimitry Andric 
242806c3fb27SDimitry Andric   if (T0->is16bitFPTy() || T1->is16bitFPTy())
242906c3fb27SDimitry Andric     return llvm::FixedVectorType::get(llvm::Type::getHalfTy(getVMContext()), 4);
243006c3fb27SDimitry Andric 
243106c3fb27SDimitry Andric   return llvm::Type::getDoubleTy(getVMContext());
243206c3fb27SDimitry Andric }
243306c3fb27SDimitry Andric 
243406c3fb27SDimitry Andric 
243506c3fb27SDimitry Andric /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
243606c3fb27SDimitry Andric /// an 8-byte GPR.  This means that we either have a scalar or we are talking
243706c3fb27SDimitry Andric /// about the high or low part of an up-to-16-byte struct.  This routine picks
243806c3fb27SDimitry Andric /// the best LLVM IR type to represent this, which may be i64 or may be anything
243906c3fb27SDimitry Andric /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
244006c3fb27SDimitry Andric /// etc).
244106c3fb27SDimitry Andric ///
244206c3fb27SDimitry Andric /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
244306c3fb27SDimitry Andric /// the source type.  IROffset is an offset in bytes into the LLVM IR type that
244406c3fb27SDimitry Andric /// the 8-byte value references.  PrefType may be null.
244506c3fb27SDimitry Andric ///
244606c3fb27SDimitry Andric /// SourceTy is the source-level type for the entire argument.  SourceOffset is
244706c3fb27SDimitry Andric /// an offset into this that we're processing (which is always either 0 or 8).
244806c3fb27SDimitry Andric ///
244906c3fb27SDimitry Andric llvm::Type *X86_64ABIInfo::
245006c3fb27SDimitry Andric GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
245106c3fb27SDimitry Andric                        QualType SourceTy, unsigned SourceOffset) const {
245206c3fb27SDimitry Andric   // If we're dealing with an un-offset LLVM IR type, then it means that we're
245306c3fb27SDimitry Andric   // returning an 8-byte unit starting with it.  See if we can safely use it.
245406c3fb27SDimitry Andric   if (IROffset == 0) {
245506c3fb27SDimitry Andric     // Pointers and int64's always fill the 8-byte unit.
245606c3fb27SDimitry Andric     if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
245706c3fb27SDimitry Andric         IRType->isIntegerTy(64))
245806c3fb27SDimitry Andric       return IRType;
245906c3fb27SDimitry Andric 
246006c3fb27SDimitry Andric     // If we have a 1/2/4-byte integer, we can use it only if the rest of the
246106c3fb27SDimitry Andric     // goodness in the source type is just tail padding.  This is allowed to
246206c3fb27SDimitry Andric     // kick in for struct {double,int} on the int, but not on
246306c3fb27SDimitry Andric     // struct{double,int,int} because we wouldn't return the second int.  We
246406c3fb27SDimitry Andric     // have to do this analysis on the source type because we can't depend on
246506c3fb27SDimitry Andric     // unions being lowered a specific way etc.
246606c3fb27SDimitry Andric     if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
246706c3fb27SDimitry Andric         IRType->isIntegerTy(32) ||
246806c3fb27SDimitry Andric         (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
246906c3fb27SDimitry Andric       unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
247006c3fb27SDimitry Andric           cast<llvm::IntegerType>(IRType)->getBitWidth();
247106c3fb27SDimitry Andric 
247206c3fb27SDimitry Andric       if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
247306c3fb27SDimitry Andric                                 SourceOffset*8+64, getContext()))
247406c3fb27SDimitry Andric         return IRType;
247506c3fb27SDimitry Andric     }
247606c3fb27SDimitry Andric   }
247706c3fb27SDimitry Andric 
247806c3fb27SDimitry Andric   if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
247906c3fb27SDimitry Andric     // If this is a struct, recurse into the field at the specified offset.
248006c3fb27SDimitry Andric     const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
248106c3fb27SDimitry Andric     if (IROffset < SL->getSizeInBytes()) {
248206c3fb27SDimitry Andric       unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
248306c3fb27SDimitry Andric       IROffset -= SL->getElementOffset(FieldIdx);
248406c3fb27SDimitry Andric 
248506c3fb27SDimitry Andric       return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
248606c3fb27SDimitry Andric                                     SourceTy, SourceOffset);
248706c3fb27SDimitry Andric     }
248806c3fb27SDimitry Andric   }
248906c3fb27SDimitry Andric 
249006c3fb27SDimitry Andric   if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
249106c3fb27SDimitry Andric     llvm::Type *EltTy = ATy->getElementType();
249206c3fb27SDimitry Andric     unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
249306c3fb27SDimitry Andric     unsigned EltOffset = IROffset/EltSize*EltSize;
249406c3fb27SDimitry Andric     return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
249506c3fb27SDimitry Andric                                   SourceOffset);
249606c3fb27SDimitry Andric   }
249706c3fb27SDimitry Andric 
249806c3fb27SDimitry Andric   // Okay, we don't have any better idea of what to pass, so we pass this in an
249906c3fb27SDimitry Andric   // integer register that isn't too big to fit the rest of the struct.
250006c3fb27SDimitry Andric   unsigned TySizeInBytes =
250106c3fb27SDimitry Andric     (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
250206c3fb27SDimitry Andric 
250306c3fb27SDimitry Andric   assert(TySizeInBytes != SourceOffset && "Empty field?");
250406c3fb27SDimitry Andric 
250506c3fb27SDimitry Andric   // It is always safe to classify this as an integer type up to i64 that
250606c3fb27SDimitry Andric   // isn't larger than the structure.
250706c3fb27SDimitry Andric   return llvm::IntegerType::get(getVMContext(),
250806c3fb27SDimitry Andric                                 std::min(TySizeInBytes-SourceOffset, 8U)*8);
250906c3fb27SDimitry Andric }
251006c3fb27SDimitry Andric 
251106c3fb27SDimitry Andric 
251206c3fb27SDimitry Andric /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
251306c3fb27SDimitry Andric /// be used as elements of a two register pair to pass or return, return a
251406c3fb27SDimitry Andric /// first class aggregate to represent them.  For example, if the low part of
251506c3fb27SDimitry Andric /// a by-value argument should be passed as i32* and the high part as float,
251606c3fb27SDimitry Andric /// return {i32*, float}.
251706c3fb27SDimitry Andric static llvm::Type *
251806c3fb27SDimitry Andric GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
251906c3fb27SDimitry Andric                            const llvm::DataLayout &TD) {
252006c3fb27SDimitry Andric   // In order to correctly satisfy the ABI, we need to the high part to start
252106c3fb27SDimitry Andric   // at offset 8.  If the high and low parts we inferred are both 4-byte types
252206c3fb27SDimitry Andric   // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
252306c3fb27SDimitry Andric   // the second element at offset 8.  Check for this:
252406c3fb27SDimitry Andric   unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
252506c3fb27SDimitry Andric   llvm::Align HiAlign = TD.getABITypeAlign(Hi);
252606c3fb27SDimitry Andric   unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
252706c3fb27SDimitry Andric   assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
252806c3fb27SDimitry Andric 
252906c3fb27SDimitry Andric   // To handle this, we have to increase the size of the low part so that the
253006c3fb27SDimitry Andric   // second element will start at an 8 byte offset.  We can't increase the size
253106c3fb27SDimitry Andric   // of the second element because it might make us access off the end of the
253206c3fb27SDimitry Andric   // struct.
253306c3fb27SDimitry Andric   if (HiStart != 8) {
253406c3fb27SDimitry Andric     // There are usually two sorts of types the ABI generation code can produce
253506c3fb27SDimitry Andric     // for the low part of a pair that aren't 8 bytes in size: half, float or
253606c3fb27SDimitry Andric     // i8/i16/i32.  This can also include pointers when they are 32-bit (X32 and
253706c3fb27SDimitry Andric     // NaCl).
253806c3fb27SDimitry Andric     // Promote these to a larger type.
253906c3fb27SDimitry Andric     if (Lo->isHalfTy() || Lo->isFloatTy())
254006c3fb27SDimitry Andric       Lo = llvm::Type::getDoubleTy(Lo->getContext());
254106c3fb27SDimitry Andric     else {
254206c3fb27SDimitry Andric       assert((Lo->isIntegerTy() || Lo->isPointerTy())
254306c3fb27SDimitry Andric              && "Invalid/unknown lo type");
254406c3fb27SDimitry Andric       Lo = llvm::Type::getInt64Ty(Lo->getContext());
254506c3fb27SDimitry Andric     }
254606c3fb27SDimitry Andric   }
254706c3fb27SDimitry Andric 
254806c3fb27SDimitry Andric   llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
254906c3fb27SDimitry Andric 
255006c3fb27SDimitry Andric   // Verify that the second element is at an 8-byte offset.
255106c3fb27SDimitry Andric   assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
255206c3fb27SDimitry Andric          "Invalid x86-64 argument pair!");
255306c3fb27SDimitry Andric   return Result;
255406c3fb27SDimitry Andric }
255506c3fb27SDimitry Andric 
255606c3fb27SDimitry Andric ABIArgInfo X86_64ABIInfo::
255706c3fb27SDimitry Andric classifyReturnType(QualType RetTy) const {
255806c3fb27SDimitry Andric   // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
255906c3fb27SDimitry Andric   // classification algorithm.
256006c3fb27SDimitry Andric   X86_64ABIInfo::Class Lo, Hi;
256106c3fb27SDimitry Andric   classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
256206c3fb27SDimitry Andric 
256306c3fb27SDimitry Andric   // Check some invariants.
256406c3fb27SDimitry Andric   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
256506c3fb27SDimitry Andric   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
256606c3fb27SDimitry Andric 
256706c3fb27SDimitry Andric   llvm::Type *ResType = nullptr;
256806c3fb27SDimitry Andric   switch (Lo) {
256906c3fb27SDimitry Andric   case NoClass:
257006c3fb27SDimitry Andric     if (Hi == NoClass)
257106c3fb27SDimitry Andric       return ABIArgInfo::getIgnore();
257206c3fb27SDimitry Andric     // If the low part is just padding, it takes no register, leave ResType
257306c3fb27SDimitry Andric     // null.
257406c3fb27SDimitry Andric     assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
257506c3fb27SDimitry Andric            "Unknown missing lo part");
257606c3fb27SDimitry Andric     break;
257706c3fb27SDimitry Andric 
257806c3fb27SDimitry Andric   case SSEUp:
257906c3fb27SDimitry Andric   case X87Up:
258006c3fb27SDimitry Andric     llvm_unreachable("Invalid classification for lo word.");
258106c3fb27SDimitry Andric 
258206c3fb27SDimitry Andric     // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
258306c3fb27SDimitry Andric     // hidden argument.
258406c3fb27SDimitry Andric   case Memory:
258506c3fb27SDimitry Andric     return getIndirectReturnResult(RetTy);
258606c3fb27SDimitry Andric 
258706c3fb27SDimitry Andric     // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
258806c3fb27SDimitry Andric     // available register of the sequence %rax, %rdx is used.
258906c3fb27SDimitry Andric   case Integer:
259006c3fb27SDimitry Andric     ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
259106c3fb27SDimitry Andric 
259206c3fb27SDimitry Andric     // If we have a sign or zero extended integer, make sure to return Extend
259306c3fb27SDimitry Andric     // so that the parameter gets the right LLVM IR attributes.
259406c3fb27SDimitry Andric     if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
259506c3fb27SDimitry Andric       // Treat an enum type as its underlying type.
259606c3fb27SDimitry Andric       if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
259706c3fb27SDimitry Andric         RetTy = EnumTy->getDecl()->getIntegerType();
259806c3fb27SDimitry Andric 
259906c3fb27SDimitry Andric       if (RetTy->isIntegralOrEnumerationType() &&
260006c3fb27SDimitry Andric           isPromotableIntegerTypeForABI(RetTy))
260106c3fb27SDimitry Andric         return ABIArgInfo::getExtend(RetTy);
260206c3fb27SDimitry Andric     }
260306c3fb27SDimitry Andric     break;
260406c3fb27SDimitry Andric 
260506c3fb27SDimitry Andric     // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
260606c3fb27SDimitry Andric     // available SSE register of the sequence %xmm0, %xmm1 is used.
260706c3fb27SDimitry Andric   case SSE:
260806c3fb27SDimitry Andric     ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
260906c3fb27SDimitry Andric     break;
261006c3fb27SDimitry Andric 
261106c3fb27SDimitry Andric     // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
261206c3fb27SDimitry Andric     // returned on the X87 stack in %st0 as 80-bit x87 number.
261306c3fb27SDimitry Andric   case X87:
261406c3fb27SDimitry Andric     ResType = llvm::Type::getX86_FP80Ty(getVMContext());
261506c3fb27SDimitry Andric     break;
261606c3fb27SDimitry Andric 
261706c3fb27SDimitry Andric     // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
261806c3fb27SDimitry Andric     // part of the value is returned in %st0 and the imaginary part in
261906c3fb27SDimitry Andric     // %st1.
262006c3fb27SDimitry Andric   case ComplexX87:
262106c3fb27SDimitry Andric     assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
262206c3fb27SDimitry Andric     ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
262306c3fb27SDimitry Andric                                     llvm::Type::getX86_FP80Ty(getVMContext()));
262406c3fb27SDimitry Andric     break;
262506c3fb27SDimitry Andric   }
262606c3fb27SDimitry Andric 
262706c3fb27SDimitry Andric   llvm::Type *HighPart = nullptr;
262806c3fb27SDimitry Andric   switch (Hi) {
262906c3fb27SDimitry Andric     // Memory was handled previously and X87 should
263006c3fb27SDimitry Andric     // never occur as a hi class.
263106c3fb27SDimitry Andric   case Memory:
263206c3fb27SDimitry Andric   case X87:
263306c3fb27SDimitry Andric     llvm_unreachable("Invalid classification for hi word.");
263406c3fb27SDimitry Andric 
263506c3fb27SDimitry Andric   case ComplexX87: // Previously handled.
263606c3fb27SDimitry Andric   case NoClass:
263706c3fb27SDimitry Andric     break;
263806c3fb27SDimitry Andric 
263906c3fb27SDimitry Andric   case Integer:
264006c3fb27SDimitry Andric     HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
264106c3fb27SDimitry Andric     if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
264206c3fb27SDimitry Andric       return ABIArgInfo::getDirect(HighPart, 8);
264306c3fb27SDimitry Andric     break;
264406c3fb27SDimitry Andric   case SSE:
264506c3fb27SDimitry Andric     HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
264606c3fb27SDimitry Andric     if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
264706c3fb27SDimitry Andric       return ABIArgInfo::getDirect(HighPart, 8);
264806c3fb27SDimitry Andric     break;
264906c3fb27SDimitry Andric 
265006c3fb27SDimitry Andric     // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
265106c3fb27SDimitry Andric     // is passed in the next available eightbyte chunk if the last used
265206c3fb27SDimitry Andric     // vector register.
265306c3fb27SDimitry Andric     //
265406c3fb27SDimitry Andric     // SSEUP should always be preceded by SSE, just widen.
265506c3fb27SDimitry Andric   case SSEUp:
265606c3fb27SDimitry Andric     assert(Lo == SSE && "Unexpected SSEUp classification.");
265706c3fb27SDimitry Andric     ResType = GetByteVectorType(RetTy);
265806c3fb27SDimitry Andric     break;
265906c3fb27SDimitry Andric 
266006c3fb27SDimitry Andric     // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
266106c3fb27SDimitry Andric     // returned together with the previous X87 value in %st0.
266206c3fb27SDimitry Andric   case X87Up:
266306c3fb27SDimitry Andric     // If X87Up is preceded by X87, we don't need to do
266406c3fb27SDimitry Andric     // anything. However, in some cases with unions it may not be
266506c3fb27SDimitry Andric     // preceded by X87. In such situations we follow gcc and pass the
266606c3fb27SDimitry Andric     // extra bits in an SSE reg.
266706c3fb27SDimitry Andric     if (Lo != X87) {
266806c3fb27SDimitry Andric       HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
266906c3fb27SDimitry Andric       if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
267006c3fb27SDimitry Andric         return ABIArgInfo::getDirect(HighPart, 8);
267106c3fb27SDimitry Andric     }
267206c3fb27SDimitry Andric     break;
267306c3fb27SDimitry Andric   }
267406c3fb27SDimitry Andric 
267506c3fb27SDimitry Andric   // If a high part was specified, merge it together with the low part.  It is
267606c3fb27SDimitry Andric   // known to pass in the high eightbyte of the result.  We do this by forming a
267706c3fb27SDimitry Andric   // first class struct aggregate with the high and low part: {low, high}
267806c3fb27SDimitry Andric   if (HighPart)
267906c3fb27SDimitry Andric     ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
268006c3fb27SDimitry Andric 
268106c3fb27SDimitry Andric   return ABIArgInfo::getDirect(ResType);
268206c3fb27SDimitry Andric }
268306c3fb27SDimitry Andric 
268406c3fb27SDimitry Andric ABIArgInfo
268506c3fb27SDimitry Andric X86_64ABIInfo::classifyArgumentType(QualType Ty, unsigned freeIntRegs,
268606c3fb27SDimitry Andric                                     unsigned &neededInt, unsigned &neededSSE,
268706c3fb27SDimitry Andric                                     bool isNamedArg, bool IsRegCall) const {
268806c3fb27SDimitry Andric   Ty = useFirstFieldIfTransparentUnion(Ty);
268906c3fb27SDimitry Andric 
269006c3fb27SDimitry Andric   X86_64ABIInfo::Class Lo, Hi;
269106c3fb27SDimitry Andric   classify(Ty, 0, Lo, Hi, isNamedArg, IsRegCall);
269206c3fb27SDimitry Andric 
269306c3fb27SDimitry Andric   // Check some invariants.
269406c3fb27SDimitry Andric   // FIXME: Enforce these by construction.
269506c3fb27SDimitry Andric   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
269606c3fb27SDimitry Andric   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
269706c3fb27SDimitry Andric 
269806c3fb27SDimitry Andric   neededInt = 0;
269906c3fb27SDimitry Andric   neededSSE = 0;
270006c3fb27SDimitry Andric   llvm::Type *ResType = nullptr;
270106c3fb27SDimitry Andric   switch (Lo) {
270206c3fb27SDimitry Andric   case NoClass:
270306c3fb27SDimitry Andric     if (Hi == NoClass)
270406c3fb27SDimitry Andric       return ABIArgInfo::getIgnore();
270506c3fb27SDimitry Andric     // If the low part is just padding, it takes no register, leave ResType
270606c3fb27SDimitry Andric     // null.
270706c3fb27SDimitry Andric     assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
270806c3fb27SDimitry Andric            "Unknown missing lo part");
270906c3fb27SDimitry Andric     break;
271006c3fb27SDimitry Andric 
271106c3fb27SDimitry Andric     // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
271206c3fb27SDimitry Andric     // on the stack.
271306c3fb27SDimitry Andric   case Memory:
271406c3fb27SDimitry Andric 
271506c3fb27SDimitry Andric     // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
271606c3fb27SDimitry Andric     // COMPLEX_X87, it is passed in memory.
271706c3fb27SDimitry Andric   case X87:
271806c3fb27SDimitry Andric   case ComplexX87:
271906c3fb27SDimitry Andric     if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
272006c3fb27SDimitry Andric       ++neededInt;
272106c3fb27SDimitry Andric     return getIndirectResult(Ty, freeIntRegs);
272206c3fb27SDimitry Andric 
272306c3fb27SDimitry Andric   case SSEUp:
272406c3fb27SDimitry Andric   case X87Up:
272506c3fb27SDimitry Andric     llvm_unreachable("Invalid classification for lo word.");
272606c3fb27SDimitry Andric 
272706c3fb27SDimitry Andric     // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
272806c3fb27SDimitry Andric     // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
272906c3fb27SDimitry Andric     // and %r9 is used.
273006c3fb27SDimitry Andric   case Integer:
273106c3fb27SDimitry Andric     ++neededInt;
273206c3fb27SDimitry Andric 
273306c3fb27SDimitry Andric     // Pick an 8-byte type based on the preferred type.
273406c3fb27SDimitry Andric     ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
273506c3fb27SDimitry Andric 
273606c3fb27SDimitry Andric     // If we have a sign or zero extended integer, make sure to return Extend
273706c3fb27SDimitry Andric     // so that the parameter gets the right LLVM IR attributes.
273806c3fb27SDimitry Andric     if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
273906c3fb27SDimitry Andric       // Treat an enum type as its underlying type.
274006c3fb27SDimitry Andric       if (const EnumType *EnumTy = Ty->getAs<EnumType>())
274106c3fb27SDimitry Andric         Ty = EnumTy->getDecl()->getIntegerType();
274206c3fb27SDimitry Andric 
274306c3fb27SDimitry Andric       if (Ty->isIntegralOrEnumerationType() &&
274406c3fb27SDimitry Andric           isPromotableIntegerTypeForABI(Ty))
274506c3fb27SDimitry Andric         return ABIArgInfo::getExtend(Ty);
274606c3fb27SDimitry Andric     }
274706c3fb27SDimitry Andric 
274806c3fb27SDimitry Andric     break;
274906c3fb27SDimitry Andric 
275006c3fb27SDimitry Andric     // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
275106c3fb27SDimitry Andric     // available SSE register is used, the registers are taken in the
275206c3fb27SDimitry Andric     // order from %xmm0 to %xmm7.
275306c3fb27SDimitry Andric   case SSE: {
275406c3fb27SDimitry Andric     llvm::Type *IRType = CGT.ConvertType(Ty);
275506c3fb27SDimitry Andric     ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
275606c3fb27SDimitry Andric     ++neededSSE;
275706c3fb27SDimitry Andric     break;
275806c3fb27SDimitry Andric   }
275906c3fb27SDimitry Andric   }
276006c3fb27SDimitry Andric 
276106c3fb27SDimitry Andric   llvm::Type *HighPart = nullptr;
276206c3fb27SDimitry Andric   switch (Hi) {
276306c3fb27SDimitry Andric     // Memory was handled previously, ComplexX87 and X87 should
276406c3fb27SDimitry Andric     // never occur as hi classes, and X87Up must be preceded by X87,
276506c3fb27SDimitry Andric     // which is passed in memory.
276606c3fb27SDimitry Andric   case Memory:
276706c3fb27SDimitry Andric   case X87:
276806c3fb27SDimitry Andric   case ComplexX87:
276906c3fb27SDimitry Andric     llvm_unreachable("Invalid classification for hi word.");
277006c3fb27SDimitry Andric 
277106c3fb27SDimitry Andric   case NoClass: break;
277206c3fb27SDimitry Andric 
277306c3fb27SDimitry Andric   case Integer:
277406c3fb27SDimitry Andric     ++neededInt;
277506c3fb27SDimitry Andric     // Pick an 8-byte type based on the preferred type.
277606c3fb27SDimitry Andric     HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
277706c3fb27SDimitry Andric 
277806c3fb27SDimitry Andric     if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
277906c3fb27SDimitry Andric       return ABIArgInfo::getDirect(HighPart, 8);
278006c3fb27SDimitry Andric     break;
278106c3fb27SDimitry Andric 
278206c3fb27SDimitry Andric     // X87Up generally doesn't occur here (long double is passed in
278306c3fb27SDimitry Andric     // memory), except in situations involving unions.
278406c3fb27SDimitry Andric   case X87Up:
278506c3fb27SDimitry Andric   case SSE:
278606c3fb27SDimitry Andric     HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
278706c3fb27SDimitry Andric 
278806c3fb27SDimitry Andric     if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
278906c3fb27SDimitry Andric       return ABIArgInfo::getDirect(HighPart, 8);
279006c3fb27SDimitry Andric 
279106c3fb27SDimitry Andric     ++neededSSE;
279206c3fb27SDimitry Andric     break;
279306c3fb27SDimitry Andric 
279406c3fb27SDimitry Andric     // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
279506c3fb27SDimitry Andric     // eightbyte is passed in the upper half of the last used SSE
279606c3fb27SDimitry Andric     // register.  This only happens when 128-bit vectors are passed.
279706c3fb27SDimitry Andric   case SSEUp:
279806c3fb27SDimitry Andric     assert(Lo == SSE && "Unexpected SSEUp classification");
279906c3fb27SDimitry Andric     ResType = GetByteVectorType(Ty);
280006c3fb27SDimitry Andric     break;
280106c3fb27SDimitry Andric   }
280206c3fb27SDimitry Andric 
280306c3fb27SDimitry Andric   // If a high part was specified, merge it together with the low part.  It is
280406c3fb27SDimitry Andric   // known to pass in the high eightbyte of the result.  We do this by forming a
280506c3fb27SDimitry Andric   // first class struct aggregate with the high and low part: {low, high}
280606c3fb27SDimitry Andric   if (HighPart)
280706c3fb27SDimitry Andric     ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
280806c3fb27SDimitry Andric 
280906c3fb27SDimitry Andric   return ABIArgInfo::getDirect(ResType);
281006c3fb27SDimitry Andric }
281106c3fb27SDimitry Andric 
281206c3fb27SDimitry Andric ABIArgInfo
281306c3fb27SDimitry Andric X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
281406c3fb27SDimitry Andric                                              unsigned &NeededSSE,
281506c3fb27SDimitry Andric                                              unsigned &MaxVectorWidth) const {
281606c3fb27SDimitry Andric   auto RT = Ty->getAs<RecordType>();
281706c3fb27SDimitry Andric   assert(RT && "classifyRegCallStructType only valid with struct types");
281806c3fb27SDimitry Andric 
281906c3fb27SDimitry Andric   if (RT->getDecl()->hasFlexibleArrayMember())
282006c3fb27SDimitry Andric     return getIndirectReturnResult(Ty);
282106c3fb27SDimitry Andric 
282206c3fb27SDimitry Andric   // Sum up bases
282306c3fb27SDimitry Andric   if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
282406c3fb27SDimitry Andric     if (CXXRD->isDynamicClass()) {
282506c3fb27SDimitry Andric       NeededInt = NeededSSE = 0;
282606c3fb27SDimitry Andric       return getIndirectReturnResult(Ty);
282706c3fb27SDimitry Andric     }
282806c3fb27SDimitry Andric 
282906c3fb27SDimitry Andric     for (const auto &I : CXXRD->bases())
283006c3fb27SDimitry Andric       if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE,
283106c3fb27SDimitry Andric                                         MaxVectorWidth)
283206c3fb27SDimitry Andric               .isIndirect()) {
283306c3fb27SDimitry Andric         NeededInt = NeededSSE = 0;
283406c3fb27SDimitry Andric         return getIndirectReturnResult(Ty);
283506c3fb27SDimitry Andric       }
283606c3fb27SDimitry Andric   }
283706c3fb27SDimitry Andric 
283806c3fb27SDimitry Andric   // Sum up members
283906c3fb27SDimitry Andric   for (const auto *FD : RT->getDecl()->fields()) {
284006c3fb27SDimitry Andric     QualType MTy = FD->getType();
284106c3fb27SDimitry Andric     if (MTy->isRecordType() && !MTy->isUnionType()) {
284206c3fb27SDimitry Andric       if (classifyRegCallStructTypeImpl(MTy, NeededInt, NeededSSE,
284306c3fb27SDimitry Andric                                         MaxVectorWidth)
284406c3fb27SDimitry Andric               .isIndirect()) {
284506c3fb27SDimitry Andric         NeededInt = NeededSSE = 0;
284606c3fb27SDimitry Andric         return getIndirectReturnResult(Ty);
284706c3fb27SDimitry Andric       }
284806c3fb27SDimitry Andric     } else {
284906c3fb27SDimitry Andric       unsigned LocalNeededInt, LocalNeededSSE;
285006c3fb27SDimitry Andric       if (classifyArgumentType(MTy, UINT_MAX, LocalNeededInt, LocalNeededSSE,
285106c3fb27SDimitry Andric                                true, true)
285206c3fb27SDimitry Andric               .isIndirect()) {
285306c3fb27SDimitry Andric         NeededInt = NeededSSE = 0;
285406c3fb27SDimitry Andric         return getIndirectReturnResult(Ty);
285506c3fb27SDimitry Andric       }
285606c3fb27SDimitry Andric       if (const auto *AT = getContext().getAsConstantArrayType(MTy))
285706c3fb27SDimitry Andric         MTy = AT->getElementType();
285806c3fb27SDimitry Andric       if (const auto *VT = MTy->getAs<VectorType>())
285906c3fb27SDimitry Andric         if (getContext().getTypeSize(VT) > MaxVectorWidth)
286006c3fb27SDimitry Andric           MaxVectorWidth = getContext().getTypeSize(VT);
286106c3fb27SDimitry Andric       NeededInt += LocalNeededInt;
286206c3fb27SDimitry Andric       NeededSSE += LocalNeededSSE;
286306c3fb27SDimitry Andric     }
286406c3fb27SDimitry Andric   }
286506c3fb27SDimitry Andric 
286606c3fb27SDimitry Andric   return ABIArgInfo::getDirect();
286706c3fb27SDimitry Andric }
286806c3fb27SDimitry Andric 
286906c3fb27SDimitry Andric ABIArgInfo
287006c3fb27SDimitry Andric X86_64ABIInfo::classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
287106c3fb27SDimitry Andric                                          unsigned &NeededSSE,
287206c3fb27SDimitry Andric                                          unsigned &MaxVectorWidth) const {
287306c3fb27SDimitry Andric 
287406c3fb27SDimitry Andric   NeededInt = 0;
287506c3fb27SDimitry Andric   NeededSSE = 0;
287606c3fb27SDimitry Andric   MaxVectorWidth = 0;
287706c3fb27SDimitry Andric 
287806c3fb27SDimitry Andric   return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE,
287906c3fb27SDimitry Andric                                        MaxVectorWidth);
288006c3fb27SDimitry Andric }
288106c3fb27SDimitry Andric 
288206c3fb27SDimitry Andric void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
288306c3fb27SDimitry Andric 
288406c3fb27SDimitry Andric   const unsigned CallingConv = FI.getCallingConvention();
288506c3fb27SDimitry Andric   // It is possible to force Win64 calling convention on any x86_64 target by
288606c3fb27SDimitry Andric   // using __attribute__((ms_abi)). In such case to correctly emit Win64
288706c3fb27SDimitry Andric   // compatible code delegate this call to WinX86_64ABIInfo::computeInfo.
288806c3fb27SDimitry Andric   if (CallingConv == llvm::CallingConv::Win64) {
288906c3fb27SDimitry Andric     WinX86_64ABIInfo Win64ABIInfo(CGT, AVXLevel);
289006c3fb27SDimitry Andric     Win64ABIInfo.computeInfo(FI);
289106c3fb27SDimitry Andric     return;
289206c3fb27SDimitry Andric   }
289306c3fb27SDimitry Andric 
289406c3fb27SDimitry Andric   bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall;
289506c3fb27SDimitry Andric 
289606c3fb27SDimitry Andric   // Keep track of the number of assigned registers.
289706c3fb27SDimitry Andric   unsigned FreeIntRegs = IsRegCall ? 11 : 6;
289806c3fb27SDimitry Andric   unsigned FreeSSERegs = IsRegCall ? 16 : 8;
289906c3fb27SDimitry Andric   unsigned NeededInt = 0, NeededSSE = 0, MaxVectorWidth = 0;
290006c3fb27SDimitry Andric 
290106c3fb27SDimitry Andric   if (!::classifyReturnType(getCXXABI(), FI, *this)) {
290206c3fb27SDimitry Andric     if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
290306c3fb27SDimitry Andric         !FI.getReturnType()->getTypePtr()->isUnionType()) {
290406c3fb27SDimitry Andric       FI.getReturnInfo() = classifyRegCallStructType(
290506c3fb27SDimitry Andric           FI.getReturnType(), NeededInt, NeededSSE, MaxVectorWidth);
290606c3fb27SDimitry Andric       if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
290706c3fb27SDimitry Andric         FreeIntRegs -= NeededInt;
290806c3fb27SDimitry Andric         FreeSSERegs -= NeededSSE;
290906c3fb27SDimitry Andric       } else {
291006c3fb27SDimitry Andric         FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
291106c3fb27SDimitry Andric       }
291206c3fb27SDimitry Andric     } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>() &&
291306c3fb27SDimitry Andric                getContext().getCanonicalType(FI.getReturnType()
291406c3fb27SDimitry Andric                                                  ->getAs<ComplexType>()
291506c3fb27SDimitry Andric                                                  ->getElementType()) ==
291606c3fb27SDimitry Andric                    getContext().LongDoubleTy)
291706c3fb27SDimitry Andric       // Complex Long Double Type is passed in Memory when Regcall
291806c3fb27SDimitry Andric       // calling convention is used.
291906c3fb27SDimitry Andric       FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
292006c3fb27SDimitry Andric     else
292106c3fb27SDimitry Andric       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
292206c3fb27SDimitry Andric   }
292306c3fb27SDimitry Andric 
292406c3fb27SDimitry Andric   // If the return value is indirect, then the hidden argument is consuming one
292506c3fb27SDimitry Andric   // integer register.
292606c3fb27SDimitry Andric   if (FI.getReturnInfo().isIndirect())
292706c3fb27SDimitry Andric     --FreeIntRegs;
292806c3fb27SDimitry Andric   else if (NeededSSE && MaxVectorWidth > 0)
292906c3fb27SDimitry Andric     FI.setMaxVectorWidth(MaxVectorWidth);
293006c3fb27SDimitry Andric 
293106c3fb27SDimitry Andric   // The chain argument effectively gives us another free register.
293206c3fb27SDimitry Andric   if (FI.isChainCall())
293306c3fb27SDimitry Andric     ++FreeIntRegs;
293406c3fb27SDimitry Andric 
293506c3fb27SDimitry Andric   unsigned NumRequiredArgs = FI.getNumRequiredArgs();
293606c3fb27SDimitry Andric   // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
293706c3fb27SDimitry Andric   // get assigned (in left-to-right order) for passing as follows...
293806c3fb27SDimitry Andric   unsigned ArgNo = 0;
293906c3fb27SDimitry Andric   for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
294006c3fb27SDimitry Andric        it != ie; ++it, ++ArgNo) {
294106c3fb27SDimitry Andric     bool IsNamedArg = ArgNo < NumRequiredArgs;
294206c3fb27SDimitry Andric 
294306c3fb27SDimitry Andric     if (IsRegCall && it->type->isStructureOrClassType())
294406c3fb27SDimitry Andric       it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE,
294506c3fb27SDimitry Andric                                            MaxVectorWidth);
294606c3fb27SDimitry Andric     else
294706c3fb27SDimitry Andric       it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
294806c3fb27SDimitry Andric                                       NeededSSE, IsNamedArg);
294906c3fb27SDimitry Andric 
295006c3fb27SDimitry Andric     // AMD64-ABI 3.2.3p3: If there are no registers available for any
295106c3fb27SDimitry Andric     // eightbyte of an argument, the whole argument is passed on the
295206c3fb27SDimitry Andric     // stack. If registers have already been assigned for some
295306c3fb27SDimitry Andric     // eightbytes of such an argument, the assignments get reverted.
295406c3fb27SDimitry Andric     if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
295506c3fb27SDimitry Andric       FreeIntRegs -= NeededInt;
295606c3fb27SDimitry Andric       FreeSSERegs -= NeededSSE;
295706c3fb27SDimitry Andric       if (MaxVectorWidth > FI.getMaxVectorWidth())
295806c3fb27SDimitry Andric         FI.setMaxVectorWidth(MaxVectorWidth);
295906c3fb27SDimitry Andric     } else {
296006c3fb27SDimitry Andric       it->info = getIndirectResult(it->type, FreeIntRegs);
296106c3fb27SDimitry Andric     }
296206c3fb27SDimitry Andric   }
296306c3fb27SDimitry Andric }
296406c3fb27SDimitry Andric 
296506c3fb27SDimitry Andric static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
296606c3fb27SDimitry Andric                                          Address VAListAddr, QualType Ty) {
296706c3fb27SDimitry Andric   Address overflow_arg_area_p =
296806c3fb27SDimitry Andric       CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
296906c3fb27SDimitry Andric   llvm::Value *overflow_arg_area =
297006c3fb27SDimitry Andric     CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
297106c3fb27SDimitry Andric 
297206c3fb27SDimitry Andric   // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
297306c3fb27SDimitry Andric   // byte boundary if alignment needed by type exceeds 8 byte boundary.
297406c3fb27SDimitry Andric   // It isn't stated explicitly in the standard, but in practice we use
297506c3fb27SDimitry Andric   // alignment greater than 16 where necessary.
297606c3fb27SDimitry Andric   CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
297706c3fb27SDimitry Andric   if (Align > CharUnits::fromQuantity(8)) {
297806c3fb27SDimitry Andric     overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
297906c3fb27SDimitry Andric                                                       Align);
298006c3fb27SDimitry Andric   }
298106c3fb27SDimitry Andric 
298206c3fb27SDimitry Andric   // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
298306c3fb27SDimitry Andric   llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
29845f757f3fSDimitry Andric   llvm::Value *Res = overflow_arg_area;
298506c3fb27SDimitry Andric 
298606c3fb27SDimitry Andric   // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
298706c3fb27SDimitry Andric   // l->overflow_arg_area + sizeof(type).
298806c3fb27SDimitry Andric   // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
298906c3fb27SDimitry Andric   // an 8 byte boundary.
299006c3fb27SDimitry Andric 
299106c3fb27SDimitry Andric   uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
299206c3fb27SDimitry Andric   llvm::Value *Offset =
299306c3fb27SDimitry Andric       llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7)  & ~7);
299406c3fb27SDimitry Andric   overflow_arg_area = CGF.Builder.CreateGEP(CGF.Int8Ty, overflow_arg_area,
299506c3fb27SDimitry Andric                                             Offset, "overflow_arg_area.next");
299606c3fb27SDimitry Andric   CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
299706c3fb27SDimitry Andric 
299806c3fb27SDimitry Andric   // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
299906c3fb27SDimitry Andric   return Address(Res, LTy, Align);
300006c3fb27SDimitry Andric }
300106c3fb27SDimitry Andric 
300206c3fb27SDimitry Andric Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
300306c3fb27SDimitry Andric                                  QualType Ty) const {
300406c3fb27SDimitry Andric   // Assume that va_list type is correct; should be pointer to LLVM type:
300506c3fb27SDimitry Andric   // struct {
300606c3fb27SDimitry Andric   //   i32 gp_offset;
300706c3fb27SDimitry Andric   //   i32 fp_offset;
300806c3fb27SDimitry Andric   //   i8* overflow_arg_area;
300906c3fb27SDimitry Andric   //   i8* reg_save_area;
301006c3fb27SDimitry Andric   // };
301106c3fb27SDimitry Andric   unsigned neededInt, neededSSE;
301206c3fb27SDimitry Andric 
301306c3fb27SDimitry Andric   Ty = getContext().getCanonicalType(Ty);
301406c3fb27SDimitry Andric   ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
301506c3fb27SDimitry Andric                                        /*isNamedArg*/false);
301606c3fb27SDimitry Andric 
301706c3fb27SDimitry Andric   // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
301806c3fb27SDimitry Andric   // in the registers. If not go to step 7.
301906c3fb27SDimitry Andric   if (!neededInt && !neededSSE)
302006c3fb27SDimitry Andric     return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
302106c3fb27SDimitry Andric 
302206c3fb27SDimitry Andric   // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
302306c3fb27SDimitry Andric   // general purpose registers needed to pass type and num_fp to hold
302406c3fb27SDimitry Andric   // the number of floating point registers needed.
302506c3fb27SDimitry Andric 
302606c3fb27SDimitry Andric   // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
302706c3fb27SDimitry Andric   // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
302806c3fb27SDimitry Andric   // l->fp_offset > 304 - num_fp * 16 go to step 7.
302906c3fb27SDimitry Andric   //
303006c3fb27SDimitry Andric   // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
303106c3fb27SDimitry Andric   // register save space).
303206c3fb27SDimitry Andric 
303306c3fb27SDimitry Andric   llvm::Value *InRegs = nullptr;
303406c3fb27SDimitry Andric   Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
303506c3fb27SDimitry Andric   llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
303606c3fb27SDimitry Andric   if (neededInt) {
303706c3fb27SDimitry Andric     gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
303806c3fb27SDimitry Andric     gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
303906c3fb27SDimitry Andric     InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
304006c3fb27SDimitry Andric     InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
304106c3fb27SDimitry Andric   }
304206c3fb27SDimitry Andric 
304306c3fb27SDimitry Andric   if (neededSSE) {
304406c3fb27SDimitry Andric     fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
304506c3fb27SDimitry Andric     fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
304606c3fb27SDimitry Andric     llvm::Value *FitsInFP =
304706c3fb27SDimitry Andric       llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
304806c3fb27SDimitry Andric     FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
304906c3fb27SDimitry Andric     InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
305006c3fb27SDimitry Andric   }
305106c3fb27SDimitry Andric 
305206c3fb27SDimitry Andric   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
305306c3fb27SDimitry Andric   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
305406c3fb27SDimitry Andric   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
305506c3fb27SDimitry Andric   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
305606c3fb27SDimitry Andric 
305706c3fb27SDimitry Andric   // Emit code to load the value if it was passed in registers.
305806c3fb27SDimitry Andric 
305906c3fb27SDimitry Andric   CGF.EmitBlock(InRegBlock);
306006c3fb27SDimitry Andric 
306106c3fb27SDimitry Andric   // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
306206c3fb27SDimitry Andric   // an offset of l->gp_offset and/or l->fp_offset. This may require
306306c3fb27SDimitry Andric   // copying to a temporary location in case the parameter is passed
306406c3fb27SDimitry Andric   // in different register classes or requires an alignment greater
306506c3fb27SDimitry Andric   // than 8 for general purpose registers and 16 for XMM registers.
306606c3fb27SDimitry Andric   //
306706c3fb27SDimitry Andric   // FIXME: This really results in shameful code when we end up needing to
306806c3fb27SDimitry Andric   // collect arguments from different places; often what should result in a
306906c3fb27SDimitry Andric   // simple assembling of a structure from scattered addresses has many more
307006c3fb27SDimitry Andric   // loads than necessary. Can we clean this up?
307106c3fb27SDimitry Andric   llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
307206c3fb27SDimitry Andric   llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
307306c3fb27SDimitry Andric       CGF.Builder.CreateStructGEP(VAListAddr, 3), "reg_save_area");
307406c3fb27SDimitry Andric 
307506c3fb27SDimitry Andric   Address RegAddr = Address::invalid();
307606c3fb27SDimitry Andric   if (neededInt && neededSSE) {
307706c3fb27SDimitry Andric     // FIXME: Cleanup.
307806c3fb27SDimitry Andric     assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
307906c3fb27SDimitry Andric     llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
308006c3fb27SDimitry Andric     Address Tmp = CGF.CreateMemTemp(Ty);
308106c3fb27SDimitry Andric     Tmp = Tmp.withElementType(ST);
308206c3fb27SDimitry Andric     assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
308306c3fb27SDimitry Andric     llvm::Type *TyLo = ST->getElementType(0);
308406c3fb27SDimitry Andric     llvm::Type *TyHi = ST->getElementType(1);
308506c3fb27SDimitry Andric     assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
308606c3fb27SDimitry Andric            "Unexpected ABI info for mixed regs");
308706c3fb27SDimitry Andric     llvm::Value *GPAddr =
308806c3fb27SDimitry Andric         CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, gp_offset);
308906c3fb27SDimitry Andric     llvm::Value *FPAddr =
309006c3fb27SDimitry Andric         CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, fp_offset);
309106c3fb27SDimitry Andric     llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
309206c3fb27SDimitry Andric     llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
309306c3fb27SDimitry Andric 
309406c3fb27SDimitry Andric     // Copy the first element.
309506c3fb27SDimitry Andric     // FIXME: Our choice of alignment here and below is probably pessimistic.
309606c3fb27SDimitry Andric     llvm::Value *V = CGF.Builder.CreateAlignedLoad(
30975f757f3fSDimitry Andric         TyLo, RegLoAddr,
309806c3fb27SDimitry Andric         CharUnits::fromQuantity(getDataLayout().getABITypeAlign(TyLo)));
309906c3fb27SDimitry Andric     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
310006c3fb27SDimitry Andric 
310106c3fb27SDimitry Andric     // Copy the second element.
310206c3fb27SDimitry Andric     V = CGF.Builder.CreateAlignedLoad(
31035f757f3fSDimitry Andric         TyHi, RegHiAddr,
310406c3fb27SDimitry Andric         CharUnits::fromQuantity(getDataLayout().getABITypeAlign(TyHi)));
310506c3fb27SDimitry Andric     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
310606c3fb27SDimitry Andric 
310706c3fb27SDimitry Andric     RegAddr = Tmp.withElementType(LTy);
310806c3fb27SDimitry Andric   } else if (neededInt) {
310906c3fb27SDimitry Andric     RegAddr = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, gp_offset),
311006c3fb27SDimitry Andric                       LTy, CharUnits::fromQuantity(8));
311106c3fb27SDimitry Andric 
311206c3fb27SDimitry Andric     // Copy to a temporary if necessary to ensure the appropriate alignment.
311306c3fb27SDimitry Andric     auto TInfo = getContext().getTypeInfoInChars(Ty);
311406c3fb27SDimitry Andric     uint64_t TySize = TInfo.Width.getQuantity();
311506c3fb27SDimitry Andric     CharUnits TyAlign = TInfo.Align;
311606c3fb27SDimitry Andric 
311706c3fb27SDimitry Andric     // Copy into a temporary if the type is more aligned than the
311806c3fb27SDimitry Andric     // register save area.
311906c3fb27SDimitry Andric     if (TyAlign.getQuantity() > 8) {
312006c3fb27SDimitry Andric       Address Tmp = CGF.CreateMemTemp(Ty);
312106c3fb27SDimitry Andric       CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
312206c3fb27SDimitry Andric       RegAddr = Tmp;
312306c3fb27SDimitry Andric     }
312406c3fb27SDimitry Andric 
312506c3fb27SDimitry Andric   } else if (neededSSE == 1) {
312606c3fb27SDimitry Andric     RegAddr = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, fp_offset),
312706c3fb27SDimitry Andric                       LTy, CharUnits::fromQuantity(16));
312806c3fb27SDimitry Andric   } else {
312906c3fb27SDimitry Andric     assert(neededSSE == 2 && "Invalid number of needed registers!");
313006c3fb27SDimitry Andric     // SSE registers are spaced 16 bytes apart in the register save
313106c3fb27SDimitry Andric     // area, we need to collect the two eightbytes together.
313206c3fb27SDimitry Andric     // The ABI isn't explicit about this, but it seems reasonable
313306c3fb27SDimitry Andric     // to assume that the slots are 16-byte aligned, since the stack is
313406c3fb27SDimitry Andric     // naturally 16-byte aligned and the prologue is expected to store
313506c3fb27SDimitry Andric     // all the SSE registers to the RSA.
313606c3fb27SDimitry Andric     Address RegAddrLo = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea,
313706c3fb27SDimitry Andric                                                       fp_offset),
313806c3fb27SDimitry Andric                                 CGF.Int8Ty, CharUnits::fromQuantity(16));
313906c3fb27SDimitry Andric     Address RegAddrHi =
314006c3fb27SDimitry Andric       CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
314106c3fb27SDimitry Andric                                              CharUnits::fromQuantity(16));
314206c3fb27SDimitry Andric     llvm::Type *ST = AI.canHaveCoerceToType()
314306c3fb27SDimitry Andric                          ? AI.getCoerceToType()
314406c3fb27SDimitry Andric                          : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy);
314506c3fb27SDimitry Andric     llvm::Value *V;
314606c3fb27SDimitry Andric     Address Tmp = CGF.CreateMemTemp(Ty);
314706c3fb27SDimitry Andric     Tmp = Tmp.withElementType(ST);
314806c3fb27SDimitry Andric     V = CGF.Builder.CreateLoad(
314906c3fb27SDimitry Andric         RegAddrLo.withElementType(ST->getStructElementType(0)));
315006c3fb27SDimitry Andric     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
315106c3fb27SDimitry Andric     V = CGF.Builder.CreateLoad(
315206c3fb27SDimitry Andric         RegAddrHi.withElementType(ST->getStructElementType(1)));
315306c3fb27SDimitry Andric     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
315406c3fb27SDimitry Andric 
315506c3fb27SDimitry Andric     RegAddr = Tmp.withElementType(LTy);
315606c3fb27SDimitry Andric   }
315706c3fb27SDimitry Andric 
315806c3fb27SDimitry Andric   // AMD64-ABI 3.5.7p5: Step 5. Set:
315906c3fb27SDimitry Andric   // l->gp_offset = l->gp_offset + num_gp * 8
316006c3fb27SDimitry Andric   // l->fp_offset = l->fp_offset + num_fp * 16.
316106c3fb27SDimitry Andric   if (neededInt) {
316206c3fb27SDimitry Andric     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
316306c3fb27SDimitry Andric     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
316406c3fb27SDimitry Andric                             gp_offset_p);
316506c3fb27SDimitry Andric   }
316606c3fb27SDimitry Andric   if (neededSSE) {
316706c3fb27SDimitry Andric     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
316806c3fb27SDimitry Andric     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
316906c3fb27SDimitry Andric                             fp_offset_p);
317006c3fb27SDimitry Andric   }
317106c3fb27SDimitry Andric   CGF.EmitBranch(ContBlock);
317206c3fb27SDimitry Andric 
317306c3fb27SDimitry Andric   // Emit code to load the value if it was passed in memory.
317406c3fb27SDimitry Andric 
317506c3fb27SDimitry Andric   CGF.EmitBlock(InMemBlock);
317606c3fb27SDimitry Andric   Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
317706c3fb27SDimitry Andric 
317806c3fb27SDimitry Andric   // Return the appropriate result.
317906c3fb27SDimitry Andric 
318006c3fb27SDimitry Andric   CGF.EmitBlock(ContBlock);
318106c3fb27SDimitry Andric   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
318206c3fb27SDimitry Andric                                  "vaarg.addr");
318306c3fb27SDimitry Andric   return ResAddr;
318406c3fb27SDimitry Andric }
318506c3fb27SDimitry Andric 
318606c3fb27SDimitry Andric Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
318706c3fb27SDimitry Andric                                    QualType Ty) const {
318806c3fb27SDimitry Andric   // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
318906c3fb27SDimitry Andric   // not 1, 2, 4, or 8 bytes, must be passed by reference."
319006c3fb27SDimitry Andric   uint64_t Width = getContext().getTypeSize(Ty);
319106c3fb27SDimitry Andric   bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
319206c3fb27SDimitry Andric 
319306c3fb27SDimitry Andric   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
319406c3fb27SDimitry Andric                           CGF.getContext().getTypeInfoInChars(Ty),
319506c3fb27SDimitry Andric                           CharUnits::fromQuantity(8),
319606c3fb27SDimitry Andric                           /*allowHigherAlign*/ false);
319706c3fb27SDimitry Andric }
319806c3fb27SDimitry Andric 
319906c3fb27SDimitry Andric ABIArgInfo WinX86_64ABIInfo::reclassifyHvaArgForVectorCall(
320006c3fb27SDimitry Andric     QualType Ty, unsigned &FreeSSERegs, const ABIArgInfo &current) const {
320106c3fb27SDimitry Andric   const Type *Base = nullptr;
320206c3fb27SDimitry Andric   uint64_t NumElts = 0;
320306c3fb27SDimitry Andric 
320406c3fb27SDimitry Andric   if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
320506c3fb27SDimitry Andric       isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
320606c3fb27SDimitry Andric     FreeSSERegs -= NumElts;
320706c3fb27SDimitry Andric     return getDirectX86Hva();
320806c3fb27SDimitry Andric   }
320906c3fb27SDimitry Andric   return current;
321006c3fb27SDimitry Andric }
321106c3fb27SDimitry Andric 
321206c3fb27SDimitry Andric ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
321306c3fb27SDimitry Andric                                       bool IsReturnType, bool IsVectorCall,
321406c3fb27SDimitry Andric                                       bool IsRegCall) const {
321506c3fb27SDimitry Andric 
321606c3fb27SDimitry Andric   if (Ty->isVoidType())
321706c3fb27SDimitry Andric     return ABIArgInfo::getIgnore();
321806c3fb27SDimitry Andric 
321906c3fb27SDimitry Andric   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
322006c3fb27SDimitry Andric     Ty = EnumTy->getDecl()->getIntegerType();
322106c3fb27SDimitry Andric 
322206c3fb27SDimitry Andric   TypeInfo Info = getContext().getTypeInfo(Ty);
322306c3fb27SDimitry Andric   uint64_t Width = Info.Width;
322406c3fb27SDimitry Andric   CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
322506c3fb27SDimitry Andric 
322606c3fb27SDimitry Andric   const RecordType *RT = Ty->getAs<RecordType>();
322706c3fb27SDimitry Andric   if (RT) {
322806c3fb27SDimitry Andric     if (!IsReturnType) {
322906c3fb27SDimitry Andric       if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
323006c3fb27SDimitry Andric         return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
323106c3fb27SDimitry Andric     }
323206c3fb27SDimitry Andric 
323306c3fb27SDimitry Andric     if (RT->getDecl()->hasFlexibleArrayMember())
323406c3fb27SDimitry Andric       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
323506c3fb27SDimitry Andric 
323606c3fb27SDimitry Andric   }
323706c3fb27SDimitry Andric 
323806c3fb27SDimitry Andric   const Type *Base = nullptr;
323906c3fb27SDimitry Andric   uint64_t NumElts = 0;
324006c3fb27SDimitry Andric   // vectorcall adds the concept of a homogenous vector aggregate, similar to
324106c3fb27SDimitry Andric   // other targets.
324206c3fb27SDimitry Andric   if ((IsVectorCall || IsRegCall) &&
324306c3fb27SDimitry Andric       isHomogeneousAggregate(Ty, Base, NumElts)) {
324406c3fb27SDimitry Andric     if (IsRegCall) {
324506c3fb27SDimitry Andric       if (FreeSSERegs >= NumElts) {
324606c3fb27SDimitry Andric         FreeSSERegs -= NumElts;
324706c3fb27SDimitry Andric         if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
324806c3fb27SDimitry Andric           return ABIArgInfo::getDirect();
324906c3fb27SDimitry Andric         return ABIArgInfo::getExpand();
325006c3fb27SDimitry Andric       }
325106c3fb27SDimitry Andric       return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
325206c3fb27SDimitry Andric     } else if (IsVectorCall) {
325306c3fb27SDimitry Andric       if (FreeSSERegs >= NumElts &&
325406c3fb27SDimitry Andric           (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
325506c3fb27SDimitry Andric         FreeSSERegs -= NumElts;
325606c3fb27SDimitry Andric         return ABIArgInfo::getDirect();
325706c3fb27SDimitry Andric       } else if (IsReturnType) {
325806c3fb27SDimitry Andric         return ABIArgInfo::getExpand();
325906c3fb27SDimitry Andric       } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
326006c3fb27SDimitry Andric         // HVAs are delayed and reclassified in the 2nd step.
326106c3fb27SDimitry Andric         return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
326206c3fb27SDimitry Andric       }
326306c3fb27SDimitry Andric     }
326406c3fb27SDimitry Andric   }
326506c3fb27SDimitry Andric 
326606c3fb27SDimitry Andric   if (Ty->isMemberPointerType()) {
326706c3fb27SDimitry Andric     // If the member pointer is represented by an LLVM int or ptr, pass it
326806c3fb27SDimitry Andric     // directly.
326906c3fb27SDimitry Andric     llvm::Type *LLTy = CGT.ConvertType(Ty);
327006c3fb27SDimitry Andric     if (LLTy->isPointerTy() || LLTy->isIntegerTy())
327106c3fb27SDimitry Andric       return ABIArgInfo::getDirect();
327206c3fb27SDimitry Andric   }
327306c3fb27SDimitry Andric 
327406c3fb27SDimitry Andric   if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
327506c3fb27SDimitry Andric     // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
327606c3fb27SDimitry Andric     // not 1, 2, 4, or 8 bytes, must be passed by reference."
327706c3fb27SDimitry Andric     if (Width > 64 || !llvm::isPowerOf2_64(Width))
327806c3fb27SDimitry Andric       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
327906c3fb27SDimitry Andric 
328006c3fb27SDimitry Andric     // Otherwise, coerce it to a small integer.
328106c3fb27SDimitry Andric     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
328206c3fb27SDimitry Andric   }
328306c3fb27SDimitry Andric 
328406c3fb27SDimitry Andric   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
328506c3fb27SDimitry Andric     switch (BT->getKind()) {
328606c3fb27SDimitry Andric     case BuiltinType::Bool:
328706c3fb27SDimitry Andric       // Bool type is always extended to the ABI, other builtin types are not
328806c3fb27SDimitry Andric       // extended.
328906c3fb27SDimitry Andric       return ABIArgInfo::getExtend(Ty);
329006c3fb27SDimitry Andric 
329106c3fb27SDimitry Andric     case BuiltinType::LongDouble:
329206c3fb27SDimitry Andric       // Mingw64 GCC uses the old 80 bit extended precision floating point
329306c3fb27SDimitry Andric       // unit. It passes them indirectly through memory.
329406c3fb27SDimitry Andric       if (IsMingw64) {
329506c3fb27SDimitry Andric         const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
329606c3fb27SDimitry Andric         if (LDF == &llvm::APFloat::x87DoubleExtended())
329706c3fb27SDimitry Andric           return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
329806c3fb27SDimitry Andric       }
329906c3fb27SDimitry Andric       break;
330006c3fb27SDimitry Andric 
330106c3fb27SDimitry Andric     case BuiltinType::Int128:
330206c3fb27SDimitry Andric     case BuiltinType::UInt128:
330306c3fb27SDimitry Andric       // If it's a parameter type, the normal ABI rule is that arguments larger
330406c3fb27SDimitry Andric       // than 8 bytes are passed indirectly. GCC follows it. We follow it too,
330506c3fb27SDimitry Andric       // even though it isn't particularly efficient.
330606c3fb27SDimitry Andric       if (!IsReturnType)
330706c3fb27SDimitry Andric         return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
330806c3fb27SDimitry Andric 
330906c3fb27SDimitry Andric       // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that.
331006c3fb27SDimitry Andric       // Clang matches them for compatibility.
331106c3fb27SDimitry Andric       return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
331206c3fb27SDimitry Andric           llvm::Type::getInt64Ty(getVMContext()), 2));
331306c3fb27SDimitry Andric 
331406c3fb27SDimitry Andric     default:
331506c3fb27SDimitry Andric       break;
331606c3fb27SDimitry Andric     }
331706c3fb27SDimitry Andric   }
331806c3fb27SDimitry Andric 
331906c3fb27SDimitry Andric   if (Ty->isBitIntType()) {
332006c3fb27SDimitry Andric     // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
332106c3fb27SDimitry Andric     // not 1, 2, 4, or 8 bytes, must be passed by reference."
332206c3fb27SDimitry Andric     // However, non-power-of-two bit-precise integers will be passed as 1, 2, 4,
332306c3fb27SDimitry Andric     // or 8 bytes anyway as long is it fits in them, so we don't have to check
332406c3fb27SDimitry Andric     // the power of 2.
332506c3fb27SDimitry Andric     if (Width <= 64)
332606c3fb27SDimitry Andric       return ABIArgInfo::getDirect();
332706c3fb27SDimitry Andric     return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
332806c3fb27SDimitry Andric   }
332906c3fb27SDimitry Andric 
333006c3fb27SDimitry Andric   return ABIArgInfo::getDirect();
333106c3fb27SDimitry Andric }
333206c3fb27SDimitry Andric 
333306c3fb27SDimitry Andric void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
333406c3fb27SDimitry Andric   const unsigned CC = FI.getCallingConvention();
333506c3fb27SDimitry Andric   bool IsVectorCall = CC == llvm::CallingConv::X86_VectorCall;
333606c3fb27SDimitry Andric   bool IsRegCall = CC == llvm::CallingConv::X86_RegCall;
333706c3fb27SDimitry Andric 
333806c3fb27SDimitry Andric   // If __attribute__((sysv_abi)) is in use, use the SysV argument
333906c3fb27SDimitry Andric   // classification rules.
334006c3fb27SDimitry Andric   if (CC == llvm::CallingConv::X86_64_SysV) {
334106c3fb27SDimitry Andric     X86_64ABIInfo SysVABIInfo(CGT, AVXLevel);
334206c3fb27SDimitry Andric     SysVABIInfo.computeInfo(FI);
334306c3fb27SDimitry Andric     return;
334406c3fb27SDimitry Andric   }
334506c3fb27SDimitry Andric 
334606c3fb27SDimitry Andric   unsigned FreeSSERegs = 0;
334706c3fb27SDimitry Andric   if (IsVectorCall) {
334806c3fb27SDimitry Andric     // We can use up to 4 SSE return registers with vectorcall.
334906c3fb27SDimitry Andric     FreeSSERegs = 4;
335006c3fb27SDimitry Andric   } else if (IsRegCall) {
335106c3fb27SDimitry Andric     // RegCall gives us 16 SSE registers.
335206c3fb27SDimitry Andric     FreeSSERegs = 16;
335306c3fb27SDimitry Andric   }
335406c3fb27SDimitry Andric 
335506c3fb27SDimitry Andric   if (!getCXXABI().classifyReturnType(FI))
335606c3fb27SDimitry Andric     FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
335706c3fb27SDimitry Andric                                   IsVectorCall, IsRegCall);
335806c3fb27SDimitry Andric 
335906c3fb27SDimitry Andric   if (IsVectorCall) {
336006c3fb27SDimitry Andric     // We can use up to 6 SSE register parameters with vectorcall.
336106c3fb27SDimitry Andric     FreeSSERegs = 6;
336206c3fb27SDimitry Andric   } else if (IsRegCall) {
336306c3fb27SDimitry Andric     // RegCall gives us 16 SSE registers, we can reuse the return registers.
336406c3fb27SDimitry Andric     FreeSSERegs = 16;
336506c3fb27SDimitry Andric   }
336606c3fb27SDimitry Andric 
336706c3fb27SDimitry Andric   unsigned ArgNum = 0;
336806c3fb27SDimitry Andric   unsigned ZeroSSERegs = 0;
336906c3fb27SDimitry Andric   for (auto &I : FI.arguments()) {
337006c3fb27SDimitry Andric     // Vectorcall in x64 only permits the first 6 arguments to be passed as
337106c3fb27SDimitry Andric     // XMM/YMM registers. After the sixth argument, pretend no vector
337206c3fb27SDimitry Andric     // registers are left.
337306c3fb27SDimitry Andric     unsigned *MaybeFreeSSERegs =
337406c3fb27SDimitry Andric         (IsVectorCall && ArgNum >= 6) ? &ZeroSSERegs : &FreeSSERegs;
337506c3fb27SDimitry Andric     I.info =
337606c3fb27SDimitry Andric         classify(I.type, *MaybeFreeSSERegs, false, IsVectorCall, IsRegCall);
337706c3fb27SDimitry Andric     ++ArgNum;
337806c3fb27SDimitry Andric   }
337906c3fb27SDimitry Andric 
338006c3fb27SDimitry Andric   if (IsVectorCall) {
338106c3fb27SDimitry Andric     // For vectorcall, assign aggregate HVAs to any free vector registers in a
338206c3fb27SDimitry Andric     // second pass.
338306c3fb27SDimitry Andric     for (auto &I : FI.arguments())
338406c3fb27SDimitry Andric       I.info = reclassifyHvaArgForVectorCall(I.type, FreeSSERegs, I.info);
338506c3fb27SDimitry Andric   }
338606c3fb27SDimitry Andric }
338706c3fb27SDimitry Andric 
338806c3fb27SDimitry Andric Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
338906c3fb27SDimitry Andric                                     QualType Ty) const {
339006c3fb27SDimitry Andric   // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
339106c3fb27SDimitry Andric   // not 1, 2, 4, or 8 bytes, must be passed by reference."
339206c3fb27SDimitry Andric   uint64_t Width = getContext().getTypeSize(Ty);
339306c3fb27SDimitry Andric   bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
339406c3fb27SDimitry Andric 
339506c3fb27SDimitry Andric   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
339606c3fb27SDimitry Andric                           CGF.getContext().getTypeInfoInChars(Ty),
339706c3fb27SDimitry Andric                           CharUnits::fromQuantity(8),
339806c3fb27SDimitry Andric                           /*allowHigherAlign*/ false);
339906c3fb27SDimitry Andric }
340006c3fb27SDimitry Andric 
340106c3fb27SDimitry Andric std::unique_ptr<TargetCodeGenInfo> CodeGen::createX86_32TargetCodeGenInfo(
340206c3fb27SDimitry Andric     CodeGenModule &CGM, bool DarwinVectorABI, bool Win32StructABI,
340306c3fb27SDimitry Andric     unsigned NumRegisterParameters, bool SoftFloatABI) {
340406c3fb27SDimitry Andric   bool RetSmallStructInRegABI = X86_32TargetCodeGenInfo::isStructReturnInRegABI(
340506c3fb27SDimitry Andric       CGM.getTriple(), CGM.getCodeGenOpts());
340606c3fb27SDimitry Andric   return std::make_unique<X86_32TargetCodeGenInfo>(
340706c3fb27SDimitry Andric       CGM.getTypes(), DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
340806c3fb27SDimitry Andric       NumRegisterParameters, SoftFloatABI);
340906c3fb27SDimitry Andric }
341006c3fb27SDimitry Andric 
341106c3fb27SDimitry Andric std::unique_ptr<TargetCodeGenInfo> CodeGen::createWinX86_32TargetCodeGenInfo(
341206c3fb27SDimitry Andric     CodeGenModule &CGM, bool DarwinVectorABI, bool Win32StructABI,
341306c3fb27SDimitry Andric     unsigned NumRegisterParameters) {
341406c3fb27SDimitry Andric   bool RetSmallStructInRegABI = X86_32TargetCodeGenInfo::isStructReturnInRegABI(
341506c3fb27SDimitry Andric       CGM.getTriple(), CGM.getCodeGenOpts());
341606c3fb27SDimitry Andric   return std::make_unique<WinX86_32TargetCodeGenInfo>(
341706c3fb27SDimitry Andric       CGM.getTypes(), DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
341806c3fb27SDimitry Andric       NumRegisterParameters);
341906c3fb27SDimitry Andric }
342006c3fb27SDimitry Andric 
342106c3fb27SDimitry Andric std::unique_ptr<TargetCodeGenInfo>
342206c3fb27SDimitry Andric CodeGen::createX86_64TargetCodeGenInfo(CodeGenModule &CGM,
342306c3fb27SDimitry Andric                                        X86AVXABILevel AVXLevel) {
342406c3fb27SDimitry Andric   return std::make_unique<X86_64TargetCodeGenInfo>(CGM.getTypes(), AVXLevel);
342506c3fb27SDimitry Andric }
342606c3fb27SDimitry Andric 
342706c3fb27SDimitry Andric std::unique_ptr<TargetCodeGenInfo>
342806c3fb27SDimitry Andric CodeGen::createWinX86_64TargetCodeGenInfo(CodeGenModule &CGM,
342906c3fb27SDimitry Andric                                           X86AVXABILevel AVXLevel) {
343006c3fb27SDimitry Andric   return std::make_unique<WinX86_64TargetCodeGenInfo>(CGM.getTypes(), AVXLevel);
343106c3fb27SDimitry Andric }
3432