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