1 //===---- TargetInfo.cpp - Encapsulate target details -----------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // These classes wrap the information about a call or function
10 // definition used to handle ABI compliancy.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "TargetInfo.h"
15 #include "ABIInfo.h"
16 #include "CGBlocks.h"
17 #include "CGCXXABI.h"
18 #include "CGValue.h"
19 #include "CodeGenFunction.h"
20 #include "clang/AST/Attr.h"
21 #include "clang/AST/RecordLayout.h"
22 #include "clang/Basic/CodeGenOptions.h"
23 #include "clang/Basic/DiagnosticFrontend.h"
24 #include "clang/Basic/Builtins.h"
25 #include "clang/CodeGen/CGFunctionInfo.h"
26 #include "clang/CodeGen/SwiftCallingConv.h"
27 #include "llvm/ADT/SmallBitVector.h"
28 #include "llvm/ADT/StringExtras.h"
29 #include "llvm/ADT/StringSwitch.h"
30 #include "llvm/ADT/Triple.h"
31 #include "llvm/ADT/Twine.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/IntrinsicsNVPTX.h"
34 #include "llvm/IR/IntrinsicsS390.h"
35 #include "llvm/IR/Type.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include <algorithm> // std::sort
38 
39 using namespace clang;
40 using namespace CodeGen;
41 
42 // Helper for coercing an aggregate argument or return value into an integer
43 // array of the same size (including padding) and alignment.  This alternate
44 // coercion happens only for the RenderScript ABI and can be removed after
45 // runtimes that rely on it are no longer supported.
46 //
47 // RenderScript assumes that the size of the argument / return value in the IR
48 // is the same as the size of the corresponding qualified type. This helper
49 // coerces the aggregate type into an array of the same size (including
50 // padding).  This coercion is used in lieu of expansion of struct members or
51 // other canonical coercions that return a coerced-type of larger size.
52 //
53 // Ty          - The argument / return value type
54 // Context     - The associated ASTContext
55 // LLVMContext - The associated LLVMContext
56 static ABIArgInfo coerceToIntArray(QualType Ty,
57                                    ASTContext &Context,
58                                    llvm::LLVMContext &LLVMContext) {
59   // Alignment and Size are measured in bits.
60   const uint64_t Size = Context.getTypeSize(Ty);
61   const uint64_t Alignment = Context.getTypeAlign(Ty);
62   llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Alignment);
63   const uint64_t NumElements = (Size + Alignment - 1) / Alignment;
64   return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
65 }
66 
67 static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
68                                llvm::Value *Array,
69                                llvm::Value *Value,
70                                unsigned FirstIndex,
71                                unsigned LastIndex) {
72   // Alternatively, we could emit this as a loop in the source.
73   for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
74     llvm::Value *Cell =
75         Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I);
76     Builder.CreateAlignedStore(Value, Cell, CharUnits::One());
77   }
78 }
79 
80 static bool isAggregateTypeForABI(QualType T) {
81   return !CodeGenFunction::hasScalarEvaluationKind(T) ||
82          T->isMemberFunctionPointerType();
83 }
84 
85 ABIArgInfo ABIInfo::getNaturalAlignIndirect(QualType Ty, bool ByVal,
86                                             bool Realign,
87                                             llvm::Type *Padding) const {
88   return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty), ByVal,
89                                  Realign, Padding);
90 }
91 
92 ABIArgInfo
93 ABIInfo::getNaturalAlignIndirectInReg(QualType Ty, bool Realign) const {
94   return ABIArgInfo::getIndirectInReg(getContext().getTypeAlignInChars(Ty),
95                                       /*ByVal*/ false, Realign);
96 }
97 
98 Address ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
99                              QualType Ty) const {
100   return Address::invalid();
101 }
102 
103 bool ABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const {
104   if (Ty->isPromotableIntegerType())
105     return true;
106 
107   if (const auto *EIT = Ty->getAs<BitIntType>())
108     if (EIT->getNumBits() < getContext().getTypeSize(getContext().IntTy))
109       return true;
110 
111   return false;
112 }
113 
114 ABIInfo::~ABIInfo() {}
115 
116 /// Does the given lowering require more than the given number of
117 /// registers when expanded?
118 ///
119 /// This is intended to be the basis of a reasonable basic implementation
120 /// of should{Pass,Return}IndirectlyForSwift.
121 ///
122 /// For most targets, a limit of four total registers is reasonable; this
123 /// limits the amount of code required in order to move around the value
124 /// in case it wasn't produced immediately prior to the call by the caller
125 /// (or wasn't produced in exactly the right registers) or isn't used
126 /// immediately within the callee.  But some targets may need to further
127 /// limit the register count due to an inability to support that many
128 /// return registers.
129 static bool occupiesMoreThan(CodeGenTypes &cgt,
130                              ArrayRef<llvm::Type*> scalarTypes,
131                              unsigned maxAllRegisters) {
132   unsigned intCount = 0, fpCount = 0;
133   for (llvm::Type *type : scalarTypes) {
134     if (type->isPointerTy()) {
135       intCount++;
136     } else if (auto intTy = dyn_cast<llvm::IntegerType>(type)) {
137       auto ptrWidth = cgt.getTarget().getPointerWidth(0);
138       intCount += (intTy->getBitWidth() + ptrWidth - 1) / ptrWidth;
139     } else {
140       assert(type->isVectorTy() || type->isFloatingPointTy());
141       fpCount++;
142     }
143   }
144 
145   return (intCount + fpCount > maxAllRegisters);
146 }
147 
148 bool SwiftABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
149                                              llvm::Type *eltTy,
150                                              unsigned numElts) const {
151   // The default implementation of this assumes that the target guarantees
152   // 128-bit SIMD support but nothing more.
153   return (vectorSize.getQuantity() > 8 && vectorSize.getQuantity() <= 16);
154 }
155 
156 static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
157                                               CGCXXABI &CXXABI) {
158   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
159   if (!RD) {
160     if (!RT->getDecl()->canPassInRegisters())
161       return CGCXXABI::RAA_Indirect;
162     return CGCXXABI::RAA_Default;
163   }
164   return CXXABI.getRecordArgABI(RD);
165 }
166 
167 static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
168                                               CGCXXABI &CXXABI) {
169   const RecordType *RT = T->getAs<RecordType>();
170   if (!RT)
171     return CGCXXABI::RAA_Default;
172   return getRecordArgABI(RT, CXXABI);
173 }
174 
175 static bool classifyReturnType(const CGCXXABI &CXXABI, CGFunctionInfo &FI,
176                                const ABIInfo &Info) {
177   QualType Ty = FI.getReturnType();
178 
179   if (const auto *RT = Ty->getAs<RecordType>())
180     if (!isa<CXXRecordDecl>(RT->getDecl()) &&
181         !RT->getDecl()->canPassInRegisters()) {
182       FI.getReturnInfo() = Info.getNaturalAlignIndirect(Ty);
183       return true;
184     }
185 
186   return CXXABI.classifyReturnType(FI);
187 }
188 
189 /// Pass transparent unions as if they were the type of the first element. Sema
190 /// should ensure that all elements of the union have the same "machine type".
191 static QualType useFirstFieldIfTransparentUnion(QualType Ty) {
192   if (const RecordType *UT = Ty->getAsUnionType()) {
193     const RecordDecl *UD = UT->getDecl();
194     if (UD->hasAttr<TransparentUnionAttr>()) {
195       assert(!UD->field_empty() && "sema created an empty transparent union");
196       return UD->field_begin()->getType();
197     }
198   }
199   return Ty;
200 }
201 
202 CGCXXABI &ABIInfo::getCXXABI() const {
203   return CGT.getCXXABI();
204 }
205 
206 ASTContext &ABIInfo::getContext() const {
207   return CGT.getContext();
208 }
209 
210 llvm::LLVMContext &ABIInfo::getVMContext() const {
211   return CGT.getLLVMContext();
212 }
213 
214 const llvm::DataLayout &ABIInfo::getDataLayout() const {
215   return CGT.getDataLayout();
216 }
217 
218 const TargetInfo &ABIInfo::getTarget() const {
219   return CGT.getTarget();
220 }
221 
222 const CodeGenOptions &ABIInfo::getCodeGenOpts() const {
223   return CGT.getCodeGenOpts();
224 }
225 
226 bool ABIInfo::isAndroid() const { return getTarget().getTriple().isAndroid(); }
227 
228 bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
229   return false;
230 }
231 
232 bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
233                                                 uint64_t Members) const {
234   return false;
235 }
236 
237 LLVM_DUMP_METHOD void ABIArgInfo::dump() const {
238   raw_ostream &OS = llvm::errs();
239   OS << "(ABIArgInfo Kind=";
240   switch (TheKind) {
241   case Direct:
242     OS << "Direct Type=";
243     if (llvm::Type *Ty = getCoerceToType())
244       Ty->print(OS);
245     else
246       OS << "null";
247     break;
248   case Extend:
249     OS << "Extend";
250     break;
251   case Ignore:
252     OS << "Ignore";
253     break;
254   case InAlloca:
255     OS << "InAlloca Offset=" << getInAllocaFieldIndex();
256     break;
257   case Indirect:
258     OS << "Indirect Align=" << getIndirectAlign().getQuantity()
259        << " ByVal=" << getIndirectByVal()
260        << " Realign=" << getIndirectRealign();
261     break;
262   case IndirectAliased:
263     OS << "Indirect Align=" << getIndirectAlign().getQuantity()
264        << " AadrSpace=" << getIndirectAddrSpace()
265        << " Realign=" << getIndirectRealign();
266     break;
267   case Expand:
268     OS << "Expand";
269     break;
270   case CoerceAndExpand:
271     OS << "CoerceAndExpand Type=";
272     getCoerceAndExpandType()->print(OS);
273     break;
274   }
275   OS << ")\n";
276 }
277 
278 // Dynamically round a pointer up to a multiple of the given alignment.
279 static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF,
280                                                   llvm::Value *Ptr,
281                                                   CharUnits Align) {
282   llvm::Value *PtrAsInt = Ptr;
283   // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align;
284   PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy);
285   PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt,
286         llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1));
287   PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt,
288            llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity()));
289   PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt,
290                                         Ptr->getType(),
291                                         Ptr->getName() + ".aligned");
292   return PtrAsInt;
293 }
294 
295 /// Emit va_arg for a platform using the common void* representation,
296 /// where arguments are simply emitted in an array of slots on the stack.
297 ///
298 /// This version implements the core direct-value passing rules.
299 ///
300 /// \param SlotSize - The size and alignment of a stack slot.
301 ///   Each argument will be allocated to a multiple of this number of
302 ///   slots, and all the slots will be aligned to this value.
303 /// \param AllowHigherAlign - The slot alignment is not a cap;
304 ///   an argument type with an alignment greater than the slot size
305 ///   will be emitted on a higher-alignment address, potentially
306 ///   leaving one or more empty slots behind as padding.  If this
307 ///   is false, the returned address might be less-aligned than
308 ///   DirectAlign.
309 static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF,
310                                       Address VAListAddr,
311                                       llvm::Type *DirectTy,
312                                       CharUnits DirectSize,
313                                       CharUnits DirectAlign,
314                                       CharUnits SlotSize,
315                                       bool AllowHigherAlign) {
316   // Cast the element type to i8* if necessary.  Some platforms define
317   // va_list as a struct containing an i8* instead of just an i8*.
318   if (VAListAddr.getElementType() != CGF.Int8PtrTy)
319     VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy);
320 
321   llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur");
322 
323   // If the CC aligns values higher than the slot size, do so if needed.
324   Address Addr = Address::invalid();
325   if (AllowHigherAlign && DirectAlign > SlotSize) {
326     Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign),
327                    CGF.Int8Ty, DirectAlign);
328   } else {
329     Addr = Address(Ptr, CGF.Int8Ty, SlotSize);
330   }
331 
332   // Advance the pointer past the argument, then store that back.
333   CharUnits FullDirectSize = DirectSize.alignTo(SlotSize);
334   Address NextPtr =
335       CGF.Builder.CreateConstInBoundsByteGEP(Addr, FullDirectSize, "argp.next");
336   CGF.Builder.CreateStore(NextPtr.getPointer(), VAListAddr);
337 
338   // If the argument is smaller than a slot, and this is a big-endian
339   // target, the argument will be right-adjusted in its slot.
340   if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() &&
341       !DirectTy->isStructTy()) {
342     Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize);
343   }
344 
345   Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy);
346   return Addr;
347 }
348 
349 /// Emit va_arg for a platform using the common void* representation,
350 /// where arguments are simply emitted in an array of slots on the stack.
351 ///
352 /// \param IsIndirect - Values of this type are passed indirectly.
353 /// \param ValueInfo - The size and alignment of this type, generally
354 ///   computed with getContext().getTypeInfoInChars(ValueTy).
355 /// \param SlotSizeAndAlign - The size and alignment of a stack slot.
356 ///   Each argument will be allocated to a multiple of this number of
357 ///   slots, and all the slots will be aligned to this value.
358 /// \param AllowHigherAlign - The slot alignment is not a cap;
359 ///   an argument type with an alignment greater than the slot size
360 ///   will be emitted on a higher-alignment address, potentially
361 ///   leaving one or more empty slots behind as padding.
362 static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr,
363                                 QualType ValueTy, bool IsIndirect,
364                                 TypeInfoChars ValueInfo,
365                                 CharUnits SlotSizeAndAlign,
366                                 bool AllowHigherAlign) {
367   // The size and alignment of the value that was passed directly.
368   CharUnits DirectSize, DirectAlign;
369   if (IsIndirect) {
370     DirectSize = CGF.getPointerSize();
371     DirectAlign = CGF.getPointerAlign();
372   } else {
373     DirectSize = ValueInfo.Width;
374     DirectAlign = ValueInfo.Align;
375   }
376 
377   // Cast the address we've calculated to the right type.
378   llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy);
379   if (IsIndirect)
380     DirectTy = DirectTy->getPointerTo(0);
381 
382   Address Addr =
383       emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy, DirectSize, DirectAlign,
384                              SlotSizeAndAlign, AllowHigherAlign);
385 
386   if (IsIndirect) {
387     Addr = Address::deprecated(CGF.Builder.CreateLoad(Addr), ValueInfo.Align);
388   }
389 
390   return Addr;
391 }
392 
393 static Address complexTempStructure(CodeGenFunction &CGF, Address VAListAddr,
394                                     QualType Ty, CharUnits SlotSize,
395                                     CharUnits EltSize, const ComplexType *CTy) {
396   Address Addr =
397       emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty, SlotSize * 2,
398                              SlotSize, SlotSize, /*AllowHigher*/ true);
399 
400   Address RealAddr = Addr;
401   Address ImagAddr = RealAddr;
402   if (CGF.CGM.getDataLayout().isBigEndian()) {
403     RealAddr =
404         CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize - EltSize);
405     ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
406                                                       2 * SlotSize - EltSize);
407   } else {
408     ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
409   }
410 
411   llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
412   RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
413   ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
414   llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
415   llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
416 
417   Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
418   CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
419                          /*init*/ true);
420   return Temp;
421 }
422 
423 static Address emitMergePHI(CodeGenFunction &CGF,
424                             Address Addr1, llvm::BasicBlock *Block1,
425                             Address Addr2, llvm::BasicBlock *Block2,
426                             const llvm::Twine &Name = "") {
427   assert(Addr1.getType() == Addr2.getType());
428   llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name);
429   PHI->addIncoming(Addr1.getPointer(), Block1);
430   PHI->addIncoming(Addr2.getPointer(), Block2);
431   CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment());
432   return Address(PHI, Addr1.getElementType(), Align);
433 }
434 
435 TargetCodeGenInfo::~TargetCodeGenInfo() = default;
436 
437 // If someone can figure out a general rule for this, that would be great.
438 // It's probably just doomed to be platform-dependent, though.
439 unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
440   // Verified for:
441   //   x86-64     FreeBSD, Linux, Darwin
442   //   x86-32     FreeBSD, Linux, Darwin
443   //   PowerPC    Linux, Darwin
444   //   ARM        Darwin (*not* EABI)
445   //   AArch64    Linux
446   return 32;
447 }
448 
449 bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
450                                      const FunctionNoProtoType *fnType) const {
451   // The following conventions are known to require this to be false:
452   //   x86_stdcall
453   //   MIPS
454   // For everything else, we just prefer false unless we opt out.
455   return false;
456 }
457 
458 void
459 TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
460                                              llvm::SmallString<24> &Opt) const {
461   // This assumes the user is passing a library name like "rt" instead of a
462   // filename like "librt.a/so", and that they don't care whether it's static or
463   // dynamic.
464   Opt = "-l";
465   Opt += Lib;
466 }
467 
468 unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const {
469   // OpenCL kernels are called via an explicit runtime API with arguments
470   // set with clSetKernelArg(), not as normal sub-functions.
471   // Return SPIR_KERNEL by default as the kernel calling convention to
472   // ensure the fingerprint is fixed such way that each OpenCL argument
473   // gets one matching argument in the produced kernel function argument
474   // list to enable feasible implementation of clSetKernelArg() with
475   // aggregates etc. In case we would use the default C calling conv here,
476   // clSetKernelArg() might break depending on the target-specific
477   // conventions; different targets might split structs passed as values
478   // to multiple function arguments etc.
479   return llvm::CallingConv::SPIR_KERNEL;
480 }
481 
482 llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM,
483     llvm::PointerType *T, QualType QT) const {
484   return llvm::ConstantPointerNull::get(T);
485 }
486 
487 LangAS TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
488                                                    const VarDecl *D) const {
489   assert(!CGM.getLangOpts().OpenCL &&
490          !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
491          "Address space agnostic languages only");
492   return D ? D->getType().getAddressSpace() : LangAS::Default;
493 }
494 
495 llvm::Value *TargetCodeGenInfo::performAddrSpaceCast(
496     CodeGen::CodeGenFunction &CGF, llvm::Value *Src, LangAS SrcAddr,
497     LangAS DestAddr, llvm::Type *DestTy, bool isNonNull) const {
498   // Since target may map different address spaces in AST to the same address
499   // space, an address space conversion may end up as a bitcast.
500   if (auto *C = dyn_cast<llvm::Constant>(Src))
501     return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy);
502   // Try to preserve the source's name to make IR more readable.
503   return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
504       Src, DestTy, Src->hasName() ? Src->getName() + ".ascast" : "");
505 }
506 
507 llvm::Constant *
508 TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src,
509                                         LangAS SrcAddr, LangAS DestAddr,
510                                         llvm::Type *DestTy) const {
511   // Since target may map different address spaces in AST to the same address
512   // space, an address space conversion may end up as a bitcast.
513   return llvm::ConstantExpr::getPointerCast(Src, DestTy);
514 }
515 
516 llvm::SyncScope::ID
517 TargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
518                                       SyncScope Scope,
519                                       llvm::AtomicOrdering Ordering,
520                                       llvm::LLVMContext &Ctx) const {
521   return Ctx.getOrInsertSyncScopeID(""); /* default sync scope */
522 }
523 
524 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
525 
526 /// isEmptyField - Return true iff a the field is "empty", that is it
527 /// is an unnamed bit-field or an (array of) empty record(s).
528 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
529                          bool AllowArrays) {
530   if (FD->isUnnamedBitfield())
531     return true;
532 
533   QualType FT = FD->getType();
534 
535   // Constant arrays of empty records count as empty, strip them off.
536   // Constant arrays of zero length always count as empty.
537   bool WasArray = false;
538   if (AllowArrays)
539     while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
540       if (AT->getSize() == 0)
541         return true;
542       FT = AT->getElementType();
543       // The [[no_unique_address]] special case below does not apply to
544       // arrays of C++ empty records, so we need to remember this fact.
545       WasArray = true;
546     }
547 
548   const RecordType *RT = FT->getAs<RecordType>();
549   if (!RT)
550     return false;
551 
552   // C++ record fields are never empty, at least in the Itanium ABI.
553   //
554   // FIXME: We should use a predicate for whether this behavior is true in the
555   // current ABI.
556   //
557   // The exception to the above rule are fields marked with the
558   // [[no_unique_address]] attribute (since C++20).  Those do count as empty
559   // according to the Itanium ABI.  The exception applies only to records,
560   // not arrays of records, so we must also check whether we stripped off an
561   // array type above.
562   if (isa<CXXRecordDecl>(RT->getDecl()) &&
563       (WasArray || !FD->hasAttr<NoUniqueAddressAttr>()))
564     return false;
565 
566   return isEmptyRecord(Context, FT, AllowArrays);
567 }
568 
569 /// isEmptyRecord - Return true iff a structure contains only empty
570 /// fields. Note that a structure with a flexible array member is not
571 /// considered empty.
572 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
573   const RecordType *RT = T->getAs<RecordType>();
574   if (!RT)
575     return false;
576   const RecordDecl *RD = RT->getDecl();
577   if (RD->hasFlexibleArrayMember())
578     return false;
579 
580   // If this is a C++ record, check the bases first.
581   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
582     for (const auto &I : CXXRD->bases())
583       if (!isEmptyRecord(Context, I.getType(), true))
584         return false;
585 
586   for (const auto *I : RD->fields())
587     if (!isEmptyField(Context, I, AllowArrays))
588       return false;
589   return true;
590 }
591 
592 /// isSingleElementStruct - Determine if a structure is a "single
593 /// element struct", i.e. it has exactly one non-empty field or
594 /// exactly one field which is itself a single element
595 /// struct. Structures with flexible array members are never
596 /// considered single element structs.
597 ///
598 /// \return The field declaration for the single non-empty field, if
599 /// it exists.
600 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
601   const RecordType *RT = T->getAs<RecordType>();
602   if (!RT)
603     return nullptr;
604 
605   const RecordDecl *RD = RT->getDecl();
606   if (RD->hasFlexibleArrayMember())
607     return nullptr;
608 
609   const Type *Found = nullptr;
610 
611   // If this is a C++ record, check the bases first.
612   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
613     for (const auto &I : CXXRD->bases()) {
614       // Ignore empty records.
615       if (isEmptyRecord(Context, I.getType(), true))
616         continue;
617 
618       // If we already found an element then this isn't a single-element struct.
619       if (Found)
620         return nullptr;
621 
622       // If this is non-empty and not a single element struct, the composite
623       // cannot be a single element struct.
624       Found = isSingleElementStruct(I.getType(), Context);
625       if (!Found)
626         return nullptr;
627     }
628   }
629 
630   // Check for single element.
631   for (const auto *FD : RD->fields()) {
632     QualType FT = FD->getType();
633 
634     // Ignore empty fields.
635     if (isEmptyField(Context, FD, true))
636       continue;
637 
638     // If we already found an element then this isn't a single-element
639     // struct.
640     if (Found)
641       return nullptr;
642 
643     // Treat single element arrays as the element.
644     while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
645       if (AT->getSize().getZExtValue() != 1)
646         break;
647       FT = AT->getElementType();
648     }
649 
650     if (!isAggregateTypeForABI(FT)) {
651       Found = FT.getTypePtr();
652     } else {
653       Found = isSingleElementStruct(FT, Context);
654       if (!Found)
655         return nullptr;
656     }
657   }
658 
659   // We don't consider a struct a single-element struct if it has
660   // padding beyond the element type.
661   if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
662     return nullptr;
663 
664   return Found;
665 }
666 
667 namespace {
668 Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
669                        const ABIArgInfo &AI) {
670   // This default implementation defers to the llvm backend's va_arg
671   // instruction. It can handle only passing arguments directly
672   // (typically only handled in the backend for primitive types), or
673   // aggregates passed indirectly by pointer (NOTE: if the "byval"
674   // flag has ABI impact in the callee, this implementation cannot
675   // work.)
676 
677   // Only a few cases are covered here at the moment -- those needed
678   // by the default abi.
679   llvm::Value *Val;
680 
681   if (AI.isIndirect()) {
682     assert(!AI.getPaddingType() &&
683            "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
684     assert(
685         !AI.getIndirectRealign() &&
686         "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!");
687 
688     auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
689     CharUnits TyAlignForABI = TyInfo.Align;
690 
691     llvm::Type *BaseTy =
692         llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
693     llvm::Value *Addr =
694         CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
695     return Address::deprecated(Addr, TyAlignForABI);
696   } else {
697     assert((AI.isDirect() || AI.isExtend()) &&
698            "Unexpected ArgInfo Kind in generic VAArg emitter!");
699 
700     assert(!AI.getInReg() &&
701            "Unexpected InReg seen in arginfo in generic VAArg emitter!");
702     assert(!AI.getPaddingType() &&
703            "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
704     assert(!AI.getDirectOffset() &&
705            "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!");
706     assert(!AI.getCoerceToType() &&
707            "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!");
708 
709     Address Temp = CGF.CreateMemTemp(Ty, "varet");
710     Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(),
711                                   CGF.ConvertTypeForMem(Ty));
712     CGF.Builder.CreateStore(Val, Temp);
713     return Temp;
714   }
715 }
716 
717 /// DefaultABIInfo - The default implementation for ABI specific
718 /// details. This implementation provides information which results in
719 /// self-consistent and sensible LLVM IR generation, but does not
720 /// conform to any particular ABI.
721 class DefaultABIInfo : public ABIInfo {
722 public:
723   DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
724 
725   ABIArgInfo classifyReturnType(QualType RetTy) const;
726   ABIArgInfo classifyArgumentType(QualType RetTy) const;
727 
728   void computeInfo(CGFunctionInfo &FI) const override {
729     if (!getCXXABI().classifyReturnType(FI))
730       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
731     for (auto &I : FI.arguments())
732       I.info = classifyArgumentType(I.type);
733   }
734 
735   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
736                     QualType Ty) const override {
737     return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
738   }
739 };
740 
741 class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
742 public:
743   DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
744       : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {}
745 };
746 
747 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
748   Ty = useFirstFieldIfTransparentUnion(Ty);
749 
750   if (isAggregateTypeForABI(Ty)) {
751     // Records with non-trivial destructors/copy-constructors should not be
752     // passed by value.
753     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
754       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
755 
756     return getNaturalAlignIndirect(Ty);
757   }
758 
759   // Treat an enum type as its underlying type.
760   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
761     Ty = EnumTy->getDecl()->getIntegerType();
762 
763   ASTContext &Context = getContext();
764   if (const auto *EIT = Ty->getAs<BitIntType>())
765     if (EIT->getNumBits() >
766         Context.getTypeSize(Context.getTargetInfo().hasInt128Type()
767                                 ? Context.Int128Ty
768                                 : Context.LongLongTy))
769       return getNaturalAlignIndirect(Ty);
770 
771   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
772                                             : ABIArgInfo::getDirect());
773 }
774 
775 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
776   if (RetTy->isVoidType())
777     return ABIArgInfo::getIgnore();
778 
779   if (isAggregateTypeForABI(RetTy))
780     return getNaturalAlignIndirect(RetTy);
781 
782   // Treat an enum type as its underlying type.
783   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
784     RetTy = EnumTy->getDecl()->getIntegerType();
785 
786   if (const auto *EIT = RetTy->getAs<BitIntType>())
787     if (EIT->getNumBits() >
788         getContext().getTypeSize(getContext().getTargetInfo().hasInt128Type()
789                                      ? getContext().Int128Ty
790                                      : getContext().LongLongTy))
791       return getNaturalAlignIndirect(RetTy);
792 
793   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
794                                                : ABIArgInfo::getDirect());
795 }
796 
797 //===----------------------------------------------------------------------===//
798 // WebAssembly ABI Implementation
799 //
800 // This is a very simple ABI that relies a lot on DefaultABIInfo.
801 //===----------------------------------------------------------------------===//
802 
803 class WebAssemblyABIInfo final : public SwiftABIInfo {
804 public:
805   enum ABIKind {
806     MVP = 0,
807     ExperimentalMV = 1,
808   };
809 
810 private:
811   DefaultABIInfo defaultInfo;
812   ABIKind Kind;
813 
814 public:
815   explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind)
816       : SwiftABIInfo(CGT), defaultInfo(CGT), Kind(Kind) {}
817 
818 private:
819   ABIArgInfo classifyReturnType(QualType RetTy) const;
820   ABIArgInfo classifyArgumentType(QualType Ty) const;
821 
822   // DefaultABIInfo's classifyReturnType and classifyArgumentType are
823   // non-virtual, but computeInfo and EmitVAArg are virtual, so we
824   // overload them.
825   void computeInfo(CGFunctionInfo &FI) const override {
826     if (!getCXXABI().classifyReturnType(FI))
827       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
828     for (auto &Arg : FI.arguments())
829       Arg.info = classifyArgumentType(Arg.type);
830   }
831 
832   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
833                     QualType Ty) const override;
834 
835   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
836                                     bool asReturnValue) const override {
837     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
838   }
839 
840   bool isSwiftErrorInRegister() const override {
841     return false;
842   }
843 };
844 
845 class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
846 public:
847   explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
848                                         WebAssemblyABIInfo::ABIKind K)
849       : TargetCodeGenInfo(std::make_unique<WebAssemblyABIInfo>(CGT, K)) {}
850 
851   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
852                            CodeGen::CodeGenModule &CGM) const override {
853     TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
854     if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
855       if (const auto *Attr = FD->getAttr<WebAssemblyImportModuleAttr>()) {
856         llvm::Function *Fn = cast<llvm::Function>(GV);
857         llvm::AttrBuilder B(GV->getContext());
858         B.addAttribute("wasm-import-module", Attr->getImportModule());
859         Fn->addFnAttrs(B);
860       }
861       if (const auto *Attr = FD->getAttr<WebAssemblyImportNameAttr>()) {
862         llvm::Function *Fn = cast<llvm::Function>(GV);
863         llvm::AttrBuilder B(GV->getContext());
864         B.addAttribute("wasm-import-name", Attr->getImportName());
865         Fn->addFnAttrs(B);
866       }
867       if (const auto *Attr = FD->getAttr<WebAssemblyExportNameAttr>()) {
868         llvm::Function *Fn = cast<llvm::Function>(GV);
869         llvm::AttrBuilder B(GV->getContext());
870         B.addAttribute("wasm-export-name", Attr->getExportName());
871         Fn->addFnAttrs(B);
872       }
873     }
874 
875     if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
876       llvm::Function *Fn = cast<llvm::Function>(GV);
877       if (!FD->doesThisDeclarationHaveABody() && !FD->hasPrototype())
878         Fn->addFnAttr("no-prototype");
879     }
880   }
881 };
882 
883 /// Classify argument of given type \p Ty.
884 ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
885   Ty = useFirstFieldIfTransparentUnion(Ty);
886 
887   if (isAggregateTypeForABI(Ty)) {
888     // Records with non-trivial destructors/copy-constructors should not be
889     // passed by value.
890     if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
891       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
892     // Ignore empty structs/unions.
893     if (isEmptyRecord(getContext(), Ty, true))
894       return ABIArgInfo::getIgnore();
895     // Lower single-element structs to just pass a regular value. TODO: We
896     // could do reasonable-size multiple-element structs too, using getExpand(),
897     // though watch out for things like bitfields.
898     if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
899       return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
900     // For the experimental multivalue ABI, fully expand all other aggregates
901     if (Kind == ABIKind::ExperimentalMV) {
902       const RecordType *RT = Ty->getAs<RecordType>();
903       assert(RT);
904       bool HasBitField = false;
905       for (auto *Field : RT->getDecl()->fields()) {
906         if (Field->isBitField()) {
907           HasBitField = true;
908           break;
909         }
910       }
911       if (!HasBitField)
912         return ABIArgInfo::getExpand();
913     }
914   }
915 
916   // Otherwise just do the default thing.
917   return defaultInfo.classifyArgumentType(Ty);
918 }
919 
920 ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
921   if (isAggregateTypeForABI(RetTy)) {
922     // Records with non-trivial destructors/copy-constructors should not be
923     // returned by value.
924     if (!getRecordArgABI(RetTy, getCXXABI())) {
925       // Ignore empty structs/unions.
926       if (isEmptyRecord(getContext(), RetTy, true))
927         return ABIArgInfo::getIgnore();
928       // Lower single-element structs to just return a regular value. TODO: We
929       // could do reasonable-size multiple-element structs too, using
930       // ABIArgInfo::getDirect().
931       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
932         return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
933       // For the experimental multivalue ABI, return all other aggregates
934       if (Kind == ABIKind::ExperimentalMV)
935         return ABIArgInfo::getDirect();
936     }
937   }
938 
939   // Otherwise just do the default thing.
940   return defaultInfo.classifyReturnType(RetTy);
941 }
942 
943 Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
944                                       QualType Ty) const {
945   bool IsIndirect = isAggregateTypeForABI(Ty) &&
946                     !isEmptyRecord(getContext(), Ty, true) &&
947                     !isSingleElementStruct(Ty, getContext());
948   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
949                           getContext().getTypeInfoInChars(Ty),
950                           CharUnits::fromQuantity(4),
951                           /*AllowHigherAlign=*/true);
952 }
953 
954 //===----------------------------------------------------------------------===//
955 // le32/PNaCl bitcode ABI Implementation
956 //
957 // This is a simplified version of the x86_32 ABI.  Arguments and return values
958 // are always passed on the stack.
959 //===----------------------------------------------------------------------===//
960 
961 class PNaClABIInfo : public ABIInfo {
962  public:
963   PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
964 
965   ABIArgInfo classifyReturnType(QualType RetTy) const;
966   ABIArgInfo classifyArgumentType(QualType RetTy) const;
967 
968   void computeInfo(CGFunctionInfo &FI) const override;
969   Address EmitVAArg(CodeGenFunction &CGF,
970                     Address VAListAddr, QualType Ty) const override;
971 };
972 
973 class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
974  public:
975    PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
976        : TargetCodeGenInfo(std::make_unique<PNaClABIInfo>(CGT)) {}
977 };
978 
979 void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
980   if (!getCXXABI().classifyReturnType(FI))
981     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
982 
983   for (auto &I : FI.arguments())
984     I.info = classifyArgumentType(I.type);
985 }
986 
987 Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
988                                 QualType Ty) const {
989   // The PNaCL ABI is a bit odd, in that varargs don't use normal
990   // function classification. Structs get passed directly for varargs
991   // functions, through a rewriting transform in
992   // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
993   // this target to actually support a va_arg instructions with an
994   // aggregate type, unlike other targets.
995   return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
996 }
997 
998 /// Classify argument of given type \p Ty.
999 ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
1000   if (isAggregateTypeForABI(Ty)) {
1001     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
1002       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
1003     return getNaturalAlignIndirect(Ty);
1004   } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
1005     // Treat an enum type as its underlying type.
1006     Ty = EnumTy->getDecl()->getIntegerType();
1007   } else if (Ty->isFloatingType()) {
1008     // Floating-point types don't go inreg.
1009     return ABIArgInfo::getDirect();
1010   } else if (const auto *EIT = Ty->getAs<BitIntType>()) {
1011     // Treat bit-precise integers as integers if <= 64, otherwise pass
1012     // indirectly.
1013     if (EIT->getNumBits() > 64)
1014       return getNaturalAlignIndirect(Ty);
1015     return ABIArgInfo::getDirect();
1016   }
1017 
1018   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
1019                                             : ABIArgInfo::getDirect());
1020 }
1021 
1022 ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
1023   if (RetTy->isVoidType())
1024     return ABIArgInfo::getIgnore();
1025 
1026   // In the PNaCl ABI we always return records/structures on the stack.
1027   if (isAggregateTypeForABI(RetTy))
1028     return getNaturalAlignIndirect(RetTy);
1029 
1030   // Treat bit-precise integers as integers if <= 64, otherwise pass indirectly.
1031   if (const auto *EIT = RetTy->getAs<BitIntType>()) {
1032     if (EIT->getNumBits() > 64)
1033       return getNaturalAlignIndirect(RetTy);
1034     return ABIArgInfo::getDirect();
1035   }
1036 
1037   // Treat an enum type as its underlying type.
1038   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1039     RetTy = EnumTy->getDecl()->getIntegerType();
1040 
1041   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
1042                                                : ABIArgInfo::getDirect());
1043 }
1044 
1045 /// IsX86_MMXType - Return true if this is an MMX type.
1046 bool IsX86_MMXType(llvm::Type *IRType) {
1047   // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
1048   return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
1049     cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
1050     IRType->getScalarSizeInBits() != 64;
1051 }
1052 
1053 static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1054                                           StringRef Constraint,
1055                                           llvm::Type* Ty) {
1056   bool IsMMXCons = llvm::StringSwitch<bool>(Constraint)
1057                      .Cases("y", "&y", "^Ym", true)
1058                      .Default(false);
1059   if (IsMMXCons && Ty->isVectorTy()) {
1060     if (cast<llvm::VectorType>(Ty)->getPrimitiveSizeInBits().getFixedSize() !=
1061         64) {
1062       // Invalid MMX constraint
1063       return nullptr;
1064     }
1065 
1066     return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
1067   }
1068 
1069   // No operation needed
1070   return Ty;
1071 }
1072 
1073 /// Returns true if this type can be passed in SSE registers with the
1074 /// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
1075 static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
1076   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
1077     if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) {
1078       if (BT->getKind() == BuiltinType::LongDouble) {
1079         if (&Context.getTargetInfo().getLongDoubleFormat() ==
1080             &llvm::APFloat::x87DoubleExtended())
1081           return false;
1082       }
1083       return true;
1084     }
1085   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
1086     // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
1087     // registers specially.
1088     unsigned VecSize = Context.getTypeSize(VT);
1089     if (VecSize == 128 || VecSize == 256 || VecSize == 512)
1090       return true;
1091   }
1092   return false;
1093 }
1094 
1095 /// Returns true if this aggregate is small enough to be passed in SSE registers
1096 /// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
1097 static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
1098   return NumMembers <= 4;
1099 }
1100 
1101 /// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
1102 static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
1103   auto AI = ABIArgInfo::getDirect(T);
1104   AI.setInReg(true);
1105   AI.setCanBeFlattened(false);
1106   return AI;
1107 }
1108 
1109 //===----------------------------------------------------------------------===//
1110 // X86-32 ABI Implementation
1111 //===----------------------------------------------------------------------===//
1112 
1113 /// Similar to llvm::CCState, but for Clang.
1114 struct CCState {
1115   CCState(CGFunctionInfo &FI)
1116       : IsPreassigned(FI.arg_size()), CC(FI.getCallingConvention()) {}
1117 
1118   llvm::SmallBitVector IsPreassigned;
1119   unsigned CC = CallingConv::CC_C;
1120   unsigned FreeRegs = 0;
1121   unsigned FreeSSERegs = 0;
1122 };
1123 
1124 /// X86_32ABIInfo - The X86-32 ABI information.
1125 class X86_32ABIInfo : public SwiftABIInfo {
1126   enum Class {
1127     Integer,
1128     Float
1129   };
1130 
1131   static const unsigned MinABIStackAlignInBytes = 4;
1132 
1133   bool IsDarwinVectorABI;
1134   bool IsRetSmallStructInRegABI;
1135   bool IsWin32StructABI;
1136   bool IsSoftFloatABI;
1137   bool IsMCUABI;
1138   bool IsLinuxABI;
1139   unsigned DefaultNumRegisterParameters;
1140 
1141   static bool isRegisterSize(unsigned Size) {
1142     return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
1143   }
1144 
1145   bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1146     // FIXME: Assumes vectorcall is in use.
1147     return isX86VectorTypeForVectorCall(getContext(), Ty);
1148   }
1149 
1150   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1151                                          uint64_t NumMembers) const override {
1152     // FIXME: Assumes vectorcall is in use.
1153     return isX86VectorCallAggregateSmallEnough(NumMembers);
1154   }
1155 
1156   bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
1157 
1158   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
1159   /// such that the argument will be passed in memory.
1160   ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
1161 
1162   ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
1163 
1164   /// Return the alignment to use for the given type on the stack.
1165   unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
1166 
1167   Class classify(QualType Ty) const;
1168   ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
1169   ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
1170 
1171   /// Updates the number of available free registers, returns
1172   /// true if any registers were allocated.
1173   bool updateFreeRegs(QualType Ty, CCState &State) const;
1174 
1175   bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
1176                                 bool &NeedsPadding) const;
1177   bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
1178 
1179   bool canExpandIndirectArgument(QualType Ty) const;
1180 
1181   /// Rewrite the function info so that all memory arguments use
1182   /// inalloca.
1183   void rewriteWithInAlloca(CGFunctionInfo &FI) const;
1184 
1185   void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1186                            CharUnits &StackOffset, ABIArgInfo &Info,
1187                            QualType Type) const;
1188   void runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const;
1189 
1190 public:
1191 
1192   void computeInfo(CGFunctionInfo &FI) const override;
1193   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1194                     QualType Ty) const override;
1195 
1196   X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1197                 bool RetSmallStructInRegABI, bool Win32StructABI,
1198                 unsigned NumRegisterParameters, bool SoftFloatABI)
1199     : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
1200       IsRetSmallStructInRegABI(RetSmallStructInRegABI),
1201       IsWin32StructABI(Win32StructABI), IsSoftFloatABI(SoftFloatABI),
1202       IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
1203       IsLinuxABI(CGT.getTarget().getTriple().isOSLinux() ||
1204                  CGT.getTarget().getTriple().isOSCygMing()),
1205       DefaultNumRegisterParameters(NumRegisterParameters) {}
1206 
1207   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
1208                                     bool asReturnValue) const override {
1209     // LLVM's x86-32 lowering currently only assigns up to three
1210     // integer registers and three fp registers.  Oddly, it'll use up to
1211     // four vector registers for vectors, but those can overlap with the
1212     // scalar registers.
1213     return occupiesMoreThan(CGT, scalars, /*total*/ 3);
1214   }
1215 
1216   bool isSwiftErrorInRegister() const override {
1217     // x86-32 lowering does not support passing swifterror in a register.
1218     return false;
1219   }
1220 };
1221 
1222 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
1223 public:
1224   X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1225                           bool RetSmallStructInRegABI, bool Win32StructABI,
1226                           unsigned NumRegisterParameters, bool SoftFloatABI)
1227       : TargetCodeGenInfo(std::make_unique<X86_32ABIInfo>(
1228             CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
1229             NumRegisterParameters, SoftFloatABI)) {}
1230 
1231   static bool isStructReturnInRegABI(
1232       const llvm::Triple &Triple, const CodeGenOptions &Opts);
1233 
1234   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1235                            CodeGen::CodeGenModule &CGM) const override;
1236 
1237   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
1238     // Darwin uses different dwarf register numbers for EH.
1239     if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
1240     return 4;
1241   }
1242 
1243   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1244                                llvm::Value *Address) const override;
1245 
1246   llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1247                                   StringRef Constraint,
1248                                   llvm::Type* Ty) const override {
1249     return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1250   }
1251 
1252   void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
1253                                 std::string &Constraints,
1254                                 std::vector<llvm::Type *> &ResultRegTypes,
1255                                 std::vector<llvm::Type *> &ResultTruncRegTypes,
1256                                 std::vector<LValue> &ResultRegDests,
1257                                 std::string &AsmString,
1258                                 unsigned NumOutputs) const override;
1259 
1260   llvm::Constant *
1261   getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
1262     unsigned Sig = (0xeb << 0) |  // jmp rel8
1263                    (0x06 << 8) |  //           .+0x08
1264                    ('v' << 16) |
1265                    ('2' << 24);
1266     return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1267   }
1268 
1269   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
1270     return "movl\t%ebp, %ebp"
1271            "\t\t// marker for objc_retainAutoreleaseReturnValue";
1272   }
1273 };
1274 
1275 }
1276 
1277 /// Rewrite input constraint references after adding some output constraints.
1278 /// In the case where there is one output and one input and we add one output,
1279 /// we need to replace all operand references greater than or equal to 1:
1280 ///     mov $0, $1
1281 ///     mov eax, $1
1282 /// The result will be:
1283 ///     mov $0, $2
1284 ///     mov eax, $2
1285 static void rewriteInputConstraintReferences(unsigned FirstIn,
1286                                              unsigned NumNewOuts,
1287                                              std::string &AsmString) {
1288   std::string Buf;
1289   llvm::raw_string_ostream OS(Buf);
1290   size_t Pos = 0;
1291   while (Pos < AsmString.size()) {
1292     size_t DollarStart = AsmString.find('$', Pos);
1293     if (DollarStart == std::string::npos)
1294       DollarStart = AsmString.size();
1295     size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1296     if (DollarEnd == std::string::npos)
1297       DollarEnd = AsmString.size();
1298     OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1299     Pos = DollarEnd;
1300     size_t NumDollars = DollarEnd - DollarStart;
1301     if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1302       // We have an operand reference.
1303       size_t DigitStart = Pos;
1304       if (AsmString[DigitStart] == '{') {
1305         OS << '{';
1306         ++DigitStart;
1307       }
1308       size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1309       if (DigitEnd == std::string::npos)
1310         DigitEnd = AsmString.size();
1311       StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1312       unsigned OperandIndex;
1313       if (!OperandStr.getAsInteger(10, OperandIndex)) {
1314         if (OperandIndex >= FirstIn)
1315           OperandIndex += NumNewOuts;
1316         OS << OperandIndex;
1317       } else {
1318         OS << OperandStr;
1319       }
1320       Pos = DigitEnd;
1321     }
1322   }
1323   AsmString = std::move(OS.str());
1324 }
1325 
1326 /// Add output constraints for EAX:EDX because they are return registers.
1327 void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1328     CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1329     std::vector<llvm::Type *> &ResultRegTypes,
1330     std::vector<llvm::Type *> &ResultTruncRegTypes,
1331     std::vector<LValue> &ResultRegDests, std::string &AsmString,
1332     unsigned NumOutputs) const {
1333   uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1334 
1335   // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1336   // larger.
1337   if (!Constraints.empty())
1338     Constraints += ',';
1339   if (RetWidth <= 32) {
1340     Constraints += "={eax}";
1341     ResultRegTypes.push_back(CGF.Int32Ty);
1342   } else {
1343     // Use the 'A' constraint for EAX:EDX.
1344     Constraints += "=A";
1345     ResultRegTypes.push_back(CGF.Int64Ty);
1346   }
1347 
1348   // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1349   llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1350   ResultTruncRegTypes.push_back(CoerceTy);
1351 
1352   // Coerce the integer by bitcasting the return slot pointer.
1353   ReturnSlot.setAddress(
1354       CGF.Builder.CreateElementBitCast(ReturnSlot.getAddress(CGF), CoerceTy));
1355   ResultRegDests.push_back(ReturnSlot);
1356 
1357   rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1358 }
1359 
1360 /// shouldReturnTypeInRegister - Determine if the given type should be
1361 /// returned in a register (for the Darwin and MCU ABI).
1362 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1363                                                ASTContext &Context) const {
1364   uint64_t Size = Context.getTypeSize(Ty);
1365 
1366   // For i386, type must be register sized.
1367   // For the MCU ABI, it only needs to be <= 8-byte
1368   if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1369    return false;
1370 
1371   if (Ty->isVectorType()) {
1372     // 64- and 128- bit vectors inside structures are not returned in
1373     // registers.
1374     if (Size == 64 || Size == 128)
1375       return false;
1376 
1377     return true;
1378   }
1379 
1380   // If this is a builtin, pointer, enum, complex type, member pointer, or
1381   // member function pointer it is ok.
1382   if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
1383       Ty->isAnyComplexType() || Ty->isEnumeralType() ||
1384       Ty->isBlockPointerType() || Ty->isMemberPointerType())
1385     return true;
1386 
1387   // Arrays are treated like records.
1388   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
1389     return shouldReturnTypeInRegister(AT->getElementType(), Context);
1390 
1391   // Otherwise, it must be a record type.
1392   const RecordType *RT = Ty->getAs<RecordType>();
1393   if (!RT) return false;
1394 
1395   // FIXME: Traverse bases here too.
1396 
1397   // Structure types are passed in register if all fields would be
1398   // passed in a register.
1399   for (const auto *FD : RT->getDecl()->fields()) {
1400     // Empty fields are ignored.
1401     if (isEmptyField(Context, FD, true))
1402       continue;
1403 
1404     // Check fields recursively.
1405     if (!shouldReturnTypeInRegister(FD->getType(), Context))
1406       return false;
1407   }
1408   return true;
1409 }
1410 
1411 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1412   // Treat complex types as the element type.
1413   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1414     Ty = CTy->getElementType();
1415 
1416   // Check for a type which we know has a simple scalar argument-passing
1417   // convention without any padding.  (We're specifically looking for 32
1418   // and 64-bit integer and integer-equivalents, float, and double.)
1419   if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1420       !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1421     return false;
1422 
1423   uint64_t Size = Context.getTypeSize(Ty);
1424   return Size == 32 || Size == 64;
1425 }
1426 
1427 static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
1428                           uint64_t &Size) {
1429   for (const auto *FD : RD->fields()) {
1430     // Scalar arguments on the stack get 4 byte alignment on x86. If the
1431     // argument is smaller than 32-bits, expanding the struct will create
1432     // alignment padding.
1433     if (!is32Or64BitBasicType(FD->getType(), Context))
1434       return false;
1435 
1436     // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1437     // how to expand them yet, and the predicate for telling if a bitfield still
1438     // counts as "basic" is more complicated than what we were doing previously.
1439     if (FD->isBitField())
1440       return false;
1441 
1442     Size += Context.getTypeSize(FD->getType());
1443   }
1444   return true;
1445 }
1446 
1447 static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
1448                                  uint64_t &Size) {
1449   // Don't do this if there are any non-empty bases.
1450   for (const CXXBaseSpecifier &Base : RD->bases()) {
1451     if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
1452                               Size))
1453       return false;
1454   }
1455   if (!addFieldSizes(Context, RD, Size))
1456     return false;
1457   return true;
1458 }
1459 
1460 /// Test whether an argument type which is to be passed indirectly (on the
1461 /// stack) would have the equivalent layout if it was expanded into separate
1462 /// arguments. If so, we prefer to do the latter to avoid inhibiting
1463 /// optimizations.
1464 bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1465   // We can only expand structure types.
1466   const RecordType *RT = Ty->getAs<RecordType>();
1467   if (!RT)
1468     return false;
1469   const RecordDecl *RD = RT->getDecl();
1470   uint64_t Size = 0;
1471   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1472     if (!IsWin32StructABI) {
1473       // On non-Windows, we have to conservatively match our old bitcode
1474       // prototypes in order to be ABI-compatible at the bitcode level.
1475       if (!CXXRD->isCLike())
1476         return false;
1477     } else {
1478       // Don't do this for dynamic classes.
1479       if (CXXRD->isDynamicClass())
1480         return false;
1481     }
1482     if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
1483       return false;
1484   } else {
1485     if (!addFieldSizes(getContext(), RD, Size))
1486       return false;
1487   }
1488 
1489   // We can do this if there was no alignment padding.
1490   return Size == getContext().getTypeSize(Ty);
1491 }
1492 
1493 ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
1494   // If the return value is indirect, then the hidden argument is consuming one
1495   // integer register.
1496   if (State.FreeRegs) {
1497     --State.FreeRegs;
1498     if (!IsMCUABI)
1499       return getNaturalAlignIndirectInReg(RetTy);
1500   }
1501   return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
1502 }
1503 
1504 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1505                                              CCState &State) const {
1506   if (RetTy->isVoidType())
1507     return ABIArgInfo::getIgnore();
1508 
1509   const Type *Base = nullptr;
1510   uint64_t NumElts = 0;
1511   if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1512        State.CC == llvm::CallingConv::X86_RegCall) &&
1513       isHomogeneousAggregate(RetTy, Base, NumElts)) {
1514     // The LLVM struct type for such an aggregate should lower properly.
1515     return ABIArgInfo::getDirect();
1516   }
1517 
1518   if (const VectorType *VT = RetTy->getAs<VectorType>()) {
1519     // On Darwin, some vectors are returned in registers.
1520     if (IsDarwinVectorABI) {
1521       uint64_t Size = getContext().getTypeSize(RetTy);
1522 
1523       // 128-bit vectors are a special case; they are returned in
1524       // registers and we need to make sure to pick a type the LLVM
1525       // backend will like.
1526       if (Size == 128)
1527         return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
1528             llvm::Type::getInt64Ty(getVMContext()), 2));
1529 
1530       // Always return in register if it fits in a general purpose
1531       // register, or if it is 64 bits and has a single element.
1532       if ((Size == 8 || Size == 16 || Size == 32) ||
1533           (Size == 64 && VT->getNumElements() == 1))
1534         return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1535                                                             Size));
1536 
1537       return getIndirectReturnResult(RetTy, State);
1538     }
1539 
1540     return ABIArgInfo::getDirect();
1541   }
1542 
1543   if (isAggregateTypeForABI(RetTy)) {
1544     if (const RecordType *RT = RetTy->getAs<RecordType>()) {
1545       // Structures with flexible arrays are always indirect.
1546       if (RT->getDecl()->hasFlexibleArrayMember())
1547         return getIndirectReturnResult(RetTy, State);
1548     }
1549 
1550     // If specified, structs and unions are always indirect.
1551     if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
1552       return getIndirectReturnResult(RetTy, State);
1553 
1554     // Ignore empty structs/unions.
1555     if (isEmptyRecord(getContext(), RetTy, true))
1556       return ABIArgInfo::getIgnore();
1557 
1558     // Return complex of _Float16 as <2 x half> so the backend will use xmm0.
1559     if (const ComplexType *CT = RetTy->getAs<ComplexType>()) {
1560       QualType ET = getContext().getCanonicalType(CT->getElementType());
1561       if (ET->isFloat16Type())
1562         return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
1563             llvm::Type::getHalfTy(getVMContext()), 2));
1564     }
1565 
1566     // Small structures which are register sized are generally returned
1567     // in a register.
1568     if (shouldReturnTypeInRegister(RetTy, getContext())) {
1569       uint64_t Size = getContext().getTypeSize(RetTy);
1570 
1571       // As a special-case, if the struct is a "single-element" struct, and
1572       // the field is of type "float" or "double", return it in a
1573       // floating-point register. (MSVC does not apply this special case.)
1574       // We apply a similar transformation for pointer types to improve the
1575       // quality of the generated IR.
1576       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
1577         if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
1578             || SeltTy->hasPointerRepresentation())
1579           return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1580 
1581       // FIXME: We should be able to narrow this integer in cases with dead
1582       // padding.
1583       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
1584     }
1585 
1586     return getIndirectReturnResult(RetTy, State);
1587   }
1588 
1589   // Treat an enum type as its underlying type.
1590   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1591     RetTy = EnumTy->getDecl()->getIntegerType();
1592 
1593   if (const auto *EIT = RetTy->getAs<BitIntType>())
1594     if (EIT->getNumBits() > 64)
1595       return getIndirectReturnResult(RetTy, State);
1596 
1597   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
1598                                                : ABIArgInfo::getDirect());
1599 }
1600 
1601 static bool isSIMDVectorType(ASTContext &Context, QualType Ty) {
1602   return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1603 }
1604 
1605 static bool isRecordWithSIMDVectorType(ASTContext &Context, QualType Ty) {
1606   const RecordType *RT = Ty->getAs<RecordType>();
1607   if (!RT)
1608     return false;
1609   const RecordDecl *RD = RT->getDecl();
1610 
1611   // If this is a C++ record, check the bases first.
1612   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1613     for (const auto &I : CXXRD->bases())
1614       if (!isRecordWithSIMDVectorType(Context, I.getType()))
1615         return false;
1616 
1617   for (const auto *i : RD->fields()) {
1618     QualType FT = i->getType();
1619 
1620     if (isSIMDVectorType(Context, FT))
1621       return true;
1622 
1623     if (isRecordWithSIMDVectorType(Context, FT))
1624       return true;
1625   }
1626 
1627   return false;
1628 }
1629 
1630 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1631                                                  unsigned Align) const {
1632   // Otherwise, if the alignment is less than or equal to the minimum ABI
1633   // alignment, just use the default; the backend will handle this.
1634   if (Align <= MinABIStackAlignInBytes)
1635     return 0; // Use default alignment.
1636 
1637   if (IsLinuxABI) {
1638     // Exclude other System V OS (e.g Darwin, PS4 and FreeBSD) since we don't
1639     // want to spend any effort dealing with the ramifications of ABI breaks.
1640     //
1641     // If the vector type is __m128/__m256/__m512, return the default alignment.
1642     if (Ty->isVectorType() && (Align == 16 || Align == 32 || Align == 64))
1643       return Align;
1644   }
1645   // On non-Darwin, the stack type alignment is always 4.
1646   if (!IsDarwinVectorABI) {
1647     // Set explicit alignment, since we may need to realign the top.
1648     return MinABIStackAlignInBytes;
1649   }
1650 
1651   // Otherwise, if the type contains an SSE vector type, the alignment is 16.
1652   if (Align >= 16 && (isSIMDVectorType(getContext(), Ty) ||
1653                       isRecordWithSIMDVectorType(getContext(), Ty)))
1654     return 16;
1655 
1656   return MinABIStackAlignInBytes;
1657 }
1658 
1659 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
1660                                             CCState &State) const {
1661   if (!ByVal) {
1662     if (State.FreeRegs) {
1663       --State.FreeRegs; // Non-byval indirects just use one pointer.
1664       if (!IsMCUABI)
1665         return getNaturalAlignIndirectInReg(Ty);
1666     }
1667     return getNaturalAlignIndirect(Ty, false);
1668   }
1669 
1670   // Compute the byval alignment.
1671   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1672   unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1673   if (StackAlign == 0)
1674     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
1675 
1676   // If the stack alignment is less than the type alignment, realign the
1677   // argument.
1678   bool Realign = TypeAlign > StackAlign;
1679   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1680                                  /*ByVal=*/true, Realign);
1681 }
1682 
1683 X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1684   const Type *T = isSingleElementStruct(Ty, getContext());
1685   if (!T)
1686     T = Ty.getTypePtr();
1687 
1688   if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1689     BuiltinType::Kind K = BT->getKind();
1690     if (K == BuiltinType::Float || K == BuiltinType::Double)
1691       return Float;
1692   }
1693   return Integer;
1694 }
1695 
1696 bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
1697   if (!IsSoftFloatABI) {
1698     Class C = classify(Ty);
1699     if (C == Float)
1700       return false;
1701   }
1702 
1703   unsigned Size = getContext().getTypeSize(Ty);
1704   unsigned SizeInRegs = (Size + 31) / 32;
1705 
1706   if (SizeInRegs == 0)
1707     return false;
1708 
1709   if (!IsMCUABI) {
1710     if (SizeInRegs > State.FreeRegs) {
1711       State.FreeRegs = 0;
1712       return false;
1713     }
1714   } else {
1715     // The MCU psABI allows passing parameters in-reg even if there are
1716     // earlier parameters that are passed on the stack. Also,
1717     // it does not allow passing >8-byte structs in-register,
1718     // even if there are 3 free registers available.
1719     if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1720       return false;
1721   }
1722 
1723   State.FreeRegs -= SizeInRegs;
1724   return true;
1725 }
1726 
1727 bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1728                                              bool &InReg,
1729                                              bool &NeedsPadding) const {
1730   // On Windows, aggregates other than HFAs are never passed in registers, and
1731   // they do not consume register slots. Homogenous floating-point aggregates
1732   // (HFAs) have already been dealt with at this point.
1733   if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1734     return false;
1735 
1736   NeedsPadding = false;
1737   InReg = !IsMCUABI;
1738 
1739   if (!updateFreeRegs(Ty, State))
1740     return false;
1741 
1742   if (IsMCUABI)
1743     return true;
1744 
1745   if (State.CC == llvm::CallingConv::X86_FastCall ||
1746       State.CC == llvm::CallingConv::X86_VectorCall ||
1747       State.CC == llvm::CallingConv::X86_RegCall) {
1748     if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
1749       NeedsPadding = true;
1750 
1751     return false;
1752   }
1753 
1754   return true;
1755 }
1756 
1757 bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1758   if (!updateFreeRegs(Ty, State))
1759     return false;
1760 
1761   if (IsMCUABI)
1762     return false;
1763 
1764   if (State.CC == llvm::CallingConv::X86_FastCall ||
1765       State.CC == llvm::CallingConv::X86_VectorCall ||
1766       State.CC == llvm::CallingConv::X86_RegCall) {
1767     if (getContext().getTypeSize(Ty) > 32)
1768       return false;
1769 
1770     return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1771         Ty->isReferenceType());
1772   }
1773 
1774   return true;
1775 }
1776 
1777 void X86_32ABIInfo::runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const {
1778   // Vectorcall x86 works subtly different than in x64, so the format is
1779   // a bit different than the x64 version.  First, all vector types (not HVAs)
1780   // are assigned, with the first 6 ending up in the [XYZ]MM0-5 registers.
1781   // This differs from the x64 implementation, where the first 6 by INDEX get
1782   // registers.
1783   // In the second pass over the arguments, HVAs are passed in the remaining
1784   // vector registers if possible, or indirectly by address. The address will be
1785   // passed in ECX/EDX if available. Any other arguments are passed according to
1786   // the usual fastcall rules.
1787   MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
1788   for (int I = 0, E = Args.size(); I < E; ++I) {
1789     const Type *Base = nullptr;
1790     uint64_t NumElts = 0;
1791     const QualType &Ty = Args[I].type;
1792     if ((Ty->isVectorType() || Ty->isBuiltinType()) &&
1793         isHomogeneousAggregate(Ty, Base, NumElts)) {
1794       if (State.FreeSSERegs >= NumElts) {
1795         State.FreeSSERegs -= NumElts;
1796         Args[I].info = ABIArgInfo::getDirectInReg();
1797         State.IsPreassigned.set(I);
1798       }
1799     }
1800   }
1801 }
1802 
1803 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1804                                                CCState &State) const {
1805   // FIXME: Set alignment on indirect arguments.
1806   bool IsFastCall = State.CC == llvm::CallingConv::X86_FastCall;
1807   bool IsRegCall = State.CC == llvm::CallingConv::X86_RegCall;
1808   bool IsVectorCall = State.CC == llvm::CallingConv::X86_VectorCall;
1809 
1810   Ty = useFirstFieldIfTransparentUnion(Ty);
1811   TypeInfo TI = getContext().getTypeInfo(Ty);
1812 
1813   // Check with the C++ ABI first.
1814   const RecordType *RT = Ty->getAs<RecordType>();
1815   if (RT) {
1816     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1817     if (RAA == CGCXXABI::RAA_Indirect) {
1818       return getIndirectResult(Ty, false, State);
1819     } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1820       // The field index doesn't matter, we'll fix it up later.
1821       return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1822     }
1823   }
1824 
1825   // Regcall uses the concept of a homogenous vector aggregate, similar
1826   // to other targets.
1827   const Type *Base = nullptr;
1828   uint64_t NumElts = 0;
1829   if ((IsRegCall || IsVectorCall) &&
1830       isHomogeneousAggregate(Ty, Base, NumElts)) {
1831     if (State.FreeSSERegs >= NumElts) {
1832       State.FreeSSERegs -= NumElts;
1833 
1834       // Vectorcall passes HVAs directly and does not flatten them, but regcall
1835       // does.
1836       if (IsVectorCall)
1837         return getDirectX86Hva();
1838 
1839       if (Ty->isBuiltinType() || Ty->isVectorType())
1840         return ABIArgInfo::getDirect();
1841       return ABIArgInfo::getExpand();
1842     }
1843     return getIndirectResult(Ty, /*ByVal=*/false, State);
1844   }
1845 
1846   if (isAggregateTypeForABI(Ty)) {
1847     // Structures with flexible arrays are always indirect.
1848     // FIXME: This should not be byval!
1849     if (RT && RT->getDecl()->hasFlexibleArrayMember())
1850       return getIndirectResult(Ty, true, State);
1851 
1852     // Ignore empty structs/unions on non-Windows.
1853     if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
1854       return ABIArgInfo::getIgnore();
1855 
1856     llvm::LLVMContext &LLVMContext = getVMContext();
1857     llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
1858     bool NeedsPadding = false;
1859     bool InReg;
1860     if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
1861       unsigned SizeInRegs = (TI.Width + 31) / 32;
1862       SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
1863       llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
1864       if (InReg)
1865         return ABIArgInfo::getDirectInReg(Result);
1866       else
1867         return ABIArgInfo::getDirect(Result);
1868     }
1869     llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
1870 
1871     // Pass over-aligned aggregates on Windows indirectly. This behavior was
1872     // added in MSVC 2015.
1873     if (IsWin32StructABI && TI.isAlignRequired() && TI.Align > 32)
1874       return getIndirectResult(Ty, /*ByVal=*/false, State);
1875 
1876     // Expand small (<= 128-bit) record types when we know that the stack layout
1877     // of those arguments will match the struct. This is important because the
1878     // LLVM backend isn't smart enough to remove byval, which inhibits many
1879     // optimizations.
1880     // Don't do this for the MCU if there are still free integer registers
1881     // (see X86_64 ABI for full explanation).
1882     if (TI.Width <= 4 * 32 && (!IsMCUABI || State.FreeRegs == 0) &&
1883         canExpandIndirectArgument(Ty))
1884       return ABIArgInfo::getExpandWithPadding(
1885           IsFastCall || IsVectorCall || IsRegCall, PaddingType);
1886 
1887     return getIndirectResult(Ty, true, State);
1888   }
1889 
1890   if (const VectorType *VT = Ty->getAs<VectorType>()) {
1891     // On Windows, vectors are passed directly if registers are available, or
1892     // indirectly if not. This avoids the need to align argument memory. Pass
1893     // user-defined vector types larger than 512 bits indirectly for simplicity.
1894     if (IsWin32StructABI) {
1895       if (TI.Width <= 512 && State.FreeSSERegs > 0) {
1896         --State.FreeSSERegs;
1897         return ABIArgInfo::getDirectInReg();
1898       }
1899       return getIndirectResult(Ty, /*ByVal=*/false, State);
1900     }
1901 
1902     // On Darwin, some vectors are passed in memory, we handle this by passing
1903     // it as an i8/i16/i32/i64.
1904     if (IsDarwinVectorABI) {
1905       if ((TI.Width == 8 || TI.Width == 16 || TI.Width == 32) ||
1906           (TI.Width == 64 && VT->getNumElements() == 1))
1907         return ABIArgInfo::getDirect(
1908             llvm::IntegerType::get(getVMContext(), TI.Width));
1909     }
1910 
1911     if (IsX86_MMXType(CGT.ConvertType(Ty)))
1912       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
1913 
1914     return ABIArgInfo::getDirect();
1915   }
1916 
1917 
1918   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1919     Ty = EnumTy->getDecl()->getIntegerType();
1920 
1921   bool InReg = shouldPrimitiveUseInReg(Ty, State);
1922 
1923   if (isPromotableIntegerTypeForABI(Ty)) {
1924     if (InReg)
1925       return ABIArgInfo::getExtendInReg(Ty);
1926     return ABIArgInfo::getExtend(Ty);
1927   }
1928 
1929   if (const auto *EIT = Ty->getAs<BitIntType>()) {
1930     if (EIT->getNumBits() <= 64) {
1931       if (InReg)
1932         return ABIArgInfo::getDirectInReg();
1933       return ABIArgInfo::getDirect();
1934     }
1935     return getIndirectResult(Ty, /*ByVal=*/false, State);
1936   }
1937 
1938   if (InReg)
1939     return ABIArgInfo::getDirectInReg();
1940   return ABIArgInfo::getDirect();
1941 }
1942 
1943 void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
1944   CCState State(FI);
1945   if (IsMCUABI)
1946     State.FreeRegs = 3;
1947   else if (State.CC == llvm::CallingConv::X86_FastCall) {
1948     State.FreeRegs = 2;
1949     State.FreeSSERegs = 3;
1950   } else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1951     State.FreeRegs = 2;
1952     State.FreeSSERegs = 6;
1953   } else if (FI.getHasRegParm())
1954     State.FreeRegs = FI.getRegParm();
1955   else if (State.CC == llvm::CallingConv::X86_RegCall) {
1956     State.FreeRegs = 5;
1957     State.FreeSSERegs = 8;
1958   } else if (IsWin32StructABI) {
1959     // Since MSVC 2015, the first three SSE vectors have been passed in
1960     // registers. The rest are passed indirectly.
1961     State.FreeRegs = DefaultNumRegisterParameters;
1962     State.FreeSSERegs = 3;
1963   } else
1964     State.FreeRegs = DefaultNumRegisterParameters;
1965 
1966   if (!::classifyReturnType(getCXXABI(), FI, *this)) {
1967     FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
1968   } else if (FI.getReturnInfo().isIndirect()) {
1969     // The C++ ABI is not aware of register usage, so we have to check if the
1970     // return value was sret and put it in a register ourselves if appropriate.
1971     if (State.FreeRegs) {
1972       --State.FreeRegs;  // The sret parameter consumes a register.
1973       if (!IsMCUABI)
1974         FI.getReturnInfo().setInReg(true);
1975     }
1976   }
1977 
1978   // The chain argument effectively gives us another free register.
1979   if (FI.isChainCall())
1980     ++State.FreeRegs;
1981 
1982   // For vectorcall, do a first pass over the arguments, assigning FP and vector
1983   // arguments to XMM registers as available.
1984   if (State.CC == llvm::CallingConv::X86_VectorCall)
1985     runVectorCallFirstPass(FI, State);
1986 
1987   bool UsedInAlloca = false;
1988   MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
1989   for (int I = 0, E = Args.size(); I < E; ++I) {
1990     // Skip arguments that have already been assigned.
1991     if (State.IsPreassigned.test(I))
1992       continue;
1993 
1994     Args[I].info = classifyArgumentType(Args[I].type, State);
1995     UsedInAlloca |= (Args[I].info.getKind() == ABIArgInfo::InAlloca);
1996   }
1997 
1998   // If we needed to use inalloca for any argument, do a second pass and rewrite
1999   // all the memory arguments to use inalloca.
2000   if (UsedInAlloca)
2001     rewriteWithInAlloca(FI);
2002 }
2003 
2004 void
2005 X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
2006                                    CharUnits &StackOffset, ABIArgInfo &Info,
2007                                    QualType Type) const {
2008   // Arguments are always 4-byte-aligned.
2009   CharUnits WordSize = CharUnits::fromQuantity(4);
2010   assert(StackOffset.isMultipleOf(WordSize) && "unaligned inalloca struct");
2011 
2012   // sret pointers and indirect things will require an extra pointer
2013   // indirection, unless they are byval. Most things are byval, and will not
2014   // require this indirection.
2015   bool IsIndirect = false;
2016   if (Info.isIndirect() && !Info.getIndirectByVal())
2017     IsIndirect = true;
2018   Info = ABIArgInfo::getInAlloca(FrameFields.size(), IsIndirect);
2019   llvm::Type *LLTy = CGT.ConvertTypeForMem(Type);
2020   if (IsIndirect)
2021     LLTy = LLTy->getPointerTo(0);
2022   FrameFields.push_back(LLTy);
2023   StackOffset += IsIndirect ? WordSize : getContext().getTypeSizeInChars(Type);
2024 
2025   // Insert padding bytes to respect alignment.
2026   CharUnits FieldEnd = StackOffset;
2027   StackOffset = FieldEnd.alignTo(WordSize);
2028   if (StackOffset != FieldEnd) {
2029     CharUnits NumBytes = StackOffset - FieldEnd;
2030     llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
2031     Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
2032     FrameFields.push_back(Ty);
2033   }
2034 }
2035 
2036 static bool isArgInAlloca(const ABIArgInfo &Info) {
2037   // Leave ignored and inreg arguments alone.
2038   switch (Info.getKind()) {
2039   case ABIArgInfo::InAlloca:
2040     return true;
2041   case ABIArgInfo::Ignore:
2042   case ABIArgInfo::IndirectAliased:
2043     return false;
2044   case ABIArgInfo::Indirect:
2045   case ABIArgInfo::Direct:
2046   case ABIArgInfo::Extend:
2047     return !Info.getInReg();
2048   case ABIArgInfo::Expand:
2049   case ABIArgInfo::CoerceAndExpand:
2050     // These are aggregate types which are never passed in registers when
2051     // inalloca is involved.
2052     return true;
2053   }
2054   llvm_unreachable("invalid enum");
2055 }
2056 
2057 void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
2058   assert(IsWin32StructABI && "inalloca only supported on win32");
2059 
2060   // Build a packed struct type for all of the arguments in memory.
2061   SmallVector<llvm::Type *, 6> FrameFields;
2062 
2063   // The stack alignment is always 4.
2064   CharUnits StackAlign = CharUnits::fromQuantity(4);
2065 
2066   CharUnits StackOffset;
2067   CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
2068 
2069   // Put 'this' into the struct before 'sret', if necessary.
2070   bool IsThisCall =
2071       FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
2072   ABIArgInfo &Ret = FI.getReturnInfo();
2073   if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
2074       isArgInAlloca(I->info)) {
2075     addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
2076     ++I;
2077   }
2078 
2079   // Put the sret parameter into the inalloca struct if it's in memory.
2080   if (Ret.isIndirect() && !Ret.getInReg()) {
2081     addFieldToArgStruct(FrameFields, StackOffset, Ret, FI.getReturnType());
2082     // On Windows, the hidden sret parameter is always returned in eax.
2083     Ret.setInAllocaSRet(IsWin32StructABI);
2084   }
2085 
2086   // Skip the 'this' parameter in ecx.
2087   if (IsThisCall)
2088     ++I;
2089 
2090   // Put arguments passed in memory into the struct.
2091   for (; I != E; ++I) {
2092     if (isArgInAlloca(I->info))
2093       addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
2094   }
2095 
2096   FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
2097                                         /*isPacked=*/true),
2098                   StackAlign);
2099 }
2100 
2101 Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
2102                                  Address VAListAddr, QualType Ty) const {
2103 
2104   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
2105 
2106   // x86-32 changes the alignment of certain arguments on the stack.
2107   //
2108   // Just messing with TypeInfo like this works because we never pass
2109   // anything indirectly.
2110   TypeInfo.Align = CharUnits::fromQuantity(
2111                 getTypeStackAlignInBytes(Ty, TypeInfo.Align.getQuantity()));
2112 
2113   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
2114                           TypeInfo, CharUnits::fromQuantity(4),
2115                           /*AllowHigherAlign*/ true);
2116 }
2117 
2118 bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
2119     const llvm::Triple &Triple, const CodeGenOptions &Opts) {
2120   assert(Triple.getArch() == llvm::Triple::x86);
2121 
2122   switch (Opts.getStructReturnConvention()) {
2123   case CodeGenOptions::SRCK_Default:
2124     break;
2125   case CodeGenOptions::SRCK_OnStack:  // -fpcc-struct-return
2126     return false;
2127   case CodeGenOptions::SRCK_InRegs:  // -freg-struct-return
2128     return true;
2129   }
2130 
2131   if (Triple.isOSDarwin() || Triple.isOSIAMCU())
2132     return true;
2133 
2134   switch (Triple.getOS()) {
2135   case llvm::Triple::DragonFly:
2136   case llvm::Triple::FreeBSD:
2137   case llvm::Triple::OpenBSD:
2138   case llvm::Triple::Win32:
2139     return true;
2140   default:
2141     return false;
2142   }
2143 }
2144 
2145 static void addX86InterruptAttrs(const FunctionDecl *FD, llvm::GlobalValue *GV,
2146                                  CodeGen::CodeGenModule &CGM) {
2147   if (!FD->hasAttr<AnyX86InterruptAttr>())
2148     return;
2149 
2150   llvm::Function *Fn = cast<llvm::Function>(GV);
2151   Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2152   if (FD->getNumParams() == 0)
2153     return;
2154 
2155   auto PtrTy = cast<PointerType>(FD->getParamDecl(0)->getType());
2156   llvm::Type *ByValTy = CGM.getTypes().ConvertType(PtrTy->getPointeeType());
2157   llvm::Attribute NewAttr = llvm::Attribute::getWithByValType(
2158     Fn->getContext(), ByValTy);
2159   Fn->addParamAttr(0, NewAttr);
2160 }
2161 
2162 void X86_32TargetCodeGenInfo::setTargetAttributes(
2163     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2164   if (GV->isDeclaration())
2165     return;
2166   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2167     if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2168       llvm::Function *Fn = cast<llvm::Function>(GV);
2169       Fn->addFnAttr("stackrealign");
2170     }
2171 
2172     addX86InterruptAttrs(FD, GV, CGM);
2173   }
2174 }
2175 
2176 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
2177                                                CodeGen::CodeGenFunction &CGF,
2178                                                llvm::Value *Address) const {
2179   CodeGen::CGBuilderTy &Builder = CGF.Builder;
2180 
2181   llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
2182 
2183   // 0-7 are the eight integer registers;  the order is different
2184   //   on Darwin (for EH), but the range is the same.
2185   // 8 is %eip.
2186   AssignToArrayRange(Builder, Address, Four8, 0, 8);
2187 
2188   if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
2189     // 12-16 are st(0..4).  Not sure why we stop at 4.
2190     // These have size 16, which is sizeof(long double) on
2191     // platforms with 8-byte alignment for that type.
2192     llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
2193     AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
2194 
2195   } else {
2196     // 9 is %eflags, which doesn't get a size on Darwin for some
2197     // reason.
2198     Builder.CreateAlignedStore(
2199         Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
2200                                CharUnits::One());
2201 
2202     // 11-16 are st(0..5).  Not sure why we stop at 5.
2203     // These have size 12, which is sizeof(long double) on
2204     // platforms with 4-byte alignment for that type.
2205     llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
2206     AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
2207   }
2208 
2209   return false;
2210 }
2211 
2212 //===----------------------------------------------------------------------===//
2213 // X86-64 ABI Implementation
2214 //===----------------------------------------------------------------------===//
2215 
2216 
2217 namespace {
2218 /// The AVX ABI level for X86 targets.
2219 enum class X86AVXABILevel {
2220   None,
2221   AVX,
2222   AVX512
2223 };
2224 
2225 /// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
2226 static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
2227   switch (AVXLevel) {
2228   case X86AVXABILevel::AVX512:
2229     return 512;
2230   case X86AVXABILevel::AVX:
2231     return 256;
2232   case X86AVXABILevel::None:
2233     return 128;
2234   }
2235   llvm_unreachable("Unknown AVXLevel");
2236 }
2237 
2238 /// X86_64ABIInfo - The X86_64 ABI information.
2239 class X86_64ABIInfo : public SwiftABIInfo {
2240   enum Class {
2241     Integer = 0,
2242     SSE,
2243     SSEUp,
2244     X87,
2245     X87Up,
2246     ComplexX87,
2247     NoClass,
2248     Memory
2249   };
2250 
2251   /// merge - Implement the X86_64 ABI merging algorithm.
2252   ///
2253   /// Merge an accumulating classification \arg Accum with a field
2254   /// classification \arg Field.
2255   ///
2256   /// \param Accum - The accumulating classification. This should
2257   /// always be either NoClass or the result of a previous merge
2258   /// call. In addition, this should never be Memory (the caller
2259   /// should just return Memory for the aggregate).
2260   static Class merge(Class Accum, Class Field);
2261 
2262   /// postMerge - Implement the X86_64 ABI post merging algorithm.
2263   ///
2264   /// Post merger cleanup, reduces a malformed Hi and Lo pair to
2265   /// final MEMORY or SSE classes when necessary.
2266   ///
2267   /// \param AggregateSize - The size of the current aggregate in
2268   /// the classification process.
2269   ///
2270   /// \param Lo - The classification for the parts of the type
2271   /// residing in the low word of the containing object.
2272   ///
2273   /// \param Hi - The classification for the parts of the type
2274   /// residing in the higher words of the containing object.
2275   ///
2276   void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
2277 
2278   /// classify - Determine the x86_64 register classes in which the
2279   /// given type T should be passed.
2280   ///
2281   /// \param Lo - The classification for the parts of the type
2282   /// residing in the low word of the containing object.
2283   ///
2284   /// \param Hi - The classification for the parts of the type
2285   /// residing in the high word of the containing object.
2286   ///
2287   /// \param OffsetBase - The bit offset of this type in the
2288   /// containing object.  Some parameters are classified different
2289   /// depending on whether they straddle an eightbyte boundary.
2290   ///
2291   /// \param isNamedArg - Whether the argument in question is a "named"
2292   /// argument, as used in AMD64-ABI 3.5.7.
2293   ///
2294   /// If a word is unused its result will be NoClass; if a type should
2295   /// be passed in Memory then at least the classification of \arg Lo
2296   /// will be Memory.
2297   ///
2298   /// The \arg Lo class will be NoClass iff the argument is ignored.
2299   ///
2300   /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
2301   /// also be ComplexX87.
2302   void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
2303                 bool isNamedArg) const;
2304 
2305   llvm::Type *GetByteVectorType(QualType Ty) const;
2306   llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
2307                                  unsigned IROffset, QualType SourceTy,
2308                                  unsigned SourceOffset) const;
2309   llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
2310                                      unsigned IROffset, QualType SourceTy,
2311                                      unsigned SourceOffset) const;
2312 
2313   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2314   /// such that the argument will be returned in memory.
2315   ABIArgInfo getIndirectReturnResult(QualType Ty) const;
2316 
2317   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2318   /// such that the argument will be passed in memory.
2319   ///
2320   /// \param freeIntRegs - The number of free integer registers remaining
2321   /// available.
2322   ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
2323 
2324   ABIArgInfo classifyReturnType(QualType RetTy) const;
2325 
2326   ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
2327                                   unsigned &neededInt, unsigned &neededSSE,
2328                                   bool isNamedArg) const;
2329 
2330   ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
2331                                        unsigned &NeededSSE) const;
2332 
2333   ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
2334                                            unsigned &NeededSSE) const;
2335 
2336   bool IsIllegalVectorType(QualType Ty) const;
2337 
2338   /// The 0.98 ABI revision clarified a lot of ambiguities,
2339   /// unfortunately in ways that were not always consistent with
2340   /// certain previous compilers.  In particular, platforms which
2341   /// required strict binary compatibility with older versions of GCC
2342   /// may need to exempt themselves.
2343   bool honorsRevision0_98() const {
2344     return !getTarget().getTriple().isOSDarwin();
2345   }
2346 
2347   /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to
2348   /// classify it as INTEGER (for compatibility with older clang compilers).
2349   bool classifyIntegerMMXAsSSE() const {
2350     // Clang <= 3.8 did not do this.
2351     if (getContext().getLangOpts().getClangABICompat() <=
2352         LangOptions::ClangABI::Ver3_8)
2353       return false;
2354 
2355     const llvm::Triple &Triple = getTarget().getTriple();
2356     if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
2357       return false;
2358     if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
2359       return false;
2360     return true;
2361   }
2362 
2363   // GCC classifies vectors of __int128 as memory.
2364   bool passInt128VectorsInMem() const {
2365     // Clang <= 9.0 did not do this.
2366     if (getContext().getLangOpts().getClangABICompat() <=
2367         LangOptions::ClangABI::Ver9)
2368       return false;
2369 
2370     const llvm::Triple &T = getTarget().getTriple();
2371     return T.isOSLinux() || T.isOSNetBSD();
2372   }
2373 
2374   X86AVXABILevel AVXLevel;
2375   // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
2376   // 64-bit hardware.
2377   bool Has64BitPointers;
2378 
2379 public:
2380   X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
2381       SwiftABIInfo(CGT), AVXLevel(AVXLevel),
2382       Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
2383   }
2384 
2385   bool isPassedUsingAVXType(QualType type) const {
2386     unsigned neededInt, neededSSE;
2387     // The freeIntRegs argument doesn't matter here.
2388     ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
2389                                            /*isNamedArg*/true);
2390     if (info.isDirect()) {
2391       llvm::Type *ty = info.getCoerceToType();
2392       if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
2393         return vectorTy->getPrimitiveSizeInBits().getFixedSize() > 128;
2394     }
2395     return false;
2396   }
2397 
2398   void computeInfo(CGFunctionInfo &FI) const override;
2399 
2400   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2401                     QualType Ty) const override;
2402   Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
2403                       QualType Ty) const override;
2404 
2405   bool has64BitPointers() const {
2406     return Has64BitPointers;
2407   }
2408 
2409   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
2410                                     bool asReturnValue) const override {
2411     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2412   }
2413   bool isSwiftErrorInRegister() const override {
2414     return true;
2415   }
2416 };
2417 
2418 /// WinX86_64ABIInfo - The Windows X86_64 ABI information.
2419 class WinX86_64ABIInfo : public SwiftABIInfo {
2420 public:
2421   WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2422       : SwiftABIInfo(CGT), AVXLevel(AVXLevel),
2423         IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
2424 
2425   void computeInfo(CGFunctionInfo &FI) const override;
2426 
2427   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2428                     QualType Ty) const override;
2429 
2430   bool isHomogeneousAggregateBaseType(QualType Ty) const override {
2431     // FIXME: Assumes vectorcall is in use.
2432     return isX86VectorTypeForVectorCall(getContext(), Ty);
2433   }
2434 
2435   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2436                                          uint64_t NumMembers) const override {
2437     // FIXME: Assumes vectorcall is in use.
2438     return isX86VectorCallAggregateSmallEnough(NumMembers);
2439   }
2440 
2441   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars,
2442                                     bool asReturnValue) const override {
2443     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2444   }
2445 
2446   bool isSwiftErrorInRegister() const override {
2447     return true;
2448   }
2449 
2450 private:
2451   ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
2452                       bool IsVectorCall, bool IsRegCall) const;
2453   ABIArgInfo reclassifyHvaArgForVectorCall(QualType Ty, unsigned &FreeSSERegs,
2454                                            const ABIArgInfo &current) const;
2455 
2456   X86AVXABILevel AVXLevel;
2457 
2458   bool IsMingw64;
2459 };
2460 
2461 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2462 public:
2463   X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2464       : TargetCodeGenInfo(std::make_unique<X86_64ABIInfo>(CGT, AVXLevel)) {}
2465 
2466   const X86_64ABIInfo &getABIInfo() const {
2467     return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2468   }
2469 
2470   /// Disable tail call on x86-64. The epilogue code before the tail jump blocks
2471   /// autoreleaseRV/retainRV and autoreleaseRV/unsafeClaimRV optimizations.
2472   bool markARCOptimizedReturnCallsAsNoTail() const override { return true; }
2473 
2474   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2475     return 7;
2476   }
2477 
2478   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2479                                llvm::Value *Address) const override {
2480     llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2481 
2482     // 0-15 are the 16 integer registers.
2483     // 16 is %rip.
2484     AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2485     return false;
2486   }
2487 
2488   llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
2489                                   StringRef Constraint,
2490                                   llvm::Type* Ty) const override {
2491     return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2492   }
2493 
2494   bool isNoProtoCallVariadic(const CallArgList &args,
2495                              const FunctionNoProtoType *fnType) const override {
2496     // The default CC on x86-64 sets %al to the number of SSA
2497     // registers used, and GCC sets this when calling an unprototyped
2498     // function, so we override the default behavior.  However, don't do
2499     // that when AVX types are involved: the ABI explicitly states it is
2500     // undefined, and it doesn't work in practice because of how the ABI
2501     // defines varargs anyway.
2502     if (fnType->getCallConv() == CC_C) {
2503       bool HasAVXType = false;
2504       for (CallArgList::const_iterator
2505              it = args.begin(), ie = args.end(); it != ie; ++it) {
2506         if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2507           HasAVXType = true;
2508           break;
2509         }
2510       }
2511 
2512       if (!HasAVXType)
2513         return true;
2514     }
2515 
2516     return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
2517   }
2518 
2519   llvm::Constant *
2520   getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
2521     unsigned Sig = (0xeb << 0) | // jmp rel8
2522                    (0x06 << 8) | //           .+0x08
2523                    ('v' << 16) |
2524                    ('2' << 24);
2525     return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2526   }
2527 
2528   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2529                            CodeGen::CodeGenModule &CGM) const override {
2530     if (GV->isDeclaration())
2531       return;
2532     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2533       if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2534         llvm::Function *Fn = cast<llvm::Function>(GV);
2535         Fn->addFnAttr("stackrealign");
2536       }
2537 
2538       addX86InterruptAttrs(FD, GV, CGM);
2539     }
2540   }
2541 
2542   void checkFunctionCallABI(CodeGenModule &CGM, SourceLocation CallLoc,
2543                             const FunctionDecl *Caller,
2544                             const FunctionDecl *Callee,
2545                             const CallArgList &Args) const override;
2546 };
2547 
2548 static void initFeatureMaps(const ASTContext &Ctx,
2549                             llvm::StringMap<bool> &CallerMap,
2550                             const FunctionDecl *Caller,
2551                             llvm::StringMap<bool> &CalleeMap,
2552                             const FunctionDecl *Callee) {
2553   if (CalleeMap.empty() && CallerMap.empty()) {
2554     // The caller is potentially nullptr in the case where the call isn't in a
2555     // function.  In this case, the getFunctionFeatureMap ensures we just get
2556     // the TU level setting (since it cannot be modified by 'target'..
2557     Ctx.getFunctionFeatureMap(CallerMap, Caller);
2558     Ctx.getFunctionFeatureMap(CalleeMap, Callee);
2559   }
2560 }
2561 
2562 static bool checkAVXParamFeature(DiagnosticsEngine &Diag,
2563                                  SourceLocation CallLoc,
2564                                  const llvm::StringMap<bool> &CallerMap,
2565                                  const llvm::StringMap<bool> &CalleeMap,
2566                                  QualType Ty, StringRef Feature,
2567                                  bool IsArgument) {
2568   bool CallerHasFeat = CallerMap.lookup(Feature);
2569   bool CalleeHasFeat = CalleeMap.lookup(Feature);
2570   if (!CallerHasFeat && !CalleeHasFeat)
2571     return Diag.Report(CallLoc, diag::warn_avx_calling_convention)
2572            << IsArgument << Ty << Feature;
2573 
2574   // Mixing calling conventions here is very clearly an error.
2575   if (!CallerHasFeat || !CalleeHasFeat)
2576     return Diag.Report(CallLoc, diag::err_avx_calling_convention)
2577            << IsArgument << Ty << Feature;
2578 
2579   // Else, both caller and callee have the required feature, so there is no need
2580   // to diagnose.
2581   return false;
2582 }
2583 
2584 static bool checkAVXParam(DiagnosticsEngine &Diag, ASTContext &Ctx,
2585                           SourceLocation CallLoc,
2586                           const llvm::StringMap<bool> &CallerMap,
2587                           const llvm::StringMap<bool> &CalleeMap, QualType Ty,
2588                           bool IsArgument) {
2589   uint64_t Size = Ctx.getTypeSize(Ty);
2590   if (Size > 256)
2591     return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty,
2592                                 "avx512f", IsArgument);
2593 
2594   if (Size > 128)
2595     return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty, "avx",
2596                                 IsArgument);
2597 
2598   return false;
2599 }
2600 
2601 void X86_64TargetCodeGenInfo::checkFunctionCallABI(
2602     CodeGenModule &CGM, SourceLocation CallLoc, const FunctionDecl *Caller,
2603     const FunctionDecl *Callee, const CallArgList &Args) const {
2604   llvm::StringMap<bool> CallerMap;
2605   llvm::StringMap<bool> CalleeMap;
2606   unsigned ArgIndex = 0;
2607 
2608   // We need to loop through the actual call arguments rather than the the
2609   // function's parameters, in case this variadic.
2610   for (const CallArg &Arg : Args) {
2611     // The "avx" feature changes how vectors >128 in size are passed. "avx512f"
2612     // additionally changes how vectors >256 in size are passed. Like GCC, we
2613     // warn when a function is called with an argument where this will change.
2614     // Unlike GCC, we also error when it is an obvious ABI mismatch, that is,
2615     // the caller and callee features are mismatched.
2616     // Unfortunately, we cannot do this diagnostic in SEMA, since the callee can
2617     // change its ABI with attribute-target after this call.
2618     if (Arg.getType()->isVectorType() &&
2619         CGM.getContext().getTypeSize(Arg.getType()) > 128) {
2620       initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
2621       QualType Ty = Arg.getType();
2622       // The CallArg seems to have desugared the type already, so for clearer
2623       // diagnostics, replace it with the type in the FunctionDecl if possible.
2624       if (ArgIndex < Callee->getNumParams())
2625         Ty = Callee->getParamDecl(ArgIndex)->getType();
2626 
2627       if (checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap,
2628                         CalleeMap, Ty, /*IsArgument*/ true))
2629         return;
2630     }
2631     ++ArgIndex;
2632   }
2633 
2634   // Check return always, as we don't have a good way of knowing in codegen
2635   // whether this value is used, tail-called, etc.
2636   if (Callee->getReturnType()->isVectorType() &&
2637       CGM.getContext().getTypeSize(Callee->getReturnType()) > 128) {
2638     initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
2639     checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap,
2640                   CalleeMap, Callee->getReturnType(),
2641                   /*IsArgument*/ false);
2642   }
2643 }
2644 
2645 static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
2646   // If the argument does not end in .lib, automatically add the suffix.
2647   // If the argument contains a space, enclose it in quotes.
2648   // This matches the behavior of MSVC.
2649   bool Quote = Lib.contains(' ');
2650   std::string ArgStr = Quote ? "\"" : "";
2651   ArgStr += Lib;
2652   if (!Lib.endswith_insensitive(".lib") && !Lib.endswith_insensitive(".a"))
2653     ArgStr += ".lib";
2654   ArgStr += Quote ? "\"" : "";
2655   return ArgStr;
2656 }
2657 
2658 class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2659 public:
2660   WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2661         bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2662         unsigned NumRegisterParameters)
2663     : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
2664         Win32StructABI, NumRegisterParameters, false) {}
2665 
2666   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2667                            CodeGen::CodeGenModule &CGM) const override;
2668 
2669   void getDependentLibraryOption(llvm::StringRef Lib,
2670                                  llvm::SmallString<24> &Opt) const override {
2671     Opt = "/DEFAULTLIB:";
2672     Opt += qualifyWindowsLibrary(Lib);
2673   }
2674 
2675   void getDetectMismatchOption(llvm::StringRef Name,
2676                                llvm::StringRef Value,
2677                                llvm::SmallString<32> &Opt) const override {
2678     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2679   }
2680 };
2681 
2682 static void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2683                                           CodeGen::CodeGenModule &CGM) {
2684   if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(GV)) {
2685 
2686     if (CGM.getCodeGenOpts().StackProbeSize != 4096)
2687       Fn->addFnAttr("stack-probe-size",
2688                     llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
2689     if (CGM.getCodeGenOpts().NoStackArgProbe)
2690       Fn->addFnAttr("no-stack-arg-probe");
2691   }
2692 }
2693 
2694 void WinX86_32TargetCodeGenInfo::setTargetAttributes(
2695     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2696   X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2697   if (GV->isDeclaration())
2698     return;
2699   addStackProbeTargetAttributes(D, GV, CGM);
2700 }
2701 
2702 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2703 public:
2704   WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2705                              X86AVXABILevel AVXLevel)
2706       : TargetCodeGenInfo(std::make_unique<WinX86_64ABIInfo>(CGT, AVXLevel)) {}
2707 
2708   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2709                            CodeGen::CodeGenModule &CGM) const override;
2710 
2711   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2712     return 7;
2713   }
2714 
2715   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2716                                llvm::Value *Address) const override {
2717     llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2718 
2719     // 0-15 are the 16 integer registers.
2720     // 16 is %rip.
2721     AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2722     return false;
2723   }
2724 
2725   void getDependentLibraryOption(llvm::StringRef Lib,
2726                                  llvm::SmallString<24> &Opt) const override {
2727     Opt = "/DEFAULTLIB:";
2728     Opt += qualifyWindowsLibrary(Lib);
2729   }
2730 
2731   void getDetectMismatchOption(llvm::StringRef Name,
2732                                llvm::StringRef Value,
2733                                llvm::SmallString<32> &Opt) const override {
2734     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2735   }
2736 };
2737 
2738 void WinX86_64TargetCodeGenInfo::setTargetAttributes(
2739     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2740   TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2741   if (GV->isDeclaration())
2742     return;
2743   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2744     if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2745       llvm::Function *Fn = cast<llvm::Function>(GV);
2746       Fn->addFnAttr("stackrealign");
2747     }
2748 
2749     addX86InterruptAttrs(FD, GV, CGM);
2750   }
2751 
2752   addStackProbeTargetAttributes(D, GV, CGM);
2753 }
2754 }
2755 
2756 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2757                               Class &Hi) const {
2758   // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2759   //
2760   // (a) If one of the classes is Memory, the whole argument is passed in
2761   //     memory.
2762   //
2763   // (b) If X87UP is not preceded by X87, the whole argument is passed in
2764   //     memory.
2765   //
2766   // (c) If the size of the aggregate exceeds two eightbytes and the first
2767   //     eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2768   //     argument is passed in memory. NOTE: This is necessary to keep the
2769   //     ABI working for processors that don't support the __m256 type.
2770   //
2771   // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2772   //
2773   // Some of these are enforced by the merging logic.  Others can arise
2774   // only with unions; for example:
2775   //   union { _Complex double; unsigned; }
2776   //
2777   // Note that clauses (b) and (c) were added in 0.98.
2778   //
2779   if (Hi == Memory)
2780     Lo = Memory;
2781   if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2782     Lo = Memory;
2783   if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2784     Lo = Memory;
2785   if (Hi == SSEUp && Lo != SSE)
2786     Hi = SSE;
2787 }
2788 
2789 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
2790   // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2791   // classified recursively so that always two fields are
2792   // considered. The resulting class is calculated according to
2793   // the classes of the fields in the eightbyte:
2794   //
2795   // (a) If both classes are equal, this is the resulting class.
2796   //
2797   // (b) If one of the classes is NO_CLASS, the resulting class is
2798   // the other class.
2799   //
2800   // (c) If one of the classes is MEMORY, the result is the MEMORY
2801   // class.
2802   //
2803   // (d) If one of the classes is INTEGER, the result is the
2804   // INTEGER.
2805   //
2806   // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2807   // MEMORY is used as class.
2808   //
2809   // (f) Otherwise class SSE is used.
2810 
2811   // Accum should never be memory (we should have returned) or
2812   // ComplexX87 (because this cannot be passed in a structure).
2813   assert((Accum != Memory && Accum != ComplexX87) &&
2814          "Invalid accumulated classification during merge.");
2815   if (Accum == Field || Field == NoClass)
2816     return Accum;
2817   if (Field == Memory)
2818     return Memory;
2819   if (Accum == NoClass)
2820     return Field;
2821   if (Accum == Integer || Field == Integer)
2822     return Integer;
2823   if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2824       Accum == X87 || Accum == X87Up)
2825     return Memory;
2826   return SSE;
2827 }
2828 
2829 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
2830                              Class &Lo, Class &Hi, bool isNamedArg) const {
2831   // FIXME: This code can be simplified by introducing a simple value class for
2832   // Class pairs with appropriate constructor methods for the various
2833   // situations.
2834 
2835   // FIXME: Some of the split computations are wrong; unaligned vectors
2836   // shouldn't be passed in registers for example, so there is no chance they
2837   // can straddle an eightbyte. Verify & simplify.
2838 
2839   Lo = Hi = NoClass;
2840 
2841   Class &Current = OffsetBase < 64 ? Lo : Hi;
2842   Current = Memory;
2843 
2844   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
2845     BuiltinType::Kind k = BT->getKind();
2846 
2847     if (k == BuiltinType::Void) {
2848       Current = NoClass;
2849     } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2850       Lo = Integer;
2851       Hi = Integer;
2852     } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2853       Current = Integer;
2854     } else if (k == BuiltinType::Float || k == BuiltinType::Double ||
2855                k == BuiltinType::Float16) {
2856       Current = SSE;
2857     } else if (k == BuiltinType::LongDouble) {
2858       const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2859       if (LDF == &llvm::APFloat::IEEEquad()) {
2860         Lo = SSE;
2861         Hi = SSEUp;
2862       } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
2863         Lo = X87;
2864         Hi = X87Up;
2865       } else if (LDF == &llvm::APFloat::IEEEdouble()) {
2866         Current = SSE;
2867       } else
2868         llvm_unreachable("unexpected long double representation!");
2869     }
2870     // FIXME: _Decimal32 and _Decimal64 are SSE.
2871     // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
2872     return;
2873   }
2874 
2875   if (const EnumType *ET = Ty->getAs<EnumType>()) {
2876     // Classify the underlying integer type.
2877     classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
2878     return;
2879   }
2880 
2881   if (Ty->hasPointerRepresentation()) {
2882     Current = Integer;
2883     return;
2884   }
2885 
2886   if (Ty->isMemberPointerType()) {
2887     if (Ty->isMemberFunctionPointerType()) {
2888       if (Has64BitPointers) {
2889         // If Has64BitPointers, this is an {i64, i64}, so classify both
2890         // Lo and Hi now.
2891         Lo = Hi = Integer;
2892       } else {
2893         // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2894         // straddles an eightbyte boundary, Hi should be classified as well.
2895         uint64_t EB_FuncPtr = (OffsetBase) / 64;
2896         uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2897         if (EB_FuncPtr != EB_ThisAdj) {
2898           Lo = Hi = Integer;
2899         } else {
2900           Current = Integer;
2901         }
2902       }
2903     } else {
2904       Current = Integer;
2905     }
2906     return;
2907   }
2908 
2909   if (const VectorType *VT = Ty->getAs<VectorType>()) {
2910     uint64_t Size = getContext().getTypeSize(VT);
2911     if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2912       // gcc passes the following as integer:
2913       // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2914       // 2 bytes - <2 x char>, <1 x short>
2915       // 1 byte  - <1 x char>
2916       Current = Integer;
2917 
2918       // If this type crosses an eightbyte boundary, it should be
2919       // split.
2920       uint64_t EB_Lo = (OffsetBase) / 64;
2921       uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2922       if (EB_Lo != EB_Hi)
2923         Hi = Lo;
2924     } else if (Size == 64) {
2925       QualType ElementType = VT->getElementType();
2926 
2927       // gcc passes <1 x double> in memory. :(
2928       if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
2929         return;
2930 
2931       // gcc passes <1 x long long> as SSE but clang used to unconditionally
2932       // pass them as integer.  For platforms where clang is the de facto
2933       // platform compiler, we must continue to use integer.
2934       if (!classifyIntegerMMXAsSSE() &&
2935           (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2936            ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2937            ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2938            ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
2939         Current = Integer;
2940       else
2941         Current = SSE;
2942 
2943       // If this type crosses an eightbyte boundary, it should be
2944       // split.
2945       if (OffsetBase && OffsetBase != 64)
2946         Hi = Lo;
2947     } else if (Size == 128 ||
2948                (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
2949       QualType ElementType = VT->getElementType();
2950 
2951       // gcc passes 256 and 512 bit <X x __int128> vectors in memory. :(
2952       if (passInt128VectorsInMem() && Size != 128 &&
2953           (ElementType->isSpecificBuiltinType(BuiltinType::Int128) ||
2954            ElementType->isSpecificBuiltinType(BuiltinType::UInt128)))
2955         return;
2956 
2957       // Arguments of 256-bits are split into four eightbyte chunks. The
2958       // least significant one belongs to class SSE and all the others to class
2959       // SSEUP. The original Lo and Hi design considers that types can't be
2960       // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2961       // This design isn't correct for 256-bits, but since there're no cases
2962       // where the upper parts would need to be inspected, avoid adding
2963       // complexity and just consider Hi to match the 64-256 part.
2964       //
2965       // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2966       // registers if they are "named", i.e. not part of the "..." of a
2967       // variadic function.
2968       //
2969       // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2970       // split into eight eightbyte chunks, one SSE and seven SSEUP.
2971       Lo = SSE;
2972       Hi = SSEUp;
2973     }
2974     return;
2975   }
2976 
2977   if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
2978     QualType ET = getContext().getCanonicalType(CT->getElementType());
2979 
2980     uint64_t Size = getContext().getTypeSize(Ty);
2981     if (ET->isIntegralOrEnumerationType()) {
2982       if (Size <= 64)
2983         Current = Integer;
2984       else if (Size <= 128)
2985         Lo = Hi = Integer;
2986     } else if (ET->isFloat16Type() || ET == getContext().FloatTy) {
2987       Current = SSE;
2988     } else if (ET == getContext().DoubleTy) {
2989       Lo = Hi = SSE;
2990     } else if (ET == getContext().LongDoubleTy) {
2991       const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2992       if (LDF == &llvm::APFloat::IEEEquad())
2993         Current = Memory;
2994       else if (LDF == &llvm::APFloat::x87DoubleExtended())
2995         Current = ComplexX87;
2996       else if (LDF == &llvm::APFloat::IEEEdouble())
2997         Lo = Hi = SSE;
2998       else
2999         llvm_unreachable("unexpected long double representation!");
3000     }
3001 
3002     // If this complex type crosses an eightbyte boundary then it
3003     // should be split.
3004     uint64_t EB_Real = (OffsetBase) / 64;
3005     uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
3006     if (Hi == NoClass && EB_Real != EB_Imag)
3007       Hi = Lo;
3008 
3009     return;
3010   }
3011 
3012   if (const auto *EITy = Ty->getAs<BitIntType>()) {
3013     if (EITy->getNumBits() <= 64)
3014       Current = Integer;
3015     else if (EITy->getNumBits() <= 128)
3016       Lo = Hi = Integer;
3017     // Larger values need to get passed in memory.
3018     return;
3019   }
3020 
3021   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
3022     // Arrays are treated like structures.
3023 
3024     uint64_t Size = getContext().getTypeSize(Ty);
3025 
3026     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
3027     // than eight eightbytes, ..., it has class MEMORY.
3028     if (Size > 512)
3029       return;
3030 
3031     // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
3032     // fields, it has class MEMORY.
3033     //
3034     // Only need to check alignment of array base.
3035     if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
3036       return;
3037 
3038     // Otherwise implement simplified merge. We could be smarter about
3039     // this, but it isn't worth it and would be harder to verify.
3040     Current = NoClass;
3041     uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
3042     uint64_t ArraySize = AT->getSize().getZExtValue();
3043 
3044     // The only case a 256-bit wide vector could be used is when the array
3045     // contains a single 256-bit element. Since Lo and Hi logic isn't extended
3046     // to work for sizes wider than 128, early check and fallback to memory.
3047     //
3048     if (Size > 128 &&
3049         (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
3050       return;
3051 
3052     for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
3053       Class FieldLo, FieldHi;
3054       classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
3055       Lo = merge(Lo, FieldLo);
3056       Hi = merge(Hi, FieldHi);
3057       if (Lo == Memory || Hi == Memory)
3058         break;
3059     }
3060 
3061     postMerge(Size, Lo, Hi);
3062     assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
3063     return;
3064   }
3065 
3066   if (const RecordType *RT = Ty->getAs<RecordType>()) {
3067     uint64_t Size = getContext().getTypeSize(Ty);
3068 
3069     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
3070     // than eight eightbytes, ..., it has class MEMORY.
3071     if (Size > 512)
3072       return;
3073 
3074     // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
3075     // copy constructor or a non-trivial destructor, it is passed by invisible
3076     // reference.
3077     if (getRecordArgABI(RT, getCXXABI()))
3078       return;
3079 
3080     const RecordDecl *RD = RT->getDecl();
3081 
3082     // Assume variable sized types are passed in memory.
3083     if (RD->hasFlexibleArrayMember())
3084       return;
3085 
3086     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
3087 
3088     // Reset Lo class, this will be recomputed.
3089     Current = NoClass;
3090 
3091     // If this is a C++ record, classify the bases first.
3092     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3093       for (const auto &I : CXXRD->bases()) {
3094         assert(!I.isVirtual() && !I.getType()->isDependentType() &&
3095                "Unexpected base class!");
3096         const auto *Base =
3097             cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
3098 
3099         // Classify this field.
3100         //
3101         // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
3102         // single eightbyte, each is classified separately. Each eightbyte gets
3103         // initialized to class NO_CLASS.
3104         Class FieldLo, FieldHi;
3105         uint64_t Offset =
3106           OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
3107         classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
3108         Lo = merge(Lo, FieldLo);
3109         Hi = merge(Hi, FieldHi);
3110         if (Lo == Memory || Hi == Memory) {
3111           postMerge(Size, Lo, Hi);
3112           return;
3113         }
3114       }
3115     }
3116 
3117     // Classify the fields one at a time, merging the results.
3118     unsigned idx = 0;
3119     bool UseClang11Compat = getContext().getLangOpts().getClangABICompat() <=
3120                                 LangOptions::ClangABI::Ver11 ||
3121                             getContext().getTargetInfo().getTriple().isPS4();
3122     bool IsUnion = RT->isUnionType() && !UseClang11Compat;
3123 
3124     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3125            i != e; ++i, ++idx) {
3126       uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
3127       bool BitField = i->isBitField();
3128 
3129       // Ignore padding bit-fields.
3130       if (BitField && i->isUnnamedBitfield())
3131         continue;
3132 
3133       // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
3134       // eight eightbytes, or it contains unaligned fields, it has class MEMORY.
3135       //
3136       // The only case a 256-bit or a 512-bit wide vector could be used is when
3137       // the struct contains a single 256-bit or 512-bit element. Early check
3138       // and fallback to memory.
3139       //
3140       // FIXME: Extended the Lo and Hi logic properly to work for size wider
3141       // than 128.
3142       if (Size > 128 &&
3143           ((!IsUnion && Size != getContext().getTypeSize(i->getType())) ||
3144            Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
3145         Lo = Memory;
3146         postMerge(Size, Lo, Hi);
3147         return;
3148       }
3149       // Note, skip this test for bit-fields, see below.
3150       if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
3151         Lo = Memory;
3152         postMerge(Size, Lo, Hi);
3153         return;
3154       }
3155 
3156       // Classify this field.
3157       //
3158       // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
3159       // exceeds a single eightbyte, each is classified
3160       // separately. Each eightbyte gets initialized to class
3161       // NO_CLASS.
3162       Class FieldLo, FieldHi;
3163 
3164       // Bit-fields require special handling, they do not force the
3165       // structure to be passed in memory even if unaligned, and
3166       // therefore they can straddle an eightbyte.
3167       if (BitField) {
3168         assert(!i->isUnnamedBitfield());
3169         uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
3170         uint64_t Size = i->getBitWidthValue(getContext());
3171 
3172         uint64_t EB_Lo = Offset / 64;
3173         uint64_t EB_Hi = (Offset + Size - 1) / 64;
3174 
3175         if (EB_Lo) {
3176           assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
3177           FieldLo = NoClass;
3178           FieldHi = Integer;
3179         } else {
3180           FieldLo = Integer;
3181           FieldHi = EB_Hi ? Integer : NoClass;
3182         }
3183       } else
3184         classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
3185       Lo = merge(Lo, FieldLo);
3186       Hi = merge(Hi, FieldHi);
3187       if (Lo == Memory || Hi == Memory)
3188         break;
3189     }
3190 
3191     postMerge(Size, Lo, Hi);
3192   }
3193 }
3194 
3195 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
3196   // If this is a scalar LLVM value then assume LLVM will pass it in the right
3197   // place naturally.
3198   if (!isAggregateTypeForABI(Ty)) {
3199     // Treat an enum type as its underlying type.
3200     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3201       Ty = EnumTy->getDecl()->getIntegerType();
3202 
3203     if (Ty->isBitIntType())
3204       return getNaturalAlignIndirect(Ty);
3205 
3206     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
3207                                               : ABIArgInfo::getDirect());
3208   }
3209 
3210   return getNaturalAlignIndirect(Ty);
3211 }
3212 
3213 bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
3214   if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
3215     uint64_t Size = getContext().getTypeSize(VecTy);
3216     unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
3217     if (Size <= 64 || Size > LargestVector)
3218       return true;
3219     QualType EltTy = VecTy->getElementType();
3220     if (passInt128VectorsInMem() &&
3221         (EltTy->isSpecificBuiltinType(BuiltinType::Int128) ||
3222          EltTy->isSpecificBuiltinType(BuiltinType::UInt128)))
3223       return true;
3224   }
3225 
3226   return false;
3227 }
3228 
3229 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
3230                                             unsigned freeIntRegs) const {
3231   // If this is a scalar LLVM value then assume LLVM will pass it in the right
3232   // place naturally.
3233   //
3234   // This assumption is optimistic, as there could be free registers available
3235   // when we need to pass this argument in memory, and LLVM could try to pass
3236   // the argument in the free register. This does not seem to happen currently,
3237   // but this code would be much safer if we could mark the argument with
3238   // 'onstack'. See PR12193.
3239   if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty) &&
3240       !Ty->isBitIntType()) {
3241     // Treat an enum type as its underlying type.
3242     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3243       Ty = EnumTy->getDecl()->getIntegerType();
3244 
3245     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
3246                                               : ABIArgInfo::getDirect());
3247   }
3248 
3249   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
3250     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
3251 
3252   // Compute the byval alignment. We specify the alignment of the byval in all
3253   // cases so that the mid-level optimizer knows the alignment of the byval.
3254   unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
3255 
3256   // Attempt to avoid passing indirect results using byval when possible. This
3257   // is important for good codegen.
3258   //
3259   // We do this by coercing the value into a scalar type which the backend can
3260   // handle naturally (i.e., without using byval).
3261   //
3262   // For simplicity, we currently only do this when we have exhausted all of the
3263   // free integer registers. Doing this when there are free integer registers
3264   // would require more care, as we would have to ensure that the coerced value
3265   // did not claim the unused register. That would require either reording the
3266   // arguments to the function (so that any subsequent inreg values came first),
3267   // or only doing this optimization when there were no following arguments that
3268   // might be inreg.
3269   //
3270   // We currently expect it to be rare (particularly in well written code) for
3271   // arguments to be passed on the stack when there are still free integer
3272   // registers available (this would typically imply large structs being passed
3273   // by value), so this seems like a fair tradeoff for now.
3274   //
3275   // We can revisit this if the backend grows support for 'onstack' parameter
3276   // attributes. See PR12193.
3277   if (freeIntRegs == 0) {
3278     uint64_t Size = getContext().getTypeSize(Ty);
3279 
3280     // If this type fits in an eightbyte, coerce it into the matching integral
3281     // type, which will end up on the stack (with alignment 8).
3282     if (Align == 8 && Size <= 64)
3283       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
3284                                                           Size));
3285   }
3286 
3287   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
3288 }
3289 
3290 /// The ABI specifies that a value should be passed in a full vector XMM/YMM
3291 /// register. Pick an LLVM IR type that will be passed as a vector register.
3292 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
3293   // Wrapper structs/arrays that only contain vectors are passed just like
3294   // vectors; strip them off if present.
3295   if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
3296     Ty = QualType(InnerTy, 0);
3297 
3298   llvm::Type *IRType = CGT.ConvertType(Ty);
3299   if (isa<llvm::VectorType>(IRType)) {
3300     // Don't pass vXi128 vectors in their native type, the backend can't
3301     // legalize them.
3302     if (passInt128VectorsInMem() &&
3303         cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy(128)) {
3304       // Use a vXi64 vector.
3305       uint64_t Size = getContext().getTypeSize(Ty);
3306       return llvm::FixedVectorType::get(llvm::Type::getInt64Ty(getVMContext()),
3307                                         Size / 64);
3308     }
3309 
3310     return IRType;
3311   }
3312 
3313   if (IRType->getTypeID() == llvm::Type::FP128TyID)
3314     return IRType;
3315 
3316   // We couldn't find the preferred IR vector type for 'Ty'.
3317   uint64_t Size = getContext().getTypeSize(Ty);
3318   assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
3319 
3320 
3321   // Return a LLVM IR vector type based on the size of 'Ty'.
3322   return llvm::FixedVectorType::get(llvm::Type::getDoubleTy(getVMContext()),
3323                                     Size / 64);
3324 }
3325 
3326 /// BitsContainNoUserData - Return true if the specified [start,end) bit range
3327 /// is known to either be off the end of the specified type or being in
3328 /// alignment padding.  The user type specified is known to be at most 128 bits
3329 /// in size, and have passed through X86_64ABIInfo::classify with a successful
3330 /// classification that put one of the two halves in the INTEGER class.
3331 ///
3332 /// It is conservatively correct to return false.
3333 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
3334                                   unsigned EndBit, ASTContext &Context) {
3335   // If the bytes being queried are off the end of the type, there is no user
3336   // data hiding here.  This handles analysis of builtins, vectors and other
3337   // types that don't contain interesting padding.
3338   unsigned TySize = (unsigned)Context.getTypeSize(Ty);
3339   if (TySize <= StartBit)
3340     return true;
3341 
3342   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
3343     unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
3344     unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
3345 
3346     // Check each element to see if the element overlaps with the queried range.
3347     for (unsigned i = 0; i != NumElts; ++i) {
3348       // If the element is after the span we care about, then we're done..
3349       unsigned EltOffset = i*EltSize;
3350       if (EltOffset >= EndBit) break;
3351 
3352       unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
3353       if (!BitsContainNoUserData(AT->getElementType(), EltStart,
3354                                  EndBit-EltOffset, Context))
3355         return false;
3356     }
3357     // If it overlaps no elements, then it is safe to process as padding.
3358     return true;
3359   }
3360 
3361   if (const RecordType *RT = Ty->getAs<RecordType>()) {
3362     const RecordDecl *RD = RT->getDecl();
3363     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3364 
3365     // If this is a C++ record, check the bases first.
3366     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3367       for (const auto &I : CXXRD->bases()) {
3368         assert(!I.isVirtual() && !I.getType()->isDependentType() &&
3369                "Unexpected base class!");
3370         const auto *Base =
3371             cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
3372 
3373         // If the base is after the span we care about, ignore it.
3374         unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
3375         if (BaseOffset >= EndBit) continue;
3376 
3377         unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
3378         if (!BitsContainNoUserData(I.getType(), BaseStart,
3379                                    EndBit-BaseOffset, Context))
3380           return false;
3381       }
3382     }
3383 
3384     // Verify that no field has data that overlaps the region of interest.  Yes
3385     // this could be sped up a lot by being smarter about queried fields,
3386     // however we're only looking at structs up to 16 bytes, so we don't care
3387     // much.
3388     unsigned idx = 0;
3389     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3390          i != e; ++i, ++idx) {
3391       unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
3392 
3393       // If we found a field after the region we care about, then we're done.
3394       if (FieldOffset >= EndBit) break;
3395 
3396       unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
3397       if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
3398                                  Context))
3399         return false;
3400     }
3401 
3402     // If nothing in this record overlapped the area of interest, then we're
3403     // clean.
3404     return true;
3405   }
3406 
3407   return false;
3408 }
3409 
3410 /// getFPTypeAtOffset - Return a floating point type at the specified offset.
3411 static llvm::Type *getFPTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3412                                      const llvm::DataLayout &TD) {
3413   if (IROffset == 0 && IRType->isFloatingPointTy())
3414     return IRType;
3415 
3416   // If this is a struct, recurse into the field at the specified offset.
3417   if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3418     if (!STy->getNumContainedTypes())
3419       return nullptr;
3420 
3421     const llvm::StructLayout *SL = TD.getStructLayout(STy);
3422     unsigned Elt = SL->getElementContainingOffset(IROffset);
3423     IROffset -= SL->getElementOffset(Elt);
3424     return getFPTypeAtOffset(STy->getElementType(Elt), IROffset, TD);
3425   }
3426 
3427   // If this is an array, recurse into the field at the specified offset.
3428   if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3429     llvm::Type *EltTy = ATy->getElementType();
3430     unsigned EltSize = TD.getTypeAllocSize(EltTy);
3431     IROffset -= IROffset / EltSize * EltSize;
3432     return getFPTypeAtOffset(EltTy, IROffset, TD);
3433   }
3434 
3435   return nullptr;
3436 }
3437 
3438 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
3439 /// low 8 bytes of an XMM register, corresponding to the SSE class.
3440 llvm::Type *X86_64ABIInfo::
3441 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3442                    QualType SourceTy, unsigned SourceOffset) const {
3443   const llvm::DataLayout &TD = getDataLayout();
3444   unsigned SourceSize =
3445       (unsigned)getContext().getTypeSize(SourceTy) / 8 - SourceOffset;
3446   llvm::Type *T0 = getFPTypeAtOffset(IRType, IROffset, TD);
3447   if (!T0 || T0->isDoubleTy())
3448     return llvm::Type::getDoubleTy(getVMContext());
3449 
3450   // Get the adjacent FP type.
3451   llvm::Type *T1 = nullptr;
3452   unsigned T0Size = TD.getTypeAllocSize(T0);
3453   if (SourceSize > T0Size)
3454       T1 = getFPTypeAtOffset(IRType, IROffset + T0Size, TD);
3455   if (T1 == nullptr) {
3456     // Check if IRType is a half + float. float type will be in IROffset+4 due
3457     // to its alignment.
3458     if (T0->isHalfTy() && SourceSize > 4)
3459       T1 = getFPTypeAtOffset(IRType, IROffset + 4, TD);
3460     // If we can't get a second FP type, return a simple half or float.
3461     // avx512fp16-abi.c:pr51813_2 shows it works to return float for
3462     // {float, i8} too.
3463     if (T1 == nullptr)
3464       return T0;
3465   }
3466 
3467   if (T0->isFloatTy() && T1->isFloatTy())
3468     return llvm::FixedVectorType::get(T0, 2);
3469 
3470   if (T0->isHalfTy() && T1->isHalfTy()) {
3471     llvm::Type *T2 = nullptr;
3472     if (SourceSize > 4)
3473       T2 = getFPTypeAtOffset(IRType, IROffset + 4, TD);
3474     if (T2 == nullptr)
3475       return llvm::FixedVectorType::get(T0, 2);
3476     return llvm::FixedVectorType::get(T0, 4);
3477   }
3478 
3479   if (T0->isHalfTy() || T1->isHalfTy())
3480     return llvm::FixedVectorType::get(llvm::Type::getHalfTy(getVMContext()), 4);
3481 
3482   return llvm::Type::getDoubleTy(getVMContext());
3483 }
3484 
3485 
3486 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
3487 /// an 8-byte GPR.  This means that we either have a scalar or we are talking
3488 /// about the high or low part of an up-to-16-byte struct.  This routine picks
3489 /// the best LLVM IR type to represent this, which may be i64 or may be anything
3490 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
3491 /// etc).
3492 ///
3493 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
3494 /// the source type.  IROffset is an offset in bytes into the LLVM IR type that
3495 /// the 8-byte value references.  PrefType may be null.
3496 ///
3497 /// SourceTy is the source-level type for the entire argument.  SourceOffset is
3498 /// an offset into this that we're processing (which is always either 0 or 8).
3499 ///
3500 llvm::Type *X86_64ABIInfo::
3501 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3502                        QualType SourceTy, unsigned SourceOffset) const {
3503   // If we're dealing with an un-offset LLVM IR type, then it means that we're
3504   // returning an 8-byte unit starting with it.  See if we can safely use it.
3505   if (IROffset == 0) {
3506     // Pointers and int64's always fill the 8-byte unit.
3507     if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
3508         IRType->isIntegerTy(64))
3509       return IRType;
3510 
3511     // If we have a 1/2/4-byte integer, we can use it only if the rest of the
3512     // goodness in the source type is just tail padding.  This is allowed to
3513     // kick in for struct {double,int} on the int, but not on
3514     // struct{double,int,int} because we wouldn't return the second int.  We
3515     // have to do this analysis on the source type because we can't depend on
3516     // unions being lowered a specific way etc.
3517     if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
3518         IRType->isIntegerTy(32) ||
3519         (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
3520       unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
3521           cast<llvm::IntegerType>(IRType)->getBitWidth();
3522 
3523       if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
3524                                 SourceOffset*8+64, getContext()))
3525         return IRType;
3526     }
3527   }
3528 
3529   if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3530     // If this is a struct, recurse into the field at the specified offset.
3531     const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
3532     if (IROffset < SL->getSizeInBytes()) {
3533       unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
3534       IROffset -= SL->getElementOffset(FieldIdx);
3535 
3536       return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
3537                                     SourceTy, SourceOffset);
3538     }
3539   }
3540 
3541   if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3542     llvm::Type *EltTy = ATy->getElementType();
3543     unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
3544     unsigned EltOffset = IROffset/EltSize*EltSize;
3545     return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
3546                                   SourceOffset);
3547   }
3548 
3549   // Okay, we don't have any better idea of what to pass, so we pass this in an
3550   // integer register that isn't too big to fit the rest of the struct.
3551   unsigned TySizeInBytes =
3552     (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
3553 
3554   assert(TySizeInBytes != SourceOffset && "Empty field?");
3555 
3556   // It is always safe to classify this as an integer type up to i64 that
3557   // isn't larger than the structure.
3558   return llvm::IntegerType::get(getVMContext(),
3559                                 std::min(TySizeInBytes-SourceOffset, 8U)*8);
3560 }
3561 
3562 
3563 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
3564 /// be used as elements of a two register pair to pass or return, return a
3565 /// first class aggregate to represent them.  For example, if the low part of
3566 /// a by-value argument should be passed as i32* and the high part as float,
3567 /// return {i32*, float}.
3568 static llvm::Type *
3569 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
3570                            const llvm::DataLayout &TD) {
3571   // In order to correctly satisfy the ABI, we need to the high part to start
3572   // at offset 8.  If the high and low parts we inferred are both 4-byte types
3573   // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
3574   // the second element at offset 8.  Check for this:
3575   unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
3576   unsigned HiAlign = TD.getABITypeAlignment(Hi);
3577   unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
3578   assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
3579 
3580   // To handle this, we have to increase the size of the low part so that the
3581   // second element will start at an 8 byte offset.  We can't increase the size
3582   // of the second element because it might make us access off the end of the
3583   // struct.
3584   if (HiStart != 8) {
3585     // There are usually two sorts of types the ABI generation code can produce
3586     // for the low part of a pair that aren't 8 bytes in size: half, float or
3587     // i8/i16/i32.  This can also include pointers when they are 32-bit (X32 and
3588     // NaCl).
3589     // Promote these to a larger type.
3590     if (Lo->isHalfTy() || Lo->isFloatTy())
3591       Lo = llvm::Type::getDoubleTy(Lo->getContext());
3592     else {
3593       assert((Lo->isIntegerTy() || Lo->isPointerTy())
3594              && "Invalid/unknown lo type");
3595       Lo = llvm::Type::getInt64Ty(Lo->getContext());
3596     }
3597   }
3598 
3599   llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
3600 
3601   // Verify that the second element is at an 8-byte offset.
3602   assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
3603          "Invalid x86-64 argument pair!");
3604   return Result;
3605 }
3606 
3607 ABIArgInfo X86_64ABIInfo::
3608 classifyReturnType(QualType RetTy) const {
3609   // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3610   // classification algorithm.
3611   X86_64ABIInfo::Class Lo, Hi;
3612   classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
3613 
3614   // Check some invariants.
3615   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3616   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3617 
3618   llvm::Type *ResType = nullptr;
3619   switch (Lo) {
3620   case NoClass:
3621     if (Hi == NoClass)
3622       return ABIArgInfo::getIgnore();
3623     // If the low part is just padding, it takes no register, leave ResType
3624     // null.
3625     assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3626            "Unknown missing lo part");
3627     break;
3628 
3629   case SSEUp:
3630   case X87Up:
3631     llvm_unreachable("Invalid classification for lo word.");
3632 
3633     // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3634     // hidden argument.
3635   case Memory:
3636     return getIndirectReturnResult(RetTy);
3637 
3638     // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3639     // available register of the sequence %rax, %rdx is used.
3640   case Integer:
3641     ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3642 
3643     // If we have a sign or zero extended integer, make sure to return Extend
3644     // so that the parameter gets the right LLVM IR attributes.
3645     if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3646       // Treat an enum type as its underlying type.
3647       if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3648         RetTy = EnumTy->getDecl()->getIntegerType();
3649 
3650       if (RetTy->isIntegralOrEnumerationType() &&
3651           isPromotableIntegerTypeForABI(RetTy))
3652         return ABIArgInfo::getExtend(RetTy);
3653     }
3654     break;
3655 
3656     // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3657     // available SSE register of the sequence %xmm0, %xmm1 is used.
3658   case SSE:
3659     ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3660     break;
3661 
3662     // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3663     // returned on the X87 stack in %st0 as 80-bit x87 number.
3664   case X87:
3665     ResType = llvm::Type::getX86_FP80Ty(getVMContext());
3666     break;
3667 
3668     // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3669     // part of the value is returned in %st0 and the imaginary part in
3670     // %st1.
3671   case ComplexX87:
3672     assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
3673     ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
3674                                     llvm::Type::getX86_FP80Ty(getVMContext()));
3675     break;
3676   }
3677 
3678   llvm::Type *HighPart = nullptr;
3679   switch (Hi) {
3680     // Memory was handled previously and X87 should
3681     // never occur as a hi class.
3682   case Memory:
3683   case X87:
3684     llvm_unreachable("Invalid classification for hi word.");
3685 
3686   case ComplexX87: // Previously handled.
3687   case NoClass:
3688     break;
3689 
3690   case Integer:
3691     HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3692     if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3693       return ABIArgInfo::getDirect(HighPart, 8);
3694     break;
3695   case SSE:
3696     HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3697     if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3698       return ABIArgInfo::getDirect(HighPart, 8);
3699     break;
3700 
3701     // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
3702     // is passed in the next available eightbyte chunk if the last used
3703     // vector register.
3704     //
3705     // SSEUP should always be preceded by SSE, just widen.
3706   case SSEUp:
3707     assert(Lo == SSE && "Unexpected SSEUp classification.");
3708     ResType = GetByteVectorType(RetTy);
3709     break;
3710 
3711     // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3712     // returned together with the previous X87 value in %st0.
3713   case X87Up:
3714     // If X87Up is preceded by X87, we don't need to do
3715     // anything. However, in some cases with unions it may not be
3716     // preceded by X87. In such situations we follow gcc and pass the
3717     // extra bits in an SSE reg.
3718     if (Lo != X87) {
3719       HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3720       if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3721         return ABIArgInfo::getDirect(HighPart, 8);
3722     }
3723     break;
3724   }
3725 
3726   // If a high part was specified, merge it together with the low part.  It is
3727   // known to pass in the high eightbyte of the result.  We do this by forming a
3728   // first class struct aggregate with the high and low part: {low, high}
3729   if (HighPart)
3730     ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3731 
3732   return ABIArgInfo::getDirect(ResType);
3733 }
3734 
3735 ABIArgInfo X86_64ABIInfo::classifyArgumentType(
3736   QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3737   bool isNamedArg)
3738   const
3739 {
3740   Ty = useFirstFieldIfTransparentUnion(Ty);
3741 
3742   X86_64ABIInfo::Class Lo, Hi;
3743   classify(Ty, 0, Lo, Hi, isNamedArg);
3744 
3745   // Check some invariants.
3746   // FIXME: Enforce these by construction.
3747   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3748   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3749 
3750   neededInt = 0;
3751   neededSSE = 0;
3752   llvm::Type *ResType = nullptr;
3753   switch (Lo) {
3754   case NoClass:
3755     if (Hi == NoClass)
3756       return ABIArgInfo::getIgnore();
3757     // If the low part is just padding, it takes no register, leave ResType
3758     // null.
3759     assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3760            "Unknown missing lo part");
3761     break;
3762 
3763     // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3764     // on the stack.
3765   case Memory:
3766 
3767     // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3768     // COMPLEX_X87, it is passed in memory.
3769   case X87:
3770   case ComplexX87:
3771     if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
3772       ++neededInt;
3773     return getIndirectResult(Ty, freeIntRegs);
3774 
3775   case SSEUp:
3776   case X87Up:
3777     llvm_unreachable("Invalid classification for lo word.");
3778 
3779     // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3780     // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3781     // and %r9 is used.
3782   case Integer:
3783     ++neededInt;
3784 
3785     // Pick an 8-byte type based on the preferred type.
3786     ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
3787 
3788     // If we have a sign or zero extended integer, make sure to return Extend
3789     // so that the parameter gets the right LLVM IR attributes.
3790     if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3791       // Treat an enum type as its underlying type.
3792       if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3793         Ty = EnumTy->getDecl()->getIntegerType();
3794 
3795       if (Ty->isIntegralOrEnumerationType() &&
3796           isPromotableIntegerTypeForABI(Ty))
3797         return ABIArgInfo::getExtend(Ty);
3798     }
3799 
3800     break;
3801 
3802     // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3803     // available SSE register is used, the registers are taken in the
3804     // order from %xmm0 to %xmm7.
3805   case SSE: {
3806     llvm::Type *IRType = CGT.ConvertType(Ty);
3807     ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
3808     ++neededSSE;
3809     break;
3810   }
3811   }
3812 
3813   llvm::Type *HighPart = nullptr;
3814   switch (Hi) {
3815     // Memory was handled previously, ComplexX87 and X87 should
3816     // never occur as hi classes, and X87Up must be preceded by X87,
3817     // which is passed in memory.
3818   case Memory:
3819   case X87:
3820   case ComplexX87:
3821     llvm_unreachable("Invalid classification for hi word.");
3822 
3823   case NoClass: break;
3824 
3825   case Integer:
3826     ++neededInt;
3827     // Pick an 8-byte type based on the preferred type.
3828     HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3829 
3830     if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
3831       return ABIArgInfo::getDirect(HighPart, 8);
3832     break;
3833 
3834     // X87Up generally doesn't occur here (long double is passed in
3835     // memory), except in situations involving unions.
3836   case X87Up:
3837   case SSE:
3838     HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3839 
3840     if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
3841       return ABIArgInfo::getDirect(HighPart, 8);
3842 
3843     ++neededSSE;
3844     break;
3845 
3846     // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3847     // eightbyte is passed in the upper half of the last used SSE
3848     // register.  This only happens when 128-bit vectors are passed.
3849   case SSEUp:
3850     assert(Lo == SSE && "Unexpected SSEUp classification");
3851     ResType = GetByteVectorType(Ty);
3852     break;
3853   }
3854 
3855   // If a high part was specified, merge it together with the low part.  It is
3856   // known to pass in the high eightbyte of the result.  We do this by forming a
3857   // first class struct aggregate with the high and low part: {low, high}
3858   if (HighPart)
3859     ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3860 
3861   return ABIArgInfo::getDirect(ResType);
3862 }
3863 
3864 ABIArgInfo
3865 X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
3866                                              unsigned &NeededSSE) const {
3867   auto RT = Ty->getAs<RecordType>();
3868   assert(RT && "classifyRegCallStructType only valid with struct types");
3869 
3870   if (RT->getDecl()->hasFlexibleArrayMember())
3871     return getIndirectReturnResult(Ty);
3872 
3873   // Sum up bases
3874   if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3875     if (CXXRD->isDynamicClass()) {
3876       NeededInt = NeededSSE = 0;
3877       return getIndirectReturnResult(Ty);
3878     }
3879 
3880     for (const auto &I : CXXRD->bases())
3881       if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE)
3882               .isIndirect()) {
3883         NeededInt = NeededSSE = 0;
3884         return getIndirectReturnResult(Ty);
3885       }
3886   }
3887 
3888   // Sum up members
3889   for (const auto *FD : RT->getDecl()->fields()) {
3890     if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) {
3891       if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE)
3892               .isIndirect()) {
3893         NeededInt = NeededSSE = 0;
3894         return getIndirectReturnResult(Ty);
3895       }
3896     } else {
3897       unsigned LocalNeededInt, LocalNeededSSE;
3898       if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt,
3899                                LocalNeededSSE, true)
3900               .isIndirect()) {
3901         NeededInt = NeededSSE = 0;
3902         return getIndirectReturnResult(Ty);
3903       }
3904       NeededInt += LocalNeededInt;
3905       NeededSSE += LocalNeededSSE;
3906     }
3907   }
3908 
3909   return ABIArgInfo::getDirect();
3910 }
3911 
3912 ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty,
3913                                                     unsigned &NeededInt,
3914                                                     unsigned &NeededSSE) const {
3915 
3916   NeededInt = 0;
3917   NeededSSE = 0;
3918 
3919   return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE);
3920 }
3921 
3922 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3923 
3924   const unsigned CallingConv = FI.getCallingConvention();
3925   // It is possible to force Win64 calling convention on any x86_64 target by
3926   // using __attribute__((ms_abi)). In such case to correctly emit Win64
3927   // compatible code delegate this call to WinX86_64ABIInfo::computeInfo.
3928   if (CallingConv == llvm::CallingConv::Win64) {
3929     WinX86_64ABIInfo Win64ABIInfo(CGT, AVXLevel);
3930     Win64ABIInfo.computeInfo(FI);
3931     return;
3932   }
3933 
3934   bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall;
3935 
3936   // Keep track of the number of assigned registers.
3937   unsigned FreeIntRegs = IsRegCall ? 11 : 6;
3938   unsigned FreeSSERegs = IsRegCall ? 16 : 8;
3939   unsigned NeededInt, NeededSSE;
3940 
3941   if (!::classifyReturnType(getCXXABI(), FI, *this)) {
3942     if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
3943         !FI.getReturnType()->getTypePtr()->isUnionType()) {
3944       FI.getReturnInfo() =
3945           classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE);
3946       if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3947         FreeIntRegs -= NeededInt;
3948         FreeSSERegs -= NeededSSE;
3949       } else {
3950         FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3951       }
3952     } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>() &&
3953                getContext().getCanonicalType(FI.getReturnType()
3954                                                  ->getAs<ComplexType>()
3955                                                  ->getElementType()) ==
3956                    getContext().LongDoubleTy)
3957       // Complex Long Double Type is passed in Memory when Regcall
3958       // calling convention is used.
3959       FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3960     else
3961       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3962   }
3963 
3964   // If the return value is indirect, then the hidden argument is consuming one
3965   // integer register.
3966   if (FI.getReturnInfo().isIndirect())
3967     --FreeIntRegs;
3968 
3969   // The chain argument effectively gives us another free register.
3970   if (FI.isChainCall())
3971     ++FreeIntRegs;
3972 
3973   unsigned NumRequiredArgs = FI.getNumRequiredArgs();
3974   // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3975   // get assigned (in left-to-right order) for passing as follows...
3976   unsigned ArgNo = 0;
3977   for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3978        it != ie; ++it, ++ArgNo) {
3979     bool IsNamedArg = ArgNo < NumRequiredArgs;
3980 
3981     if (IsRegCall && it->type->isStructureOrClassType())
3982       it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE);
3983     else
3984       it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
3985                                       NeededSSE, IsNamedArg);
3986 
3987     // AMD64-ABI 3.2.3p3: If there are no registers available for any
3988     // eightbyte of an argument, the whole argument is passed on the
3989     // stack. If registers have already been assigned for some
3990     // eightbytes of such an argument, the assignments get reverted.
3991     if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3992       FreeIntRegs -= NeededInt;
3993       FreeSSERegs -= NeededSSE;
3994     } else {
3995       it->info = getIndirectResult(it->type, FreeIntRegs);
3996     }
3997   }
3998 }
3999 
4000 static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
4001                                          Address VAListAddr, QualType Ty) {
4002   Address overflow_arg_area_p =
4003       CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
4004   llvm::Value *overflow_arg_area =
4005     CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
4006 
4007   // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
4008   // byte boundary if alignment needed by type exceeds 8 byte boundary.
4009   // It isn't stated explicitly in the standard, but in practice we use
4010   // alignment greater than 16 where necessary.
4011   CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4012   if (Align > CharUnits::fromQuantity(8)) {
4013     overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
4014                                                       Align);
4015   }
4016 
4017   // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
4018   llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
4019   llvm::Value *Res =
4020     CGF.Builder.CreateBitCast(overflow_arg_area,
4021                               llvm::PointerType::getUnqual(LTy));
4022 
4023   // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
4024   // l->overflow_arg_area + sizeof(type).
4025   // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
4026   // an 8 byte boundary.
4027 
4028   uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
4029   llvm::Value *Offset =
4030       llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7)  & ~7);
4031   overflow_arg_area = CGF.Builder.CreateGEP(CGF.Int8Ty, overflow_arg_area,
4032                                             Offset, "overflow_arg_area.next");
4033   CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
4034 
4035   // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
4036   return Address(Res, LTy, Align);
4037 }
4038 
4039 Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4040                                  QualType Ty) const {
4041   // Assume that va_list type is correct; should be pointer to LLVM type:
4042   // struct {
4043   //   i32 gp_offset;
4044   //   i32 fp_offset;
4045   //   i8* overflow_arg_area;
4046   //   i8* reg_save_area;
4047   // };
4048   unsigned neededInt, neededSSE;
4049 
4050   Ty = getContext().getCanonicalType(Ty);
4051   ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
4052                                        /*isNamedArg*/false);
4053 
4054   // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
4055   // in the registers. If not go to step 7.
4056   if (!neededInt && !neededSSE)
4057     return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
4058 
4059   // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
4060   // general purpose registers needed to pass type and num_fp to hold
4061   // the number of floating point registers needed.
4062 
4063   // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
4064   // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
4065   // l->fp_offset > 304 - num_fp * 16 go to step 7.
4066   //
4067   // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
4068   // register save space).
4069 
4070   llvm::Value *InRegs = nullptr;
4071   Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
4072   llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
4073   if (neededInt) {
4074     gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
4075     gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
4076     InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
4077     InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
4078   }
4079 
4080   if (neededSSE) {
4081     fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
4082     fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
4083     llvm::Value *FitsInFP =
4084       llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
4085     FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
4086     InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
4087   }
4088 
4089   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4090   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
4091   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4092   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
4093 
4094   // Emit code to load the value if it was passed in registers.
4095 
4096   CGF.EmitBlock(InRegBlock);
4097 
4098   // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
4099   // an offset of l->gp_offset and/or l->fp_offset. This may require
4100   // copying to a temporary location in case the parameter is passed
4101   // in different register classes or requires an alignment greater
4102   // than 8 for general purpose registers and 16 for XMM registers.
4103   //
4104   // FIXME: This really results in shameful code when we end up needing to
4105   // collect arguments from different places; often what should result in a
4106   // simple assembling of a structure from scattered addresses has many more
4107   // loads than necessary. Can we clean this up?
4108   llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
4109   llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
4110       CGF.Builder.CreateStructGEP(VAListAddr, 3), "reg_save_area");
4111 
4112   Address RegAddr = Address::invalid();
4113   if (neededInt && neededSSE) {
4114     // FIXME: Cleanup.
4115     assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
4116     llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
4117     Address Tmp = CGF.CreateMemTemp(Ty);
4118     Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
4119     assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
4120     llvm::Type *TyLo = ST->getElementType(0);
4121     llvm::Type *TyHi = ST->getElementType(1);
4122     assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
4123            "Unexpected ABI info for mixed regs");
4124     llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
4125     llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
4126     llvm::Value *GPAddr =
4127         CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, gp_offset);
4128     llvm::Value *FPAddr =
4129         CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, fp_offset);
4130     llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
4131     llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
4132 
4133     // Copy the first element.
4134     // FIXME: Our choice of alignment here and below is probably pessimistic.
4135     llvm::Value *V = CGF.Builder.CreateAlignedLoad(
4136         TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo),
4137         CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo)));
4138     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
4139 
4140     // Copy the second element.
4141     V = CGF.Builder.CreateAlignedLoad(
4142         TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
4143         CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
4144     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
4145 
4146     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
4147   } else if (neededInt) {
4148     RegAddr = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, gp_offset),
4149                       CGF.Int8Ty, CharUnits::fromQuantity(8));
4150     RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
4151 
4152     // Copy to a temporary if necessary to ensure the appropriate alignment.
4153     auto TInfo = getContext().getTypeInfoInChars(Ty);
4154     uint64_t TySize = TInfo.Width.getQuantity();
4155     CharUnits TyAlign = TInfo.Align;
4156 
4157     // Copy into a temporary if the type is more aligned than the
4158     // register save area.
4159     if (TyAlign.getQuantity() > 8) {
4160       Address Tmp = CGF.CreateMemTemp(Ty);
4161       CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
4162       RegAddr = Tmp;
4163     }
4164 
4165   } else if (neededSSE == 1) {
4166     RegAddr = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, fp_offset),
4167                       CGF.Int8Ty, CharUnits::fromQuantity(16));
4168     RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
4169   } else {
4170     assert(neededSSE == 2 && "Invalid number of needed registers!");
4171     // SSE registers are spaced 16 bytes apart in the register save
4172     // area, we need to collect the two eightbytes together.
4173     // The ABI isn't explicit about this, but it seems reasonable
4174     // to assume that the slots are 16-byte aligned, since the stack is
4175     // naturally 16-byte aligned and the prologue is expected to store
4176     // all the SSE registers to the RSA.
4177     Address RegAddrLo = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea,
4178                                                       fp_offset),
4179                                 CGF.Int8Ty, CharUnits::fromQuantity(16));
4180     Address RegAddrHi =
4181       CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
4182                                              CharUnits::fromQuantity(16));
4183     llvm::Type *ST = AI.canHaveCoerceToType()
4184                          ? AI.getCoerceToType()
4185                          : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy);
4186     llvm::Value *V;
4187     Address Tmp = CGF.CreateMemTemp(Ty);
4188     Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
4189     V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
4190         RegAddrLo, ST->getStructElementType(0)));
4191     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
4192     V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
4193         RegAddrHi, ST->getStructElementType(1)));
4194     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
4195 
4196     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
4197   }
4198 
4199   // AMD64-ABI 3.5.7p5: Step 5. Set:
4200   // l->gp_offset = l->gp_offset + num_gp * 8
4201   // l->fp_offset = l->fp_offset + num_fp * 16.
4202   if (neededInt) {
4203     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
4204     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
4205                             gp_offset_p);
4206   }
4207   if (neededSSE) {
4208     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
4209     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
4210                             fp_offset_p);
4211   }
4212   CGF.EmitBranch(ContBlock);
4213 
4214   // Emit code to load the value if it was passed in memory.
4215 
4216   CGF.EmitBlock(InMemBlock);
4217   Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
4218 
4219   // Return the appropriate result.
4220 
4221   CGF.EmitBlock(ContBlock);
4222   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
4223                                  "vaarg.addr");
4224   return ResAddr;
4225 }
4226 
4227 Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
4228                                    QualType Ty) const {
4229   // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4230   // not 1, 2, 4, or 8 bytes, must be passed by reference."
4231   uint64_t Width = getContext().getTypeSize(Ty);
4232   bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
4233 
4234   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
4235                           CGF.getContext().getTypeInfoInChars(Ty),
4236                           CharUnits::fromQuantity(8),
4237                           /*allowHigherAlign*/ false);
4238 }
4239 
4240 ABIArgInfo WinX86_64ABIInfo::reclassifyHvaArgForVectorCall(
4241     QualType Ty, unsigned &FreeSSERegs, const ABIArgInfo &current) const {
4242   const Type *Base = nullptr;
4243   uint64_t NumElts = 0;
4244 
4245   if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
4246       isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
4247     FreeSSERegs -= NumElts;
4248     return getDirectX86Hva();
4249   }
4250   return current;
4251 }
4252 
4253 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
4254                                       bool IsReturnType, bool IsVectorCall,
4255                                       bool IsRegCall) const {
4256 
4257   if (Ty->isVoidType())
4258     return ABIArgInfo::getIgnore();
4259 
4260   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4261     Ty = EnumTy->getDecl()->getIntegerType();
4262 
4263   TypeInfo Info = getContext().getTypeInfo(Ty);
4264   uint64_t Width = Info.Width;
4265   CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
4266 
4267   const RecordType *RT = Ty->getAs<RecordType>();
4268   if (RT) {
4269     if (!IsReturnType) {
4270       if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
4271         return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
4272     }
4273 
4274     if (RT->getDecl()->hasFlexibleArrayMember())
4275       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4276 
4277   }
4278 
4279   const Type *Base = nullptr;
4280   uint64_t NumElts = 0;
4281   // vectorcall adds the concept of a homogenous vector aggregate, similar to
4282   // other targets.
4283   if ((IsVectorCall || IsRegCall) &&
4284       isHomogeneousAggregate(Ty, Base, NumElts)) {
4285     if (IsRegCall) {
4286       if (FreeSSERegs >= NumElts) {
4287         FreeSSERegs -= NumElts;
4288         if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
4289           return ABIArgInfo::getDirect();
4290         return ABIArgInfo::getExpand();
4291       }
4292       return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4293     } else if (IsVectorCall) {
4294       if (FreeSSERegs >= NumElts &&
4295           (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
4296         FreeSSERegs -= NumElts;
4297         return ABIArgInfo::getDirect();
4298       } else if (IsReturnType) {
4299         return ABIArgInfo::getExpand();
4300       } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
4301         // HVAs are delayed and reclassified in the 2nd step.
4302         return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4303       }
4304     }
4305   }
4306 
4307   if (Ty->isMemberPointerType()) {
4308     // If the member pointer is represented by an LLVM int or ptr, pass it
4309     // directly.
4310     llvm::Type *LLTy = CGT.ConvertType(Ty);
4311     if (LLTy->isPointerTy() || LLTy->isIntegerTy())
4312       return ABIArgInfo::getDirect();
4313   }
4314 
4315   if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
4316     // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4317     // not 1, 2, 4, or 8 bytes, must be passed by reference."
4318     if (Width > 64 || !llvm::isPowerOf2_64(Width))
4319       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4320 
4321     // Otherwise, coerce it to a small integer.
4322     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
4323   }
4324 
4325   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4326     switch (BT->getKind()) {
4327     case BuiltinType::Bool:
4328       // Bool type is always extended to the ABI, other builtin types are not
4329       // extended.
4330       return ABIArgInfo::getExtend(Ty);
4331 
4332     case BuiltinType::LongDouble:
4333       // Mingw64 GCC uses the old 80 bit extended precision floating point
4334       // unit. It passes them indirectly through memory.
4335       if (IsMingw64) {
4336         const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
4337         if (LDF == &llvm::APFloat::x87DoubleExtended())
4338           return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4339       }
4340       break;
4341 
4342     case BuiltinType::Int128:
4343     case BuiltinType::UInt128:
4344       // If it's a parameter type, the normal ABI rule is that arguments larger
4345       // than 8 bytes are passed indirectly. GCC follows it. We follow it too,
4346       // even though it isn't particularly efficient.
4347       if (!IsReturnType)
4348         return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4349 
4350       // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that.
4351       // Clang matches them for compatibility.
4352       return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
4353           llvm::Type::getInt64Ty(getVMContext()), 2));
4354 
4355     default:
4356       break;
4357     }
4358   }
4359 
4360   if (Ty->isBitIntType()) {
4361     // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4362     // not 1, 2, 4, or 8 bytes, must be passed by reference."
4363     // However, non-power-of-two bit-precise integers will be passed as 1, 2, 4,
4364     // or 8 bytes anyway as long is it fits in them, so we don't have to check
4365     // the power of 2.
4366     if (Width <= 64)
4367       return ABIArgInfo::getDirect();
4368     return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4369   }
4370 
4371   return ABIArgInfo::getDirect();
4372 }
4373 
4374 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
4375   const unsigned CC = FI.getCallingConvention();
4376   bool IsVectorCall = CC == llvm::CallingConv::X86_VectorCall;
4377   bool IsRegCall = CC == llvm::CallingConv::X86_RegCall;
4378 
4379   // If __attribute__((sysv_abi)) is in use, use the SysV argument
4380   // classification rules.
4381   if (CC == llvm::CallingConv::X86_64_SysV) {
4382     X86_64ABIInfo SysVABIInfo(CGT, AVXLevel);
4383     SysVABIInfo.computeInfo(FI);
4384     return;
4385   }
4386 
4387   unsigned FreeSSERegs = 0;
4388   if (IsVectorCall) {
4389     // We can use up to 4 SSE return registers with vectorcall.
4390     FreeSSERegs = 4;
4391   } else if (IsRegCall) {
4392     // RegCall gives us 16 SSE registers.
4393     FreeSSERegs = 16;
4394   }
4395 
4396   if (!getCXXABI().classifyReturnType(FI))
4397     FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
4398                                   IsVectorCall, IsRegCall);
4399 
4400   if (IsVectorCall) {
4401     // We can use up to 6 SSE register parameters with vectorcall.
4402     FreeSSERegs = 6;
4403   } else if (IsRegCall) {
4404     // RegCall gives us 16 SSE registers, we can reuse the return registers.
4405     FreeSSERegs = 16;
4406   }
4407 
4408   unsigned ArgNum = 0;
4409   unsigned ZeroSSERegs = 0;
4410   for (auto &I : FI.arguments()) {
4411     // Vectorcall in x64 only permits the first 6 arguments to be passed as
4412     // XMM/YMM registers. After the sixth argument, pretend no vector
4413     // registers are left.
4414     unsigned *MaybeFreeSSERegs =
4415         (IsVectorCall && ArgNum >= 6) ? &ZeroSSERegs : &FreeSSERegs;
4416     I.info =
4417         classify(I.type, *MaybeFreeSSERegs, false, IsVectorCall, IsRegCall);
4418     ++ArgNum;
4419   }
4420 
4421   if (IsVectorCall) {
4422     // For vectorcall, assign aggregate HVAs to any free vector registers in a
4423     // second pass.
4424     for (auto &I : FI.arguments())
4425       I.info = reclassifyHvaArgForVectorCall(I.type, FreeSSERegs, I.info);
4426   }
4427 }
4428 
4429 Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4430                                     QualType Ty) const {
4431   // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4432   // not 1, 2, 4, or 8 bytes, must be passed by reference."
4433   uint64_t Width = getContext().getTypeSize(Ty);
4434   bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
4435 
4436   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
4437                           CGF.getContext().getTypeInfoInChars(Ty),
4438                           CharUnits::fromQuantity(8),
4439                           /*allowHigherAlign*/ false);
4440 }
4441 
4442 static bool PPC_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4443                                         llvm::Value *Address, bool Is64Bit,
4444                                         bool IsAIX) {
4445   // This is calculated from the LLVM and GCC tables and verified
4446   // against gcc output.  AFAIK all PPC ABIs use the same encoding.
4447 
4448   CodeGen::CGBuilderTy &Builder = CGF.Builder;
4449 
4450   llvm::IntegerType *i8 = CGF.Int8Ty;
4451   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4452   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4453   llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4454 
4455   // 0-31: r0-31, the 4-byte or 8-byte general-purpose registers
4456   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 0, 31);
4457 
4458   // 32-63: fp0-31, the 8-byte floating-point registers
4459   AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4460 
4461   // 64-67 are various 4-byte or 8-byte special-purpose registers:
4462   // 64: mq
4463   // 65: lr
4464   // 66: ctr
4465   // 67: ap
4466   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 64, 67);
4467 
4468   // 68-76 are various 4-byte special-purpose registers:
4469   // 68-75 cr0-7
4470   // 76: xer
4471   AssignToArrayRange(Builder, Address, Four8, 68, 76);
4472 
4473   // 77-108: v0-31, the 16-byte vector registers
4474   AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4475 
4476   // 109: vrsave
4477   // 110: vscr
4478   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 109, 110);
4479 
4480   // AIX does not utilize the rest of the registers.
4481   if (IsAIX)
4482     return false;
4483 
4484   // 111: spe_acc
4485   // 112: spefscr
4486   // 113: sfp
4487   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 111, 113);
4488 
4489   if (!Is64Bit)
4490     return false;
4491 
4492   // TODO: Need to verify if these registers are used on 64 bit AIX with Power8
4493   // or above CPU.
4494   // 64-bit only registers:
4495   // 114: tfhar
4496   // 115: tfiar
4497   // 116: texasr
4498   AssignToArrayRange(Builder, Address, Eight8, 114, 116);
4499 
4500   return false;
4501 }
4502 
4503 // AIX
4504 namespace {
4505 /// AIXABIInfo - The AIX XCOFF ABI information.
4506 class AIXABIInfo : public ABIInfo {
4507   const bool Is64Bit;
4508   const unsigned PtrByteSize;
4509   CharUnits getParamTypeAlignment(QualType Ty) const;
4510 
4511 public:
4512   AIXABIInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit)
4513       : ABIInfo(CGT), Is64Bit(Is64Bit), PtrByteSize(Is64Bit ? 8 : 4) {}
4514 
4515   bool isPromotableTypeForABI(QualType Ty) const;
4516 
4517   ABIArgInfo classifyReturnType(QualType RetTy) const;
4518   ABIArgInfo classifyArgumentType(QualType Ty) const;
4519 
4520   void computeInfo(CGFunctionInfo &FI) const override {
4521     if (!getCXXABI().classifyReturnType(FI))
4522       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4523 
4524     for (auto &I : FI.arguments())
4525       I.info = classifyArgumentType(I.type);
4526   }
4527 
4528   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4529                     QualType Ty) const override;
4530 };
4531 
4532 class AIXTargetCodeGenInfo : public TargetCodeGenInfo {
4533   const bool Is64Bit;
4534 
4535 public:
4536   AIXTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit)
4537       : TargetCodeGenInfo(std::make_unique<AIXABIInfo>(CGT, Is64Bit)),
4538         Is64Bit(Is64Bit) {}
4539   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4540     return 1; // r1 is the dedicated stack pointer
4541   }
4542 
4543   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4544                                llvm::Value *Address) const override;
4545 };
4546 } // namespace
4547 
4548 // Return true if the ABI requires Ty to be passed sign- or zero-
4549 // extended to 32/64 bits.
4550 bool AIXABIInfo::isPromotableTypeForABI(QualType Ty) const {
4551   // Treat an enum type as its underlying type.
4552   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4553     Ty = EnumTy->getDecl()->getIntegerType();
4554 
4555   // Promotable integer types are required to be promoted by the ABI.
4556   if (Ty->isPromotableIntegerType())
4557     return true;
4558 
4559   if (!Is64Bit)
4560     return false;
4561 
4562   // For 64 bit mode, in addition to the usual promotable integer types, we also
4563   // need to extend all 32-bit types, since the ABI requires promotion to 64
4564   // bits.
4565   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4566     switch (BT->getKind()) {
4567     case BuiltinType::Int:
4568     case BuiltinType::UInt:
4569       return true;
4570     default:
4571       break;
4572     }
4573 
4574   return false;
4575 }
4576 
4577 ABIArgInfo AIXABIInfo::classifyReturnType(QualType RetTy) const {
4578   if (RetTy->isAnyComplexType())
4579     return ABIArgInfo::getDirect();
4580 
4581   if (RetTy->isVectorType())
4582     return ABIArgInfo::getDirect();
4583 
4584   if (RetTy->isVoidType())
4585     return ABIArgInfo::getIgnore();
4586 
4587   if (isAggregateTypeForABI(RetTy))
4588     return getNaturalAlignIndirect(RetTy);
4589 
4590   return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
4591                                         : ABIArgInfo::getDirect());
4592 }
4593 
4594 ABIArgInfo AIXABIInfo::classifyArgumentType(QualType Ty) const {
4595   Ty = useFirstFieldIfTransparentUnion(Ty);
4596 
4597   if (Ty->isAnyComplexType())
4598     return ABIArgInfo::getDirect();
4599 
4600   if (Ty->isVectorType())
4601     return ABIArgInfo::getDirect();
4602 
4603   if (isAggregateTypeForABI(Ty)) {
4604     // Records with non-trivial destructors/copy-constructors should not be
4605     // passed by value.
4606     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
4607       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
4608 
4609     CharUnits CCAlign = getParamTypeAlignment(Ty);
4610     CharUnits TyAlign = getContext().getTypeAlignInChars(Ty);
4611 
4612     return ABIArgInfo::getIndirect(CCAlign, /*ByVal*/ true,
4613                                    /*Realign*/ TyAlign > CCAlign);
4614   }
4615 
4616   return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
4617                                      : ABIArgInfo::getDirect());
4618 }
4619 
4620 CharUnits AIXABIInfo::getParamTypeAlignment(QualType Ty) const {
4621   // Complex types are passed just like their elements.
4622   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4623     Ty = CTy->getElementType();
4624 
4625   if (Ty->isVectorType())
4626     return CharUnits::fromQuantity(16);
4627 
4628   // If the structure contains a vector type, the alignment is 16.
4629   if (isRecordWithSIMDVectorType(getContext(), Ty))
4630     return CharUnits::fromQuantity(16);
4631 
4632   return CharUnits::fromQuantity(PtrByteSize);
4633 }
4634 
4635 Address AIXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4636                               QualType Ty) const {
4637 
4638   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4639   TypeInfo.Align = getParamTypeAlignment(Ty);
4640 
4641   CharUnits SlotSize = CharUnits::fromQuantity(PtrByteSize);
4642 
4643   // If we have a complex type and the base type is smaller than the register
4644   // size, the ABI calls for the real and imaginary parts to be right-adjusted
4645   // in separate words in 32bit mode or doublewords in 64bit mode. However,
4646   // Clang expects us to produce a pointer to a structure with the two parts
4647   // packed tightly. So generate loads of the real and imaginary parts relative
4648   // to the va_list pointer, and store them to a temporary structure. We do the
4649   // same as the PPC64ABI here.
4650   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4651     CharUnits EltSize = TypeInfo.Width / 2;
4652     if (EltSize < SlotSize)
4653       return complexTempStructure(CGF, VAListAddr, Ty, SlotSize, EltSize, CTy);
4654   }
4655 
4656   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, TypeInfo,
4657                           SlotSize, /*AllowHigher*/ true);
4658 }
4659 
4660 bool AIXTargetCodeGenInfo::initDwarfEHRegSizeTable(
4661     CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const {
4662   return PPC_initDwarfEHRegSizeTable(CGF, Address, Is64Bit, /*IsAIX*/ true);
4663 }
4664 
4665 // PowerPC-32
4666 namespace {
4667 /// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
4668 class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
4669   bool IsSoftFloatABI;
4670   bool IsRetSmallStructInRegABI;
4671 
4672   CharUnits getParamTypeAlignment(QualType Ty) const;
4673 
4674 public:
4675   PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI,
4676                      bool RetSmallStructInRegABI)
4677       : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI),
4678         IsRetSmallStructInRegABI(RetSmallStructInRegABI) {}
4679 
4680   ABIArgInfo classifyReturnType(QualType RetTy) const;
4681 
4682   void computeInfo(CGFunctionInfo &FI) const override {
4683     if (!getCXXABI().classifyReturnType(FI))
4684       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4685     for (auto &I : FI.arguments())
4686       I.info = classifyArgumentType(I.type);
4687   }
4688 
4689   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4690                     QualType Ty) const override;
4691 };
4692 
4693 class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
4694 public:
4695   PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI,
4696                          bool RetSmallStructInRegABI)
4697       : TargetCodeGenInfo(std::make_unique<PPC32_SVR4_ABIInfo>(
4698             CGT, SoftFloatABI, RetSmallStructInRegABI)) {}
4699 
4700   static bool isStructReturnInRegABI(const llvm::Triple &Triple,
4701                                      const CodeGenOptions &Opts);
4702 
4703   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4704     // This is recovered from gcc output.
4705     return 1; // r1 is the dedicated stack pointer
4706   }
4707 
4708   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4709                                llvm::Value *Address) const override;
4710 };
4711 }
4712 
4713 CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
4714   // Complex types are passed just like their elements.
4715   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4716     Ty = CTy->getElementType();
4717 
4718   if (Ty->isVectorType())
4719     return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16
4720                                                                        : 4);
4721 
4722   // For single-element float/vector structs, we consider the whole type
4723   // to have the same alignment requirements as its single element.
4724   const Type *AlignTy = nullptr;
4725   if (const Type *EltType = isSingleElementStruct(Ty, getContext())) {
4726     const BuiltinType *BT = EltType->getAs<BuiltinType>();
4727     if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
4728         (BT && BT->isFloatingPoint()))
4729       AlignTy = EltType;
4730   }
4731 
4732   if (AlignTy)
4733     return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4);
4734   return CharUnits::fromQuantity(4);
4735 }
4736 
4737 ABIArgInfo PPC32_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4738   uint64_t Size;
4739 
4740   // -msvr4-struct-return puts small aggregates in GPR3 and GPR4.
4741   if (isAggregateTypeForABI(RetTy) && IsRetSmallStructInRegABI &&
4742       (Size = getContext().getTypeSize(RetTy)) <= 64) {
4743     // System V ABI (1995), page 3-22, specified:
4744     // > A structure or union whose size is less than or equal to 8 bytes
4745     // > shall be returned in r3 and r4, as if it were first stored in the
4746     // > 8-byte aligned memory area and then the low addressed word were
4747     // > loaded into r3 and the high-addressed word into r4.  Bits beyond
4748     // > the last member of the structure or union are not defined.
4749     //
4750     // GCC for big-endian PPC32 inserts the pad before the first member,
4751     // not "beyond the last member" of the struct.  To stay compatible
4752     // with GCC, we coerce the struct to an integer of the same size.
4753     // LLVM will extend it and return i32 in r3, or i64 in r3:r4.
4754     if (Size == 0)
4755       return ABIArgInfo::getIgnore();
4756     else {
4757       llvm::Type *CoerceTy = llvm::Type::getIntNTy(getVMContext(), Size);
4758       return ABIArgInfo::getDirect(CoerceTy);
4759     }
4760   }
4761 
4762   return DefaultABIInfo::classifyReturnType(RetTy);
4763 }
4764 
4765 // TODO: this implementation is now likely redundant with
4766 // DefaultABIInfo::EmitVAArg.
4767 Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
4768                                       QualType Ty) const {
4769   if (getTarget().getTriple().isOSDarwin()) {
4770     auto TI = getContext().getTypeInfoInChars(Ty);
4771     TI.Align = getParamTypeAlignment(Ty);
4772 
4773     CharUnits SlotSize = CharUnits::fromQuantity(4);
4774     return emitVoidPtrVAArg(CGF, VAList, Ty,
4775                             classifyArgumentType(Ty).isIndirect(), TI, SlotSize,
4776                             /*AllowHigherAlign=*/true);
4777   }
4778 
4779   const unsigned OverflowLimit = 8;
4780   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4781     // TODO: Implement this. For now ignore.
4782     (void)CTy;
4783     return Address::invalid(); // FIXME?
4784   }
4785 
4786   // struct __va_list_tag {
4787   //   unsigned char gpr;
4788   //   unsigned char fpr;
4789   //   unsigned short reserved;
4790   //   void *overflow_arg_area;
4791   //   void *reg_save_area;
4792   // };
4793 
4794   bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
4795   bool isInt = !Ty->isFloatingType();
4796   bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
4797 
4798   // All aggregates are passed indirectly?  That doesn't seem consistent
4799   // with the argument-lowering code.
4800   bool isIndirect = isAggregateTypeForABI(Ty);
4801 
4802   CGBuilderTy &Builder = CGF.Builder;
4803 
4804   // The calling convention either uses 1-2 GPRs or 1 FPR.
4805   Address NumRegsAddr = Address::invalid();
4806   if (isInt || IsSoftFloatABI) {
4807     NumRegsAddr = Builder.CreateStructGEP(VAList, 0, "gpr");
4808   } else {
4809     NumRegsAddr = Builder.CreateStructGEP(VAList, 1, "fpr");
4810   }
4811 
4812   llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
4813 
4814   // "Align" the register count when TY is i64.
4815   if (isI64 || (isF64 && IsSoftFloatABI)) {
4816     NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
4817     NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
4818   }
4819 
4820   llvm::Value *CC =
4821       Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
4822 
4823   llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
4824   llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
4825   llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
4826 
4827   Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
4828 
4829   llvm::Type *DirectTy = CGF.ConvertType(Ty);
4830   if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
4831 
4832   // Case 1: consume registers.
4833   Address RegAddr = Address::invalid();
4834   {
4835     CGF.EmitBlock(UsingRegs);
4836 
4837     Address RegSaveAreaPtr = Builder.CreateStructGEP(VAList, 4);
4838     RegAddr = Address::deprecated(Builder.CreateLoad(RegSaveAreaPtr),
4839                                   CharUnits::fromQuantity(8));
4840     assert(RegAddr.getElementType() == CGF.Int8Ty);
4841 
4842     // Floating-point registers start after the general-purpose registers.
4843     if (!(isInt || IsSoftFloatABI)) {
4844       RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
4845                                                    CharUnits::fromQuantity(32));
4846     }
4847 
4848     // Get the address of the saved value by scaling the number of
4849     // registers we've used by the number of
4850     CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
4851     llvm::Value *RegOffset =
4852         Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
4853     RegAddr = Address(
4854         Builder.CreateInBoundsGEP(CGF.Int8Ty, RegAddr.getPointer(), RegOffset),
4855         CGF.Int8Ty, RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
4856     RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
4857 
4858     // Increase the used-register count.
4859     NumRegs =
4860       Builder.CreateAdd(NumRegs,
4861                         Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
4862     Builder.CreateStore(NumRegs, NumRegsAddr);
4863 
4864     CGF.EmitBranch(Cont);
4865   }
4866 
4867   // Case 2: consume space in the overflow area.
4868   Address MemAddr = Address::invalid();
4869   {
4870     CGF.EmitBlock(UsingOverflow);
4871 
4872     Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
4873 
4874     // Everything in the overflow area is rounded up to a size of at least 4.
4875     CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
4876 
4877     CharUnits Size;
4878     if (!isIndirect) {
4879       auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
4880       Size = TypeInfo.Width.alignTo(OverflowAreaAlign);
4881     } else {
4882       Size = CGF.getPointerSize();
4883     }
4884 
4885     Address OverflowAreaAddr = Builder.CreateStructGEP(VAList, 3);
4886     Address OverflowArea = Address::deprecated(
4887         Builder.CreateLoad(OverflowAreaAddr, "argp.cur"), OverflowAreaAlign);
4888     // Round up address of argument to alignment
4889     CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4890     if (Align > OverflowAreaAlign) {
4891       llvm::Value *Ptr = OverflowArea.getPointer();
4892       OverflowArea = Address::deprecated(
4893           emitRoundPointerUpToAlignment(CGF, Ptr, Align), Align);
4894     }
4895 
4896     MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
4897 
4898     // Increase the overflow area.
4899     OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
4900     Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
4901     CGF.EmitBranch(Cont);
4902   }
4903 
4904   CGF.EmitBlock(Cont);
4905 
4906   // Merge the cases with a phi.
4907   Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
4908                                 "vaarg.addr");
4909 
4910   // Load the pointer if the argument was passed indirectly.
4911   if (isIndirect) {
4912     Result = Address::deprecated(Builder.CreateLoad(Result, "aggr"),
4913                                  getContext().getTypeAlignInChars(Ty));
4914   }
4915 
4916   return Result;
4917 }
4918 
4919 bool PPC32TargetCodeGenInfo::isStructReturnInRegABI(
4920     const llvm::Triple &Triple, const CodeGenOptions &Opts) {
4921   assert(Triple.isPPC32());
4922 
4923   switch (Opts.getStructReturnConvention()) {
4924   case CodeGenOptions::SRCK_Default:
4925     break;
4926   case CodeGenOptions::SRCK_OnStack: // -maix-struct-return
4927     return false;
4928   case CodeGenOptions::SRCK_InRegs: // -msvr4-struct-return
4929     return true;
4930   }
4931 
4932   if (Triple.isOSBinFormatELF() && !Triple.isOSLinux())
4933     return true;
4934 
4935   return false;
4936 }
4937 
4938 bool
4939 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4940                                                 llvm::Value *Address) const {
4941   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ false,
4942                                      /*IsAIX*/ false);
4943 }
4944 
4945 // PowerPC-64
4946 
4947 namespace {
4948 /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
4949 class PPC64_SVR4_ABIInfo : public SwiftABIInfo {
4950 public:
4951   enum ABIKind {
4952     ELFv1 = 0,
4953     ELFv2
4954   };
4955 
4956 private:
4957   static const unsigned GPRBits = 64;
4958   ABIKind Kind;
4959   bool IsSoftFloatABI;
4960 
4961 public:
4962   PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind,
4963                      bool SoftFloatABI)
4964       : SwiftABIInfo(CGT), Kind(Kind), IsSoftFloatABI(SoftFloatABI) {}
4965 
4966   bool isPromotableTypeForABI(QualType Ty) const;
4967   CharUnits getParamTypeAlignment(QualType Ty) const;
4968 
4969   ABIArgInfo classifyReturnType(QualType RetTy) const;
4970   ABIArgInfo classifyArgumentType(QualType Ty) const;
4971 
4972   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4973   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4974                                          uint64_t Members) const override;
4975 
4976   // TODO: We can add more logic to computeInfo to improve performance.
4977   // Example: For aggregate arguments that fit in a register, we could
4978   // use getDirectInReg (as is done below for structs containing a single
4979   // floating-point value) to avoid pushing them to memory on function
4980   // entry.  This would require changing the logic in PPCISelLowering
4981   // when lowering the parameters in the caller and args in the callee.
4982   void computeInfo(CGFunctionInfo &FI) const override {
4983     if (!getCXXABI().classifyReturnType(FI))
4984       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4985     for (auto &I : FI.arguments()) {
4986       // We rely on the default argument classification for the most part.
4987       // One exception:  An aggregate containing a single floating-point
4988       // or vector item must be passed in a register if one is available.
4989       const Type *T = isSingleElementStruct(I.type, getContext());
4990       if (T) {
4991         const BuiltinType *BT = T->getAs<BuiltinType>();
4992         if ((T->isVectorType() && getContext().getTypeSize(T) == 128) ||
4993             (BT && BT->isFloatingPoint())) {
4994           QualType QT(T, 0);
4995           I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
4996           continue;
4997         }
4998       }
4999       I.info = classifyArgumentType(I.type);
5000     }
5001   }
5002 
5003   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5004                     QualType Ty) const override;
5005 
5006   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
5007                                     bool asReturnValue) const override {
5008     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5009   }
5010 
5011   bool isSwiftErrorInRegister() const override {
5012     return false;
5013   }
5014 };
5015 
5016 class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
5017 
5018 public:
5019   PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
5020                                PPC64_SVR4_ABIInfo::ABIKind Kind,
5021                                bool SoftFloatABI)
5022       : TargetCodeGenInfo(
5023             std::make_unique<PPC64_SVR4_ABIInfo>(CGT, Kind, SoftFloatABI)) {}
5024 
5025   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5026     // This is recovered from gcc output.
5027     return 1; // r1 is the dedicated stack pointer
5028   }
5029 
5030   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5031                                llvm::Value *Address) const override;
5032 };
5033 
5034 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
5035 public:
5036   PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
5037 
5038   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5039     // This is recovered from gcc output.
5040     return 1; // r1 is the dedicated stack pointer
5041   }
5042 
5043   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5044                                llvm::Value *Address) const override;
5045 };
5046 
5047 }
5048 
5049 // Return true if the ABI requires Ty to be passed sign- or zero-
5050 // extended to 64 bits.
5051 bool
5052 PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
5053   // Treat an enum type as its underlying type.
5054   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5055     Ty = EnumTy->getDecl()->getIntegerType();
5056 
5057   // Promotable integer types are required to be promoted by the ABI.
5058   if (isPromotableIntegerTypeForABI(Ty))
5059     return true;
5060 
5061   // In addition to the usual promotable integer types, we also need to
5062   // extend all 32-bit types, since the ABI requires promotion to 64 bits.
5063   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5064     switch (BT->getKind()) {
5065     case BuiltinType::Int:
5066     case BuiltinType::UInt:
5067       return true;
5068     default:
5069       break;
5070     }
5071 
5072   if (const auto *EIT = Ty->getAs<BitIntType>())
5073     if (EIT->getNumBits() < 64)
5074       return true;
5075 
5076   return false;
5077 }
5078 
5079 /// isAlignedParamType - Determine whether a type requires 16-byte or
5080 /// higher alignment in the parameter area.  Always returns at least 8.
5081 CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
5082   // Complex types are passed just like their elements.
5083   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
5084     Ty = CTy->getElementType();
5085 
5086   auto FloatUsesVector = [this](QualType Ty){
5087     return Ty->isRealFloatingType() && &getContext().getFloatTypeSemantics(
5088                                            Ty) == &llvm::APFloat::IEEEquad();
5089   };
5090 
5091   // Only vector types of size 16 bytes need alignment (larger types are
5092   // passed via reference, smaller types are not aligned).
5093   if (Ty->isVectorType()) {
5094     return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
5095   } else if (FloatUsesVector(Ty)) {
5096     // According to ABI document section 'Optional Save Areas': If extended
5097     // precision floating-point values in IEEE BINARY 128 QUADRUPLE PRECISION
5098     // format are supported, map them to a single quadword, quadword aligned.
5099     return CharUnits::fromQuantity(16);
5100   }
5101 
5102   // For single-element float/vector structs, we consider the whole type
5103   // to have the same alignment requirements as its single element.
5104   const Type *AlignAsType = nullptr;
5105   const Type *EltType = isSingleElementStruct(Ty, getContext());
5106   if (EltType) {
5107     const BuiltinType *BT = EltType->getAs<BuiltinType>();
5108     if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
5109         (BT && BT->isFloatingPoint()))
5110       AlignAsType = EltType;
5111   }
5112 
5113   // Likewise for ELFv2 homogeneous aggregates.
5114   const Type *Base = nullptr;
5115   uint64_t Members = 0;
5116   if (!AlignAsType && Kind == ELFv2 &&
5117       isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
5118     AlignAsType = Base;
5119 
5120   // With special case aggregates, only vector base types need alignment.
5121   if (AlignAsType) {
5122     bool UsesVector = AlignAsType->isVectorType() ||
5123                       FloatUsesVector(QualType(AlignAsType, 0));
5124     return CharUnits::fromQuantity(UsesVector ? 16 : 8);
5125   }
5126 
5127   // Otherwise, we only need alignment for any aggregate type that
5128   // has an alignment requirement of >= 16 bytes.
5129   if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
5130     return CharUnits::fromQuantity(16);
5131   }
5132 
5133   return CharUnits::fromQuantity(8);
5134 }
5135 
5136 /// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
5137 /// aggregate.  Base is set to the base element type, and Members is set
5138 /// to the number of base elements.
5139 bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
5140                                      uint64_t &Members) const {
5141   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
5142     uint64_t NElements = AT->getSize().getZExtValue();
5143     if (NElements == 0)
5144       return false;
5145     if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
5146       return false;
5147     Members *= NElements;
5148   } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
5149     const RecordDecl *RD = RT->getDecl();
5150     if (RD->hasFlexibleArrayMember())
5151       return false;
5152 
5153     Members = 0;
5154 
5155     // If this is a C++ record, check the properties of the record such as
5156     // bases and ABI specific restrictions
5157     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
5158       if (!getCXXABI().isPermittedToBeHomogeneousAggregate(CXXRD))
5159         return false;
5160 
5161       for (const auto &I : CXXRD->bases()) {
5162         // Ignore empty records.
5163         if (isEmptyRecord(getContext(), I.getType(), true))
5164           continue;
5165 
5166         uint64_t FldMembers;
5167         if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
5168           return false;
5169 
5170         Members += FldMembers;
5171       }
5172     }
5173 
5174     for (const auto *FD : RD->fields()) {
5175       // Ignore (non-zero arrays of) empty records.
5176       QualType FT = FD->getType();
5177       while (const ConstantArrayType *AT =
5178              getContext().getAsConstantArrayType(FT)) {
5179         if (AT->getSize().getZExtValue() == 0)
5180           return false;
5181         FT = AT->getElementType();
5182       }
5183       if (isEmptyRecord(getContext(), FT, true))
5184         continue;
5185 
5186       // For compatibility with GCC, ignore empty bitfields in C++ mode.
5187       if (getContext().getLangOpts().CPlusPlus &&
5188           FD->isZeroLengthBitField(getContext()))
5189         continue;
5190 
5191       uint64_t FldMembers;
5192       if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
5193         return false;
5194 
5195       Members = (RD->isUnion() ?
5196                  std::max(Members, FldMembers) : Members + FldMembers);
5197     }
5198 
5199     if (!Base)
5200       return false;
5201 
5202     // Ensure there is no padding.
5203     if (getContext().getTypeSize(Base) * Members !=
5204         getContext().getTypeSize(Ty))
5205       return false;
5206   } else {
5207     Members = 1;
5208     if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
5209       Members = 2;
5210       Ty = CT->getElementType();
5211     }
5212 
5213     // Most ABIs only support float, double, and some vector type widths.
5214     if (!isHomogeneousAggregateBaseType(Ty))
5215       return false;
5216 
5217     // The base type must be the same for all members.  Types that
5218     // agree in both total size and mode (float vs. vector) are
5219     // treated as being equivalent here.
5220     const Type *TyPtr = Ty.getTypePtr();
5221     if (!Base) {
5222       Base = TyPtr;
5223       // If it's a non-power-of-2 vector, its size is already a power-of-2,
5224       // so make sure to widen it explicitly.
5225       if (const VectorType *VT = Base->getAs<VectorType>()) {
5226         QualType EltTy = VT->getElementType();
5227         unsigned NumElements =
5228             getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
5229         Base = getContext()
5230                    .getVectorType(EltTy, NumElements, VT->getVectorKind())
5231                    .getTypePtr();
5232       }
5233     }
5234 
5235     if (Base->isVectorType() != TyPtr->isVectorType() ||
5236         getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
5237       return false;
5238   }
5239   return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
5240 }
5241 
5242 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5243   // Homogeneous aggregates for ELFv2 must have base types of float,
5244   // double, long double, or 128-bit vectors.
5245   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5246     if (BT->getKind() == BuiltinType::Float ||
5247         BT->getKind() == BuiltinType::Double ||
5248         BT->getKind() == BuiltinType::LongDouble ||
5249         BT->getKind() == BuiltinType::Ibm128 ||
5250         (getContext().getTargetInfo().hasFloat128Type() &&
5251          (BT->getKind() == BuiltinType::Float128))) {
5252       if (IsSoftFloatABI)
5253         return false;
5254       return true;
5255     }
5256   }
5257   if (const VectorType *VT = Ty->getAs<VectorType>()) {
5258     if (getContext().getTypeSize(VT) == 128)
5259       return true;
5260   }
5261   return false;
5262 }
5263 
5264 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
5265     const Type *Base, uint64_t Members) const {
5266   // Vector and fp128 types require one register, other floating point types
5267   // require one or two registers depending on their size.
5268   uint32_t NumRegs =
5269       ((getContext().getTargetInfo().hasFloat128Type() &&
5270           Base->isFloat128Type()) ||
5271         Base->isVectorType()) ? 1
5272                               : (getContext().getTypeSize(Base) + 63) / 64;
5273 
5274   // Homogeneous Aggregates may occupy at most 8 registers.
5275   return Members * NumRegs <= 8;
5276 }
5277 
5278 ABIArgInfo
5279 PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
5280   Ty = useFirstFieldIfTransparentUnion(Ty);
5281 
5282   if (Ty->isAnyComplexType())
5283     return ABIArgInfo::getDirect();
5284 
5285   // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
5286   // or via reference (larger than 16 bytes).
5287   if (Ty->isVectorType()) {
5288     uint64_t Size = getContext().getTypeSize(Ty);
5289     if (Size > 128)
5290       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5291     else if (Size < 128) {
5292       llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
5293       return ABIArgInfo::getDirect(CoerceTy);
5294     }
5295   }
5296 
5297   if (const auto *EIT = Ty->getAs<BitIntType>())
5298     if (EIT->getNumBits() > 128)
5299       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
5300 
5301   if (isAggregateTypeForABI(Ty)) {
5302     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
5303       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
5304 
5305     uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
5306     uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
5307 
5308     // ELFv2 homogeneous aggregates are passed as array types.
5309     const Type *Base = nullptr;
5310     uint64_t Members = 0;
5311     if (Kind == ELFv2 &&
5312         isHomogeneousAggregate(Ty, Base, Members)) {
5313       llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
5314       llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
5315       return ABIArgInfo::getDirect(CoerceTy);
5316     }
5317 
5318     // If an aggregate may end up fully in registers, we do not
5319     // use the ByVal method, but pass the aggregate as array.
5320     // This is usually beneficial since we avoid forcing the
5321     // back-end to store the argument to memory.
5322     uint64_t Bits = getContext().getTypeSize(Ty);
5323     if (Bits > 0 && Bits <= 8 * GPRBits) {
5324       llvm::Type *CoerceTy;
5325 
5326       // Types up to 8 bytes are passed as integer type (which will be
5327       // properly aligned in the argument save area doubleword).
5328       if (Bits <= GPRBits)
5329         CoerceTy =
5330             llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
5331       // Larger types are passed as arrays, with the base type selected
5332       // according to the required alignment in the save area.
5333       else {
5334         uint64_t RegBits = ABIAlign * 8;
5335         uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
5336         llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
5337         CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
5338       }
5339 
5340       return ABIArgInfo::getDirect(CoerceTy);
5341     }
5342 
5343     // All other aggregates are passed ByVal.
5344     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5345                                    /*ByVal=*/true,
5346                                    /*Realign=*/TyAlign > ABIAlign);
5347   }
5348 
5349   return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
5350                                      : ABIArgInfo::getDirect());
5351 }
5352 
5353 ABIArgInfo
5354 PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
5355   if (RetTy->isVoidType())
5356     return ABIArgInfo::getIgnore();
5357 
5358   if (RetTy->isAnyComplexType())
5359     return ABIArgInfo::getDirect();
5360 
5361   // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
5362   // or via reference (larger than 16 bytes).
5363   if (RetTy->isVectorType()) {
5364     uint64_t Size = getContext().getTypeSize(RetTy);
5365     if (Size > 128)
5366       return getNaturalAlignIndirect(RetTy);
5367     else if (Size < 128) {
5368       llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
5369       return ABIArgInfo::getDirect(CoerceTy);
5370     }
5371   }
5372 
5373   if (const auto *EIT = RetTy->getAs<BitIntType>())
5374     if (EIT->getNumBits() > 128)
5375       return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
5376 
5377   if (isAggregateTypeForABI(RetTy)) {
5378     // ELFv2 homogeneous aggregates are returned as array types.
5379     const Type *Base = nullptr;
5380     uint64_t Members = 0;
5381     if (Kind == ELFv2 &&
5382         isHomogeneousAggregate(RetTy, Base, Members)) {
5383       llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
5384       llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
5385       return ABIArgInfo::getDirect(CoerceTy);
5386     }
5387 
5388     // ELFv2 small aggregates are returned in up to two registers.
5389     uint64_t Bits = getContext().getTypeSize(RetTy);
5390     if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
5391       if (Bits == 0)
5392         return ABIArgInfo::getIgnore();
5393 
5394       llvm::Type *CoerceTy;
5395       if (Bits > GPRBits) {
5396         CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
5397         CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy);
5398       } else
5399         CoerceTy =
5400             llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
5401       return ABIArgInfo::getDirect(CoerceTy);
5402     }
5403 
5404     // All other aggregates are returned indirectly.
5405     return getNaturalAlignIndirect(RetTy);
5406   }
5407 
5408   return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
5409                                         : ABIArgInfo::getDirect());
5410 }
5411 
5412 // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
5413 Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5414                                       QualType Ty) const {
5415   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
5416   TypeInfo.Align = getParamTypeAlignment(Ty);
5417 
5418   CharUnits SlotSize = CharUnits::fromQuantity(8);
5419 
5420   // If we have a complex type and the base type is smaller than 8 bytes,
5421   // the ABI calls for the real and imaginary parts to be right-adjusted
5422   // in separate doublewords.  However, Clang expects us to produce a
5423   // pointer to a structure with the two parts packed tightly.  So generate
5424   // loads of the real and imaginary parts relative to the va_list pointer,
5425   // and store them to a temporary structure.
5426   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
5427     CharUnits EltSize = TypeInfo.Width / 2;
5428     if (EltSize < SlotSize)
5429       return complexTempStructure(CGF, VAListAddr, Ty, SlotSize, EltSize, CTy);
5430   }
5431 
5432   // Otherwise, just use the general rule.
5433   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
5434                           TypeInfo, SlotSize, /*AllowHigher*/ true);
5435 }
5436 
5437 bool
5438 PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
5439   CodeGen::CodeGenFunction &CGF,
5440   llvm::Value *Address) const {
5441   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true,
5442                                      /*IsAIX*/ false);
5443 }
5444 
5445 bool
5446 PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5447                                                 llvm::Value *Address) const {
5448   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true,
5449                                      /*IsAIX*/ false);
5450 }
5451 
5452 //===----------------------------------------------------------------------===//
5453 // AArch64 ABI Implementation
5454 //===----------------------------------------------------------------------===//
5455 
5456 namespace {
5457 
5458 class AArch64ABIInfo : public SwiftABIInfo {
5459 public:
5460   enum ABIKind {
5461     AAPCS = 0,
5462     DarwinPCS,
5463     Win64
5464   };
5465 
5466 private:
5467   ABIKind Kind;
5468 
5469 public:
5470   AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
5471     : SwiftABIInfo(CGT), Kind(Kind) {}
5472 
5473 private:
5474   ABIKind getABIKind() const { return Kind; }
5475   bool isDarwinPCS() const { return Kind == DarwinPCS; }
5476 
5477   ABIArgInfo classifyReturnType(QualType RetTy, bool IsVariadic) const;
5478   ABIArgInfo classifyArgumentType(QualType RetTy, bool IsVariadic,
5479                                   unsigned CallingConvention) const;
5480   ABIArgInfo coerceIllegalVector(QualType Ty) const;
5481   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5482   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5483                                          uint64_t Members) const override;
5484 
5485   bool isIllegalVectorType(QualType Ty) const;
5486 
5487   void computeInfo(CGFunctionInfo &FI) const override {
5488     if (!::classifyReturnType(getCXXABI(), FI, *this))
5489       FI.getReturnInfo() =
5490           classifyReturnType(FI.getReturnType(), FI.isVariadic());
5491 
5492     for (auto &it : FI.arguments())
5493       it.info = classifyArgumentType(it.type, FI.isVariadic(),
5494                                      FI.getCallingConvention());
5495   }
5496 
5497   Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5498                           CodeGenFunction &CGF) const;
5499 
5500   Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
5501                          CodeGenFunction &CGF) const;
5502 
5503   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5504                     QualType Ty) const override {
5505     llvm::Type *BaseTy = CGF.ConvertType(Ty);
5506     if (isa<llvm::ScalableVectorType>(BaseTy))
5507       llvm::report_fatal_error("Passing SVE types to variadic functions is "
5508                                "currently not supported");
5509 
5510     return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty)
5511                          : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
5512                                          : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
5513   }
5514 
5515   Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
5516                       QualType Ty) const override;
5517 
5518   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
5519                                     bool asReturnValue) const override {
5520     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5521   }
5522   bool isSwiftErrorInRegister() const override {
5523     return true;
5524   }
5525 
5526   bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
5527                                  unsigned elts) const override;
5528 
5529   bool allowBFloatArgsAndRet() const override {
5530     return getTarget().hasBFloat16Type();
5531   }
5532 };
5533 
5534 class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
5535 public:
5536   AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
5537       : TargetCodeGenInfo(std::make_unique<AArch64ABIInfo>(CGT, Kind)) {}
5538 
5539   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
5540     return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue";
5541   }
5542 
5543   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5544     return 31;
5545   }
5546 
5547   bool doesReturnSlotInterfereWithArgs() const override { return false; }
5548 
5549   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5550                            CodeGen::CodeGenModule &CGM) const override {
5551     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
5552     if (!FD)
5553       return;
5554 
5555     const auto *TA = FD->getAttr<TargetAttr>();
5556     if (TA == nullptr)
5557       return;
5558 
5559     ParsedTargetAttr Attr = TA->parse();
5560     if (Attr.BranchProtection.empty())
5561       return;
5562 
5563     TargetInfo::BranchProtectionInfo BPI;
5564     StringRef Error;
5565     (void)CGM.getTarget().validateBranchProtection(
5566         Attr.BranchProtection, Attr.Architecture, BPI, Error);
5567     assert(Error.empty());
5568 
5569     auto *Fn = cast<llvm::Function>(GV);
5570     static const char *SignReturnAddrStr[] = {"none", "non-leaf", "all"};
5571     Fn->addFnAttr("sign-return-address", SignReturnAddrStr[static_cast<int>(BPI.SignReturnAddr)]);
5572 
5573     if (BPI.SignReturnAddr != LangOptions::SignReturnAddressScopeKind::None) {
5574       Fn->addFnAttr("sign-return-address-key",
5575                     BPI.SignKey == LangOptions::SignReturnAddressKeyKind::AKey
5576                         ? "a_key"
5577                         : "b_key");
5578     }
5579 
5580     Fn->addFnAttr("branch-target-enforcement",
5581                   BPI.BranchTargetEnforcement ? "true" : "false");
5582   }
5583 
5584   bool isScalarizableAsmOperand(CodeGen::CodeGenFunction &CGF,
5585                                 llvm::Type *Ty) const override {
5586     if (CGF.getTarget().hasFeature("ls64")) {
5587       auto *ST = dyn_cast<llvm::StructType>(Ty);
5588       if (ST && ST->getNumElements() == 1) {
5589         auto *AT = dyn_cast<llvm::ArrayType>(ST->getElementType(0));
5590         if (AT && AT->getNumElements() == 8 &&
5591             AT->getElementType()->isIntegerTy(64))
5592           return true;
5593       }
5594     }
5595     return TargetCodeGenInfo::isScalarizableAsmOperand(CGF, Ty);
5596   }
5597 };
5598 
5599 class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
5600 public:
5601   WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K)
5602       : AArch64TargetCodeGenInfo(CGT, K) {}
5603 
5604   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5605                            CodeGen::CodeGenModule &CGM) const override;
5606 
5607   void getDependentLibraryOption(llvm::StringRef Lib,
5608                                  llvm::SmallString<24> &Opt) const override {
5609     Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5610   }
5611 
5612   void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5613                                llvm::SmallString<32> &Opt) const override {
5614     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5615   }
5616 };
5617 
5618 void WindowsAArch64TargetCodeGenInfo::setTargetAttributes(
5619     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
5620   AArch64TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
5621   if (GV->isDeclaration())
5622     return;
5623   addStackProbeTargetAttributes(D, GV, CGM);
5624 }
5625 }
5626 
5627 ABIArgInfo AArch64ABIInfo::coerceIllegalVector(QualType Ty) const {
5628   assert(Ty->isVectorType() && "expected vector type!");
5629 
5630   const auto *VT = Ty->castAs<VectorType>();
5631   if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) {
5632     assert(VT->getElementType()->isBuiltinType() && "expected builtin type!");
5633     assert(VT->getElementType()->castAs<BuiltinType>()->getKind() ==
5634                BuiltinType::UChar &&
5635            "unexpected builtin type for SVE predicate!");
5636     return ABIArgInfo::getDirect(llvm::ScalableVectorType::get(
5637         llvm::Type::getInt1Ty(getVMContext()), 16));
5638   }
5639 
5640   if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) {
5641     assert(VT->getElementType()->isBuiltinType() && "expected builtin type!");
5642 
5643     const auto *BT = VT->getElementType()->castAs<BuiltinType>();
5644     llvm::ScalableVectorType *ResType = nullptr;
5645     switch (BT->getKind()) {
5646     default:
5647       llvm_unreachable("unexpected builtin type for SVE vector!");
5648     case BuiltinType::SChar:
5649     case BuiltinType::UChar:
5650       ResType = llvm::ScalableVectorType::get(
5651           llvm::Type::getInt8Ty(getVMContext()), 16);
5652       break;
5653     case BuiltinType::Short:
5654     case BuiltinType::UShort:
5655       ResType = llvm::ScalableVectorType::get(
5656           llvm::Type::getInt16Ty(getVMContext()), 8);
5657       break;
5658     case BuiltinType::Int:
5659     case BuiltinType::UInt:
5660       ResType = llvm::ScalableVectorType::get(
5661           llvm::Type::getInt32Ty(getVMContext()), 4);
5662       break;
5663     case BuiltinType::Long:
5664     case BuiltinType::ULong:
5665       ResType = llvm::ScalableVectorType::get(
5666           llvm::Type::getInt64Ty(getVMContext()), 2);
5667       break;
5668     case BuiltinType::Half:
5669       ResType = llvm::ScalableVectorType::get(
5670           llvm::Type::getHalfTy(getVMContext()), 8);
5671       break;
5672     case BuiltinType::Float:
5673       ResType = llvm::ScalableVectorType::get(
5674           llvm::Type::getFloatTy(getVMContext()), 4);
5675       break;
5676     case BuiltinType::Double:
5677       ResType = llvm::ScalableVectorType::get(
5678           llvm::Type::getDoubleTy(getVMContext()), 2);
5679       break;
5680     case BuiltinType::BFloat16:
5681       ResType = llvm::ScalableVectorType::get(
5682           llvm::Type::getBFloatTy(getVMContext()), 8);
5683       break;
5684     }
5685     return ABIArgInfo::getDirect(ResType);
5686   }
5687 
5688   uint64_t Size = getContext().getTypeSize(Ty);
5689   // Android promotes <2 x i8> to i16, not i32
5690   if (isAndroid() && (Size <= 16)) {
5691     llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
5692     return ABIArgInfo::getDirect(ResType);
5693   }
5694   if (Size <= 32) {
5695     llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
5696     return ABIArgInfo::getDirect(ResType);
5697   }
5698   if (Size == 64) {
5699     auto *ResType =
5700         llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
5701     return ABIArgInfo::getDirect(ResType);
5702   }
5703   if (Size == 128) {
5704     auto *ResType =
5705         llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
5706     return ABIArgInfo::getDirect(ResType);
5707   }
5708   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5709 }
5710 
5711 ABIArgInfo
5712 AArch64ABIInfo::classifyArgumentType(QualType Ty, bool IsVariadic,
5713                                      unsigned CallingConvention) const {
5714   Ty = useFirstFieldIfTransparentUnion(Ty);
5715 
5716   // Handle illegal vector types here.
5717   if (isIllegalVectorType(Ty))
5718     return coerceIllegalVector(Ty);
5719 
5720   if (!isAggregateTypeForABI(Ty)) {
5721     // Treat an enum type as its underlying type.
5722     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5723       Ty = EnumTy->getDecl()->getIntegerType();
5724 
5725     if (const auto *EIT = Ty->getAs<BitIntType>())
5726       if (EIT->getNumBits() > 128)
5727         return getNaturalAlignIndirect(Ty);
5728 
5729     return (isPromotableIntegerTypeForABI(Ty) && isDarwinPCS()
5730                 ? ABIArgInfo::getExtend(Ty)
5731                 : ABIArgInfo::getDirect());
5732   }
5733 
5734   // Structures with either a non-trivial destructor or a non-trivial
5735   // copy constructor are always indirect.
5736   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
5737     return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
5738                                      CGCXXABI::RAA_DirectInMemory);
5739   }
5740 
5741   // Empty records are always ignored on Darwin, but actually passed in C++ mode
5742   // elsewhere for GNU compatibility.
5743   uint64_t Size = getContext().getTypeSize(Ty);
5744   bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
5745   if (IsEmpty || Size == 0) {
5746     if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
5747       return ABIArgInfo::getIgnore();
5748 
5749     // GNU C mode. The only argument that gets ignored is an empty one with size
5750     // 0.
5751     if (IsEmpty && Size == 0)
5752       return ABIArgInfo::getIgnore();
5753     return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5754   }
5755 
5756   // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
5757   const Type *Base = nullptr;
5758   uint64_t Members = 0;
5759   bool IsWin64 = Kind == Win64 || CallingConvention == llvm::CallingConv::Win64;
5760   bool IsWinVariadic = IsWin64 && IsVariadic;
5761   // In variadic functions on Windows, all composite types are treated alike,
5762   // no special handling of HFAs/HVAs.
5763   if (!IsWinVariadic && isHomogeneousAggregate(Ty, Base, Members)) {
5764     if (Kind != AArch64ABIInfo::AAPCS)
5765       return ABIArgInfo::getDirect(
5766           llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
5767 
5768     // For alignment adjusted HFAs, cap the argument alignment to 16, leave it
5769     // default otherwise.
5770     unsigned Align =
5771         getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
5772     unsigned BaseAlign = getContext().getTypeAlignInChars(Base).getQuantity();
5773     Align = (Align > BaseAlign && Align >= 16) ? 16 : 0;
5774     return ABIArgInfo::getDirect(
5775         llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members), 0,
5776         nullptr, true, Align);
5777   }
5778 
5779   // Aggregates <= 16 bytes are passed directly in registers or on the stack.
5780   if (Size <= 128) {
5781     // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5782     // same size and alignment.
5783     if (getTarget().isRenderScriptTarget()) {
5784       return coerceToIntArray(Ty, getContext(), getVMContext());
5785     }
5786     unsigned Alignment;
5787     if (Kind == AArch64ABIInfo::AAPCS) {
5788       Alignment = getContext().getTypeUnadjustedAlign(Ty);
5789       Alignment = Alignment < 128 ? 64 : 128;
5790     } else {
5791       Alignment = std::max(getContext().getTypeAlign(Ty),
5792                            (unsigned)getTarget().getPointerWidth(0));
5793     }
5794     Size = llvm::alignTo(Size, Alignment);
5795 
5796     // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5797     // For aggregates with 16-byte alignment, we use i128.
5798     llvm::Type *BaseTy = llvm::Type::getIntNTy(getVMContext(), Alignment);
5799     return ABIArgInfo::getDirect(
5800         Size == Alignment ? BaseTy
5801                           : llvm::ArrayType::get(BaseTy, Size / Alignment));
5802   }
5803 
5804   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5805 }
5806 
5807 ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy,
5808                                               bool IsVariadic) const {
5809   if (RetTy->isVoidType())
5810     return ABIArgInfo::getIgnore();
5811 
5812   if (const auto *VT = RetTy->getAs<VectorType>()) {
5813     if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector ||
5814         VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
5815       return coerceIllegalVector(RetTy);
5816   }
5817 
5818   // Large vector types should be returned via memory.
5819   if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
5820     return getNaturalAlignIndirect(RetTy);
5821 
5822   if (!isAggregateTypeForABI(RetTy)) {
5823     // Treat an enum type as its underlying type.
5824     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5825       RetTy = EnumTy->getDecl()->getIntegerType();
5826 
5827     if (const auto *EIT = RetTy->getAs<BitIntType>())
5828       if (EIT->getNumBits() > 128)
5829         return getNaturalAlignIndirect(RetTy);
5830 
5831     return (isPromotableIntegerTypeForABI(RetTy) && isDarwinPCS()
5832                 ? ABIArgInfo::getExtend(RetTy)
5833                 : ABIArgInfo::getDirect());
5834   }
5835 
5836   uint64_t Size = getContext().getTypeSize(RetTy);
5837   if (isEmptyRecord(getContext(), RetTy, true) || Size == 0)
5838     return ABIArgInfo::getIgnore();
5839 
5840   const Type *Base = nullptr;
5841   uint64_t Members = 0;
5842   if (isHomogeneousAggregate(RetTy, Base, Members) &&
5843       !(getTarget().getTriple().getArch() == llvm::Triple::aarch64_32 &&
5844         IsVariadic))
5845     // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
5846     return ABIArgInfo::getDirect();
5847 
5848   // Aggregates <= 16 bytes are returned directly in registers or on the stack.
5849   if (Size <= 128) {
5850     // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5851     // same size and alignment.
5852     if (getTarget().isRenderScriptTarget()) {
5853       return coerceToIntArray(RetTy, getContext(), getVMContext());
5854     }
5855 
5856     if (Size <= 64 && getDataLayout().isLittleEndian()) {
5857       // Composite types are returned in lower bits of a 64-bit register for LE,
5858       // and in higher bits for BE. However, integer types are always returned
5859       // in lower bits for both LE and BE, and they are not rounded up to
5860       // 64-bits. We can skip rounding up of composite types for LE, but not for
5861       // BE, otherwise composite types will be indistinguishable from integer
5862       // types.
5863       return ABIArgInfo::getDirect(
5864           llvm::IntegerType::get(getVMContext(), Size));
5865     }
5866 
5867     unsigned Alignment = getContext().getTypeAlign(RetTy);
5868     Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
5869 
5870     // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5871     // For aggregates with 16-byte alignment, we use i128.
5872     if (Alignment < 128 && Size == 128) {
5873       llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5874       return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5875     }
5876     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5877   }
5878 
5879   return getNaturalAlignIndirect(RetTy);
5880 }
5881 
5882 /// isIllegalVectorType - check whether the vector type is legal for AArch64.
5883 bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
5884   if (const VectorType *VT = Ty->getAs<VectorType>()) {
5885     // Check whether VT is a fixed-length SVE vector. These types are
5886     // represented as scalable vectors in function args/return and must be
5887     // coerced from fixed vectors.
5888     if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector ||
5889         VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
5890       return true;
5891 
5892     // Check whether VT is legal.
5893     unsigned NumElements = VT->getNumElements();
5894     uint64_t Size = getContext().getTypeSize(VT);
5895     // NumElements should be power of 2.
5896     if (!llvm::isPowerOf2_32(NumElements))
5897       return true;
5898 
5899     // arm64_32 has to be compatible with the ARM logic here, which allows huge
5900     // vectors for some reason.
5901     llvm::Triple Triple = getTarget().getTriple();
5902     if (Triple.getArch() == llvm::Triple::aarch64_32 &&
5903         Triple.isOSBinFormatMachO())
5904       return Size <= 32;
5905 
5906     return Size != 64 && (Size != 128 || NumElements == 1);
5907   }
5908   return false;
5909 }
5910 
5911 bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize,
5912                                                llvm::Type *eltTy,
5913                                                unsigned elts) const {
5914   if (!llvm::isPowerOf2_32(elts))
5915     return false;
5916   if (totalSize.getQuantity() != 8 &&
5917       (totalSize.getQuantity() != 16 || elts == 1))
5918     return false;
5919   return true;
5920 }
5921 
5922 bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5923   // Homogeneous aggregates for AAPCS64 must have base types of a floating
5924   // point type or a short-vector type. This is the same as the 32-bit ABI,
5925   // but with the difference that any floating-point type is allowed,
5926   // including __fp16.
5927   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5928     if (BT->isFloatingPoint())
5929       return true;
5930   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5931     unsigned VecSize = getContext().getTypeSize(VT);
5932     if (VecSize == 64 || VecSize == 128)
5933       return true;
5934   }
5935   return false;
5936 }
5937 
5938 bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5939                                                        uint64_t Members) const {
5940   return Members <= 4;
5941 }
5942 
5943 Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
5944                                        CodeGenFunction &CGF) const {
5945   ABIArgInfo AI = classifyArgumentType(Ty, /*IsVariadic=*/true,
5946                                        CGF.CurFnInfo->getCallingConvention());
5947   bool IsIndirect = AI.isIndirect();
5948 
5949   llvm::Type *BaseTy = CGF.ConvertType(Ty);
5950   if (IsIndirect)
5951     BaseTy = llvm::PointerType::getUnqual(BaseTy);
5952   else if (AI.getCoerceToType())
5953     BaseTy = AI.getCoerceToType();
5954 
5955   unsigned NumRegs = 1;
5956   if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
5957     BaseTy = ArrTy->getElementType();
5958     NumRegs = ArrTy->getNumElements();
5959   }
5960   bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
5961 
5962   // The AArch64 va_list type and handling is specified in the Procedure Call
5963   // Standard, section B.4:
5964   //
5965   // struct {
5966   //   void *__stack;
5967   //   void *__gr_top;
5968   //   void *__vr_top;
5969   //   int __gr_offs;
5970   //   int __vr_offs;
5971   // };
5972 
5973   llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
5974   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5975   llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
5976   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5977 
5978   CharUnits TySize = getContext().getTypeSizeInChars(Ty);
5979   CharUnits TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty);
5980 
5981   Address reg_offs_p = Address::invalid();
5982   llvm::Value *reg_offs = nullptr;
5983   int reg_top_index;
5984   int RegSize = IsIndirect ? 8 : TySize.getQuantity();
5985   if (!IsFPR) {
5986     // 3 is the field number of __gr_offs
5987     reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
5988     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
5989     reg_top_index = 1; // field number for __gr_top
5990     RegSize = llvm::alignTo(RegSize, 8);
5991   } else {
5992     // 4 is the field number of __vr_offs.
5993     reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
5994     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
5995     reg_top_index = 2; // field number for __vr_top
5996     RegSize = 16 * NumRegs;
5997   }
5998 
5999   //=======================================
6000   // Find out where argument was passed
6001   //=======================================
6002 
6003   // If reg_offs >= 0 we're already using the stack for this type of
6004   // argument. We don't want to keep updating reg_offs (in case it overflows,
6005   // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
6006   // whatever they get).
6007   llvm::Value *UsingStack = nullptr;
6008   UsingStack = CGF.Builder.CreateICmpSGE(
6009       reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
6010 
6011   CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
6012 
6013   // Otherwise, at least some kind of argument could go in these registers, the
6014   // question is whether this particular type is too big.
6015   CGF.EmitBlock(MaybeRegBlock);
6016 
6017   // Integer arguments may need to correct register alignment (for example a
6018   // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
6019   // align __gr_offs to calculate the potential address.
6020   if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
6021     int Align = TyAlign.getQuantity();
6022 
6023     reg_offs = CGF.Builder.CreateAdd(
6024         reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
6025         "align_regoffs");
6026     reg_offs = CGF.Builder.CreateAnd(
6027         reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
6028         "aligned_regoffs");
6029   }
6030 
6031   // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
6032   // The fact that this is done unconditionally reflects the fact that
6033   // allocating an argument to the stack also uses up all the remaining
6034   // registers of the appropriate kind.
6035   llvm::Value *NewOffset = nullptr;
6036   NewOffset = CGF.Builder.CreateAdd(
6037       reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
6038   CGF.Builder.CreateStore(NewOffset, reg_offs_p);
6039 
6040   // Now we're in a position to decide whether this argument really was in
6041   // registers or not.
6042   llvm::Value *InRegs = nullptr;
6043   InRegs = CGF.Builder.CreateICmpSLE(
6044       NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
6045 
6046   CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
6047 
6048   //=======================================
6049   // Argument was in registers
6050   //=======================================
6051 
6052   // Now we emit the code for if the argument was originally passed in
6053   // registers. First start the appropriate block:
6054   CGF.EmitBlock(InRegBlock);
6055 
6056   llvm::Value *reg_top = nullptr;
6057   Address reg_top_p =
6058       CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
6059   reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
6060   Address BaseAddr(CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, reg_top, reg_offs),
6061                    CGF.Int8Ty, CharUnits::fromQuantity(IsFPR ? 16 : 8));
6062   Address RegAddr = Address::invalid();
6063   llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
6064 
6065   if (IsIndirect) {
6066     // If it's been passed indirectly (actually a struct), whatever we find from
6067     // stored registers or on the stack will actually be a struct **.
6068     MemTy = llvm::PointerType::getUnqual(MemTy);
6069   }
6070 
6071   const Type *Base = nullptr;
6072   uint64_t NumMembers = 0;
6073   bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
6074   if (IsHFA && NumMembers > 1) {
6075     // Homogeneous aggregates passed in registers will have their elements split
6076     // and stored 16-bytes apart regardless of size (they're notionally in qN,
6077     // qN+1, ...). We reload and store into a temporary local variable
6078     // contiguously.
6079     assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
6080     auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
6081     llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
6082     llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
6083     Address Tmp = CGF.CreateTempAlloca(HFATy,
6084                                        std::max(TyAlign, BaseTyInfo.Align));
6085 
6086     // On big-endian platforms, the value will be right-aligned in its slot.
6087     int Offset = 0;
6088     if (CGF.CGM.getDataLayout().isBigEndian() &&
6089         BaseTyInfo.Width.getQuantity() < 16)
6090       Offset = 16 - BaseTyInfo.Width.getQuantity();
6091 
6092     for (unsigned i = 0; i < NumMembers; ++i) {
6093       CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
6094       Address LoadAddr =
6095         CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
6096       LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
6097 
6098       Address StoreAddr = CGF.Builder.CreateConstArrayGEP(Tmp, i);
6099 
6100       llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
6101       CGF.Builder.CreateStore(Elem, StoreAddr);
6102     }
6103 
6104     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
6105   } else {
6106     // Otherwise the object is contiguous in memory.
6107 
6108     // It might be right-aligned in its slot.
6109     CharUnits SlotSize = BaseAddr.getAlignment();
6110     if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
6111         (IsHFA || !isAggregateTypeForABI(Ty)) &&
6112         TySize < SlotSize) {
6113       CharUnits Offset = SlotSize - TySize;
6114       BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
6115     }
6116 
6117     RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
6118   }
6119 
6120   CGF.EmitBranch(ContBlock);
6121 
6122   //=======================================
6123   // Argument was on the stack
6124   //=======================================
6125   CGF.EmitBlock(OnStackBlock);
6126 
6127   Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
6128   llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
6129 
6130   // Again, stack arguments may need realignment. In this case both integer and
6131   // floating-point ones might be affected.
6132   if (!IsIndirect && TyAlign.getQuantity() > 8) {
6133     int Align = TyAlign.getQuantity();
6134 
6135     OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
6136 
6137     OnStackPtr = CGF.Builder.CreateAdd(
6138         OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
6139         "align_stack");
6140     OnStackPtr = CGF.Builder.CreateAnd(
6141         OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
6142         "align_stack");
6143 
6144     OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
6145   }
6146   Address OnStackAddr = Address::deprecated(
6147       OnStackPtr, std::max(CharUnits::fromQuantity(8), TyAlign));
6148 
6149   // All stack slots are multiples of 8 bytes.
6150   CharUnits StackSlotSize = CharUnits::fromQuantity(8);
6151   CharUnits StackSize;
6152   if (IsIndirect)
6153     StackSize = StackSlotSize;
6154   else
6155     StackSize = TySize.alignTo(StackSlotSize);
6156 
6157   llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
6158   llvm::Value *NewStack = CGF.Builder.CreateInBoundsGEP(
6159       CGF.Int8Ty, OnStackPtr, StackSizeC, "new_stack");
6160 
6161   // Write the new value of __stack for the next call to va_arg
6162   CGF.Builder.CreateStore(NewStack, stack_p);
6163 
6164   if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
6165       TySize < StackSlotSize) {
6166     CharUnits Offset = StackSlotSize - TySize;
6167     OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
6168   }
6169 
6170   OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
6171 
6172   CGF.EmitBranch(ContBlock);
6173 
6174   //=======================================
6175   // Tidy up
6176   //=======================================
6177   CGF.EmitBlock(ContBlock);
6178 
6179   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, OnStackAddr,
6180                                  OnStackBlock, "vaargs.addr");
6181 
6182   if (IsIndirect)
6183     return Address::deprecated(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
6184                                TyAlign);
6185 
6186   return ResAddr;
6187 }
6188 
6189 Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
6190                                         CodeGenFunction &CGF) const {
6191   // The backend's lowering doesn't support va_arg for aggregates or
6192   // illegal vector types.  Lower VAArg here for these cases and use
6193   // the LLVM va_arg instruction for everything else.
6194   if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
6195     return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
6196 
6197   uint64_t PointerSize = getTarget().getPointerWidth(0) / 8;
6198   CharUnits SlotSize = CharUnits::fromQuantity(PointerSize);
6199 
6200   // Empty records are ignored for parameter passing purposes.
6201   if (isEmptyRecord(getContext(), Ty, true)) {
6202     Address Addr = Address::deprecated(
6203         CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
6204     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6205     return Addr;
6206   }
6207 
6208   // The size of the actual thing passed, which might end up just
6209   // being a pointer for indirect types.
6210   auto TyInfo = getContext().getTypeInfoInChars(Ty);
6211 
6212   // Arguments bigger than 16 bytes which aren't homogeneous
6213   // aggregates should be passed indirectly.
6214   bool IsIndirect = false;
6215   if (TyInfo.Width.getQuantity() > 16) {
6216     const Type *Base = nullptr;
6217     uint64_t Members = 0;
6218     IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
6219   }
6220 
6221   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
6222                           TyInfo, SlotSize, /*AllowHigherAlign*/ true);
6223 }
6224 
6225 Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
6226                                     QualType Ty) const {
6227   bool IsIndirect = false;
6228 
6229   // Composites larger than 16 bytes are passed by reference.
6230   if (isAggregateTypeForABI(Ty) && getContext().getTypeSize(Ty) > 128)
6231     IsIndirect = true;
6232 
6233   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
6234                           CGF.getContext().getTypeInfoInChars(Ty),
6235                           CharUnits::fromQuantity(8),
6236                           /*allowHigherAlign*/ false);
6237 }
6238 
6239 //===----------------------------------------------------------------------===//
6240 // ARM ABI Implementation
6241 //===----------------------------------------------------------------------===//
6242 
6243 namespace {
6244 
6245 class ARMABIInfo : public SwiftABIInfo {
6246 public:
6247   enum ABIKind {
6248     APCS = 0,
6249     AAPCS = 1,
6250     AAPCS_VFP = 2,
6251     AAPCS16_VFP = 3,
6252   };
6253 
6254 private:
6255   ABIKind Kind;
6256   bool IsFloatABISoftFP;
6257 
6258 public:
6259   ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
6260       : SwiftABIInfo(CGT), Kind(_Kind) {
6261     setCCs();
6262     IsFloatABISoftFP = CGT.getCodeGenOpts().FloatABI == "softfp" ||
6263         CGT.getCodeGenOpts().FloatABI == ""; // default
6264   }
6265 
6266   bool isEABI() const {
6267     switch (getTarget().getTriple().getEnvironment()) {
6268     case llvm::Triple::Android:
6269     case llvm::Triple::EABI:
6270     case llvm::Triple::EABIHF:
6271     case llvm::Triple::GNUEABI:
6272     case llvm::Triple::GNUEABIHF:
6273     case llvm::Triple::MuslEABI:
6274     case llvm::Triple::MuslEABIHF:
6275       return true;
6276     default:
6277       return false;
6278     }
6279   }
6280 
6281   bool isEABIHF() const {
6282     switch (getTarget().getTriple().getEnvironment()) {
6283     case llvm::Triple::EABIHF:
6284     case llvm::Triple::GNUEABIHF:
6285     case llvm::Triple::MuslEABIHF:
6286       return true;
6287     default:
6288       return false;
6289     }
6290   }
6291 
6292   ABIKind getABIKind() const { return Kind; }
6293 
6294   bool allowBFloatArgsAndRet() const override {
6295     return !IsFloatABISoftFP && getTarget().hasBFloat16Type();
6296   }
6297 
6298 private:
6299   ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic,
6300                                 unsigned functionCallConv) const;
6301   ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic,
6302                                   unsigned functionCallConv) const;
6303   ABIArgInfo classifyHomogeneousAggregate(QualType Ty, const Type *Base,
6304                                           uint64_t Members) const;
6305   ABIArgInfo coerceIllegalVector(QualType Ty) const;
6306   bool isIllegalVectorType(QualType Ty) const;
6307   bool containsAnyFP16Vectors(QualType Ty) const;
6308 
6309   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
6310   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
6311                                          uint64_t Members) const override;
6312 
6313   bool isEffectivelyAAPCS_VFP(unsigned callConvention, bool acceptHalf) const;
6314 
6315   void computeInfo(CGFunctionInfo &FI) const override;
6316 
6317   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6318                     QualType Ty) const override;
6319 
6320   llvm::CallingConv::ID getLLVMDefaultCC() const;
6321   llvm::CallingConv::ID getABIDefaultCC() const;
6322   void setCCs();
6323 
6324   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
6325                                     bool asReturnValue) const override {
6326     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
6327   }
6328   bool isSwiftErrorInRegister() const override {
6329     return true;
6330   }
6331   bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
6332                                  unsigned elts) const override;
6333 };
6334 
6335 class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
6336 public:
6337   ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
6338       : TargetCodeGenInfo(std::make_unique<ARMABIInfo>(CGT, K)) {}
6339 
6340   const ARMABIInfo &getABIInfo() const {
6341     return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
6342   }
6343 
6344   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
6345     return 13;
6346   }
6347 
6348   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
6349     return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue";
6350   }
6351 
6352   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6353                                llvm::Value *Address) const override {
6354     llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
6355 
6356     // 0-15 are the 16 integer registers.
6357     AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
6358     return false;
6359   }
6360 
6361   unsigned getSizeOfUnwindException() const override {
6362     if (getABIInfo().isEABI()) return 88;
6363     return TargetCodeGenInfo::getSizeOfUnwindException();
6364   }
6365 
6366   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6367                            CodeGen::CodeGenModule &CGM) const override {
6368     if (GV->isDeclaration())
6369       return;
6370     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
6371     if (!FD)
6372       return;
6373     auto *Fn = cast<llvm::Function>(GV);
6374 
6375     if (const auto *TA = FD->getAttr<TargetAttr>()) {
6376       ParsedTargetAttr Attr = TA->parse();
6377       if (!Attr.BranchProtection.empty()) {
6378         TargetInfo::BranchProtectionInfo BPI;
6379         StringRef DiagMsg;
6380         StringRef Arch = Attr.Architecture.empty()
6381                              ? CGM.getTarget().getTargetOpts().CPU
6382                              : Attr.Architecture;
6383         if (!CGM.getTarget().validateBranchProtection(Attr.BranchProtection,
6384                                                       Arch, BPI, DiagMsg)) {
6385           CGM.getDiags().Report(
6386               D->getLocation(),
6387               diag::warn_target_unsupported_branch_protection_attribute)
6388               << Arch;
6389         } else {
6390           static const char *SignReturnAddrStr[] = {"none", "non-leaf", "all"};
6391           assert(static_cast<unsigned>(BPI.SignReturnAddr) <= 2 &&
6392                  "Unexpected SignReturnAddressScopeKind");
6393           Fn->addFnAttr(
6394               "sign-return-address",
6395               SignReturnAddrStr[static_cast<int>(BPI.SignReturnAddr)]);
6396 
6397           Fn->addFnAttr("branch-target-enforcement",
6398                         BPI.BranchTargetEnforcement ? "true" : "false");
6399         }
6400       } else if (CGM.getLangOpts().BranchTargetEnforcement ||
6401                  CGM.getLangOpts().hasSignReturnAddress()) {
6402         // If the Branch Protection attribute is missing, validate the target
6403         // Architecture attribute against Branch Protection command line
6404         // settings.
6405         if (!CGM.getTarget().isBranchProtectionSupportedArch(Attr.Architecture))
6406           CGM.getDiags().Report(
6407               D->getLocation(),
6408               diag::warn_target_unsupported_branch_protection_attribute)
6409               << Attr.Architecture;
6410       }
6411     }
6412 
6413     const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
6414     if (!Attr)
6415       return;
6416 
6417     const char *Kind;
6418     switch (Attr->getInterrupt()) {
6419     case ARMInterruptAttr::Generic: Kind = ""; break;
6420     case ARMInterruptAttr::IRQ:     Kind = "IRQ"; break;
6421     case ARMInterruptAttr::FIQ:     Kind = "FIQ"; break;
6422     case ARMInterruptAttr::SWI:     Kind = "SWI"; break;
6423     case ARMInterruptAttr::ABORT:   Kind = "ABORT"; break;
6424     case ARMInterruptAttr::UNDEF:   Kind = "UNDEF"; break;
6425     }
6426 
6427     Fn->addFnAttr("interrupt", Kind);
6428 
6429     ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
6430     if (ABI == ARMABIInfo::APCS)
6431       return;
6432 
6433     // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
6434     // however this is not necessarily true on taking any interrupt. Instruct
6435     // the backend to perform a realignment as part of the function prologue.
6436     llvm::AttrBuilder B(Fn->getContext());
6437     B.addStackAlignmentAttr(8);
6438     Fn->addFnAttrs(B);
6439   }
6440 };
6441 
6442 class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
6443 public:
6444   WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
6445       : ARMTargetCodeGenInfo(CGT, K) {}
6446 
6447   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6448                            CodeGen::CodeGenModule &CGM) const override;
6449 
6450   void getDependentLibraryOption(llvm::StringRef Lib,
6451                                  llvm::SmallString<24> &Opt) const override {
6452     Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
6453   }
6454 
6455   void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
6456                                llvm::SmallString<32> &Opt) const override {
6457     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
6458   }
6459 };
6460 
6461 void WindowsARMTargetCodeGenInfo::setTargetAttributes(
6462     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
6463   ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
6464   if (GV->isDeclaration())
6465     return;
6466   addStackProbeTargetAttributes(D, GV, CGM);
6467 }
6468 }
6469 
6470 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
6471   if (!::classifyReturnType(getCXXABI(), FI, *this))
6472     FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic(),
6473                                             FI.getCallingConvention());
6474 
6475   for (auto &I : FI.arguments())
6476     I.info = classifyArgumentType(I.type, FI.isVariadic(),
6477                                   FI.getCallingConvention());
6478 
6479 
6480   // Always honor user-specified calling convention.
6481   if (FI.getCallingConvention() != llvm::CallingConv::C)
6482     return;
6483 
6484   llvm::CallingConv::ID cc = getRuntimeCC();
6485   if (cc != llvm::CallingConv::C)
6486     FI.setEffectiveCallingConvention(cc);
6487 }
6488 
6489 /// Return the default calling convention that LLVM will use.
6490 llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
6491   // The default calling convention that LLVM will infer.
6492   if (isEABIHF() || getTarget().getTriple().isWatchABI())
6493     return llvm::CallingConv::ARM_AAPCS_VFP;
6494   else if (isEABI())
6495     return llvm::CallingConv::ARM_AAPCS;
6496   else
6497     return llvm::CallingConv::ARM_APCS;
6498 }
6499 
6500 /// Return the calling convention that our ABI would like us to use
6501 /// as the C calling convention.
6502 llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
6503   switch (getABIKind()) {
6504   case APCS: return llvm::CallingConv::ARM_APCS;
6505   case AAPCS: return llvm::CallingConv::ARM_AAPCS;
6506   case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
6507   case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
6508   }
6509   llvm_unreachable("bad ABI kind");
6510 }
6511 
6512 void ARMABIInfo::setCCs() {
6513   assert(getRuntimeCC() == llvm::CallingConv::C);
6514 
6515   // Don't muddy up the IR with a ton of explicit annotations if
6516   // they'd just match what LLVM will infer from the triple.
6517   llvm::CallingConv::ID abiCC = getABIDefaultCC();
6518   if (abiCC != getLLVMDefaultCC())
6519     RuntimeCC = abiCC;
6520 }
6521 
6522 ABIArgInfo ARMABIInfo::coerceIllegalVector(QualType Ty) const {
6523   uint64_t Size = getContext().getTypeSize(Ty);
6524   if (Size <= 32) {
6525     llvm::Type *ResType =
6526         llvm::Type::getInt32Ty(getVMContext());
6527     return ABIArgInfo::getDirect(ResType);
6528   }
6529   if (Size == 64 || Size == 128) {
6530     auto *ResType = llvm::FixedVectorType::get(
6531         llvm::Type::getInt32Ty(getVMContext()), Size / 32);
6532     return ABIArgInfo::getDirect(ResType);
6533   }
6534   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
6535 }
6536 
6537 ABIArgInfo ARMABIInfo::classifyHomogeneousAggregate(QualType Ty,
6538                                                     const Type *Base,
6539                                                     uint64_t Members) const {
6540   assert(Base && "Base class should be set for homogeneous aggregate");
6541   // Base can be a floating-point or a vector.
6542   if (const VectorType *VT = Base->getAs<VectorType>()) {
6543     // FP16 vectors should be converted to integer vectors
6544     if (!getTarget().hasLegalHalfType() && containsAnyFP16Vectors(Ty)) {
6545       uint64_t Size = getContext().getTypeSize(VT);
6546       auto *NewVecTy = llvm::FixedVectorType::get(
6547           llvm::Type::getInt32Ty(getVMContext()), Size / 32);
6548       llvm::Type *Ty = llvm::ArrayType::get(NewVecTy, Members);
6549       return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
6550     }
6551   }
6552   unsigned Align = 0;
6553   if (getABIKind() == ARMABIInfo::AAPCS ||
6554       getABIKind() == ARMABIInfo::AAPCS_VFP) {
6555     // For alignment adjusted HFAs, cap the argument alignment to 8, leave it
6556     // default otherwise.
6557     Align = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
6558     unsigned BaseAlign = getContext().getTypeAlignInChars(Base).getQuantity();
6559     Align = (Align > BaseAlign && Align >= 8) ? 8 : 0;
6560   }
6561   return ABIArgInfo::getDirect(nullptr, 0, nullptr, false, Align);
6562 }
6563 
6564 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic,
6565                                             unsigned functionCallConv) const {
6566   // 6.1.2.1 The following argument types are VFP CPRCs:
6567   //   A single-precision floating-point type (including promoted
6568   //   half-precision types); A double-precision floating-point type;
6569   //   A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
6570   //   with a Base Type of a single- or double-precision floating-point type,
6571   //   64-bit containerized vectors or 128-bit containerized vectors with one
6572   //   to four Elements.
6573   // Variadic functions should always marshal to the base standard.
6574   bool IsAAPCS_VFP =
6575       !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ false);
6576 
6577   Ty = useFirstFieldIfTransparentUnion(Ty);
6578 
6579   // Handle illegal vector types here.
6580   if (isIllegalVectorType(Ty))
6581     return coerceIllegalVector(Ty);
6582 
6583   if (!isAggregateTypeForABI(Ty)) {
6584     // Treat an enum type as its underlying type.
6585     if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
6586       Ty = EnumTy->getDecl()->getIntegerType();
6587     }
6588 
6589     if (const auto *EIT = Ty->getAs<BitIntType>())
6590       if (EIT->getNumBits() > 64)
6591         return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
6592 
6593     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
6594                                               : ABIArgInfo::getDirect());
6595   }
6596 
6597   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
6598     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
6599   }
6600 
6601   // Ignore empty records.
6602   if (isEmptyRecord(getContext(), Ty, true))
6603     return ABIArgInfo::getIgnore();
6604 
6605   if (IsAAPCS_VFP) {
6606     // Homogeneous Aggregates need to be expanded when we can fit the aggregate
6607     // into VFP registers.
6608     const Type *Base = nullptr;
6609     uint64_t Members = 0;
6610     if (isHomogeneousAggregate(Ty, Base, Members))
6611       return classifyHomogeneousAggregate(Ty, Base, Members);
6612   } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6613     // WatchOS does have homogeneous aggregates. Note that we intentionally use
6614     // this convention even for a variadic function: the backend will use GPRs
6615     // if needed.
6616     const Type *Base = nullptr;
6617     uint64_t Members = 0;
6618     if (isHomogeneousAggregate(Ty, Base, Members)) {
6619       assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
6620       llvm::Type *Ty =
6621         llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
6622       return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
6623     }
6624   }
6625 
6626   if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6627       getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
6628     // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
6629     // bigger than 128-bits, they get placed in space allocated by the caller,
6630     // and a pointer is passed.
6631     return ABIArgInfo::getIndirect(
6632         CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
6633   }
6634 
6635   // Support byval for ARM.
6636   // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
6637   // most 8-byte. We realign the indirect argument if type alignment is bigger
6638   // than ABI alignment.
6639   uint64_t ABIAlign = 4;
6640   uint64_t TyAlign;
6641   if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6642       getABIKind() == ARMABIInfo::AAPCS) {
6643     TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
6644     ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
6645   } else {
6646     TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
6647   }
6648   if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
6649     assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
6650     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
6651                                    /*ByVal=*/true,
6652                                    /*Realign=*/TyAlign > ABIAlign);
6653   }
6654 
6655   // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
6656   // same size and alignment.
6657   if (getTarget().isRenderScriptTarget()) {
6658     return coerceToIntArray(Ty, getContext(), getVMContext());
6659   }
6660 
6661   // Otherwise, pass by coercing to a structure of the appropriate size.
6662   llvm::Type* ElemTy;
6663   unsigned SizeRegs;
6664   // FIXME: Try to match the types of the arguments more accurately where
6665   // we can.
6666   if (TyAlign <= 4) {
6667     ElemTy = llvm::Type::getInt32Ty(getVMContext());
6668     SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
6669   } else {
6670     ElemTy = llvm::Type::getInt64Ty(getVMContext());
6671     SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
6672   }
6673 
6674   return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
6675 }
6676 
6677 static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
6678                               llvm::LLVMContext &VMContext) {
6679   // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
6680   // is called integer-like if its size is less than or equal to one word, and
6681   // the offset of each of its addressable sub-fields is zero.
6682 
6683   uint64_t Size = Context.getTypeSize(Ty);
6684 
6685   // Check that the type fits in a word.
6686   if (Size > 32)
6687     return false;
6688 
6689   // FIXME: Handle vector types!
6690   if (Ty->isVectorType())
6691     return false;
6692 
6693   // Float types are never treated as "integer like".
6694   if (Ty->isRealFloatingType())
6695     return false;
6696 
6697   // If this is a builtin or pointer type then it is ok.
6698   if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
6699     return true;
6700 
6701   // Small complex integer types are "integer like".
6702   if (const ComplexType *CT = Ty->getAs<ComplexType>())
6703     return isIntegerLikeType(CT->getElementType(), Context, VMContext);
6704 
6705   // Single element and zero sized arrays should be allowed, by the definition
6706   // above, but they are not.
6707 
6708   // Otherwise, it must be a record type.
6709   const RecordType *RT = Ty->getAs<RecordType>();
6710   if (!RT) return false;
6711 
6712   // Ignore records with flexible arrays.
6713   const RecordDecl *RD = RT->getDecl();
6714   if (RD->hasFlexibleArrayMember())
6715     return false;
6716 
6717   // Check that all sub-fields are at offset 0, and are themselves "integer
6718   // like".
6719   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
6720 
6721   bool HadField = false;
6722   unsigned idx = 0;
6723   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6724        i != e; ++i, ++idx) {
6725     const FieldDecl *FD = *i;
6726 
6727     // Bit-fields are not addressable, we only need to verify they are "integer
6728     // like". We still have to disallow a subsequent non-bitfield, for example:
6729     //   struct { int : 0; int x }
6730     // is non-integer like according to gcc.
6731     if (FD->isBitField()) {
6732       if (!RD->isUnion())
6733         HadField = true;
6734 
6735       if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6736         return false;
6737 
6738       continue;
6739     }
6740 
6741     // Check if this field is at offset 0.
6742     if (Layout.getFieldOffset(idx) != 0)
6743       return false;
6744 
6745     if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6746       return false;
6747 
6748     // Only allow at most one field in a structure. This doesn't match the
6749     // wording above, but follows gcc in situations with a field following an
6750     // empty structure.
6751     if (!RD->isUnion()) {
6752       if (HadField)
6753         return false;
6754 
6755       HadField = true;
6756     }
6757   }
6758 
6759   return true;
6760 }
6761 
6762 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy, bool isVariadic,
6763                                           unsigned functionCallConv) const {
6764 
6765   // Variadic functions should always marshal to the base standard.
6766   bool IsAAPCS_VFP =
6767       !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ true);
6768 
6769   if (RetTy->isVoidType())
6770     return ABIArgInfo::getIgnore();
6771 
6772   if (const VectorType *VT = RetTy->getAs<VectorType>()) {
6773     // Large vector types should be returned via memory.
6774     if (getContext().getTypeSize(RetTy) > 128)
6775       return getNaturalAlignIndirect(RetTy);
6776     // TODO: FP16/BF16 vectors should be converted to integer vectors
6777     // This check is similar  to isIllegalVectorType - refactor?
6778     if ((!getTarget().hasLegalHalfType() &&
6779         (VT->getElementType()->isFloat16Type() ||
6780          VT->getElementType()->isHalfType())) ||
6781         (IsFloatABISoftFP &&
6782          VT->getElementType()->isBFloat16Type()))
6783       return coerceIllegalVector(RetTy);
6784   }
6785 
6786   if (!isAggregateTypeForABI(RetTy)) {
6787     // Treat an enum type as its underlying type.
6788     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6789       RetTy = EnumTy->getDecl()->getIntegerType();
6790 
6791     if (const auto *EIT = RetTy->getAs<BitIntType>())
6792       if (EIT->getNumBits() > 64)
6793         return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
6794 
6795     return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
6796                                                 : ABIArgInfo::getDirect();
6797   }
6798 
6799   // Are we following APCS?
6800   if (getABIKind() == APCS) {
6801     if (isEmptyRecord(getContext(), RetTy, false))
6802       return ABIArgInfo::getIgnore();
6803 
6804     // Complex types are all returned as packed integers.
6805     //
6806     // FIXME: Consider using 2 x vector types if the back end handles them
6807     // correctly.
6808     if (RetTy->isAnyComplexType())
6809       return ABIArgInfo::getDirect(llvm::IntegerType::get(
6810           getVMContext(), getContext().getTypeSize(RetTy)));
6811 
6812     // Integer like structures are returned in r0.
6813     if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
6814       // Return in the smallest viable integer type.
6815       uint64_t Size = getContext().getTypeSize(RetTy);
6816       if (Size <= 8)
6817         return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6818       if (Size <= 16)
6819         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6820       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6821     }
6822 
6823     // Otherwise return in memory.
6824     return getNaturalAlignIndirect(RetTy);
6825   }
6826 
6827   // Otherwise this is an AAPCS variant.
6828 
6829   if (isEmptyRecord(getContext(), RetTy, true))
6830     return ABIArgInfo::getIgnore();
6831 
6832   // Check for homogeneous aggregates with AAPCS-VFP.
6833   if (IsAAPCS_VFP) {
6834     const Type *Base = nullptr;
6835     uint64_t Members = 0;
6836     if (isHomogeneousAggregate(RetTy, Base, Members))
6837       return classifyHomogeneousAggregate(RetTy, Base, Members);
6838   }
6839 
6840   // Aggregates <= 4 bytes are returned in r0; other aggregates
6841   // are returned indirectly.
6842   uint64_t Size = getContext().getTypeSize(RetTy);
6843   if (Size <= 32) {
6844     // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
6845     // same size and alignment.
6846     if (getTarget().isRenderScriptTarget()) {
6847       return coerceToIntArray(RetTy, getContext(), getVMContext());
6848     }
6849     if (getDataLayout().isBigEndian())
6850       // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
6851       return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6852 
6853     // Return in the smallest viable integer type.
6854     if (Size <= 8)
6855       return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6856     if (Size <= 16)
6857       return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6858     return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6859   } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
6860     llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
6861     llvm::Type *CoerceTy =
6862         llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
6863     return ABIArgInfo::getDirect(CoerceTy);
6864   }
6865 
6866   return getNaturalAlignIndirect(RetTy);
6867 }
6868 
6869 /// isIllegalVector - check whether Ty is an illegal vector type.
6870 bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
6871   if (const VectorType *VT = Ty->getAs<VectorType> ()) {
6872     // On targets that don't support half, fp16 or bfloat, they are expanded
6873     // into float, and we don't want the ABI to depend on whether or not they
6874     // are supported in hardware. Thus return false to coerce vectors of these
6875     // types into integer vectors.
6876     // We do not depend on hasLegalHalfType for bfloat as it is a
6877     // separate IR type.
6878     if ((!getTarget().hasLegalHalfType() &&
6879         (VT->getElementType()->isFloat16Type() ||
6880          VT->getElementType()->isHalfType())) ||
6881         (IsFloatABISoftFP &&
6882          VT->getElementType()->isBFloat16Type()))
6883       return true;
6884     if (isAndroid()) {
6885       // Android shipped using Clang 3.1, which supported a slightly different
6886       // vector ABI. The primary differences were that 3-element vector types
6887       // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
6888       // accepts that legacy behavior for Android only.
6889       // Check whether VT is legal.
6890       unsigned NumElements = VT->getNumElements();
6891       // NumElements should be power of 2 or equal to 3.
6892       if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
6893         return true;
6894     } else {
6895       // Check whether VT is legal.
6896       unsigned NumElements = VT->getNumElements();
6897       uint64_t Size = getContext().getTypeSize(VT);
6898       // NumElements should be power of 2.
6899       if (!llvm::isPowerOf2_32(NumElements))
6900         return true;
6901       // Size should be greater than 32 bits.
6902       return Size <= 32;
6903     }
6904   }
6905   return false;
6906 }
6907 
6908 /// Return true if a type contains any 16-bit floating point vectors
6909 bool ARMABIInfo::containsAnyFP16Vectors(QualType Ty) const {
6910   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
6911     uint64_t NElements = AT->getSize().getZExtValue();
6912     if (NElements == 0)
6913       return false;
6914     return containsAnyFP16Vectors(AT->getElementType());
6915   } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
6916     const RecordDecl *RD = RT->getDecl();
6917 
6918     // If this is a C++ record, check the bases first.
6919     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6920       if (llvm::any_of(CXXRD->bases(), [this](const CXXBaseSpecifier &B) {
6921             return containsAnyFP16Vectors(B.getType());
6922           }))
6923         return true;
6924 
6925     if (llvm::any_of(RD->fields(), [this](FieldDecl *FD) {
6926           return FD && containsAnyFP16Vectors(FD->getType());
6927         }))
6928       return true;
6929 
6930     return false;
6931   } else {
6932     if (const VectorType *VT = Ty->getAs<VectorType>())
6933       return (VT->getElementType()->isFloat16Type() ||
6934               VT->getElementType()->isBFloat16Type() ||
6935               VT->getElementType()->isHalfType());
6936     return false;
6937   }
6938 }
6939 
6940 bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
6941                                            llvm::Type *eltTy,
6942                                            unsigned numElts) const {
6943   if (!llvm::isPowerOf2_32(numElts))
6944     return false;
6945   unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy);
6946   if (size > 64)
6947     return false;
6948   if (vectorSize.getQuantity() != 8 &&
6949       (vectorSize.getQuantity() != 16 || numElts == 1))
6950     return false;
6951   return true;
6952 }
6953 
6954 bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
6955   // Homogeneous aggregates for AAPCS-VFP must have base types of float,
6956   // double, or 64-bit or 128-bit vectors.
6957   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
6958     if (BT->getKind() == BuiltinType::Float ||
6959         BT->getKind() == BuiltinType::Double ||
6960         BT->getKind() == BuiltinType::LongDouble)
6961       return true;
6962   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
6963     unsigned VecSize = getContext().getTypeSize(VT);
6964     if (VecSize == 64 || VecSize == 128)
6965       return true;
6966   }
6967   return false;
6968 }
6969 
6970 bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
6971                                                    uint64_t Members) const {
6972   return Members <= 4;
6973 }
6974 
6975 bool ARMABIInfo::isEffectivelyAAPCS_VFP(unsigned callConvention,
6976                                         bool acceptHalf) const {
6977   // Give precedence to user-specified calling conventions.
6978   if (callConvention != llvm::CallingConv::C)
6979     return (callConvention == llvm::CallingConv::ARM_AAPCS_VFP);
6980   else
6981     return (getABIKind() == AAPCS_VFP) ||
6982            (acceptHalf && (getABIKind() == AAPCS16_VFP));
6983 }
6984 
6985 Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6986                               QualType Ty) const {
6987   CharUnits SlotSize = CharUnits::fromQuantity(4);
6988 
6989   // Empty records are ignored for parameter passing purposes.
6990   if (isEmptyRecord(getContext(), Ty, true)) {
6991     Address Addr =
6992         Address::deprecated(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
6993     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6994     return Addr;
6995   }
6996 
6997   CharUnits TySize = getContext().getTypeSizeInChars(Ty);
6998   CharUnits TyAlignForABI = getContext().getTypeUnadjustedAlignInChars(Ty);
6999 
7000   // Use indirect if size of the illegal vector is bigger than 16 bytes.
7001   bool IsIndirect = false;
7002   const Type *Base = nullptr;
7003   uint64_t Members = 0;
7004   if (TySize > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
7005     IsIndirect = true;
7006 
7007   // ARMv7k passes structs bigger than 16 bytes indirectly, in space
7008   // allocated by the caller.
7009   } else if (TySize > CharUnits::fromQuantity(16) &&
7010              getABIKind() == ARMABIInfo::AAPCS16_VFP &&
7011              !isHomogeneousAggregate(Ty, Base, Members)) {
7012     IsIndirect = true;
7013 
7014   // Otherwise, bound the type's ABI alignment.
7015   // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
7016   // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
7017   // Our callers should be prepared to handle an under-aligned address.
7018   } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
7019              getABIKind() == ARMABIInfo::AAPCS) {
7020     TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
7021     TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
7022   } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
7023     // ARMv7k allows type alignment up to 16 bytes.
7024     TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
7025     TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
7026   } else {
7027     TyAlignForABI = CharUnits::fromQuantity(4);
7028   }
7029 
7030   TypeInfoChars TyInfo(TySize, TyAlignForABI, AlignRequirementKind::None);
7031   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
7032                           SlotSize, /*AllowHigherAlign*/ true);
7033 }
7034 
7035 //===----------------------------------------------------------------------===//
7036 // NVPTX ABI Implementation
7037 //===----------------------------------------------------------------------===//
7038 
7039 namespace {
7040 
7041 class NVPTXTargetCodeGenInfo;
7042 
7043 class NVPTXABIInfo : public ABIInfo {
7044   NVPTXTargetCodeGenInfo &CGInfo;
7045 
7046 public:
7047   NVPTXABIInfo(CodeGenTypes &CGT, NVPTXTargetCodeGenInfo &Info)
7048       : ABIInfo(CGT), CGInfo(Info) {}
7049 
7050   ABIArgInfo classifyReturnType(QualType RetTy) const;
7051   ABIArgInfo classifyArgumentType(QualType Ty) const;
7052 
7053   void computeInfo(CGFunctionInfo &FI) const override;
7054   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7055                     QualType Ty) const override;
7056   bool isUnsupportedType(QualType T) const;
7057   ABIArgInfo coerceToIntArrayWithLimit(QualType Ty, unsigned MaxSize) const;
7058 };
7059 
7060 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
7061 public:
7062   NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
7063       : TargetCodeGenInfo(std::make_unique<NVPTXABIInfo>(CGT, *this)) {}
7064 
7065   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7066                            CodeGen::CodeGenModule &M) const override;
7067   bool shouldEmitStaticExternCAliases() const override;
7068 
7069   llvm::Type *getCUDADeviceBuiltinSurfaceDeviceType() const override {
7070     // On the device side, surface reference is represented as an object handle
7071     // in 64-bit integer.
7072     return llvm::Type::getInt64Ty(getABIInfo().getVMContext());
7073   }
7074 
7075   llvm::Type *getCUDADeviceBuiltinTextureDeviceType() const override {
7076     // On the device side, texture reference is represented as an object handle
7077     // in 64-bit integer.
7078     return llvm::Type::getInt64Ty(getABIInfo().getVMContext());
7079   }
7080 
7081   bool emitCUDADeviceBuiltinSurfaceDeviceCopy(CodeGenFunction &CGF, LValue Dst,
7082                                               LValue Src) const override {
7083     emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src);
7084     return true;
7085   }
7086 
7087   bool emitCUDADeviceBuiltinTextureDeviceCopy(CodeGenFunction &CGF, LValue Dst,
7088                                               LValue Src) const override {
7089     emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src);
7090     return true;
7091   }
7092 
7093 private:
7094   // Adds a NamedMDNode with GV, Name, and Operand as operands, and adds the
7095   // resulting MDNode to the nvvm.annotations MDNode.
7096   static void addNVVMMetadata(llvm::GlobalValue *GV, StringRef Name,
7097                               int Operand);
7098 
7099   static void emitBuiltinSurfTexDeviceCopy(CodeGenFunction &CGF, LValue Dst,
7100                                            LValue Src) {
7101     llvm::Value *Handle = nullptr;
7102     llvm::Constant *C =
7103         llvm::dyn_cast<llvm::Constant>(Src.getAddress(CGF).getPointer());
7104     // Lookup `addrspacecast` through the constant pointer if any.
7105     if (auto *ASC = llvm::dyn_cast_or_null<llvm::AddrSpaceCastOperator>(C))
7106       C = llvm::cast<llvm::Constant>(ASC->getPointerOperand());
7107     if (auto *GV = llvm::dyn_cast_or_null<llvm::GlobalVariable>(C)) {
7108       // Load the handle from the specific global variable using
7109       // `nvvm.texsurf.handle.internal` intrinsic.
7110       Handle = CGF.EmitRuntimeCall(
7111           CGF.CGM.getIntrinsic(llvm::Intrinsic::nvvm_texsurf_handle_internal,
7112                                {GV->getType()}),
7113           {GV}, "texsurf_handle");
7114     } else
7115       Handle = CGF.EmitLoadOfScalar(Src, SourceLocation());
7116     CGF.EmitStoreOfScalar(Handle, Dst);
7117   }
7118 };
7119 
7120 /// Checks if the type is unsupported directly by the current target.
7121 bool NVPTXABIInfo::isUnsupportedType(QualType T) const {
7122   ASTContext &Context = getContext();
7123   if (!Context.getTargetInfo().hasFloat16Type() && T->isFloat16Type())
7124     return true;
7125   if (!Context.getTargetInfo().hasFloat128Type() &&
7126       (T->isFloat128Type() ||
7127        (T->isRealFloatingType() && Context.getTypeSize(T) == 128)))
7128     return true;
7129   if (const auto *EIT = T->getAs<BitIntType>())
7130     return EIT->getNumBits() >
7131            (Context.getTargetInfo().hasInt128Type() ? 128U : 64U);
7132   if (!Context.getTargetInfo().hasInt128Type() && T->isIntegerType() &&
7133       Context.getTypeSize(T) > 64U)
7134     return true;
7135   if (const auto *AT = T->getAsArrayTypeUnsafe())
7136     return isUnsupportedType(AT->getElementType());
7137   const auto *RT = T->getAs<RecordType>();
7138   if (!RT)
7139     return false;
7140   const RecordDecl *RD = RT->getDecl();
7141 
7142   // If this is a C++ record, check the bases first.
7143   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7144     for (const CXXBaseSpecifier &I : CXXRD->bases())
7145       if (isUnsupportedType(I.getType()))
7146         return true;
7147 
7148   for (const FieldDecl *I : RD->fields())
7149     if (isUnsupportedType(I->getType()))
7150       return true;
7151   return false;
7152 }
7153 
7154 /// Coerce the given type into an array with maximum allowed size of elements.
7155 ABIArgInfo NVPTXABIInfo::coerceToIntArrayWithLimit(QualType Ty,
7156                                                    unsigned MaxSize) const {
7157   // Alignment and Size are measured in bits.
7158   const uint64_t Size = getContext().getTypeSize(Ty);
7159   const uint64_t Alignment = getContext().getTypeAlign(Ty);
7160   const unsigned Div = std::min<unsigned>(MaxSize, Alignment);
7161   llvm::Type *IntType = llvm::Type::getIntNTy(getVMContext(), Div);
7162   const uint64_t NumElements = (Size + Div - 1) / Div;
7163   return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
7164 }
7165 
7166 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
7167   if (RetTy->isVoidType())
7168     return ABIArgInfo::getIgnore();
7169 
7170   if (getContext().getLangOpts().OpenMP &&
7171       getContext().getLangOpts().OpenMPIsDevice && isUnsupportedType(RetTy))
7172     return coerceToIntArrayWithLimit(RetTy, 64);
7173 
7174   // note: this is different from default ABI
7175   if (!RetTy->isScalarType())
7176     return ABIArgInfo::getDirect();
7177 
7178   // Treat an enum type as its underlying type.
7179   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7180     RetTy = EnumTy->getDecl()->getIntegerType();
7181 
7182   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
7183                                                : ABIArgInfo::getDirect());
7184 }
7185 
7186 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
7187   // Treat an enum type as its underlying type.
7188   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7189     Ty = EnumTy->getDecl()->getIntegerType();
7190 
7191   // Return aggregates type as indirect by value
7192   if (isAggregateTypeForABI(Ty)) {
7193     // Under CUDA device compilation, tex/surf builtin types are replaced with
7194     // object types and passed directly.
7195     if (getContext().getLangOpts().CUDAIsDevice) {
7196       if (Ty->isCUDADeviceBuiltinSurfaceType())
7197         return ABIArgInfo::getDirect(
7198             CGInfo.getCUDADeviceBuiltinSurfaceDeviceType());
7199       if (Ty->isCUDADeviceBuiltinTextureType())
7200         return ABIArgInfo::getDirect(
7201             CGInfo.getCUDADeviceBuiltinTextureDeviceType());
7202     }
7203     return getNaturalAlignIndirect(Ty, /* byval */ true);
7204   }
7205 
7206   if (const auto *EIT = Ty->getAs<BitIntType>()) {
7207     if ((EIT->getNumBits() > 128) ||
7208         (!getContext().getTargetInfo().hasInt128Type() &&
7209          EIT->getNumBits() > 64))
7210       return getNaturalAlignIndirect(Ty, /* byval */ true);
7211   }
7212 
7213   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
7214                                             : ABIArgInfo::getDirect());
7215 }
7216 
7217 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
7218   if (!getCXXABI().classifyReturnType(FI))
7219     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7220   for (auto &I : FI.arguments())
7221     I.info = classifyArgumentType(I.type);
7222 
7223   // Always honor user-specified calling convention.
7224   if (FI.getCallingConvention() != llvm::CallingConv::C)
7225     return;
7226 
7227   FI.setEffectiveCallingConvention(getRuntimeCC());
7228 }
7229 
7230 Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7231                                 QualType Ty) const {
7232   llvm_unreachable("NVPTX does not support varargs");
7233 }
7234 
7235 void NVPTXTargetCodeGenInfo::setTargetAttributes(
7236     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7237   if (GV->isDeclaration())
7238     return;
7239   const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
7240   if (VD) {
7241     if (M.getLangOpts().CUDA) {
7242       if (VD->getType()->isCUDADeviceBuiltinSurfaceType())
7243         addNVVMMetadata(GV, "surface", 1);
7244       else if (VD->getType()->isCUDADeviceBuiltinTextureType())
7245         addNVVMMetadata(GV, "texture", 1);
7246       return;
7247     }
7248   }
7249 
7250   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7251   if (!FD) return;
7252 
7253   llvm::Function *F = cast<llvm::Function>(GV);
7254 
7255   // Perform special handling in OpenCL mode
7256   if (M.getLangOpts().OpenCL) {
7257     // Use OpenCL function attributes to check for kernel functions
7258     // By default, all functions are device functions
7259     if (FD->hasAttr<OpenCLKernelAttr>()) {
7260       // OpenCL __kernel functions get kernel metadata
7261       // Create !{<func-ref>, metadata !"kernel", i32 1} node
7262       addNVVMMetadata(F, "kernel", 1);
7263       // And kernel functions are not subject to inlining
7264       F->addFnAttr(llvm::Attribute::NoInline);
7265     }
7266   }
7267 
7268   // Perform special handling in CUDA mode.
7269   if (M.getLangOpts().CUDA) {
7270     // CUDA __global__ functions get a kernel metadata entry.  Since
7271     // __global__ functions cannot be called from the device, we do not
7272     // need to set the noinline attribute.
7273     if (FD->hasAttr<CUDAGlobalAttr>()) {
7274       // Create !{<func-ref>, metadata !"kernel", i32 1} node
7275       addNVVMMetadata(F, "kernel", 1);
7276     }
7277     if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
7278       // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
7279       llvm::APSInt MaxThreads(32);
7280       MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
7281       if (MaxThreads > 0)
7282         addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
7283 
7284       // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
7285       // not specified in __launch_bounds__ or if the user specified a 0 value,
7286       // we don't have to add a PTX directive.
7287       if (Attr->getMinBlocks()) {
7288         llvm::APSInt MinBlocks(32);
7289         MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
7290         if (MinBlocks > 0)
7291           // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
7292           addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
7293       }
7294     }
7295   }
7296 }
7297 
7298 void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::GlobalValue *GV,
7299                                              StringRef Name, int Operand) {
7300   llvm::Module *M = GV->getParent();
7301   llvm::LLVMContext &Ctx = M->getContext();
7302 
7303   // Get "nvvm.annotations" metadata node
7304   llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
7305 
7306   llvm::Metadata *MDVals[] = {
7307       llvm::ConstantAsMetadata::get(GV), llvm::MDString::get(Ctx, Name),
7308       llvm::ConstantAsMetadata::get(
7309           llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
7310   // Append metadata to nvvm.annotations
7311   MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
7312 }
7313 
7314 bool NVPTXTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
7315   return false;
7316 }
7317 }
7318 
7319 //===----------------------------------------------------------------------===//
7320 // SystemZ ABI Implementation
7321 //===----------------------------------------------------------------------===//
7322 
7323 namespace {
7324 
7325 class SystemZABIInfo : public SwiftABIInfo {
7326   bool HasVector;
7327   bool IsSoftFloatABI;
7328 
7329 public:
7330   SystemZABIInfo(CodeGenTypes &CGT, bool HV, bool SF)
7331     : SwiftABIInfo(CGT), HasVector(HV), IsSoftFloatABI(SF) {}
7332 
7333   bool isPromotableIntegerTypeForABI(QualType Ty) const;
7334   bool isCompoundType(QualType Ty) const;
7335   bool isVectorArgumentType(QualType Ty) const;
7336   bool isFPArgumentType(QualType Ty) const;
7337   QualType GetSingleElementType(QualType Ty) const;
7338 
7339   ABIArgInfo classifyReturnType(QualType RetTy) const;
7340   ABIArgInfo classifyArgumentType(QualType ArgTy) const;
7341 
7342   void computeInfo(CGFunctionInfo &FI) const override {
7343     if (!getCXXABI().classifyReturnType(FI))
7344       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7345     for (auto &I : FI.arguments())
7346       I.info = classifyArgumentType(I.type);
7347   }
7348 
7349   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7350                     QualType Ty) const override;
7351 
7352   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
7353                                     bool asReturnValue) const override {
7354     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
7355   }
7356   bool isSwiftErrorInRegister() const override {
7357     return false;
7358   }
7359 };
7360 
7361 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
7362 public:
7363   SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector, bool SoftFloatABI)
7364       : TargetCodeGenInfo(
7365             std::make_unique<SystemZABIInfo>(CGT, HasVector, SoftFloatABI)) {}
7366 
7367   llvm::Value *testFPKind(llvm::Value *V, unsigned BuiltinID,
7368                           CGBuilderTy &Builder,
7369                           CodeGenModule &CGM) const override {
7370     assert(V->getType()->isFloatingPointTy() && "V should have an FP type.");
7371     // Only use TDC in constrained FP mode.
7372     if (!Builder.getIsFPConstrained())
7373       return nullptr;
7374 
7375     llvm::Type *Ty = V->getType();
7376     if (Ty->isFloatTy() || Ty->isDoubleTy() || Ty->isFP128Ty()) {
7377       llvm::Module &M = CGM.getModule();
7378       auto &Ctx = M.getContext();
7379       llvm::Function *TDCFunc =
7380           llvm::Intrinsic::getDeclaration(&M, llvm::Intrinsic::s390_tdc, Ty);
7381       unsigned TDCBits = 0;
7382       switch (BuiltinID) {
7383       case Builtin::BI__builtin_isnan:
7384         TDCBits = 0xf;
7385         break;
7386       case Builtin::BIfinite:
7387       case Builtin::BI__finite:
7388       case Builtin::BIfinitef:
7389       case Builtin::BI__finitef:
7390       case Builtin::BIfinitel:
7391       case Builtin::BI__finitel:
7392       case Builtin::BI__builtin_isfinite:
7393         TDCBits = 0xfc0;
7394         break;
7395       case Builtin::BI__builtin_isinf:
7396         TDCBits = 0x30;
7397         break;
7398       default:
7399         break;
7400       }
7401       if (TDCBits)
7402         return Builder.CreateCall(
7403             TDCFunc,
7404             {V, llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), TDCBits)});
7405     }
7406     return nullptr;
7407   }
7408 };
7409 }
7410 
7411 bool SystemZABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const {
7412   // Treat an enum type as its underlying type.
7413   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7414     Ty = EnumTy->getDecl()->getIntegerType();
7415 
7416   // Promotable integer types are required to be promoted by the ABI.
7417   if (ABIInfo::isPromotableIntegerTypeForABI(Ty))
7418     return true;
7419 
7420   if (const auto *EIT = Ty->getAs<BitIntType>())
7421     if (EIT->getNumBits() < 64)
7422       return true;
7423 
7424   // 32-bit values must also be promoted.
7425   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
7426     switch (BT->getKind()) {
7427     case BuiltinType::Int:
7428     case BuiltinType::UInt:
7429       return true;
7430     default:
7431       return false;
7432     }
7433   return false;
7434 }
7435 
7436 bool SystemZABIInfo::isCompoundType(QualType Ty) const {
7437   return (Ty->isAnyComplexType() ||
7438           Ty->isVectorType() ||
7439           isAggregateTypeForABI(Ty));
7440 }
7441 
7442 bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
7443   return (HasVector &&
7444           Ty->isVectorType() &&
7445           getContext().getTypeSize(Ty) <= 128);
7446 }
7447 
7448 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
7449   if (IsSoftFloatABI)
7450     return false;
7451 
7452   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
7453     switch (BT->getKind()) {
7454     case BuiltinType::Float:
7455     case BuiltinType::Double:
7456       return true;
7457     default:
7458       return false;
7459     }
7460 
7461   return false;
7462 }
7463 
7464 QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
7465   const RecordType *RT = Ty->getAs<RecordType>();
7466 
7467   if (RT && RT->isStructureOrClassType()) {
7468     const RecordDecl *RD = RT->getDecl();
7469     QualType Found;
7470 
7471     // If this is a C++ record, check the bases first.
7472     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7473       for (const auto &I : CXXRD->bases()) {
7474         QualType Base = I.getType();
7475 
7476         // Empty bases don't affect things either way.
7477         if (isEmptyRecord(getContext(), Base, true))
7478           continue;
7479 
7480         if (!Found.isNull())
7481           return Ty;
7482         Found = GetSingleElementType(Base);
7483       }
7484 
7485     // Check the fields.
7486     for (const auto *FD : RD->fields()) {
7487       // For compatibility with GCC, ignore empty bitfields in C++ mode.
7488       // Unlike isSingleElementStruct(), empty structure and array fields
7489       // do count.  So do anonymous bitfields that aren't zero-sized.
7490       if (getContext().getLangOpts().CPlusPlus &&
7491           FD->isZeroLengthBitField(getContext()))
7492         continue;
7493       // Like isSingleElementStruct(), ignore C++20 empty data members.
7494       if (FD->hasAttr<NoUniqueAddressAttr>() &&
7495           isEmptyRecord(getContext(), FD->getType(), true))
7496         continue;
7497 
7498       // Unlike isSingleElementStruct(), arrays do not count.
7499       // Nested structures still do though.
7500       if (!Found.isNull())
7501         return Ty;
7502       Found = GetSingleElementType(FD->getType());
7503     }
7504 
7505     // Unlike isSingleElementStruct(), trailing padding is allowed.
7506     // An 8-byte aligned struct s { float f; } is passed as a double.
7507     if (!Found.isNull())
7508       return Found;
7509   }
7510 
7511   return Ty;
7512 }
7513 
7514 Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7515                                   QualType Ty) const {
7516   // Assume that va_list type is correct; should be pointer to LLVM type:
7517   // struct {
7518   //   i64 __gpr;
7519   //   i64 __fpr;
7520   //   i8 *__overflow_arg_area;
7521   //   i8 *__reg_save_area;
7522   // };
7523 
7524   // Every non-vector argument occupies 8 bytes and is passed by preference
7525   // in either GPRs or FPRs.  Vector arguments occupy 8 or 16 bytes and are
7526   // always passed on the stack.
7527   Ty = getContext().getCanonicalType(Ty);
7528   auto TyInfo = getContext().getTypeInfoInChars(Ty);
7529   llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
7530   llvm::Type *DirectTy = ArgTy;
7531   ABIArgInfo AI = classifyArgumentType(Ty);
7532   bool IsIndirect = AI.isIndirect();
7533   bool InFPRs = false;
7534   bool IsVector = false;
7535   CharUnits UnpaddedSize;
7536   CharUnits DirectAlign;
7537   if (IsIndirect) {
7538     DirectTy = llvm::PointerType::getUnqual(DirectTy);
7539     UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
7540   } else {
7541     if (AI.getCoerceToType())
7542       ArgTy = AI.getCoerceToType();
7543     InFPRs = (!IsSoftFloatABI && (ArgTy->isFloatTy() || ArgTy->isDoubleTy()));
7544     IsVector = ArgTy->isVectorTy();
7545     UnpaddedSize = TyInfo.Width;
7546     DirectAlign = TyInfo.Align;
7547   }
7548   CharUnits PaddedSize = CharUnits::fromQuantity(8);
7549   if (IsVector && UnpaddedSize > PaddedSize)
7550     PaddedSize = CharUnits::fromQuantity(16);
7551   assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
7552 
7553   CharUnits Padding = (PaddedSize - UnpaddedSize);
7554 
7555   llvm::Type *IndexTy = CGF.Int64Ty;
7556   llvm::Value *PaddedSizeV =
7557     llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
7558 
7559   if (IsVector) {
7560     // Work out the address of a vector argument on the stack.
7561     // Vector arguments are always passed in the high bits of a
7562     // single (8 byte) or double (16 byte) stack slot.
7563     Address OverflowArgAreaPtr =
7564         CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
7565     Address OverflowArgArea = Address::deprecated(
7566         CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
7567         TyInfo.Align);
7568     Address MemAddr =
7569         CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
7570 
7571     // Update overflow_arg_area_ptr pointer
7572     llvm::Value *NewOverflowArgArea = CGF.Builder.CreateGEP(
7573         OverflowArgArea.getElementType(), OverflowArgArea.getPointer(),
7574         PaddedSizeV, "overflow_arg_area");
7575     CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
7576 
7577     return MemAddr;
7578   }
7579 
7580   assert(PaddedSize.getQuantity() == 8);
7581 
7582   unsigned MaxRegs, RegCountField, RegSaveIndex;
7583   CharUnits RegPadding;
7584   if (InFPRs) {
7585     MaxRegs = 4; // Maximum of 4 FPR arguments
7586     RegCountField = 1; // __fpr
7587     RegSaveIndex = 16; // save offset for f0
7588     RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
7589   } else {
7590     MaxRegs = 5; // Maximum of 5 GPR arguments
7591     RegCountField = 0; // __gpr
7592     RegSaveIndex = 2; // save offset for r2
7593     RegPadding = Padding; // values are passed in the low bits of a GPR
7594   }
7595 
7596   Address RegCountPtr =
7597       CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
7598   llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
7599   llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
7600   llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
7601                                                  "fits_in_regs");
7602 
7603   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
7604   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
7605   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
7606   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
7607 
7608   // Emit code to load the value if it was passed in registers.
7609   CGF.EmitBlock(InRegBlock);
7610 
7611   // Work out the address of an argument register.
7612   llvm::Value *ScaledRegCount =
7613     CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
7614   llvm::Value *RegBase =
7615     llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
7616                                       + RegPadding.getQuantity());
7617   llvm::Value *RegOffset =
7618     CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
7619   Address RegSaveAreaPtr =
7620       CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
7621   llvm::Value *RegSaveArea =
7622       CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
7623   Address RawRegAddr(
7624       CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, RegOffset, "raw_reg_addr"),
7625       CGF.Int8Ty, PaddedSize);
7626   Address RegAddr =
7627       CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
7628 
7629   // Update the register count
7630   llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
7631   llvm::Value *NewRegCount =
7632     CGF.Builder.CreateAdd(RegCount, One, "reg_count");
7633   CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
7634   CGF.EmitBranch(ContBlock);
7635 
7636   // Emit code to load the value if it was passed in memory.
7637   CGF.EmitBlock(InMemBlock);
7638 
7639   // Work out the address of a stack argument.
7640   Address OverflowArgAreaPtr =
7641       CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
7642   Address OverflowArgArea = Address::deprecated(
7643       CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
7644       PaddedSize);
7645   Address RawMemAddr =
7646       CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
7647   Address MemAddr =
7648     CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
7649 
7650   // Update overflow_arg_area_ptr pointer
7651   llvm::Value *NewOverflowArgArea =
7652     CGF.Builder.CreateGEP(OverflowArgArea.getElementType(),
7653                           OverflowArgArea.getPointer(), PaddedSizeV,
7654                           "overflow_arg_area");
7655   CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
7656   CGF.EmitBranch(ContBlock);
7657 
7658   // Return the appropriate result.
7659   CGF.EmitBlock(ContBlock);
7660   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
7661                                  "va_arg.addr");
7662 
7663   if (IsIndirect)
7664     ResAddr = Address::deprecated(
7665         CGF.Builder.CreateLoad(ResAddr, "indirect_arg"), TyInfo.Align);
7666 
7667   return ResAddr;
7668 }
7669 
7670 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
7671   if (RetTy->isVoidType())
7672     return ABIArgInfo::getIgnore();
7673   if (isVectorArgumentType(RetTy))
7674     return ABIArgInfo::getDirect();
7675   if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
7676     return getNaturalAlignIndirect(RetTy);
7677   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
7678                                                : ABIArgInfo::getDirect());
7679 }
7680 
7681 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
7682   // Handle the generic C++ ABI.
7683   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7684     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7685 
7686   // Integers and enums are extended to full register width.
7687   if (isPromotableIntegerTypeForABI(Ty))
7688     return ABIArgInfo::getExtend(Ty);
7689 
7690   // Handle vector types and vector-like structure types.  Note that
7691   // as opposed to float-like structure types, we do not allow any
7692   // padding for vector-like structures, so verify the sizes match.
7693   uint64_t Size = getContext().getTypeSize(Ty);
7694   QualType SingleElementTy = GetSingleElementType(Ty);
7695   if (isVectorArgumentType(SingleElementTy) &&
7696       getContext().getTypeSize(SingleElementTy) == Size)
7697     return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
7698 
7699   // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
7700   if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
7701     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7702 
7703   // Handle small structures.
7704   if (const RecordType *RT = Ty->getAs<RecordType>()) {
7705     // Structures with flexible arrays have variable length, so really
7706     // fail the size test above.
7707     const RecordDecl *RD = RT->getDecl();
7708     if (RD->hasFlexibleArrayMember())
7709       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7710 
7711     // The structure is passed as an unextended integer, a float, or a double.
7712     llvm::Type *PassTy;
7713     if (isFPArgumentType(SingleElementTy)) {
7714       assert(Size == 32 || Size == 64);
7715       if (Size == 32)
7716         PassTy = llvm::Type::getFloatTy(getVMContext());
7717       else
7718         PassTy = llvm::Type::getDoubleTy(getVMContext());
7719     } else
7720       PassTy = llvm::IntegerType::get(getVMContext(), Size);
7721     return ABIArgInfo::getDirect(PassTy);
7722   }
7723 
7724   // Non-structure compounds are passed indirectly.
7725   if (isCompoundType(Ty))
7726     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
7727 
7728   return ABIArgInfo::getDirect(nullptr);
7729 }
7730 
7731 //===----------------------------------------------------------------------===//
7732 // MSP430 ABI Implementation
7733 //===----------------------------------------------------------------------===//
7734 
7735 namespace {
7736 
7737 class MSP430ABIInfo : public DefaultABIInfo {
7738   static ABIArgInfo complexArgInfo() {
7739     ABIArgInfo Info = ABIArgInfo::getDirect();
7740     Info.setCanBeFlattened(false);
7741     return Info;
7742   }
7743 
7744 public:
7745   MSP430ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7746 
7747   ABIArgInfo classifyReturnType(QualType RetTy) const {
7748     if (RetTy->isAnyComplexType())
7749       return complexArgInfo();
7750 
7751     return DefaultABIInfo::classifyReturnType(RetTy);
7752   }
7753 
7754   ABIArgInfo classifyArgumentType(QualType RetTy) const {
7755     if (RetTy->isAnyComplexType())
7756       return complexArgInfo();
7757 
7758     return DefaultABIInfo::classifyArgumentType(RetTy);
7759   }
7760 
7761   // Just copy the original implementations because
7762   // DefaultABIInfo::classify{Return,Argument}Type() are not virtual
7763   void computeInfo(CGFunctionInfo &FI) const override {
7764     if (!getCXXABI().classifyReturnType(FI))
7765       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7766     for (auto &I : FI.arguments())
7767       I.info = classifyArgumentType(I.type);
7768   }
7769 
7770   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7771                     QualType Ty) const override {
7772     return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
7773   }
7774 };
7775 
7776 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
7777 public:
7778   MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
7779       : TargetCodeGenInfo(std::make_unique<MSP430ABIInfo>(CGT)) {}
7780   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7781                            CodeGen::CodeGenModule &M) const override;
7782 };
7783 
7784 }
7785 
7786 void MSP430TargetCodeGenInfo::setTargetAttributes(
7787     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7788   if (GV->isDeclaration())
7789     return;
7790   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
7791     const auto *InterruptAttr = FD->getAttr<MSP430InterruptAttr>();
7792     if (!InterruptAttr)
7793       return;
7794 
7795     // Handle 'interrupt' attribute:
7796     llvm::Function *F = cast<llvm::Function>(GV);
7797 
7798     // Step 1: Set ISR calling convention.
7799     F->setCallingConv(llvm::CallingConv::MSP430_INTR);
7800 
7801     // Step 2: Add attributes goodness.
7802     F->addFnAttr(llvm::Attribute::NoInline);
7803     F->addFnAttr("interrupt", llvm::utostr(InterruptAttr->getNumber()));
7804   }
7805 }
7806 
7807 //===----------------------------------------------------------------------===//
7808 // MIPS ABI Implementation.  This works for both little-endian and
7809 // big-endian variants.
7810 //===----------------------------------------------------------------------===//
7811 
7812 namespace {
7813 class MipsABIInfo : public ABIInfo {
7814   bool IsO32;
7815   unsigned MinABIStackAlignInBytes, StackAlignInBytes;
7816   void CoerceToIntArgs(uint64_t TySize,
7817                        SmallVectorImpl<llvm::Type *> &ArgList) const;
7818   llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
7819   llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
7820   llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
7821 public:
7822   MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
7823     ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
7824     StackAlignInBytes(IsO32 ? 8 : 16) {}
7825 
7826   ABIArgInfo classifyReturnType(QualType RetTy) const;
7827   ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
7828   void computeInfo(CGFunctionInfo &FI) const override;
7829   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7830                     QualType Ty) const override;
7831   ABIArgInfo extendType(QualType Ty) const;
7832 };
7833 
7834 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
7835   unsigned SizeOfUnwindException;
7836 public:
7837   MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
7838       : TargetCodeGenInfo(std::make_unique<MipsABIInfo>(CGT, IsO32)),
7839         SizeOfUnwindException(IsO32 ? 24 : 32) {}
7840 
7841   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
7842     return 29;
7843   }
7844 
7845   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7846                            CodeGen::CodeGenModule &CGM) const override {
7847     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7848     if (!FD) return;
7849     llvm::Function *Fn = cast<llvm::Function>(GV);
7850 
7851     if (FD->hasAttr<MipsLongCallAttr>())
7852       Fn->addFnAttr("long-call");
7853     else if (FD->hasAttr<MipsShortCallAttr>())
7854       Fn->addFnAttr("short-call");
7855 
7856     // Other attributes do not have a meaning for declarations.
7857     if (GV->isDeclaration())
7858       return;
7859 
7860     if (FD->hasAttr<Mips16Attr>()) {
7861       Fn->addFnAttr("mips16");
7862     }
7863     else if (FD->hasAttr<NoMips16Attr>()) {
7864       Fn->addFnAttr("nomips16");
7865     }
7866 
7867     if (FD->hasAttr<MicroMipsAttr>())
7868       Fn->addFnAttr("micromips");
7869     else if (FD->hasAttr<NoMicroMipsAttr>())
7870       Fn->addFnAttr("nomicromips");
7871 
7872     const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
7873     if (!Attr)
7874       return;
7875 
7876     const char *Kind;
7877     switch (Attr->getInterrupt()) {
7878     case MipsInterruptAttr::eic:     Kind = "eic"; break;
7879     case MipsInterruptAttr::sw0:     Kind = "sw0"; break;
7880     case MipsInterruptAttr::sw1:     Kind = "sw1"; break;
7881     case MipsInterruptAttr::hw0:     Kind = "hw0"; break;
7882     case MipsInterruptAttr::hw1:     Kind = "hw1"; break;
7883     case MipsInterruptAttr::hw2:     Kind = "hw2"; break;
7884     case MipsInterruptAttr::hw3:     Kind = "hw3"; break;
7885     case MipsInterruptAttr::hw4:     Kind = "hw4"; break;
7886     case MipsInterruptAttr::hw5:     Kind = "hw5"; break;
7887     }
7888 
7889     Fn->addFnAttr("interrupt", Kind);
7890 
7891   }
7892 
7893   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7894                                llvm::Value *Address) const override;
7895 
7896   unsigned getSizeOfUnwindException() const override {
7897     return SizeOfUnwindException;
7898   }
7899 };
7900 }
7901 
7902 void MipsABIInfo::CoerceToIntArgs(
7903     uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
7904   llvm::IntegerType *IntTy =
7905     llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
7906 
7907   // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
7908   for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
7909     ArgList.push_back(IntTy);
7910 
7911   // If necessary, add one more integer type to ArgList.
7912   unsigned R = TySize % (MinABIStackAlignInBytes * 8);
7913 
7914   if (R)
7915     ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
7916 }
7917 
7918 // In N32/64, an aligned double precision floating point field is passed in
7919 // a register.
7920 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
7921   SmallVector<llvm::Type*, 8> ArgList, IntArgList;
7922 
7923   if (IsO32) {
7924     CoerceToIntArgs(TySize, ArgList);
7925     return llvm::StructType::get(getVMContext(), ArgList);
7926   }
7927 
7928   if (Ty->isComplexType())
7929     return CGT.ConvertType(Ty);
7930 
7931   const RecordType *RT = Ty->getAs<RecordType>();
7932 
7933   // Unions/vectors are passed in integer registers.
7934   if (!RT || !RT->isStructureOrClassType()) {
7935     CoerceToIntArgs(TySize, ArgList);
7936     return llvm::StructType::get(getVMContext(), ArgList);
7937   }
7938 
7939   const RecordDecl *RD = RT->getDecl();
7940   const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
7941   assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
7942 
7943   uint64_t LastOffset = 0;
7944   unsigned idx = 0;
7945   llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
7946 
7947   // Iterate over fields in the struct/class and check if there are any aligned
7948   // double fields.
7949   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
7950        i != e; ++i, ++idx) {
7951     const QualType Ty = i->getType();
7952     const BuiltinType *BT = Ty->getAs<BuiltinType>();
7953 
7954     if (!BT || BT->getKind() != BuiltinType::Double)
7955       continue;
7956 
7957     uint64_t Offset = Layout.getFieldOffset(idx);
7958     if (Offset % 64) // Ignore doubles that are not aligned.
7959       continue;
7960 
7961     // Add ((Offset - LastOffset) / 64) args of type i64.
7962     for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
7963       ArgList.push_back(I64);
7964 
7965     // Add double type.
7966     ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
7967     LastOffset = Offset + 64;
7968   }
7969 
7970   CoerceToIntArgs(TySize - LastOffset, IntArgList);
7971   ArgList.append(IntArgList.begin(), IntArgList.end());
7972 
7973   return llvm::StructType::get(getVMContext(), ArgList);
7974 }
7975 
7976 llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
7977                                         uint64_t Offset) const {
7978   if (OrigOffset + MinABIStackAlignInBytes > Offset)
7979     return nullptr;
7980 
7981   return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
7982 }
7983 
7984 ABIArgInfo
7985 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
7986   Ty = useFirstFieldIfTransparentUnion(Ty);
7987 
7988   uint64_t OrigOffset = Offset;
7989   uint64_t TySize = getContext().getTypeSize(Ty);
7990   uint64_t Align = getContext().getTypeAlign(Ty) / 8;
7991 
7992   Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
7993                    (uint64_t)StackAlignInBytes);
7994   unsigned CurrOffset = llvm::alignTo(Offset, Align);
7995   Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
7996 
7997   if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
7998     // Ignore empty aggregates.
7999     if (TySize == 0)
8000       return ABIArgInfo::getIgnore();
8001 
8002     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
8003       Offset = OrigOffset + MinABIStackAlignInBytes;
8004       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
8005     }
8006 
8007     // If we have reached here, aggregates are passed directly by coercing to
8008     // another structure type. Padding is inserted if the offset of the
8009     // aggregate is unaligned.
8010     ABIArgInfo ArgInfo =
8011         ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
8012                               getPaddingType(OrigOffset, CurrOffset));
8013     ArgInfo.setInReg(true);
8014     return ArgInfo;
8015   }
8016 
8017   // Treat an enum type as its underlying type.
8018   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
8019     Ty = EnumTy->getDecl()->getIntegerType();
8020 
8021   // Make sure we pass indirectly things that are too large.
8022   if (const auto *EIT = Ty->getAs<BitIntType>())
8023     if (EIT->getNumBits() > 128 ||
8024         (EIT->getNumBits() > 64 &&
8025          !getContext().getTargetInfo().hasInt128Type()))
8026       return getNaturalAlignIndirect(Ty);
8027 
8028   // All integral types are promoted to the GPR width.
8029   if (Ty->isIntegralOrEnumerationType())
8030     return extendType(Ty);
8031 
8032   return ABIArgInfo::getDirect(
8033       nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
8034 }
8035 
8036 llvm::Type*
8037 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
8038   const RecordType *RT = RetTy->getAs<RecordType>();
8039   SmallVector<llvm::Type*, 8> RTList;
8040 
8041   if (RT && RT->isStructureOrClassType()) {
8042     const RecordDecl *RD = RT->getDecl();
8043     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
8044     unsigned FieldCnt = Layout.getFieldCount();
8045 
8046     // N32/64 returns struct/classes in floating point registers if the
8047     // following conditions are met:
8048     // 1. The size of the struct/class is no larger than 128-bit.
8049     // 2. The struct/class has one or two fields all of which are floating
8050     //    point types.
8051     // 3. The offset of the first field is zero (this follows what gcc does).
8052     //
8053     // Any other composite results are returned in integer registers.
8054     //
8055     if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
8056       RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
8057       for (; b != e; ++b) {
8058         const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
8059 
8060         if (!BT || !BT->isFloatingPoint())
8061           break;
8062 
8063         RTList.push_back(CGT.ConvertType(b->getType()));
8064       }
8065 
8066       if (b == e)
8067         return llvm::StructType::get(getVMContext(), RTList,
8068                                      RD->hasAttr<PackedAttr>());
8069 
8070       RTList.clear();
8071     }
8072   }
8073 
8074   CoerceToIntArgs(Size, RTList);
8075   return llvm::StructType::get(getVMContext(), RTList);
8076 }
8077 
8078 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
8079   uint64_t Size = getContext().getTypeSize(RetTy);
8080 
8081   if (RetTy->isVoidType())
8082     return ABIArgInfo::getIgnore();
8083 
8084   // O32 doesn't treat zero-sized structs differently from other structs.
8085   // However, N32/N64 ignores zero sized return values.
8086   if (!IsO32 && Size == 0)
8087     return ABIArgInfo::getIgnore();
8088 
8089   if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
8090     if (Size <= 128) {
8091       if (RetTy->isAnyComplexType())
8092         return ABIArgInfo::getDirect();
8093 
8094       // O32 returns integer vectors in registers and N32/N64 returns all small
8095       // aggregates in registers.
8096       if (!IsO32 ||
8097           (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
8098         ABIArgInfo ArgInfo =
8099             ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
8100         ArgInfo.setInReg(true);
8101         return ArgInfo;
8102       }
8103     }
8104 
8105     return getNaturalAlignIndirect(RetTy);
8106   }
8107 
8108   // Treat an enum type as its underlying type.
8109   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
8110     RetTy = EnumTy->getDecl()->getIntegerType();
8111 
8112   // Make sure we pass indirectly things that are too large.
8113   if (const auto *EIT = RetTy->getAs<BitIntType>())
8114     if (EIT->getNumBits() > 128 ||
8115         (EIT->getNumBits() > 64 &&
8116          !getContext().getTargetInfo().hasInt128Type()))
8117       return getNaturalAlignIndirect(RetTy);
8118 
8119   if (isPromotableIntegerTypeForABI(RetTy))
8120     return ABIArgInfo::getExtend(RetTy);
8121 
8122   if ((RetTy->isUnsignedIntegerOrEnumerationType() ||
8123       RetTy->isSignedIntegerOrEnumerationType()) && Size == 32 && !IsO32)
8124     return ABIArgInfo::getSignExtend(RetTy);
8125 
8126   return ABIArgInfo::getDirect();
8127 }
8128 
8129 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
8130   ABIArgInfo &RetInfo = FI.getReturnInfo();
8131   if (!getCXXABI().classifyReturnType(FI))
8132     RetInfo = classifyReturnType(FI.getReturnType());
8133 
8134   // Check if a pointer to an aggregate is passed as a hidden argument.
8135   uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
8136 
8137   for (auto &I : FI.arguments())
8138     I.info = classifyArgumentType(I.type, Offset);
8139 }
8140 
8141 Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8142                                QualType OrigTy) const {
8143   QualType Ty = OrigTy;
8144 
8145   // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
8146   // Pointers are also promoted in the same way but this only matters for N32.
8147   unsigned SlotSizeInBits = IsO32 ? 32 : 64;
8148   unsigned PtrWidth = getTarget().getPointerWidth(0);
8149   bool DidPromote = false;
8150   if ((Ty->isIntegerType() &&
8151           getContext().getIntWidth(Ty) < SlotSizeInBits) ||
8152       (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
8153     DidPromote = true;
8154     Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
8155                                             Ty->isSignedIntegerType());
8156   }
8157 
8158   auto TyInfo = getContext().getTypeInfoInChars(Ty);
8159 
8160   // The alignment of things in the argument area is never larger than
8161   // StackAlignInBytes.
8162   TyInfo.Align =
8163     std::min(TyInfo.Align, CharUnits::fromQuantity(StackAlignInBytes));
8164 
8165   // MinABIStackAlignInBytes is the size of argument slots on the stack.
8166   CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
8167 
8168   Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
8169                           TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
8170 
8171 
8172   // If there was a promotion, "unpromote" into a temporary.
8173   // TODO: can we just use a pointer into a subset of the original slot?
8174   if (DidPromote) {
8175     Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
8176     llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
8177 
8178     // Truncate down to the right width.
8179     llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
8180                                                  : CGF.IntPtrTy);
8181     llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
8182     if (OrigTy->isPointerType())
8183       V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
8184 
8185     CGF.Builder.CreateStore(V, Temp);
8186     Addr = Temp;
8187   }
8188 
8189   return Addr;
8190 }
8191 
8192 ABIArgInfo MipsABIInfo::extendType(QualType Ty) const {
8193   int TySize = getContext().getTypeSize(Ty);
8194 
8195   // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
8196   if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
8197     return ABIArgInfo::getSignExtend(Ty);
8198 
8199   return ABIArgInfo::getExtend(Ty);
8200 }
8201 
8202 bool
8203 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
8204                                                llvm::Value *Address) const {
8205   // This information comes from gcc's implementation, which seems to
8206   // as canonical as it gets.
8207 
8208   // Everything on MIPS is 4 bytes.  Double-precision FP registers
8209   // are aliased to pairs of single-precision FP registers.
8210   llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
8211 
8212   // 0-31 are the general purpose registers, $0 - $31.
8213   // 32-63 are the floating-point registers, $f0 - $f31.
8214   // 64 and 65 are the multiply/divide registers, $hi and $lo.
8215   // 66 is the (notional, I think) register for signal-handler return.
8216   AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
8217 
8218   // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
8219   // They are one bit wide and ignored here.
8220 
8221   // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
8222   // (coprocessor 1 is the FP unit)
8223   // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
8224   // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
8225   // 176-181 are the DSP accumulator registers.
8226   AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
8227   return false;
8228 }
8229 
8230 //===----------------------------------------------------------------------===//
8231 // M68k ABI Implementation
8232 //===----------------------------------------------------------------------===//
8233 
8234 namespace {
8235 
8236 class M68kTargetCodeGenInfo : public TargetCodeGenInfo {
8237 public:
8238   M68kTargetCodeGenInfo(CodeGenTypes &CGT)
8239       : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {}
8240   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8241                            CodeGen::CodeGenModule &M) const override;
8242 };
8243 
8244 } // namespace
8245 
8246 void M68kTargetCodeGenInfo::setTargetAttributes(
8247     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
8248   if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
8249     if (const auto *attr = FD->getAttr<M68kInterruptAttr>()) {
8250       // Handle 'interrupt' attribute:
8251       llvm::Function *F = cast<llvm::Function>(GV);
8252 
8253       // Step 1: Set ISR calling convention.
8254       F->setCallingConv(llvm::CallingConv::M68k_INTR);
8255 
8256       // Step 2: Add attributes goodness.
8257       F->addFnAttr(llvm::Attribute::NoInline);
8258 
8259       // Step 3: Emit ISR vector alias.
8260       unsigned Num = attr->getNumber() / 2;
8261       llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
8262                                 "__isr_" + Twine(Num), F);
8263     }
8264   }
8265 }
8266 
8267 //===----------------------------------------------------------------------===//
8268 // AVR ABI Implementation. Documented at
8269 // https://gcc.gnu.org/wiki/avr-gcc#Calling_Convention
8270 // https://gcc.gnu.org/wiki/avr-gcc#Reduced_Tiny
8271 //===----------------------------------------------------------------------===//
8272 
8273 namespace {
8274 class AVRABIInfo : public DefaultABIInfo {
8275 public:
8276   AVRABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8277 
8278   ABIArgInfo classifyReturnType(QualType Ty) const {
8279     // A return struct with size less than or equal to 8 bytes is returned
8280     // directly via registers R18-R25.
8281     if (isAggregateTypeForABI(Ty) && getContext().getTypeSize(Ty) <= 64)
8282       return ABIArgInfo::getDirect();
8283     else
8284       return DefaultABIInfo::classifyReturnType(Ty);
8285   }
8286 
8287   // Just copy the original implementation of DefaultABIInfo::computeInfo(),
8288   // since DefaultABIInfo::classify{Return,Argument}Type() are not virtual.
8289   void computeInfo(CGFunctionInfo &FI) const override {
8290     if (!getCXXABI().classifyReturnType(FI))
8291       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8292     for (auto &I : FI.arguments())
8293       I.info = classifyArgumentType(I.type);
8294   }
8295 };
8296 
8297 class AVRTargetCodeGenInfo : public TargetCodeGenInfo {
8298 public:
8299   AVRTargetCodeGenInfo(CodeGenTypes &CGT)
8300       : TargetCodeGenInfo(std::make_unique<AVRABIInfo>(CGT)) {}
8301 
8302   LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
8303                                   const VarDecl *D) const override {
8304     // Check if global/static variable is defined in address space
8305     // 1~6 (__flash, __flash1, __flash2, __flash3, __flash4, __flash5)
8306     // but not constant.
8307     if (D) {
8308       LangAS AS = D->getType().getAddressSpace();
8309       if (isTargetAddressSpace(AS) && 1 <= toTargetAddressSpace(AS) &&
8310           toTargetAddressSpace(AS) <= 6 && !D->getType().isConstQualified())
8311         CGM.getDiags().Report(D->getLocation(),
8312                               diag::err_verify_nonconst_addrspace)
8313             << "__flash*";
8314     }
8315     return TargetCodeGenInfo::getGlobalVarAddressSpace(CGM, D);
8316   }
8317 
8318   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8319                            CodeGen::CodeGenModule &CGM) const override {
8320     if (GV->isDeclaration())
8321       return;
8322     const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
8323     if (!FD) return;
8324     auto *Fn = cast<llvm::Function>(GV);
8325 
8326     if (FD->getAttr<AVRInterruptAttr>())
8327       Fn->addFnAttr("interrupt");
8328 
8329     if (FD->getAttr<AVRSignalAttr>())
8330       Fn->addFnAttr("signal");
8331   }
8332 };
8333 }
8334 
8335 //===----------------------------------------------------------------------===//
8336 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
8337 // Currently subclassed only to implement custom OpenCL C function attribute
8338 // handling.
8339 //===----------------------------------------------------------------------===//
8340 
8341 namespace {
8342 
8343 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
8344 public:
8345   TCETargetCodeGenInfo(CodeGenTypes &CGT)
8346     : DefaultTargetCodeGenInfo(CGT) {}
8347 
8348   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8349                            CodeGen::CodeGenModule &M) const override;
8350 };
8351 
8352 void TCETargetCodeGenInfo::setTargetAttributes(
8353     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
8354   if (GV->isDeclaration())
8355     return;
8356   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
8357   if (!FD) return;
8358 
8359   llvm::Function *F = cast<llvm::Function>(GV);
8360 
8361   if (M.getLangOpts().OpenCL) {
8362     if (FD->hasAttr<OpenCLKernelAttr>()) {
8363       // OpenCL C Kernel functions are not subject to inlining
8364       F->addFnAttr(llvm::Attribute::NoInline);
8365       const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
8366       if (Attr) {
8367         // Convert the reqd_work_group_size() attributes to metadata.
8368         llvm::LLVMContext &Context = F->getContext();
8369         llvm::NamedMDNode *OpenCLMetadata =
8370             M.getModule().getOrInsertNamedMetadata(
8371                 "opencl.kernel_wg_size_info");
8372 
8373         SmallVector<llvm::Metadata *, 5> Operands;
8374         Operands.push_back(llvm::ConstantAsMetadata::get(F));
8375 
8376         Operands.push_back(
8377             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8378                 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
8379         Operands.push_back(
8380             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8381                 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
8382         Operands.push_back(
8383             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8384                 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
8385 
8386         // Add a boolean constant operand for "required" (true) or "hint"
8387         // (false) for implementing the work_group_size_hint attr later.
8388         // Currently always true as the hint is not yet implemented.
8389         Operands.push_back(
8390             llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
8391         OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
8392       }
8393     }
8394   }
8395 }
8396 
8397 }
8398 
8399 //===----------------------------------------------------------------------===//
8400 // Hexagon ABI Implementation
8401 //===----------------------------------------------------------------------===//
8402 
8403 namespace {
8404 
8405 class HexagonABIInfo : public DefaultABIInfo {
8406 public:
8407   HexagonABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8408 
8409 private:
8410   ABIArgInfo classifyReturnType(QualType RetTy) const;
8411   ABIArgInfo classifyArgumentType(QualType RetTy) const;
8412   ABIArgInfo classifyArgumentType(QualType RetTy, unsigned *RegsLeft) const;
8413 
8414   void computeInfo(CGFunctionInfo &FI) const override;
8415 
8416   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8417                     QualType Ty) const override;
8418   Address EmitVAArgFromMemory(CodeGenFunction &CFG, Address VAListAddr,
8419                               QualType Ty) const;
8420   Address EmitVAArgForHexagon(CodeGenFunction &CFG, Address VAListAddr,
8421                               QualType Ty) const;
8422   Address EmitVAArgForHexagonLinux(CodeGenFunction &CFG, Address VAListAddr,
8423                                    QualType Ty) const;
8424 };
8425 
8426 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
8427 public:
8428   HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
8429       : TargetCodeGenInfo(std::make_unique<HexagonABIInfo>(CGT)) {}
8430 
8431   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
8432     return 29;
8433   }
8434 
8435   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8436                            CodeGen::CodeGenModule &GCM) const override {
8437     if (GV->isDeclaration())
8438       return;
8439     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
8440     if (!FD)
8441       return;
8442   }
8443 };
8444 
8445 } // namespace
8446 
8447 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
8448   unsigned RegsLeft = 6;
8449   if (!getCXXABI().classifyReturnType(FI))
8450     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8451   for (auto &I : FI.arguments())
8452     I.info = classifyArgumentType(I.type, &RegsLeft);
8453 }
8454 
8455 static bool HexagonAdjustRegsLeft(uint64_t Size, unsigned *RegsLeft) {
8456   assert(Size <= 64 && "Not expecting to pass arguments larger than 64 bits"
8457                        " through registers");
8458 
8459   if (*RegsLeft == 0)
8460     return false;
8461 
8462   if (Size <= 32) {
8463     (*RegsLeft)--;
8464     return true;
8465   }
8466 
8467   if (2 <= (*RegsLeft & (~1U))) {
8468     *RegsLeft = (*RegsLeft & (~1U)) - 2;
8469     return true;
8470   }
8471 
8472   // Next available register was r5 but candidate was greater than 32-bits so it
8473   // has to go on the stack. However we still consume r5
8474   if (*RegsLeft == 1)
8475     *RegsLeft = 0;
8476 
8477   return false;
8478 }
8479 
8480 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty,
8481                                                 unsigned *RegsLeft) const {
8482   if (!isAggregateTypeForABI(Ty)) {
8483     // Treat an enum type as its underlying type.
8484     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
8485       Ty = EnumTy->getDecl()->getIntegerType();
8486 
8487     uint64_t Size = getContext().getTypeSize(Ty);
8488     if (Size <= 64)
8489       HexagonAdjustRegsLeft(Size, RegsLeft);
8490 
8491     if (Size > 64 && Ty->isBitIntType())
8492       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8493 
8494     return isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
8495                                              : ABIArgInfo::getDirect();
8496   }
8497 
8498   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
8499     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
8500 
8501   // Ignore empty records.
8502   if (isEmptyRecord(getContext(), Ty, true))
8503     return ABIArgInfo::getIgnore();
8504 
8505   uint64_t Size = getContext().getTypeSize(Ty);
8506   unsigned Align = getContext().getTypeAlign(Ty);
8507 
8508   if (Size > 64)
8509     return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8510 
8511   if (HexagonAdjustRegsLeft(Size, RegsLeft))
8512     Align = Size <= 32 ? 32 : 64;
8513   if (Size <= Align) {
8514     // Pass in the smallest viable integer type.
8515     if (!llvm::isPowerOf2_64(Size))
8516       Size = llvm::NextPowerOf2(Size);
8517     return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size));
8518   }
8519   return DefaultABIInfo::classifyArgumentType(Ty);
8520 }
8521 
8522 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
8523   if (RetTy->isVoidType())
8524     return ABIArgInfo::getIgnore();
8525 
8526   const TargetInfo &T = CGT.getTarget();
8527   uint64_t Size = getContext().getTypeSize(RetTy);
8528 
8529   if (RetTy->getAs<VectorType>()) {
8530     // HVX vectors are returned in vector registers or register pairs.
8531     if (T.hasFeature("hvx")) {
8532       assert(T.hasFeature("hvx-length64b") || T.hasFeature("hvx-length128b"));
8533       uint64_t VecSize = T.hasFeature("hvx-length64b") ? 64*8 : 128*8;
8534       if (Size == VecSize || Size == 2*VecSize)
8535         return ABIArgInfo::getDirectInReg();
8536     }
8537     // Large vector types should be returned via memory.
8538     if (Size > 64)
8539       return getNaturalAlignIndirect(RetTy);
8540   }
8541 
8542   if (!isAggregateTypeForABI(RetTy)) {
8543     // Treat an enum type as its underlying type.
8544     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
8545       RetTy = EnumTy->getDecl()->getIntegerType();
8546 
8547     if (Size > 64 && RetTy->isBitIntType())
8548       return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
8549 
8550     return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
8551                                                 : ABIArgInfo::getDirect();
8552   }
8553 
8554   if (isEmptyRecord(getContext(), RetTy, true))
8555     return ABIArgInfo::getIgnore();
8556 
8557   // Aggregates <= 8 bytes are returned in registers, other aggregates
8558   // are returned indirectly.
8559   if (Size <= 64) {
8560     // Return in the smallest viable integer type.
8561     if (!llvm::isPowerOf2_64(Size))
8562       Size = llvm::NextPowerOf2(Size);
8563     return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size));
8564   }
8565   return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
8566 }
8567 
8568 Address HexagonABIInfo::EmitVAArgFromMemory(CodeGenFunction &CGF,
8569                                             Address VAListAddr,
8570                                             QualType Ty) const {
8571   // Load the overflow area pointer.
8572   Address __overflow_area_pointer_p =
8573       CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p");
8574   llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad(
8575       __overflow_area_pointer_p, "__overflow_area_pointer");
8576 
8577   uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
8578   if (Align > 4) {
8579     // Alignment should be a power of 2.
8580     assert((Align & (Align - 1)) == 0 && "Alignment is not power of 2!");
8581 
8582     // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
8583     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
8584 
8585     // Add offset to the current pointer to access the argument.
8586     __overflow_area_pointer =
8587         CGF.Builder.CreateGEP(CGF.Int8Ty, __overflow_area_pointer, Offset);
8588     llvm::Value *AsInt =
8589         CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty);
8590 
8591     // Create a mask which should be "AND"ed
8592     // with (overflow_arg_area + align - 1)
8593     llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -(int)Align);
8594     __overflow_area_pointer = CGF.Builder.CreateIntToPtr(
8595         CGF.Builder.CreateAnd(AsInt, Mask), __overflow_area_pointer->getType(),
8596         "__overflow_area_pointer.align");
8597   }
8598 
8599   // Get the type of the argument from memory and bitcast
8600   // overflow area pointer to the argument type.
8601   llvm::Type *PTy = CGF.ConvertTypeForMem(Ty);
8602   Address AddrTyped = CGF.Builder.CreateElementBitCast(
8603       Address::deprecated(__overflow_area_pointer,
8604                           CharUnits::fromQuantity(Align)),
8605       PTy);
8606 
8607   // Round up to the minimum stack alignment for varargs which is 4 bytes.
8608   uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4);
8609 
8610   __overflow_area_pointer = CGF.Builder.CreateGEP(
8611       CGF.Int8Ty, __overflow_area_pointer,
8612       llvm::ConstantInt::get(CGF.Int32Ty, Offset),
8613       "__overflow_area_pointer.next");
8614   CGF.Builder.CreateStore(__overflow_area_pointer, __overflow_area_pointer_p);
8615 
8616   return AddrTyped;
8617 }
8618 
8619 Address HexagonABIInfo::EmitVAArgForHexagon(CodeGenFunction &CGF,
8620                                             Address VAListAddr,
8621                                             QualType Ty) const {
8622   // FIXME: Need to handle alignment
8623   llvm::Type *BP = CGF.Int8PtrTy;
8624   CGBuilderTy &Builder = CGF.Builder;
8625   Address VAListAddrAsBPP = Builder.CreateElementBitCast(VAListAddr, BP, "ap");
8626   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
8627   // Handle address alignment for type alignment > 32 bits
8628   uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
8629   if (TyAlign > 4) {
8630     assert((TyAlign & (TyAlign - 1)) == 0 && "Alignment is not power of 2!");
8631     llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
8632     AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
8633     AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
8634     Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
8635   }
8636   Address AddrTyped = Builder.CreateElementBitCast(
8637       Address::deprecated(Addr, CharUnits::fromQuantity(TyAlign)),
8638       CGF.ConvertType(Ty));
8639 
8640   uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4);
8641   llvm::Value *NextAddr = Builder.CreateGEP(
8642       CGF.Int8Ty, Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next");
8643   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
8644 
8645   return AddrTyped;
8646 }
8647 
8648 Address HexagonABIInfo::EmitVAArgForHexagonLinux(CodeGenFunction &CGF,
8649                                                  Address VAListAddr,
8650                                                  QualType Ty) const {
8651   int ArgSize = CGF.getContext().getTypeSize(Ty) / 8;
8652 
8653   if (ArgSize > 8)
8654     return EmitVAArgFromMemory(CGF, VAListAddr, Ty);
8655 
8656   // Here we have check if the argument is in register area or
8657   // in overflow area.
8658   // If the saved register area pointer + argsize rounded up to alignment >
8659   // saved register area end pointer, argument is in overflow area.
8660   unsigned RegsLeft = 6;
8661   Ty = CGF.getContext().getCanonicalType(Ty);
8662   (void)classifyArgumentType(Ty, &RegsLeft);
8663 
8664   llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
8665   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
8666   llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
8667   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
8668 
8669   // Get rounded size of the argument.GCC does not allow vararg of
8670   // size < 4 bytes. We follow the same logic here.
8671   ArgSize = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8;
8672   int ArgAlign = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8;
8673 
8674   // Argument may be in saved register area
8675   CGF.EmitBlock(MaybeRegBlock);
8676 
8677   // Load the current saved register area pointer.
8678   Address __current_saved_reg_area_pointer_p = CGF.Builder.CreateStructGEP(
8679       VAListAddr, 0, "__current_saved_reg_area_pointer_p");
8680   llvm::Value *__current_saved_reg_area_pointer = CGF.Builder.CreateLoad(
8681       __current_saved_reg_area_pointer_p, "__current_saved_reg_area_pointer");
8682 
8683   // Load the saved register area end pointer.
8684   Address __saved_reg_area_end_pointer_p = CGF.Builder.CreateStructGEP(
8685       VAListAddr, 1, "__saved_reg_area_end_pointer_p");
8686   llvm::Value *__saved_reg_area_end_pointer = CGF.Builder.CreateLoad(
8687       __saved_reg_area_end_pointer_p, "__saved_reg_area_end_pointer");
8688 
8689   // If the size of argument is > 4 bytes, check if the stack
8690   // location is aligned to 8 bytes
8691   if (ArgAlign > 4) {
8692 
8693     llvm::Value *__current_saved_reg_area_pointer_int =
8694         CGF.Builder.CreatePtrToInt(__current_saved_reg_area_pointer,
8695                                    CGF.Int32Ty);
8696 
8697     __current_saved_reg_area_pointer_int = CGF.Builder.CreateAdd(
8698         __current_saved_reg_area_pointer_int,
8699         llvm::ConstantInt::get(CGF.Int32Ty, (ArgAlign - 1)),
8700         "align_current_saved_reg_area_pointer");
8701 
8702     __current_saved_reg_area_pointer_int =
8703         CGF.Builder.CreateAnd(__current_saved_reg_area_pointer_int,
8704                               llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign),
8705                               "align_current_saved_reg_area_pointer");
8706 
8707     __current_saved_reg_area_pointer =
8708         CGF.Builder.CreateIntToPtr(__current_saved_reg_area_pointer_int,
8709                                    __current_saved_reg_area_pointer->getType(),
8710                                    "align_current_saved_reg_area_pointer");
8711   }
8712 
8713   llvm::Value *__new_saved_reg_area_pointer =
8714       CGF.Builder.CreateGEP(CGF.Int8Ty, __current_saved_reg_area_pointer,
8715                             llvm::ConstantInt::get(CGF.Int32Ty, ArgSize),
8716                             "__new_saved_reg_area_pointer");
8717 
8718   llvm::Value *UsingStack = nullptr;
8719   UsingStack = CGF.Builder.CreateICmpSGT(__new_saved_reg_area_pointer,
8720                                          __saved_reg_area_end_pointer);
8721 
8722   CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, InRegBlock);
8723 
8724   // Argument in saved register area
8725   // Implement the block where argument is in register saved area
8726   CGF.EmitBlock(InRegBlock);
8727 
8728   llvm::Type *PTy = CGF.ConvertType(Ty);
8729   llvm::Value *__saved_reg_area_p = CGF.Builder.CreateBitCast(
8730       __current_saved_reg_area_pointer, llvm::PointerType::getUnqual(PTy));
8731 
8732   CGF.Builder.CreateStore(__new_saved_reg_area_pointer,
8733                           __current_saved_reg_area_pointer_p);
8734 
8735   CGF.EmitBranch(ContBlock);
8736 
8737   // Argument in overflow area
8738   // Implement the block where the argument is in overflow area.
8739   CGF.EmitBlock(OnStackBlock);
8740 
8741   // Load the overflow area pointer
8742   Address __overflow_area_pointer_p =
8743       CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p");
8744   llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad(
8745       __overflow_area_pointer_p, "__overflow_area_pointer");
8746 
8747   // Align the overflow area pointer according to the alignment of the argument
8748   if (ArgAlign > 4) {
8749     llvm::Value *__overflow_area_pointer_int =
8750         CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty);
8751 
8752     __overflow_area_pointer_int =
8753         CGF.Builder.CreateAdd(__overflow_area_pointer_int,
8754                               llvm::ConstantInt::get(CGF.Int32Ty, ArgAlign - 1),
8755                               "align_overflow_area_pointer");
8756 
8757     __overflow_area_pointer_int =
8758         CGF.Builder.CreateAnd(__overflow_area_pointer_int,
8759                               llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign),
8760                               "align_overflow_area_pointer");
8761 
8762     __overflow_area_pointer = CGF.Builder.CreateIntToPtr(
8763         __overflow_area_pointer_int, __overflow_area_pointer->getType(),
8764         "align_overflow_area_pointer");
8765   }
8766 
8767   // Get the pointer for next argument in overflow area and store it
8768   // to overflow area pointer.
8769   llvm::Value *__new_overflow_area_pointer = CGF.Builder.CreateGEP(
8770       CGF.Int8Ty, __overflow_area_pointer,
8771       llvm::ConstantInt::get(CGF.Int32Ty, ArgSize),
8772       "__overflow_area_pointer.next");
8773 
8774   CGF.Builder.CreateStore(__new_overflow_area_pointer,
8775                           __overflow_area_pointer_p);
8776 
8777   CGF.Builder.CreateStore(__new_overflow_area_pointer,
8778                           __current_saved_reg_area_pointer_p);
8779 
8780   // Bitcast the overflow area pointer to the type of argument.
8781   llvm::Type *OverflowPTy = CGF.ConvertTypeForMem(Ty);
8782   llvm::Value *__overflow_area_p = CGF.Builder.CreateBitCast(
8783       __overflow_area_pointer, llvm::PointerType::getUnqual(OverflowPTy));
8784 
8785   CGF.EmitBranch(ContBlock);
8786 
8787   // Get the correct pointer to load the variable argument
8788   // Implement the ContBlock
8789   CGF.EmitBlock(ContBlock);
8790 
8791   llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
8792   llvm::Type *MemPTy = llvm::PointerType::getUnqual(MemTy);
8793   llvm::PHINode *ArgAddr = CGF.Builder.CreatePHI(MemPTy, 2, "vaarg.addr");
8794   ArgAddr->addIncoming(__saved_reg_area_p, InRegBlock);
8795   ArgAddr->addIncoming(__overflow_area_p, OnStackBlock);
8796 
8797   return Address(ArgAddr, MemTy, CharUnits::fromQuantity(ArgAlign));
8798 }
8799 
8800 Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8801                                   QualType Ty) const {
8802 
8803   if (getTarget().getTriple().isMusl())
8804     return EmitVAArgForHexagonLinux(CGF, VAListAddr, Ty);
8805 
8806   return EmitVAArgForHexagon(CGF, VAListAddr, Ty);
8807 }
8808 
8809 //===----------------------------------------------------------------------===//
8810 // Lanai ABI Implementation
8811 //===----------------------------------------------------------------------===//
8812 
8813 namespace {
8814 class LanaiABIInfo : public DefaultABIInfo {
8815 public:
8816   LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8817 
8818   bool shouldUseInReg(QualType Ty, CCState &State) const;
8819 
8820   void computeInfo(CGFunctionInfo &FI) const override {
8821     CCState State(FI);
8822     // Lanai uses 4 registers to pass arguments unless the function has the
8823     // regparm attribute set.
8824     if (FI.getHasRegParm()) {
8825       State.FreeRegs = FI.getRegParm();
8826     } else {
8827       State.FreeRegs = 4;
8828     }
8829 
8830     if (!getCXXABI().classifyReturnType(FI))
8831       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8832     for (auto &I : FI.arguments())
8833       I.info = classifyArgumentType(I.type, State);
8834   }
8835 
8836   ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
8837   ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
8838 };
8839 } // end anonymous namespace
8840 
8841 bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
8842   unsigned Size = getContext().getTypeSize(Ty);
8843   unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
8844 
8845   if (SizeInRegs == 0)
8846     return false;
8847 
8848   if (SizeInRegs > State.FreeRegs) {
8849     State.FreeRegs = 0;
8850     return false;
8851   }
8852 
8853   State.FreeRegs -= SizeInRegs;
8854 
8855   return true;
8856 }
8857 
8858 ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
8859                                            CCState &State) const {
8860   if (!ByVal) {
8861     if (State.FreeRegs) {
8862       --State.FreeRegs; // Non-byval indirects just use one pointer.
8863       return getNaturalAlignIndirectInReg(Ty);
8864     }
8865     return getNaturalAlignIndirect(Ty, false);
8866   }
8867 
8868   // Compute the byval alignment.
8869   const unsigned MinABIStackAlignInBytes = 4;
8870   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
8871   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
8872                                  /*Realign=*/TypeAlign >
8873                                      MinABIStackAlignInBytes);
8874 }
8875 
8876 ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
8877                                               CCState &State) const {
8878   // Check with the C++ ABI first.
8879   const RecordType *RT = Ty->getAs<RecordType>();
8880   if (RT) {
8881     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
8882     if (RAA == CGCXXABI::RAA_Indirect) {
8883       return getIndirectResult(Ty, /*ByVal=*/false, State);
8884     } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
8885       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8886     }
8887   }
8888 
8889   if (isAggregateTypeForABI(Ty)) {
8890     // Structures with flexible arrays are always indirect.
8891     if (RT && RT->getDecl()->hasFlexibleArrayMember())
8892       return getIndirectResult(Ty, /*ByVal=*/true, State);
8893 
8894     // Ignore empty structs/unions.
8895     if (isEmptyRecord(getContext(), Ty, true))
8896       return ABIArgInfo::getIgnore();
8897 
8898     llvm::LLVMContext &LLVMContext = getVMContext();
8899     unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
8900     if (SizeInRegs <= State.FreeRegs) {
8901       llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
8902       SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
8903       llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
8904       State.FreeRegs -= SizeInRegs;
8905       return ABIArgInfo::getDirectInReg(Result);
8906     } else {
8907       State.FreeRegs = 0;
8908     }
8909     return getIndirectResult(Ty, true, State);
8910   }
8911 
8912   // Treat an enum type as its underlying type.
8913   if (const auto *EnumTy = Ty->getAs<EnumType>())
8914     Ty = EnumTy->getDecl()->getIntegerType();
8915 
8916   bool InReg = shouldUseInReg(Ty, State);
8917 
8918   // Don't pass >64 bit integers in registers.
8919   if (const auto *EIT = Ty->getAs<BitIntType>())
8920     if (EIT->getNumBits() > 64)
8921       return getIndirectResult(Ty, /*ByVal=*/true, State);
8922 
8923   if (isPromotableIntegerTypeForABI(Ty)) {
8924     if (InReg)
8925       return ABIArgInfo::getDirectInReg();
8926     return ABIArgInfo::getExtend(Ty);
8927   }
8928   if (InReg)
8929     return ABIArgInfo::getDirectInReg();
8930   return ABIArgInfo::getDirect();
8931 }
8932 
8933 namespace {
8934 class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
8935 public:
8936   LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
8937       : TargetCodeGenInfo(std::make_unique<LanaiABIInfo>(CGT)) {}
8938 };
8939 }
8940 
8941 //===----------------------------------------------------------------------===//
8942 // AMDGPU ABI Implementation
8943 //===----------------------------------------------------------------------===//
8944 
8945 namespace {
8946 
8947 class AMDGPUABIInfo final : public DefaultABIInfo {
8948 private:
8949   static const unsigned MaxNumRegsForArgsRet = 16;
8950 
8951   unsigned numRegsForType(QualType Ty) const;
8952 
8953   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
8954   bool isHomogeneousAggregateSmallEnough(const Type *Base,
8955                                          uint64_t Members) const override;
8956 
8957   // Coerce HIP scalar pointer arguments from generic pointers to global ones.
8958   llvm::Type *coerceKernelArgumentType(llvm::Type *Ty, unsigned FromAS,
8959                                        unsigned ToAS) const {
8960     // Single value types.
8961     auto *PtrTy = llvm::dyn_cast<llvm::PointerType>(Ty);
8962     if (PtrTy && PtrTy->getAddressSpace() == FromAS)
8963       return llvm::PointerType::getWithSamePointeeType(PtrTy, ToAS);
8964     return Ty;
8965   }
8966 
8967 public:
8968   explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) :
8969     DefaultABIInfo(CGT) {}
8970 
8971   ABIArgInfo classifyReturnType(QualType RetTy) const;
8972   ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
8973   ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const;
8974 
8975   void computeInfo(CGFunctionInfo &FI) const override;
8976   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8977                     QualType Ty) const override;
8978 };
8979 
8980 bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
8981   return true;
8982 }
8983 
8984 bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough(
8985   const Type *Base, uint64_t Members) const {
8986   uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32;
8987 
8988   // Homogeneous Aggregates may occupy at most 16 registers.
8989   return Members * NumRegs <= MaxNumRegsForArgsRet;
8990 }
8991 
8992 /// Estimate number of registers the type will use when passed in registers.
8993 unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const {
8994   unsigned NumRegs = 0;
8995 
8996   if (const VectorType *VT = Ty->getAs<VectorType>()) {
8997     // Compute from the number of elements. The reported size is based on the
8998     // in-memory size, which includes the padding 4th element for 3-vectors.
8999     QualType EltTy = VT->getElementType();
9000     unsigned EltSize = getContext().getTypeSize(EltTy);
9001 
9002     // 16-bit element vectors should be passed as packed.
9003     if (EltSize == 16)
9004       return (VT->getNumElements() + 1) / 2;
9005 
9006     unsigned EltNumRegs = (EltSize + 31) / 32;
9007     return EltNumRegs * VT->getNumElements();
9008   }
9009 
9010   if (const RecordType *RT = Ty->getAs<RecordType>()) {
9011     const RecordDecl *RD = RT->getDecl();
9012     assert(!RD->hasFlexibleArrayMember());
9013 
9014     for (const FieldDecl *Field : RD->fields()) {
9015       QualType FieldTy = Field->getType();
9016       NumRegs += numRegsForType(FieldTy);
9017     }
9018 
9019     return NumRegs;
9020   }
9021 
9022   return (getContext().getTypeSize(Ty) + 31) / 32;
9023 }
9024 
9025 void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
9026   llvm::CallingConv::ID CC = FI.getCallingConvention();
9027 
9028   if (!getCXXABI().classifyReturnType(FI))
9029     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
9030 
9031   unsigned NumRegsLeft = MaxNumRegsForArgsRet;
9032   for (auto &Arg : FI.arguments()) {
9033     if (CC == llvm::CallingConv::AMDGPU_KERNEL) {
9034       Arg.info = classifyKernelArgumentType(Arg.type);
9035     } else {
9036       Arg.info = classifyArgumentType(Arg.type, NumRegsLeft);
9037     }
9038   }
9039 }
9040 
9041 Address AMDGPUABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9042                                  QualType Ty) const {
9043   llvm_unreachable("AMDGPU does not support varargs");
9044 }
9045 
9046 ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const {
9047   if (isAggregateTypeForABI(RetTy)) {
9048     // Records with non-trivial destructors/copy-constructors should not be
9049     // returned by value.
9050     if (!getRecordArgABI(RetTy, getCXXABI())) {
9051       // Ignore empty structs/unions.
9052       if (isEmptyRecord(getContext(), RetTy, true))
9053         return ABIArgInfo::getIgnore();
9054 
9055       // Lower single-element structs to just return a regular value.
9056       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
9057         return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
9058 
9059       if (const RecordType *RT = RetTy->getAs<RecordType>()) {
9060         const RecordDecl *RD = RT->getDecl();
9061         if (RD->hasFlexibleArrayMember())
9062           return DefaultABIInfo::classifyReturnType(RetTy);
9063       }
9064 
9065       // Pack aggregates <= 4 bytes into single VGPR or pair.
9066       uint64_t Size = getContext().getTypeSize(RetTy);
9067       if (Size <= 16)
9068         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
9069 
9070       if (Size <= 32)
9071         return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
9072 
9073       if (Size <= 64) {
9074         llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
9075         return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
9076       }
9077 
9078       if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet)
9079         return ABIArgInfo::getDirect();
9080     }
9081   }
9082 
9083   // Otherwise just do the default thing.
9084   return DefaultABIInfo::classifyReturnType(RetTy);
9085 }
9086 
9087 /// For kernels all parameters are really passed in a special buffer. It doesn't
9088 /// make sense to pass anything byval, so everything must be direct.
9089 ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const {
9090   Ty = useFirstFieldIfTransparentUnion(Ty);
9091 
9092   // TODO: Can we omit empty structs?
9093 
9094   if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
9095     Ty = QualType(SeltTy, 0);
9096 
9097   llvm::Type *OrigLTy = CGT.ConvertType(Ty);
9098   llvm::Type *LTy = OrigLTy;
9099   if (getContext().getLangOpts().HIP) {
9100     LTy = coerceKernelArgumentType(
9101         OrigLTy, /*FromAS=*/getContext().getTargetAddressSpace(LangAS::Default),
9102         /*ToAS=*/getContext().getTargetAddressSpace(LangAS::cuda_device));
9103   }
9104 
9105   // FIXME: Should also use this for OpenCL, but it requires addressing the
9106   // problem of kernels being called.
9107   //
9108   // FIXME: This doesn't apply the optimization of coercing pointers in structs
9109   // to global address space when using byref. This would require implementing a
9110   // new kind of coercion of the in-memory type when for indirect arguments.
9111   if (!getContext().getLangOpts().OpenCL && LTy == OrigLTy &&
9112       isAggregateTypeForABI(Ty)) {
9113     return ABIArgInfo::getIndirectAliased(
9114         getContext().getTypeAlignInChars(Ty),
9115         getContext().getTargetAddressSpace(LangAS::opencl_constant),
9116         false /*Realign*/, nullptr /*Padding*/);
9117   }
9118 
9119   // If we set CanBeFlattened to true, CodeGen will expand the struct to its
9120   // individual elements, which confuses the Clover OpenCL backend; therefore we
9121   // have to set it to false here. Other args of getDirect() are just defaults.
9122   return ABIArgInfo::getDirect(LTy, 0, nullptr, false);
9123 }
9124 
9125 ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty,
9126                                                unsigned &NumRegsLeft) const {
9127   assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow");
9128 
9129   Ty = useFirstFieldIfTransparentUnion(Ty);
9130 
9131   if (isAggregateTypeForABI(Ty)) {
9132     // Records with non-trivial destructors/copy-constructors should not be
9133     // passed by value.
9134     if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
9135       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
9136 
9137     // Ignore empty structs/unions.
9138     if (isEmptyRecord(getContext(), Ty, true))
9139       return ABIArgInfo::getIgnore();
9140 
9141     // Lower single-element structs to just pass a regular value. TODO: We
9142     // could do reasonable-size multiple-element structs too, using getExpand(),
9143     // though watch out for things like bitfields.
9144     if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
9145       return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
9146 
9147     if (const RecordType *RT = Ty->getAs<RecordType>()) {
9148       const RecordDecl *RD = RT->getDecl();
9149       if (RD->hasFlexibleArrayMember())
9150         return DefaultABIInfo::classifyArgumentType(Ty);
9151     }
9152 
9153     // Pack aggregates <= 8 bytes into single VGPR or pair.
9154     uint64_t Size = getContext().getTypeSize(Ty);
9155     if (Size <= 64) {
9156       unsigned NumRegs = (Size + 31) / 32;
9157       NumRegsLeft -= std::min(NumRegsLeft, NumRegs);
9158 
9159       if (Size <= 16)
9160         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
9161 
9162       if (Size <= 32)
9163         return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
9164 
9165       // XXX: Should this be i64 instead, and should the limit increase?
9166       llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
9167       return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
9168     }
9169 
9170     if (NumRegsLeft > 0) {
9171       unsigned NumRegs = numRegsForType(Ty);
9172       if (NumRegsLeft >= NumRegs) {
9173         NumRegsLeft -= NumRegs;
9174         return ABIArgInfo::getDirect();
9175       }
9176     }
9177   }
9178 
9179   // Otherwise just do the default thing.
9180   ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty);
9181   if (!ArgInfo.isIndirect()) {
9182     unsigned NumRegs = numRegsForType(Ty);
9183     NumRegsLeft -= std::min(NumRegs, NumRegsLeft);
9184   }
9185 
9186   return ArgInfo;
9187 }
9188 
9189 class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
9190 public:
9191   AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
9192       : TargetCodeGenInfo(std::make_unique<AMDGPUABIInfo>(CGT)) {}
9193 
9194   void setFunctionDeclAttributes(const FunctionDecl *FD, llvm::Function *F,
9195                                  CodeGenModule &CGM) const;
9196 
9197   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
9198                            CodeGen::CodeGenModule &M) const override;
9199   unsigned getOpenCLKernelCallingConv() const override;
9200 
9201   llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
9202       llvm::PointerType *T, QualType QT) const override;
9203 
9204   LangAS getASTAllocaAddressSpace() const override {
9205     return getLangASFromTargetAS(
9206         getABIInfo().getDataLayout().getAllocaAddrSpace());
9207   }
9208   LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
9209                                   const VarDecl *D) const override;
9210   llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts,
9211                                          SyncScope Scope,
9212                                          llvm::AtomicOrdering Ordering,
9213                                          llvm::LLVMContext &Ctx) const override;
9214   llvm::Function *
9215   createEnqueuedBlockKernel(CodeGenFunction &CGF,
9216                             llvm::Function *BlockInvokeFunc,
9217                             llvm::Value *BlockLiteral) const override;
9218   bool shouldEmitStaticExternCAliases() const override;
9219   void setCUDAKernelCallingConvention(const FunctionType *&FT) const override;
9220 };
9221 }
9222 
9223 static bool requiresAMDGPUProtectedVisibility(const Decl *D,
9224                                               llvm::GlobalValue *GV) {
9225   if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility)
9226     return false;
9227 
9228   return D->hasAttr<OpenCLKernelAttr>() ||
9229          (isa<FunctionDecl>(D) && D->hasAttr<CUDAGlobalAttr>()) ||
9230          (isa<VarDecl>(D) &&
9231           (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
9232            cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinSurfaceType() ||
9233            cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinTextureType()));
9234 }
9235 
9236 void AMDGPUTargetCodeGenInfo::setFunctionDeclAttributes(
9237     const FunctionDecl *FD, llvm::Function *F, CodeGenModule &M) const {
9238   const auto *ReqdWGS =
9239       M.getLangOpts().OpenCL ? FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr;
9240   const bool IsOpenCLKernel =
9241       M.getLangOpts().OpenCL && FD->hasAttr<OpenCLKernelAttr>();
9242   const bool IsHIPKernel = M.getLangOpts().HIP && FD->hasAttr<CUDAGlobalAttr>();
9243 
9244   const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
9245   if (ReqdWGS || FlatWGS) {
9246     unsigned Min = 0;
9247     unsigned Max = 0;
9248     if (FlatWGS) {
9249       Min = FlatWGS->getMin()
9250                 ->EvaluateKnownConstInt(M.getContext())
9251                 .getExtValue();
9252       Max = FlatWGS->getMax()
9253                 ->EvaluateKnownConstInt(M.getContext())
9254                 .getExtValue();
9255     }
9256     if (ReqdWGS && Min == 0 && Max == 0)
9257       Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim();
9258 
9259     if (Min != 0) {
9260       assert(Min <= Max && "Min must be less than or equal Max");
9261 
9262       std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
9263       F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
9264     } else
9265       assert(Max == 0 && "Max must be zero");
9266   } else if (IsOpenCLKernel || IsHIPKernel) {
9267     // By default, restrict the maximum size to a value specified by
9268     // --gpu-max-threads-per-block=n or its default value for HIP.
9269     const unsigned OpenCLDefaultMaxWorkGroupSize = 256;
9270     const unsigned DefaultMaxWorkGroupSize =
9271         IsOpenCLKernel ? OpenCLDefaultMaxWorkGroupSize
9272                        : M.getLangOpts().GPUMaxThreadsPerBlock;
9273     std::string AttrVal =
9274         std::string("1,") + llvm::utostr(DefaultMaxWorkGroupSize);
9275     F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
9276   }
9277 
9278   if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
9279     unsigned Min =
9280         Attr->getMin()->EvaluateKnownConstInt(M.getContext()).getExtValue();
9281     unsigned Max = Attr->getMax() ? Attr->getMax()
9282                                         ->EvaluateKnownConstInt(M.getContext())
9283                                         .getExtValue()
9284                                   : 0;
9285 
9286     if (Min != 0) {
9287       assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
9288 
9289       std::string AttrVal = llvm::utostr(Min);
9290       if (Max != 0)
9291         AttrVal = AttrVal + "," + llvm::utostr(Max);
9292       F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
9293     } else
9294       assert(Max == 0 && "Max must be zero");
9295   }
9296 
9297   if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
9298     unsigned NumSGPR = Attr->getNumSGPR();
9299 
9300     if (NumSGPR != 0)
9301       F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
9302   }
9303 
9304   if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
9305     uint32_t NumVGPR = Attr->getNumVGPR();
9306 
9307     if (NumVGPR != 0)
9308       F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
9309   }
9310 }
9311 
9312 void AMDGPUTargetCodeGenInfo::setTargetAttributes(
9313     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
9314   if (requiresAMDGPUProtectedVisibility(D, GV)) {
9315     GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
9316     GV->setDSOLocal(true);
9317   }
9318 
9319   if (GV->isDeclaration())
9320     return;
9321 
9322   llvm::Function *F = dyn_cast<llvm::Function>(GV);
9323   if (!F)
9324     return;
9325 
9326   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
9327   if (FD)
9328     setFunctionDeclAttributes(FD, F, M);
9329 
9330   const bool IsHIPKernel =
9331       M.getLangOpts().HIP && FD && FD->hasAttr<CUDAGlobalAttr>();
9332 
9333   if (IsHIPKernel)
9334     F->addFnAttr("uniform-work-group-size", "true");
9335 
9336   if (M.getContext().getTargetInfo().allowAMDGPUUnsafeFPAtomics())
9337     F->addFnAttr("amdgpu-unsafe-fp-atomics", "true");
9338 
9339   if (!getABIInfo().getCodeGenOpts().EmitIEEENaNCompliantInsts)
9340     F->addFnAttr("amdgpu-ieee", "false");
9341 }
9342 
9343 unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
9344   return llvm::CallingConv::AMDGPU_KERNEL;
9345 }
9346 
9347 // Currently LLVM assumes null pointers always have value 0,
9348 // which results in incorrectly transformed IR. Therefore, instead of
9349 // emitting null pointers in private and local address spaces, a null
9350 // pointer in generic address space is emitted which is casted to a
9351 // pointer in local or private address space.
9352 llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
9353     const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
9354     QualType QT) const {
9355   if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
9356     return llvm::ConstantPointerNull::get(PT);
9357 
9358   auto &Ctx = CGM.getContext();
9359   auto NPT = llvm::PointerType::getWithSamePointeeType(
9360       PT, Ctx.getTargetAddressSpace(LangAS::opencl_generic));
9361   return llvm::ConstantExpr::getAddrSpaceCast(
9362       llvm::ConstantPointerNull::get(NPT), PT);
9363 }
9364 
9365 LangAS
9366 AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
9367                                                   const VarDecl *D) const {
9368   assert(!CGM.getLangOpts().OpenCL &&
9369          !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
9370          "Address space agnostic languages only");
9371   LangAS DefaultGlobalAS = getLangASFromTargetAS(
9372       CGM.getContext().getTargetAddressSpace(LangAS::opencl_global));
9373   if (!D)
9374     return DefaultGlobalAS;
9375 
9376   LangAS AddrSpace = D->getType().getAddressSpace();
9377   assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace));
9378   if (AddrSpace != LangAS::Default)
9379     return AddrSpace;
9380 
9381   // Only promote to address space 4 if VarDecl has constant initialization.
9382   if (CGM.isTypeConstant(D->getType(), false) &&
9383       D->hasConstantInitialization()) {
9384     if (auto ConstAS = CGM.getTarget().getConstantAddressSpace())
9385       return ConstAS.getValue();
9386   }
9387   return DefaultGlobalAS;
9388 }
9389 
9390 llvm::SyncScope::ID
9391 AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
9392                                             SyncScope Scope,
9393                                             llvm::AtomicOrdering Ordering,
9394                                             llvm::LLVMContext &Ctx) const {
9395   std::string Name;
9396   switch (Scope) {
9397   case SyncScope::HIPSingleThread:
9398     Name = "singlethread";
9399     break;
9400   case SyncScope::HIPWavefront:
9401   case SyncScope::OpenCLSubGroup:
9402     Name = "wavefront";
9403     break;
9404   case SyncScope::HIPWorkgroup:
9405   case SyncScope::OpenCLWorkGroup:
9406     Name = "workgroup";
9407     break;
9408   case SyncScope::HIPAgent:
9409   case SyncScope::OpenCLDevice:
9410     Name = "agent";
9411     break;
9412   case SyncScope::HIPSystem:
9413   case SyncScope::OpenCLAllSVMDevices:
9414     Name = "";
9415     break;
9416   }
9417 
9418   if (Ordering != llvm::AtomicOrdering::SequentiallyConsistent) {
9419     if (!Name.empty())
9420       Name = Twine(Twine(Name) + Twine("-")).str();
9421 
9422     Name = Twine(Twine(Name) + Twine("one-as")).str();
9423   }
9424 
9425   return Ctx.getOrInsertSyncScopeID(Name);
9426 }
9427 
9428 bool AMDGPUTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
9429   return false;
9430 }
9431 
9432 void AMDGPUTargetCodeGenInfo::setCUDAKernelCallingConvention(
9433     const FunctionType *&FT) const {
9434   FT = getABIInfo().getContext().adjustFunctionType(
9435       FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel));
9436 }
9437 
9438 //===----------------------------------------------------------------------===//
9439 // SPARC v8 ABI Implementation.
9440 // Based on the SPARC Compliance Definition version 2.4.1.
9441 //
9442 // Ensures that complex values are passed in registers.
9443 //
9444 namespace {
9445 class SparcV8ABIInfo : public DefaultABIInfo {
9446 public:
9447   SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
9448 
9449 private:
9450   ABIArgInfo classifyReturnType(QualType RetTy) const;
9451   void computeInfo(CGFunctionInfo &FI) const override;
9452 };
9453 } // end anonymous namespace
9454 
9455 
9456 ABIArgInfo
9457 SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
9458   if (Ty->isAnyComplexType()) {
9459     return ABIArgInfo::getDirect();
9460   }
9461   else {
9462     return DefaultABIInfo::classifyReturnType(Ty);
9463   }
9464 }
9465 
9466 void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
9467 
9468   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
9469   for (auto &Arg : FI.arguments())
9470     Arg.info = classifyArgumentType(Arg.type);
9471 }
9472 
9473 namespace {
9474 class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
9475 public:
9476   SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
9477       : TargetCodeGenInfo(std::make_unique<SparcV8ABIInfo>(CGT)) {}
9478 
9479   llvm::Value *decodeReturnAddress(CodeGen::CodeGenFunction &CGF,
9480                                    llvm::Value *Address) const override {
9481     int Offset;
9482     if (isAggregateTypeForABI(CGF.CurFnInfo->getReturnType()))
9483       Offset = 12;
9484     else
9485       Offset = 8;
9486     return CGF.Builder.CreateGEP(CGF.Int8Ty, Address,
9487                                  llvm::ConstantInt::get(CGF.Int32Ty, Offset));
9488   }
9489 
9490   llvm::Value *encodeReturnAddress(CodeGen::CodeGenFunction &CGF,
9491                                    llvm::Value *Address) const override {
9492     int Offset;
9493     if (isAggregateTypeForABI(CGF.CurFnInfo->getReturnType()))
9494       Offset = -12;
9495     else
9496       Offset = -8;
9497     return CGF.Builder.CreateGEP(CGF.Int8Ty, Address,
9498                                  llvm::ConstantInt::get(CGF.Int32Ty, Offset));
9499   }
9500 };
9501 } // end anonymous namespace
9502 
9503 //===----------------------------------------------------------------------===//
9504 // SPARC v9 ABI Implementation.
9505 // Based on the SPARC Compliance Definition version 2.4.1.
9506 //
9507 // Function arguments a mapped to a nominal "parameter array" and promoted to
9508 // registers depending on their type. Each argument occupies 8 or 16 bytes in
9509 // the array, structs larger than 16 bytes are passed indirectly.
9510 //
9511 // One case requires special care:
9512 //
9513 //   struct mixed {
9514 //     int i;
9515 //     float f;
9516 //   };
9517 //
9518 // When a struct mixed is passed by value, it only occupies 8 bytes in the
9519 // parameter array, but the int is passed in an integer register, and the float
9520 // is passed in a floating point register. This is represented as two arguments
9521 // with the LLVM IR inreg attribute:
9522 //
9523 //   declare void f(i32 inreg %i, float inreg %f)
9524 //
9525 // The code generator will only allocate 4 bytes from the parameter array for
9526 // the inreg arguments. All other arguments are allocated a multiple of 8
9527 // bytes.
9528 //
9529 namespace {
9530 class SparcV9ABIInfo : public ABIInfo {
9531 public:
9532   SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
9533 
9534 private:
9535   ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
9536   void computeInfo(CGFunctionInfo &FI) const override;
9537   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9538                     QualType Ty) const override;
9539 
9540   // Coercion type builder for structs passed in registers. The coercion type
9541   // serves two purposes:
9542   //
9543   // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
9544   //    in registers.
9545   // 2. Expose aligned floating point elements as first-level elements, so the
9546   //    code generator knows to pass them in floating point registers.
9547   //
9548   // We also compute the InReg flag which indicates that the struct contains
9549   // aligned 32-bit floats.
9550   //
9551   struct CoerceBuilder {
9552     llvm::LLVMContext &Context;
9553     const llvm::DataLayout &DL;
9554     SmallVector<llvm::Type*, 8> Elems;
9555     uint64_t Size;
9556     bool InReg;
9557 
9558     CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
9559       : Context(c), DL(dl), Size(0), InReg(false) {}
9560 
9561     // Pad Elems with integers until Size is ToSize.
9562     void pad(uint64_t ToSize) {
9563       assert(ToSize >= Size && "Cannot remove elements");
9564       if (ToSize == Size)
9565         return;
9566 
9567       // Finish the current 64-bit word.
9568       uint64_t Aligned = llvm::alignTo(Size, 64);
9569       if (Aligned > Size && Aligned <= ToSize) {
9570         Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
9571         Size = Aligned;
9572       }
9573 
9574       // Add whole 64-bit words.
9575       while (Size + 64 <= ToSize) {
9576         Elems.push_back(llvm::Type::getInt64Ty(Context));
9577         Size += 64;
9578       }
9579 
9580       // Final in-word padding.
9581       if (Size < ToSize) {
9582         Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
9583         Size = ToSize;
9584       }
9585     }
9586 
9587     // Add a floating point element at Offset.
9588     void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
9589       // Unaligned floats are treated as integers.
9590       if (Offset % Bits)
9591         return;
9592       // The InReg flag is only required if there are any floats < 64 bits.
9593       if (Bits < 64)
9594         InReg = true;
9595       pad(Offset);
9596       Elems.push_back(Ty);
9597       Size = Offset + Bits;
9598     }
9599 
9600     // Add a struct type to the coercion type, starting at Offset (in bits).
9601     void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
9602       const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
9603       for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
9604         llvm::Type *ElemTy = StrTy->getElementType(i);
9605         uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
9606         switch (ElemTy->getTypeID()) {
9607         case llvm::Type::StructTyID:
9608           addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
9609           break;
9610         case llvm::Type::FloatTyID:
9611           addFloat(ElemOffset, ElemTy, 32);
9612           break;
9613         case llvm::Type::DoubleTyID:
9614           addFloat(ElemOffset, ElemTy, 64);
9615           break;
9616         case llvm::Type::FP128TyID:
9617           addFloat(ElemOffset, ElemTy, 128);
9618           break;
9619         case llvm::Type::PointerTyID:
9620           if (ElemOffset % 64 == 0) {
9621             pad(ElemOffset);
9622             Elems.push_back(ElemTy);
9623             Size += 64;
9624           }
9625           break;
9626         default:
9627           break;
9628         }
9629       }
9630     }
9631 
9632     // Check if Ty is a usable substitute for the coercion type.
9633     bool isUsableType(llvm::StructType *Ty) const {
9634       return llvm::makeArrayRef(Elems) == Ty->elements();
9635     }
9636 
9637     // Get the coercion type as a literal struct type.
9638     llvm::Type *getType() const {
9639       if (Elems.size() == 1)
9640         return Elems.front();
9641       else
9642         return llvm::StructType::get(Context, Elems);
9643     }
9644   };
9645 };
9646 } // end anonymous namespace
9647 
9648 ABIArgInfo
9649 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
9650   if (Ty->isVoidType())
9651     return ABIArgInfo::getIgnore();
9652 
9653   uint64_t Size = getContext().getTypeSize(Ty);
9654 
9655   // Anything too big to fit in registers is passed with an explicit indirect
9656   // pointer / sret pointer.
9657   if (Size > SizeLimit)
9658     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
9659 
9660   // Treat an enum type as its underlying type.
9661   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
9662     Ty = EnumTy->getDecl()->getIntegerType();
9663 
9664   // Integer types smaller than a register are extended.
9665   if (Size < 64 && Ty->isIntegerType())
9666     return ABIArgInfo::getExtend(Ty);
9667 
9668   if (const auto *EIT = Ty->getAs<BitIntType>())
9669     if (EIT->getNumBits() < 64)
9670       return ABIArgInfo::getExtend(Ty);
9671 
9672   // Other non-aggregates go in registers.
9673   if (!isAggregateTypeForABI(Ty))
9674     return ABIArgInfo::getDirect();
9675 
9676   // If a C++ object has either a non-trivial copy constructor or a non-trivial
9677   // destructor, it is passed with an explicit indirect pointer / sret pointer.
9678   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
9679     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
9680 
9681   // This is a small aggregate type that should be passed in registers.
9682   // Build a coercion type from the LLVM struct type.
9683   llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
9684   if (!StrTy)
9685     return ABIArgInfo::getDirect();
9686 
9687   CoerceBuilder CB(getVMContext(), getDataLayout());
9688   CB.addStruct(0, StrTy);
9689   CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
9690 
9691   // Try to use the original type for coercion.
9692   llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
9693 
9694   if (CB.InReg)
9695     return ABIArgInfo::getDirectInReg(CoerceTy);
9696   else
9697     return ABIArgInfo::getDirect(CoerceTy);
9698 }
9699 
9700 Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9701                                   QualType Ty) const {
9702   ABIArgInfo AI = classifyType(Ty, 16 * 8);
9703   llvm::Type *ArgTy = CGT.ConvertType(Ty);
9704   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
9705     AI.setCoerceToType(ArgTy);
9706 
9707   CharUnits SlotSize = CharUnits::fromQuantity(8);
9708 
9709   CGBuilderTy &Builder = CGF.Builder;
9710   Address Addr =
9711       Address::deprecated(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
9712   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
9713 
9714   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
9715 
9716   Address ArgAddr = Address::invalid();
9717   CharUnits Stride;
9718   switch (AI.getKind()) {
9719   case ABIArgInfo::Expand:
9720   case ABIArgInfo::CoerceAndExpand:
9721   case ABIArgInfo::InAlloca:
9722     llvm_unreachable("Unsupported ABI kind for va_arg");
9723 
9724   case ABIArgInfo::Extend: {
9725     Stride = SlotSize;
9726     CharUnits Offset = SlotSize - TypeInfo.Width;
9727     ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
9728     break;
9729   }
9730 
9731   case ABIArgInfo::Direct: {
9732     auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
9733     Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
9734     ArgAddr = Addr;
9735     break;
9736   }
9737 
9738   case ABIArgInfo::Indirect:
9739   case ABIArgInfo::IndirectAliased:
9740     Stride = SlotSize;
9741     ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
9742     ArgAddr = Address::deprecated(Builder.CreateLoad(ArgAddr, "indirect.arg"),
9743                                   TypeInfo.Align);
9744     break;
9745 
9746   case ABIArgInfo::Ignore:
9747     return Address(llvm::UndefValue::get(ArgPtrTy), ArgTy, TypeInfo.Align);
9748   }
9749 
9750   // Update VAList.
9751   Address NextPtr = Builder.CreateConstInBoundsByteGEP(Addr, Stride, "ap.next");
9752   Builder.CreateStore(NextPtr.getPointer(), VAListAddr);
9753 
9754   return Builder.CreateElementBitCast(ArgAddr, ArgTy, "arg.addr");
9755 }
9756 
9757 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
9758   FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
9759   for (auto &I : FI.arguments())
9760     I.info = classifyType(I.type, 16 * 8);
9761 }
9762 
9763 namespace {
9764 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
9765 public:
9766   SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
9767       : TargetCodeGenInfo(std::make_unique<SparcV9ABIInfo>(CGT)) {}
9768 
9769   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
9770     return 14;
9771   }
9772 
9773   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
9774                                llvm::Value *Address) const override;
9775 
9776   llvm::Value *decodeReturnAddress(CodeGen::CodeGenFunction &CGF,
9777                                    llvm::Value *Address) const override {
9778     return CGF.Builder.CreateGEP(CGF.Int8Ty, Address,
9779                                  llvm::ConstantInt::get(CGF.Int32Ty, 8));
9780   }
9781 
9782   llvm::Value *encodeReturnAddress(CodeGen::CodeGenFunction &CGF,
9783                                    llvm::Value *Address) const override {
9784     return CGF.Builder.CreateGEP(CGF.Int8Ty, Address,
9785                                  llvm::ConstantInt::get(CGF.Int32Ty, -8));
9786   }
9787 };
9788 } // end anonymous namespace
9789 
9790 bool
9791 SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
9792                                                 llvm::Value *Address) const {
9793   // This is calculated from the LLVM and GCC tables and verified
9794   // against gcc output.  AFAIK all ABIs use the same encoding.
9795 
9796   CodeGen::CGBuilderTy &Builder = CGF.Builder;
9797 
9798   llvm::IntegerType *i8 = CGF.Int8Ty;
9799   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
9800   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
9801 
9802   // 0-31: the 8-byte general-purpose registers
9803   AssignToArrayRange(Builder, Address, Eight8, 0, 31);
9804 
9805   // 32-63: f0-31, the 4-byte floating-point registers
9806   AssignToArrayRange(Builder, Address, Four8, 32, 63);
9807 
9808   //   Y   = 64
9809   //   PSR = 65
9810   //   WIM = 66
9811   //   TBR = 67
9812   //   PC  = 68
9813   //   NPC = 69
9814   //   FSR = 70
9815   //   CSR = 71
9816   AssignToArrayRange(Builder, Address, Eight8, 64, 71);
9817 
9818   // 72-87: d0-15, the 8-byte floating-point registers
9819   AssignToArrayRange(Builder, Address, Eight8, 72, 87);
9820 
9821   return false;
9822 }
9823 
9824 // ARC ABI implementation.
9825 namespace {
9826 
9827 class ARCABIInfo : public DefaultABIInfo {
9828 public:
9829   using DefaultABIInfo::DefaultABIInfo;
9830 
9831 private:
9832   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9833                     QualType Ty) const override;
9834 
9835   void updateState(const ABIArgInfo &Info, QualType Ty, CCState &State) const {
9836     if (!State.FreeRegs)
9837       return;
9838     if (Info.isIndirect() && Info.getInReg())
9839       State.FreeRegs--;
9840     else if (Info.isDirect() && Info.getInReg()) {
9841       unsigned sz = (getContext().getTypeSize(Ty) + 31) / 32;
9842       if (sz < State.FreeRegs)
9843         State.FreeRegs -= sz;
9844       else
9845         State.FreeRegs = 0;
9846     }
9847   }
9848 
9849   void computeInfo(CGFunctionInfo &FI) const override {
9850     CCState State(FI);
9851     // ARC uses 8 registers to pass arguments.
9852     State.FreeRegs = 8;
9853 
9854     if (!getCXXABI().classifyReturnType(FI))
9855       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
9856     updateState(FI.getReturnInfo(), FI.getReturnType(), State);
9857     for (auto &I : FI.arguments()) {
9858       I.info = classifyArgumentType(I.type, State.FreeRegs);
9859       updateState(I.info, I.type, State);
9860     }
9861   }
9862 
9863   ABIArgInfo getIndirectByRef(QualType Ty, bool HasFreeRegs) const;
9864   ABIArgInfo getIndirectByValue(QualType Ty) const;
9865   ABIArgInfo classifyArgumentType(QualType Ty, uint8_t FreeRegs) const;
9866   ABIArgInfo classifyReturnType(QualType RetTy) const;
9867 };
9868 
9869 class ARCTargetCodeGenInfo : public TargetCodeGenInfo {
9870 public:
9871   ARCTargetCodeGenInfo(CodeGenTypes &CGT)
9872       : TargetCodeGenInfo(std::make_unique<ARCABIInfo>(CGT)) {}
9873 };
9874 
9875 
9876 ABIArgInfo ARCABIInfo::getIndirectByRef(QualType Ty, bool HasFreeRegs) const {
9877   return HasFreeRegs ? getNaturalAlignIndirectInReg(Ty) :
9878                        getNaturalAlignIndirect(Ty, false);
9879 }
9880 
9881 ABIArgInfo ARCABIInfo::getIndirectByValue(QualType Ty) const {
9882   // Compute the byval alignment.
9883   const unsigned MinABIStackAlignInBytes = 4;
9884   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
9885   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
9886                                  TypeAlign > MinABIStackAlignInBytes);
9887 }
9888 
9889 Address ARCABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9890                               QualType Ty) const {
9891   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
9892                           getContext().getTypeInfoInChars(Ty),
9893                           CharUnits::fromQuantity(4), true);
9894 }
9895 
9896 ABIArgInfo ARCABIInfo::classifyArgumentType(QualType Ty,
9897                                             uint8_t FreeRegs) const {
9898   // Handle the generic C++ ABI.
9899   const RecordType *RT = Ty->getAs<RecordType>();
9900   if (RT) {
9901     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
9902     if (RAA == CGCXXABI::RAA_Indirect)
9903       return getIndirectByRef(Ty, FreeRegs > 0);
9904 
9905     if (RAA == CGCXXABI::RAA_DirectInMemory)
9906       return getIndirectByValue(Ty);
9907   }
9908 
9909   // Treat an enum type as its underlying type.
9910   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
9911     Ty = EnumTy->getDecl()->getIntegerType();
9912 
9913   auto SizeInRegs = llvm::alignTo(getContext().getTypeSize(Ty), 32) / 32;
9914 
9915   if (isAggregateTypeForABI(Ty)) {
9916     // Structures with flexible arrays are always indirect.
9917     if (RT && RT->getDecl()->hasFlexibleArrayMember())
9918       return getIndirectByValue(Ty);
9919 
9920     // Ignore empty structs/unions.
9921     if (isEmptyRecord(getContext(), Ty, true))
9922       return ABIArgInfo::getIgnore();
9923 
9924     llvm::LLVMContext &LLVMContext = getVMContext();
9925 
9926     llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
9927     SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
9928     llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
9929 
9930     return FreeRegs >= SizeInRegs ?
9931         ABIArgInfo::getDirectInReg(Result) :
9932         ABIArgInfo::getDirect(Result, 0, nullptr, false);
9933   }
9934 
9935   if (const auto *EIT = Ty->getAs<BitIntType>())
9936     if (EIT->getNumBits() > 64)
9937       return getIndirectByValue(Ty);
9938 
9939   return isPromotableIntegerTypeForABI(Ty)
9940              ? (FreeRegs >= SizeInRegs ? ABIArgInfo::getExtendInReg(Ty)
9941                                        : ABIArgInfo::getExtend(Ty))
9942              : (FreeRegs >= SizeInRegs ? ABIArgInfo::getDirectInReg()
9943                                        : ABIArgInfo::getDirect());
9944 }
9945 
9946 ABIArgInfo ARCABIInfo::classifyReturnType(QualType RetTy) const {
9947   if (RetTy->isAnyComplexType())
9948     return ABIArgInfo::getDirectInReg();
9949 
9950   // Arguments of size > 4 registers are indirect.
9951   auto RetSize = llvm::alignTo(getContext().getTypeSize(RetTy), 32) / 32;
9952   if (RetSize > 4)
9953     return getIndirectByRef(RetTy, /*HasFreeRegs*/ true);
9954 
9955   return DefaultABIInfo::classifyReturnType(RetTy);
9956 }
9957 
9958 } // End anonymous namespace.
9959 
9960 //===----------------------------------------------------------------------===//
9961 // XCore ABI Implementation
9962 //===----------------------------------------------------------------------===//
9963 
9964 namespace {
9965 
9966 /// A SmallStringEnc instance is used to build up the TypeString by passing
9967 /// it by reference between functions that append to it.
9968 typedef llvm::SmallString<128> SmallStringEnc;
9969 
9970 /// TypeStringCache caches the meta encodings of Types.
9971 ///
9972 /// The reason for caching TypeStrings is two fold:
9973 ///   1. To cache a type's encoding for later uses;
9974 ///   2. As a means to break recursive member type inclusion.
9975 ///
9976 /// A cache Entry can have a Status of:
9977 ///   NonRecursive:   The type encoding is not recursive;
9978 ///   Recursive:      The type encoding is recursive;
9979 ///   Incomplete:     An incomplete TypeString;
9980 ///   IncompleteUsed: An incomplete TypeString that has been used in a
9981 ///                   Recursive type encoding.
9982 ///
9983 /// A NonRecursive entry will have all of its sub-members expanded as fully
9984 /// as possible. Whilst it may contain types which are recursive, the type
9985 /// itself is not recursive and thus its encoding may be safely used whenever
9986 /// the type is encountered.
9987 ///
9988 /// A Recursive entry will have all of its sub-members expanded as fully as
9989 /// possible. The type itself is recursive and it may contain other types which
9990 /// are recursive. The Recursive encoding must not be used during the expansion
9991 /// of a recursive type's recursive branch. For simplicity the code uses
9992 /// IncompleteCount to reject all usage of Recursive encodings for member types.
9993 ///
9994 /// An Incomplete entry is always a RecordType and only encodes its
9995 /// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
9996 /// are placed into the cache during type expansion as a means to identify and
9997 /// handle recursive inclusion of types as sub-members. If there is recursion
9998 /// the entry becomes IncompleteUsed.
9999 ///
10000 /// During the expansion of a RecordType's members:
10001 ///
10002 ///   If the cache contains a NonRecursive encoding for the member type, the
10003 ///   cached encoding is used;
10004 ///
10005 ///   If the cache contains a Recursive encoding for the member type, the
10006 ///   cached encoding is 'Swapped' out, as it may be incorrect, and...
10007 ///
10008 ///   If the member is a RecordType, an Incomplete encoding is placed into the
10009 ///   cache to break potential recursive inclusion of itself as a sub-member;
10010 ///
10011 ///   Once a member RecordType has been expanded, its temporary incomplete
10012 ///   entry is removed from the cache. If a Recursive encoding was swapped out
10013 ///   it is swapped back in;
10014 ///
10015 ///   If an incomplete entry is used to expand a sub-member, the incomplete
10016 ///   entry is marked as IncompleteUsed. The cache keeps count of how many
10017 ///   IncompleteUsed entries it currently contains in IncompleteUsedCount;
10018 ///
10019 ///   If a member's encoding is found to be a NonRecursive or Recursive viz:
10020 ///   IncompleteUsedCount==0, the member's encoding is added to the cache.
10021 ///   Else the member is part of a recursive type and thus the recursion has
10022 ///   been exited too soon for the encoding to be correct for the member.
10023 ///
10024 class TypeStringCache {
10025   enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
10026   struct Entry {
10027     std::string Str;     // The encoded TypeString for the type.
10028     enum Status State;   // Information about the encoding in 'Str'.
10029     std::string Swapped; // A temporary place holder for a Recursive encoding
10030                          // during the expansion of RecordType's members.
10031   };
10032   std::map<const IdentifierInfo *, struct Entry> Map;
10033   unsigned IncompleteCount;     // Number of Incomplete entries in the Map.
10034   unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
10035 public:
10036   TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
10037   void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
10038   bool removeIncomplete(const IdentifierInfo *ID);
10039   void addIfComplete(const IdentifierInfo *ID, StringRef Str,
10040                      bool IsRecursive);
10041   StringRef lookupStr(const IdentifierInfo *ID);
10042 };
10043 
10044 /// TypeString encodings for enum & union fields must be order.
10045 /// FieldEncoding is a helper for this ordering process.
10046 class FieldEncoding {
10047   bool HasName;
10048   std::string Enc;
10049 public:
10050   FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
10051   StringRef str() { return Enc; }
10052   bool operator<(const FieldEncoding &rhs) const {
10053     if (HasName != rhs.HasName) return HasName;
10054     return Enc < rhs.Enc;
10055   }
10056 };
10057 
10058 class XCoreABIInfo : public DefaultABIInfo {
10059 public:
10060   XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
10061   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
10062                     QualType Ty) const override;
10063 };
10064 
10065 class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
10066   mutable TypeStringCache TSC;
10067   void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
10068                     const CodeGen::CodeGenModule &M) const;
10069 
10070 public:
10071   XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
10072       : TargetCodeGenInfo(std::make_unique<XCoreABIInfo>(CGT)) {}
10073   void emitTargetMetadata(CodeGen::CodeGenModule &CGM,
10074                           const llvm::MapVector<GlobalDecl, StringRef>
10075                               &MangledDeclNames) const override;
10076 };
10077 
10078 } // End anonymous namespace.
10079 
10080 // TODO: this implementation is likely now redundant with the default
10081 // EmitVAArg.
10082 Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
10083                                 QualType Ty) const {
10084   CGBuilderTy &Builder = CGF.Builder;
10085 
10086   // Get the VAList.
10087   CharUnits SlotSize = CharUnits::fromQuantity(4);
10088   Address AP = Address::deprecated(Builder.CreateLoad(VAListAddr), SlotSize);
10089 
10090   // Handle the argument.
10091   ABIArgInfo AI = classifyArgumentType(Ty);
10092   CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
10093   llvm::Type *ArgTy = CGT.ConvertType(Ty);
10094   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
10095     AI.setCoerceToType(ArgTy);
10096   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
10097 
10098   Address Val = Address::invalid();
10099   CharUnits ArgSize = CharUnits::Zero();
10100   switch (AI.getKind()) {
10101   case ABIArgInfo::Expand:
10102   case ABIArgInfo::CoerceAndExpand:
10103   case ABIArgInfo::InAlloca:
10104     llvm_unreachable("Unsupported ABI kind for va_arg");
10105   case ABIArgInfo::Ignore:
10106     Val = Address(llvm::UndefValue::get(ArgPtrTy), ArgTy, TypeAlign);
10107     ArgSize = CharUnits::Zero();
10108     break;
10109   case ABIArgInfo::Extend:
10110   case ABIArgInfo::Direct:
10111     Val = Builder.CreateElementBitCast(AP, ArgTy);
10112     ArgSize = CharUnits::fromQuantity(
10113         getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
10114     ArgSize = ArgSize.alignTo(SlotSize);
10115     break;
10116   case ABIArgInfo::Indirect:
10117   case ABIArgInfo::IndirectAliased:
10118     Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
10119     Val = Address::deprecated(Builder.CreateLoad(Val), TypeAlign);
10120     ArgSize = SlotSize;
10121     break;
10122   }
10123 
10124   // Increment the VAList.
10125   if (!ArgSize.isZero()) {
10126     Address APN = Builder.CreateConstInBoundsByteGEP(AP, ArgSize);
10127     Builder.CreateStore(APN.getPointer(), VAListAddr);
10128   }
10129 
10130   return Val;
10131 }
10132 
10133 /// During the expansion of a RecordType, an incomplete TypeString is placed
10134 /// into the cache as a means to identify and break recursion.
10135 /// If there is a Recursive encoding in the cache, it is swapped out and will
10136 /// be reinserted by removeIncomplete().
10137 /// All other types of encoding should have been used rather than arriving here.
10138 void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
10139                                     std::string StubEnc) {
10140   if (!ID)
10141     return;
10142   Entry &E = Map[ID];
10143   assert( (E.Str.empty() || E.State == Recursive) &&
10144          "Incorrectly use of addIncomplete");
10145   assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
10146   E.Swapped.swap(E.Str); // swap out the Recursive
10147   E.Str.swap(StubEnc);
10148   E.State = Incomplete;
10149   ++IncompleteCount;
10150 }
10151 
10152 /// Once the RecordType has been expanded, the temporary incomplete TypeString
10153 /// must be removed from the cache.
10154 /// If a Recursive was swapped out by addIncomplete(), it will be replaced.
10155 /// Returns true if the RecordType was defined recursively.
10156 bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
10157   if (!ID)
10158     return false;
10159   auto I = Map.find(ID);
10160   assert(I != Map.end() && "Entry not present");
10161   Entry &E = I->second;
10162   assert( (E.State == Incomplete ||
10163            E.State == IncompleteUsed) &&
10164          "Entry must be an incomplete type");
10165   bool IsRecursive = false;
10166   if (E.State == IncompleteUsed) {
10167     // We made use of our Incomplete encoding, thus we are recursive.
10168     IsRecursive = true;
10169     --IncompleteUsedCount;
10170   }
10171   if (E.Swapped.empty())
10172     Map.erase(I);
10173   else {
10174     // Swap the Recursive back.
10175     E.Swapped.swap(E.Str);
10176     E.Swapped.clear();
10177     E.State = Recursive;
10178   }
10179   --IncompleteCount;
10180   return IsRecursive;
10181 }
10182 
10183 /// Add the encoded TypeString to the cache only if it is NonRecursive or
10184 /// Recursive (viz: all sub-members were expanded as fully as possible).
10185 void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
10186                                     bool IsRecursive) {
10187   if (!ID || IncompleteUsedCount)
10188     return; // No key or it is is an incomplete sub-type so don't add.
10189   Entry &E = Map[ID];
10190   if (IsRecursive && !E.Str.empty()) {
10191     assert(E.State==Recursive && E.Str.size() == Str.size() &&
10192            "This is not the same Recursive entry");
10193     // The parent container was not recursive after all, so we could have used
10194     // this Recursive sub-member entry after all, but we assumed the worse when
10195     // we started viz: IncompleteCount!=0.
10196     return;
10197   }
10198   assert(E.Str.empty() && "Entry already present");
10199   E.Str = Str.str();
10200   E.State = IsRecursive? Recursive : NonRecursive;
10201 }
10202 
10203 /// Return a cached TypeString encoding for the ID. If there isn't one, or we
10204 /// are recursively expanding a type (IncompleteCount != 0) and the cached
10205 /// encoding is Recursive, return an empty StringRef.
10206 StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
10207   if (!ID)
10208     return StringRef();   // We have no key.
10209   auto I = Map.find(ID);
10210   if (I == Map.end())
10211     return StringRef();   // We have no encoding.
10212   Entry &E = I->second;
10213   if (E.State == Recursive && IncompleteCount)
10214     return StringRef();   // We don't use Recursive encodings for member types.
10215 
10216   if (E.State == Incomplete) {
10217     // The incomplete type is being used to break out of recursion.
10218     E.State = IncompleteUsed;
10219     ++IncompleteUsedCount;
10220   }
10221   return E.Str;
10222 }
10223 
10224 /// The XCore ABI includes a type information section that communicates symbol
10225 /// type information to the linker. The linker uses this information to verify
10226 /// safety/correctness of things such as array bound and pointers et al.
10227 /// The ABI only requires C (and XC) language modules to emit TypeStrings.
10228 /// This type information (TypeString) is emitted into meta data for all global
10229 /// symbols: definitions, declarations, functions & variables.
10230 ///
10231 /// The TypeString carries type, qualifier, name, size & value details.
10232 /// Please see 'Tools Development Guide' section 2.16.2 for format details:
10233 /// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
10234 /// The output is tested by test/CodeGen/xcore-stringtype.c.
10235 ///
10236 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
10237                           const CodeGen::CodeGenModule &CGM,
10238                           TypeStringCache &TSC);
10239 
10240 /// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
10241 void XCoreTargetCodeGenInfo::emitTargetMD(
10242     const Decl *D, llvm::GlobalValue *GV,
10243     const CodeGen::CodeGenModule &CGM) const {
10244   SmallStringEnc Enc;
10245   if (getTypeString(Enc, D, CGM, TSC)) {
10246     llvm::LLVMContext &Ctx = CGM.getModule().getContext();
10247     llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
10248                                 llvm::MDString::get(Ctx, Enc.str())};
10249     llvm::NamedMDNode *MD =
10250       CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
10251     MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
10252   }
10253 }
10254 
10255 void XCoreTargetCodeGenInfo::emitTargetMetadata(
10256     CodeGen::CodeGenModule &CGM,
10257     const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames) const {
10258   // Warning, new MangledDeclNames may be appended within this loop.
10259   // We rely on MapVector insertions adding new elements to the end
10260   // of the container.
10261   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
10262     auto Val = *(MangledDeclNames.begin() + I);
10263     llvm::GlobalValue *GV = CGM.GetGlobalValue(Val.second);
10264     if (GV) {
10265       const Decl *D = Val.first.getDecl()->getMostRecentDecl();
10266       emitTargetMD(D, GV, CGM);
10267     }
10268   }
10269 }
10270 
10271 //===----------------------------------------------------------------------===//
10272 // Base ABI and target codegen info implementation common between SPIR and
10273 // SPIR-V.
10274 //===----------------------------------------------------------------------===//
10275 
10276 namespace {
10277 class CommonSPIRABIInfo : public DefaultABIInfo {
10278 public:
10279   CommonSPIRABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) { setCCs(); }
10280 
10281 private:
10282   void setCCs();
10283 };
10284 
10285 class SPIRVABIInfo : public CommonSPIRABIInfo {
10286 public:
10287   SPIRVABIInfo(CodeGenTypes &CGT) : CommonSPIRABIInfo(CGT) {}
10288   void computeInfo(CGFunctionInfo &FI) const override;
10289 
10290 private:
10291   ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
10292 };
10293 } // end anonymous namespace
10294 namespace {
10295 class CommonSPIRTargetCodeGenInfo : public TargetCodeGenInfo {
10296 public:
10297   CommonSPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
10298       : TargetCodeGenInfo(std::make_unique<CommonSPIRABIInfo>(CGT)) {}
10299   CommonSPIRTargetCodeGenInfo(std::unique_ptr<ABIInfo> ABIInfo)
10300       : TargetCodeGenInfo(std::move(ABIInfo)) {}
10301 
10302   LangAS getASTAllocaAddressSpace() const override {
10303     return getLangASFromTargetAS(
10304         getABIInfo().getDataLayout().getAllocaAddrSpace());
10305   }
10306 
10307   unsigned getOpenCLKernelCallingConv() const override;
10308 };
10309 class SPIRVTargetCodeGenInfo : public CommonSPIRTargetCodeGenInfo {
10310 public:
10311   SPIRVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
10312       : CommonSPIRTargetCodeGenInfo(std::make_unique<SPIRVABIInfo>(CGT)) {}
10313   void setCUDAKernelCallingConvention(const FunctionType *&FT) const override;
10314 };
10315 } // End anonymous namespace.
10316 
10317 void CommonSPIRABIInfo::setCCs() {
10318   assert(getRuntimeCC() == llvm::CallingConv::C);
10319   RuntimeCC = llvm::CallingConv::SPIR_FUNC;
10320 }
10321 
10322 ABIArgInfo SPIRVABIInfo::classifyKernelArgumentType(QualType Ty) const {
10323   if (getContext().getLangOpts().CUDAIsDevice) {
10324     // Coerce pointer arguments with default address space to CrossWorkGroup
10325     // pointers for HIPSPV/CUDASPV. When the language mode is HIP/CUDA, the
10326     // SPIRTargetInfo maps cuda_device to SPIR-V's CrossWorkGroup address space.
10327     llvm::Type *LTy = CGT.ConvertType(Ty);
10328     auto DefaultAS = getContext().getTargetAddressSpace(LangAS::Default);
10329     auto GlobalAS = getContext().getTargetAddressSpace(LangAS::cuda_device);
10330     auto *PtrTy = llvm::dyn_cast<llvm::PointerType>(LTy);
10331     if (PtrTy && PtrTy->getAddressSpace() == DefaultAS) {
10332       LTy = llvm::PointerType::getWithSamePointeeType(PtrTy, GlobalAS);
10333       return ABIArgInfo::getDirect(LTy, 0, nullptr, false);
10334     }
10335   }
10336   return classifyArgumentType(Ty);
10337 }
10338 
10339 void SPIRVABIInfo::computeInfo(CGFunctionInfo &FI) const {
10340   // The logic is same as in DefaultABIInfo with an exception on the kernel
10341   // arguments handling.
10342   llvm::CallingConv::ID CC = FI.getCallingConvention();
10343 
10344   if (!getCXXABI().classifyReturnType(FI))
10345     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
10346 
10347   for (auto &I : FI.arguments()) {
10348     if (CC == llvm::CallingConv::SPIR_KERNEL) {
10349       I.info = classifyKernelArgumentType(I.type);
10350     } else {
10351       I.info = classifyArgumentType(I.type);
10352     }
10353   }
10354 }
10355 
10356 namespace clang {
10357 namespace CodeGen {
10358 void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) {
10359   if (CGM.getTarget().getTriple().isSPIRV())
10360     SPIRVABIInfo(CGM.getTypes()).computeInfo(FI);
10361   else
10362     CommonSPIRABIInfo(CGM.getTypes()).computeInfo(FI);
10363 }
10364 }
10365 }
10366 
10367 unsigned CommonSPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
10368   return llvm::CallingConv::SPIR_KERNEL;
10369 }
10370 
10371 void SPIRVTargetCodeGenInfo::setCUDAKernelCallingConvention(
10372     const FunctionType *&FT) const {
10373   // Convert HIP kernels to SPIR-V kernels.
10374   if (getABIInfo().getContext().getLangOpts().HIP) {
10375     FT = getABIInfo().getContext().adjustFunctionType(
10376         FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel));
10377     return;
10378   }
10379 }
10380 
10381 static bool appendType(SmallStringEnc &Enc, QualType QType,
10382                        const CodeGen::CodeGenModule &CGM,
10383                        TypeStringCache &TSC);
10384 
10385 /// Helper function for appendRecordType().
10386 /// Builds a SmallVector containing the encoded field types in declaration
10387 /// order.
10388 static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
10389                              const RecordDecl *RD,
10390                              const CodeGen::CodeGenModule &CGM,
10391                              TypeStringCache &TSC) {
10392   for (const auto *Field : RD->fields()) {
10393     SmallStringEnc Enc;
10394     Enc += "m(";
10395     Enc += Field->getName();
10396     Enc += "){";
10397     if (Field->isBitField()) {
10398       Enc += "b(";
10399       llvm::raw_svector_ostream OS(Enc);
10400       OS << Field->getBitWidthValue(CGM.getContext());
10401       Enc += ':';
10402     }
10403     if (!appendType(Enc, Field->getType(), CGM, TSC))
10404       return false;
10405     if (Field->isBitField())
10406       Enc += ')';
10407     Enc += '}';
10408     FE.emplace_back(!Field->getName().empty(), Enc);
10409   }
10410   return true;
10411 }
10412 
10413 /// Appends structure and union types to Enc and adds encoding to cache.
10414 /// Recursively calls appendType (via extractFieldType) for each field.
10415 /// Union types have their fields ordered according to the ABI.
10416 static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
10417                              const CodeGen::CodeGenModule &CGM,
10418                              TypeStringCache &TSC, const IdentifierInfo *ID) {
10419   // Append the cached TypeString if we have one.
10420   StringRef TypeString = TSC.lookupStr(ID);
10421   if (!TypeString.empty()) {
10422     Enc += TypeString;
10423     return true;
10424   }
10425 
10426   // Start to emit an incomplete TypeString.
10427   size_t Start = Enc.size();
10428   Enc += (RT->isUnionType()? 'u' : 's');
10429   Enc += '(';
10430   if (ID)
10431     Enc += ID->getName();
10432   Enc += "){";
10433 
10434   // We collect all encoded fields and order as necessary.
10435   bool IsRecursive = false;
10436   const RecordDecl *RD = RT->getDecl()->getDefinition();
10437   if (RD && !RD->field_empty()) {
10438     // An incomplete TypeString stub is placed in the cache for this RecordType
10439     // so that recursive calls to this RecordType will use it whilst building a
10440     // complete TypeString for this RecordType.
10441     SmallVector<FieldEncoding, 16> FE;
10442     std::string StubEnc(Enc.substr(Start).str());
10443     StubEnc += '}';  // StubEnc now holds a valid incomplete TypeString.
10444     TSC.addIncomplete(ID, std::move(StubEnc));
10445     if (!extractFieldType(FE, RD, CGM, TSC)) {
10446       (void) TSC.removeIncomplete(ID);
10447       return false;
10448     }
10449     IsRecursive = TSC.removeIncomplete(ID);
10450     // The ABI requires unions to be sorted but not structures.
10451     // See FieldEncoding::operator< for sort algorithm.
10452     if (RT->isUnionType())
10453       llvm::sort(FE);
10454     // We can now complete the TypeString.
10455     unsigned E = FE.size();
10456     for (unsigned I = 0; I != E; ++I) {
10457       if (I)
10458         Enc += ',';
10459       Enc += FE[I].str();
10460     }
10461   }
10462   Enc += '}';
10463   TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
10464   return true;
10465 }
10466 
10467 /// Appends enum types to Enc and adds the encoding to the cache.
10468 static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
10469                            TypeStringCache &TSC,
10470                            const IdentifierInfo *ID) {
10471   // Append the cached TypeString if we have one.
10472   StringRef TypeString = TSC.lookupStr(ID);
10473   if (!TypeString.empty()) {
10474     Enc += TypeString;
10475     return true;
10476   }
10477 
10478   size_t Start = Enc.size();
10479   Enc += "e(";
10480   if (ID)
10481     Enc += ID->getName();
10482   Enc += "){";
10483 
10484   // We collect all encoded enumerations and order them alphanumerically.
10485   if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
10486     SmallVector<FieldEncoding, 16> FE;
10487     for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
10488          ++I) {
10489       SmallStringEnc EnumEnc;
10490       EnumEnc += "m(";
10491       EnumEnc += I->getName();
10492       EnumEnc += "){";
10493       I->getInitVal().toString(EnumEnc);
10494       EnumEnc += '}';
10495       FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
10496     }
10497     llvm::sort(FE);
10498     unsigned E = FE.size();
10499     for (unsigned I = 0; I != E; ++I) {
10500       if (I)
10501         Enc += ',';
10502       Enc += FE[I].str();
10503     }
10504   }
10505   Enc += '}';
10506   TSC.addIfComplete(ID, Enc.substr(Start), false);
10507   return true;
10508 }
10509 
10510 /// Appends type's qualifier to Enc.
10511 /// This is done prior to appending the type's encoding.
10512 static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
10513   // Qualifiers are emitted in alphabetical order.
10514   static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
10515   int Lookup = 0;
10516   if (QT.isConstQualified())
10517     Lookup += 1<<0;
10518   if (QT.isRestrictQualified())
10519     Lookup += 1<<1;
10520   if (QT.isVolatileQualified())
10521     Lookup += 1<<2;
10522   Enc += Table[Lookup];
10523 }
10524 
10525 /// Appends built-in types to Enc.
10526 static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
10527   const char *EncType;
10528   switch (BT->getKind()) {
10529     case BuiltinType::Void:
10530       EncType = "0";
10531       break;
10532     case BuiltinType::Bool:
10533       EncType = "b";
10534       break;
10535     case BuiltinType::Char_U:
10536       EncType = "uc";
10537       break;
10538     case BuiltinType::UChar:
10539       EncType = "uc";
10540       break;
10541     case BuiltinType::SChar:
10542       EncType = "sc";
10543       break;
10544     case BuiltinType::UShort:
10545       EncType = "us";
10546       break;
10547     case BuiltinType::Short:
10548       EncType = "ss";
10549       break;
10550     case BuiltinType::UInt:
10551       EncType = "ui";
10552       break;
10553     case BuiltinType::Int:
10554       EncType = "si";
10555       break;
10556     case BuiltinType::ULong:
10557       EncType = "ul";
10558       break;
10559     case BuiltinType::Long:
10560       EncType = "sl";
10561       break;
10562     case BuiltinType::ULongLong:
10563       EncType = "ull";
10564       break;
10565     case BuiltinType::LongLong:
10566       EncType = "sll";
10567       break;
10568     case BuiltinType::Float:
10569       EncType = "ft";
10570       break;
10571     case BuiltinType::Double:
10572       EncType = "d";
10573       break;
10574     case BuiltinType::LongDouble:
10575       EncType = "ld";
10576       break;
10577     default:
10578       return false;
10579   }
10580   Enc += EncType;
10581   return true;
10582 }
10583 
10584 /// Appends a pointer encoding to Enc before calling appendType for the pointee.
10585 static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
10586                               const CodeGen::CodeGenModule &CGM,
10587                               TypeStringCache &TSC) {
10588   Enc += "p(";
10589   if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
10590     return false;
10591   Enc += ')';
10592   return true;
10593 }
10594 
10595 /// Appends array encoding to Enc before calling appendType for the element.
10596 static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
10597                             const ArrayType *AT,
10598                             const CodeGen::CodeGenModule &CGM,
10599                             TypeStringCache &TSC, StringRef NoSizeEnc) {
10600   if (AT->getSizeModifier() != ArrayType::Normal)
10601     return false;
10602   Enc += "a(";
10603   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
10604     CAT->getSize().toStringUnsigned(Enc);
10605   else
10606     Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
10607   Enc += ':';
10608   // The Qualifiers should be attached to the type rather than the array.
10609   appendQualifier(Enc, QT);
10610   if (!appendType(Enc, AT->getElementType(), CGM, TSC))
10611     return false;
10612   Enc += ')';
10613   return true;
10614 }
10615 
10616 /// Appends a function encoding to Enc, calling appendType for the return type
10617 /// and the arguments.
10618 static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
10619                              const CodeGen::CodeGenModule &CGM,
10620                              TypeStringCache &TSC) {
10621   Enc += "f{";
10622   if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
10623     return false;
10624   Enc += "}(";
10625   if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
10626     // N.B. we are only interested in the adjusted param types.
10627     auto I = FPT->param_type_begin();
10628     auto E = FPT->param_type_end();
10629     if (I != E) {
10630       do {
10631         if (!appendType(Enc, *I, CGM, TSC))
10632           return false;
10633         ++I;
10634         if (I != E)
10635           Enc += ',';
10636       } while (I != E);
10637       if (FPT->isVariadic())
10638         Enc += ",va";
10639     } else {
10640       if (FPT->isVariadic())
10641         Enc += "va";
10642       else
10643         Enc += '0';
10644     }
10645   }
10646   Enc += ')';
10647   return true;
10648 }
10649 
10650 /// Handles the type's qualifier before dispatching a call to handle specific
10651 /// type encodings.
10652 static bool appendType(SmallStringEnc &Enc, QualType QType,
10653                        const CodeGen::CodeGenModule &CGM,
10654                        TypeStringCache &TSC) {
10655 
10656   QualType QT = QType.getCanonicalType();
10657 
10658   if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
10659     // The Qualifiers should be attached to the type rather than the array.
10660     // Thus we don't call appendQualifier() here.
10661     return appendArrayType(Enc, QT, AT, CGM, TSC, "");
10662 
10663   appendQualifier(Enc, QT);
10664 
10665   if (const BuiltinType *BT = QT->getAs<BuiltinType>())
10666     return appendBuiltinType(Enc, BT);
10667 
10668   if (const PointerType *PT = QT->getAs<PointerType>())
10669     return appendPointerType(Enc, PT, CGM, TSC);
10670 
10671   if (const EnumType *ET = QT->getAs<EnumType>())
10672     return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
10673 
10674   if (const RecordType *RT = QT->getAsStructureType())
10675     return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
10676 
10677   if (const RecordType *RT = QT->getAsUnionType())
10678     return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
10679 
10680   if (const FunctionType *FT = QT->getAs<FunctionType>())
10681     return appendFunctionType(Enc, FT, CGM, TSC);
10682 
10683   return false;
10684 }
10685 
10686 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
10687                           const CodeGen::CodeGenModule &CGM,
10688                           TypeStringCache &TSC) {
10689   if (!D)
10690     return false;
10691 
10692   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10693     if (FD->getLanguageLinkage() != CLanguageLinkage)
10694       return false;
10695     return appendType(Enc, FD->getType(), CGM, TSC);
10696   }
10697 
10698   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
10699     if (VD->getLanguageLinkage() != CLanguageLinkage)
10700       return false;
10701     QualType QT = VD->getType().getCanonicalType();
10702     if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
10703       // Global ArrayTypes are given a size of '*' if the size is unknown.
10704       // The Qualifiers should be attached to the type rather than the array.
10705       // Thus we don't call appendQualifier() here.
10706       return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
10707     }
10708     return appendType(Enc, QT, CGM, TSC);
10709   }
10710   return false;
10711 }
10712 
10713 //===----------------------------------------------------------------------===//
10714 // RISCV ABI Implementation
10715 //===----------------------------------------------------------------------===//
10716 
10717 namespace {
10718 class RISCVABIInfo : public DefaultABIInfo {
10719 private:
10720   // Size of the integer ('x') registers in bits.
10721   unsigned XLen;
10722   // Size of the floating point ('f') registers in bits. Note that the target
10723   // ISA might have a wider FLen than the selected ABI (e.g. an RV32IF target
10724   // with soft float ABI has FLen==0).
10725   unsigned FLen;
10726   static const int NumArgGPRs = 8;
10727   static const int NumArgFPRs = 8;
10728   bool detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
10729                                       llvm::Type *&Field1Ty,
10730                                       CharUnits &Field1Off,
10731                                       llvm::Type *&Field2Ty,
10732                                       CharUnits &Field2Off) const;
10733 
10734 public:
10735   RISCVABIInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, unsigned FLen)
10736       : DefaultABIInfo(CGT), XLen(XLen), FLen(FLen) {}
10737 
10738   // DefaultABIInfo's classifyReturnType and classifyArgumentType are
10739   // non-virtual, but computeInfo is virtual, so we overload it.
10740   void computeInfo(CGFunctionInfo &FI) const override;
10741 
10742   ABIArgInfo classifyArgumentType(QualType Ty, bool IsFixed, int &ArgGPRsLeft,
10743                                   int &ArgFPRsLeft) const;
10744   ABIArgInfo classifyReturnType(QualType RetTy) const;
10745 
10746   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
10747                     QualType Ty) const override;
10748 
10749   ABIArgInfo extendType(QualType Ty) const;
10750 
10751   bool detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
10752                                 CharUnits &Field1Off, llvm::Type *&Field2Ty,
10753                                 CharUnits &Field2Off, int &NeededArgGPRs,
10754                                 int &NeededArgFPRs) const;
10755   ABIArgInfo coerceAndExpandFPCCEligibleStruct(llvm::Type *Field1Ty,
10756                                                CharUnits Field1Off,
10757                                                llvm::Type *Field2Ty,
10758                                                CharUnits Field2Off) const;
10759 };
10760 } // end anonymous namespace
10761 
10762 void RISCVABIInfo::computeInfo(CGFunctionInfo &FI) const {
10763   QualType RetTy = FI.getReturnType();
10764   if (!getCXXABI().classifyReturnType(FI))
10765     FI.getReturnInfo() = classifyReturnType(RetTy);
10766 
10767   // IsRetIndirect is true if classifyArgumentType indicated the value should
10768   // be passed indirect, or if the type size is a scalar greater than 2*XLen
10769   // and not a complex type with elements <= FLen. e.g. fp128 is passed direct
10770   // in LLVM IR, relying on the backend lowering code to rewrite the argument
10771   // list and pass indirectly on RV32.
10772   bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect;
10773   if (!IsRetIndirect && RetTy->isScalarType() &&
10774       getContext().getTypeSize(RetTy) > (2 * XLen)) {
10775     if (RetTy->isComplexType() && FLen) {
10776       QualType EltTy = RetTy->castAs<ComplexType>()->getElementType();
10777       IsRetIndirect = getContext().getTypeSize(EltTy) > FLen;
10778     } else {
10779       // This is a normal scalar > 2*XLen, such as fp128 on RV32.
10780       IsRetIndirect = true;
10781     }
10782   }
10783 
10784   // We must track the number of GPRs used in order to conform to the RISC-V
10785   // ABI, as integer scalars passed in registers should have signext/zeroext
10786   // when promoted, but are anyext if passed on the stack. As GPR usage is
10787   // different for variadic arguments, we must also track whether we are
10788   // examining a vararg or not.
10789   int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs;
10790   int ArgFPRsLeft = FLen ? NumArgFPRs : 0;
10791   int NumFixedArgs = FI.getNumRequiredArgs();
10792 
10793   int ArgNum = 0;
10794   for (auto &ArgInfo : FI.arguments()) {
10795     bool IsFixed = ArgNum < NumFixedArgs;
10796     ArgInfo.info =
10797         classifyArgumentType(ArgInfo.type, IsFixed, ArgGPRsLeft, ArgFPRsLeft);
10798     ArgNum++;
10799   }
10800 }
10801 
10802 // Returns true if the struct is a potential candidate for the floating point
10803 // calling convention. If this function returns true, the caller is
10804 // responsible for checking that if there is only a single field then that
10805 // field is a float.
10806 bool RISCVABIInfo::detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
10807                                                   llvm::Type *&Field1Ty,
10808                                                   CharUnits &Field1Off,
10809                                                   llvm::Type *&Field2Ty,
10810                                                   CharUnits &Field2Off) const {
10811   bool IsInt = Ty->isIntegralOrEnumerationType();
10812   bool IsFloat = Ty->isRealFloatingType();
10813 
10814   if (IsInt || IsFloat) {
10815     uint64_t Size = getContext().getTypeSize(Ty);
10816     if (IsInt && Size > XLen)
10817       return false;
10818     // Can't be eligible if larger than the FP registers. Half precision isn't
10819     // currently supported on RISC-V and the ABI hasn't been confirmed, so
10820     // default to the integer ABI in that case.
10821     if (IsFloat && (Size > FLen || Size < 32))
10822       return false;
10823     // Can't be eligible if an integer type was already found (int+int pairs
10824     // are not eligible).
10825     if (IsInt && Field1Ty && Field1Ty->isIntegerTy())
10826       return false;
10827     if (!Field1Ty) {
10828       Field1Ty = CGT.ConvertType(Ty);
10829       Field1Off = CurOff;
10830       return true;
10831     }
10832     if (!Field2Ty) {
10833       Field2Ty = CGT.ConvertType(Ty);
10834       Field2Off = CurOff;
10835       return true;
10836     }
10837     return false;
10838   }
10839 
10840   if (auto CTy = Ty->getAs<ComplexType>()) {
10841     if (Field1Ty)
10842       return false;
10843     QualType EltTy = CTy->getElementType();
10844     if (getContext().getTypeSize(EltTy) > FLen)
10845       return false;
10846     Field1Ty = CGT.ConvertType(EltTy);
10847     Field1Off = CurOff;
10848     Field2Ty = Field1Ty;
10849     Field2Off = Field1Off + getContext().getTypeSizeInChars(EltTy);
10850     return true;
10851   }
10852 
10853   if (const ConstantArrayType *ATy = getContext().getAsConstantArrayType(Ty)) {
10854     uint64_t ArraySize = ATy->getSize().getZExtValue();
10855     QualType EltTy = ATy->getElementType();
10856     CharUnits EltSize = getContext().getTypeSizeInChars(EltTy);
10857     for (uint64_t i = 0; i < ArraySize; ++i) {
10858       bool Ret = detectFPCCEligibleStructHelper(EltTy, CurOff, Field1Ty,
10859                                                 Field1Off, Field2Ty, Field2Off);
10860       if (!Ret)
10861         return false;
10862       CurOff += EltSize;
10863     }
10864     return true;
10865   }
10866 
10867   if (const auto *RTy = Ty->getAs<RecordType>()) {
10868     // Structures with either a non-trivial destructor or a non-trivial
10869     // copy constructor are not eligible for the FP calling convention.
10870     if (getRecordArgABI(Ty, CGT.getCXXABI()))
10871       return false;
10872     if (isEmptyRecord(getContext(), Ty, true))
10873       return true;
10874     const RecordDecl *RD = RTy->getDecl();
10875     // Unions aren't eligible unless they're empty (which is caught above).
10876     if (RD->isUnion())
10877       return false;
10878     int ZeroWidthBitFieldCount = 0;
10879     for (const FieldDecl *FD : RD->fields()) {
10880       const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
10881       uint64_t FieldOffInBits = Layout.getFieldOffset(FD->getFieldIndex());
10882       QualType QTy = FD->getType();
10883       if (FD->isBitField()) {
10884         unsigned BitWidth = FD->getBitWidthValue(getContext());
10885         // Allow a bitfield with a type greater than XLen as long as the
10886         // bitwidth is XLen or less.
10887         if (getContext().getTypeSize(QTy) > XLen && BitWidth <= XLen)
10888           QTy = getContext().getIntTypeForBitwidth(XLen, false);
10889         if (BitWidth == 0) {
10890           ZeroWidthBitFieldCount++;
10891           continue;
10892         }
10893       }
10894 
10895       bool Ret = detectFPCCEligibleStructHelper(
10896           QTy, CurOff + getContext().toCharUnitsFromBits(FieldOffInBits),
10897           Field1Ty, Field1Off, Field2Ty, Field2Off);
10898       if (!Ret)
10899         return false;
10900 
10901       // As a quirk of the ABI, zero-width bitfields aren't ignored for fp+fp
10902       // or int+fp structs, but are ignored for a struct with an fp field and
10903       // any number of zero-width bitfields.
10904       if (Field2Ty && ZeroWidthBitFieldCount > 0)
10905         return false;
10906     }
10907     return Field1Ty != nullptr;
10908   }
10909 
10910   return false;
10911 }
10912 
10913 // Determine if a struct is eligible for passing according to the floating
10914 // point calling convention (i.e., when flattened it contains a single fp
10915 // value, fp+fp, or int+fp of appropriate size). If so, NeededArgFPRs and
10916 // NeededArgGPRs are incremented appropriately.
10917 bool RISCVABIInfo::detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
10918                                             CharUnits &Field1Off,
10919                                             llvm::Type *&Field2Ty,
10920                                             CharUnits &Field2Off,
10921                                             int &NeededArgGPRs,
10922                                             int &NeededArgFPRs) const {
10923   Field1Ty = nullptr;
10924   Field2Ty = nullptr;
10925   NeededArgGPRs = 0;
10926   NeededArgFPRs = 0;
10927   bool IsCandidate = detectFPCCEligibleStructHelper(
10928       Ty, CharUnits::Zero(), Field1Ty, Field1Off, Field2Ty, Field2Off);
10929   // Not really a candidate if we have a single int but no float.
10930   if (Field1Ty && !Field2Ty && !Field1Ty->isFloatingPointTy())
10931     return false;
10932   if (!IsCandidate)
10933     return false;
10934   if (Field1Ty && Field1Ty->isFloatingPointTy())
10935     NeededArgFPRs++;
10936   else if (Field1Ty)
10937     NeededArgGPRs++;
10938   if (Field2Ty && Field2Ty->isFloatingPointTy())
10939     NeededArgFPRs++;
10940   else if (Field2Ty)
10941     NeededArgGPRs++;
10942   return true;
10943 }
10944 
10945 // Call getCoerceAndExpand for the two-element flattened struct described by
10946 // Field1Ty, Field1Off, Field2Ty, Field2Off. This method will create an
10947 // appropriate coerceToType and unpaddedCoerceToType.
10948 ABIArgInfo RISCVABIInfo::coerceAndExpandFPCCEligibleStruct(
10949     llvm::Type *Field1Ty, CharUnits Field1Off, llvm::Type *Field2Ty,
10950     CharUnits Field2Off) const {
10951   SmallVector<llvm::Type *, 3> CoerceElts;
10952   SmallVector<llvm::Type *, 2> UnpaddedCoerceElts;
10953   if (!Field1Off.isZero())
10954     CoerceElts.push_back(llvm::ArrayType::get(
10955         llvm::Type::getInt8Ty(getVMContext()), Field1Off.getQuantity()));
10956 
10957   CoerceElts.push_back(Field1Ty);
10958   UnpaddedCoerceElts.push_back(Field1Ty);
10959 
10960   if (!Field2Ty) {
10961     return ABIArgInfo::getCoerceAndExpand(
10962         llvm::StructType::get(getVMContext(), CoerceElts, !Field1Off.isZero()),
10963         UnpaddedCoerceElts[0]);
10964   }
10965 
10966   CharUnits Field2Align =
10967       CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(Field2Ty));
10968   CharUnits Field1End = Field1Off +
10969       CharUnits::fromQuantity(getDataLayout().getTypeStoreSize(Field1Ty));
10970   CharUnits Field2OffNoPadNoPack = Field1End.alignTo(Field2Align);
10971 
10972   CharUnits Padding = CharUnits::Zero();
10973   if (Field2Off > Field2OffNoPadNoPack)
10974     Padding = Field2Off - Field2OffNoPadNoPack;
10975   else if (Field2Off != Field2Align && Field2Off > Field1End)
10976     Padding = Field2Off - Field1End;
10977 
10978   bool IsPacked = !Field2Off.isMultipleOf(Field2Align);
10979 
10980   if (!Padding.isZero())
10981     CoerceElts.push_back(llvm::ArrayType::get(
10982         llvm::Type::getInt8Ty(getVMContext()), Padding.getQuantity()));
10983 
10984   CoerceElts.push_back(Field2Ty);
10985   UnpaddedCoerceElts.push_back(Field2Ty);
10986 
10987   auto CoerceToType =
10988       llvm::StructType::get(getVMContext(), CoerceElts, IsPacked);
10989   auto UnpaddedCoerceToType =
10990       llvm::StructType::get(getVMContext(), UnpaddedCoerceElts, IsPacked);
10991 
10992   return ABIArgInfo::getCoerceAndExpand(CoerceToType, UnpaddedCoerceToType);
10993 }
10994 
10995 ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, bool IsFixed,
10996                                               int &ArgGPRsLeft,
10997                                               int &ArgFPRsLeft) const {
10998   assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow");
10999   Ty = useFirstFieldIfTransparentUnion(Ty);
11000 
11001   // Structures with either a non-trivial destructor or a non-trivial
11002   // copy constructor are always passed indirectly.
11003   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
11004     if (ArgGPRsLeft)
11005       ArgGPRsLeft -= 1;
11006     return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
11007                                            CGCXXABI::RAA_DirectInMemory);
11008   }
11009 
11010   // Ignore empty structs/unions.
11011   if (isEmptyRecord(getContext(), Ty, true))
11012     return ABIArgInfo::getIgnore();
11013 
11014   uint64_t Size = getContext().getTypeSize(Ty);
11015 
11016   // Pass floating point values via FPRs if possible.
11017   if (IsFixed && Ty->isFloatingType() && !Ty->isComplexType() &&
11018       FLen >= Size && ArgFPRsLeft) {
11019     ArgFPRsLeft--;
11020     return ABIArgInfo::getDirect();
11021   }
11022 
11023   // Complex types for the hard float ABI must be passed direct rather than
11024   // using CoerceAndExpand.
11025   if (IsFixed && Ty->isComplexType() && FLen && ArgFPRsLeft >= 2) {
11026     QualType EltTy = Ty->castAs<ComplexType>()->getElementType();
11027     if (getContext().getTypeSize(EltTy) <= FLen) {
11028       ArgFPRsLeft -= 2;
11029       return ABIArgInfo::getDirect();
11030     }
11031   }
11032 
11033   if (IsFixed && FLen && Ty->isStructureOrClassType()) {
11034     llvm::Type *Field1Ty = nullptr;
11035     llvm::Type *Field2Ty = nullptr;
11036     CharUnits Field1Off = CharUnits::Zero();
11037     CharUnits Field2Off = CharUnits::Zero();
11038     int NeededArgGPRs = 0;
11039     int NeededArgFPRs = 0;
11040     bool IsCandidate =
11041         detectFPCCEligibleStruct(Ty, Field1Ty, Field1Off, Field2Ty, Field2Off,
11042                                  NeededArgGPRs, NeededArgFPRs);
11043     if (IsCandidate && NeededArgGPRs <= ArgGPRsLeft &&
11044         NeededArgFPRs <= ArgFPRsLeft) {
11045       ArgGPRsLeft -= NeededArgGPRs;
11046       ArgFPRsLeft -= NeededArgFPRs;
11047       return coerceAndExpandFPCCEligibleStruct(Field1Ty, Field1Off, Field2Ty,
11048                                                Field2Off);
11049     }
11050   }
11051 
11052   uint64_t NeededAlign = getContext().getTypeAlign(Ty);
11053   bool MustUseStack = false;
11054   // Determine the number of GPRs needed to pass the current argument
11055   // according to the ABI. 2*XLen-aligned varargs are passed in "aligned"
11056   // register pairs, so may consume 3 registers.
11057   int NeededArgGPRs = 1;
11058   if (!IsFixed && NeededAlign == 2 * XLen)
11059     NeededArgGPRs = 2 + (ArgGPRsLeft % 2);
11060   else if (Size > XLen && Size <= 2 * XLen)
11061     NeededArgGPRs = 2;
11062 
11063   if (NeededArgGPRs > ArgGPRsLeft) {
11064     MustUseStack = true;
11065     NeededArgGPRs = ArgGPRsLeft;
11066   }
11067 
11068   ArgGPRsLeft -= NeededArgGPRs;
11069 
11070   if (!isAggregateTypeForABI(Ty) && !Ty->isVectorType()) {
11071     // Treat an enum type as its underlying type.
11072     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
11073       Ty = EnumTy->getDecl()->getIntegerType();
11074 
11075     // All integral types are promoted to XLen width, unless passed on the
11076     // stack.
11077     if (Size < XLen && Ty->isIntegralOrEnumerationType() && !MustUseStack) {
11078       return extendType(Ty);
11079     }
11080 
11081     if (const auto *EIT = Ty->getAs<BitIntType>()) {
11082       if (EIT->getNumBits() < XLen && !MustUseStack)
11083         return extendType(Ty);
11084       if (EIT->getNumBits() > 128 ||
11085           (!getContext().getTargetInfo().hasInt128Type() &&
11086            EIT->getNumBits() > 64))
11087         return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
11088     }
11089 
11090     return ABIArgInfo::getDirect();
11091   }
11092 
11093   // Aggregates which are <= 2*XLen will be passed in registers if possible,
11094   // so coerce to integers.
11095   if (Size <= 2 * XLen) {
11096     unsigned Alignment = getContext().getTypeAlign(Ty);
11097 
11098     // Use a single XLen int if possible, 2*XLen if 2*XLen alignment is
11099     // required, and a 2-element XLen array if only XLen alignment is required.
11100     if (Size <= XLen) {
11101       return ABIArgInfo::getDirect(
11102           llvm::IntegerType::get(getVMContext(), XLen));
11103     } else if (Alignment == 2 * XLen) {
11104       return ABIArgInfo::getDirect(
11105           llvm::IntegerType::get(getVMContext(), 2 * XLen));
11106     } else {
11107       return ABIArgInfo::getDirect(llvm::ArrayType::get(
11108           llvm::IntegerType::get(getVMContext(), XLen), 2));
11109     }
11110   }
11111   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
11112 }
11113 
11114 ABIArgInfo RISCVABIInfo::classifyReturnType(QualType RetTy) const {
11115   if (RetTy->isVoidType())
11116     return ABIArgInfo::getIgnore();
11117 
11118   int ArgGPRsLeft = 2;
11119   int ArgFPRsLeft = FLen ? 2 : 0;
11120 
11121   // The rules for return and argument types are the same, so defer to
11122   // classifyArgumentType.
11123   return classifyArgumentType(RetTy, /*IsFixed=*/true, ArgGPRsLeft,
11124                               ArgFPRsLeft);
11125 }
11126 
11127 Address RISCVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
11128                                 QualType Ty) const {
11129   CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8);
11130 
11131   // Empty records are ignored for parameter passing purposes.
11132   if (isEmptyRecord(getContext(), Ty, true)) {
11133     Address Addr =
11134         Address::deprecated(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
11135     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
11136     return Addr;
11137   }
11138 
11139   auto TInfo = getContext().getTypeInfoInChars(Ty);
11140 
11141   // Arguments bigger than 2*Xlen bytes are passed indirectly.
11142   bool IsIndirect = TInfo.Width > 2 * SlotSize;
11143 
11144   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TInfo,
11145                           SlotSize, /*AllowHigherAlign=*/true);
11146 }
11147 
11148 ABIArgInfo RISCVABIInfo::extendType(QualType Ty) const {
11149   int TySize = getContext().getTypeSize(Ty);
11150   // RV64 ABI requires unsigned 32 bit integers to be sign extended.
11151   if (XLen == 64 && Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
11152     return ABIArgInfo::getSignExtend(Ty);
11153   return ABIArgInfo::getExtend(Ty);
11154 }
11155 
11156 namespace {
11157 class RISCVTargetCodeGenInfo : public TargetCodeGenInfo {
11158 public:
11159   RISCVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen,
11160                          unsigned FLen)
11161       : TargetCodeGenInfo(std::make_unique<RISCVABIInfo>(CGT, XLen, FLen)) {}
11162 
11163   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
11164                            CodeGen::CodeGenModule &CGM) const override {
11165     const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
11166     if (!FD) return;
11167 
11168     const auto *Attr = FD->getAttr<RISCVInterruptAttr>();
11169     if (!Attr)
11170       return;
11171 
11172     const char *Kind;
11173     switch (Attr->getInterrupt()) {
11174     case RISCVInterruptAttr::user: Kind = "user"; break;
11175     case RISCVInterruptAttr::supervisor: Kind = "supervisor"; break;
11176     case RISCVInterruptAttr::machine: Kind = "machine"; break;
11177     }
11178 
11179     auto *Fn = cast<llvm::Function>(GV);
11180 
11181     Fn->addFnAttr("interrupt", Kind);
11182   }
11183 };
11184 } // namespace
11185 
11186 //===----------------------------------------------------------------------===//
11187 // VE ABI Implementation.
11188 //
11189 namespace {
11190 class VEABIInfo : public DefaultABIInfo {
11191 public:
11192   VEABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
11193 
11194 private:
11195   ABIArgInfo classifyReturnType(QualType RetTy) const;
11196   ABIArgInfo classifyArgumentType(QualType RetTy) const;
11197   void computeInfo(CGFunctionInfo &FI) const override;
11198 };
11199 } // end anonymous namespace
11200 
11201 ABIArgInfo VEABIInfo::classifyReturnType(QualType Ty) const {
11202   if (Ty->isAnyComplexType())
11203     return ABIArgInfo::getDirect();
11204   uint64_t Size = getContext().getTypeSize(Ty);
11205   if (Size < 64 && Ty->isIntegerType())
11206     return ABIArgInfo::getExtend(Ty);
11207   return DefaultABIInfo::classifyReturnType(Ty);
11208 }
11209 
11210 ABIArgInfo VEABIInfo::classifyArgumentType(QualType Ty) const {
11211   if (Ty->isAnyComplexType())
11212     return ABIArgInfo::getDirect();
11213   uint64_t Size = getContext().getTypeSize(Ty);
11214   if (Size < 64 && Ty->isIntegerType())
11215     return ABIArgInfo::getExtend(Ty);
11216   return DefaultABIInfo::classifyArgumentType(Ty);
11217 }
11218 
11219 void VEABIInfo::computeInfo(CGFunctionInfo &FI) const {
11220   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
11221   for (auto &Arg : FI.arguments())
11222     Arg.info = classifyArgumentType(Arg.type);
11223 }
11224 
11225 namespace {
11226 class VETargetCodeGenInfo : public TargetCodeGenInfo {
11227 public:
11228   VETargetCodeGenInfo(CodeGenTypes &CGT)
11229       : TargetCodeGenInfo(std::make_unique<VEABIInfo>(CGT)) {}
11230   // VE ABI requires the arguments of variadic and prototype-less functions
11231   // are passed in both registers and memory.
11232   bool isNoProtoCallVariadic(const CallArgList &args,
11233                              const FunctionNoProtoType *fnType) const override {
11234     return true;
11235   }
11236 };
11237 } // end anonymous namespace
11238 
11239 //===----------------------------------------------------------------------===//
11240 // Driver code
11241 //===----------------------------------------------------------------------===//
11242 
11243 bool CodeGenModule::supportsCOMDAT() const {
11244   return getTriple().supportsCOMDAT();
11245 }
11246 
11247 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
11248   if (TheTargetCodeGenInfo)
11249     return *TheTargetCodeGenInfo;
11250 
11251   // Helper to set the unique_ptr while still keeping the return value.
11252   auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
11253     this->TheTargetCodeGenInfo.reset(P);
11254     return *P;
11255   };
11256 
11257   const llvm::Triple &Triple = getTarget().getTriple();
11258   switch (Triple.getArch()) {
11259   default:
11260     return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
11261 
11262   case llvm::Triple::le32:
11263     return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
11264   case llvm::Triple::m68k:
11265     return SetCGInfo(new M68kTargetCodeGenInfo(Types));
11266   case llvm::Triple::mips:
11267   case llvm::Triple::mipsel:
11268     if (Triple.getOS() == llvm::Triple::NaCl)
11269       return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
11270     return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
11271 
11272   case llvm::Triple::mips64:
11273   case llvm::Triple::mips64el:
11274     return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
11275 
11276   case llvm::Triple::avr:
11277     return SetCGInfo(new AVRTargetCodeGenInfo(Types));
11278 
11279   case llvm::Triple::aarch64:
11280   case llvm::Triple::aarch64_32:
11281   case llvm::Triple::aarch64_be: {
11282     AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
11283     if (getTarget().getABI() == "darwinpcs")
11284       Kind = AArch64ABIInfo::DarwinPCS;
11285     else if (Triple.isOSWindows())
11286       return SetCGInfo(
11287           new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64));
11288 
11289     return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
11290   }
11291 
11292   case llvm::Triple::wasm32:
11293   case llvm::Triple::wasm64: {
11294     WebAssemblyABIInfo::ABIKind Kind = WebAssemblyABIInfo::MVP;
11295     if (getTarget().getABI() == "experimental-mv")
11296       Kind = WebAssemblyABIInfo::ExperimentalMV;
11297     return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types, Kind));
11298   }
11299 
11300   case llvm::Triple::arm:
11301   case llvm::Triple::armeb:
11302   case llvm::Triple::thumb:
11303   case llvm::Triple::thumbeb: {
11304     if (Triple.getOS() == llvm::Triple::Win32) {
11305       return SetCGInfo(
11306           new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
11307     }
11308 
11309     ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
11310     StringRef ABIStr = getTarget().getABI();
11311     if (ABIStr == "apcs-gnu")
11312       Kind = ARMABIInfo::APCS;
11313     else if (ABIStr == "aapcs16")
11314       Kind = ARMABIInfo::AAPCS16_VFP;
11315     else if (CodeGenOpts.FloatABI == "hard" ||
11316              (CodeGenOpts.FloatABI != "soft" &&
11317               (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
11318                Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
11319                Triple.getEnvironment() == llvm::Triple::EABIHF)))
11320       Kind = ARMABIInfo::AAPCS_VFP;
11321 
11322     return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
11323   }
11324 
11325   case llvm::Triple::ppc: {
11326     if (Triple.isOSAIX())
11327       return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ false));
11328 
11329     bool IsSoftFloat =
11330         CodeGenOpts.FloatABI == "soft" || getTarget().hasFeature("spe");
11331     bool RetSmallStructInRegABI =
11332         PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
11333     return SetCGInfo(
11334         new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI));
11335   }
11336   case llvm::Triple::ppcle: {
11337     bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
11338     bool RetSmallStructInRegABI =
11339         PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
11340     return SetCGInfo(
11341         new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI));
11342   }
11343   case llvm::Triple::ppc64:
11344     if (Triple.isOSAIX())
11345       return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ true));
11346 
11347     if (Triple.isOSBinFormatELF()) {
11348       PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
11349       if (getTarget().getABI() == "elfv2")
11350         Kind = PPC64_SVR4_ABIInfo::ELFv2;
11351       bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
11352 
11353       return SetCGInfo(
11354           new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, IsSoftFloat));
11355     }
11356     return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
11357   case llvm::Triple::ppc64le: {
11358     assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
11359     PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
11360     if (getTarget().getABI() == "elfv1")
11361       Kind = PPC64_SVR4_ABIInfo::ELFv1;
11362     bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
11363 
11364     return SetCGInfo(
11365         new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, IsSoftFloat));
11366   }
11367 
11368   case llvm::Triple::nvptx:
11369   case llvm::Triple::nvptx64:
11370     return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
11371 
11372   case llvm::Triple::msp430:
11373     return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
11374 
11375   case llvm::Triple::riscv32:
11376   case llvm::Triple::riscv64: {
11377     StringRef ABIStr = getTarget().getABI();
11378     unsigned XLen = getTarget().getPointerWidth(0);
11379     unsigned ABIFLen = 0;
11380     if (ABIStr.endswith("f"))
11381       ABIFLen = 32;
11382     else if (ABIStr.endswith("d"))
11383       ABIFLen = 64;
11384     return SetCGInfo(new RISCVTargetCodeGenInfo(Types, XLen, ABIFLen));
11385   }
11386 
11387   case llvm::Triple::systemz: {
11388     bool SoftFloat = CodeGenOpts.FloatABI == "soft";
11389     bool HasVector = !SoftFloat && getTarget().getABI() == "vector";
11390     return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector, SoftFloat));
11391   }
11392 
11393   case llvm::Triple::tce:
11394   case llvm::Triple::tcele:
11395     return SetCGInfo(new TCETargetCodeGenInfo(Types));
11396 
11397   case llvm::Triple::x86: {
11398     bool IsDarwinVectorABI = Triple.isOSDarwin();
11399     bool RetSmallStructInRegABI =
11400         X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
11401     bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
11402 
11403     if (Triple.getOS() == llvm::Triple::Win32) {
11404       return SetCGInfo(new WinX86_32TargetCodeGenInfo(
11405           Types, IsDarwinVectorABI, RetSmallStructInRegABI,
11406           IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
11407     } else {
11408       return SetCGInfo(new X86_32TargetCodeGenInfo(
11409           Types, IsDarwinVectorABI, RetSmallStructInRegABI,
11410           IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
11411           CodeGenOpts.FloatABI == "soft"));
11412     }
11413   }
11414 
11415   case llvm::Triple::x86_64: {
11416     StringRef ABI = getTarget().getABI();
11417     X86AVXABILevel AVXLevel =
11418         (ABI == "avx512"
11419              ? X86AVXABILevel::AVX512
11420              : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
11421 
11422     switch (Triple.getOS()) {
11423     case llvm::Triple::Win32:
11424       return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
11425     default:
11426       return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
11427     }
11428   }
11429   case llvm::Triple::hexagon:
11430     return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
11431   case llvm::Triple::lanai:
11432     return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
11433   case llvm::Triple::r600:
11434     return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
11435   case llvm::Triple::amdgcn:
11436     return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
11437   case llvm::Triple::sparc:
11438     return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
11439   case llvm::Triple::sparcv9:
11440     return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
11441   case llvm::Triple::xcore:
11442     return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
11443   case llvm::Triple::arc:
11444     return SetCGInfo(new ARCTargetCodeGenInfo(Types));
11445   case llvm::Triple::spir:
11446   case llvm::Triple::spir64:
11447     return SetCGInfo(new CommonSPIRTargetCodeGenInfo(Types));
11448   case llvm::Triple::spirv32:
11449   case llvm::Triple::spirv64:
11450     return SetCGInfo(new SPIRVTargetCodeGenInfo(Types));
11451   case llvm::Triple::ve:
11452     return SetCGInfo(new VETargetCodeGenInfo(Types));
11453   }
11454 }
11455 
11456 /// Create an OpenCL kernel for an enqueued block.
11457 ///
11458 /// The kernel has the same function type as the block invoke function. Its
11459 /// name is the name of the block invoke function postfixed with "_kernel".
11460 /// It simply calls the block invoke function then returns.
11461 llvm::Function *
11462 TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF,
11463                                              llvm::Function *Invoke,
11464                                              llvm::Value *BlockLiteral) const {
11465   auto *InvokeFT = Invoke->getFunctionType();
11466   llvm::SmallVector<llvm::Type *, 2> ArgTys;
11467   for (auto &P : InvokeFT->params())
11468     ArgTys.push_back(P);
11469   auto &C = CGF.getLLVMContext();
11470   std::string Name = Invoke->getName().str() + "_kernel";
11471   auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
11472   auto *F = llvm::Function::Create(FT, llvm::GlobalValue::ExternalLinkage, Name,
11473                                    &CGF.CGM.getModule());
11474   auto IP = CGF.Builder.saveIP();
11475   auto *BB = llvm::BasicBlock::Create(C, "entry", F);
11476   auto &Builder = CGF.Builder;
11477   Builder.SetInsertPoint(BB);
11478   llvm::SmallVector<llvm::Value *, 2> Args;
11479   for (auto &A : F->args())
11480     Args.push_back(&A);
11481   llvm::CallInst *call = Builder.CreateCall(Invoke, Args);
11482   call->setCallingConv(Invoke->getCallingConv());
11483   Builder.CreateRetVoid();
11484   Builder.restoreIP(IP);
11485   return F;
11486 }
11487 
11488 /// Create an OpenCL kernel for an enqueued block.
11489 ///
11490 /// The type of the first argument (the block literal) is the struct type
11491 /// of the block literal instead of a pointer type. The first argument
11492 /// (block literal) is passed directly by value to the kernel. The kernel
11493 /// allocates the same type of struct on stack and stores the block literal
11494 /// to it and passes its pointer to the block invoke function. The kernel
11495 /// has "enqueued-block" function attribute and kernel argument metadata.
11496 llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel(
11497     CodeGenFunction &CGF, llvm::Function *Invoke,
11498     llvm::Value *BlockLiteral) const {
11499   auto &Builder = CGF.Builder;
11500   auto &C = CGF.getLLVMContext();
11501 
11502   auto *BlockTy = BlockLiteral->getType()->getPointerElementType();
11503   auto *InvokeFT = Invoke->getFunctionType();
11504   llvm::SmallVector<llvm::Type *, 2> ArgTys;
11505   llvm::SmallVector<llvm::Metadata *, 8> AddressQuals;
11506   llvm::SmallVector<llvm::Metadata *, 8> AccessQuals;
11507   llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames;
11508   llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames;
11509   llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals;
11510   llvm::SmallVector<llvm::Metadata *, 8> ArgNames;
11511 
11512   ArgTys.push_back(BlockTy);
11513   ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
11514   AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0)));
11515   ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
11516   ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
11517   AccessQuals.push_back(llvm::MDString::get(C, "none"));
11518   ArgNames.push_back(llvm::MDString::get(C, "block_literal"));
11519   for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) {
11520     ArgTys.push_back(InvokeFT->getParamType(I));
11521     ArgTypeNames.push_back(llvm::MDString::get(C, "void*"));
11522     AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3)));
11523     AccessQuals.push_back(llvm::MDString::get(C, "none"));
11524     ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*"));
11525     ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
11526     ArgNames.push_back(
11527         llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str()));
11528   }
11529   std::string Name = Invoke->getName().str() + "_kernel";
11530   auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
11531   auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
11532                                    &CGF.CGM.getModule());
11533   F->addFnAttr("enqueued-block");
11534   auto IP = CGF.Builder.saveIP();
11535   auto *BB = llvm::BasicBlock::Create(C, "entry", F);
11536   Builder.SetInsertPoint(BB);
11537   const auto BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlign(BlockTy);
11538   auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr);
11539   BlockPtr->setAlignment(BlockAlign);
11540   Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign);
11541   auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0));
11542   llvm::SmallVector<llvm::Value *, 2> Args;
11543   Args.push_back(Cast);
11544   for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I)
11545     Args.push_back(I);
11546   llvm::CallInst *call = Builder.CreateCall(Invoke, Args);
11547   call->setCallingConv(Invoke->getCallingConv());
11548   Builder.CreateRetVoid();
11549   Builder.restoreIP(IP);
11550 
11551   F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals));
11552   F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals));
11553   F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames));
11554   F->setMetadata("kernel_arg_base_type",
11555                  llvm::MDNode::get(C, ArgBaseTypeNames));
11556   F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals));
11557   if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
11558     F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames));
11559 
11560   return F;
11561 }
11562