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                                                  DirectAlign);
328   } else {
329     Addr = Address(Ptr, 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 = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy,
383                                         DirectSize, DirectAlign,
384                                         SlotSizeAndAlign,
385                                         AllowHigherAlign);
386 
387   if (IsIndirect) {
388     Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.Align);
389   }
390 
391   return Addr;
392 
393 }
394 
395 static Address complexTempStructure(CodeGenFunction &CGF, Address VAListAddr,
396                                     QualType Ty, CharUnits SlotSize,
397                                     CharUnits EltSize, const ComplexType *CTy) {
398   Address Addr =
399       emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty, SlotSize * 2,
400                              SlotSize, SlotSize, /*AllowHigher*/ true);
401 
402   Address RealAddr = Addr;
403   Address ImagAddr = RealAddr;
404   if (CGF.CGM.getDataLayout().isBigEndian()) {
405     RealAddr =
406         CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize - EltSize);
407     ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
408                                                       2 * SlotSize - EltSize);
409   } else {
410     ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
411   }
412 
413   llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
414   RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
415   ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
416   llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
417   llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
418 
419   Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
420   CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
421                          /*init*/ true);
422   return Temp;
423 }
424 
425 static Address emitMergePHI(CodeGenFunction &CGF,
426                             Address Addr1, llvm::BasicBlock *Block1,
427                             Address Addr2, llvm::BasicBlock *Block2,
428                             const llvm::Twine &Name = "") {
429   assert(Addr1.getType() == Addr2.getType());
430   llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name);
431   PHI->addIncoming(Addr1.getPointer(), Block1);
432   PHI->addIncoming(Addr2.getPointer(), Block2);
433   CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment());
434   return Address(PHI, Addr1.getElementType(), Align);
435 }
436 
437 TargetCodeGenInfo::~TargetCodeGenInfo() = default;
438 
439 // If someone can figure out a general rule for this, that would be great.
440 // It's probably just doomed to be platform-dependent, though.
441 unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
442   // Verified for:
443   //   x86-64     FreeBSD, Linux, Darwin
444   //   x86-32     FreeBSD, Linux, Darwin
445   //   PowerPC    Linux, Darwin
446   //   ARM        Darwin (*not* EABI)
447   //   AArch64    Linux
448   return 32;
449 }
450 
451 bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
452                                      const FunctionNoProtoType *fnType) const {
453   // The following conventions are known to require this to be false:
454   //   x86_stdcall
455   //   MIPS
456   // For everything else, we just prefer false unless we opt out.
457   return false;
458 }
459 
460 void
461 TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
462                                              llvm::SmallString<24> &Opt) const {
463   // This assumes the user is passing a library name like "rt" instead of a
464   // filename like "librt.a/so", and that they don't care whether it's static or
465   // dynamic.
466   Opt = "-l";
467   Opt += Lib;
468 }
469 
470 unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const {
471   // OpenCL kernels are called via an explicit runtime API with arguments
472   // set with clSetKernelArg(), not as normal sub-functions.
473   // Return SPIR_KERNEL by default as the kernel calling convention to
474   // ensure the fingerprint is fixed such way that each OpenCL argument
475   // gets one matching argument in the produced kernel function argument
476   // list to enable feasible implementation of clSetKernelArg() with
477   // aggregates etc. In case we would use the default C calling conv here,
478   // clSetKernelArg() might break depending on the target-specific
479   // conventions; different targets might split structs passed as values
480   // to multiple function arguments etc.
481   return llvm::CallingConv::SPIR_KERNEL;
482 }
483 
484 llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM,
485     llvm::PointerType *T, QualType QT) const {
486   return llvm::ConstantPointerNull::get(T);
487 }
488 
489 LangAS TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
490                                                    const VarDecl *D) const {
491   assert(!CGM.getLangOpts().OpenCL &&
492          !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
493          "Address space agnostic languages only");
494   return D ? D->getType().getAddressSpace() : LangAS::Default;
495 }
496 
497 llvm::Value *TargetCodeGenInfo::performAddrSpaceCast(
498     CodeGen::CodeGenFunction &CGF, llvm::Value *Src, LangAS SrcAddr,
499     LangAS DestAddr, llvm::Type *DestTy, bool isNonNull) const {
500   // Since target may map different address spaces in AST to the same address
501   // space, an address space conversion may end up as a bitcast.
502   if (auto *C = dyn_cast<llvm::Constant>(Src))
503     return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy);
504   // Try to preserve the source's name to make IR more readable.
505   return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
506       Src, DestTy, Src->hasName() ? Src->getName() + ".ascast" : "");
507 }
508 
509 llvm::Constant *
510 TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src,
511                                         LangAS SrcAddr, LangAS DestAddr,
512                                         llvm::Type *DestTy) const {
513   // Since target may map different address spaces in AST to the same address
514   // space, an address space conversion may end up as a bitcast.
515   return llvm::ConstantExpr::getPointerCast(Src, DestTy);
516 }
517 
518 llvm::SyncScope::ID
519 TargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
520                                       SyncScope Scope,
521                                       llvm::AtomicOrdering Ordering,
522                                       llvm::LLVMContext &Ctx) const {
523   return Ctx.getOrInsertSyncScopeID(""); /* default sync scope */
524 }
525 
526 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
527 
528 /// isEmptyField - Return true iff a the field is "empty", that is it
529 /// is an unnamed bit-field or an (array of) empty record(s).
530 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
531                          bool AllowArrays) {
532   if (FD->isUnnamedBitfield())
533     return true;
534 
535   QualType FT = FD->getType();
536 
537   // Constant arrays of empty records count as empty, strip them off.
538   // Constant arrays of zero length always count as empty.
539   bool WasArray = false;
540   if (AllowArrays)
541     while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
542       if (AT->getSize() == 0)
543         return true;
544       FT = AT->getElementType();
545       // The [[no_unique_address]] special case below does not apply to
546       // arrays of C++ empty records, so we need to remember this fact.
547       WasArray = true;
548     }
549 
550   const RecordType *RT = FT->getAs<RecordType>();
551   if (!RT)
552     return false;
553 
554   // C++ record fields are never empty, at least in the Itanium ABI.
555   //
556   // FIXME: We should use a predicate for whether this behavior is true in the
557   // current ABI.
558   //
559   // The exception to the above rule are fields marked with the
560   // [[no_unique_address]] attribute (since C++20).  Those do count as empty
561   // according to the Itanium ABI.  The exception applies only to records,
562   // not arrays of records, so we must also check whether we stripped off an
563   // array type above.
564   if (isa<CXXRecordDecl>(RT->getDecl()) &&
565       (WasArray || !FD->hasAttr<NoUniqueAddressAttr>()))
566     return false;
567 
568   return isEmptyRecord(Context, FT, AllowArrays);
569 }
570 
571 /// isEmptyRecord - Return true iff a structure contains only empty
572 /// fields. Note that a structure with a flexible array member is not
573 /// considered empty.
574 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
575   const RecordType *RT = T->getAs<RecordType>();
576   if (!RT)
577     return false;
578   const RecordDecl *RD = RT->getDecl();
579   if (RD->hasFlexibleArrayMember())
580     return false;
581 
582   // If this is a C++ record, check the bases first.
583   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
584     for (const auto &I : CXXRD->bases())
585       if (!isEmptyRecord(Context, I.getType(), true))
586         return false;
587 
588   for (const auto *I : RD->fields())
589     if (!isEmptyField(Context, I, AllowArrays))
590       return false;
591   return true;
592 }
593 
594 /// isSingleElementStruct - Determine if a structure is a "single
595 /// element struct", i.e. it has exactly one non-empty field or
596 /// exactly one field which is itself a single element
597 /// struct. Structures with flexible array members are never
598 /// considered single element structs.
599 ///
600 /// \return The field declaration for the single non-empty field, if
601 /// it exists.
602 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
603   const RecordType *RT = T->getAs<RecordType>();
604   if (!RT)
605     return nullptr;
606 
607   const RecordDecl *RD = RT->getDecl();
608   if (RD->hasFlexibleArrayMember())
609     return nullptr;
610 
611   const Type *Found = nullptr;
612 
613   // If this is a C++ record, check the bases first.
614   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
615     for (const auto &I : CXXRD->bases()) {
616       // Ignore empty records.
617       if (isEmptyRecord(Context, I.getType(), true))
618         continue;
619 
620       // If we already found an element then this isn't a single-element struct.
621       if (Found)
622         return nullptr;
623 
624       // If this is non-empty and not a single element struct, the composite
625       // cannot be a single element struct.
626       Found = isSingleElementStruct(I.getType(), Context);
627       if (!Found)
628         return nullptr;
629     }
630   }
631 
632   // Check for single element.
633   for (const auto *FD : RD->fields()) {
634     QualType FT = FD->getType();
635 
636     // Ignore empty fields.
637     if (isEmptyField(Context, FD, true))
638       continue;
639 
640     // If we already found an element then this isn't a single-element
641     // struct.
642     if (Found)
643       return nullptr;
644 
645     // Treat single element arrays as the element.
646     while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
647       if (AT->getSize().getZExtValue() != 1)
648         break;
649       FT = AT->getElementType();
650     }
651 
652     if (!isAggregateTypeForABI(FT)) {
653       Found = FT.getTypePtr();
654     } else {
655       Found = isSingleElementStruct(FT, Context);
656       if (!Found)
657         return nullptr;
658     }
659   }
660 
661   // We don't consider a struct a single-element struct if it has
662   // padding beyond the element type.
663   if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
664     return nullptr;
665 
666   return Found;
667 }
668 
669 namespace {
670 Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
671                        const ABIArgInfo &AI) {
672   // This default implementation defers to the llvm backend's va_arg
673   // instruction. It can handle only passing arguments directly
674   // (typically only handled in the backend for primitive types), or
675   // aggregates passed indirectly by pointer (NOTE: if the "byval"
676   // flag has ABI impact in the callee, this implementation cannot
677   // work.)
678 
679   // Only a few cases are covered here at the moment -- those needed
680   // by the default abi.
681   llvm::Value *Val;
682 
683   if (AI.isIndirect()) {
684     assert(!AI.getPaddingType() &&
685            "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
686     assert(
687         !AI.getIndirectRealign() &&
688         "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!");
689 
690     auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
691     CharUnits TyAlignForABI = TyInfo.Align;
692 
693     llvm::Type *BaseTy =
694         llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
695     llvm::Value *Addr =
696         CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
697     return Address(Addr, TyAlignForABI);
698   } else {
699     assert((AI.isDirect() || AI.isExtend()) &&
700            "Unexpected ArgInfo Kind in generic VAArg emitter!");
701 
702     assert(!AI.getInReg() &&
703            "Unexpected InReg seen in arginfo in generic VAArg emitter!");
704     assert(!AI.getPaddingType() &&
705            "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
706     assert(!AI.getDirectOffset() &&
707            "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!");
708     assert(!AI.getCoerceToType() &&
709            "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!");
710 
711     Address Temp = CGF.CreateMemTemp(Ty, "varet");
712     Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty));
713     CGF.Builder.CreateStore(Val, Temp);
714     return Temp;
715   }
716 }
717 
718 /// DefaultABIInfo - The default implementation for ABI specific
719 /// details. This implementation provides information which results in
720 /// self-consistent and sensible LLVM IR generation, but does not
721 /// conform to any particular ABI.
722 class DefaultABIInfo : public ABIInfo {
723 public:
724   DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
725 
726   ABIArgInfo classifyReturnType(QualType RetTy) const;
727   ABIArgInfo classifyArgumentType(QualType RetTy) const;
728 
729   void computeInfo(CGFunctionInfo &FI) const override {
730     if (!getCXXABI().classifyReturnType(FI))
731       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
732     for (auto &I : FI.arguments())
733       I.info = classifyArgumentType(I.type);
734   }
735 
736   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
737                     QualType Ty) const override {
738     return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
739   }
740 };
741 
742 class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
743 public:
744   DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
745       : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {}
746 };
747 
748 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
749   Ty = useFirstFieldIfTransparentUnion(Ty);
750 
751   if (isAggregateTypeForABI(Ty)) {
752     // Records with non-trivial destructors/copy-constructors should not be
753     // passed by value.
754     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
755       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
756 
757     return getNaturalAlignIndirect(Ty);
758   }
759 
760   // Treat an enum type as its underlying type.
761   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
762     Ty = EnumTy->getDecl()->getIntegerType();
763 
764   ASTContext &Context = getContext();
765   if (const auto *EIT = Ty->getAs<BitIntType>())
766     if (EIT->getNumBits() >
767         Context.getTypeSize(Context.getTargetInfo().hasInt128Type()
768                                 ? Context.Int128Ty
769                                 : Context.LongLongTy))
770       return getNaturalAlignIndirect(Ty);
771 
772   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
773                                             : ABIArgInfo::getDirect());
774 }
775 
776 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
777   if (RetTy->isVoidType())
778     return ABIArgInfo::getIgnore();
779 
780   if (isAggregateTypeForABI(RetTy))
781     return getNaturalAlignIndirect(RetTy);
782 
783   // Treat an enum type as its underlying type.
784   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
785     RetTy = EnumTy->getDecl()->getIntegerType();
786 
787   if (const auto *EIT = RetTy->getAs<BitIntType>())
788     if (EIT->getNumBits() >
789         getContext().getTypeSize(getContext().getTargetInfo().hasInt128Type()
790                                      ? getContext().Int128Ty
791                                      : getContext().LongLongTy))
792       return getNaturalAlignIndirect(RetTy);
793 
794   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
795                                                : ABIArgInfo::getDirect());
796 }
797 
798 //===----------------------------------------------------------------------===//
799 // WebAssembly ABI Implementation
800 //
801 // This is a very simple ABI that relies a lot on DefaultABIInfo.
802 //===----------------------------------------------------------------------===//
803 
804 class WebAssemblyABIInfo final : public SwiftABIInfo {
805 public:
806   enum ABIKind {
807     MVP = 0,
808     ExperimentalMV = 1,
809   };
810 
811 private:
812   DefaultABIInfo defaultInfo;
813   ABIKind Kind;
814 
815 public:
816   explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind)
817       : SwiftABIInfo(CGT), defaultInfo(CGT), Kind(Kind) {}
818 
819 private:
820   ABIArgInfo classifyReturnType(QualType RetTy) const;
821   ABIArgInfo classifyArgumentType(QualType Ty) const;
822 
823   // DefaultABIInfo's classifyReturnType and classifyArgumentType are
824   // non-virtual, but computeInfo and EmitVAArg are virtual, so we
825   // overload them.
826   void computeInfo(CGFunctionInfo &FI) const override {
827     if (!getCXXABI().classifyReturnType(FI))
828       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
829     for (auto &Arg : FI.arguments())
830       Arg.info = classifyArgumentType(Arg.type);
831   }
832 
833   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
834                     QualType Ty) const override;
835 
836   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
837                                     bool asReturnValue) const override {
838     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
839   }
840 
841   bool isSwiftErrorInRegister() const override {
842     return false;
843   }
844 };
845 
846 class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
847 public:
848   explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
849                                         WebAssemblyABIInfo::ABIKind K)
850       : TargetCodeGenInfo(std::make_unique<WebAssemblyABIInfo>(CGT, K)) {}
851 
852   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
853                            CodeGen::CodeGenModule &CGM) const override {
854     TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
855     if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
856       if (const auto *Attr = FD->getAttr<WebAssemblyImportModuleAttr>()) {
857         llvm::Function *Fn = cast<llvm::Function>(GV);
858         llvm::AttrBuilder B(GV->getContext());
859         B.addAttribute("wasm-import-module", Attr->getImportModule());
860         Fn->addFnAttrs(B);
861       }
862       if (const auto *Attr = FD->getAttr<WebAssemblyImportNameAttr>()) {
863         llvm::Function *Fn = cast<llvm::Function>(GV);
864         llvm::AttrBuilder B(GV->getContext());
865         B.addAttribute("wasm-import-name", Attr->getImportName());
866         Fn->addFnAttrs(B);
867       }
868       if (const auto *Attr = FD->getAttr<WebAssemblyExportNameAttr>()) {
869         llvm::Function *Fn = cast<llvm::Function>(GV);
870         llvm::AttrBuilder B(GV->getContext());
871         B.addAttribute("wasm-export-name", Attr->getExportName());
872         Fn->addFnAttrs(B);
873       }
874     }
875 
876     if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
877       llvm::Function *Fn = cast<llvm::Function>(GV);
878       if (!FD->doesThisDeclarationHaveABody() && !FD->hasPrototype())
879         Fn->addFnAttr("no-prototype");
880     }
881   }
882 };
883 
884 /// Classify argument of given type \p Ty.
885 ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
886   Ty = useFirstFieldIfTransparentUnion(Ty);
887 
888   if (isAggregateTypeForABI(Ty)) {
889     // Records with non-trivial destructors/copy-constructors should not be
890     // passed by value.
891     if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
892       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
893     // Ignore empty structs/unions.
894     if (isEmptyRecord(getContext(), Ty, true))
895       return ABIArgInfo::getIgnore();
896     // Lower single-element structs to just pass a regular value. TODO: We
897     // could do reasonable-size multiple-element structs too, using getExpand(),
898     // though watch out for things like bitfields.
899     if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
900       return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
901     // For the experimental multivalue ABI, fully expand all other aggregates
902     if (Kind == ABIKind::ExperimentalMV) {
903       const RecordType *RT = Ty->getAs<RecordType>();
904       assert(RT);
905       bool HasBitField = false;
906       for (auto *Field : RT->getDecl()->fields()) {
907         if (Field->isBitField()) {
908           HasBitField = true;
909           break;
910         }
911       }
912       if (!HasBitField)
913         return ABIArgInfo::getExpand();
914     }
915   }
916 
917   // Otherwise just do the default thing.
918   return defaultInfo.classifyArgumentType(Ty);
919 }
920 
921 ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
922   if (isAggregateTypeForABI(RetTy)) {
923     // Records with non-trivial destructors/copy-constructors should not be
924     // returned by value.
925     if (!getRecordArgABI(RetTy, getCXXABI())) {
926       // Ignore empty structs/unions.
927       if (isEmptyRecord(getContext(), RetTy, true))
928         return ABIArgInfo::getIgnore();
929       // Lower single-element structs to just return a regular value. TODO: We
930       // could do reasonable-size multiple-element structs too, using
931       // ABIArgInfo::getDirect().
932       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
933         return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
934       // For the experimental multivalue ABI, return all other aggregates
935       if (Kind == ABIKind::ExperimentalMV)
936         return ABIArgInfo::getDirect();
937     }
938   }
939 
940   // Otherwise just do the default thing.
941   return defaultInfo.classifyReturnType(RetTy);
942 }
943 
944 Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
945                                       QualType Ty) const {
946   bool IsIndirect = isAggregateTypeForABI(Ty) &&
947                     !isEmptyRecord(getContext(), Ty, true) &&
948                     !isSingleElementStruct(Ty, getContext());
949   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
950                           getContext().getTypeInfoInChars(Ty),
951                           CharUnits::fromQuantity(4),
952                           /*AllowHigherAlign=*/true);
953 }
954 
955 //===----------------------------------------------------------------------===//
956 // le32/PNaCl bitcode ABI Implementation
957 //
958 // This is a simplified version of the x86_32 ABI.  Arguments and return values
959 // are always passed on the stack.
960 //===----------------------------------------------------------------------===//
961 
962 class PNaClABIInfo : public ABIInfo {
963  public:
964   PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
965 
966   ABIArgInfo classifyReturnType(QualType RetTy) const;
967   ABIArgInfo classifyArgumentType(QualType RetTy) const;
968 
969   void computeInfo(CGFunctionInfo &FI) const override;
970   Address EmitVAArg(CodeGenFunction &CGF,
971                     Address VAListAddr, QualType Ty) const override;
972 };
973 
974 class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
975  public:
976    PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
977        : TargetCodeGenInfo(std::make_unique<PNaClABIInfo>(CGT)) {}
978 };
979 
980 void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
981   if (!getCXXABI().classifyReturnType(FI))
982     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
983 
984   for (auto &I : FI.arguments())
985     I.info = classifyArgumentType(I.type);
986 }
987 
988 Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
989                                 QualType Ty) const {
990   // The PNaCL ABI is a bit odd, in that varargs don't use normal
991   // function classification. Structs get passed directly for varargs
992   // functions, through a rewriting transform in
993   // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
994   // this target to actually support a va_arg instructions with an
995   // aggregate type, unlike other targets.
996   return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
997 }
998 
999 /// Classify argument of given type \p Ty.
1000 ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
1001   if (isAggregateTypeForABI(Ty)) {
1002     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
1003       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
1004     return getNaturalAlignIndirect(Ty);
1005   } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
1006     // Treat an enum type as its underlying type.
1007     Ty = EnumTy->getDecl()->getIntegerType();
1008   } else if (Ty->isFloatingType()) {
1009     // Floating-point types don't go inreg.
1010     return ABIArgInfo::getDirect();
1011   } else if (const auto *EIT = Ty->getAs<BitIntType>()) {
1012     // Treat bit-precise integers as integers if <= 64, otherwise pass
1013     // indirectly.
1014     if (EIT->getNumBits() > 64)
1015       return getNaturalAlignIndirect(Ty);
1016     return ABIArgInfo::getDirect();
1017   }
1018 
1019   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
1020                                             : ABIArgInfo::getDirect());
1021 }
1022 
1023 ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
1024   if (RetTy->isVoidType())
1025     return ABIArgInfo::getIgnore();
1026 
1027   // In the PNaCl ABI we always return records/structures on the stack.
1028   if (isAggregateTypeForABI(RetTy))
1029     return getNaturalAlignIndirect(RetTy);
1030 
1031   // Treat bit-precise integers as integers if <= 64, otherwise pass indirectly.
1032   if (const auto *EIT = RetTy->getAs<BitIntType>()) {
1033     if (EIT->getNumBits() > 64)
1034       return getNaturalAlignIndirect(RetTy);
1035     return ABIArgInfo::getDirect();
1036   }
1037 
1038   // Treat an enum type as its underlying type.
1039   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1040     RetTy = EnumTy->getDecl()->getIntegerType();
1041 
1042   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
1043                                                : ABIArgInfo::getDirect());
1044 }
1045 
1046 /// IsX86_MMXType - Return true if this is an MMX type.
1047 bool IsX86_MMXType(llvm::Type *IRType) {
1048   // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
1049   return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
1050     cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
1051     IRType->getScalarSizeInBits() != 64;
1052 }
1053 
1054 static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1055                                           StringRef Constraint,
1056                                           llvm::Type* Ty) {
1057   bool IsMMXCons = llvm::StringSwitch<bool>(Constraint)
1058                      .Cases("y", "&y", "^Ym", true)
1059                      .Default(false);
1060   if (IsMMXCons && Ty->isVectorTy()) {
1061     if (cast<llvm::VectorType>(Ty)->getPrimitiveSizeInBits().getFixedSize() !=
1062         64) {
1063       // Invalid MMX constraint
1064       return nullptr;
1065     }
1066 
1067     return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
1068   }
1069 
1070   // No operation needed
1071   return Ty;
1072 }
1073 
1074 /// Returns true if this type can be passed in SSE registers with the
1075 /// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
1076 static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
1077   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
1078     if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) {
1079       if (BT->getKind() == BuiltinType::LongDouble) {
1080         if (&Context.getTargetInfo().getLongDoubleFormat() ==
1081             &llvm::APFloat::x87DoubleExtended())
1082           return false;
1083       }
1084       return true;
1085     }
1086   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
1087     // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
1088     // registers specially.
1089     unsigned VecSize = Context.getTypeSize(VT);
1090     if (VecSize == 128 || VecSize == 256 || VecSize == 512)
1091       return true;
1092   }
1093   return false;
1094 }
1095 
1096 /// Returns true if this aggregate is small enough to be passed in SSE registers
1097 /// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
1098 static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
1099   return NumMembers <= 4;
1100 }
1101 
1102 /// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
1103 static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
1104   auto AI = ABIArgInfo::getDirect(T);
1105   AI.setInReg(true);
1106   AI.setCanBeFlattened(false);
1107   return AI;
1108 }
1109 
1110 //===----------------------------------------------------------------------===//
1111 // X86-32 ABI Implementation
1112 //===----------------------------------------------------------------------===//
1113 
1114 /// Similar to llvm::CCState, but for Clang.
1115 struct CCState {
1116   CCState(CGFunctionInfo &FI)
1117       : IsPreassigned(FI.arg_size()), CC(FI.getCallingConvention()) {}
1118 
1119   llvm::SmallBitVector IsPreassigned;
1120   unsigned CC = CallingConv::CC_C;
1121   unsigned FreeRegs = 0;
1122   unsigned FreeSSERegs = 0;
1123 };
1124 
1125 /// X86_32ABIInfo - The X86-32 ABI information.
1126 class X86_32ABIInfo : public SwiftABIInfo {
1127   enum Class {
1128     Integer,
1129     Float
1130   };
1131 
1132   static const unsigned MinABIStackAlignInBytes = 4;
1133 
1134   bool IsDarwinVectorABI;
1135   bool IsRetSmallStructInRegABI;
1136   bool IsWin32StructABI;
1137   bool IsSoftFloatABI;
1138   bool IsMCUABI;
1139   bool IsLinuxABI;
1140   unsigned DefaultNumRegisterParameters;
1141 
1142   static bool isRegisterSize(unsigned Size) {
1143     return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
1144   }
1145 
1146   bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1147     // FIXME: Assumes vectorcall is in use.
1148     return isX86VectorTypeForVectorCall(getContext(), Ty);
1149   }
1150 
1151   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1152                                          uint64_t NumMembers) const override {
1153     // FIXME: Assumes vectorcall is in use.
1154     return isX86VectorCallAggregateSmallEnough(NumMembers);
1155   }
1156 
1157   bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
1158 
1159   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
1160   /// such that the argument will be passed in memory.
1161   ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
1162 
1163   ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
1164 
1165   /// Return the alignment to use for the given type on the stack.
1166   unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
1167 
1168   Class classify(QualType Ty) const;
1169   ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
1170   ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
1171 
1172   /// Updates the number of available free registers, returns
1173   /// true if any registers were allocated.
1174   bool updateFreeRegs(QualType Ty, CCState &State) const;
1175 
1176   bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
1177                                 bool &NeedsPadding) const;
1178   bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
1179 
1180   bool canExpandIndirectArgument(QualType Ty) const;
1181 
1182   /// Rewrite the function info so that all memory arguments use
1183   /// inalloca.
1184   void rewriteWithInAlloca(CGFunctionInfo &FI) const;
1185 
1186   void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1187                            CharUnits &StackOffset, ABIArgInfo &Info,
1188                            QualType Type) const;
1189   void runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const;
1190 
1191 public:
1192 
1193   void computeInfo(CGFunctionInfo &FI) const override;
1194   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1195                     QualType Ty) const override;
1196 
1197   X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1198                 bool RetSmallStructInRegABI, bool Win32StructABI,
1199                 unsigned NumRegisterParameters, bool SoftFloatABI)
1200     : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
1201       IsRetSmallStructInRegABI(RetSmallStructInRegABI),
1202       IsWin32StructABI(Win32StructABI), IsSoftFloatABI(SoftFloatABI),
1203       IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
1204       IsLinuxABI(CGT.getTarget().getTriple().isOSLinux() ||
1205                  CGT.getTarget().getTriple().isOSCygMing()),
1206       DefaultNumRegisterParameters(NumRegisterParameters) {}
1207 
1208   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
1209                                     bool asReturnValue) const override {
1210     // LLVM's x86-32 lowering currently only assigns up to three
1211     // integer registers and three fp registers.  Oddly, it'll use up to
1212     // four vector registers for vectors, but those can overlap with the
1213     // scalar registers.
1214     return occupiesMoreThan(CGT, scalars, /*total*/ 3);
1215   }
1216 
1217   bool isSwiftErrorInRegister() const override {
1218     // x86-32 lowering does not support passing swifterror in a register.
1219     return false;
1220   }
1221 };
1222 
1223 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
1224 public:
1225   X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1226                           bool RetSmallStructInRegABI, bool Win32StructABI,
1227                           unsigned NumRegisterParameters, bool SoftFloatABI)
1228       : TargetCodeGenInfo(std::make_unique<X86_32ABIInfo>(
1229             CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
1230             NumRegisterParameters, SoftFloatABI)) {}
1231 
1232   static bool isStructReturnInRegABI(
1233       const llvm::Triple &Triple, const CodeGenOptions &Opts);
1234 
1235   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1236                            CodeGen::CodeGenModule &CGM) const override;
1237 
1238   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
1239     // Darwin uses different dwarf register numbers for EH.
1240     if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
1241     return 4;
1242   }
1243 
1244   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1245                                llvm::Value *Address) const override;
1246 
1247   llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1248                                   StringRef Constraint,
1249                                   llvm::Type* Ty) const override {
1250     return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1251   }
1252 
1253   void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
1254                                 std::string &Constraints,
1255                                 std::vector<llvm::Type *> &ResultRegTypes,
1256                                 std::vector<llvm::Type *> &ResultTruncRegTypes,
1257                                 std::vector<LValue> &ResultRegDests,
1258                                 std::string &AsmString,
1259                                 unsigned NumOutputs) const override;
1260 
1261   llvm::Constant *
1262   getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
1263     unsigned Sig = (0xeb << 0) |  // jmp rel8
1264                    (0x06 << 8) |  //           .+0x08
1265                    ('v' << 16) |
1266                    ('2' << 24);
1267     return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1268   }
1269 
1270   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
1271     return "movl\t%ebp, %ebp"
1272            "\t\t// marker for objc_retainAutoreleaseReturnValue";
1273   }
1274 };
1275 
1276 }
1277 
1278 /// Rewrite input constraint references after adding some output constraints.
1279 /// In the case where there is one output and one input and we add one output,
1280 /// we need to replace all operand references greater than or equal to 1:
1281 ///     mov $0, $1
1282 ///     mov eax, $1
1283 /// The result will be:
1284 ///     mov $0, $2
1285 ///     mov eax, $2
1286 static void rewriteInputConstraintReferences(unsigned FirstIn,
1287                                              unsigned NumNewOuts,
1288                                              std::string &AsmString) {
1289   std::string Buf;
1290   llvm::raw_string_ostream OS(Buf);
1291   size_t Pos = 0;
1292   while (Pos < AsmString.size()) {
1293     size_t DollarStart = AsmString.find('$', Pos);
1294     if (DollarStart == std::string::npos)
1295       DollarStart = AsmString.size();
1296     size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1297     if (DollarEnd == std::string::npos)
1298       DollarEnd = AsmString.size();
1299     OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1300     Pos = DollarEnd;
1301     size_t NumDollars = DollarEnd - DollarStart;
1302     if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1303       // We have an operand reference.
1304       size_t DigitStart = Pos;
1305       if (AsmString[DigitStart] == '{') {
1306         OS << '{';
1307         ++DigitStart;
1308       }
1309       size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1310       if (DigitEnd == std::string::npos)
1311         DigitEnd = AsmString.size();
1312       StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1313       unsigned OperandIndex;
1314       if (!OperandStr.getAsInteger(10, OperandIndex)) {
1315         if (OperandIndex >= FirstIn)
1316           OperandIndex += NumNewOuts;
1317         OS << OperandIndex;
1318       } else {
1319         OS << OperandStr;
1320       }
1321       Pos = DigitEnd;
1322     }
1323   }
1324   AsmString = std::move(OS.str());
1325 }
1326 
1327 /// Add output constraints for EAX:EDX because they are return registers.
1328 void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1329     CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1330     std::vector<llvm::Type *> &ResultRegTypes,
1331     std::vector<llvm::Type *> &ResultTruncRegTypes,
1332     std::vector<LValue> &ResultRegDests, std::string &AsmString,
1333     unsigned NumOutputs) const {
1334   uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1335 
1336   // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1337   // larger.
1338   if (!Constraints.empty())
1339     Constraints += ',';
1340   if (RetWidth <= 32) {
1341     Constraints += "={eax}";
1342     ResultRegTypes.push_back(CGF.Int32Ty);
1343   } else {
1344     // Use the 'A' constraint for EAX:EDX.
1345     Constraints += "=A";
1346     ResultRegTypes.push_back(CGF.Int64Ty);
1347   }
1348 
1349   // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1350   llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1351   ResultTruncRegTypes.push_back(CoerceTy);
1352 
1353   // Coerce the integer by bitcasting the return slot pointer.
1354   ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(CGF),
1355                                                   CoerceTy->getPointerTo()));
1356   ResultRegDests.push_back(ReturnSlot);
1357 
1358   rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1359 }
1360 
1361 /// shouldReturnTypeInRegister - Determine if the given type should be
1362 /// returned in a register (for the Darwin and MCU ABI).
1363 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1364                                                ASTContext &Context) const {
1365   uint64_t Size = Context.getTypeSize(Ty);
1366 
1367   // For i386, type must be register sized.
1368   // For the MCU ABI, it only needs to be <= 8-byte
1369   if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1370    return false;
1371 
1372   if (Ty->isVectorType()) {
1373     // 64- and 128- bit vectors inside structures are not returned in
1374     // registers.
1375     if (Size == 64 || Size == 128)
1376       return false;
1377 
1378     return true;
1379   }
1380 
1381   // If this is a builtin, pointer, enum, complex type, member pointer, or
1382   // member function pointer it is ok.
1383   if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
1384       Ty->isAnyComplexType() || Ty->isEnumeralType() ||
1385       Ty->isBlockPointerType() || Ty->isMemberPointerType())
1386     return true;
1387 
1388   // Arrays are treated like records.
1389   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
1390     return shouldReturnTypeInRegister(AT->getElementType(), Context);
1391 
1392   // Otherwise, it must be a record type.
1393   const RecordType *RT = Ty->getAs<RecordType>();
1394   if (!RT) return false;
1395 
1396   // FIXME: Traverse bases here too.
1397 
1398   // Structure types are passed in register if all fields would be
1399   // passed in a register.
1400   for (const auto *FD : RT->getDecl()->fields()) {
1401     // Empty fields are ignored.
1402     if (isEmptyField(Context, FD, true))
1403       continue;
1404 
1405     // Check fields recursively.
1406     if (!shouldReturnTypeInRegister(FD->getType(), Context))
1407       return false;
1408   }
1409   return true;
1410 }
1411 
1412 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1413   // Treat complex types as the element type.
1414   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1415     Ty = CTy->getElementType();
1416 
1417   // Check for a type which we know has a simple scalar argument-passing
1418   // convention without any padding.  (We're specifically looking for 32
1419   // and 64-bit integer and integer-equivalents, float, and double.)
1420   if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1421       !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1422     return false;
1423 
1424   uint64_t Size = Context.getTypeSize(Ty);
1425   return Size == 32 || Size == 64;
1426 }
1427 
1428 static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
1429                           uint64_t &Size) {
1430   for (const auto *FD : RD->fields()) {
1431     // Scalar arguments on the stack get 4 byte alignment on x86. If the
1432     // argument is smaller than 32-bits, expanding the struct will create
1433     // alignment padding.
1434     if (!is32Or64BitBasicType(FD->getType(), Context))
1435       return false;
1436 
1437     // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1438     // how to expand them yet, and the predicate for telling if a bitfield still
1439     // counts as "basic" is more complicated than what we were doing previously.
1440     if (FD->isBitField())
1441       return false;
1442 
1443     Size += Context.getTypeSize(FD->getType());
1444   }
1445   return true;
1446 }
1447 
1448 static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
1449                                  uint64_t &Size) {
1450   // Don't do this if there are any non-empty bases.
1451   for (const CXXBaseSpecifier &Base : RD->bases()) {
1452     if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
1453                               Size))
1454       return false;
1455   }
1456   if (!addFieldSizes(Context, RD, Size))
1457     return false;
1458   return true;
1459 }
1460 
1461 /// Test whether an argument type which is to be passed indirectly (on the
1462 /// stack) would have the equivalent layout if it was expanded into separate
1463 /// arguments. If so, we prefer to do the latter to avoid inhibiting
1464 /// optimizations.
1465 bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1466   // We can only expand structure types.
1467   const RecordType *RT = Ty->getAs<RecordType>();
1468   if (!RT)
1469     return false;
1470   const RecordDecl *RD = RT->getDecl();
1471   uint64_t Size = 0;
1472   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1473     if (!IsWin32StructABI) {
1474       // On non-Windows, we have to conservatively match our old bitcode
1475       // prototypes in order to be ABI-compatible at the bitcode level.
1476       if (!CXXRD->isCLike())
1477         return false;
1478     } else {
1479       // Don't do this for dynamic classes.
1480       if (CXXRD->isDynamicClass())
1481         return false;
1482     }
1483     if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
1484       return false;
1485   } else {
1486     if (!addFieldSizes(getContext(), RD, Size))
1487       return false;
1488   }
1489 
1490   // We can do this if there was no alignment padding.
1491   return Size == getContext().getTypeSize(Ty);
1492 }
1493 
1494 ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
1495   // If the return value is indirect, then the hidden argument is consuming one
1496   // integer register.
1497   if (State.FreeRegs) {
1498     --State.FreeRegs;
1499     if (!IsMCUABI)
1500       return getNaturalAlignIndirectInReg(RetTy);
1501   }
1502   return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
1503 }
1504 
1505 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1506                                              CCState &State) const {
1507   if (RetTy->isVoidType())
1508     return ABIArgInfo::getIgnore();
1509 
1510   const Type *Base = nullptr;
1511   uint64_t NumElts = 0;
1512   if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1513        State.CC == llvm::CallingConv::X86_RegCall) &&
1514       isHomogeneousAggregate(RetTy, Base, NumElts)) {
1515     // The LLVM struct type for such an aggregate should lower properly.
1516     return ABIArgInfo::getDirect();
1517   }
1518 
1519   if (const VectorType *VT = RetTy->getAs<VectorType>()) {
1520     // On Darwin, some vectors are returned in registers.
1521     if (IsDarwinVectorABI) {
1522       uint64_t Size = getContext().getTypeSize(RetTy);
1523 
1524       // 128-bit vectors are a special case; they are returned in
1525       // registers and we need to make sure to pick a type the LLVM
1526       // backend will like.
1527       if (Size == 128)
1528         return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
1529             llvm::Type::getInt64Ty(getVMContext()), 2));
1530 
1531       // Always return in register if it fits in a general purpose
1532       // register, or if it is 64 bits and has a single element.
1533       if ((Size == 8 || Size == 16 || Size == 32) ||
1534           (Size == 64 && VT->getNumElements() == 1))
1535         return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1536                                                             Size));
1537 
1538       return getIndirectReturnResult(RetTy, State);
1539     }
1540 
1541     return ABIArgInfo::getDirect();
1542   }
1543 
1544   if (isAggregateTypeForABI(RetTy)) {
1545     if (const RecordType *RT = RetTy->getAs<RecordType>()) {
1546       // Structures with flexible arrays are always indirect.
1547       if (RT->getDecl()->hasFlexibleArrayMember())
1548         return getIndirectReturnResult(RetTy, State);
1549     }
1550 
1551     // If specified, structs and unions are always indirect.
1552     if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
1553       return getIndirectReturnResult(RetTy, State);
1554 
1555     // Ignore empty structs/unions.
1556     if (isEmptyRecord(getContext(), RetTy, true))
1557       return ABIArgInfo::getIgnore();
1558 
1559     // Return complex of _Float16 as <2 x half> so the backend will use xmm0.
1560     if (const ComplexType *CT = RetTy->getAs<ComplexType>()) {
1561       QualType ET = getContext().getCanonicalType(CT->getElementType());
1562       if (ET->isFloat16Type())
1563         return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
1564             llvm::Type::getHalfTy(getVMContext()), 2));
1565     }
1566 
1567     // Small structures which are register sized are generally returned
1568     // in a register.
1569     if (shouldReturnTypeInRegister(RetTy, getContext())) {
1570       uint64_t Size = getContext().getTypeSize(RetTy);
1571 
1572       // As a special-case, if the struct is a "single-element" struct, and
1573       // the field is of type "float" or "double", return it in a
1574       // floating-point register. (MSVC does not apply this special case.)
1575       // We apply a similar transformation for pointer types to improve the
1576       // quality of the generated IR.
1577       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
1578         if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
1579             || SeltTy->hasPointerRepresentation())
1580           return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1581 
1582       // FIXME: We should be able to narrow this integer in cases with dead
1583       // padding.
1584       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
1585     }
1586 
1587     return getIndirectReturnResult(RetTy, State);
1588   }
1589 
1590   // Treat an enum type as its underlying type.
1591   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1592     RetTy = EnumTy->getDecl()->getIntegerType();
1593 
1594   if (const auto *EIT = RetTy->getAs<BitIntType>())
1595     if (EIT->getNumBits() > 64)
1596       return getIndirectReturnResult(RetTy, State);
1597 
1598   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
1599                                                : ABIArgInfo::getDirect());
1600 }
1601 
1602 static bool isSIMDVectorType(ASTContext &Context, QualType Ty) {
1603   return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1604 }
1605 
1606 static bool isRecordWithSIMDVectorType(ASTContext &Context, QualType Ty) {
1607   const RecordType *RT = Ty->getAs<RecordType>();
1608   if (!RT)
1609     return false;
1610   const RecordDecl *RD = RT->getDecl();
1611 
1612   // If this is a C++ record, check the bases first.
1613   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1614     for (const auto &I : CXXRD->bases())
1615       if (!isRecordWithSIMDVectorType(Context, I.getType()))
1616         return false;
1617 
1618   for (const auto *i : RD->fields()) {
1619     QualType FT = i->getType();
1620 
1621     if (isSIMDVectorType(Context, FT))
1622       return true;
1623 
1624     if (isRecordWithSIMDVectorType(Context, FT))
1625       return true;
1626   }
1627 
1628   return false;
1629 }
1630 
1631 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1632                                                  unsigned Align) const {
1633   // Otherwise, if the alignment is less than or equal to the minimum ABI
1634   // alignment, just use the default; the backend will handle this.
1635   if (Align <= MinABIStackAlignInBytes)
1636     return 0; // Use default alignment.
1637 
1638   if (IsLinuxABI) {
1639     // Exclude other System V OS (e.g Darwin, PS4 and FreeBSD) since we don't
1640     // want to spend any effort dealing with the ramifications of ABI breaks.
1641     //
1642     // If the vector type is __m128/__m256/__m512, return the default alignment.
1643     if (Ty->isVectorType() && (Align == 16 || Align == 32 || Align == 64))
1644       return Align;
1645   }
1646   // On non-Darwin, the stack type alignment is always 4.
1647   if (!IsDarwinVectorABI) {
1648     // Set explicit alignment, since we may need to realign the top.
1649     return MinABIStackAlignInBytes;
1650   }
1651 
1652   // Otherwise, if the type contains an SSE vector type, the alignment is 16.
1653   if (Align >= 16 && (isSIMDVectorType(getContext(), Ty) ||
1654                       isRecordWithSIMDVectorType(getContext(), Ty)))
1655     return 16;
1656 
1657   return MinABIStackAlignInBytes;
1658 }
1659 
1660 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
1661                                             CCState &State) const {
1662   if (!ByVal) {
1663     if (State.FreeRegs) {
1664       --State.FreeRegs; // Non-byval indirects just use one pointer.
1665       if (!IsMCUABI)
1666         return getNaturalAlignIndirectInReg(Ty);
1667     }
1668     return getNaturalAlignIndirect(Ty, false);
1669   }
1670 
1671   // Compute the byval alignment.
1672   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1673   unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1674   if (StackAlign == 0)
1675     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
1676 
1677   // If the stack alignment is less than the type alignment, realign the
1678   // argument.
1679   bool Realign = TypeAlign > StackAlign;
1680   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1681                                  /*ByVal=*/true, Realign);
1682 }
1683 
1684 X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1685   const Type *T = isSingleElementStruct(Ty, getContext());
1686   if (!T)
1687     T = Ty.getTypePtr();
1688 
1689   if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1690     BuiltinType::Kind K = BT->getKind();
1691     if (K == BuiltinType::Float || K == BuiltinType::Double)
1692       return Float;
1693   }
1694   return Integer;
1695 }
1696 
1697 bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
1698   if (!IsSoftFloatABI) {
1699     Class C = classify(Ty);
1700     if (C == Float)
1701       return false;
1702   }
1703 
1704   unsigned Size = getContext().getTypeSize(Ty);
1705   unsigned SizeInRegs = (Size + 31) / 32;
1706 
1707   if (SizeInRegs == 0)
1708     return false;
1709 
1710   if (!IsMCUABI) {
1711     if (SizeInRegs > State.FreeRegs) {
1712       State.FreeRegs = 0;
1713       return false;
1714     }
1715   } else {
1716     // The MCU psABI allows passing parameters in-reg even if there are
1717     // earlier parameters that are passed on the stack. Also,
1718     // it does not allow passing >8-byte structs in-register,
1719     // even if there are 3 free registers available.
1720     if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1721       return false;
1722   }
1723 
1724   State.FreeRegs -= SizeInRegs;
1725   return true;
1726 }
1727 
1728 bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1729                                              bool &InReg,
1730                                              bool &NeedsPadding) const {
1731   // On Windows, aggregates other than HFAs are never passed in registers, and
1732   // they do not consume register slots. Homogenous floating-point aggregates
1733   // (HFAs) have already been dealt with at this point.
1734   if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1735     return false;
1736 
1737   NeedsPadding = false;
1738   InReg = !IsMCUABI;
1739 
1740   if (!updateFreeRegs(Ty, State))
1741     return false;
1742 
1743   if (IsMCUABI)
1744     return true;
1745 
1746   if (State.CC == llvm::CallingConv::X86_FastCall ||
1747       State.CC == llvm::CallingConv::X86_VectorCall ||
1748       State.CC == llvm::CallingConv::X86_RegCall) {
1749     if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
1750       NeedsPadding = true;
1751 
1752     return false;
1753   }
1754 
1755   return true;
1756 }
1757 
1758 bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1759   if (!updateFreeRegs(Ty, State))
1760     return false;
1761 
1762   if (IsMCUABI)
1763     return false;
1764 
1765   if (State.CC == llvm::CallingConv::X86_FastCall ||
1766       State.CC == llvm::CallingConv::X86_VectorCall ||
1767       State.CC == llvm::CallingConv::X86_RegCall) {
1768     if (getContext().getTypeSize(Ty) > 32)
1769       return false;
1770 
1771     return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1772         Ty->isReferenceType());
1773   }
1774 
1775   return true;
1776 }
1777 
1778 void X86_32ABIInfo::runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const {
1779   // Vectorcall x86 works subtly different than in x64, so the format is
1780   // a bit different than the x64 version.  First, all vector types (not HVAs)
1781   // are assigned, with the first 6 ending up in the [XYZ]MM0-5 registers.
1782   // This differs from the x64 implementation, where the first 6 by INDEX get
1783   // registers.
1784   // In the second pass over the arguments, HVAs are passed in the remaining
1785   // vector registers if possible, or indirectly by address. The address will be
1786   // passed in ECX/EDX if available. Any other arguments are passed according to
1787   // the usual fastcall rules.
1788   MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
1789   for (int I = 0, E = Args.size(); I < E; ++I) {
1790     const Type *Base = nullptr;
1791     uint64_t NumElts = 0;
1792     const QualType &Ty = Args[I].type;
1793     if ((Ty->isVectorType() || Ty->isBuiltinType()) &&
1794         isHomogeneousAggregate(Ty, Base, NumElts)) {
1795       if (State.FreeSSERegs >= NumElts) {
1796         State.FreeSSERegs -= NumElts;
1797         Args[I].info = ABIArgInfo::getDirectInReg();
1798         State.IsPreassigned.set(I);
1799       }
1800     }
1801   }
1802 }
1803 
1804 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1805                                                CCState &State) const {
1806   // FIXME: Set alignment on indirect arguments.
1807   bool IsFastCall = State.CC == llvm::CallingConv::X86_FastCall;
1808   bool IsRegCall = State.CC == llvm::CallingConv::X86_RegCall;
1809   bool IsVectorCall = State.CC == llvm::CallingConv::X86_VectorCall;
1810 
1811   Ty = useFirstFieldIfTransparentUnion(Ty);
1812   TypeInfo TI = getContext().getTypeInfo(Ty);
1813 
1814   // Check with the C++ ABI first.
1815   const RecordType *RT = Ty->getAs<RecordType>();
1816   if (RT) {
1817     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1818     if (RAA == CGCXXABI::RAA_Indirect) {
1819       return getIndirectResult(Ty, false, State);
1820     } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1821       // The field index doesn't matter, we'll fix it up later.
1822       return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1823     }
1824   }
1825 
1826   // Regcall uses the concept of a homogenous vector aggregate, similar
1827   // to other targets.
1828   const Type *Base = nullptr;
1829   uint64_t NumElts = 0;
1830   if ((IsRegCall || IsVectorCall) &&
1831       isHomogeneousAggregate(Ty, Base, NumElts)) {
1832     if (State.FreeSSERegs >= NumElts) {
1833       State.FreeSSERegs -= NumElts;
1834 
1835       // Vectorcall passes HVAs directly and does not flatten them, but regcall
1836       // does.
1837       if (IsVectorCall)
1838         return getDirectX86Hva();
1839 
1840       if (Ty->isBuiltinType() || Ty->isVectorType())
1841         return ABIArgInfo::getDirect();
1842       return ABIArgInfo::getExpand();
1843     }
1844     return getIndirectResult(Ty, /*ByVal=*/false, State);
1845   }
1846 
1847   if (isAggregateTypeForABI(Ty)) {
1848     // Structures with flexible arrays are always indirect.
1849     // FIXME: This should not be byval!
1850     if (RT && RT->getDecl()->hasFlexibleArrayMember())
1851       return getIndirectResult(Ty, true, State);
1852 
1853     // Ignore empty structs/unions on non-Windows.
1854     if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
1855       return ABIArgInfo::getIgnore();
1856 
1857     llvm::LLVMContext &LLVMContext = getVMContext();
1858     llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
1859     bool NeedsPadding = false;
1860     bool InReg;
1861     if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
1862       unsigned SizeInRegs = (TI.Width + 31) / 32;
1863       SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
1864       llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
1865       if (InReg)
1866         return ABIArgInfo::getDirectInReg(Result);
1867       else
1868         return ABIArgInfo::getDirect(Result);
1869     }
1870     llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
1871 
1872     // Pass over-aligned aggregates on Windows indirectly. This behavior was
1873     // added in MSVC 2015.
1874     if (IsWin32StructABI && TI.isAlignRequired() && TI.Align > 32)
1875       return getIndirectResult(Ty, /*ByVal=*/false, State);
1876 
1877     // Expand small (<= 128-bit) record types when we know that the stack layout
1878     // of those arguments will match the struct. This is important because the
1879     // LLVM backend isn't smart enough to remove byval, which inhibits many
1880     // optimizations.
1881     // Don't do this for the MCU if there are still free integer registers
1882     // (see X86_64 ABI for full explanation).
1883     if (TI.Width <= 4 * 32 && (!IsMCUABI || State.FreeRegs == 0) &&
1884         canExpandIndirectArgument(Ty))
1885       return ABIArgInfo::getExpandWithPadding(
1886           IsFastCall || IsVectorCall || IsRegCall, PaddingType);
1887 
1888     return getIndirectResult(Ty, true, State);
1889   }
1890 
1891   if (const VectorType *VT = Ty->getAs<VectorType>()) {
1892     // On Windows, vectors are passed directly if registers are available, or
1893     // indirectly if not. This avoids the need to align argument memory. Pass
1894     // user-defined vector types larger than 512 bits indirectly for simplicity.
1895     if (IsWin32StructABI) {
1896       if (TI.Width <= 512 && State.FreeSSERegs > 0) {
1897         --State.FreeSSERegs;
1898         return ABIArgInfo::getDirectInReg();
1899       }
1900       return getIndirectResult(Ty, /*ByVal=*/false, State);
1901     }
1902 
1903     // On Darwin, some vectors are passed in memory, we handle this by passing
1904     // it as an i8/i16/i32/i64.
1905     if (IsDarwinVectorABI) {
1906       if ((TI.Width == 8 || TI.Width == 16 || TI.Width == 32) ||
1907           (TI.Width == 64 && VT->getNumElements() == 1))
1908         return ABIArgInfo::getDirect(
1909             llvm::IntegerType::get(getVMContext(), TI.Width));
1910     }
1911 
1912     if (IsX86_MMXType(CGT.ConvertType(Ty)))
1913       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
1914 
1915     return ABIArgInfo::getDirect();
1916   }
1917 
1918 
1919   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1920     Ty = EnumTy->getDecl()->getIntegerType();
1921 
1922   bool InReg = shouldPrimitiveUseInReg(Ty, State);
1923 
1924   if (isPromotableIntegerTypeForABI(Ty)) {
1925     if (InReg)
1926       return ABIArgInfo::getExtendInReg(Ty);
1927     return ABIArgInfo::getExtend(Ty);
1928   }
1929 
1930   if (const auto *EIT = Ty->getAs<BitIntType>()) {
1931     if (EIT->getNumBits() <= 64) {
1932       if (InReg)
1933         return ABIArgInfo::getDirectInReg();
1934       return ABIArgInfo::getDirect();
1935     }
1936     return getIndirectResult(Ty, /*ByVal=*/false, State);
1937   }
1938 
1939   if (InReg)
1940     return ABIArgInfo::getDirectInReg();
1941   return ABIArgInfo::getDirect();
1942 }
1943 
1944 void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
1945   CCState State(FI);
1946   if (IsMCUABI)
1947     State.FreeRegs = 3;
1948   else if (State.CC == llvm::CallingConv::X86_FastCall) {
1949     State.FreeRegs = 2;
1950     State.FreeSSERegs = 3;
1951   } else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1952     State.FreeRegs = 2;
1953     State.FreeSSERegs = 6;
1954   } else if (FI.getHasRegParm())
1955     State.FreeRegs = FI.getRegParm();
1956   else if (State.CC == llvm::CallingConv::X86_RegCall) {
1957     State.FreeRegs = 5;
1958     State.FreeSSERegs = 8;
1959   } else if (IsWin32StructABI) {
1960     // Since MSVC 2015, the first three SSE vectors have been passed in
1961     // registers. The rest are passed indirectly.
1962     State.FreeRegs = DefaultNumRegisterParameters;
1963     State.FreeSSERegs = 3;
1964   } else
1965     State.FreeRegs = DefaultNumRegisterParameters;
1966 
1967   if (!::classifyReturnType(getCXXABI(), FI, *this)) {
1968     FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
1969   } else if (FI.getReturnInfo().isIndirect()) {
1970     // The C++ ABI is not aware of register usage, so we have to check if the
1971     // return value was sret and put it in a register ourselves if appropriate.
1972     if (State.FreeRegs) {
1973       --State.FreeRegs;  // The sret parameter consumes a register.
1974       if (!IsMCUABI)
1975         FI.getReturnInfo().setInReg(true);
1976     }
1977   }
1978 
1979   // The chain argument effectively gives us another free register.
1980   if (FI.isChainCall())
1981     ++State.FreeRegs;
1982 
1983   // For vectorcall, do a first pass over the arguments, assigning FP and vector
1984   // arguments to XMM registers as available.
1985   if (State.CC == llvm::CallingConv::X86_VectorCall)
1986     runVectorCallFirstPass(FI, State);
1987 
1988   bool UsedInAlloca = false;
1989   MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
1990   for (int I = 0, E = Args.size(); I < E; ++I) {
1991     // Skip arguments that have already been assigned.
1992     if (State.IsPreassigned.test(I))
1993       continue;
1994 
1995     Args[I].info = classifyArgumentType(Args[I].type, State);
1996     UsedInAlloca |= (Args[I].info.getKind() == ABIArgInfo::InAlloca);
1997   }
1998 
1999   // If we needed to use inalloca for any argument, do a second pass and rewrite
2000   // all the memory arguments to use inalloca.
2001   if (UsedInAlloca)
2002     rewriteWithInAlloca(FI);
2003 }
2004 
2005 void
2006 X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
2007                                    CharUnits &StackOffset, ABIArgInfo &Info,
2008                                    QualType Type) const {
2009   // Arguments are always 4-byte-aligned.
2010   CharUnits WordSize = CharUnits::fromQuantity(4);
2011   assert(StackOffset.isMultipleOf(WordSize) && "unaligned inalloca struct");
2012 
2013   // sret pointers and indirect things will require an extra pointer
2014   // indirection, unless they are byval. Most things are byval, and will not
2015   // require this indirection.
2016   bool IsIndirect = false;
2017   if (Info.isIndirect() && !Info.getIndirectByVal())
2018     IsIndirect = true;
2019   Info = ABIArgInfo::getInAlloca(FrameFields.size(), IsIndirect);
2020   llvm::Type *LLTy = CGT.ConvertTypeForMem(Type);
2021   if (IsIndirect)
2022     LLTy = LLTy->getPointerTo(0);
2023   FrameFields.push_back(LLTy);
2024   StackOffset += IsIndirect ? WordSize : getContext().getTypeSizeInChars(Type);
2025 
2026   // Insert padding bytes to respect alignment.
2027   CharUnits FieldEnd = StackOffset;
2028   StackOffset = FieldEnd.alignTo(WordSize);
2029   if (StackOffset != FieldEnd) {
2030     CharUnits NumBytes = StackOffset - FieldEnd;
2031     llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
2032     Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
2033     FrameFields.push_back(Ty);
2034   }
2035 }
2036 
2037 static bool isArgInAlloca(const ABIArgInfo &Info) {
2038   // Leave ignored and inreg arguments alone.
2039   switch (Info.getKind()) {
2040   case ABIArgInfo::InAlloca:
2041     return true;
2042   case ABIArgInfo::Ignore:
2043   case ABIArgInfo::IndirectAliased:
2044     return false;
2045   case ABIArgInfo::Indirect:
2046   case ABIArgInfo::Direct:
2047   case ABIArgInfo::Extend:
2048     return !Info.getInReg();
2049   case ABIArgInfo::Expand:
2050   case ABIArgInfo::CoerceAndExpand:
2051     // These are aggregate types which are never passed in registers when
2052     // inalloca is involved.
2053     return true;
2054   }
2055   llvm_unreachable("invalid enum");
2056 }
2057 
2058 void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
2059   assert(IsWin32StructABI && "inalloca only supported on win32");
2060 
2061   // Build a packed struct type for all of the arguments in memory.
2062   SmallVector<llvm::Type *, 6> FrameFields;
2063 
2064   // The stack alignment is always 4.
2065   CharUnits StackAlign = CharUnits::fromQuantity(4);
2066 
2067   CharUnits StackOffset;
2068   CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
2069 
2070   // Put 'this' into the struct before 'sret', if necessary.
2071   bool IsThisCall =
2072       FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
2073   ABIArgInfo &Ret = FI.getReturnInfo();
2074   if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
2075       isArgInAlloca(I->info)) {
2076     addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
2077     ++I;
2078   }
2079 
2080   // Put the sret parameter into the inalloca struct if it's in memory.
2081   if (Ret.isIndirect() && !Ret.getInReg()) {
2082     addFieldToArgStruct(FrameFields, StackOffset, Ret, FI.getReturnType());
2083     // On Windows, the hidden sret parameter is always returned in eax.
2084     Ret.setInAllocaSRet(IsWin32StructABI);
2085   }
2086 
2087   // Skip the 'this' parameter in ecx.
2088   if (IsThisCall)
2089     ++I;
2090 
2091   // Put arguments passed in memory into the struct.
2092   for (; I != E; ++I) {
2093     if (isArgInAlloca(I->info))
2094       addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
2095   }
2096 
2097   FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
2098                                         /*isPacked=*/true),
2099                   StackAlign);
2100 }
2101 
2102 Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
2103                                  Address VAListAddr, QualType Ty) const {
2104 
2105   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
2106 
2107   // x86-32 changes the alignment of certain arguments on the stack.
2108   //
2109   // Just messing with TypeInfo like this works because we never pass
2110   // anything indirectly.
2111   TypeInfo.Align = CharUnits::fromQuantity(
2112                 getTypeStackAlignInBytes(Ty, TypeInfo.Align.getQuantity()));
2113 
2114   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
2115                           TypeInfo, CharUnits::fromQuantity(4),
2116                           /*AllowHigherAlign*/ true);
2117 }
2118 
2119 bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
2120     const llvm::Triple &Triple, const CodeGenOptions &Opts) {
2121   assert(Triple.getArch() == llvm::Triple::x86);
2122 
2123   switch (Opts.getStructReturnConvention()) {
2124   case CodeGenOptions::SRCK_Default:
2125     break;
2126   case CodeGenOptions::SRCK_OnStack:  // -fpcc-struct-return
2127     return false;
2128   case CodeGenOptions::SRCK_InRegs:  // -freg-struct-return
2129     return true;
2130   }
2131 
2132   if (Triple.isOSDarwin() || Triple.isOSIAMCU())
2133     return true;
2134 
2135   switch (Triple.getOS()) {
2136   case llvm::Triple::DragonFly:
2137   case llvm::Triple::FreeBSD:
2138   case llvm::Triple::OpenBSD:
2139   case llvm::Triple::Win32:
2140     return true;
2141   default:
2142     return false;
2143   }
2144 }
2145 
2146 static void addX86InterruptAttrs(const FunctionDecl *FD, llvm::GlobalValue *GV,
2147                                  CodeGen::CodeGenModule &CGM) {
2148   if (!FD->hasAttr<AnyX86InterruptAttr>())
2149     return;
2150 
2151   llvm::Function *Fn = cast<llvm::Function>(GV);
2152   Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2153   if (FD->getNumParams() == 0)
2154     return;
2155 
2156   auto PtrTy = cast<PointerType>(FD->getParamDecl(0)->getType());
2157   llvm::Type *ByValTy = CGM.getTypes().ConvertType(PtrTy->getPointeeType());
2158   llvm::Attribute NewAttr = llvm::Attribute::getWithByValType(
2159     Fn->getContext(), ByValTy);
2160   Fn->addParamAttr(0, NewAttr);
2161 }
2162 
2163 void X86_32TargetCodeGenInfo::setTargetAttributes(
2164     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2165   if (GV->isDeclaration())
2166     return;
2167   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2168     if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2169       llvm::Function *Fn = cast<llvm::Function>(GV);
2170       Fn->addFnAttr("stackrealign");
2171     }
2172 
2173     addX86InterruptAttrs(FD, GV, CGM);
2174   }
2175 }
2176 
2177 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
2178                                                CodeGen::CodeGenFunction &CGF,
2179                                                llvm::Value *Address) const {
2180   CodeGen::CGBuilderTy &Builder = CGF.Builder;
2181 
2182   llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
2183 
2184   // 0-7 are the eight integer registers;  the order is different
2185   //   on Darwin (for EH), but the range is the same.
2186   // 8 is %eip.
2187   AssignToArrayRange(Builder, Address, Four8, 0, 8);
2188 
2189   if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
2190     // 12-16 are st(0..4).  Not sure why we stop at 4.
2191     // These have size 16, which is sizeof(long double) on
2192     // platforms with 8-byte alignment for that type.
2193     llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
2194     AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
2195 
2196   } else {
2197     // 9 is %eflags, which doesn't get a size on Darwin for some
2198     // reason.
2199     Builder.CreateAlignedStore(
2200         Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
2201                                CharUnits::One());
2202 
2203     // 11-16 are st(0..5).  Not sure why we stop at 5.
2204     // These have size 12, which is sizeof(long double) on
2205     // platforms with 4-byte alignment for that type.
2206     llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
2207     AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
2208   }
2209 
2210   return false;
2211 }
2212 
2213 //===----------------------------------------------------------------------===//
2214 // X86-64 ABI Implementation
2215 //===----------------------------------------------------------------------===//
2216 
2217 
2218 namespace {
2219 /// The AVX ABI level for X86 targets.
2220 enum class X86AVXABILevel {
2221   None,
2222   AVX,
2223   AVX512
2224 };
2225 
2226 /// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
2227 static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
2228   switch (AVXLevel) {
2229   case X86AVXABILevel::AVX512:
2230     return 512;
2231   case X86AVXABILevel::AVX:
2232     return 256;
2233   case X86AVXABILevel::None:
2234     return 128;
2235   }
2236   llvm_unreachable("Unknown AVXLevel");
2237 }
2238 
2239 /// X86_64ABIInfo - The X86_64 ABI information.
2240 class X86_64ABIInfo : public SwiftABIInfo {
2241   enum Class {
2242     Integer = 0,
2243     SSE,
2244     SSEUp,
2245     X87,
2246     X87Up,
2247     ComplexX87,
2248     NoClass,
2249     Memory
2250   };
2251 
2252   /// merge - Implement the X86_64 ABI merging algorithm.
2253   ///
2254   /// Merge an accumulating classification \arg Accum with a field
2255   /// classification \arg Field.
2256   ///
2257   /// \param Accum - The accumulating classification. This should
2258   /// always be either NoClass or the result of a previous merge
2259   /// call. In addition, this should never be Memory (the caller
2260   /// should just return Memory for the aggregate).
2261   static Class merge(Class Accum, Class Field);
2262 
2263   /// postMerge - Implement the X86_64 ABI post merging algorithm.
2264   ///
2265   /// Post merger cleanup, reduces a malformed Hi and Lo pair to
2266   /// final MEMORY or SSE classes when necessary.
2267   ///
2268   /// \param AggregateSize - The size of the current aggregate in
2269   /// the classification process.
2270   ///
2271   /// \param Lo - The classification for the parts of the type
2272   /// residing in the low word of the containing object.
2273   ///
2274   /// \param Hi - The classification for the parts of the type
2275   /// residing in the higher words of the containing object.
2276   ///
2277   void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
2278 
2279   /// classify - Determine the x86_64 register classes in which the
2280   /// given type T should be passed.
2281   ///
2282   /// \param Lo - The classification for the parts of the type
2283   /// residing in the low word of the containing object.
2284   ///
2285   /// \param Hi - The classification for the parts of the type
2286   /// residing in the high word of the containing object.
2287   ///
2288   /// \param OffsetBase - The bit offset of this type in the
2289   /// containing object.  Some parameters are classified different
2290   /// depending on whether they straddle an eightbyte boundary.
2291   ///
2292   /// \param isNamedArg - Whether the argument in question is a "named"
2293   /// argument, as used in AMD64-ABI 3.5.7.
2294   ///
2295   /// If a word is unused its result will be NoClass; if a type should
2296   /// be passed in Memory then at least the classification of \arg Lo
2297   /// will be Memory.
2298   ///
2299   /// The \arg Lo class will be NoClass iff the argument is ignored.
2300   ///
2301   /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
2302   /// also be ComplexX87.
2303   void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
2304                 bool isNamedArg) const;
2305 
2306   llvm::Type *GetByteVectorType(QualType Ty) const;
2307   llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
2308                                  unsigned IROffset, QualType SourceTy,
2309                                  unsigned SourceOffset) const;
2310   llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
2311                                      unsigned IROffset, QualType SourceTy,
2312                                      unsigned SourceOffset) const;
2313 
2314   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2315   /// such that the argument will be returned in memory.
2316   ABIArgInfo getIndirectReturnResult(QualType Ty) const;
2317 
2318   /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2319   /// such that the argument will be passed in memory.
2320   ///
2321   /// \param freeIntRegs - The number of free integer registers remaining
2322   /// available.
2323   ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
2324 
2325   ABIArgInfo classifyReturnType(QualType RetTy) const;
2326 
2327   ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
2328                                   unsigned &neededInt, unsigned &neededSSE,
2329                                   bool isNamedArg) const;
2330 
2331   ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
2332                                        unsigned &NeededSSE) const;
2333 
2334   ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
2335                                            unsigned &NeededSSE) const;
2336 
2337   bool IsIllegalVectorType(QualType Ty) const;
2338 
2339   /// The 0.98 ABI revision clarified a lot of ambiguities,
2340   /// unfortunately in ways that were not always consistent with
2341   /// certain previous compilers.  In particular, platforms which
2342   /// required strict binary compatibility with older versions of GCC
2343   /// may need to exempt themselves.
2344   bool honorsRevision0_98() const {
2345     return !getTarget().getTriple().isOSDarwin();
2346   }
2347 
2348   /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to
2349   /// classify it as INTEGER (for compatibility with older clang compilers).
2350   bool classifyIntegerMMXAsSSE() const {
2351     // Clang <= 3.8 did not do this.
2352     if (getContext().getLangOpts().getClangABICompat() <=
2353         LangOptions::ClangABI::Ver3_8)
2354       return false;
2355 
2356     const llvm::Triple &Triple = getTarget().getTriple();
2357     if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
2358       return false;
2359     if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
2360       return false;
2361     return true;
2362   }
2363 
2364   // GCC classifies vectors of __int128 as memory.
2365   bool passInt128VectorsInMem() const {
2366     // Clang <= 9.0 did not do this.
2367     if (getContext().getLangOpts().getClangABICompat() <=
2368         LangOptions::ClangABI::Ver9)
2369       return false;
2370 
2371     const llvm::Triple &T = getTarget().getTriple();
2372     return T.isOSLinux() || T.isOSNetBSD();
2373   }
2374 
2375   X86AVXABILevel AVXLevel;
2376   // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
2377   // 64-bit hardware.
2378   bool Has64BitPointers;
2379 
2380 public:
2381   X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
2382       SwiftABIInfo(CGT), AVXLevel(AVXLevel),
2383       Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
2384   }
2385 
2386   bool isPassedUsingAVXType(QualType type) const {
2387     unsigned neededInt, neededSSE;
2388     // The freeIntRegs argument doesn't matter here.
2389     ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
2390                                            /*isNamedArg*/true);
2391     if (info.isDirect()) {
2392       llvm::Type *ty = info.getCoerceToType();
2393       if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
2394         return vectorTy->getPrimitiveSizeInBits().getFixedSize() > 128;
2395     }
2396     return false;
2397   }
2398 
2399   void computeInfo(CGFunctionInfo &FI) const override;
2400 
2401   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2402                     QualType Ty) const override;
2403   Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
2404                       QualType Ty) const override;
2405 
2406   bool has64BitPointers() const {
2407     return Has64BitPointers;
2408   }
2409 
2410   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
2411                                     bool asReturnValue) const override {
2412     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2413   }
2414   bool isSwiftErrorInRegister() const override {
2415     return true;
2416   }
2417 };
2418 
2419 /// WinX86_64ABIInfo - The Windows X86_64 ABI information.
2420 class WinX86_64ABIInfo : public SwiftABIInfo {
2421 public:
2422   WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2423       : SwiftABIInfo(CGT), AVXLevel(AVXLevel),
2424         IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
2425 
2426   void computeInfo(CGFunctionInfo &FI) const override;
2427 
2428   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2429                     QualType Ty) const override;
2430 
2431   bool isHomogeneousAggregateBaseType(QualType Ty) const override {
2432     // FIXME: Assumes vectorcall is in use.
2433     return isX86VectorTypeForVectorCall(getContext(), Ty);
2434   }
2435 
2436   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2437                                          uint64_t NumMembers) const override {
2438     // FIXME: Assumes vectorcall is in use.
2439     return isX86VectorCallAggregateSmallEnough(NumMembers);
2440   }
2441 
2442   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars,
2443                                     bool asReturnValue) const override {
2444     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2445   }
2446 
2447   bool isSwiftErrorInRegister() const override {
2448     return true;
2449   }
2450 
2451 private:
2452   ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
2453                       bool IsVectorCall, bool IsRegCall) const;
2454   ABIArgInfo reclassifyHvaArgForVectorCall(QualType Ty, unsigned &FreeSSERegs,
2455                                            const ABIArgInfo &current) const;
2456 
2457   X86AVXABILevel AVXLevel;
2458 
2459   bool IsMingw64;
2460 };
2461 
2462 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2463 public:
2464   X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2465       : TargetCodeGenInfo(std::make_unique<X86_64ABIInfo>(CGT, AVXLevel)) {}
2466 
2467   const X86_64ABIInfo &getABIInfo() const {
2468     return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2469   }
2470 
2471   /// Disable tail call on x86-64. The epilogue code before the tail jump blocks
2472   /// autoreleaseRV/retainRV and autoreleaseRV/unsafeClaimRV optimizations.
2473   bool markARCOptimizedReturnCallsAsNoTail() const override { return true; }
2474 
2475   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2476     return 7;
2477   }
2478 
2479   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2480                                llvm::Value *Address) const override {
2481     llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2482 
2483     // 0-15 are the 16 integer registers.
2484     // 16 is %rip.
2485     AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2486     return false;
2487   }
2488 
2489   llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
2490                                   StringRef Constraint,
2491                                   llvm::Type* Ty) const override {
2492     return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2493   }
2494 
2495   bool isNoProtoCallVariadic(const CallArgList &args,
2496                              const FunctionNoProtoType *fnType) const override {
2497     // The default CC on x86-64 sets %al to the number of SSA
2498     // registers used, and GCC sets this when calling an unprototyped
2499     // function, so we override the default behavior.  However, don't do
2500     // that when AVX types are involved: the ABI explicitly states it is
2501     // undefined, and it doesn't work in practice because of how the ABI
2502     // defines varargs anyway.
2503     if (fnType->getCallConv() == CC_C) {
2504       bool HasAVXType = false;
2505       for (CallArgList::const_iterator
2506              it = args.begin(), ie = args.end(); it != ie; ++it) {
2507         if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2508           HasAVXType = true;
2509           break;
2510         }
2511       }
2512 
2513       if (!HasAVXType)
2514         return true;
2515     }
2516 
2517     return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
2518   }
2519 
2520   llvm::Constant *
2521   getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
2522     unsigned Sig = (0xeb << 0) | // jmp rel8
2523                    (0x06 << 8) | //           .+0x08
2524                    ('v' << 16) |
2525                    ('2' << 24);
2526     return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2527   }
2528 
2529   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2530                            CodeGen::CodeGenModule &CGM) const override {
2531     if (GV->isDeclaration())
2532       return;
2533     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2534       if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2535         llvm::Function *Fn = cast<llvm::Function>(GV);
2536         Fn->addFnAttr("stackrealign");
2537       }
2538 
2539       addX86InterruptAttrs(FD, GV, CGM);
2540     }
2541   }
2542 
2543   void checkFunctionCallABI(CodeGenModule &CGM, SourceLocation CallLoc,
2544                             const FunctionDecl *Caller,
2545                             const FunctionDecl *Callee,
2546                             const CallArgList &Args) const override;
2547 };
2548 
2549 static void initFeatureMaps(const ASTContext &Ctx,
2550                             llvm::StringMap<bool> &CallerMap,
2551                             const FunctionDecl *Caller,
2552                             llvm::StringMap<bool> &CalleeMap,
2553                             const FunctionDecl *Callee) {
2554   if (CalleeMap.empty() && CallerMap.empty()) {
2555     // The caller is potentially nullptr in the case where the call isn't in a
2556     // function.  In this case, the getFunctionFeatureMap ensures we just get
2557     // the TU level setting (since it cannot be modified by 'target'..
2558     Ctx.getFunctionFeatureMap(CallerMap, Caller);
2559     Ctx.getFunctionFeatureMap(CalleeMap, Callee);
2560   }
2561 }
2562 
2563 static bool checkAVXParamFeature(DiagnosticsEngine &Diag,
2564                                  SourceLocation CallLoc,
2565                                  const llvm::StringMap<bool> &CallerMap,
2566                                  const llvm::StringMap<bool> &CalleeMap,
2567                                  QualType Ty, StringRef Feature,
2568                                  bool IsArgument) {
2569   bool CallerHasFeat = CallerMap.lookup(Feature);
2570   bool CalleeHasFeat = CalleeMap.lookup(Feature);
2571   if (!CallerHasFeat && !CalleeHasFeat)
2572     return Diag.Report(CallLoc, diag::warn_avx_calling_convention)
2573            << IsArgument << Ty << Feature;
2574 
2575   // Mixing calling conventions here is very clearly an error.
2576   if (!CallerHasFeat || !CalleeHasFeat)
2577     return Diag.Report(CallLoc, diag::err_avx_calling_convention)
2578            << IsArgument << Ty << Feature;
2579 
2580   // Else, both caller and callee have the required feature, so there is no need
2581   // to diagnose.
2582   return false;
2583 }
2584 
2585 static bool checkAVXParam(DiagnosticsEngine &Diag, ASTContext &Ctx,
2586                           SourceLocation CallLoc,
2587                           const llvm::StringMap<bool> &CallerMap,
2588                           const llvm::StringMap<bool> &CalleeMap, QualType Ty,
2589                           bool IsArgument) {
2590   uint64_t Size = Ctx.getTypeSize(Ty);
2591   if (Size > 256)
2592     return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty,
2593                                 "avx512f", IsArgument);
2594 
2595   if (Size > 128)
2596     return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty, "avx",
2597                                 IsArgument);
2598 
2599   return false;
2600 }
2601 
2602 void X86_64TargetCodeGenInfo::checkFunctionCallABI(
2603     CodeGenModule &CGM, SourceLocation CallLoc, const FunctionDecl *Caller,
2604     const FunctionDecl *Callee, const CallArgList &Args) const {
2605   llvm::StringMap<bool> CallerMap;
2606   llvm::StringMap<bool> CalleeMap;
2607   unsigned ArgIndex = 0;
2608 
2609   // We need to loop through the actual call arguments rather than the the
2610   // function's parameters, in case this variadic.
2611   for (const CallArg &Arg : Args) {
2612     // The "avx" feature changes how vectors >128 in size are passed. "avx512f"
2613     // additionally changes how vectors >256 in size are passed. Like GCC, we
2614     // warn when a function is called with an argument where this will change.
2615     // Unlike GCC, we also error when it is an obvious ABI mismatch, that is,
2616     // the caller and callee features are mismatched.
2617     // Unfortunately, we cannot do this diagnostic in SEMA, since the callee can
2618     // change its ABI with attribute-target after this call.
2619     if (Arg.getType()->isVectorType() &&
2620         CGM.getContext().getTypeSize(Arg.getType()) > 128) {
2621       initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
2622       QualType Ty = Arg.getType();
2623       // The CallArg seems to have desugared the type already, so for clearer
2624       // diagnostics, replace it with the type in the FunctionDecl if possible.
2625       if (ArgIndex < Callee->getNumParams())
2626         Ty = Callee->getParamDecl(ArgIndex)->getType();
2627 
2628       if (checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap,
2629                         CalleeMap, Ty, /*IsArgument*/ true))
2630         return;
2631     }
2632     ++ArgIndex;
2633   }
2634 
2635   // Check return always, as we don't have a good way of knowing in codegen
2636   // whether this value is used, tail-called, etc.
2637   if (Callee->getReturnType()->isVectorType() &&
2638       CGM.getContext().getTypeSize(Callee->getReturnType()) > 128) {
2639     initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
2640     checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap,
2641                   CalleeMap, Callee->getReturnType(),
2642                   /*IsArgument*/ false);
2643   }
2644 }
2645 
2646 static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
2647   // If the argument does not end in .lib, automatically add the suffix.
2648   // If the argument contains a space, enclose it in quotes.
2649   // This matches the behavior of MSVC.
2650   bool Quote = Lib.contains(' ');
2651   std::string ArgStr = Quote ? "\"" : "";
2652   ArgStr += Lib;
2653   if (!Lib.endswith_insensitive(".lib") && !Lib.endswith_insensitive(".a"))
2654     ArgStr += ".lib";
2655   ArgStr += Quote ? "\"" : "";
2656   return ArgStr;
2657 }
2658 
2659 class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2660 public:
2661   WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2662         bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2663         unsigned NumRegisterParameters)
2664     : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
2665         Win32StructABI, NumRegisterParameters, false) {}
2666 
2667   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2668                            CodeGen::CodeGenModule &CGM) const override;
2669 
2670   void getDependentLibraryOption(llvm::StringRef Lib,
2671                                  llvm::SmallString<24> &Opt) const override {
2672     Opt = "/DEFAULTLIB:";
2673     Opt += qualifyWindowsLibrary(Lib);
2674   }
2675 
2676   void getDetectMismatchOption(llvm::StringRef Name,
2677                                llvm::StringRef Value,
2678                                llvm::SmallString<32> &Opt) const override {
2679     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2680   }
2681 };
2682 
2683 static void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2684                                           CodeGen::CodeGenModule &CGM) {
2685   if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(GV)) {
2686 
2687     if (CGM.getCodeGenOpts().StackProbeSize != 4096)
2688       Fn->addFnAttr("stack-probe-size",
2689                     llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
2690     if (CGM.getCodeGenOpts().NoStackArgProbe)
2691       Fn->addFnAttr("no-stack-arg-probe");
2692   }
2693 }
2694 
2695 void WinX86_32TargetCodeGenInfo::setTargetAttributes(
2696     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2697   X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2698   if (GV->isDeclaration())
2699     return;
2700   addStackProbeTargetAttributes(D, GV, CGM);
2701 }
2702 
2703 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2704 public:
2705   WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2706                              X86AVXABILevel AVXLevel)
2707       : TargetCodeGenInfo(std::make_unique<WinX86_64ABIInfo>(CGT, AVXLevel)) {}
2708 
2709   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2710                            CodeGen::CodeGenModule &CGM) const override;
2711 
2712   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2713     return 7;
2714   }
2715 
2716   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2717                                llvm::Value *Address) const override {
2718     llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2719 
2720     // 0-15 are the 16 integer registers.
2721     // 16 is %rip.
2722     AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2723     return false;
2724   }
2725 
2726   void getDependentLibraryOption(llvm::StringRef Lib,
2727                                  llvm::SmallString<24> &Opt) const override {
2728     Opt = "/DEFAULTLIB:";
2729     Opt += qualifyWindowsLibrary(Lib);
2730   }
2731 
2732   void getDetectMismatchOption(llvm::StringRef Name,
2733                                llvm::StringRef Value,
2734                                llvm::SmallString<32> &Opt) const override {
2735     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2736   }
2737 };
2738 
2739 void WinX86_64TargetCodeGenInfo::setTargetAttributes(
2740     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2741   TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2742   if (GV->isDeclaration())
2743     return;
2744   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2745     if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2746       llvm::Function *Fn = cast<llvm::Function>(GV);
2747       Fn->addFnAttr("stackrealign");
2748     }
2749 
2750     addX86InterruptAttrs(FD, GV, CGM);
2751   }
2752 
2753   addStackProbeTargetAttributes(D, GV, CGM);
2754 }
2755 }
2756 
2757 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2758                               Class &Hi) const {
2759   // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2760   //
2761   // (a) If one of the classes is Memory, the whole argument is passed in
2762   //     memory.
2763   //
2764   // (b) If X87UP is not preceded by X87, the whole argument is passed in
2765   //     memory.
2766   //
2767   // (c) If the size of the aggregate exceeds two eightbytes and the first
2768   //     eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2769   //     argument is passed in memory. NOTE: This is necessary to keep the
2770   //     ABI working for processors that don't support the __m256 type.
2771   //
2772   // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2773   //
2774   // Some of these are enforced by the merging logic.  Others can arise
2775   // only with unions; for example:
2776   //   union { _Complex double; unsigned; }
2777   //
2778   // Note that clauses (b) and (c) were added in 0.98.
2779   //
2780   if (Hi == Memory)
2781     Lo = Memory;
2782   if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2783     Lo = Memory;
2784   if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2785     Lo = Memory;
2786   if (Hi == SSEUp && Lo != SSE)
2787     Hi = SSE;
2788 }
2789 
2790 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
2791   // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2792   // classified recursively so that always two fields are
2793   // considered. The resulting class is calculated according to
2794   // the classes of the fields in the eightbyte:
2795   //
2796   // (a) If both classes are equal, this is the resulting class.
2797   //
2798   // (b) If one of the classes is NO_CLASS, the resulting class is
2799   // the other class.
2800   //
2801   // (c) If one of the classes is MEMORY, the result is the MEMORY
2802   // class.
2803   //
2804   // (d) If one of the classes is INTEGER, the result is the
2805   // INTEGER.
2806   //
2807   // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2808   // MEMORY is used as class.
2809   //
2810   // (f) Otherwise class SSE is used.
2811 
2812   // Accum should never be memory (we should have returned) or
2813   // ComplexX87 (because this cannot be passed in a structure).
2814   assert((Accum != Memory && Accum != ComplexX87) &&
2815          "Invalid accumulated classification during merge.");
2816   if (Accum == Field || Field == NoClass)
2817     return Accum;
2818   if (Field == Memory)
2819     return Memory;
2820   if (Accum == NoClass)
2821     return Field;
2822   if (Accum == Integer || Field == Integer)
2823     return Integer;
2824   if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2825       Accum == X87 || Accum == X87Up)
2826     return Memory;
2827   return SSE;
2828 }
2829 
2830 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
2831                              Class &Lo, Class &Hi, bool isNamedArg) const {
2832   // FIXME: This code can be simplified by introducing a simple value class for
2833   // Class pairs with appropriate constructor methods for the various
2834   // situations.
2835 
2836   // FIXME: Some of the split computations are wrong; unaligned vectors
2837   // shouldn't be passed in registers for example, so there is no chance they
2838   // can straddle an eightbyte. Verify & simplify.
2839 
2840   Lo = Hi = NoClass;
2841 
2842   Class &Current = OffsetBase < 64 ? Lo : Hi;
2843   Current = Memory;
2844 
2845   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
2846     BuiltinType::Kind k = BT->getKind();
2847 
2848     if (k == BuiltinType::Void) {
2849       Current = NoClass;
2850     } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2851       Lo = Integer;
2852       Hi = Integer;
2853     } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2854       Current = Integer;
2855     } else if (k == BuiltinType::Float || k == BuiltinType::Double ||
2856                k == BuiltinType::Float16) {
2857       Current = SSE;
2858     } else if (k == BuiltinType::LongDouble) {
2859       const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2860       if (LDF == &llvm::APFloat::IEEEquad()) {
2861         Lo = SSE;
2862         Hi = SSEUp;
2863       } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
2864         Lo = X87;
2865         Hi = X87Up;
2866       } else if (LDF == &llvm::APFloat::IEEEdouble()) {
2867         Current = SSE;
2868       } else
2869         llvm_unreachable("unexpected long double representation!");
2870     }
2871     // FIXME: _Decimal32 and _Decimal64 are SSE.
2872     // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
2873     return;
2874   }
2875 
2876   if (const EnumType *ET = Ty->getAs<EnumType>()) {
2877     // Classify the underlying integer type.
2878     classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
2879     return;
2880   }
2881 
2882   if (Ty->hasPointerRepresentation()) {
2883     Current = Integer;
2884     return;
2885   }
2886 
2887   if (Ty->isMemberPointerType()) {
2888     if (Ty->isMemberFunctionPointerType()) {
2889       if (Has64BitPointers) {
2890         // If Has64BitPointers, this is an {i64, i64}, so classify both
2891         // Lo and Hi now.
2892         Lo = Hi = Integer;
2893       } else {
2894         // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2895         // straddles an eightbyte boundary, Hi should be classified as well.
2896         uint64_t EB_FuncPtr = (OffsetBase) / 64;
2897         uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2898         if (EB_FuncPtr != EB_ThisAdj) {
2899           Lo = Hi = Integer;
2900         } else {
2901           Current = Integer;
2902         }
2903       }
2904     } else {
2905       Current = Integer;
2906     }
2907     return;
2908   }
2909 
2910   if (const VectorType *VT = Ty->getAs<VectorType>()) {
2911     uint64_t Size = getContext().getTypeSize(VT);
2912     if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2913       // gcc passes the following as integer:
2914       // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2915       // 2 bytes - <2 x char>, <1 x short>
2916       // 1 byte  - <1 x char>
2917       Current = Integer;
2918 
2919       // If this type crosses an eightbyte boundary, it should be
2920       // split.
2921       uint64_t EB_Lo = (OffsetBase) / 64;
2922       uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2923       if (EB_Lo != EB_Hi)
2924         Hi = Lo;
2925     } else if (Size == 64) {
2926       QualType ElementType = VT->getElementType();
2927 
2928       // gcc passes <1 x double> in memory. :(
2929       if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
2930         return;
2931 
2932       // gcc passes <1 x long long> as SSE but clang used to unconditionally
2933       // pass them as integer.  For platforms where clang is the de facto
2934       // platform compiler, we must continue to use integer.
2935       if (!classifyIntegerMMXAsSSE() &&
2936           (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2937            ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2938            ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2939            ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
2940         Current = Integer;
2941       else
2942         Current = SSE;
2943 
2944       // If this type crosses an eightbyte boundary, it should be
2945       // split.
2946       if (OffsetBase && OffsetBase != 64)
2947         Hi = Lo;
2948     } else if (Size == 128 ||
2949                (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
2950       QualType ElementType = VT->getElementType();
2951 
2952       // gcc passes 256 and 512 bit <X x __int128> vectors in memory. :(
2953       if (passInt128VectorsInMem() && Size != 128 &&
2954           (ElementType->isSpecificBuiltinType(BuiltinType::Int128) ||
2955            ElementType->isSpecificBuiltinType(BuiltinType::UInt128)))
2956         return;
2957 
2958       // Arguments of 256-bits are split into four eightbyte chunks. The
2959       // least significant one belongs to class SSE and all the others to class
2960       // SSEUP. The original Lo and Hi design considers that types can't be
2961       // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2962       // This design isn't correct for 256-bits, but since there're no cases
2963       // where the upper parts would need to be inspected, avoid adding
2964       // complexity and just consider Hi to match the 64-256 part.
2965       //
2966       // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2967       // registers if they are "named", i.e. not part of the "..." of a
2968       // variadic function.
2969       //
2970       // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2971       // split into eight eightbyte chunks, one SSE and seven SSEUP.
2972       Lo = SSE;
2973       Hi = SSEUp;
2974     }
2975     return;
2976   }
2977 
2978   if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
2979     QualType ET = getContext().getCanonicalType(CT->getElementType());
2980 
2981     uint64_t Size = getContext().getTypeSize(Ty);
2982     if (ET->isIntegralOrEnumerationType()) {
2983       if (Size <= 64)
2984         Current = Integer;
2985       else if (Size <= 128)
2986         Lo = Hi = Integer;
2987     } else if (ET->isFloat16Type() || ET == getContext().FloatTy) {
2988       Current = SSE;
2989     } else if (ET == getContext().DoubleTy) {
2990       Lo = Hi = SSE;
2991     } else if (ET == getContext().LongDoubleTy) {
2992       const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2993       if (LDF == &llvm::APFloat::IEEEquad())
2994         Current = Memory;
2995       else if (LDF == &llvm::APFloat::x87DoubleExtended())
2996         Current = ComplexX87;
2997       else if (LDF == &llvm::APFloat::IEEEdouble())
2998         Lo = Hi = SSE;
2999       else
3000         llvm_unreachable("unexpected long double representation!");
3001     }
3002 
3003     // If this complex type crosses an eightbyte boundary then it
3004     // should be split.
3005     uint64_t EB_Real = (OffsetBase) / 64;
3006     uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
3007     if (Hi == NoClass && EB_Real != EB_Imag)
3008       Hi = Lo;
3009 
3010     return;
3011   }
3012 
3013   if (const auto *EITy = Ty->getAs<BitIntType>()) {
3014     if (EITy->getNumBits() <= 64)
3015       Current = Integer;
3016     else if (EITy->getNumBits() <= 128)
3017       Lo = Hi = Integer;
3018     // Larger values need to get passed in memory.
3019     return;
3020   }
3021 
3022   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
3023     // Arrays are treated like structures.
3024 
3025     uint64_t Size = getContext().getTypeSize(Ty);
3026 
3027     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
3028     // than eight eightbytes, ..., it has class MEMORY.
3029     if (Size > 512)
3030       return;
3031 
3032     // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
3033     // fields, it has class MEMORY.
3034     //
3035     // Only need to check alignment of array base.
3036     if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
3037       return;
3038 
3039     // Otherwise implement simplified merge. We could be smarter about
3040     // this, but it isn't worth it and would be harder to verify.
3041     Current = NoClass;
3042     uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
3043     uint64_t ArraySize = AT->getSize().getZExtValue();
3044 
3045     // The only case a 256-bit wide vector could be used is when the array
3046     // contains a single 256-bit element. Since Lo and Hi logic isn't extended
3047     // to work for sizes wider than 128, early check and fallback to memory.
3048     //
3049     if (Size > 128 &&
3050         (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
3051       return;
3052 
3053     for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
3054       Class FieldLo, FieldHi;
3055       classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
3056       Lo = merge(Lo, FieldLo);
3057       Hi = merge(Hi, FieldHi);
3058       if (Lo == Memory || Hi == Memory)
3059         break;
3060     }
3061 
3062     postMerge(Size, Lo, Hi);
3063     assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
3064     return;
3065   }
3066 
3067   if (const RecordType *RT = Ty->getAs<RecordType>()) {
3068     uint64_t Size = getContext().getTypeSize(Ty);
3069 
3070     // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
3071     // than eight eightbytes, ..., it has class MEMORY.
3072     if (Size > 512)
3073       return;
3074 
3075     // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
3076     // copy constructor or a non-trivial destructor, it is passed by invisible
3077     // reference.
3078     if (getRecordArgABI(RT, getCXXABI()))
3079       return;
3080 
3081     const RecordDecl *RD = RT->getDecl();
3082 
3083     // Assume variable sized types are passed in memory.
3084     if (RD->hasFlexibleArrayMember())
3085       return;
3086 
3087     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
3088 
3089     // Reset Lo class, this will be recomputed.
3090     Current = NoClass;
3091 
3092     // If this is a C++ record, classify the bases first.
3093     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3094       for (const auto &I : CXXRD->bases()) {
3095         assert(!I.isVirtual() && !I.getType()->isDependentType() &&
3096                "Unexpected base class!");
3097         const auto *Base =
3098             cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
3099 
3100         // Classify this field.
3101         //
3102         // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
3103         // single eightbyte, each is classified separately. Each eightbyte gets
3104         // initialized to class NO_CLASS.
3105         Class FieldLo, FieldHi;
3106         uint64_t Offset =
3107           OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
3108         classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
3109         Lo = merge(Lo, FieldLo);
3110         Hi = merge(Hi, FieldHi);
3111         if (Lo == Memory || Hi == Memory) {
3112           postMerge(Size, Lo, Hi);
3113           return;
3114         }
3115       }
3116     }
3117 
3118     // Classify the fields one at a time, merging the results.
3119     unsigned idx = 0;
3120     bool UseClang11Compat = getContext().getLangOpts().getClangABICompat() <=
3121                                 LangOptions::ClangABI::Ver11 ||
3122                             getContext().getTargetInfo().getTriple().isPS4();
3123     bool IsUnion = RT->isUnionType() && !UseClang11Compat;
3124 
3125     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3126            i != e; ++i, ++idx) {
3127       uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
3128       bool BitField = i->isBitField();
3129 
3130       // Ignore padding bit-fields.
3131       if (BitField && i->isUnnamedBitfield())
3132         continue;
3133 
3134       // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
3135       // eight eightbytes, or it contains unaligned fields, it has class MEMORY.
3136       //
3137       // The only case a 256-bit or a 512-bit wide vector could be used is when
3138       // the struct contains a single 256-bit or 512-bit element. Early check
3139       // and fallback to memory.
3140       //
3141       // FIXME: Extended the Lo and Hi logic properly to work for size wider
3142       // than 128.
3143       if (Size > 128 &&
3144           ((!IsUnion && Size != getContext().getTypeSize(i->getType())) ||
3145            Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
3146         Lo = Memory;
3147         postMerge(Size, Lo, Hi);
3148         return;
3149       }
3150       // Note, skip this test for bit-fields, see below.
3151       if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
3152         Lo = Memory;
3153         postMerge(Size, Lo, Hi);
3154         return;
3155       }
3156 
3157       // Classify this field.
3158       //
3159       // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
3160       // exceeds a single eightbyte, each is classified
3161       // separately. Each eightbyte gets initialized to class
3162       // NO_CLASS.
3163       Class FieldLo, FieldHi;
3164 
3165       // Bit-fields require special handling, they do not force the
3166       // structure to be passed in memory even if unaligned, and
3167       // therefore they can straddle an eightbyte.
3168       if (BitField) {
3169         assert(!i->isUnnamedBitfield());
3170         uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
3171         uint64_t Size = i->getBitWidthValue(getContext());
3172 
3173         uint64_t EB_Lo = Offset / 64;
3174         uint64_t EB_Hi = (Offset + Size - 1) / 64;
3175 
3176         if (EB_Lo) {
3177           assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
3178           FieldLo = NoClass;
3179           FieldHi = Integer;
3180         } else {
3181           FieldLo = Integer;
3182           FieldHi = EB_Hi ? Integer : NoClass;
3183         }
3184       } else
3185         classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
3186       Lo = merge(Lo, FieldLo);
3187       Hi = merge(Hi, FieldHi);
3188       if (Lo == Memory || Hi == Memory)
3189         break;
3190     }
3191 
3192     postMerge(Size, Lo, Hi);
3193   }
3194 }
3195 
3196 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
3197   // If this is a scalar LLVM value then assume LLVM will pass it in the right
3198   // place naturally.
3199   if (!isAggregateTypeForABI(Ty)) {
3200     // Treat an enum type as its underlying type.
3201     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3202       Ty = EnumTy->getDecl()->getIntegerType();
3203 
3204     if (Ty->isBitIntType())
3205       return getNaturalAlignIndirect(Ty);
3206 
3207     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
3208                                               : ABIArgInfo::getDirect());
3209   }
3210 
3211   return getNaturalAlignIndirect(Ty);
3212 }
3213 
3214 bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
3215   if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
3216     uint64_t Size = getContext().getTypeSize(VecTy);
3217     unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
3218     if (Size <= 64 || Size > LargestVector)
3219       return true;
3220     QualType EltTy = VecTy->getElementType();
3221     if (passInt128VectorsInMem() &&
3222         (EltTy->isSpecificBuiltinType(BuiltinType::Int128) ||
3223          EltTy->isSpecificBuiltinType(BuiltinType::UInt128)))
3224       return true;
3225   }
3226 
3227   return false;
3228 }
3229 
3230 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
3231                                             unsigned freeIntRegs) const {
3232   // If this is a scalar LLVM value then assume LLVM will pass it in the right
3233   // place naturally.
3234   //
3235   // This assumption is optimistic, as there could be free registers available
3236   // when we need to pass this argument in memory, and LLVM could try to pass
3237   // the argument in the free register. This does not seem to happen currently,
3238   // but this code would be much safer if we could mark the argument with
3239   // 'onstack'. See PR12193.
3240   if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty) &&
3241       !Ty->isBitIntType()) {
3242     // Treat an enum type as its underlying type.
3243     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3244       Ty = EnumTy->getDecl()->getIntegerType();
3245 
3246     return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
3247                                               : ABIArgInfo::getDirect());
3248   }
3249 
3250   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
3251     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
3252 
3253   // Compute the byval alignment. We specify the alignment of the byval in all
3254   // cases so that the mid-level optimizer knows the alignment of the byval.
3255   unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
3256 
3257   // Attempt to avoid passing indirect results using byval when possible. This
3258   // is important for good codegen.
3259   //
3260   // We do this by coercing the value into a scalar type which the backend can
3261   // handle naturally (i.e., without using byval).
3262   //
3263   // For simplicity, we currently only do this when we have exhausted all of the
3264   // free integer registers. Doing this when there are free integer registers
3265   // would require more care, as we would have to ensure that the coerced value
3266   // did not claim the unused register. That would require either reording the
3267   // arguments to the function (so that any subsequent inreg values came first),
3268   // or only doing this optimization when there were no following arguments that
3269   // might be inreg.
3270   //
3271   // We currently expect it to be rare (particularly in well written code) for
3272   // arguments to be passed on the stack when there are still free integer
3273   // registers available (this would typically imply large structs being passed
3274   // by value), so this seems like a fair tradeoff for now.
3275   //
3276   // We can revisit this if the backend grows support for 'onstack' parameter
3277   // attributes. See PR12193.
3278   if (freeIntRegs == 0) {
3279     uint64_t Size = getContext().getTypeSize(Ty);
3280 
3281     // If this type fits in an eightbyte, coerce it into the matching integral
3282     // type, which will end up on the stack (with alignment 8).
3283     if (Align == 8 && Size <= 64)
3284       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
3285                                                           Size));
3286   }
3287 
3288   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
3289 }
3290 
3291 /// The ABI specifies that a value should be passed in a full vector XMM/YMM
3292 /// register. Pick an LLVM IR type that will be passed as a vector register.
3293 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
3294   // Wrapper structs/arrays that only contain vectors are passed just like
3295   // vectors; strip them off if present.
3296   if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
3297     Ty = QualType(InnerTy, 0);
3298 
3299   llvm::Type *IRType = CGT.ConvertType(Ty);
3300   if (isa<llvm::VectorType>(IRType)) {
3301     // Don't pass vXi128 vectors in their native type, the backend can't
3302     // legalize them.
3303     if (passInt128VectorsInMem() &&
3304         cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy(128)) {
3305       // Use a vXi64 vector.
3306       uint64_t Size = getContext().getTypeSize(Ty);
3307       return llvm::FixedVectorType::get(llvm::Type::getInt64Ty(getVMContext()),
3308                                         Size / 64);
3309     }
3310 
3311     return IRType;
3312   }
3313 
3314   if (IRType->getTypeID() == llvm::Type::FP128TyID)
3315     return IRType;
3316 
3317   // We couldn't find the preferred IR vector type for 'Ty'.
3318   uint64_t Size = getContext().getTypeSize(Ty);
3319   assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
3320 
3321 
3322   // Return a LLVM IR vector type based on the size of 'Ty'.
3323   return llvm::FixedVectorType::get(llvm::Type::getDoubleTy(getVMContext()),
3324                                     Size / 64);
3325 }
3326 
3327 /// BitsContainNoUserData - Return true if the specified [start,end) bit range
3328 /// is known to either be off the end of the specified type or being in
3329 /// alignment padding.  The user type specified is known to be at most 128 bits
3330 /// in size, and have passed through X86_64ABIInfo::classify with a successful
3331 /// classification that put one of the two halves in the INTEGER class.
3332 ///
3333 /// It is conservatively correct to return false.
3334 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
3335                                   unsigned EndBit, ASTContext &Context) {
3336   // If the bytes being queried are off the end of the type, there is no user
3337   // data hiding here.  This handles analysis of builtins, vectors and other
3338   // types that don't contain interesting padding.
3339   unsigned TySize = (unsigned)Context.getTypeSize(Ty);
3340   if (TySize <= StartBit)
3341     return true;
3342 
3343   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
3344     unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
3345     unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
3346 
3347     // Check each element to see if the element overlaps with the queried range.
3348     for (unsigned i = 0; i != NumElts; ++i) {
3349       // If the element is after the span we care about, then we're done..
3350       unsigned EltOffset = i*EltSize;
3351       if (EltOffset >= EndBit) break;
3352 
3353       unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
3354       if (!BitsContainNoUserData(AT->getElementType(), EltStart,
3355                                  EndBit-EltOffset, Context))
3356         return false;
3357     }
3358     // If it overlaps no elements, then it is safe to process as padding.
3359     return true;
3360   }
3361 
3362   if (const RecordType *RT = Ty->getAs<RecordType>()) {
3363     const RecordDecl *RD = RT->getDecl();
3364     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3365 
3366     // If this is a C++ record, check the bases first.
3367     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3368       for (const auto &I : CXXRD->bases()) {
3369         assert(!I.isVirtual() && !I.getType()->isDependentType() &&
3370                "Unexpected base class!");
3371         const auto *Base =
3372             cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
3373 
3374         // If the base is after the span we care about, ignore it.
3375         unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
3376         if (BaseOffset >= EndBit) continue;
3377 
3378         unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
3379         if (!BitsContainNoUserData(I.getType(), BaseStart,
3380                                    EndBit-BaseOffset, Context))
3381           return false;
3382       }
3383     }
3384 
3385     // Verify that no field has data that overlaps the region of interest.  Yes
3386     // this could be sped up a lot by being smarter about queried fields,
3387     // however we're only looking at structs up to 16 bytes, so we don't care
3388     // much.
3389     unsigned idx = 0;
3390     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3391          i != e; ++i, ++idx) {
3392       unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
3393 
3394       // If we found a field after the region we care about, then we're done.
3395       if (FieldOffset >= EndBit) break;
3396 
3397       unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
3398       if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
3399                                  Context))
3400         return false;
3401     }
3402 
3403     // If nothing in this record overlapped the area of interest, then we're
3404     // clean.
3405     return true;
3406   }
3407 
3408   return false;
3409 }
3410 
3411 /// getFPTypeAtOffset - Return a floating point type at the specified offset.
3412 static llvm::Type *getFPTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3413                                      const llvm::DataLayout &TD) {
3414   if (IROffset == 0 && IRType->isFloatingPointTy())
3415     return IRType;
3416 
3417   // If this is a struct, recurse into the field at the specified offset.
3418   if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3419     if (!STy->getNumContainedTypes())
3420       return nullptr;
3421 
3422     const llvm::StructLayout *SL = TD.getStructLayout(STy);
3423     unsigned Elt = SL->getElementContainingOffset(IROffset);
3424     IROffset -= SL->getElementOffset(Elt);
3425     return getFPTypeAtOffset(STy->getElementType(Elt), IROffset, TD);
3426   }
3427 
3428   // If this is an array, recurse into the field at the specified offset.
3429   if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3430     llvm::Type *EltTy = ATy->getElementType();
3431     unsigned EltSize = TD.getTypeAllocSize(EltTy);
3432     IROffset -= IROffset / EltSize * EltSize;
3433     return getFPTypeAtOffset(EltTy, IROffset, TD);
3434   }
3435 
3436   return nullptr;
3437 }
3438 
3439 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
3440 /// low 8 bytes of an XMM register, corresponding to the SSE class.
3441 llvm::Type *X86_64ABIInfo::
3442 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3443                    QualType SourceTy, unsigned SourceOffset) const {
3444   const llvm::DataLayout &TD = getDataLayout();
3445   unsigned SourceSize =
3446       (unsigned)getContext().getTypeSize(SourceTy) / 8 - SourceOffset;
3447   llvm::Type *T0 = getFPTypeAtOffset(IRType, IROffset, TD);
3448   if (!T0 || T0->isDoubleTy())
3449     return llvm::Type::getDoubleTy(getVMContext());
3450 
3451   // Get the adjacent FP type.
3452   llvm::Type *T1 = nullptr;
3453   unsigned T0Size = TD.getTypeAllocSize(T0);
3454   if (SourceSize > T0Size)
3455       T1 = getFPTypeAtOffset(IRType, IROffset + T0Size, TD);
3456   if (T1 == nullptr) {
3457     // Check if IRType is a half + float. float type will be in IROffset+4 due
3458     // to its alignment.
3459     if (T0->isHalfTy() && SourceSize > 4)
3460       T1 = getFPTypeAtOffset(IRType, IROffset + 4, TD);
3461     // If we can't get a second FP type, return a simple half or float.
3462     // avx512fp16-abi.c:pr51813_2 shows it works to return float for
3463     // {float, i8} too.
3464     if (T1 == nullptr)
3465       return T0;
3466   }
3467 
3468   if (T0->isFloatTy() && T1->isFloatTy())
3469     return llvm::FixedVectorType::get(T0, 2);
3470 
3471   if (T0->isHalfTy() && T1->isHalfTy()) {
3472     llvm::Type *T2 = nullptr;
3473     if (SourceSize > 4)
3474       T2 = getFPTypeAtOffset(IRType, IROffset + 4, TD);
3475     if (T2 == nullptr)
3476       return llvm::FixedVectorType::get(T0, 2);
3477     return llvm::FixedVectorType::get(T0, 4);
3478   }
3479 
3480   if (T0->isHalfTy() || T1->isHalfTy())
3481     return llvm::FixedVectorType::get(llvm::Type::getHalfTy(getVMContext()), 4);
3482 
3483   return llvm::Type::getDoubleTy(getVMContext());
3484 }
3485 
3486 
3487 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
3488 /// an 8-byte GPR.  This means that we either have a scalar or we are talking
3489 /// about the high or low part of an up-to-16-byte struct.  This routine picks
3490 /// the best LLVM IR type to represent this, which may be i64 or may be anything
3491 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
3492 /// etc).
3493 ///
3494 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
3495 /// the source type.  IROffset is an offset in bytes into the LLVM IR type that
3496 /// the 8-byte value references.  PrefType may be null.
3497 ///
3498 /// SourceTy is the source-level type for the entire argument.  SourceOffset is
3499 /// an offset into this that we're processing (which is always either 0 or 8).
3500 ///
3501 llvm::Type *X86_64ABIInfo::
3502 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3503                        QualType SourceTy, unsigned SourceOffset) const {
3504   // If we're dealing with an un-offset LLVM IR type, then it means that we're
3505   // returning an 8-byte unit starting with it.  See if we can safely use it.
3506   if (IROffset == 0) {
3507     // Pointers and int64's always fill the 8-byte unit.
3508     if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
3509         IRType->isIntegerTy(64))
3510       return IRType;
3511 
3512     // If we have a 1/2/4-byte integer, we can use it only if the rest of the
3513     // goodness in the source type is just tail padding.  This is allowed to
3514     // kick in for struct {double,int} on the int, but not on
3515     // struct{double,int,int} because we wouldn't return the second int.  We
3516     // have to do this analysis on the source type because we can't depend on
3517     // unions being lowered a specific way etc.
3518     if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
3519         IRType->isIntegerTy(32) ||
3520         (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
3521       unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
3522           cast<llvm::IntegerType>(IRType)->getBitWidth();
3523 
3524       if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
3525                                 SourceOffset*8+64, getContext()))
3526         return IRType;
3527     }
3528   }
3529 
3530   if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3531     // If this is a struct, recurse into the field at the specified offset.
3532     const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
3533     if (IROffset < SL->getSizeInBytes()) {
3534       unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
3535       IROffset -= SL->getElementOffset(FieldIdx);
3536 
3537       return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
3538                                     SourceTy, SourceOffset);
3539     }
3540   }
3541 
3542   if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3543     llvm::Type *EltTy = ATy->getElementType();
3544     unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
3545     unsigned EltOffset = IROffset/EltSize*EltSize;
3546     return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
3547                                   SourceOffset);
3548   }
3549 
3550   // Okay, we don't have any better idea of what to pass, so we pass this in an
3551   // integer register that isn't too big to fit the rest of the struct.
3552   unsigned TySizeInBytes =
3553     (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
3554 
3555   assert(TySizeInBytes != SourceOffset && "Empty field?");
3556 
3557   // It is always safe to classify this as an integer type up to i64 that
3558   // isn't larger than the structure.
3559   return llvm::IntegerType::get(getVMContext(),
3560                                 std::min(TySizeInBytes-SourceOffset, 8U)*8);
3561 }
3562 
3563 
3564 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
3565 /// be used as elements of a two register pair to pass or return, return a
3566 /// first class aggregate to represent them.  For example, if the low part of
3567 /// a by-value argument should be passed as i32* and the high part as float,
3568 /// return {i32*, float}.
3569 static llvm::Type *
3570 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
3571                            const llvm::DataLayout &TD) {
3572   // In order to correctly satisfy the ABI, we need to the high part to start
3573   // at offset 8.  If the high and low parts we inferred are both 4-byte types
3574   // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
3575   // the second element at offset 8.  Check for this:
3576   unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
3577   unsigned HiAlign = TD.getABITypeAlignment(Hi);
3578   unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
3579   assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
3580 
3581   // To handle this, we have to increase the size of the low part so that the
3582   // second element will start at an 8 byte offset.  We can't increase the size
3583   // of the second element because it might make us access off the end of the
3584   // struct.
3585   if (HiStart != 8) {
3586     // There are usually two sorts of types the ABI generation code can produce
3587     // for the low part of a pair that aren't 8 bytes in size: half, float or
3588     // i8/i16/i32.  This can also include pointers when they are 32-bit (X32 and
3589     // NaCl).
3590     // Promote these to a larger type.
3591     if (Lo->isHalfTy() || Lo->isFloatTy())
3592       Lo = llvm::Type::getDoubleTy(Lo->getContext());
3593     else {
3594       assert((Lo->isIntegerTy() || Lo->isPointerTy())
3595              && "Invalid/unknown lo type");
3596       Lo = llvm::Type::getInt64Ty(Lo->getContext());
3597     }
3598   }
3599 
3600   llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
3601 
3602   // Verify that the second element is at an 8-byte offset.
3603   assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
3604          "Invalid x86-64 argument pair!");
3605   return Result;
3606 }
3607 
3608 ABIArgInfo X86_64ABIInfo::
3609 classifyReturnType(QualType RetTy) const {
3610   // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3611   // classification algorithm.
3612   X86_64ABIInfo::Class Lo, Hi;
3613   classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
3614 
3615   // Check some invariants.
3616   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3617   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3618 
3619   llvm::Type *ResType = nullptr;
3620   switch (Lo) {
3621   case NoClass:
3622     if (Hi == NoClass)
3623       return ABIArgInfo::getIgnore();
3624     // If the low part is just padding, it takes no register, leave ResType
3625     // null.
3626     assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3627            "Unknown missing lo part");
3628     break;
3629 
3630   case SSEUp:
3631   case X87Up:
3632     llvm_unreachable("Invalid classification for lo word.");
3633 
3634     // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3635     // hidden argument.
3636   case Memory:
3637     return getIndirectReturnResult(RetTy);
3638 
3639     // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3640     // available register of the sequence %rax, %rdx is used.
3641   case Integer:
3642     ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3643 
3644     // If we have a sign or zero extended integer, make sure to return Extend
3645     // so that the parameter gets the right LLVM IR attributes.
3646     if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3647       // Treat an enum type as its underlying type.
3648       if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3649         RetTy = EnumTy->getDecl()->getIntegerType();
3650 
3651       if (RetTy->isIntegralOrEnumerationType() &&
3652           isPromotableIntegerTypeForABI(RetTy))
3653         return ABIArgInfo::getExtend(RetTy);
3654     }
3655     break;
3656 
3657     // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3658     // available SSE register of the sequence %xmm0, %xmm1 is used.
3659   case SSE:
3660     ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3661     break;
3662 
3663     // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3664     // returned on the X87 stack in %st0 as 80-bit x87 number.
3665   case X87:
3666     ResType = llvm::Type::getX86_FP80Ty(getVMContext());
3667     break;
3668 
3669     // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3670     // part of the value is returned in %st0 and the imaginary part in
3671     // %st1.
3672   case ComplexX87:
3673     assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
3674     ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
3675                                     llvm::Type::getX86_FP80Ty(getVMContext()));
3676     break;
3677   }
3678 
3679   llvm::Type *HighPart = nullptr;
3680   switch (Hi) {
3681     // Memory was handled previously and X87 should
3682     // never occur as a hi class.
3683   case Memory:
3684   case X87:
3685     llvm_unreachable("Invalid classification for hi word.");
3686 
3687   case ComplexX87: // Previously handled.
3688   case NoClass:
3689     break;
3690 
3691   case Integer:
3692     HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3693     if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3694       return ABIArgInfo::getDirect(HighPart, 8);
3695     break;
3696   case SSE:
3697     HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3698     if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3699       return ABIArgInfo::getDirect(HighPart, 8);
3700     break;
3701 
3702     // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
3703     // is passed in the next available eightbyte chunk if the last used
3704     // vector register.
3705     //
3706     // SSEUP should always be preceded by SSE, just widen.
3707   case SSEUp:
3708     assert(Lo == SSE && "Unexpected SSEUp classification.");
3709     ResType = GetByteVectorType(RetTy);
3710     break;
3711 
3712     // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3713     // returned together with the previous X87 value in %st0.
3714   case X87Up:
3715     // If X87Up is preceded by X87, we don't need to do
3716     // anything. However, in some cases with unions it may not be
3717     // preceded by X87. In such situations we follow gcc and pass the
3718     // extra bits in an SSE reg.
3719     if (Lo != X87) {
3720       HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3721       if (Lo == NoClass)  // Return HighPart at offset 8 in memory.
3722         return ABIArgInfo::getDirect(HighPart, 8);
3723     }
3724     break;
3725   }
3726 
3727   // If a high part was specified, merge it together with the low part.  It is
3728   // known to pass in the high eightbyte of the result.  We do this by forming a
3729   // first class struct aggregate with the high and low part: {low, high}
3730   if (HighPart)
3731     ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3732 
3733   return ABIArgInfo::getDirect(ResType);
3734 }
3735 
3736 ABIArgInfo X86_64ABIInfo::classifyArgumentType(
3737   QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3738   bool isNamedArg)
3739   const
3740 {
3741   Ty = useFirstFieldIfTransparentUnion(Ty);
3742 
3743   X86_64ABIInfo::Class Lo, Hi;
3744   classify(Ty, 0, Lo, Hi, isNamedArg);
3745 
3746   // Check some invariants.
3747   // FIXME: Enforce these by construction.
3748   assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3749   assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3750 
3751   neededInt = 0;
3752   neededSSE = 0;
3753   llvm::Type *ResType = nullptr;
3754   switch (Lo) {
3755   case NoClass:
3756     if (Hi == NoClass)
3757       return ABIArgInfo::getIgnore();
3758     // If the low part is just padding, it takes no register, leave ResType
3759     // null.
3760     assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3761            "Unknown missing lo part");
3762     break;
3763 
3764     // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3765     // on the stack.
3766   case Memory:
3767 
3768     // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3769     // COMPLEX_X87, it is passed in memory.
3770   case X87:
3771   case ComplexX87:
3772     if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
3773       ++neededInt;
3774     return getIndirectResult(Ty, freeIntRegs);
3775 
3776   case SSEUp:
3777   case X87Up:
3778     llvm_unreachable("Invalid classification for lo word.");
3779 
3780     // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3781     // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3782     // and %r9 is used.
3783   case Integer:
3784     ++neededInt;
3785 
3786     // Pick an 8-byte type based on the preferred type.
3787     ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
3788 
3789     // If we have a sign or zero extended integer, make sure to return Extend
3790     // so that the parameter gets the right LLVM IR attributes.
3791     if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3792       // Treat an enum type as its underlying type.
3793       if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3794         Ty = EnumTy->getDecl()->getIntegerType();
3795 
3796       if (Ty->isIntegralOrEnumerationType() &&
3797           isPromotableIntegerTypeForABI(Ty))
3798         return ABIArgInfo::getExtend(Ty);
3799     }
3800 
3801     break;
3802 
3803     // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3804     // available SSE register is used, the registers are taken in the
3805     // order from %xmm0 to %xmm7.
3806   case SSE: {
3807     llvm::Type *IRType = CGT.ConvertType(Ty);
3808     ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
3809     ++neededSSE;
3810     break;
3811   }
3812   }
3813 
3814   llvm::Type *HighPart = nullptr;
3815   switch (Hi) {
3816     // Memory was handled previously, ComplexX87 and X87 should
3817     // never occur as hi classes, and X87Up must be preceded by X87,
3818     // which is passed in memory.
3819   case Memory:
3820   case X87:
3821   case ComplexX87:
3822     llvm_unreachable("Invalid classification for hi word.");
3823 
3824   case NoClass: break;
3825 
3826   case Integer:
3827     ++neededInt;
3828     // Pick an 8-byte type based on the preferred type.
3829     HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3830 
3831     if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
3832       return ABIArgInfo::getDirect(HighPart, 8);
3833     break;
3834 
3835     // X87Up generally doesn't occur here (long double is passed in
3836     // memory), except in situations involving unions.
3837   case X87Up:
3838   case SSE:
3839     HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3840 
3841     if (Lo == NoClass)  // Pass HighPart at offset 8 in memory.
3842       return ABIArgInfo::getDirect(HighPart, 8);
3843 
3844     ++neededSSE;
3845     break;
3846 
3847     // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3848     // eightbyte is passed in the upper half of the last used SSE
3849     // register.  This only happens when 128-bit vectors are passed.
3850   case SSEUp:
3851     assert(Lo == SSE && "Unexpected SSEUp classification");
3852     ResType = GetByteVectorType(Ty);
3853     break;
3854   }
3855 
3856   // If a high part was specified, merge it together with the low part.  It is
3857   // known to pass in the high eightbyte of the result.  We do this by forming a
3858   // first class struct aggregate with the high and low part: {low, high}
3859   if (HighPart)
3860     ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3861 
3862   return ABIArgInfo::getDirect(ResType);
3863 }
3864 
3865 ABIArgInfo
3866 X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
3867                                              unsigned &NeededSSE) const {
3868   auto RT = Ty->getAs<RecordType>();
3869   assert(RT && "classifyRegCallStructType only valid with struct types");
3870 
3871   if (RT->getDecl()->hasFlexibleArrayMember())
3872     return getIndirectReturnResult(Ty);
3873 
3874   // Sum up bases
3875   if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3876     if (CXXRD->isDynamicClass()) {
3877       NeededInt = NeededSSE = 0;
3878       return getIndirectReturnResult(Ty);
3879     }
3880 
3881     for (const auto &I : CXXRD->bases())
3882       if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE)
3883               .isIndirect()) {
3884         NeededInt = NeededSSE = 0;
3885         return getIndirectReturnResult(Ty);
3886       }
3887   }
3888 
3889   // Sum up members
3890   for (const auto *FD : RT->getDecl()->fields()) {
3891     if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) {
3892       if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE)
3893               .isIndirect()) {
3894         NeededInt = NeededSSE = 0;
3895         return getIndirectReturnResult(Ty);
3896       }
3897     } else {
3898       unsigned LocalNeededInt, LocalNeededSSE;
3899       if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt,
3900                                LocalNeededSSE, true)
3901               .isIndirect()) {
3902         NeededInt = NeededSSE = 0;
3903         return getIndirectReturnResult(Ty);
3904       }
3905       NeededInt += LocalNeededInt;
3906       NeededSSE += LocalNeededSSE;
3907     }
3908   }
3909 
3910   return ABIArgInfo::getDirect();
3911 }
3912 
3913 ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty,
3914                                                     unsigned &NeededInt,
3915                                                     unsigned &NeededSSE) const {
3916 
3917   NeededInt = 0;
3918   NeededSSE = 0;
3919 
3920   return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE);
3921 }
3922 
3923 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3924 
3925   const unsigned CallingConv = FI.getCallingConvention();
3926   // It is possible to force Win64 calling convention on any x86_64 target by
3927   // using __attribute__((ms_abi)). In such case to correctly emit Win64
3928   // compatible code delegate this call to WinX86_64ABIInfo::computeInfo.
3929   if (CallingConv == llvm::CallingConv::Win64) {
3930     WinX86_64ABIInfo Win64ABIInfo(CGT, AVXLevel);
3931     Win64ABIInfo.computeInfo(FI);
3932     return;
3933   }
3934 
3935   bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall;
3936 
3937   // Keep track of the number of assigned registers.
3938   unsigned FreeIntRegs = IsRegCall ? 11 : 6;
3939   unsigned FreeSSERegs = IsRegCall ? 16 : 8;
3940   unsigned NeededInt, NeededSSE;
3941 
3942   if (!::classifyReturnType(getCXXABI(), FI, *this)) {
3943     if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
3944         !FI.getReturnType()->getTypePtr()->isUnionType()) {
3945       FI.getReturnInfo() =
3946           classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE);
3947       if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3948         FreeIntRegs -= NeededInt;
3949         FreeSSERegs -= NeededSSE;
3950       } else {
3951         FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3952       }
3953     } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>() &&
3954                getContext().getCanonicalType(FI.getReturnType()
3955                                                  ->getAs<ComplexType>()
3956                                                  ->getElementType()) ==
3957                    getContext().LongDoubleTy)
3958       // Complex Long Double Type is passed in Memory when Regcall
3959       // calling convention is used.
3960       FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3961     else
3962       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3963   }
3964 
3965   // If the return value is indirect, then the hidden argument is consuming one
3966   // integer register.
3967   if (FI.getReturnInfo().isIndirect())
3968     --FreeIntRegs;
3969 
3970   // The chain argument effectively gives us another free register.
3971   if (FI.isChainCall())
3972     ++FreeIntRegs;
3973 
3974   unsigned NumRequiredArgs = FI.getNumRequiredArgs();
3975   // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3976   // get assigned (in left-to-right order) for passing as follows...
3977   unsigned ArgNo = 0;
3978   for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3979        it != ie; ++it, ++ArgNo) {
3980     bool IsNamedArg = ArgNo < NumRequiredArgs;
3981 
3982     if (IsRegCall && it->type->isStructureOrClassType())
3983       it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE);
3984     else
3985       it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
3986                                       NeededSSE, IsNamedArg);
3987 
3988     // AMD64-ABI 3.2.3p3: If there are no registers available for any
3989     // eightbyte of an argument, the whole argument is passed on the
3990     // stack. If registers have already been assigned for some
3991     // eightbytes of such an argument, the assignments get reverted.
3992     if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3993       FreeIntRegs -= NeededInt;
3994       FreeSSERegs -= NeededSSE;
3995     } else {
3996       it->info = getIndirectResult(it->type, FreeIntRegs);
3997     }
3998   }
3999 }
4000 
4001 static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
4002                                          Address VAListAddr, QualType Ty) {
4003   Address overflow_arg_area_p =
4004       CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
4005   llvm::Value *overflow_arg_area =
4006     CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
4007 
4008   // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
4009   // byte boundary if alignment needed by type exceeds 8 byte boundary.
4010   // It isn't stated explicitly in the standard, but in practice we use
4011   // alignment greater than 16 where necessary.
4012   CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4013   if (Align > CharUnits::fromQuantity(8)) {
4014     overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
4015                                                       Align);
4016   }
4017 
4018   // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
4019   llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
4020   llvm::Value *Res =
4021     CGF.Builder.CreateBitCast(overflow_arg_area,
4022                               llvm::PointerType::getUnqual(LTy));
4023 
4024   // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
4025   // l->overflow_arg_area + sizeof(type).
4026   // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
4027   // an 8 byte boundary.
4028 
4029   uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
4030   llvm::Value *Offset =
4031       llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7)  & ~7);
4032   overflow_arg_area = CGF.Builder.CreateGEP(CGF.Int8Ty, overflow_arg_area,
4033                                             Offset, "overflow_arg_area.next");
4034   CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
4035 
4036   // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
4037   return Address(Res, LTy, Align);
4038 }
4039 
4040 Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4041                                  QualType Ty) const {
4042   // Assume that va_list type is correct; should be pointer to LLVM type:
4043   // struct {
4044   //   i32 gp_offset;
4045   //   i32 fp_offset;
4046   //   i8* overflow_arg_area;
4047   //   i8* reg_save_area;
4048   // };
4049   unsigned neededInt, neededSSE;
4050 
4051   Ty = getContext().getCanonicalType(Ty);
4052   ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
4053                                        /*isNamedArg*/false);
4054 
4055   // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
4056   // in the registers. If not go to step 7.
4057   if (!neededInt && !neededSSE)
4058     return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
4059 
4060   // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
4061   // general purpose registers needed to pass type and num_fp to hold
4062   // the number of floating point registers needed.
4063 
4064   // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
4065   // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
4066   // l->fp_offset > 304 - num_fp * 16 go to step 7.
4067   //
4068   // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
4069   // register save space).
4070 
4071   llvm::Value *InRegs = nullptr;
4072   Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
4073   llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
4074   if (neededInt) {
4075     gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
4076     gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
4077     InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
4078     InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
4079   }
4080 
4081   if (neededSSE) {
4082     fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
4083     fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
4084     llvm::Value *FitsInFP =
4085       llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
4086     FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
4087     InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
4088   }
4089 
4090   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4091   llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
4092   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4093   CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
4094 
4095   // Emit code to load the value if it was passed in registers.
4096 
4097   CGF.EmitBlock(InRegBlock);
4098 
4099   // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
4100   // an offset of l->gp_offset and/or l->fp_offset. This may require
4101   // copying to a temporary location in case the parameter is passed
4102   // in different register classes or requires an alignment greater
4103   // than 8 for general purpose registers and 16 for XMM registers.
4104   //
4105   // FIXME: This really results in shameful code when we end up needing to
4106   // collect arguments from different places; often what should result in a
4107   // simple assembling of a structure from scattered addresses has many more
4108   // loads than necessary. Can we clean this up?
4109   llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
4110   llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
4111       CGF.Builder.CreateStructGEP(VAListAddr, 3), "reg_save_area");
4112 
4113   Address RegAddr = Address::invalid();
4114   if (neededInt && neededSSE) {
4115     // FIXME: Cleanup.
4116     assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
4117     llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
4118     Address Tmp = CGF.CreateMemTemp(Ty);
4119     Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
4120     assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
4121     llvm::Type *TyLo = ST->getElementType(0);
4122     llvm::Type *TyHi = ST->getElementType(1);
4123     assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
4124            "Unexpected ABI info for mixed regs");
4125     llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
4126     llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
4127     llvm::Value *GPAddr =
4128         CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, gp_offset);
4129     llvm::Value *FPAddr =
4130         CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, fp_offset);
4131     llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
4132     llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
4133 
4134     // Copy the first element.
4135     // FIXME: Our choice of alignment here and below is probably pessimistic.
4136     llvm::Value *V = CGF.Builder.CreateAlignedLoad(
4137         TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo),
4138         CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo)));
4139     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
4140 
4141     // Copy the second element.
4142     V = CGF.Builder.CreateAlignedLoad(
4143         TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
4144         CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
4145     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
4146 
4147     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
4148   } else if (neededInt) {
4149     RegAddr = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, gp_offset),
4150                       CGF.Int8Ty, CharUnits::fromQuantity(8));
4151     RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
4152 
4153     // Copy to a temporary if necessary to ensure the appropriate alignment.
4154     auto TInfo = getContext().getTypeInfoInChars(Ty);
4155     uint64_t TySize = TInfo.Width.getQuantity();
4156     CharUnits TyAlign = TInfo.Align;
4157 
4158     // Copy into a temporary if the type is more aligned than the
4159     // register save area.
4160     if (TyAlign.getQuantity() > 8) {
4161       Address Tmp = CGF.CreateMemTemp(Ty);
4162       CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
4163       RegAddr = Tmp;
4164     }
4165 
4166   } else if (neededSSE == 1) {
4167     RegAddr = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, fp_offset),
4168                       CGF.Int8Ty, CharUnits::fromQuantity(16));
4169     RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
4170   } else {
4171     assert(neededSSE == 2 && "Invalid number of needed registers!");
4172     // SSE registers are spaced 16 bytes apart in the register save
4173     // area, we need to collect the two eightbytes together.
4174     // The ABI isn't explicit about this, but it seems reasonable
4175     // to assume that the slots are 16-byte aligned, since the stack is
4176     // naturally 16-byte aligned and the prologue is expected to store
4177     // all the SSE registers to the RSA.
4178     Address RegAddrLo = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea,
4179                                                       fp_offset),
4180                                 CGF.Int8Ty, CharUnits::fromQuantity(16));
4181     Address RegAddrHi =
4182       CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
4183                                              CharUnits::fromQuantity(16));
4184     llvm::Type *ST = AI.canHaveCoerceToType()
4185                          ? AI.getCoerceToType()
4186                          : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy);
4187     llvm::Value *V;
4188     Address Tmp = CGF.CreateMemTemp(Ty);
4189     Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
4190     V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
4191         RegAddrLo, ST->getStructElementType(0)));
4192     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
4193     V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
4194         RegAddrHi, ST->getStructElementType(1)));
4195     CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
4196 
4197     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
4198   }
4199 
4200   // AMD64-ABI 3.5.7p5: Step 5. Set:
4201   // l->gp_offset = l->gp_offset + num_gp * 8
4202   // l->fp_offset = l->fp_offset + num_fp * 16.
4203   if (neededInt) {
4204     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
4205     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
4206                             gp_offset_p);
4207   }
4208   if (neededSSE) {
4209     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
4210     CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
4211                             fp_offset_p);
4212   }
4213   CGF.EmitBranch(ContBlock);
4214 
4215   // Emit code to load the value if it was passed in memory.
4216 
4217   CGF.EmitBlock(InMemBlock);
4218   Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
4219 
4220   // Return the appropriate result.
4221 
4222   CGF.EmitBlock(ContBlock);
4223   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
4224                                  "vaarg.addr");
4225   return ResAddr;
4226 }
4227 
4228 Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
4229                                    QualType Ty) const {
4230   // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4231   // not 1, 2, 4, or 8 bytes, must be passed by reference."
4232   uint64_t Width = getContext().getTypeSize(Ty);
4233   bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
4234 
4235   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
4236                           CGF.getContext().getTypeInfoInChars(Ty),
4237                           CharUnits::fromQuantity(8),
4238                           /*allowHigherAlign*/ false);
4239 }
4240 
4241 ABIArgInfo WinX86_64ABIInfo::reclassifyHvaArgForVectorCall(
4242     QualType Ty, unsigned &FreeSSERegs, const ABIArgInfo &current) const {
4243   const Type *Base = nullptr;
4244   uint64_t NumElts = 0;
4245 
4246   if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
4247       isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
4248     FreeSSERegs -= NumElts;
4249     return getDirectX86Hva();
4250   }
4251   return current;
4252 }
4253 
4254 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
4255                                       bool IsReturnType, bool IsVectorCall,
4256                                       bool IsRegCall) const {
4257 
4258   if (Ty->isVoidType())
4259     return ABIArgInfo::getIgnore();
4260 
4261   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4262     Ty = EnumTy->getDecl()->getIntegerType();
4263 
4264   TypeInfo Info = getContext().getTypeInfo(Ty);
4265   uint64_t Width = Info.Width;
4266   CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
4267 
4268   const RecordType *RT = Ty->getAs<RecordType>();
4269   if (RT) {
4270     if (!IsReturnType) {
4271       if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
4272         return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
4273     }
4274 
4275     if (RT->getDecl()->hasFlexibleArrayMember())
4276       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4277 
4278   }
4279 
4280   const Type *Base = nullptr;
4281   uint64_t NumElts = 0;
4282   // vectorcall adds the concept of a homogenous vector aggregate, similar to
4283   // other targets.
4284   if ((IsVectorCall || IsRegCall) &&
4285       isHomogeneousAggregate(Ty, Base, NumElts)) {
4286     if (IsRegCall) {
4287       if (FreeSSERegs >= NumElts) {
4288         FreeSSERegs -= NumElts;
4289         if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
4290           return ABIArgInfo::getDirect();
4291         return ABIArgInfo::getExpand();
4292       }
4293       return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4294     } else if (IsVectorCall) {
4295       if (FreeSSERegs >= NumElts &&
4296           (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
4297         FreeSSERegs -= NumElts;
4298         return ABIArgInfo::getDirect();
4299       } else if (IsReturnType) {
4300         return ABIArgInfo::getExpand();
4301       } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
4302         // HVAs are delayed and reclassified in the 2nd step.
4303         return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4304       }
4305     }
4306   }
4307 
4308   if (Ty->isMemberPointerType()) {
4309     // If the member pointer is represented by an LLVM int or ptr, pass it
4310     // directly.
4311     llvm::Type *LLTy = CGT.ConvertType(Ty);
4312     if (LLTy->isPointerTy() || LLTy->isIntegerTy())
4313       return ABIArgInfo::getDirect();
4314   }
4315 
4316   if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
4317     // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4318     // not 1, 2, 4, or 8 bytes, must be passed by reference."
4319     if (Width > 64 || !llvm::isPowerOf2_64(Width))
4320       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4321 
4322     // Otherwise, coerce it to a small integer.
4323     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
4324   }
4325 
4326   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4327     switch (BT->getKind()) {
4328     case BuiltinType::Bool:
4329       // Bool type is always extended to the ABI, other builtin types are not
4330       // extended.
4331       return ABIArgInfo::getExtend(Ty);
4332 
4333     case BuiltinType::LongDouble:
4334       // Mingw64 GCC uses the old 80 bit extended precision floating point
4335       // unit. It passes them indirectly through memory.
4336       if (IsMingw64) {
4337         const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
4338         if (LDF == &llvm::APFloat::x87DoubleExtended())
4339           return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4340       }
4341       break;
4342 
4343     case BuiltinType::Int128:
4344     case BuiltinType::UInt128:
4345       // If it's a parameter type, the normal ABI rule is that arguments larger
4346       // than 8 bytes are passed indirectly. GCC follows it. We follow it too,
4347       // even though it isn't particularly efficient.
4348       if (!IsReturnType)
4349         return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4350 
4351       // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that.
4352       // Clang matches them for compatibility.
4353       return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
4354           llvm::Type::getInt64Ty(getVMContext()), 2));
4355 
4356     default:
4357       break;
4358     }
4359   }
4360 
4361   if (Ty->isBitIntType()) {
4362     // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4363     // not 1, 2, 4, or 8 bytes, must be passed by reference."
4364     // However, non-power-of-two bit-precise integers will be passed as 1, 2, 4,
4365     // or 8 bytes anyway as long is it fits in them, so we don't have to check
4366     // the power of 2.
4367     if (Width <= 64)
4368       return ABIArgInfo::getDirect();
4369     return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4370   }
4371 
4372   return ABIArgInfo::getDirect();
4373 }
4374 
4375 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
4376   const unsigned CC = FI.getCallingConvention();
4377   bool IsVectorCall = CC == llvm::CallingConv::X86_VectorCall;
4378   bool IsRegCall = CC == llvm::CallingConv::X86_RegCall;
4379 
4380   // If __attribute__((sysv_abi)) is in use, use the SysV argument
4381   // classification rules.
4382   if (CC == llvm::CallingConv::X86_64_SysV) {
4383     X86_64ABIInfo SysVABIInfo(CGT, AVXLevel);
4384     SysVABIInfo.computeInfo(FI);
4385     return;
4386   }
4387 
4388   unsigned FreeSSERegs = 0;
4389   if (IsVectorCall) {
4390     // We can use up to 4 SSE return registers with vectorcall.
4391     FreeSSERegs = 4;
4392   } else if (IsRegCall) {
4393     // RegCall gives us 16 SSE registers.
4394     FreeSSERegs = 16;
4395   }
4396 
4397   if (!getCXXABI().classifyReturnType(FI))
4398     FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
4399                                   IsVectorCall, IsRegCall);
4400 
4401   if (IsVectorCall) {
4402     // We can use up to 6 SSE register parameters with vectorcall.
4403     FreeSSERegs = 6;
4404   } else if (IsRegCall) {
4405     // RegCall gives us 16 SSE registers, we can reuse the return registers.
4406     FreeSSERegs = 16;
4407   }
4408 
4409   unsigned ArgNum = 0;
4410   unsigned ZeroSSERegs = 0;
4411   for (auto &I : FI.arguments()) {
4412     // Vectorcall in x64 only permits the first 6 arguments to be passed as
4413     // XMM/YMM registers. After the sixth argument, pretend no vector
4414     // registers are left.
4415     unsigned *MaybeFreeSSERegs =
4416         (IsVectorCall && ArgNum >= 6) ? &ZeroSSERegs : &FreeSSERegs;
4417     I.info =
4418         classify(I.type, *MaybeFreeSSERegs, false, IsVectorCall, IsRegCall);
4419     ++ArgNum;
4420   }
4421 
4422   if (IsVectorCall) {
4423     // For vectorcall, assign aggregate HVAs to any free vector registers in a
4424     // second pass.
4425     for (auto &I : FI.arguments())
4426       I.info = reclassifyHvaArgForVectorCall(I.type, FreeSSERegs, I.info);
4427   }
4428 }
4429 
4430 Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4431                                     QualType Ty) const {
4432   // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4433   // not 1, 2, 4, or 8 bytes, must be passed by reference."
4434   uint64_t Width = getContext().getTypeSize(Ty);
4435   bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
4436 
4437   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
4438                           CGF.getContext().getTypeInfoInChars(Ty),
4439                           CharUnits::fromQuantity(8),
4440                           /*allowHigherAlign*/ false);
4441 }
4442 
4443 static bool PPC_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4444                                         llvm::Value *Address, bool Is64Bit,
4445                                         bool IsAIX) {
4446   // This is calculated from the LLVM and GCC tables and verified
4447   // against gcc output.  AFAIK all PPC ABIs use the same encoding.
4448 
4449   CodeGen::CGBuilderTy &Builder = CGF.Builder;
4450 
4451   llvm::IntegerType *i8 = CGF.Int8Ty;
4452   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4453   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4454   llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4455 
4456   // 0-31: r0-31, the 4-byte or 8-byte general-purpose registers
4457   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 0, 31);
4458 
4459   // 32-63: fp0-31, the 8-byte floating-point registers
4460   AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4461 
4462   // 64-67 are various 4-byte or 8-byte special-purpose registers:
4463   // 64: mq
4464   // 65: lr
4465   // 66: ctr
4466   // 67: ap
4467   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 64, 67);
4468 
4469   // 68-76 are various 4-byte special-purpose registers:
4470   // 68-75 cr0-7
4471   // 76: xer
4472   AssignToArrayRange(Builder, Address, Four8, 68, 76);
4473 
4474   // 77-108: v0-31, the 16-byte vector registers
4475   AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4476 
4477   // 109: vrsave
4478   // 110: vscr
4479   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 109, 110);
4480 
4481   // AIX does not utilize the rest of the registers.
4482   if (IsAIX)
4483     return false;
4484 
4485   // 111: spe_acc
4486   // 112: spefscr
4487   // 113: sfp
4488   AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 111, 113);
4489 
4490   if (!Is64Bit)
4491     return false;
4492 
4493   // TODO: Need to verify if these registers are used on 64 bit AIX with Power8
4494   // or above CPU.
4495   // 64-bit only registers:
4496   // 114: tfhar
4497   // 115: tfiar
4498   // 116: texasr
4499   AssignToArrayRange(Builder, Address, Eight8, 114, 116);
4500 
4501   return false;
4502 }
4503 
4504 // AIX
4505 namespace {
4506 /// AIXABIInfo - The AIX XCOFF ABI information.
4507 class AIXABIInfo : public ABIInfo {
4508   const bool Is64Bit;
4509   const unsigned PtrByteSize;
4510   CharUnits getParamTypeAlignment(QualType Ty) const;
4511 
4512 public:
4513   AIXABIInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit)
4514       : ABIInfo(CGT), Is64Bit(Is64Bit), PtrByteSize(Is64Bit ? 8 : 4) {}
4515 
4516   bool isPromotableTypeForABI(QualType Ty) const;
4517 
4518   ABIArgInfo classifyReturnType(QualType RetTy) const;
4519   ABIArgInfo classifyArgumentType(QualType Ty) const;
4520 
4521   void computeInfo(CGFunctionInfo &FI) const override {
4522     if (!getCXXABI().classifyReturnType(FI))
4523       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4524 
4525     for (auto &I : FI.arguments())
4526       I.info = classifyArgumentType(I.type);
4527   }
4528 
4529   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4530                     QualType Ty) const override;
4531 };
4532 
4533 class AIXTargetCodeGenInfo : public TargetCodeGenInfo {
4534   const bool Is64Bit;
4535 
4536 public:
4537   AIXTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit)
4538       : TargetCodeGenInfo(std::make_unique<AIXABIInfo>(CGT, Is64Bit)),
4539         Is64Bit(Is64Bit) {}
4540   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4541     return 1; // r1 is the dedicated stack pointer
4542   }
4543 
4544   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4545                                llvm::Value *Address) const override;
4546 };
4547 } // namespace
4548 
4549 // Return true if the ABI requires Ty to be passed sign- or zero-
4550 // extended to 32/64 bits.
4551 bool AIXABIInfo::isPromotableTypeForABI(QualType Ty) const {
4552   // Treat an enum type as its underlying type.
4553   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4554     Ty = EnumTy->getDecl()->getIntegerType();
4555 
4556   // Promotable integer types are required to be promoted by the ABI.
4557   if (Ty->isPromotableIntegerType())
4558     return true;
4559 
4560   if (!Is64Bit)
4561     return false;
4562 
4563   // For 64 bit mode, in addition to the usual promotable integer types, we also
4564   // need to extend all 32-bit types, since the ABI requires promotion to 64
4565   // bits.
4566   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4567     switch (BT->getKind()) {
4568     case BuiltinType::Int:
4569     case BuiltinType::UInt:
4570       return true;
4571     default:
4572       break;
4573     }
4574 
4575   return false;
4576 }
4577 
4578 ABIArgInfo AIXABIInfo::classifyReturnType(QualType RetTy) const {
4579   if (RetTy->isAnyComplexType())
4580     return ABIArgInfo::getDirect();
4581 
4582   if (RetTy->isVectorType())
4583     return ABIArgInfo::getDirect();
4584 
4585   if (RetTy->isVoidType())
4586     return ABIArgInfo::getIgnore();
4587 
4588   if (isAggregateTypeForABI(RetTy))
4589     return getNaturalAlignIndirect(RetTy);
4590 
4591   return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
4592                                         : ABIArgInfo::getDirect());
4593 }
4594 
4595 ABIArgInfo AIXABIInfo::classifyArgumentType(QualType Ty) const {
4596   Ty = useFirstFieldIfTransparentUnion(Ty);
4597 
4598   if (Ty->isAnyComplexType())
4599     return ABIArgInfo::getDirect();
4600 
4601   if (Ty->isVectorType())
4602     return ABIArgInfo::getDirect();
4603 
4604   if (isAggregateTypeForABI(Ty)) {
4605     // Records with non-trivial destructors/copy-constructors should not be
4606     // passed by value.
4607     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
4608       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
4609 
4610     CharUnits CCAlign = getParamTypeAlignment(Ty);
4611     CharUnits TyAlign = getContext().getTypeAlignInChars(Ty);
4612 
4613     return ABIArgInfo::getIndirect(CCAlign, /*ByVal*/ true,
4614                                    /*Realign*/ TyAlign > CCAlign);
4615   }
4616 
4617   return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
4618                                      : ABIArgInfo::getDirect());
4619 }
4620 
4621 CharUnits AIXABIInfo::getParamTypeAlignment(QualType Ty) const {
4622   // Complex types are passed just like their elements.
4623   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4624     Ty = CTy->getElementType();
4625 
4626   if (Ty->isVectorType())
4627     return CharUnits::fromQuantity(16);
4628 
4629   // If the structure contains a vector type, the alignment is 16.
4630   if (isRecordWithSIMDVectorType(getContext(), Ty))
4631     return CharUnits::fromQuantity(16);
4632 
4633   return CharUnits::fromQuantity(PtrByteSize);
4634 }
4635 
4636 Address AIXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4637                               QualType Ty) const {
4638 
4639   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4640   TypeInfo.Align = getParamTypeAlignment(Ty);
4641 
4642   CharUnits SlotSize = CharUnits::fromQuantity(PtrByteSize);
4643 
4644   // If we have a complex type and the base type is smaller than the register
4645   // size, the ABI calls for the real and imaginary parts to be right-adjusted
4646   // in separate words in 32bit mode or doublewords in 64bit mode. However,
4647   // Clang expects us to produce a pointer to a structure with the two parts
4648   // packed tightly. So generate loads of the real and imaginary parts relative
4649   // to the va_list pointer, and store them to a temporary structure. We do the
4650   // same as the PPC64ABI here.
4651   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4652     CharUnits EltSize = TypeInfo.Width / 2;
4653     if (EltSize < SlotSize)
4654       return complexTempStructure(CGF, VAListAddr, Ty, SlotSize, EltSize, CTy);
4655   }
4656 
4657   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, TypeInfo,
4658                           SlotSize, /*AllowHigher*/ true);
4659 }
4660 
4661 bool AIXTargetCodeGenInfo::initDwarfEHRegSizeTable(
4662     CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const {
4663   return PPC_initDwarfEHRegSizeTable(CGF, Address, Is64Bit, /*IsAIX*/ true);
4664 }
4665 
4666 // PowerPC-32
4667 namespace {
4668 /// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
4669 class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
4670   bool IsSoftFloatABI;
4671   bool IsRetSmallStructInRegABI;
4672 
4673   CharUnits getParamTypeAlignment(QualType Ty) const;
4674 
4675 public:
4676   PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI,
4677                      bool RetSmallStructInRegABI)
4678       : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI),
4679         IsRetSmallStructInRegABI(RetSmallStructInRegABI) {}
4680 
4681   ABIArgInfo classifyReturnType(QualType RetTy) const;
4682 
4683   void computeInfo(CGFunctionInfo &FI) const override {
4684     if (!getCXXABI().classifyReturnType(FI))
4685       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4686     for (auto &I : FI.arguments())
4687       I.info = classifyArgumentType(I.type);
4688   }
4689 
4690   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4691                     QualType Ty) const override;
4692 };
4693 
4694 class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
4695 public:
4696   PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI,
4697                          bool RetSmallStructInRegABI)
4698       : TargetCodeGenInfo(std::make_unique<PPC32_SVR4_ABIInfo>(
4699             CGT, SoftFloatABI, RetSmallStructInRegABI)) {}
4700 
4701   static bool isStructReturnInRegABI(const llvm::Triple &Triple,
4702                                      const CodeGenOptions &Opts);
4703 
4704   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4705     // This is recovered from gcc output.
4706     return 1; // r1 is the dedicated stack pointer
4707   }
4708 
4709   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4710                                llvm::Value *Address) const override;
4711 };
4712 }
4713 
4714 CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
4715   // Complex types are passed just like their elements.
4716   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4717     Ty = CTy->getElementType();
4718 
4719   if (Ty->isVectorType())
4720     return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16
4721                                                                        : 4);
4722 
4723   // For single-element float/vector structs, we consider the whole type
4724   // to have the same alignment requirements as its single element.
4725   const Type *AlignTy = nullptr;
4726   if (const Type *EltType = isSingleElementStruct(Ty, getContext())) {
4727     const BuiltinType *BT = EltType->getAs<BuiltinType>();
4728     if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
4729         (BT && BT->isFloatingPoint()))
4730       AlignTy = EltType;
4731   }
4732 
4733   if (AlignTy)
4734     return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4);
4735   return CharUnits::fromQuantity(4);
4736 }
4737 
4738 ABIArgInfo PPC32_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4739   uint64_t Size;
4740 
4741   // -msvr4-struct-return puts small aggregates in GPR3 and GPR4.
4742   if (isAggregateTypeForABI(RetTy) && IsRetSmallStructInRegABI &&
4743       (Size = getContext().getTypeSize(RetTy)) <= 64) {
4744     // System V ABI (1995), page 3-22, specified:
4745     // > A structure or union whose size is less than or equal to 8 bytes
4746     // > shall be returned in r3 and r4, as if it were first stored in the
4747     // > 8-byte aligned memory area and then the low addressed word were
4748     // > loaded into r3 and the high-addressed word into r4.  Bits beyond
4749     // > the last member of the structure or union are not defined.
4750     //
4751     // GCC for big-endian PPC32 inserts the pad before the first member,
4752     // not "beyond the last member" of the struct.  To stay compatible
4753     // with GCC, we coerce the struct to an integer of the same size.
4754     // LLVM will extend it and return i32 in r3, or i64 in r3:r4.
4755     if (Size == 0)
4756       return ABIArgInfo::getIgnore();
4757     else {
4758       llvm::Type *CoerceTy = llvm::Type::getIntNTy(getVMContext(), Size);
4759       return ABIArgInfo::getDirect(CoerceTy);
4760     }
4761   }
4762 
4763   return DefaultABIInfo::classifyReturnType(RetTy);
4764 }
4765 
4766 // TODO: this implementation is now likely redundant with
4767 // DefaultABIInfo::EmitVAArg.
4768 Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
4769                                       QualType Ty) const {
4770   if (getTarget().getTriple().isOSDarwin()) {
4771     auto TI = getContext().getTypeInfoInChars(Ty);
4772     TI.Align = getParamTypeAlignment(Ty);
4773 
4774     CharUnits SlotSize = CharUnits::fromQuantity(4);
4775     return emitVoidPtrVAArg(CGF, VAList, Ty,
4776                             classifyArgumentType(Ty).isIndirect(), TI, SlotSize,
4777                             /*AllowHigherAlign=*/true);
4778   }
4779 
4780   const unsigned OverflowLimit = 8;
4781   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4782     // TODO: Implement this. For now ignore.
4783     (void)CTy;
4784     return Address::invalid(); // FIXME?
4785   }
4786 
4787   // struct __va_list_tag {
4788   //   unsigned char gpr;
4789   //   unsigned char fpr;
4790   //   unsigned short reserved;
4791   //   void *overflow_arg_area;
4792   //   void *reg_save_area;
4793   // };
4794 
4795   bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
4796   bool isInt = !Ty->isFloatingType();
4797   bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
4798 
4799   // All aggregates are passed indirectly?  That doesn't seem consistent
4800   // with the argument-lowering code.
4801   bool isIndirect = isAggregateTypeForABI(Ty);
4802 
4803   CGBuilderTy &Builder = CGF.Builder;
4804 
4805   // The calling convention either uses 1-2 GPRs or 1 FPR.
4806   Address NumRegsAddr = Address::invalid();
4807   if (isInt || IsSoftFloatABI) {
4808     NumRegsAddr = Builder.CreateStructGEP(VAList, 0, "gpr");
4809   } else {
4810     NumRegsAddr = Builder.CreateStructGEP(VAList, 1, "fpr");
4811   }
4812 
4813   llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
4814 
4815   // "Align" the register count when TY is i64.
4816   if (isI64 || (isF64 && IsSoftFloatABI)) {
4817     NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
4818     NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
4819   }
4820 
4821   llvm::Value *CC =
4822       Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
4823 
4824   llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
4825   llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
4826   llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
4827 
4828   Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
4829 
4830   llvm::Type *DirectTy = CGF.ConvertType(Ty);
4831   if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
4832 
4833   // Case 1: consume registers.
4834   Address RegAddr = Address::invalid();
4835   {
4836     CGF.EmitBlock(UsingRegs);
4837 
4838     Address RegSaveAreaPtr = Builder.CreateStructGEP(VAList, 4);
4839     RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
4840                       CharUnits::fromQuantity(8));
4841     assert(RegAddr.getElementType() == CGF.Int8Ty);
4842 
4843     // Floating-point registers start after the general-purpose registers.
4844     if (!(isInt || IsSoftFloatABI)) {
4845       RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
4846                                                    CharUnits::fromQuantity(32));
4847     }
4848 
4849     // Get the address of the saved value by scaling the number of
4850     // registers we've used by the number of
4851     CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
4852     llvm::Value *RegOffset =
4853       Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
4854     RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
4855                                             RegAddr.getPointer(), RegOffset),
4856                       RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
4857     RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
4858 
4859     // Increase the used-register count.
4860     NumRegs =
4861       Builder.CreateAdd(NumRegs,
4862                         Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
4863     Builder.CreateStore(NumRegs, NumRegsAddr);
4864 
4865     CGF.EmitBranch(Cont);
4866   }
4867 
4868   // Case 2: consume space in the overflow area.
4869   Address MemAddr = Address::invalid();
4870   {
4871     CGF.EmitBlock(UsingOverflow);
4872 
4873     Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
4874 
4875     // Everything in the overflow area is rounded up to a size of at least 4.
4876     CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
4877 
4878     CharUnits Size;
4879     if (!isIndirect) {
4880       auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
4881       Size = TypeInfo.Width.alignTo(OverflowAreaAlign);
4882     } else {
4883       Size = CGF.getPointerSize();
4884     }
4885 
4886     Address OverflowAreaAddr = Builder.CreateStructGEP(VAList, 3);
4887     Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
4888                          OverflowAreaAlign);
4889     // Round up address of argument to alignment
4890     CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4891     if (Align > OverflowAreaAlign) {
4892       llvm::Value *Ptr = OverflowArea.getPointer();
4893       OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
4894                                                            Align);
4895     }
4896 
4897     MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
4898 
4899     // Increase the overflow area.
4900     OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
4901     Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
4902     CGF.EmitBranch(Cont);
4903   }
4904 
4905   CGF.EmitBlock(Cont);
4906 
4907   // Merge the cases with a phi.
4908   Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
4909                                 "vaarg.addr");
4910 
4911   // Load the pointer if the argument was passed indirectly.
4912   if (isIndirect) {
4913     Result = Address(Builder.CreateLoad(Result, "aggr"),
4914                      getContext().getTypeAlignInChars(Ty));
4915   }
4916 
4917   return Result;
4918 }
4919 
4920 bool PPC32TargetCodeGenInfo::isStructReturnInRegABI(
4921     const llvm::Triple &Triple, const CodeGenOptions &Opts) {
4922   assert(Triple.isPPC32());
4923 
4924   switch (Opts.getStructReturnConvention()) {
4925   case CodeGenOptions::SRCK_Default:
4926     break;
4927   case CodeGenOptions::SRCK_OnStack: // -maix-struct-return
4928     return false;
4929   case CodeGenOptions::SRCK_InRegs: // -msvr4-struct-return
4930     return true;
4931   }
4932 
4933   if (Triple.isOSBinFormatELF() && !Triple.isOSLinux())
4934     return true;
4935 
4936   return false;
4937 }
4938 
4939 bool
4940 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4941                                                 llvm::Value *Address) const {
4942   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ false,
4943                                      /*IsAIX*/ false);
4944 }
4945 
4946 // PowerPC-64
4947 
4948 namespace {
4949 /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
4950 class PPC64_SVR4_ABIInfo : public SwiftABIInfo {
4951 public:
4952   enum ABIKind {
4953     ELFv1 = 0,
4954     ELFv2
4955   };
4956 
4957 private:
4958   static const unsigned GPRBits = 64;
4959   ABIKind Kind;
4960   bool IsSoftFloatABI;
4961 
4962 public:
4963   PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind,
4964                      bool SoftFloatABI)
4965       : SwiftABIInfo(CGT), Kind(Kind), IsSoftFloatABI(SoftFloatABI) {}
4966 
4967   bool isPromotableTypeForABI(QualType Ty) const;
4968   CharUnits getParamTypeAlignment(QualType Ty) const;
4969 
4970   ABIArgInfo classifyReturnType(QualType RetTy) const;
4971   ABIArgInfo classifyArgumentType(QualType Ty) const;
4972 
4973   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4974   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4975                                          uint64_t Members) const override;
4976 
4977   // TODO: We can add more logic to computeInfo to improve performance.
4978   // Example: For aggregate arguments that fit in a register, we could
4979   // use getDirectInReg (as is done below for structs containing a single
4980   // floating-point value) to avoid pushing them to memory on function
4981   // entry.  This would require changing the logic in PPCISelLowering
4982   // when lowering the parameters in the caller and args in the callee.
4983   void computeInfo(CGFunctionInfo &FI) const override {
4984     if (!getCXXABI().classifyReturnType(FI))
4985       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4986     for (auto &I : FI.arguments()) {
4987       // We rely on the default argument classification for the most part.
4988       // One exception:  An aggregate containing a single floating-point
4989       // or vector item must be passed in a register if one is available.
4990       const Type *T = isSingleElementStruct(I.type, getContext());
4991       if (T) {
4992         const BuiltinType *BT = T->getAs<BuiltinType>();
4993         if ((T->isVectorType() && getContext().getTypeSize(T) == 128) ||
4994             (BT && BT->isFloatingPoint())) {
4995           QualType QT(T, 0);
4996           I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
4997           continue;
4998         }
4999       }
5000       I.info = classifyArgumentType(I.type);
5001     }
5002   }
5003 
5004   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5005                     QualType Ty) const override;
5006 
5007   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
5008                                     bool asReturnValue) const override {
5009     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5010   }
5011 
5012   bool isSwiftErrorInRegister() const override {
5013     return false;
5014   }
5015 };
5016 
5017 class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
5018 
5019 public:
5020   PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
5021                                PPC64_SVR4_ABIInfo::ABIKind Kind,
5022                                bool SoftFloatABI)
5023       : TargetCodeGenInfo(
5024             std::make_unique<PPC64_SVR4_ABIInfo>(CGT, Kind, SoftFloatABI)) {}
5025 
5026   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5027     // This is recovered from gcc output.
5028     return 1; // r1 is the dedicated stack pointer
5029   }
5030 
5031   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5032                                llvm::Value *Address) const override;
5033 };
5034 
5035 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
5036 public:
5037   PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
5038 
5039   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5040     // This is recovered from gcc output.
5041     return 1; // r1 is the dedicated stack pointer
5042   }
5043 
5044   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5045                                llvm::Value *Address) const override;
5046 };
5047 
5048 }
5049 
5050 // Return true if the ABI requires Ty to be passed sign- or zero-
5051 // extended to 64 bits.
5052 bool
5053 PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
5054   // Treat an enum type as its underlying type.
5055   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5056     Ty = EnumTy->getDecl()->getIntegerType();
5057 
5058   // Promotable integer types are required to be promoted by the ABI.
5059   if (isPromotableIntegerTypeForABI(Ty))
5060     return true;
5061 
5062   // In addition to the usual promotable integer types, we also need to
5063   // extend all 32-bit types, since the ABI requires promotion to 64 bits.
5064   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5065     switch (BT->getKind()) {
5066     case BuiltinType::Int:
5067     case BuiltinType::UInt:
5068       return true;
5069     default:
5070       break;
5071     }
5072 
5073   if (const auto *EIT = Ty->getAs<BitIntType>())
5074     if (EIT->getNumBits() < 64)
5075       return true;
5076 
5077   return false;
5078 }
5079 
5080 /// isAlignedParamType - Determine whether a type requires 16-byte or
5081 /// higher alignment in the parameter area.  Always returns at least 8.
5082 CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
5083   // Complex types are passed just like their elements.
5084   if (const ComplexType *CTy = Ty->getAs<ComplexType>())
5085     Ty = CTy->getElementType();
5086 
5087   auto FloatUsesVector = [this](QualType Ty){
5088     return Ty->isRealFloatingType() && &getContext().getFloatTypeSemantics(
5089                                            Ty) == &llvm::APFloat::IEEEquad();
5090   };
5091 
5092   // Only vector types of size 16 bytes need alignment (larger types are
5093   // passed via reference, smaller types are not aligned).
5094   if (Ty->isVectorType()) {
5095     return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
5096   } else if (FloatUsesVector(Ty)) {
5097     // According to ABI document section 'Optional Save Areas': If extended
5098     // precision floating-point values in IEEE BINARY 128 QUADRUPLE PRECISION
5099     // format are supported, map them to a single quadword, quadword aligned.
5100     return CharUnits::fromQuantity(16);
5101   }
5102 
5103   // For single-element float/vector structs, we consider the whole type
5104   // to have the same alignment requirements as its single element.
5105   const Type *AlignAsType = nullptr;
5106   const Type *EltType = isSingleElementStruct(Ty, getContext());
5107   if (EltType) {
5108     const BuiltinType *BT = EltType->getAs<BuiltinType>();
5109     if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
5110         (BT && BT->isFloatingPoint()))
5111       AlignAsType = EltType;
5112   }
5113 
5114   // Likewise for ELFv2 homogeneous aggregates.
5115   const Type *Base = nullptr;
5116   uint64_t Members = 0;
5117   if (!AlignAsType && Kind == ELFv2 &&
5118       isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
5119     AlignAsType = Base;
5120 
5121   // With special case aggregates, only vector base types need alignment.
5122   if (AlignAsType) {
5123     bool UsesVector = AlignAsType->isVectorType() ||
5124                       FloatUsesVector(QualType(AlignAsType, 0));
5125     return CharUnits::fromQuantity(UsesVector ? 16 : 8);
5126   }
5127 
5128   // Otherwise, we only need alignment for any aggregate type that
5129   // has an alignment requirement of >= 16 bytes.
5130   if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
5131     return CharUnits::fromQuantity(16);
5132   }
5133 
5134   return CharUnits::fromQuantity(8);
5135 }
5136 
5137 /// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
5138 /// aggregate.  Base is set to the base element type, and Members is set
5139 /// to the number of base elements.
5140 bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
5141                                      uint64_t &Members) const {
5142   if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
5143     uint64_t NElements = AT->getSize().getZExtValue();
5144     if (NElements == 0)
5145       return false;
5146     if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
5147       return false;
5148     Members *= NElements;
5149   } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
5150     const RecordDecl *RD = RT->getDecl();
5151     if (RD->hasFlexibleArrayMember())
5152       return false;
5153 
5154     Members = 0;
5155 
5156     // If this is a C++ record, check the properties of the record such as
5157     // bases and ABI specific restrictions
5158     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
5159       if (!getCXXABI().isPermittedToBeHomogeneousAggregate(CXXRD))
5160         return false;
5161 
5162       for (const auto &I : CXXRD->bases()) {
5163         // Ignore empty records.
5164         if (isEmptyRecord(getContext(), I.getType(), true))
5165           continue;
5166 
5167         uint64_t FldMembers;
5168         if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
5169           return false;
5170 
5171         Members += FldMembers;
5172       }
5173     }
5174 
5175     for (const auto *FD : RD->fields()) {
5176       // Ignore (non-zero arrays of) empty records.
5177       QualType FT = FD->getType();
5178       while (const ConstantArrayType *AT =
5179              getContext().getAsConstantArrayType(FT)) {
5180         if (AT->getSize().getZExtValue() == 0)
5181           return false;
5182         FT = AT->getElementType();
5183       }
5184       if (isEmptyRecord(getContext(), FT, true))
5185         continue;
5186 
5187       // For compatibility with GCC, ignore empty bitfields in C++ mode.
5188       if (getContext().getLangOpts().CPlusPlus &&
5189           FD->isZeroLengthBitField(getContext()))
5190         continue;
5191 
5192       uint64_t FldMembers;
5193       if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
5194         return false;
5195 
5196       Members = (RD->isUnion() ?
5197                  std::max(Members, FldMembers) : Members + FldMembers);
5198     }
5199 
5200     if (!Base)
5201       return false;
5202 
5203     // Ensure there is no padding.
5204     if (getContext().getTypeSize(Base) * Members !=
5205         getContext().getTypeSize(Ty))
5206       return false;
5207   } else {
5208     Members = 1;
5209     if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
5210       Members = 2;
5211       Ty = CT->getElementType();
5212     }
5213 
5214     // Most ABIs only support float, double, and some vector type widths.
5215     if (!isHomogeneousAggregateBaseType(Ty))
5216       return false;
5217 
5218     // The base type must be the same for all members.  Types that
5219     // agree in both total size and mode (float vs. vector) are
5220     // treated as being equivalent here.
5221     const Type *TyPtr = Ty.getTypePtr();
5222     if (!Base) {
5223       Base = TyPtr;
5224       // If it's a non-power-of-2 vector, its size is already a power-of-2,
5225       // so make sure to widen it explicitly.
5226       if (const VectorType *VT = Base->getAs<VectorType>()) {
5227         QualType EltTy = VT->getElementType();
5228         unsigned NumElements =
5229             getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
5230         Base = getContext()
5231                    .getVectorType(EltTy, NumElements, VT->getVectorKind())
5232                    .getTypePtr();
5233       }
5234     }
5235 
5236     if (Base->isVectorType() != TyPtr->isVectorType() ||
5237         getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
5238       return false;
5239   }
5240   return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
5241 }
5242 
5243 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5244   // Homogeneous aggregates for ELFv2 must have base types of float,
5245   // double, long double, or 128-bit vectors.
5246   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5247     if (BT->getKind() == BuiltinType::Float ||
5248         BT->getKind() == BuiltinType::Double ||
5249         BT->getKind() == BuiltinType::LongDouble ||
5250         BT->getKind() == BuiltinType::Ibm128 ||
5251         (getContext().getTargetInfo().hasFloat128Type() &&
5252          (BT->getKind() == BuiltinType::Float128))) {
5253       if (IsSoftFloatABI)
5254         return false;
5255       return true;
5256     }
5257   }
5258   if (const VectorType *VT = Ty->getAs<VectorType>()) {
5259     if (getContext().getTypeSize(VT) == 128)
5260       return true;
5261   }
5262   return false;
5263 }
5264 
5265 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
5266     const Type *Base, uint64_t Members) const {
5267   // Vector and fp128 types require one register, other floating point types
5268   // require one or two registers depending on their size.
5269   uint32_t NumRegs =
5270       ((getContext().getTargetInfo().hasFloat128Type() &&
5271           Base->isFloat128Type()) ||
5272         Base->isVectorType()) ? 1
5273                               : (getContext().getTypeSize(Base) + 63) / 64;
5274 
5275   // Homogeneous Aggregates may occupy at most 8 registers.
5276   return Members * NumRegs <= 8;
5277 }
5278 
5279 ABIArgInfo
5280 PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
5281   Ty = useFirstFieldIfTransparentUnion(Ty);
5282 
5283   if (Ty->isAnyComplexType())
5284     return ABIArgInfo::getDirect();
5285 
5286   // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
5287   // or via reference (larger than 16 bytes).
5288   if (Ty->isVectorType()) {
5289     uint64_t Size = getContext().getTypeSize(Ty);
5290     if (Size > 128)
5291       return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5292     else if (Size < 128) {
5293       llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
5294       return ABIArgInfo::getDirect(CoerceTy);
5295     }
5296   }
5297 
5298   if (const auto *EIT = Ty->getAs<BitIntType>())
5299     if (EIT->getNumBits() > 128)
5300       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
5301 
5302   if (isAggregateTypeForABI(Ty)) {
5303     if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
5304       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
5305 
5306     uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
5307     uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
5308 
5309     // ELFv2 homogeneous aggregates are passed as array types.
5310     const Type *Base = nullptr;
5311     uint64_t Members = 0;
5312     if (Kind == ELFv2 &&
5313         isHomogeneousAggregate(Ty, Base, Members)) {
5314       llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
5315       llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
5316       return ABIArgInfo::getDirect(CoerceTy);
5317     }
5318 
5319     // If an aggregate may end up fully in registers, we do not
5320     // use the ByVal method, but pass the aggregate as array.
5321     // This is usually beneficial since we avoid forcing the
5322     // back-end to store the argument to memory.
5323     uint64_t Bits = getContext().getTypeSize(Ty);
5324     if (Bits > 0 && Bits <= 8 * GPRBits) {
5325       llvm::Type *CoerceTy;
5326 
5327       // Types up to 8 bytes are passed as integer type (which will be
5328       // properly aligned in the argument save area doubleword).
5329       if (Bits <= GPRBits)
5330         CoerceTy =
5331             llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
5332       // Larger types are passed as arrays, with the base type selected
5333       // according to the required alignment in the save area.
5334       else {
5335         uint64_t RegBits = ABIAlign * 8;
5336         uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
5337         llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
5338         CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
5339       }
5340 
5341       return ABIArgInfo::getDirect(CoerceTy);
5342     }
5343 
5344     // All other aggregates are passed ByVal.
5345     return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5346                                    /*ByVal=*/true,
5347                                    /*Realign=*/TyAlign > ABIAlign);
5348   }
5349 
5350   return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
5351                                      : ABIArgInfo::getDirect());
5352 }
5353 
5354 ABIArgInfo
5355 PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
5356   if (RetTy->isVoidType())
5357     return ABIArgInfo::getIgnore();
5358 
5359   if (RetTy->isAnyComplexType())
5360     return ABIArgInfo::getDirect();
5361 
5362   // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
5363   // or via reference (larger than 16 bytes).
5364   if (RetTy->isVectorType()) {
5365     uint64_t Size = getContext().getTypeSize(RetTy);
5366     if (Size > 128)
5367       return getNaturalAlignIndirect(RetTy);
5368     else if (Size < 128) {
5369       llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
5370       return ABIArgInfo::getDirect(CoerceTy);
5371     }
5372   }
5373 
5374   if (const auto *EIT = RetTy->getAs<BitIntType>())
5375     if (EIT->getNumBits() > 128)
5376       return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
5377 
5378   if (isAggregateTypeForABI(RetTy)) {
5379     // ELFv2 homogeneous aggregates are returned as array types.
5380     const Type *Base = nullptr;
5381     uint64_t Members = 0;
5382     if (Kind == ELFv2 &&
5383         isHomogeneousAggregate(RetTy, Base, Members)) {
5384       llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
5385       llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
5386       return ABIArgInfo::getDirect(CoerceTy);
5387     }
5388 
5389     // ELFv2 small aggregates are returned in up to two registers.
5390     uint64_t Bits = getContext().getTypeSize(RetTy);
5391     if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
5392       if (Bits == 0)
5393         return ABIArgInfo::getIgnore();
5394 
5395       llvm::Type *CoerceTy;
5396       if (Bits > GPRBits) {
5397         CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
5398         CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy);
5399       } else
5400         CoerceTy =
5401             llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
5402       return ABIArgInfo::getDirect(CoerceTy);
5403     }
5404 
5405     // All other aggregates are returned indirectly.
5406     return getNaturalAlignIndirect(RetTy);
5407   }
5408 
5409   return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
5410                                         : ABIArgInfo::getDirect());
5411 }
5412 
5413 // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
5414 Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5415                                       QualType Ty) const {
5416   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
5417   TypeInfo.Align = getParamTypeAlignment(Ty);
5418 
5419   CharUnits SlotSize = CharUnits::fromQuantity(8);
5420 
5421   // If we have a complex type and the base type is smaller than 8 bytes,
5422   // the ABI calls for the real and imaginary parts to be right-adjusted
5423   // in separate doublewords.  However, Clang expects us to produce a
5424   // pointer to a structure with the two parts packed tightly.  So generate
5425   // loads of the real and imaginary parts relative to the va_list pointer,
5426   // and store them to a temporary structure.
5427   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
5428     CharUnits EltSize = TypeInfo.Width / 2;
5429     if (EltSize < SlotSize)
5430       return complexTempStructure(CGF, VAListAddr, Ty, SlotSize, EltSize, CTy);
5431   }
5432 
5433   // Otherwise, just use the general rule.
5434   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
5435                           TypeInfo, SlotSize, /*AllowHigher*/ true);
5436 }
5437 
5438 bool
5439 PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
5440   CodeGen::CodeGenFunction &CGF,
5441   llvm::Value *Address) const {
5442   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true,
5443                                      /*IsAIX*/ false);
5444 }
5445 
5446 bool
5447 PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5448                                                 llvm::Value *Address) const {
5449   return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true,
5450                                      /*IsAIX*/ false);
5451 }
5452 
5453 //===----------------------------------------------------------------------===//
5454 // AArch64 ABI Implementation
5455 //===----------------------------------------------------------------------===//
5456 
5457 namespace {
5458 
5459 class AArch64ABIInfo : public SwiftABIInfo {
5460 public:
5461   enum ABIKind {
5462     AAPCS = 0,
5463     DarwinPCS,
5464     Win64
5465   };
5466 
5467 private:
5468   ABIKind Kind;
5469 
5470 public:
5471   AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
5472     : SwiftABIInfo(CGT), Kind(Kind) {}
5473 
5474 private:
5475   ABIKind getABIKind() const { return Kind; }
5476   bool isDarwinPCS() const { return Kind == DarwinPCS; }
5477 
5478   ABIArgInfo classifyReturnType(QualType RetTy, bool IsVariadic) const;
5479   ABIArgInfo classifyArgumentType(QualType RetTy, bool IsVariadic,
5480                                   unsigned CallingConvention) const;
5481   ABIArgInfo coerceIllegalVector(QualType Ty) const;
5482   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5483   bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5484                                          uint64_t Members) const override;
5485 
5486   bool isIllegalVectorType(QualType Ty) const;
5487 
5488   void computeInfo(CGFunctionInfo &FI) const override {
5489     if (!::classifyReturnType(getCXXABI(), FI, *this))
5490       FI.getReturnInfo() =
5491           classifyReturnType(FI.getReturnType(), FI.isVariadic());
5492 
5493     for (auto &it : FI.arguments())
5494       it.info = classifyArgumentType(it.type, FI.isVariadic(),
5495                                      FI.getCallingConvention());
5496   }
5497 
5498   Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5499                           CodeGenFunction &CGF) const;
5500 
5501   Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
5502                          CodeGenFunction &CGF) const;
5503 
5504   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5505                     QualType Ty) const override {
5506     llvm::Type *BaseTy = CGF.ConvertType(Ty);
5507     if (isa<llvm::ScalableVectorType>(BaseTy))
5508       llvm::report_fatal_error("Passing SVE types to variadic functions is "
5509                                "currently not supported");
5510 
5511     return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty)
5512                          : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
5513                                          : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
5514   }
5515 
5516   Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
5517                       QualType Ty) const override;
5518 
5519   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
5520                                     bool asReturnValue) const override {
5521     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5522   }
5523   bool isSwiftErrorInRegister() const override {
5524     return true;
5525   }
5526 
5527   bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
5528                                  unsigned elts) const override;
5529 
5530   bool allowBFloatArgsAndRet() const override {
5531     return getTarget().hasBFloat16Type();
5532   }
5533 };
5534 
5535 class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
5536 public:
5537   AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
5538       : TargetCodeGenInfo(std::make_unique<AArch64ABIInfo>(CGT, Kind)) {}
5539 
5540   StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
5541     return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue";
5542   }
5543 
5544   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5545     return 31;
5546   }
5547 
5548   bool doesReturnSlotInterfereWithArgs() const override { return false; }
5549 
5550   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5551                            CodeGen::CodeGenModule &CGM) const override {
5552     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
5553     if (!FD)
5554       return;
5555 
5556     const auto *TA = FD->getAttr<TargetAttr>();
5557     if (TA == nullptr)
5558       return;
5559 
5560     ParsedTargetAttr Attr = TA->parse();
5561     if (Attr.BranchProtection.empty())
5562       return;
5563 
5564     TargetInfo::BranchProtectionInfo BPI;
5565     StringRef Error;
5566     (void)CGM.getTarget().validateBranchProtection(
5567         Attr.BranchProtection, Attr.Architecture, BPI, Error);
5568     assert(Error.empty());
5569 
5570     auto *Fn = cast<llvm::Function>(GV);
5571     static const char *SignReturnAddrStr[] = {"none", "non-leaf", "all"};
5572     Fn->addFnAttr("sign-return-address", SignReturnAddrStr[static_cast<int>(BPI.SignReturnAddr)]);
5573 
5574     if (BPI.SignReturnAddr != LangOptions::SignReturnAddressScopeKind::None) {
5575       Fn->addFnAttr("sign-return-address-key",
5576                     BPI.SignKey == LangOptions::SignReturnAddressKeyKind::AKey
5577                         ? "a_key"
5578                         : "b_key");
5579     }
5580 
5581     Fn->addFnAttr("branch-target-enforcement",
5582                   BPI.BranchTargetEnforcement ? "true" : "false");
5583   }
5584 
5585   bool isScalarizableAsmOperand(CodeGen::CodeGenFunction &CGF,
5586                                 llvm::Type *Ty) const override {
5587     if (CGF.getTarget().hasFeature("ls64")) {
5588       auto *ST = dyn_cast<llvm::StructType>(Ty);
5589       if (ST && ST->getNumElements() == 1) {
5590         auto *AT = dyn_cast<llvm::ArrayType>(ST->getElementType(0));
5591         if (AT && AT->getNumElements() == 8 &&
5592             AT->getElementType()->isIntegerTy(64))
5593           return true;
5594       }
5595     }
5596     return TargetCodeGenInfo::isScalarizableAsmOperand(CGF, Ty);
5597   }
5598 };
5599 
5600 class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
5601 public:
5602   WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K)
5603       : AArch64TargetCodeGenInfo(CGT, K) {}
5604 
5605   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5606                            CodeGen::CodeGenModule &CGM) const override;
5607 
5608   void getDependentLibraryOption(llvm::StringRef Lib,
5609                                  llvm::SmallString<24> &Opt) const override {
5610     Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5611   }
5612 
5613   void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5614                                llvm::SmallString<32> &Opt) const override {
5615     Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5616   }
5617 };
5618 
5619 void WindowsAArch64TargetCodeGenInfo::setTargetAttributes(
5620     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
5621   AArch64TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
5622   if (GV->isDeclaration())
5623     return;
5624   addStackProbeTargetAttributes(D, GV, CGM);
5625 }
5626 }
5627 
5628 ABIArgInfo AArch64ABIInfo::coerceIllegalVector(QualType Ty) const {
5629   assert(Ty->isVectorType() && "expected vector type!");
5630 
5631   const auto *VT = Ty->castAs<VectorType>();
5632   if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) {
5633     assert(VT->getElementType()->isBuiltinType() && "expected builtin type!");
5634     assert(VT->getElementType()->castAs<BuiltinType>()->getKind() ==
5635                BuiltinType::UChar &&
5636            "unexpected builtin type for SVE predicate!");
5637     return ABIArgInfo::getDirect(llvm::ScalableVectorType::get(
5638         llvm::Type::getInt1Ty(getVMContext()), 16));
5639   }
5640 
5641   if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) {
5642     assert(VT->getElementType()->isBuiltinType() && "expected builtin type!");
5643 
5644     const auto *BT = VT->getElementType()->castAs<BuiltinType>();
5645     llvm::ScalableVectorType *ResType = nullptr;
5646     switch (BT->getKind()) {
5647     default:
5648       llvm_unreachable("unexpected builtin type for SVE vector!");
5649     case BuiltinType::SChar:
5650     case BuiltinType::UChar:
5651       ResType = llvm::ScalableVectorType::get(
5652           llvm::Type::getInt8Ty(getVMContext()), 16);
5653       break;
5654     case BuiltinType::Short:
5655     case BuiltinType::UShort:
5656       ResType = llvm::ScalableVectorType::get(
5657           llvm::Type::getInt16Ty(getVMContext()), 8);
5658       break;
5659     case BuiltinType::Int:
5660     case BuiltinType::UInt:
5661       ResType = llvm::ScalableVectorType::get(
5662           llvm::Type::getInt32Ty(getVMContext()), 4);
5663       break;
5664     case BuiltinType::Long:
5665     case BuiltinType::ULong:
5666       ResType = llvm::ScalableVectorType::get(
5667           llvm::Type::getInt64Ty(getVMContext()), 2);
5668       break;
5669     case BuiltinType::Half:
5670       ResType = llvm::ScalableVectorType::get(
5671           llvm::Type::getHalfTy(getVMContext()), 8);
5672       break;
5673     case BuiltinType::Float:
5674       ResType = llvm::ScalableVectorType::get(
5675           llvm::Type::getFloatTy(getVMContext()), 4);
5676       break;
5677     case BuiltinType::Double:
5678       ResType = llvm::ScalableVectorType::get(
5679           llvm::Type::getDoubleTy(getVMContext()), 2);
5680       break;
5681     case BuiltinType::BFloat16:
5682       ResType = llvm::ScalableVectorType::get(
5683           llvm::Type::getBFloatTy(getVMContext()), 8);
5684       break;
5685     }
5686     return ABIArgInfo::getDirect(ResType);
5687   }
5688 
5689   uint64_t Size = getContext().getTypeSize(Ty);
5690   // Android promotes <2 x i8> to i16, not i32
5691   if (isAndroid() && (Size <= 16)) {
5692     llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
5693     return ABIArgInfo::getDirect(ResType);
5694   }
5695   if (Size <= 32) {
5696     llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
5697     return ABIArgInfo::getDirect(ResType);
5698   }
5699   if (Size == 64) {
5700     auto *ResType =
5701         llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
5702     return ABIArgInfo::getDirect(ResType);
5703   }
5704   if (Size == 128) {
5705     auto *ResType =
5706         llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
5707     return ABIArgInfo::getDirect(ResType);
5708   }
5709   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5710 }
5711 
5712 ABIArgInfo
5713 AArch64ABIInfo::classifyArgumentType(QualType Ty, bool IsVariadic,
5714                                      unsigned CallingConvention) const {
5715   Ty = useFirstFieldIfTransparentUnion(Ty);
5716 
5717   // Handle illegal vector types here.
5718   if (isIllegalVectorType(Ty))
5719     return coerceIllegalVector(Ty);
5720 
5721   if (!isAggregateTypeForABI(Ty)) {
5722     // Treat an enum type as its underlying type.
5723     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5724       Ty = EnumTy->getDecl()->getIntegerType();
5725 
5726     if (const auto *EIT = Ty->getAs<BitIntType>())
5727       if (EIT->getNumBits() > 128)
5728         return getNaturalAlignIndirect(Ty);
5729 
5730     return (isPromotableIntegerTypeForABI(Ty) && isDarwinPCS()
5731                 ? ABIArgInfo::getExtend(Ty)
5732                 : ABIArgInfo::getDirect());
5733   }
5734 
5735   // Structures with either a non-trivial destructor or a non-trivial
5736   // copy constructor are always indirect.
5737   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
5738     return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
5739                                      CGCXXABI::RAA_DirectInMemory);
5740   }
5741 
5742   // Empty records are always ignored on Darwin, but actually passed in C++ mode
5743   // elsewhere for GNU compatibility.
5744   uint64_t Size = getContext().getTypeSize(Ty);
5745   bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
5746   if (IsEmpty || Size == 0) {
5747     if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
5748       return ABIArgInfo::getIgnore();
5749 
5750     // GNU C mode. The only argument that gets ignored is an empty one with size
5751     // 0.
5752     if (IsEmpty && Size == 0)
5753       return ABIArgInfo::getIgnore();
5754     return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5755   }
5756 
5757   // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
5758   const Type *Base = nullptr;
5759   uint64_t Members = 0;
5760   bool IsWin64 = Kind == Win64 || CallingConvention == llvm::CallingConv::Win64;
5761   bool IsWinVariadic = IsWin64 && IsVariadic;
5762   // In variadic functions on Windows, all composite types are treated alike,
5763   // no special handling of HFAs/HVAs.
5764   if (!IsWinVariadic && isHomogeneousAggregate(Ty, Base, Members)) {
5765     if (Kind != AArch64ABIInfo::AAPCS)
5766       return ABIArgInfo::getDirect(
5767           llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
5768 
5769     // For alignment adjusted HFAs, cap the argument alignment to 16, leave it
5770     // default otherwise.
5771     unsigned Align =
5772         getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
5773     unsigned BaseAlign = getContext().getTypeAlignInChars(Base).getQuantity();
5774     Align = (Align > BaseAlign && Align >= 16) ? 16 : 0;
5775     return ABIArgInfo::getDirect(
5776         llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members), 0,
5777         nullptr, true, Align);
5778   }
5779 
5780   // Aggregates <= 16 bytes are passed directly in registers or on the stack.
5781   if (Size <= 128) {
5782     // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5783     // same size and alignment.
5784     if (getTarget().isRenderScriptTarget()) {
5785       return coerceToIntArray(Ty, getContext(), getVMContext());
5786     }
5787     unsigned Alignment;
5788     if (Kind == AArch64ABIInfo::AAPCS) {
5789       Alignment = getContext().getTypeUnadjustedAlign(Ty);
5790       Alignment = Alignment < 128 ? 64 : 128;
5791     } else {
5792       Alignment = std::max(getContext().getTypeAlign(Ty),
5793                            (unsigned)getTarget().getPointerWidth(0));
5794     }
5795     Size = llvm::alignTo(Size, Alignment);
5796 
5797     // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5798     // For aggregates with 16-byte alignment, we use i128.
5799     llvm::Type *BaseTy = llvm::Type::getIntNTy(getVMContext(), Alignment);
5800     return ABIArgInfo::getDirect(
5801         Size == Alignment ? BaseTy
5802                           : llvm::ArrayType::get(BaseTy, Size / Alignment));
5803   }
5804 
5805   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5806 }
5807 
5808 ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy,
5809                                               bool IsVariadic) const {
5810   if (RetTy->isVoidType())
5811     return ABIArgInfo::getIgnore();
5812 
5813   if (const auto *VT = RetTy->getAs<VectorType>()) {
5814     if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector ||
5815         VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
5816       return coerceIllegalVector(RetTy);
5817   }
5818 
5819   // Large vector types should be returned via memory.
5820   if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
5821     return getNaturalAlignIndirect(RetTy);
5822 
5823   if (!isAggregateTypeForABI(RetTy)) {
5824     // Treat an enum type as its underlying type.
5825     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5826       RetTy = EnumTy->getDecl()->getIntegerType();
5827 
5828     if (const auto *EIT = RetTy->getAs<BitIntType>())
5829       if (EIT->getNumBits() > 128)
5830         return getNaturalAlignIndirect(RetTy);
5831 
5832     return (isPromotableIntegerTypeForABI(RetTy) && isDarwinPCS()
5833                 ? ABIArgInfo::getExtend(RetTy)
5834                 : ABIArgInfo::getDirect());
5835   }
5836 
5837   uint64_t Size = getContext().getTypeSize(RetTy);
5838   if (isEmptyRecord(getContext(), RetTy, true) || Size == 0)
5839     return ABIArgInfo::getIgnore();
5840 
5841   const Type *Base = nullptr;
5842   uint64_t Members = 0;
5843   if (isHomogeneousAggregate(RetTy, Base, Members) &&
5844       !(getTarget().getTriple().getArch() == llvm::Triple::aarch64_32 &&
5845         IsVariadic))
5846     // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
5847     return ABIArgInfo::getDirect();
5848 
5849   // Aggregates <= 16 bytes are returned directly in registers or on the stack.
5850   if (Size <= 128) {
5851     // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5852     // same size and alignment.
5853     if (getTarget().isRenderScriptTarget()) {
5854       return coerceToIntArray(RetTy, getContext(), getVMContext());
5855     }
5856 
5857     if (Size <= 64 && getDataLayout().isLittleEndian()) {
5858       // Composite types are returned in lower bits of a 64-bit register for LE,
5859       // and in higher bits for BE. However, integer types are always returned
5860       // in lower bits for both LE and BE, and they are not rounded up to
5861       // 64-bits. We can skip rounding up of composite types for LE, but not for
5862       // BE, otherwise composite types will be indistinguishable from integer
5863       // types.
5864       return ABIArgInfo::getDirect(
5865           llvm::IntegerType::get(getVMContext(), Size));
5866     }
5867 
5868     unsigned Alignment = getContext().getTypeAlign(RetTy);
5869     Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
5870 
5871     // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5872     // For aggregates with 16-byte alignment, we use i128.
5873     if (Alignment < 128 && Size == 128) {
5874       llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5875       return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5876     }
5877     return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5878   }
5879 
5880   return getNaturalAlignIndirect(RetTy);
5881 }
5882 
5883 /// isIllegalVectorType - check whether the vector type is legal for AArch64.
5884 bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
5885   if (const VectorType *VT = Ty->getAs<VectorType>()) {
5886     // Check whether VT is a fixed-length SVE vector. These types are
5887     // represented as scalable vectors in function args/return and must be
5888     // coerced from fixed vectors.
5889     if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector ||
5890         VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
5891       return true;
5892 
5893     // Check whether VT is legal.
5894     unsigned NumElements = VT->getNumElements();
5895     uint64_t Size = getContext().getTypeSize(VT);
5896     // NumElements should be power of 2.
5897     if (!llvm::isPowerOf2_32(NumElements))
5898       return true;
5899 
5900     // arm64_32 has to be compatible with the ARM logic here, which allows huge
5901     // vectors for some reason.
5902     llvm::Triple Triple = getTarget().getTriple();
5903     if (Triple.getArch() == llvm::Triple::aarch64_32 &&
5904         Triple.isOSBinFormatMachO())
5905       return Size <= 32;
5906 
5907     return Size != 64 && (Size != 128 || NumElements == 1);
5908   }
5909   return false;
5910 }
5911 
5912 bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize,
5913                                                llvm::Type *eltTy,
5914                                                unsigned elts) const {
5915   if (!llvm::isPowerOf2_32(elts))
5916     return false;
5917   if (totalSize.getQuantity() != 8 &&
5918       (totalSize.getQuantity() != 16 || elts == 1))
5919     return false;
5920   return true;
5921 }
5922 
5923 bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5924   // Homogeneous aggregates for AAPCS64 must have base types of a floating
5925   // point type or a short-vector type. This is the same as the 32-bit ABI,
5926   // but with the difference that any floating-point type is allowed,
5927   // including __fp16.
5928   if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5929     if (BT->isFloatingPoint())
5930       return true;
5931   } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5932     unsigned VecSize = getContext().getTypeSize(VT);
5933     if (VecSize == 64 || VecSize == 128)
5934       return true;
5935   }
5936   return false;
5937 }
5938 
5939 bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5940                                                        uint64_t Members) const {
5941   return Members <= 4;
5942 }
5943 
5944 Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
5945                                        CodeGenFunction &CGF) const {
5946   ABIArgInfo AI = classifyArgumentType(Ty, /*IsVariadic=*/true,
5947                                        CGF.CurFnInfo->getCallingConvention());
5948   bool IsIndirect = AI.isIndirect();
5949 
5950   llvm::Type *BaseTy = CGF.ConvertType(Ty);
5951   if (IsIndirect)
5952     BaseTy = llvm::PointerType::getUnqual(BaseTy);
5953   else if (AI.getCoerceToType())
5954     BaseTy = AI.getCoerceToType();
5955 
5956   unsigned NumRegs = 1;
5957   if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
5958     BaseTy = ArrTy->getElementType();
5959     NumRegs = ArrTy->getNumElements();
5960   }
5961   bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
5962 
5963   // The AArch64 va_list type and handling is specified in the Procedure Call
5964   // Standard, section B.4:
5965   //
5966   // struct {
5967   //   void *__stack;
5968   //   void *__gr_top;
5969   //   void *__vr_top;
5970   //   int __gr_offs;
5971   //   int __vr_offs;
5972   // };
5973 
5974   llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
5975   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5976   llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
5977   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5978 
5979   CharUnits TySize = getContext().getTypeSizeInChars(Ty);
5980   CharUnits TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty);
5981 
5982   Address reg_offs_p = Address::invalid();
5983   llvm::Value *reg_offs = nullptr;
5984   int reg_top_index;
5985   int RegSize = IsIndirect ? 8 : TySize.getQuantity();
5986   if (!IsFPR) {
5987     // 3 is the field number of __gr_offs
5988     reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
5989     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
5990     reg_top_index = 1; // field number for __gr_top
5991     RegSize = llvm::alignTo(RegSize, 8);
5992   } else {
5993     // 4 is the field number of __vr_offs.
5994     reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
5995     reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
5996     reg_top_index = 2; // field number for __vr_top
5997     RegSize = 16 * NumRegs;
5998   }
5999 
6000   //=======================================
6001   // Find out where argument was passed
6002   //=======================================
6003 
6004   // If reg_offs >= 0 we're already using the stack for this type of
6005   // argument. We don't want to keep updating reg_offs (in case it overflows,
6006   // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
6007   // whatever they get).
6008   llvm::Value *UsingStack = nullptr;
6009   UsingStack = CGF.Builder.CreateICmpSGE(
6010       reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
6011 
6012   CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
6013 
6014   // Otherwise, at least some kind of argument could go in these registers, the
6015   // question is whether this particular type is too big.
6016   CGF.EmitBlock(MaybeRegBlock);
6017 
6018   // Integer arguments may need to correct register alignment (for example a
6019   // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
6020   // align __gr_offs to calculate the potential address.
6021   if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
6022     int Align = TyAlign.getQuantity();
6023 
6024     reg_offs = CGF.Builder.CreateAdd(
6025         reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
6026         "align_regoffs");
6027     reg_offs = CGF.Builder.CreateAnd(
6028         reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
6029         "aligned_regoffs");
6030   }
6031 
6032   // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
6033   // The fact that this is done unconditionally reflects the fact that
6034   // allocating an argument to the stack also uses up all the remaining
6035   // registers of the appropriate kind.
6036   llvm::Value *NewOffset = nullptr;
6037   NewOffset = CGF.Builder.CreateAdd(
6038       reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
6039   CGF.Builder.CreateStore(NewOffset, reg_offs_p);
6040 
6041   // Now we're in a position to decide whether this argument really was in
6042   // registers or not.
6043   llvm::Value *InRegs = nullptr;
6044   InRegs = CGF.Builder.CreateICmpSLE(
6045       NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
6046 
6047   CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
6048 
6049   //=======================================
6050   // Argument was in registers
6051   //=======================================
6052 
6053   // Now we emit the code for if the argument was originally passed in
6054   // registers. First start the appropriate block:
6055   CGF.EmitBlock(InRegBlock);
6056 
6057   llvm::Value *reg_top = nullptr;
6058   Address reg_top_p =
6059       CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
6060   reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
6061   Address BaseAddr(CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, reg_top, reg_offs),
6062                    CharUnits::fromQuantity(IsFPR ? 16 : 8));
6063   Address RegAddr = Address::invalid();
6064   llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
6065 
6066   if (IsIndirect) {
6067     // If it's been passed indirectly (actually a struct), whatever we find from
6068     // stored registers or on the stack will actually be a struct **.
6069     MemTy = llvm::PointerType::getUnqual(MemTy);
6070   }
6071 
6072   const Type *Base = nullptr;
6073   uint64_t NumMembers = 0;
6074   bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
6075   if (IsHFA && NumMembers > 1) {
6076     // Homogeneous aggregates passed in registers will have their elements split
6077     // and stored 16-bytes apart regardless of size (they're notionally in qN,
6078     // qN+1, ...). We reload and store into a temporary local variable
6079     // contiguously.
6080     assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
6081     auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
6082     llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
6083     llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
6084     Address Tmp = CGF.CreateTempAlloca(HFATy,
6085                                        std::max(TyAlign, BaseTyInfo.Align));
6086 
6087     // On big-endian platforms, the value will be right-aligned in its slot.
6088     int Offset = 0;
6089     if (CGF.CGM.getDataLayout().isBigEndian() &&
6090         BaseTyInfo.Width.getQuantity() < 16)
6091       Offset = 16 - BaseTyInfo.Width.getQuantity();
6092 
6093     for (unsigned i = 0; i < NumMembers; ++i) {
6094       CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
6095       Address LoadAddr =
6096         CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
6097       LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
6098 
6099       Address StoreAddr = CGF.Builder.CreateConstArrayGEP(Tmp, i);
6100 
6101       llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
6102       CGF.Builder.CreateStore(Elem, StoreAddr);
6103     }
6104 
6105     RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
6106   } else {
6107     // Otherwise the object is contiguous in memory.
6108 
6109     // It might be right-aligned in its slot.
6110     CharUnits SlotSize = BaseAddr.getAlignment();
6111     if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
6112         (IsHFA || !isAggregateTypeForABI(Ty)) &&
6113         TySize < SlotSize) {
6114       CharUnits Offset = SlotSize - TySize;
6115       BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
6116     }
6117 
6118     RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
6119   }
6120 
6121   CGF.EmitBranch(ContBlock);
6122 
6123   //=======================================
6124   // Argument was on the stack
6125   //=======================================
6126   CGF.EmitBlock(OnStackBlock);
6127 
6128   Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
6129   llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
6130 
6131   // Again, stack arguments may need realignment. In this case both integer and
6132   // floating-point ones might be affected.
6133   if (!IsIndirect && TyAlign.getQuantity() > 8) {
6134     int Align = TyAlign.getQuantity();
6135 
6136     OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
6137 
6138     OnStackPtr = CGF.Builder.CreateAdd(
6139         OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
6140         "align_stack");
6141     OnStackPtr = CGF.Builder.CreateAnd(
6142         OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
6143         "align_stack");
6144 
6145     OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
6146   }
6147   Address OnStackAddr(OnStackPtr,
6148                       std::max(CharUnits::fromQuantity(8), TyAlign));
6149 
6150   // All stack slots are multiples of 8 bytes.
6151   CharUnits StackSlotSize = CharUnits::fromQuantity(8);
6152   CharUnits StackSize;
6153   if (IsIndirect)
6154     StackSize = StackSlotSize;
6155   else
6156     StackSize = TySize.alignTo(StackSlotSize);
6157 
6158   llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
6159   llvm::Value *NewStack = CGF.Builder.CreateInBoundsGEP(
6160       CGF.Int8Ty, OnStackPtr, StackSizeC, "new_stack");
6161 
6162   // Write the new value of __stack for the next call to va_arg
6163   CGF.Builder.CreateStore(NewStack, stack_p);
6164 
6165   if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
6166       TySize < StackSlotSize) {
6167     CharUnits Offset = StackSlotSize - TySize;
6168     OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
6169   }
6170 
6171   OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
6172 
6173   CGF.EmitBranch(ContBlock);
6174 
6175   //=======================================
6176   // Tidy up
6177   //=======================================
6178   CGF.EmitBlock(ContBlock);
6179 
6180   Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
6181                                  OnStackAddr, OnStackBlock, "vaargs.addr");
6182 
6183   if (IsIndirect)
6184     return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
6185                    TyAlign);
6186 
6187   return ResAddr;
6188 }
6189 
6190 Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
6191                                         CodeGenFunction &CGF) const {
6192   // The backend's lowering doesn't support va_arg for aggregates or
6193   // illegal vector types.  Lower VAArg here for these cases and use
6194   // the LLVM va_arg instruction for everything else.
6195   if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
6196     return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
6197 
6198   uint64_t PointerSize = getTarget().getPointerWidth(0) / 8;
6199   CharUnits SlotSize = CharUnits::fromQuantity(PointerSize);
6200 
6201   // Empty records are ignored for parameter passing purposes.
6202   if (isEmptyRecord(getContext(), Ty, true)) {
6203     Address Addr(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(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
6992     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6993     return Addr;
6994   }
6995 
6996   CharUnits TySize = getContext().getTypeSizeInChars(Ty);
6997   CharUnits TyAlignForABI = getContext().getTypeUnadjustedAlignInChars(Ty);
6998 
6999   // Use indirect if size of the illegal vector is bigger than 16 bytes.
7000   bool IsIndirect = false;
7001   const Type *Base = nullptr;
7002   uint64_t Members = 0;
7003   if (TySize > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
7004     IsIndirect = true;
7005 
7006   // ARMv7k passes structs bigger than 16 bytes indirectly, in space
7007   // allocated by the caller.
7008   } else if (TySize > CharUnits::fromQuantity(16) &&
7009              getABIKind() == ARMABIInfo::AAPCS16_VFP &&
7010              !isHomogeneousAggregate(Ty, Base, Members)) {
7011     IsIndirect = true;
7012 
7013   // Otherwise, bound the type's ABI alignment.
7014   // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
7015   // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
7016   // Our callers should be prepared to handle an under-aligned address.
7017   } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
7018              getABIKind() == ARMABIInfo::AAPCS) {
7019     TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
7020     TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
7021   } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
7022     // ARMv7k allows type alignment up to 16 bytes.
7023     TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
7024     TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
7025   } else {
7026     TyAlignForABI = CharUnits::fromQuantity(4);
7027   }
7028 
7029   TypeInfoChars TyInfo(TySize, TyAlignForABI, AlignRequirementKind::None);
7030   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
7031                           SlotSize, /*AllowHigherAlign*/ true);
7032 }
7033 
7034 //===----------------------------------------------------------------------===//
7035 // NVPTX ABI Implementation
7036 //===----------------------------------------------------------------------===//
7037 
7038 namespace {
7039 
7040 class NVPTXTargetCodeGenInfo;
7041 
7042 class NVPTXABIInfo : public ABIInfo {
7043   NVPTXTargetCodeGenInfo &CGInfo;
7044 
7045 public:
7046   NVPTXABIInfo(CodeGenTypes &CGT, NVPTXTargetCodeGenInfo &Info)
7047       : ABIInfo(CGT), CGInfo(Info) {}
7048 
7049   ABIArgInfo classifyReturnType(QualType RetTy) const;
7050   ABIArgInfo classifyArgumentType(QualType Ty) const;
7051 
7052   void computeInfo(CGFunctionInfo &FI) const override;
7053   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7054                     QualType Ty) const override;
7055   bool isUnsupportedType(QualType T) const;
7056   ABIArgInfo coerceToIntArrayWithLimit(QualType Ty, unsigned MaxSize) const;
7057 };
7058 
7059 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
7060 public:
7061   NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
7062       : TargetCodeGenInfo(std::make_unique<NVPTXABIInfo>(CGT, *this)) {}
7063 
7064   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7065                            CodeGen::CodeGenModule &M) const override;
7066   bool shouldEmitStaticExternCAliases() const override;
7067 
7068   llvm::Type *getCUDADeviceBuiltinSurfaceDeviceType() const override {
7069     // On the device side, surface reference is represented as an object handle
7070     // in 64-bit integer.
7071     return llvm::Type::getInt64Ty(getABIInfo().getVMContext());
7072   }
7073 
7074   llvm::Type *getCUDADeviceBuiltinTextureDeviceType() const override {
7075     // On the device side, texture reference is represented as an object handle
7076     // in 64-bit integer.
7077     return llvm::Type::getInt64Ty(getABIInfo().getVMContext());
7078   }
7079 
7080   bool emitCUDADeviceBuiltinSurfaceDeviceCopy(CodeGenFunction &CGF, LValue Dst,
7081                                               LValue Src) const override {
7082     emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src);
7083     return true;
7084   }
7085 
7086   bool emitCUDADeviceBuiltinTextureDeviceCopy(CodeGenFunction &CGF, LValue Dst,
7087                                               LValue Src) const override {
7088     emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src);
7089     return true;
7090   }
7091 
7092 private:
7093   // Adds a NamedMDNode with GV, Name, and Operand as operands, and adds the
7094   // resulting MDNode to the nvvm.annotations MDNode.
7095   static void addNVVMMetadata(llvm::GlobalValue *GV, StringRef Name,
7096                               int Operand);
7097 
7098   static void emitBuiltinSurfTexDeviceCopy(CodeGenFunction &CGF, LValue Dst,
7099                                            LValue Src) {
7100     llvm::Value *Handle = nullptr;
7101     llvm::Constant *C =
7102         llvm::dyn_cast<llvm::Constant>(Src.getAddress(CGF).getPointer());
7103     // Lookup `addrspacecast` through the constant pointer if any.
7104     if (auto *ASC = llvm::dyn_cast_or_null<llvm::AddrSpaceCastOperator>(C))
7105       C = llvm::cast<llvm::Constant>(ASC->getPointerOperand());
7106     if (auto *GV = llvm::dyn_cast_or_null<llvm::GlobalVariable>(C)) {
7107       // Load the handle from the specific global variable using
7108       // `nvvm.texsurf.handle.internal` intrinsic.
7109       Handle = CGF.EmitRuntimeCall(
7110           CGF.CGM.getIntrinsic(llvm::Intrinsic::nvvm_texsurf_handle_internal,
7111                                {GV->getType()}),
7112           {GV}, "texsurf_handle");
7113     } else
7114       Handle = CGF.EmitLoadOfScalar(Src, SourceLocation());
7115     CGF.EmitStoreOfScalar(Handle, Dst);
7116   }
7117 };
7118 
7119 /// Checks if the type is unsupported directly by the current target.
7120 bool NVPTXABIInfo::isUnsupportedType(QualType T) const {
7121   ASTContext &Context = getContext();
7122   if (!Context.getTargetInfo().hasFloat16Type() && T->isFloat16Type())
7123     return true;
7124   if (!Context.getTargetInfo().hasFloat128Type() &&
7125       (T->isFloat128Type() ||
7126        (T->isRealFloatingType() && Context.getTypeSize(T) == 128)))
7127     return true;
7128   if (const auto *EIT = T->getAs<BitIntType>())
7129     return EIT->getNumBits() >
7130            (Context.getTargetInfo().hasInt128Type() ? 128U : 64U);
7131   if (!Context.getTargetInfo().hasInt128Type() && T->isIntegerType() &&
7132       Context.getTypeSize(T) > 64U)
7133     return true;
7134   if (const auto *AT = T->getAsArrayTypeUnsafe())
7135     return isUnsupportedType(AT->getElementType());
7136   const auto *RT = T->getAs<RecordType>();
7137   if (!RT)
7138     return false;
7139   const RecordDecl *RD = RT->getDecl();
7140 
7141   // If this is a C++ record, check the bases first.
7142   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7143     for (const CXXBaseSpecifier &I : CXXRD->bases())
7144       if (isUnsupportedType(I.getType()))
7145         return true;
7146 
7147   for (const FieldDecl *I : RD->fields())
7148     if (isUnsupportedType(I->getType()))
7149       return true;
7150   return false;
7151 }
7152 
7153 /// Coerce the given type into an array with maximum allowed size of elements.
7154 ABIArgInfo NVPTXABIInfo::coerceToIntArrayWithLimit(QualType Ty,
7155                                                    unsigned MaxSize) const {
7156   // Alignment and Size are measured in bits.
7157   const uint64_t Size = getContext().getTypeSize(Ty);
7158   const uint64_t Alignment = getContext().getTypeAlign(Ty);
7159   const unsigned Div = std::min<unsigned>(MaxSize, Alignment);
7160   llvm::Type *IntType = llvm::Type::getIntNTy(getVMContext(), Div);
7161   const uint64_t NumElements = (Size + Div - 1) / Div;
7162   return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
7163 }
7164 
7165 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
7166   if (RetTy->isVoidType())
7167     return ABIArgInfo::getIgnore();
7168 
7169   if (getContext().getLangOpts().OpenMP &&
7170       getContext().getLangOpts().OpenMPIsDevice && isUnsupportedType(RetTy))
7171     return coerceToIntArrayWithLimit(RetTy, 64);
7172 
7173   // note: this is different from default ABI
7174   if (!RetTy->isScalarType())
7175     return ABIArgInfo::getDirect();
7176 
7177   // Treat an enum type as its underlying type.
7178   if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7179     RetTy = EnumTy->getDecl()->getIntegerType();
7180 
7181   return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
7182                                                : ABIArgInfo::getDirect());
7183 }
7184 
7185 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
7186   // Treat an enum type as its underlying type.
7187   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7188     Ty = EnumTy->getDecl()->getIntegerType();
7189 
7190   // Return aggregates type as indirect by value
7191   if (isAggregateTypeForABI(Ty)) {
7192     // Under CUDA device compilation, tex/surf builtin types are replaced with
7193     // object types and passed directly.
7194     if (getContext().getLangOpts().CUDAIsDevice) {
7195       if (Ty->isCUDADeviceBuiltinSurfaceType())
7196         return ABIArgInfo::getDirect(
7197             CGInfo.getCUDADeviceBuiltinSurfaceDeviceType());
7198       if (Ty->isCUDADeviceBuiltinTextureType())
7199         return ABIArgInfo::getDirect(
7200             CGInfo.getCUDADeviceBuiltinTextureDeviceType());
7201     }
7202     return getNaturalAlignIndirect(Ty, /* byval */ true);
7203   }
7204 
7205   if (const auto *EIT = Ty->getAs<BitIntType>()) {
7206     if ((EIT->getNumBits() > 128) ||
7207         (!getContext().getTargetInfo().hasInt128Type() &&
7208          EIT->getNumBits() > 64))
7209       return getNaturalAlignIndirect(Ty, /* byval */ true);
7210   }
7211 
7212   return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
7213                                             : ABIArgInfo::getDirect());
7214 }
7215 
7216 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
7217   if (!getCXXABI().classifyReturnType(FI))
7218     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7219   for (auto &I : FI.arguments())
7220     I.info = classifyArgumentType(I.type);
7221 
7222   // Always honor user-specified calling convention.
7223   if (FI.getCallingConvention() != llvm::CallingConv::C)
7224     return;
7225 
7226   FI.setEffectiveCallingConvention(getRuntimeCC());
7227 }
7228 
7229 Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7230                                 QualType Ty) const {
7231   llvm_unreachable("NVPTX does not support varargs");
7232 }
7233 
7234 void NVPTXTargetCodeGenInfo::setTargetAttributes(
7235     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7236   if (GV->isDeclaration())
7237     return;
7238   const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
7239   if (VD) {
7240     if (M.getLangOpts().CUDA) {
7241       if (VD->getType()->isCUDADeviceBuiltinSurfaceType())
7242         addNVVMMetadata(GV, "surface", 1);
7243       else if (VD->getType()->isCUDADeviceBuiltinTextureType())
7244         addNVVMMetadata(GV, "texture", 1);
7245       return;
7246     }
7247   }
7248 
7249   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7250   if (!FD) return;
7251 
7252   llvm::Function *F = cast<llvm::Function>(GV);
7253 
7254   // Perform special handling in OpenCL mode
7255   if (M.getLangOpts().OpenCL) {
7256     // Use OpenCL function attributes to check for kernel functions
7257     // By default, all functions are device functions
7258     if (FD->hasAttr<OpenCLKernelAttr>()) {
7259       // OpenCL __kernel functions get kernel metadata
7260       // Create !{<func-ref>, metadata !"kernel", i32 1} node
7261       addNVVMMetadata(F, "kernel", 1);
7262       // And kernel functions are not subject to inlining
7263       F->addFnAttr(llvm::Attribute::NoInline);
7264     }
7265   }
7266 
7267   // Perform special handling in CUDA mode.
7268   if (M.getLangOpts().CUDA) {
7269     // CUDA __global__ functions get a kernel metadata entry.  Since
7270     // __global__ functions cannot be called from the device, we do not
7271     // need to set the noinline attribute.
7272     if (FD->hasAttr<CUDAGlobalAttr>()) {
7273       // Create !{<func-ref>, metadata !"kernel", i32 1} node
7274       addNVVMMetadata(F, "kernel", 1);
7275     }
7276     if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
7277       // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
7278       llvm::APSInt MaxThreads(32);
7279       MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
7280       if (MaxThreads > 0)
7281         addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
7282 
7283       // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
7284       // not specified in __launch_bounds__ or if the user specified a 0 value,
7285       // we don't have to add a PTX directive.
7286       if (Attr->getMinBlocks()) {
7287         llvm::APSInt MinBlocks(32);
7288         MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
7289         if (MinBlocks > 0)
7290           // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
7291           addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
7292       }
7293     }
7294   }
7295 }
7296 
7297 void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::GlobalValue *GV,
7298                                              StringRef Name, int Operand) {
7299   llvm::Module *M = GV->getParent();
7300   llvm::LLVMContext &Ctx = M->getContext();
7301 
7302   // Get "nvvm.annotations" metadata node
7303   llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
7304 
7305   llvm::Metadata *MDVals[] = {
7306       llvm::ConstantAsMetadata::get(GV), llvm::MDString::get(Ctx, Name),
7307       llvm::ConstantAsMetadata::get(
7308           llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
7309   // Append metadata to nvvm.annotations
7310   MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
7311 }
7312 
7313 bool NVPTXTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
7314   return false;
7315 }
7316 }
7317 
7318 //===----------------------------------------------------------------------===//
7319 // SystemZ ABI Implementation
7320 //===----------------------------------------------------------------------===//
7321 
7322 namespace {
7323 
7324 class SystemZABIInfo : public SwiftABIInfo {
7325   bool HasVector;
7326   bool IsSoftFloatABI;
7327 
7328 public:
7329   SystemZABIInfo(CodeGenTypes &CGT, bool HV, bool SF)
7330     : SwiftABIInfo(CGT), HasVector(HV), IsSoftFloatABI(SF) {}
7331 
7332   bool isPromotableIntegerTypeForABI(QualType Ty) const;
7333   bool isCompoundType(QualType Ty) const;
7334   bool isVectorArgumentType(QualType Ty) const;
7335   bool isFPArgumentType(QualType Ty) const;
7336   QualType GetSingleElementType(QualType Ty) const;
7337 
7338   ABIArgInfo classifyReturnType(QualType RetTy) const;
7339   ABIArgInfo classifyArgumentType(QualType ArgTy) const;
7340 
7341   void computeInfo(CGFunctionInfo &FI) const override {
7342     if (!getCXXABI().classifyReturnType(FI))
7343       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7344     for (auto &I : FI.arguments())
7345       I.info = classifyArgumentType(I.type);
7346   }
7347 
7348   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7349                     QualType Ty) const override;
7350 
7351   bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
7352                                     bool asReturnValue) const override {
7353     return occupiesMoreThan(CGT, scalars, /*total*/ 4);
7354   }
7355   bool isSwiftErrorInRegister() const override {
7356     return false;
7357   }
7358 };
7359 
7360 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
7361 public:
7362   SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector, bool SoftFloatABI)
7363       : TargetCodeGenInfo(
7364             std::make_unique<SystemZABIInfo>(CGT, HasVector, SoftFloatABI)) {}
7365 
7366   llvm::Value *testFPKind(llvm::Value *V, unsigned BuiltinID,
7367                           CGBuilderTy &Builder,
7368                           CodeGenModule &CGM) const override {
7369     assert(V->getType()->isFloatingPointTy() && "V should have an FP type.");
7370     // Only use TDC in constrained FP mode.
7371     if (!Builder.getIsFPConstrained())
7372       return nullptr;
7373 
7374     llvm::Type *Ty = V->getType();
7375     if (Ty->isFloatTy() || Ty->isDoubleTy() || Ty->isFP128Ty()) {
7376       llvm::Module &M = CGM.getModule();
7377       auto &Ctx = M.getContext();
7378       llvm::Function *TDCFunc =
7379           llvm::Intrinsic::getDeclaration(&M, llvm::Intrinsic::s390_tdc, Ty);
7380       unsigned TDCBits = 0;
7381       switch (BuiltinID) {
7382       case Builtin::BI__builtin_isnan:
7383         TDCBits = 0xf;
7384         break;
7385       case Builtin::BIfinite:
7386       case Builtin::BI__finite:
7387       case Builtin::BIfinitef:
7388       case Builtin::BI__finitef:
7389       case Builtin::BIfinitel:
7390       case Builtin::BI__finitel:
7391       case Builtin::BI__builtin_isfinite:
7392         TDCBits = 0xfc0;
7393         break;
7394       case Builtin::BI__builtin_isinf:
7395         TDCBits = 0x30;
7396         break;
7397       default:
7398         break;
7399       }
7400       if (TDCBits)
7401         return Builder.CreateCall(
7402             TDCFunc,
7403             {V, llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), TDCBits)});
7404     }
7405     return nullptr;
7406   }
7407 };
7408 }
7409 
7410 bool SystemZABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const {
7411   // Treat an enum type as its underlying type.
7412   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7413     Ty = EnumTy->getDecl()->getIntegerType();
7414 
7415   // Promotable integer types are required to be promoted by the ABI.
7416   if (ABIInfo::isPromotableIntegerTypeForABI(Ty))
7417     return true;
7418 
7419   if (const auto *EIT = Ty->getAs<BitIntType>())
7420     if (EIT->getNumBits() < 64)
7421       return true;
7422 
7423   // 32-bit values must also be promoted.
7424   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
7425     switch (BT->getKind()) {
7426     case BuiltinType::Int:
7427     case BuiltinType::UInt:
7428       return true;
7429     default:
7430       return false;
7431     }
7432   return false;
7433 }
7434 
7435 bool SystemZABIInfo::isCompoundType(QualType Ty) const {
7436   return (Ty->isAnyComplexType() ||
7437           Ty->isVectorType() ||
7438           isAggregateTypeForABI(Ty));
7439 }
7440 
7441 bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
7442   return (HasVector &&
7443           Ty->isVectorType() &&
7444           getContext().getTypeSize(Ty) <= 128);
7445 }
7446 
7447 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
7448   if (IsSoftFloatABI)
7449     return false;
7450 
7451   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
7452     switch (BT->getKind()) {
7453     case BuiltinType::Float:
7454     case BuiltinType::Double:
7455       return true;
7456     default:
7457       return false;
7458     }
7459 
7460   return false;
7461 }
7462 
7463 QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
7464   const RecordType *RT = Ty->getAs<RecordType>();
7465 
7466   if (RT && RT->isStructureOrClassType()) {
7467     const RecordDecl *RD = RT->getDecl();
7468     QualType Found;
7469 
7470     // If this is a C++ record, check the bases first.
7471     if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7472       for (const auto &I : CXXRD->bases()) {
7473         QualType Base = I.getType();
7474 
7475         // Empty bases don't affect things either way.
7476         if (isEmptyRecord(getContext(), Base, true))
7477           continue;
7478 
7479         if (!Found.isNull())
7480           return Ty;
7481         Found = GetSingleElementType(Base);
7482       }
7483 
7484     // Check the fields.
7485     for (const auto *FD : RD->fields()) {
7486       // For compatibility with GCC, ignore empty bitfields in C++ mode.
7487       // Unlike isSingleElementStruct(), empty structure and array fields
7488       // do count.  So do anonymous bitfields that aren't zero-sized.
7489       if (getContext().getLangOpts().CPlusPlus &&
7490           FD->isZeroLengthBitField(getContext()))
7491         continue;
7492       // Like isSingleElementStruct(), ignore C++20 empty data members.
7493       if (FD->hasAttr<NoUniqueAddressAttr>() &&
7494           isEmptyRecord(getContext(), FD->getType(), true))
7495         continue;
7496 
7497       // Unlike isSingleElementStruct(), arrays do not count.
7498       // Nested structures still do though.
7499       if (!Found.isNull())
7500         return Ty;
7501       Found = GetSingleElementType(FD->getType());
7502     }
7503 
7504     // Unlike isSingleElementStruct(), trailing padding is allowed.
7505     // An 8-byte aligned struct s { float f; } is passed as a double.
7506     if (!Found.isNull())
7507       return Found;
7508   }
7509 
7510   return Ty;
7511 }
7512 
7513 Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7514                                   QualType Ty) const {
7515   // Assume that va_list type is correct; should be pointer to LLVM type:
7516   // struct {
7517   //   i64 __gpr;
7518   //   i64 __fpr;
7519   //   i8 *__overflow_arg_area;
7520   //   i8 *__reg_save_area;
7521   // };
7522 
7523   // Every non-vector argument occupies 8 bytes and is passed by preference
7524   // in either GPRs or FPRs.  Vector arguments occupy 8 or 16 bytes and are
7525   // always passed on the stack.
7526   Ty = getContext().getCanonicalType(Ty);
7527   auto TyInfo = getContext().getTypeInfoInChars(Ty);
7528   llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
7529   llvm::Type *DirectTy = ArgTy;
7530   ABIArgInfo AI = classifyArgumentType(Ty);
7531   bool IsIndirect = AI.isIndirect();
7532   bool InFPRs = false;
7533   bool IsVector = false;
7534   CharUnits UnpaddedSize;
7535   CharUnits DirectAlign;
7536   if (IsIndirect) {
7537     DirectTy = llvm::PointerType::getUnqual(DirectTy);
7538     UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
7539   } else {
7540     if (AI.getCoerceToType())
7541       ArgTy = AI.getCoerceToType();
7542     InFPRs = (!IsSoftFloatABI && (ArgTy->isFloatTy() || ArgTy->isDoubleTy()));
7543     IsVector = ArgTy->isVectorTy();
7544     UnpaddedSize = TyInfo.Width;
7545     DirectAlign = TyInfo.Align;
7546   }
7547   CharUnits PaddedSize = CharUnits::fromQuantity(8);
7548   if (IsVector && UnpaddedSize > PaddedSize)
7549     PaddedSize = CharUnits::fromQuantity(16);
7550   assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
7551 
7552   CharUnits Padding = (PaddedSize - UnpaddedSize);
7553 
7554   llvm::Type *IndexTy = CGF.Int64Ty;
7555   llvm::Value *PaddedSizeV =
7556     llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
7557 
7558   if (IsVector) {
7559     // Work out the address of a vector argument on the stack.
7560     // Vector arguments are always passed in the high bits of a
7561     // single (8 byte) or double (16 byte) stack slot.
7562     Address OverflowArgAreaPtr =
7563         CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
7564     Address OverflowArgArea =
7565       Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
7566               TyInfo.Align);
7567     Address MemAddr =
7568       CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
7569 
7570     // Update overflow_arg_area_ptr pointer
7571     llvm::Value *NewOverflowArgArea =
7572       CGF.Builder.CreateGEP(OverflowArgArea.getElementType(),
7573                             OverflowArgArea.getPointer(), PaddedSizeV,
7574                             "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(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, RegOffset,
7624                                            "raw_reg_addr"),
7625                      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 =
7643     Address(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,
7661                                  MemAddr, InMemBlock, "va_arg.addr");
7662 
7663   if (IsIndirect)
7664     ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
7665                       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     LangAS AS = D->getType().getAddressSpace();
8308     if (isTargetAddressSpace(AS) && 1 <= toTargetAddressSpace(AS) &&
8309         toTargetAddressSpace(AS) <= 6 && !D->getType().isConstQualified())
8310       CGM.getDiags().Report(D->getLocation(),
8311                             diag::err_verify_nonconst_addrspace)
8312           << "__flash*";
8313     return TargetCodeGenInfo::getGlobalVarAddressSpace(CGM, D);
8314   }
8315 
8316   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8317                            CodeGen::CodeGenModule &CGM) const override {
8318     if (GV->isDeclaration())
8319       return;
8320     const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
8321     if (!FD) return;
8322     auto *Fn = cast<llvm::Function>(GV);
8323 
8324     if (FD->getAttr<AVRInterruptAttr>())
8325       Fn->addFnAttr("interrupt");
8326 
8327     if (FD->getAttr<AVRSignalAttr>())
8328       Fn->addFnAttr("signal");
8329   }
8330 };
8331 }
8332 
8333 //===----------------------------------------------------------------------===//
8334 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
8335 // Currently subclassed only to implement custom OpenCL C function attribute
8336 // handling.
8337 //===----------------------------------------------------------------------===//
8338 
8339 namespace {
8340 
8341 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
8342 public:
8343   TCETargetCodeGenInfo(CodeGenTypes &CGT)
8344     : DefaultTargetCodeGenInfo(CGT) {}
8345 
8346   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8347                            CodeGen::CodeGenModule &M) const override;
8348 };
8349 
8350 void TCETargetCodeGenInfo::setTargetAttributes(
8351     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
8352   if (GV->isDeclaration())
8353     return;
8354   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
8355   if (!FD) return;
8356 
8357   llvm::Function *F = cast<llvm::Function>(GV);
8358 
8359   if (M.getLangOpts().OpenCL) {
8360     if (FD->hasAttr<OpenCLKernelAttr>()) {
8361       // OpenCL C Kernel functions are not subject to inlining
8362       F->addFnAttr(llvm::Attribute::NoInline);
8363       const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
8364       if (Attr) {
8365         // Convert the reqd_work_group_size() attributes to metadata.
8366         llvm::LLVMContext &Context = F->getContext();
8367         llvm::NamedMDNode *OpenCLMetadata =
8368             M.getModule().getOrInsertNamedMetadata(
8369                 "opencl.kernel_wg_size_info");
8370 
8371         SmallVector<llvm::Metadata *, 5> Operands;
8372         Operands.push_back(llvm::ConstantAsMetadata::get(F));
8373 
8374         Operands.push_back(
8375             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8376                 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
8377         Operands.push_back(
8378             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8379                 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
8380         Operands.push_back(
8381             llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
8382                 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
8383 
8384         // Add a boolean constant operand for "required" (true) or "hint"
8385         // (false) for implementing the work_group_size_hint attr later.
8386         // Currently always true as the hint is not yet implemented.
8387         Operands.push_back(
8388             llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
8389         OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
8390       }
8391     }
8392   }
8393 }
8394 
8395 }
8396 
8397 //===----------------------------------------------------------------------===//
8398 // Hexagon ABI Implementation
8399 //===----------------------------------------------------------------------===//
8400 
8401 namespace {
8402 
8403 class HexagonABIInfo : public DefaultABIInfo {
8404 public:
8405   HexagonABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8406 
8407 private:
8408   ABIArgInfo classifyReturnType(QualType RetTy) const;
8409   ABIArgInfo classifyArgumentType(QualType RetTy) const;
8410   ABIArgInfo classifyArgumentType(QualType RetTy, unsigned *RegsLeft) const;
8411 
8412   void computeInfo(CGFunctionInfo &FI) const override;
8413 
8414   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8415                     QualType Ty) const override;
8416   Address EmitVAArgFromMemory(CodeGenFunction &CFG, Address VAListAddr,
8417                               QualType Ty) const;
8418   Address EmitVAArgForHexagon(CodeGenFunction &CFG, Address VAListAddr,
8419                               QualType Ty) const;
8420   Address EmitVAArgForHexagonLinux(CodeGenFunction &CFG, Address VAListAddr,
8421                                    QualType Ty) const;
8422 };
8423 
8424 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
8425 public:
8426   HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
8427       : TargetCodeGenInfo(std::make_unique<HexagonABIInfo>(CGT)) {}
8428 
8429   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
8430     return 29;
8431   }
8432 
8433   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8434                            CodeGen::CodeGenModule &GCM) const override {
8435     if (GV->isDeclaration())
8436       return;
8437     const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
8438     if (!FD)
8439       return;
8440   }
8441 };
8442 
8443 } // namespace
8444 
8445 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
8446   unsigned RegsLeft = 6;
8447   if (!getCXXABI().classifyReturnType(FI))
8448     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8449   for (auto &I : FI.arguments())
8450     I.info = classifyArgumentType(I.type, &RegsLeft);
8451 }
8452 
8453 static bool HexagonAdjustRegsLeft(uint64_t Size, unsigned *RegsLeft) {
8454   assert(Size <= 64 && "Not expecting to pass arguments larger than 64 bits"
8455                        " through registers");
8456 
8457   if (*RegsLeft == 0)
8458     return false;
8459 
8460   if (Size <= 32) {
8461     (*RegsLeft)--;
8462     return true;
8463   }
8464 
8465   if (2 <= (*RegsLeft & (~1U))) {
8466     *RegsLeft = (*RegsLeft & (~1U)) - 2;
8467     return true;
8468   }
8469 
8470   // Next available register was r5 but candidate was greater than 32-bits so it
8471   // has to go on the stack. However we still consume r5
8472   if (*RegsLeft == 1)
8473     *RegsLeft = 0;
8474 
8475   return false;
8476 }
8477 
8478 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty,
8479                                                 unsigned *RegsLeft) const {
8480   if (!isAggregateTypeForABI(Ty)) {
8481     // Treat an enum type as its underlying type.
8482     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
8483       Ty = EnumTy->getDecl()->getIntegerType();
8484 
8485     uint64_t Size = getContext().getTypeSize(Ty);
8486     if (Size <= 64)
8487       HexagonAdjustRegsLeft(Size, RegsLeft);
8488 
8489     if (Size > 64 && Ty->isBitIntType())
8490       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8491 
8492     return isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
8493                                              : ABIArgInfo::getDirect();
8494   }
8495 
8496   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
8497     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
8498 
8499   // Ignore empty records.
8500   if (isEmptyRecord(getContext(), Ty, true))
8501     return ABIArgInfo::getIgnore();
8502 
8503   uint64_t Size = getContext().getTypeSize(Ty);
8504   unsigned Align = getContext().getTypeAlign(Ty);
8505 
8506   if (Size > 64)
8507     return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8508 
8509   if (HexagonAdjustRegsLeft(Size, RegsLeft))
8510     Align = Size <= 32 ? 32 : 64;
8511   if (Size <= Align) {
8512     // Pass in the smallest viable integer type.
8513     if (!llvm::isPowerOf2_64(Size))
8514       Size = llvm::NextPowerOf2(Size);
8515     return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size));
8516   }
8517   return DefaultABIInfo::classifyArgumentType(Ty);
8518 }
8519 
8520 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
8521   if (RetTy->isVoidType())
8522     return ABIArgInfo::getIgnore();
8523 
8524   const TargetInfo &T = CGT.getTarget();
8525   uint64_t Size = getContext().getTypeSize(RetTy);
8526 
8527   if (RetTy->getAs<VectorType>()) {
8528     // HVX vectors are returned in vector registers or register pairs.
8529     if (T.hasFeature("hvx")) {
8530       assert(T.hasFeature("hvx-length64b") || T.hasFeature("hvx-length128b"));
8531       uint64_t VecSize = T.hasFeature("hvx-length64b") ? 64*8 : 128*8;
8532       if (Size == VecSize || Size == 2*VecSize)
8533         return ABIArgInfo::getDirectInReg();
8534     }
8535     // Large vector types should be returned via memory.
8536     if (Size > 64)
8537       return getNaturalAlignIndirect(RetTy);
8538   }
8539 
8540   if (!isAggregateTypeForABI(RetTy)) {
8541     // Treat an enum type as its underlying type.
8542     if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
8543       RetTy = EnumTy->getDecl()->getIntegerType();
8544 
8545     if (Size > 64 && RetTy->isBitIntType())
8546       return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
8547 
8548     return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
8549                                                 : ABIArgInfo::getDirect();
8550   }
8551 
8552   if (isEmptyRecord(getContext(), RetTy, true))
8553     return ABIArgInfo::getIgnore();
8554 
8555   // Aggregates <= 8 bytes are returned in registers, other aggregates
8556   // are returned indirectly.
8557   if (Size <= 64) {
8558     // Return in the smallest viable integer type.
8559     if (!llvm::isPowerOf2_64(Size))
8560       Size = llvm::NextPowerOf2(Size);
8561     return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size));
8562   }
8563   return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
8564 }
8565 
8566 Address HexagonABIInfo::EmitVAArgFromMemory(CodeGenFunction &CGF,
8567                                             Address VAListAddr,
8568                                             QualType Ty) const {
8569   // Load the overflow area pointer.
8570   Address __overflow_area_pointer_p =
8571       CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p");
8572   llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad(
8573       __overflow_area_pointer_p, "__overflow_area_pointer");
8574 
8575   uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
8576   if (Align > 4) {
8577     // Alignment should be a power of 2.
8578     assert((Align & (Align - 1)) == 0 && "Alignment is not power of 2!");
8579 
8580     // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
8581     llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
8582 
8583     // Add offset to the current pointer to access the argument.
8584     __overflow_area_pointer =
8585         CGF.Builder.CreateGEP(CGF.Int8Ty, __overflow_area_pointer, Offset);
8586     llvm::Value *AsInt =
8587         CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty);
8588 
8589     // Create a mask which should be "AND"ed
8590     // with (overflow_arg_area + align - 1)
8591     llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -(int)Align);
8592     __overflow_area_pointer = CGF.Builder.CreateIntToPtr(
8593         CGF.Builder.CreateAnd(AsInt, Mask), __overflow_area_pointer->getType(),
8594         "__overflow_area_pointer.align");
8595   }
8596 
8597   // Get the type of the argument from memory and bitcast
8598   // overflow area pointer to the argument type.
8599   llvm::Type *PTy = CGF.ConvertTypeForMem(Ty);
8600   Address AddrTyped = CGF.Builder.CreateBitCast(
8601       Address(__overflow_area_pointer, CharUnits::fromQuantity(Align)),
8602       llvm::PointerType::getUnqual(PTy));
8603 
8604   // Round up to the minimum stack alignment for varargs which is 4 bytes.
8605   uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4);
8606 
8607   __overflow_area_pointer = CGF.Builder.CreateGEP(
8608       CGF.Int8Ty, __overflow_area_pointer,
8609       llvm::ConstantInt::get(CGF.Int32Ty, Offset),
8610       "__overflow_area_pointer.next");
8611   CGF.Builder.CreateStore(__overflow_area_pointer, __overflow_area_pointer_p);
8612 
8613   return AddrTyped;
8614 }
8615 
8616 Address HexagonABIInfo::EmitVAArgForHexagon(CodeGenFunction &CGF,
8617                                             Address VAListAddr,
8618                                             QualType Ty) const {
8619   // FIXME: Need to handle alignment
8620   llvm::Type *BP = CGF.Int8PtrTy;
8621   llvm::Type *BPP = CGF.Int8PtrPtrTy;
8622   CGBuilderTy &Builder = CGF.Builder;
8623   Address VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
8624   llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
8625   // Handle address alignment for type alignment > 32 bits
8626   uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
8627   if (TyAlign > 4) {
8628     assert((TyAlign & (TyAlign - 1)) == 0 && "Alignment is not power of 2!");
8629     llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
8630     AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
8631     AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
8632     Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
8633   }
8634   llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
8635   Address AddrTyped = Builder.CreateBitCast(
8636       Address(Addr, CharUnits::fromQuantity(TyAlign)), PTy);
8637 
8638   uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4);
8639   llvm::Value *NextAddr = Builder.CreateGEP(
8640       CGF.Int8Ty, Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next");
8641   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
8642 
8643   return AddrTyped;
8644 }
8645 
8646 Address HexagonABIInfo::EmitVAArgForHexagonLinux(CodeGenFunction &CGF,
8647                                                  Address VAListAddr,
8648                                                  QualType Ty) const {
8649   int ArgSize = CGF.getContext().getTypeSize(Ty) / 8;
8650 
8651   if (ArgSize > 8)
8652     return EmitVAArgFromMemory(CGF, VAListAddr, Ty);
8653 
8654   // Here we have check if the argument is in register area or
8655   // in overflow area.
8656   // If the saved register area pointer + argsize rounded up to alignment >
8657   // saved register area end pointer, argument is in overflow area.
8658   unsigned RegsLeft = 6;
8659   Ty = CGF.getContext().getCanonicalType(Ty);
8660   (void)classifyArgumentType(Ty, &RegsLeft);
8661 
8662   llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
8663   llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
8664   llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
8665   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
8666 
8667   // Get rounded size of the argument.GCC does not allow vararg of
8668   // size < 4 bytes. We follow the same logic here.
8669   ArgSize = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8;
8670   int ArgAlign = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8;
8671 
8672   // Argument may be in saved register area
8673   CGF.EmitBlock(MaybeRegBlock);
8674 
8675   // Load the current saved register area pointer.
8676   Address __current_saved_reg_area_pointer_p = CGF.Builder.CreateStructGEP(
8677       VAListAddr, 0, "__current_saved_reg_area_pointer_p");
8678   llvm::Value *__current_saved_reg_area_pointer = CGF.Builder.CreateLoad(
8679       __current_saved_reg_area_pointer_p, "__current_saved_reg_area_pointer");
8680 
8681   // Load the saved register area end pointer.
8682   Address __saved_reg_area_end_pointer_p = CGF.Builder.CreateStructGEP(
8683       VAListAddr, 1, "__saved_reg_area_end_pointer_p");
8684   llvm::Value *__saved_reg_area_end_pointer = CGF.Builder.CreateLoad(
8685       __saved_reg_area_end_pointer_p, "__saved_reg_area_end_pointer");
8686 
8687   // If the size of argument is > 4 bytes, check if the stack
8688   // location is aligned to 8 bytes
8689   if (ArgAlign > 4) {
8690 
8691     llvm::Value *__current_saved_reg_area_pointer_int =
8692         CGF.Builder.CreatePtrToInt(__current_saved_reg_area_pointer,
8693                                    CGF.Int32Ty);
8694 
8695     __current_saved_reg_area_pointer_int = CGF.Builder.CreateAdd(
8696         __current_saved_reg_area_pointer_int,
8697         llvm::ConstantInt::get(CGF.Int32Ty, (ArgAlign - 1)),
8698         "align_current_saved_reg_area_pointer");
8699 
8700     __current_saved_reg_area_pointer_int =
8701         CGF.Builder.CreateAnd(__current_saved_reg_area_pointer_int,
8702                               llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign),
8703                               "align_current_saved_reg_area_pointer");
8704 
8705     __current_saved_reg_area_pointer =
8706         CGF.Builder.CreateIntToPtr(__current_saved_reg_area_pointer_int,
8707                                    __current_saved_reg_area_pointer->getType(),
8708                                    "align_current_saved_reg_area_pointer");
8709   }
8710 
8711   llvm::Value *__new_saved_reg_area_pointer =
8712       CGF.Builder.CreateGEP(CGF.Int8Ty, __current_saved_reg_area_pointer,
8713                             llvm::ConstantInt::get(CGF.Int32Ty, ArgSize),
8714                             "__new_saved_reg_area_pointer");
8715 
8716   llvm::Value *UsingStack = nullptr;
8717   UsingStack = CGF.Builder.CreateICmpSGT(__new_saved_reg_area_pointer,
8718                                          __saved_reg_area_end_pointer);
8719 
8720   CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, InRegBlock);
8721 
8722   // Argument in saved register area
8723   // Implement the block where argument is in register saved area
8724   CGF.EmitBlock(InRegBlock);
8725 
8726   llvm::Type *PTy = CGF.ConvertType(Ty);
8727   llvm::Value *__saved_reg_area_p = CGF.Builder.CreateBitCast(
8728       __current_saved_reg_area_pointer, llvm::PointerType::getUnqual(PTy));
8729 
8730   CGF.Builder.CreateStore(__new_saved_reg_area_pointer,
8731                           __current_saved_reg_area_pointer_p);
8732 
8733   CGF.EmitBranch(ContBlock);
8734 
8735   // Argument in overflow area
8736   // Implement the block where the argument is in overflow area.
8737   CGF.EmitBlock(OnStackBlock);
8738 
8739   // Load the overflow area pointer
8740   Address __overflow_area_pointer_p =
8741       CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p");
8742   llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad(
8743       __overflow_area_pointer_p, "__overflow_area_pointer");
8744 
8745   // Align the overflow area pointer according to the alignment of the argument
8746   if (ArgAlign > 4) {
8747     llvm::Value *__overflow_area_pointer_int =
8748         CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty);
8749 
8750     __overflow_area_pointer_int =
8751         CGF.Builder.CreateAdd(__overflow_area_pointer_int,
8752                               llvm::ConstantInt::get(CGF.Int32Ty, ArgAlign - 1),
8753                               "align_overflow_area_pointer");
8754 
8755     __overflow_area_pointer_int =
8756         CGF.Builder.CreateAnd(__overflow_area_pointer_int,
8757                               llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign),
8758                               "align_overflow_area_pointer");
8759 
8760     __overflow_area_pointer = CGF.Builder.CreateIntToPtr(
8761         __overflow_area_pointer_int, __overflow_area_pointer->getType(),
8762         "align_overflow_area_pointer");
8763   }
8764 
8765   // Get the pointer for next argument in overflow area and store it
8766   // to overflow area pointer.
8767   llvm::Value *__new_overflow_area_pointer = CGF.Builder.CreateGEP(
8768       CGF.Int8Ty, __overflow_area_pointer,
8769       llvm::ConstantInt::get(CGF.Int32Ty, ArgSize),
8770       "__overflow_area_pointer.next");
8771 
8772   CGF.Builder.CreateStore(__new_overflow_area_pointer,
8773                           __overflow_area_pointer_p);
8774 
8775   CGF.Builder.CreateStore(__new_overflow_area_pointer,
8776                           __current_saved_reg_area_pointer_p);
8777 
8778   // Bitcast the overflow area pointer to the type of argument.
8779   llvm::Type *OverflowPTy = CGF.ConvertTypeForMem(Ty);
8780   llvm::Value *__overflow_area_p = CGF.Builder.CreateBitCast(
8781       __overflow_area_pointer, llvm::PointerType::getUnqual(OverflowPTy));
8782 
8783   CGF.EmitBranch(ContBlock);
8784 
8785   // Get the correct pointer to load the variable argument
8786   // Implement the ContBlock
8787   CGF.EmitBlock(ContBlock);
8788 
8789   llvm::Type *MemPTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
8790   llvm::PHINode *ArgAddr = CGF.Builder.CreatePHI(MemPTy, 2, "vaarg.addr");
8791   ArgAddr->addIncoming(__saved_reg_area_p, InRegBlock);
8792   ArgAddr->addIncoming(__overflow_area_p, OnStackBlock);
8793 
8794   return Address(ArgAddr, CharUnits::fromQuantity(ArgAlign));
8795 }
8796 
8797 Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8798                                   QualType Ty) const {
8799 
8800   if (getTarget().getTriple().isMusl())
8801     return EmitVAArgForHexagonLinux(CGF, VAListAddr, Ty);
8802 
8803   return EmitVAArgForHexagon(CGF, VAListAddr, Ty);
8804 }
8805 
8806 //===----------------------------------------------------------------------===//
8807 // Lanai ABI Implementation
8808 //===----------------------------------------------------------------------===//
8809 
8810 namespace {
8811 class LanaiABIInfo : public DefaultABIInfo {
8812 public:
8813   LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8814 
8815   bool shouldUseInReg(QualType Ty, CCState &State) const;
8816 
8817   void computeInfo(CGFunctionInfo &FI) const override {
8818     CCState State(FI);
8819     // Lanai uses 4 registers to pass arguments unless the function has the
8820     // regparm attribute set.
8821     if (FI.getHasRegParm()) {
8822       State.FreeRegs = FI.getRegParm();
8823     } else {
8824       State.FreeRegs = 4;
8825     }
8826 
8827     if (!getCXXABI().classifyReturnType(FI))
8828       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8829     for (auto &I : FI.arguments())
8830       I.info = classifyArgumentType(I.type, State);
8831   }
8832 
8833   ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
8834   ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
8835 };
8836 } // end anonymous namespace
8837 
8838 bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
8839   unsigned Size = getContext().getTypeSize(Ty);
8840   unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
8841 
8842   if (SizeInRegs == 0)
8843     return false;
8844 
8845   if (SizeInRegs > State.FreeRegs) {
8846     State.FreeRegs = 0;
8847     return false;
8848   }
8849 
8850   State.FreeRegs -= SizeInRegs;
8851 
8852   return true;
8853 }
8854 
8855 ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
8856                                            CCState &State) const {
8857   if (!ByVal) {
8858     if (State.FreeRegs) {
8859       --State.FreeRegs; // Non-byval indirects just use one pointer.
8860       return getNaturalAlignIndirectInReg(Ty);
8861     }
8862     return getNaturalAlignIndirect(Ty, false);
8863   }
8864 
8865   // Compute the byval alignment.
8866   const unsigned MinABIStackAlignInBytes = 4;
8867   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
8868   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
8869                                  /*Realign=*/TypeAlign >
8870                                      MinABIStackAlignInBytes);
8871 }
8872 
8873 ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
8874                                               CCState &State) const {
8875   // Check with the C++ ABI first.
8876   const RecordType *RT = Ty->getAs<RecordType>();
8877   if (RT) {
8878     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
8879     if (RAA == CGCXXABI::RAA_Indirect) {
8880       return getIndirectResult(Ty, /*ByVal=*/false, State);
8881     } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
8882       return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
8883     }
8884   }
8885 
8886   if (isAggregateTypeForABI(Ty)) {
8887     // Structures with flexible arrays are always indirect.
8888     if (RT && RT->getDecl()->hasFlexibleArrayMember())
8889       return getIndirectResult(Ty, /*ByVal=*/true, State);
8890 
8891     // Ignore empty structs/unions.
8892     if (isEmptyRecord(getContext(), Ty, true))
8893       return ABIArgInfo::getIgnore();
8894 
8895     llvm::LLVMContext &LLVMContext = getVMContext();
8896     unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
8897     if (SizeInRegs <= State.FreeRegs) {
8898       llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
8899       SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
8900       llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
8901       State.FreeRegs -= SizeInRegs;
8902       return ABIArgInfo::getDirectInReg(Result);
8903     } else {
8904       State.FreeRegs = 0;
8905     }
8906     return getIndirectResult(Ty, true, State);
8907   }
8908 
8909   // Treat an enum type as its underlying type.
8910   if (const auto *EnumTy = Ty->getAs<EnumType>())
8911     Ty = EnumTy->getDecl()->getIntegerType();
8912 
8913   bool InReg = shouldUseInReg(Ty, State);
8914 
8915   // Don't pass >64 bit integers in registers.
8916   if (const auto *EIT = Ty->getAs<BitIntType>())
8917     if (EIT->getNumBits() > 64)
8918       return getIndirectResult(Ty, /*ByVal=*/true, State);
8919 
8920   if (isPromotableIntegerTypeForABI(Ty)) {
8921     if (InReg)
8922       return ABIArgInfo::getDirectInReg();
8923     return ABIArgInfo::getExtend(Ty);
8924   }
8925   if (InReg)
8926     return ABIArgInfo::getDirectInReg();
8927   return ABIArgInfo::getDirect();
8928 }
8929 
8930 namespace {
8931 class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
8932 public:
8933   LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
8934       : TargetCodeGenInfo(std::make_unique<LanaiABIInfo>(CGT)) {}
8935 };
8936 }
8937 
8938 //===----------------------------------------------------------------------===//
8939 // AMDGPU ABI Implementation
8940 //===----------------------------------------------------------------------===//
8941 
8942 namespace {
8943 
8944 class AMDGPUABIInfo final : public DefaultABIInfo {
8945 private:
8946   static const unsigned MaxNumRegsForArgsRet = 16;
8947 
8948   unsigned numRegsForType(QualType Ty) const;
8949 
8950   bool isHomogeneousAggregateBaseType(QualType Ty) const override;
8951   bool isHomogeneousAggregateSmallEnough(const Type *Base,
8952                                          uint64_t Members) const override;
8953 
8954   // Coerce HIP scalar pointer arguments from generic pointers to global ones.
8955   llvm::Type *coerceKernelArgumentType(llvm::Type *Ty, unsigned FromAS,
8956                                        unsigned ToAS) const {
8957     // Single value types.
8958     auto *PtrTy = llvm::dyn_cast<llvm::PointerType>(Ty);
8959     if (PtrTy && PtrTy->getAddressSpace() == FromAS)
8960       return llvm::PointerType::getWithSamePointeeType(PtrTy, ToAS);
8961     return Ty;
8962   }
8963 
8964 public:
8965   explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) :
8966     DefaultABIInfo(CGT) {}
8967 
8968   ABIArgInfo classifyReturnType(QualType RetTy) const;
8969   ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
8970   ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const;
8971 
8972   void computeInfo(CGFunctionInfo &FI) const override;
8973   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8974                     QualType Ty) const override;
8975 };
8976 
8977 bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
8978   return true;
8979 }
8980 
8981 bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough(
8982   const Type *Base, uint64_t Members) const {
8983   uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32;
8984 
8985   // Homogeneous Aggregates may occupy at most 16 registers.
8986   return Members * NumRegs <= MaxNumRegsForArgsRet;
8987 }
8988 
8989 /// Estimate number of registers the type will use when passed in registers.
8990 unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const {
8991   unsigned NumRegs = 0;
8992 
8993   if (const VectorType *VT = Ty->getAs<VectorType>()) {
8994     // Compute from the number of elements. The reported size is based on the
8995     // in-memory size, which includes the padding 4th element for 3-vectors.
8996     QualType EltTy = VT->getElementType();
8997     unsigned EltSize = getContext().getTypeSize(EltTy);
8998 
8999     // 16-bit element vectors should be passed as packed.
9000     if (EltSize == 16)
9001       return (VT->getNumElements() + 1) / 2;
9002 
9003     unsigned EltNumRegs = (EltSize + 31) / 32;
9004     return EltNumRegs * VT->getNumElements();
9005   }
9006 
9007   if (const RecordType *RT = Ty->getAs<RecordType>()) {
9008     const RecordDecl *RD = RT->getDecl();
9009     assert(!RD->hasFlexibleArrayMember());
9010 
9011     for (const FieldDecl *Field : RD->fields()) {
9012       QualType FieldTy = Field->getType();
9013       NumRegs += numRegsForType(FieldTy);
9014     }
9015 
9016     return NumRegs;
9017   }
9018 
9019   return (getContext().getTypeSize(Ty) + 31) / 32;
9020 }
9021 
9022 void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
9023   llvm::CallingConv::ID CC = FI.getCallingConvention();
9024 
9025   if (!getCXXABI().classifyReturnType(FI))
9026     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
9027 
9028   unsigned NumRegsLeft = MaxNumRegsForArgsRet;
9029   for (auto &Arg : FI.arguments()) {
9030     if (CC == llvm::CallingConv::AMDGPU_KERNEL) {
9031       Arg.info = classifyKernelArgumentType(Arg.type);
9032     } else {
9033       Arg.info = classifyArgumentType(Arg.type, NumRegsLeft);
9034     }
9035   }
9036 }
9037 
9038 Address AMDGPUABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9039                                  QualType Ty) const {
9040   llvm_unreachable("AMDGPU does not support varargs");
9041 }
9042 
9043 ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const {
9044   if (isAggregateTypeForABI(RetTy)) {
9045     // Records with non-trivial destructors/copy-constructors should not be
9046     // returned by value.
9047     if (!getRecordArgABI(RetTy, getCXXABI())) {
9048       // Ignore empty structs/unions.
9049       if (isEmptyRecord(getContext(), RetTy, true))
9050         return ABIArgInfo::getIgnore();
9051 
9052       // Lower single-element structs to just return a regular value.
9053       if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
9054         return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
9055 
9056       if (const RecordType *RT = RetTy->getAs<RecordType>()) {
9057         const RecordDecl *RD = RT->getDecl();
9058         if (RD->hasFlexibleArrayMember())
9059           return DefaultABIInfo::classifyReturnType(RetTy);
9060       }
9061 
9062       // Pack aggregates <= 4 bytes into single VGPR or pair.
9063       uint64_t Size = getContext().getTypeSize(RetTy);
9064       if (Size <= 16)
9065         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
9066 
9067       if (Size <= 32)
9068         return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
9069 
9070       if (Size <= 64) {
9071         llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
9072         return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
9073       }
9074 
9075       if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet)
9076         return ABIArgInfo::getDirect();
9077     }
9078   }
9079 
9080   // Otherwise just do the default thing.
9081   return DefaultABIInfo::classifyReturnType(RetTy);
9082 }
9083 
9084 /// For kernels all parameters are really passed in a special buffer. It doesn't
9085 /// make sense to pass anything byval, so everything must be direct.
9086 ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const {
9087   Ty = useFirstFieldIfTransparentUnion(Ty);
9088 
9089   // TODO: Can we omit empty structs?
9090 
9091   if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
9092     Ty = QualType(SeltTy, 0);
9093 
9094   llvm::Type *OrigLTy = CGT.ConvertType(Ty);
9095   llvm::Type *LTy = OrigLTy;
9096   if (getContext().getLangOpts().HIP) {
9097     LTy = coerceKernelArgumentType(
9098         OrigLTy, /*FromAS=*/getContext().getTargetAddressSpace(LangAS::Default),
9099         /*ToAS=*/getContext().getTargetAddressSpace(LangAS::cuda_device));
9100   }
9101 
9102   // FIXME: Should also use this for OpenCL, but it requires addressing the
9103   // problem of kernels being called.
9104   //
9105   // FIXME: This doesn't apply the optimization of coercing pointers in structs
9106   // to global address space when using byref. This would require implementing a
9107   // new kind of coercion of the in-memory type when for indirect arguments.
9108   if (!getContext().getLangOpts().OpenCL && LTy == OrigLTy &&
9109       isAggregateTypeForABI(Ty)) {
9110     return ABIArgInfo::getIndirectAliased(
9111         getContext().getTypeAlignInChars(Ty),
9112         getContext().getTargetAddressSpace(LangAS::opencl_constant),
9113         false /*Realign*/, nullptr /*Padding*/);
9114   }
9115 
9116   // If we set CanBeFlattened to true, CodeGen will expand the struct to its
9117   // individual elements, which confuses the Clover OpenCL backend; therefore we
9118   // have to set it to false here. Other args of getDirect() are just defaults.
9119   return ABIArgInfo::getDirect(LTy, 0, nullptr, false);
9120 }
9121 
9122 ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty,
9123                                                unsigned &NumRegsLeft) const {
9124   assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow");
9125 
9126   Ty = useFirstFieldIfTransparentUnion(Ty);
9127 
9128   if (isAggregateTypeForABI(Ty)) {
9129     // Records with non-trivial destructors/copy-constructors should not be
9130     // passed by value.
9131     if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
9132       return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
9133 
9134     // Ignore empty structs/unions.
9135     if (isEmptyRecord(getContext(), Ty, true))
9136       return ABIArgInfo::getIgnore();
9137 
9138     // Lower single-element structs to just pass a regular value. TODO: We
9139     // could do reasonable-size multiple-element structs too, using getExpand(),
9140     // though watch out for things like bitfields.
9141     if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
9142       return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
9143 
9144     if (const RecordType *RT = Ty->getAs<RecordType>()) {
9145       const RecordDecl *RD = RT->getDecl();
9146       if (RD->hasFlexibleArrayMember())
9147         return DefaultABIInfo::classifyArgumentType(Ty);
9148     }
9149 
9150     // Pack aggregates <= 8 bytes into single VGPR or pair.
9151     uint64_t Size = getContext().getTypeSize(Ty);
9152     if (Size <= 64) {
9153       unsigned NumRegs = (Size + 31) / 32;
9154       NumRegsLeft -= std::min(NumRegsLeft, NumRegs);
9155 
9156       if (Size <= 16)
9157         return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
9158 
9159       if (Size <= 32)
9160         return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
9161 
9162       // XXX: Should this be i64 instead, and should the limit increase?
9163       llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
9164       return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
9165     }
9166 
9167     if (NumRegsLeft > 0) {
9168       unsigned NumRegs = numRegsForType(Ty);
9169       if (NumRegsLeft >= NumRegs) {
9170         NumRegsLeft -= NumRegs;
9171         return ABIArgInfo::getDirect();
9172       }
9173     }
9174   }
9175 
9176   // Otherwise just do the default thing.
9177   ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty);
9178   if (!ArgInfo.isIndirect()) {
9179     unsigned NumRegs = numRegsForType(Ty);
9180     NumRegsLeft -= std::min(NumRegs, NumRegsLeft);
9181   }
9182 
9183   return ArgInfo;
9184 }
9185 
9186 class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
9187 public:
9188   AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
9189       : TargetCodeGenInfo(std::make_unique<AMDGPUABIInfo>(CGT)) {}
9190 
9191   void setFunctionDeclAttributes(const FunctionDecl *FD, llvm::Function *F,
9192                                  CodeGenModule &CGM) const;
9193 
9194   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
9195                            CodeGen::CodeGenModule &M) const override;
9196   unsigned getOpenCLKernelCallingConv() const override;
9197 
9198   llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
9199       llvm::PointerType *T, QualType QT) const override;
9200 
9201   LangAS getASTAllocaAddressSpace() const override {
9202     return getLangASFromTargetAS(
9203         getABIInfo().getDataLayout().getAllocaAddrSpace());
9204   }
9205   LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
9206                                   const VarDecl *D) const override;
9207   llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts,
9208                                          SyncScope Scope,
9209                                          llvm::AtomicOrdering Ordering,
9210                                          llvm::LLVMContext &Ctx) const override;
9211   llvm::Function *
9212   createEnqueuedBlockKernel(CodeGenFunction &CGF,
9213                             llvm::Function *BlockInvokeFunc,
9214                             llvm::Value *BlockLiteral) const override;
9215   bool shouldEmitStaticExternCAliases() const override;
9216   void setCUDAKernelCallingConvention(const FunctionType *&FT) const override;
9217 };
9218 }
9219 
9220 static bool requiresAMDGPUProtectedVisibility(const Decl *D,
9221                                               llvm::GlobalValue *GV) {
9222   if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility)
9223     return false;
9224 
9225   return D->hasAttr<OpenCLKernelAttr>() ||
9226          (isa<FunctionDecl>(D) && D->hasAttr<CUDAGlobalAttr>()) ||
9227          (isa<VarDecl>(D) &&
9228           (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
9229            cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinSurfaceType() ||
9230            cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinTextureType()));
9231 }
9232 
9233 void AMDGPUTargetCodeGenInfo::setFunctionDeclAttributes(
9234     const FunctionDecl *FD, llvm::Function *F, CodeGenModule &M) const {
9235   const auto *ReqdWGS =
9236       M.getLangOpts().OpenCL ? FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr;
9237   const bool IsOpenCLKernel =
9238       M.getLangOpts().OpenCL && FD->hasAttr<OpenCLKernelAttr>();
9239   const bool IsHIPKernel = M.getLangOpts().HIP && FD->hasAttr<CUDAGlobalAttr>();
9240 
9241   const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
9242   if (ReqdWGS || FlatWGS) {
9243     unsigned Min = 0;
9244     unsigned Max = 0;
9245     if (FlatWGS) {
9246       Min = FlatWGS->getMin()
9247                 ->EvaluateKnownConstInt(M.getContext())
9248                 .getExtValue();
9249       Max = FlatWGS->getMax()
9250                 ->EvaluateKnownConstInt(M.getContext())
9251                 .getExtValue();
9252     }
9253     if (ReqdWGS && Min == 0 && Max == 0)
9254       Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim();
9255 
9256     if (Min != 0) {
9257       assert(Min <= Max && "Min must be less than or equal Max");
9258 
9259       std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
9260       F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
9261     } else
9262       assert(Max == 0 && "Max must be zero");
9263   } else if (IsOpenCLKernel || IsHIPKernel) {
9264     // By default, restrict the maximum size to a value specified by
9265     // --gpu-max-threads-per-block=n or its default value for HIP.
9266     const unsigned OpenCLDefaultMaxWorkGroupSize = 256;
9267     const unsigned DefaultMaxWorkGroupSize =
9268         IsOpenCLKernel ? OpenCLDefaultMaxWorkGroupSize
9269                        : M.getLangOpts().GPUMaxThreadsPerBlock;
9270     std::string AttrVal =
9271         std::string("1,") + llvm::utostr(DefaultMaxWorkGroupSize);
9272     F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
9273   }
9274 
9275   if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
9276     unsigned Min =
9277         Attr->getMin()->EvaluateKnownConstInt(M.getContext()).getExtValue();
9278     unsigned Max = Attr->getMax() ? Attr->getMax()
9279                                         ->EvaluateKnownConstInt(M.getContext())
9280                                         .getExtValue()
9281                                   : 0;
9282 
9283     if (Min != 0) {
9284       assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
9285 
9286       std::string AttrVal = llvm::utostr(Min);
9287       if (Max != 0)
9288         AttrVal = AttrVal + "," + llvm::utostr(Max);
9289       F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
9290     } else
9291       assert(Max == 0 && "Max must be zero");
9292   }
9293 
9294   if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
9295     unsigned NumSGPR = Attr->getNumSGPR();
9296 
9297     if (NumSGPR != 0)
9298       F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
9299   }
9300 
9301   if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
9302     uint32_t NumVGPR = Attr->getNumVGPR();
9303 
9304     if (NumVGPR != 0)
9305       F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
9306   }
9307 }
9308 
9309 void AMDGPUTargetCodeGenInfo::setTargetAttributes(
9310     const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
9311   if (requiresAMDGPUProtectedVisibility(D, GV)) {
9312     GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
9313     GV->setDSOLocal(true);
9314   }
9315 
9316   if (GV->isDeclaration())
9317     return;
9318 
9319   llvm::Function *F = dyn_cast<llvm::Function>(GV);
9320   if (!F)
9321     return;
9322 
9323   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
9324   if (FD)
9325     setFunctionDeclAttributes(FD, F, M);
9326 
9327   const bool IsHIPKernel =
9328       M.getLangOpts().HIP && FD && FD->hasAttr<CUDAGlobalAttr>();
9329 
9330   if (IsHIPKernel)
9331     F->addFnAttr("uniform-work-group-size", "true");
9332 
9333   if (M.getContext().getTargetInfo().allowAMDGPUUnsafeFPAtomics())
9334     F->addFnAttr("amdgpu-unsafe-fp-atomics", "true");
9335 
9336   if (!getABIInfo().getCodeGenOpts().EmitIEEENaNCompliantInsts)
9337     F->addFnAttr("amdgpu-ieee", "false");
9338 }
9339 
9340 unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
9341   return llvm::CallingConv::AMDGPU_KERNEL;
9342 }
9343 
9344 // Currently LLVM assumes null pointers always have value 0,
9345 // which results in incorrectly transformed IR. Therefore, instead of
9346 // emitting null pointers in private and local address spaces, a null
9347 // pointer in generic address space is emitted which is casted to a
9348 // pointer in local or private address space.
9349 llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
9350     const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
9351     QualType QT) const {
9352   if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
9353     return llvm::ConstantPointerNull::get(PT);
9354 
9355   auto &Ctx = CGM.getContext();
9356   auto NPT = llvm::PointerType::getWithSamePointeeType(
9357       PT, Ctx.getTargetAddressSpace(LangAS::opencl_generic));
9358   return llvm::ConstantExpr::getAddrSpaceCast(
9359       llvm::ConstantPointerNull::get(NPT), PT);
9360 }
9361 
9362 LangAS
9363 AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
9364                                                   const VarDecl *D) const {
9365   assert(!CGM.getLangOpts().OpenCL &&
9366          !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
9367          "Address space agnostic languages only");
9368   LangAS DefaultGlobalAS = getLangASFromTargetAS(
9369       CGM.getContext().getTargetAddressSpace(LangAS::opencl_global));
9370   if (!D)
9371     return DefaultGlobalAS;
9372 
9373   LangAS AddrSpace = D->getType().getAddressSpace();
9374   assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace));
9375   if (AddrSpace != LangAS::Default)
9376     return AddrSpace;
9377 
9378   // Only promote to address space 4 if VarDecl has constant initialization.
9379   if (CGM.isTypeConstant(D->getType(), false) &&
9380       D->hasConstantInitialization()) {
9381     if (auto ConstAS = CGM.getTarget().getConstantAddressSpace())
9382       return ConstAS.getValue();
9383   }
9384   return DefaultGlobalAS;
9385 }
9386 
9387 llvm::SyncScope::ID
9388 AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
9389                                             SyncScope Scope,
9390                                             llvm::AtomicOrdering Ordering,
9391                                             llvm::LLVMContext &Ctx) const {
9392   std::string Name;
9393   switch (Scope) {
9394   case SyncScope::HIPSingleThread:
9395     Name = "singlethread";
9396     break;
9397   case SyncScope::HIPWavefront:
9398   case SyncScope::OpenCLSubGroup:
9399     Name = "wavefront";
9400     break;
9401   case SyncScope::HIPWorkgroup:
9402   case SyncScope::OpenCLWorkGroup:
9403     Name = "workgroup";
9404     break;
9405   case SyncScope::HIPAgent:
9406   case SyncScope::OpenCLDevice:
9407     Name = "agent";
9408     break;
9409   case SyncScope::HIPSystem:
9410   case SyncScope::OpenCLAllSVMDevices:
9411     Name = "";
9412     break;
9413   }
9414 
9415   if (Ordering != llvm::AtomicOrdering::SequentiallyConsistent) {
9416     if (!Name.empty())
9417       Name = Twine(Twine(Name) + Twine("-")).str();
9418 
9419     Name = Twine(Twine(Name) + Twine("one-as")).str();
9420   }
9421 
9422   return Ctx.getOrInsertSyncScopeID(Name);
9423 }
9424 
9425 bool AMDGPUTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
9426   return false;
9427 }
9428 
9429 void AMDGPUTargetCodeGenInfo::setCUDAKernelCallingConvention(
9430     const FunctionType *&FT) const {
9431   FT = getABIInfo().getContext().adjustFunctionType(
9432       FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel));
9433 }
9434 
9435 //===----------------------------------------------------------------------===//
9436 // SPARC v8 ABI Implementation.
9437 // Based on the SPARC Compliance Definition version 2.4.1.
9438 //
9439 // Ensures that complex values are passed in registers.
9440 //
9441 namespace {
9442 class SparcV8ABIInfo : public DefaultABIInfo {
9443 public:
9444   SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
9445 
9446 private:
9447   ABIArgInfo classifyReturnType(QualType RetTy) const;
9448   void computeInfo(CGFunctionInfo &FI) const override;
9449 };
9450 } // end anonymous namespace
9451 
9452 
9453 ABIArgInfo
9454 SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
9455   if (Ty->isAnyComplexType()) {
9456     return ABIArgInfo::getDirect();
9457   }
9458   else {
9459     return DefaultABIInfo::classifyReturnType(Ty);
9460   }
9461 }
9462 
9463 void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
9464 
9465   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
9466   for (auto &Arg : FI.arguments())
9467     Arg.info = classifyArgumentType(Arg.type);
9468 }
9469 
9470 namespace {
9471 class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
9472 public:
9473   SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
9474       : TargetCodeGenInfo(std::make_unique<SparcV8ABIInfo>(CGT)) {}
9475 };
9476 } // end anonymous namespace
9477 
9478 //===----------------------------------------------------------------------===//
9479 // SPARC v9 ABI Implementation.
9480 // Based on the SPARC Compliance Definition version 2.4.1.
9481 //
9482 // Function arguments a mapped to a nominal "parameter array" and promoted to
9483 // registers depending on their type. Each argument occupies 8 or 16 bytes in
9484 // the array, structs larger than 16 bytes are passed indirectly.
9485 //
9486 // One case requires special care:
9487 //
9488 //   struct mixed {
9489 //     int i;
9490 //     float f;
9491 //   };
9492 //
9493 // When a struct mixed is passed by value, it only occupies 8 bytes in the
9494 // parameter array, but the int is passed in an integer register, and the float
9495 // is passed in a floating point register. This is represented as two arguments
9496 // with the LLVM IR inreg attribute:
9497 //
9498 //   declare void f(i32 inreg %i, float inreg %f)
9499 //
9500 // The code generator will only allocate 4 bytes from the parameter array for
9501 // the inreg arguments. All other arguments are allocated a multiple of 8
9502 // bytes.
9503 //
9504 namespace {
9505 class SparcV9ABIInfo : public ABIInfo {
9506 public:
9507   SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
9508 
9509 private:
9510   ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
9511   void computeInfo(CGFunctionInfo &FI) const override;
9512   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9513                     QualType Ty) const override;
9514 
9515   // Coercion type builder for structs passed in registers. The coercion type
9516   // serves two purposes:
9517   //
9518   // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
9519   //    in registers.
9520   // 2. Expose aligned floating point elements as first-level elements, so the
9521   //    code generator knows to pass them in floating point registers.
9522   //
9523   // We also compute the InReg flag which indicates that the struct contains
9524   // aligned 32-bit floats.
9525   //
9526   struct CoerceBuilder {
9527     llvm::LLVMContext &Context;
9528     const llvm::DataLayout &DL;
9529     SmallVector<llvm::Type*, 8> Elems;
9530     uint64_t Size;
9531     bool InReg;
9532 
9533     CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
9534       : Context(c), DL(dl), Size(0), InReg(false) {}
9535 
9536     // Pad Elems with integers until Size is ToSize.
9537     void pad(uint64_t ToSize) {
9538       assert(ToSize >= Size && "Cannot remove elements");
9539       if (ToSize == Size)
9540         return;
9541 
9542       // Finish the current 64-bit word.
9543       uint64_t Aligned = llvm::alignTo(Size, 64);
9544       if (Aligned > Size && Aligned <= ToSize) {
9545         Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
9546         Size = Aligned;
9547       }
9548 
9549       // Add whole 64-bit words.
9550       while (Size + 64 <= ToSize) {
9551         Elems.push_back(llvm::Type::getInt64Ty(Context));
9552         Size += 64;
9553       }
9554 
9555       // Final in-word padding.
9556       if (Size < ToSize) {
9557         Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
9558         Size = ToSize;
9559       }
9560     }
9561 
9562     // Add a floating point element at Offset.
9563     void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
9564       // Unaligned floats are treated as integers.
9565       if (Offset % Bits)
9566         return;
9567       // The InReg flag is only required if there are any floats < 64 bits.
9568       if (Bits < 64)
9569         InReg = true;
9570       pad(Offset);
9571       Elems.push_back(Ty);
9572       Size = Offset + Bits;
9573     }
9574 
9575     // Add a struct type to the coercion type, starting at Offset (in bits).
9576     void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
9577       const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
9578       for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
9579         llvm::Type *ElemTy = StrTy->getElementType(i);
9580         uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
9581         switch (ElemTy->getTypeID()) {
9582         case llvm::Type::StructTyID:
9583           addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
9584           break;
9585         case llvm::Type::FloatTyID:
9586           addFloat(ElemOffset, ElemTy, 32);
9587           break;
9588         case llvm::Type::DoubleTyID:
9589           addFloat(ElemOffset, ElemTy, 64);
9590           break;
9591         case llvm::Type::FP128TyID:
9592           addFloat(ElemOffset, ElemTy, 128);
9593           break;
9594         case llvm::Type::PointerTyID:
9595           if (ElemOffset % 64 == 0) {
9596             pad(ElemOffset);
9597             Elems.push_back(ElemTy);
9598             Size += 64;
9599           }
9600           break;
9601         default:
9602           break;
9603         }
9604       }
9605     }
9606 
9607     // Check if Ty is a usable substitute for the coercion type.
9608     bool isUsableType(llvm::StructType *Ty) const {
9609       return llvm::makeArrayRef(Elems) == Ty->elements();
9610     }
9611 
9612     // Get the coercion type as a literal struct type.
9613     llvm::Type *getType() const {
9614       if (Elems.size() == 1)
9615         return Elems.front();
9616       else
9617         return llvm::StructType::get(Context, Elems);
9618     }
9619   };
9620 };
9621 } // end anonymous namespace
9622 
9623 ABIArgInfo
9624 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
9625   if (Ty->isVoidType())
9626     return ABIArgInfo::getIgnore();
9627 
9628   uint64_t Size = getContext().getTypeSize(Ty);
9629 
9630   // Anything too big to fit in registers is passed with an explicit indirect
9631   // pointer / sret pointer.
9632   if (Size > SizeLimit)
9633     return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
9634 
9635   // Treat an enum type as its underlying type.
9636   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
9637     Ty = EnumTy->getDecl()->getIntegerType();
9638 
9639   // Integer types smaller than a register are extended.
9640   if (Size < 64 && Ty->isIntegerType())
9641     return ABIArgInfo::getExtend(Ty);
9642 
9643   if (const auto *EIT = Ty->getAs<BitIntType>())
9644     if (EIT->getNumBits() < 64)
9645       return ABIArgInfo::getExtend(Ty);
9646 
9647   // Other non-aggregates go in registers.
9648   if (!isAggregateTypeForABI(Ty))
9649     return ABIArgInfo::getDirect();
9650 
9651   // If a C++ object has either a non-trivial copy constructor or a non-trivial
9652   // destructor, it is passed with an explicit indirect pointer / sret pointer.
9653   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
9654     return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
9655 
9656   // This is a small aggregate type that should be passed in registers.
9657   // Build a coercion type from the LLVM struct type.
9658   llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
9659   if (!StrTy)
9660     return ABIArgInfo::getDirect();
9661 
9662   CoerceBuilder CB(getVMContext(), getDataLayout());
9663   CB.addStruct(0, StrTy);
9664   CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
9665 
9666   // Try to use the original type for coercion.
9667   llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
9668 
9669   if (CB.InReg)
9670     return ABIArgInfo::getDirectInReg(CoerceTy);
9671   else
9672     return ABIArgInfo::getDirect(CoerceTy);
9673 }
9674 
9675 Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9676                                   QualType Ty) const {
9677   ABIArgInfo AI = classifyType(Ty, 16 * 8);
9678   llvm::Type *ArgTy = CGT.ConvertType(Ty);
9679   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
9680     AI.setCoerceToType(ArgTy);
9681 
9682   CharUnits SlotSize = CharUnits::fromQuantity(8);
9683 
9684   CGBuilderTy &Builder = CGF.Builder;
9685   Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
9686   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
9687 
9688   auto TypeInfo = getContext().getTypeInfoInChars(Ty);
9689 
9690   Address ArgAddr = Address::invalid();
9691   CharUnits Stride;
9692   switch (AI.getKind()) {
9693   case ABIArgInfo::Expand:
9694   case ABIArgInfo::CoerceAndExpand:
9695   case ABIArgInfo::InAlloca:
9696     llvm_unreachable("Unsupported ABI kind for va_arg");
9697 
9698   case ABIArgInfo::Extend: {
9699     Stride = SlotSize;
9700     CharUnits Offset = SlotSize - TypeInfo.Width;
9701     ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
9702     break;
9703   }
9704 
9705   case ABIArgInfo::Direct: {
9706     auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
9707     Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
9708     ArgAddr = Addr;
9709     break;
9710   }
9711 
9712   case ABIArgInfo::Indirect:
9713   case ABIArgInfo::IndirectAliased:
9714     Stride = SlotSize;
9715     ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
9716     ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
9717                       TypeInfo.Align);
9718     break;
9719 
9720   case ABIArgInfo::Ignore:
9721     return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.Align);
9722   }
9723 
9724   // Update VAList.
9725   Address NextPtr = Builder.CreateConstInBoundsByteGEP(Addr, Stride, "ap.next");
9726   Builder.CreateStore(NextPtr.getPointer(), VAListAddr);
9727 
9728   return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
9729 }
9730 
9731 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
9732   FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
9733   for (auto &I : FI.arguments())
9734     I.info = classifyType(I.type, 16 * 8);
9735 }
9736 
9737 namespace {
9738 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
9739 public:
9740   SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
9741       : TargetCodeGenInfo(std::make_unique<SparcV9ABIInfo>(CGT)) {}
9742 
9743   int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
9744     return 14;
9745   }
9746 
9747   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
9748                                llvm::Value *Address) const override;
9749 };
9750 } // end anonymous namespace
9751 
9752 bool
9753 SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
9754                                                 llvm::Value *Address) const {
9755   // This is calculated from the LLVM and GCC tables and verified
9756   // against gcc output.  AFAIK all ABIs use the same encoding.
9757 
9758   CodeGen::CGBuilderTy &Builder = CGF.Builder;
9759 
9760   llvm::IntegerType *i8 = CGF.Int8Ty;
9761   llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
9762   llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
9763 
9764   // 0-31: the 8-byte general-purpose registers
9765   AssignToArrayRange(Builder, Address, Eight8, 0, 31);
9766 
9767   // 32-63: f0-31, the 4-byte floating-point registers
9768   AssignToArrayRange(Builder, Address, Four8, 32, 63);
9769 
9770   //   Y   = 64
9771   //   PSR = 65
9772   //   WIM = 66
9773   //   TBR = 67
9774   //   PC  = 68
9775   //   NPC = 69
9776   //   FSR = 70
9777   //   CSR = 71
9778   AssignToArrayRange(Builder, Address, Eight8, 64, 71);
9779 
9780   // 72-87: d0-15, the 8-byte floating-point registers
9781   AssignToArrayRange(Builder, Address, Eight8, 72, 87);
9782 
9783   return false;
9784 }
9785 
9786 // ARC ABI implementation.
9787 namespace {
9788 
9789 class ARCABIInfo : public DefaultABIInfo {
9790 public:
9791   using DefaultABIInfo::DefaultABIInfo;
9792 
9793 private:
9794   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9795                     QualType Ty) const override;
9796 
9797   void updateState(const ABIArgInfo &Info, QualType Ty, CCState &State) const {
9798     if (!State.FreeRegs)
9799       return;
9800     if (Info.isIndirect() && Info.getInReg())
9801       State.FreeRegs--;
9802     else if (Info.isDirect() && Info.getInReg()) {
9803       unsigned sz = (getContext().getTypeSize(Ty) + 31) / 32;
9804       if (sz < State.FreeRegs)
9805         State.FreeRegs -= sz;
9806       else
9807         State.FreeRegs = 0;
9808     }
9809   }
9810 
9811   void computeInfo(CGFunctionInfo &FI) const override {
9812     CCState State(FI);
9813     // ARC uses 8 registers to pass arguments.
9814     State.FreeRegs = 8;
9815 
9816     if (!getCXXABI().classifyReturnType(FI))
9817       FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
9818     updateState(FI.getReturnInfo(), FI.getReturnType(), State);
9819     for (auto &I : FI.arguments()) {
9820       I.info = classifyArgumentType(I.type, State.FreeRegs);
9821       updateState(I.info, I.type, State);
9822     }
9823   }
9824 
9825   ABIArgInfo getIndirectByRef(QualType Ty, bool HasFreeRegs) const;
9826   ABIArgInfo getIndirectByValue(QualType Ty) const;
9827   ABIArgInfo classifyArgumentType(QualType Ty, uint8_t FreeRegs) const;
9828   ABIArgInfo classifyReturnType(QualType RetTy) const;
9829 };
9830 
9831 class ARCTargetCodeGenInfo : public TargetCodeGenInfo {
9832 public:
9833   ARCTargetCodeGenInfo(CodeGenTypes &CGT)
9834       : TargetCodeGenInfo(std::make_unique<ARCABIInfo>(CGT)) {}
9835 };
9836 
9837 
9838 ABIArgInfo ARCABIInfo::getIndirectByRef(QualType Ty, bool HasFreeRegs) const {
9839   return HasFreeRegs ? getNaturalAlignIndirectInReg(Ty) :
9840                        getNaturalAlignIndirect(Ty, false);
9841 }
9842 
9843 ABIArgInfo ARCABIInfo::getIndirectByValue(QualType Ty) const {
9844   // Compute the byval alignment.
9845   const unsigned MinABIStackAlignInBytes = 4;
9846   unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
9847   return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
9848                                  TypeAlign > MinABIStackAlignInBytes);
9849 }
9850 
9851 Address ARCABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9852                               QualType Ty) const {
9853   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
9854                           getContext().getTypeInfoInChars(Ty),
9855                           CharUnits::fromQuantity(4), true);
9856 }
9857 
9858 ABIArgInfo ARCABIInfo::classifyArgumentType(QualType Ty,
9859                                             uint8_t FreeRegs) const {
9860   // Handle the generic C++ ABI.
9861   const RecordType *RT = Ty->getAs<RecordType>();
9862   if (RT) {
9863     CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
9864     if (RAA == CGCXXABI::RAA_Indirect)
9865       return getIndirectByRef(Ty, FreeRegs > 0);
9866 
9867     if (RAA == CGCXXABI::RAA_DirectInMemory)
9868       return getIndirectByValue(Ty);
9869   }
9870 
9871   // Treat an enum type as its underlying type.
9872   if (const EnumType *EnumTy = Ty->getAs<EnumType>())
9873     Ty = EnumTy->getDecl()->getIntegerType();
9874 
9875   auto SizeInRegs = llvm::alignTo(getContext().getTypeSize(Ty), 32) / 32;
9876 
9877   if (isAggregateTypeForABI(Ty)) {
9878     // Structures with flexible arrays are always indirect.
9879     if (RT && RT->getDecl()->hasFlexibleArrayMember())
9880       return getIndirectByValue(Ty);
9881 
9882     // Ignore empty structs/unions.
9883     if (isEmptyRecord(getContext(), Ty, true))
9884       return ABIArgInfo::getIgnore();
9885 
9886     llvm::LLVMContext &LLVMContext = getVMContext();
9887 
9888     llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
9889     SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
9890     llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
9891 
9892     return FreeRegs >= SizeInRegs ?
9893         ABIArgInfo::getDirectInReg(Result) :
9894         ABIArgInfo::getDirect(Result, 0, nullptr, false);
9895   }
9896 
9897   if (const auto *EIT = Ty->getAs<BitIntType>())
9898     if (EIT->getNumBits() > 64)
9899       return getIndirectByValue(Ty);
9900 
9901   return isPromotableIntegerTypeForABI(Ty)
9902              ? (FreeRegs >= SizeInRegs ? ABIArgInfo::getExtendInReg(Ty)
9903                                        : ABIArgInfo::getExtend(Ty))
9904              : (FreeRegs >= SizeInRegs ? ABIArgInfo::getDirectInReg()
9905                                        : ABIArgInfo::getDirect());
9906 }
9907 
9908 ABIArgInfo ARCABIInfo::classifyReturnType(QualType RetTy) const {
9909   if (RetTy->isAnyComplexType())
9910     return ABIArgInfo::getDirectInReg();
9911 
9912   // Arguments of size > 4 registers are indirect.
9913   auto RetSize = llvm::alignTo(getContext().getTypeSize(RetTy), 32) / 32;
9914   if (RetSize > 4)
9915     return getIndirectByRef(RetTy, /*HasFreeRegs*/ true);
9916 
9917   return DefaultABIInfo::classifyReturnType(RetTy);
9918 }
9919 
9920 } // End anonymous namespace.
9921 
9922 //===----------------------------------------------------------------------===//
9923 // XCore ABI Implementation
9924 //===----------------------------------------------------------------------===//
9925 
9926 namespace {
9927 
9928 /// A SmallStringEnc instance is used to build up the TypeString by passing
9929 /// it by reference between functions that append to it.
9930 typedef llvm::SmallString<128> SmallStringEnc;
9931 
9932 /// TypeStringCache caches the meta encodings of Types.
9933 ///
9934 /// The reason for caching TypeStrings is two fold:
9935 ///   1. To cache a type's encoding for later uses;
9936 ///   2. As a means to break recursive member type inclusion.
9937 ///
9938 /// A cache Entry can have a Status of:
9939 ///   NonRecursive:   The type encoding is not recursive;
9940 ///   Recursive:      The type encoding is recursive;
9941 ///   Incomplete:     An incomplete TypeString;
9942 ///   IncompleteUsed: An incomplete TypeString that has been used in a
9943 ///                   Recursive type encoding.
9944 ///
9945 /// A NonRecursive entry will have all of its sub-members expanded as fully
9946 /// as possible. Whilst it may contain types which are recursive, the type
9947 /// itself is not recursive and thus its encoding may be safely used whenever
9948 /// the type is encountered.
9949 ///
9950 /// A Recursive entry will have all of its sub-members expanded as fully as
9951 /// possible. The type itself is recursive and it may contain other types which
9952 /// are recursive. The Recursive encoding must not be used during the expansion
9953 /// of a recursive type's recursive branch. For simplicity the code uses
9954 /// IncompleteCount to reject all usage of Recursive encodings for member types.
9955 ///
9956 /// An Incomplete entry is always a RecordType and only encodes its
9957 /// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
9958 /// are placed into the cache during type expansion as a means to identify and
9959 /// handle recursive inclusion of types as sub-members. If there is recursion
9960 /// the entry becomes IncompleteUsed.
9961 ///
9962 /// During the expansion of a RecordType's members:
9963 ///
9964 ///   If the cache contains a NonRecursive encoding for the member type, the
9965 ///   cached encoding is used;
9966 ///
9967 ///   If the cache contains a Recursive encoding for the member type, the
9968 ///   cached encoding is 'Swapped' out, as it may be incorrect, and...
9969 ///
9970 ///   If the member is a RecordType, an Incomplete encoding is placed into the
9971 ///   cache to break potential recursive inclusion of itself as a sub-member;
9972 ///
9973 ///   Once a member RecordType has been expanded, its temporary incomplete
9974 ///   entry is removed from the cache. If a Recursive encoding was swapped out
9975 ///   it is swapped back in;
9976 ///
9977 ///   If an incomplete entry is used to expand a sub-member, the incomplete
9978 ///   entry is marked as IncompleteUsed. The cache keeps count of how many
9979 ///   IncompleteUsed entries it currently contains in IncompleteUsedCount;
9980 ///
9981 ///   If a member's encoding is found to be a NonRecursive or Recursive viz:
9982 ///   IncompleteUsedCount==0, the member's encoding is added to the cache.
9983 ///   Else the member is part of a recursive type and thus the recursion has
9984 ///   been exited too soon for the encoding to be correct for the member.
9985 ///
9986 class TypeStringCache {
9987   enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
9988   struct Entry {
9989     std::string Str;     // The encoded TypeString for the type.
9990     enum Status State;   // Information about the encoding in 'Str'.
9991     std::string Swapped; // A temporary place holder for a Recursive encoding
9992                          // during the expansion of RecordType's members.
9993   };
9994   std::map<const IdentifierInfo *, struct Entry> Map;
9995   unsigned IncompleteCount;     // Number of Incomplete entries in the Map.
9996   unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
9997 public:
9998   TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
9999   void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
10000   bool removeIncomplete(const IdentifierInfo *ID);
10001   void addIfComplete(const IdentifierInfo *ID, StringRef Str,
10002                      bool IsRecursive);
10003   StringRef lookupStr(const IdentifierInfo *ID);
10004 };
10005 
10006 /// TypeString encodings for enum & union fields must be order.
10007 /// FieldEncoding is a helper for this ordering process.
10008 class FieldEncoding {
10009   bool HasName;
10010   std::string Enc;
10011 public:
10012   FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
10013   StringRef str() { return Enc; }
10014   bool operator<(const FieldEncoding &rhs) const {
10015     if (HasName != rhs.HasName) return HasName;
10016     return Enc < rhs.Enc;
10017   }
10018 };
10019 
10020 class XCoreABIInfo : public DefaultABIInfo {
10021 public:
10022   XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
10023   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
10024                     QualType Ty) const override;
10025 };
10026 
10027 class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
10028   mutable TypeStringCache TSC;
10029   void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
10030                     const CodeGen::CodeGenModule &M) const;
10031 
10032 public:
10033   XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
10034       : TargetCodeGenInfo(std::make_unique<XCoreABIInfo>(CGT)) {}
10035   void emitTargetMetadata(CodeGen::CodeGenModule &CGM,
10036                           const llvm::MapVector<GlobalDecl, StringRef>
10037                               &MangledDeclNames) const override;
10038 };
10039 
10040 } // End anonymous namespace.
10041 
10042 // TODO: this implementation is likely now redundant with the default
10043 // EmitVAArg.
10044 Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
10045                                 QualType Ty) const {
10046   CGBuilderTy &Builder = CGF.Builder;
10047 
10048   // Get the VAList.
10049   CharUnits SlotSize = CharUnits::fromQuantity(4);
10050   Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
10051 
10052   // Handle the argument.
10053   ABIArgInfo AI = classifyArgumentType(Ty);
10054   CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
10055   llvm::Type *ArgTy = CGT.ConvertType(Ty);
10056   if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
10057     AI.setCoerceToType(ArgTy);
10058   llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
10059 
10060   Address Val = Address::invalid();
10061   CharUnits ArgSize = CharUnits::Zero();
10062   switch (AI.getKind()) {
10063   case ABIArgInfo::Expand:
10064   case ABIArgInfo::CoerceAndExpand:
10065   case ABIArgInfo::InAlloca:
10066     llvm_unreachable("Unsupported ABI kind for va_arg");
10067   case ABIArgInfo::Ignore:
10068     Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
10069     ArgSize = CharUnits::Zero();
10070     break;
10071   case ABIArgInfo::Extend:
10072   case ABIArgInfo::Direct:
10073     Val = Builder.CreateBitCast(AP, ArgPtrTy);
10074     ArgSize = CharUnits::fromQuantity(
10075                        getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
10076     ArgSize = ArgSize.alignTo(SlotSize);
10077     break;
10078   case ABIArgInfo::Indirect:
10079   case ABIArgInfo::IndirectAliased:
10080     Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
10081     Val = Address(Builder.CreateLoad(Val), TypeAlign);
10082     ArgSize = SlotSize;
10083     break;
10084   }
10085 
10086   // Increment the VAList.
10087   if (!ArgSize.isZero()) {
10088     Address APN = Builder.CreateConstInBoundsByteGEP(AP, ArgSize);
10089     Builder.CreateStore(APN.getPointer(), VAListAddr);
10090   }
10091 
10092   return Val;
10093 }
10094 
10095 /// During the expansion of a RecordType, an incomplete TypeString is placed
10096 /// into the cache as a means to identify and break recursion.
10097 /// If there is a Recursive encoding in the cache, it is swapped out and will
10098 /// be reinserted by removeIncomplete().
10099 /// All other types of encoding should have been used rather than arriving here.
10100 void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
10101                                     std::string StubEnc) {
10102   if (!ID)
10103     return;
10104   Entry &E = Map[ID];
10105   assert( (E.Str.empty() || E.State == Recursive) &&
10106          "Incorrectly use of addIncomplete");
10107   assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
10108   E.Swapped.swap(E.Str); // swap out the Recursive
10109   E.Str.swap(StubEnc);
10110   E.State = Incomplete;
10111   ++IncompleteCount;
10112 }
10113 
10114 /// Once the RecordType has been expanded, the temporary incomplete TypeString
10115 /// must be removed from the cache.
10116 /// If a Recursive was swapped out by addIncomplete(), it will be replaced.
10117 /// Returns true if the RecordType was defined recursively.
10118 bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
10119   if (!ID)
10120     return false;
10121   auto I = Map.find(ID);
10122   assert(I != Map.end() && "Entry not present");
10123   Entry &E = I->second;
10124   assert( (E.State == Incomplete ||
10125            E.State == IncompleteUsed) &&
10126          "Entry must be an incomplete type");
10127   bool IsRecursive = false;
10128   if (E.State == IncompleteUsed) {
10129     // We made use of our Incomplete encoding, thus we are recursive.
10130     IsRecursive = true;
10131     --IncompleteUsedCount;
10132   }
10133   if (E.Swapped.empty())
10134     Map.erase(I);
10135   else {
10136     // Swap the Recursive back.
10137     E.Swapped.swap(E.Str);
10138     E.Swapped.clear();
10139     E.State = Recursive;
10140   }
10141   --IncompleteCount;
10142   return IsRecursive;
10143 }
10144 
10145 /// Add the encoded TypeString to the cache only if it is NonRecursive or
10146 /// Recursive (viz: all sub-members were expanded as fully as possible).
10147 void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
10148                                     bool IsRecursive) {
10149   if (!ID || IncompleteUsedCount)
10150     return; // No key or it is is an incomplete sub-type so don't add.
10151   Entry &E = Map[ID];
10152   if (IsRecursive && !E.Str.empty()) {
10153     assert(E.State==Recursive && E.Str.size() == Str.size() &&
10154            "This is not the same Recursive entry");
10155     // The parent container was not recursive after all, so we could have used
10156     // this Recursive sub-member entry after all, but we assumed the worse when
10157     // we started viz: IncompleteCount!=0.
10158     return;
10159   }
10160   assert(E.Str.empty() && "Entry already present");
10161   E.Str = Str.str();
10162   E.State = IsRecursive? Recursive : NonRecursive;
10163 }
10164 
10165 /// Return a cached TypeString encoding for the ID. If there isn't one, or we
10166 /// are recursively expanding a type (IncompleteCount != 0) and the cached
10167 /// encoding is Recursive, return an empty StringRef.
10168 StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
10169   if (!ID)
10170     return StringRef();   // We have no key.
10171   auto I = Map.find(ID);
10172   if (I == Map.end())
10173     return StringRef();   // We have no encoding.
10174   Entry &E = I->second;
10175   if (E.State == Recursive && IncompleteCount)
10176     return StringRef();   // We don't use Recursive encodings for member types.
10177 
10178   if (E.State == Incomplete) {
10179     // The incomplete type is being used to break out of recursion.
10180     E.State = IncompleteUsed;
10181     ++IncompleteUsedCount;
10182   }
10183   return E.Str;
10184 }
10185 
10186 /// The XCore ABI includes a type information section that communicates symbol
10187 /// type information to the linker. The linker uses this information to verify
10188 /// safety/correctness of things such as array bound and pointers et al.
10189 /// The ABI only requires C (and XC) language modules to emit TypeStrings.
10190 /// This type information (TypeString) is emitted into meta data for all global
10191 /// symbols: definitions, declarations, functions & variables.
10192 ///
10193 /// The TypeString carries type, qualifier, name, size & value details.
10194 /// Please see 'Tools Development Guide' section 2.16.2 for format details:
10195 /// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
10196 /// The output is tested by test/CodeGen/xcore-stringtype.c.
10197 ///
10198 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
10199                           const CodeGen::CodeGenModule &CGM,
10200                           TypeStringCache &TSC);
10201 
10202 /// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
10203 void XCoreTargetCodeGenInfo::emitTargetMD(
10204     const Decl *D, llvm::GlobalValue *GV,
10205     const CodeGen::CodeGenModule &CGM) const {
10206   SmallStringEnc Enc;
10207   if (getTypeString(Enc, D, CGM, TSC)) {
10208     llvm::LLVMContext &Ctx = CGM.getModule().getContext();
10209     llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
10210                                 llvm::MDString::get(Ctx, Enc.str())};
10211     llvm::NamedMDNode *MD =
10212       CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
10213     MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
10214   }
10215 }
10216 
10217 void XCoreTargetCodeGenInfo::emitTargetMetadata(
10218     CodeGen::CodeGenModule &CGM,
10219     const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames) const {
10220   // Warning, new MangledDeclNames may be appended within this loop.
10221   // We rely on MapVector insertions adding new elements to the end
10222   // of the container.
10223   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
10224     auto Val = *(MangledDeclNames.begin() + I);
10225     llvm::GlobalValue *GV = CGM.GetGlobalValue(Val.second);
10226     if (GV) {
10227       const Decl *D = Val.first.getDecl()->getMostRecentDecl();
10228       emitTargetMD(D, GV, CGM);
10229     }
10230   }
10231 }
10232 
10233 //===----------------------------------------------------------------------===//
10234 // Base ABI and target codegen info implementation common between SPIR and
10235 // SPIR-V.
10236 //===----------------------------------------------------------------------===//
10237 
10238 namespace {
10239 class CommonSPIRABIInfo : public DefaultABIInfo {
10240 public:
10241   CommonSPIRABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) { setCCs(); }
10242 
10243 private:
10244   void setCCs();
10245 };
10246 
10247 class SPIRVABIInfo : public CommonSPIRABIInfo {
10248 public:
10249   SPIRVABIInfo(CodeGenTypes &CGT) : CommonSPIRABIInfo(CGT) {}
10250   void computeInfo(CGFunctionInfo &FI) const override;
10251 
10252 private:
10253   ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
10254 };
10255 } // end anonymous namespace
10256 namespace {
10257 class CommonSPIRTargetCodeGenInfo : public TargetCodeGenInfo {
10258 public:
10259   CommonSPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
10260       : TargetCodeGenInfo(std::make_unique<CommonSPIRABIInfo>(CGT)) {}
10261   CommonSPIRTargetCodeGenInfo(std::unique_ptr<ABIInfo> ABIInfo)
10262       : TargetCodeGenInfo(std::move(ABIInfo)) {}
10263 
10264   LangAS getASTAllocaAddressSpace() const override {
10265     return getLangASFromTargetAS(
10266         getABIInfo().getDataLayout().getAllocaAddrSpace());
10267   }
10268 
10269   unsigned getOpenCLKernelCallingConv() const override;
10270 };
10271 class SPIRVTargetCodeGenInfo : public CommonSPIRTargetCodeGenInfo {
10272 public:
10273   SPIRVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
10274       : CommonSPIRTargetCodeGenInfo(std::make_unique<SPIRVABIInfo>(CGT)) {}
10275   void setCUDAKernelCallingConvention(const FunctionType *&FT) const override;
10276 };
10277 } // End anonymous namespace.
10278 
10279 void CommonSPIRABIInfo::setCCs() {
10280   assert(getRuntimeCC() == llvm::CallingConv::C);
10281   RuntimeCC = llvm::CallingConv::SPIR_FUNC;
10282 }
10283 
10284 ABIArgInfo SPIRVABIInfo::classifyKernelArgumentType(QualType Ty) const {
10285   if (getContext().getLangOpts().HIP) {
10286     // Coerce pointer arguments with default address space to CrossWorkGroup
10287     // pointers for HIPSPV. When the language mode is HIP, the SPIRTargetInfo
10288     // maps cuda_device to SPIR-V's CrossWorkGroup address space.
10289     llvm::Type *LTy = CGT.ConvertType(Ty);
10290     auto DefaultAS = getContext().getTargetAddressSpace(LangAS::Default);
10291     auto GlobalAS = getContext().getTargetAddressSpace(LangAS::cuda_device);
10292     auto *PtrTy = llvm::dyn_cast<llvm::PointerType>(LTy);
10293     if (PtrTy && PtrTy->getAddressSpace() == DefaultAS) {
10294       LTy = llvm::PointerType::getWithSamePointeeType(PtrTy, GlobalAS);
10295       return ABIArgInfo::getDirect(LTy, 0, nullptr, false);
10296     }
10297   }
10298   return classifyArgumentType(Ty);
10299 }
10300 
10301 void SPIRVABIInfo::computeInfo(CGFunctionInfo &FI) const {
10302   // The logic is same as in DefaultABIInfo with an exception on the kernel
10303   // arguments handling.
10304   llvm::CallingConv::ID CC = FI.getCallingConvention();
10305 
10306   if (!getCXXABI().classifyReturnType(FI))
10307     FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
10308 
10309   for (auto &I : FI.arguments()) {
10310     if (CC == llvm::CallingConv::SPIR_KERNEL) {
10311       I.info = classifyKernelArgumentType(I.type);
10312     } else {
10313       I.info = classifyArgumentType(I.type);
10314     }
10315   }
10316 }
10317 
10318 namespace clang {
10319 namespace CodeGen {
10320 void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) {
10321   if (CGM.getTarget().getTriple().isSPIRV())
10322     SPIRVABIInfo(CGM.getTypes()).computeInfo(FI);
10323   else
10324     CommonSPIRABIInfo(CGM.getTypes()).computeInfo(FI);
10325 }
10326 }
10327 }
10328 
10329 unsigned CommonSPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
10330   return llvm::CallingConv::SPIR_KERNEL;
10331 }
10332 
10333 void SPIRVTargetCodeGenInfo::setCUDAKernelCallingConvention(
10334     const FunctionType *&FT) const {
10335   // Convert HIP kernels to SPIR-V kernels.
10336   if (getABIInfo().getContext().getLangOpts().HIP) {
10337     FT = getABIInfo().getContext().adjustFunctionType(
10338         FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel));
10339     return;
10340   }
10341 }
10342 
10343 static bool appendType(SmallStringEnc &Enc, QualType QType,
10344                        const CodeGen::CodeGenModule &CGM,
10345                        TypeStringCache &TSC);
10346 
10347 /// Helper function for appendRecordType().
10348 /// Builds a SmallVector containing the encoded field types in declaration
10349 /// order.
10350 static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
10351                              const RecordDecl *RD,
10352                              const CodeGen::CodeGenModule &CGM,
10353                              TypeStringCache &TSC) {
10354   for (const auto *Field : RD->fields()) {
10355     SmallStringEnc Enc;
10356     Enc += "m(";
10357     Enc += Field->getName();
10358     Enc += "){";
10359     if (Field->isBitField()) {
10360       Enc += "b(";
10361       llvm::raw_svector_ostream OS(Enc);
10362       OS << Field->getBitWidthValue(CGM.getContext());
10363       Enc += ':';
10364     }
10365     if (!appendType(Enc, Field->getType(), CGM, TSC))
10366       return false;
10367     if (Field->isBitField())
10368       Enc += ')';
10369     Enc += '}';
10370     FE.emplace_back(!Field->getName().empty(), Enc);
10371   }
10372   return true;
10373 }
10374 
10375 /// Appends structure and union types to Enc and adds encoding to cache.
10376 /// Recursively calls appendType (via extractFieldType) for each field.
10377 /// Union types have their fields ordered according to the ABI.
10378 static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
10379                              const CodeGen::CodeGenModule &CGM,
10380                              TypeStringCache &TSC, const IdentifierInfo *ID) {
10381   // Append the cached TypeString if we have one.
10382   StringRef TypeString = TSC.lookupStr(ID);
10383   if (!TypeString.empty()) {
10384     Enc += TypeString;
10385     return true;
10386   }
10387 
10388   // Start to emit an incomplete TypeString.
10389   size_t Start = Enc.size();
10390   Enc += (RT->isUnionType()? 'u' : 's');
10391   Enc += '(';
10392   if (ID)
10393     Enc += ID->getName();
10394   Enc += "){";
10395 
10396   // We collect all encoded fields and order as necessary.
10397   bool IsRecursive = false;
10398   const RecordDecl *RD = RT->getDecl()->getDefinition();
10399   if (RD && !RD->field_empty()) {
10400     // An incomplete TypeString stub is placed in the cache for this RecordType
10401     // so that recursive calls to this RecordType will use it whilst building a
10402     // complete TypeString for this RecordType.
10403     SmallVector<FieldEncoding, 16> FE;
10404     std::string StubEnc(Enc.substr(Start).str());
10405     StubEnc += '}';  // StubEnc now holds a valid incomplete TypeString.
10406     TSC.addIncomplete(ID, std::move(StubEnc));
10407     if (!extractFieldType(FE, RD, CGM, TSC)) {
10408       (void) TSC.removeIncomplete(ID);
10409       return false;
10410     }
10411     IsRecursive = TSC.removeIncomplete(ID);
10412     // The ABI requires unions to be sorted but not structures.
10413     // See FieldEncoding::operator< for sort algorithm.
10414     if (RT->isUnionType())
10415       llvm::sort(FE);
10416     // We can now complete the TypeString.
10417     unsigned E = FE.size();
10418     for (unsigned I = 0; I != E; ++I) {
10419       if (I)
10420         Enc += ',';
10421       Enc += FE[I].str();
10422     }
10423   }
10424   Enc += '}';
10425   TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
10426   return true;
10427 }
10428 
10429 /// Appends enum types to Enc and adds the encoding to the cache.
10430 static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
10431                            TypeStringCache &TSC,
10432                            const IdentifierInfo *ID) {
10433   // Append the cached TypeString if we have one.
10434   StringRef TypeString = TSC.lookupStr(ID);
10435   if (!TypeString.empty()) {
10436     Enc += TypeString;
10437     return true;
10438   }
10439 
10440   size_t Start = Enc.size();
10441   Enc += "e(";
10442   if (ID)
10443     Enc += ID->getName();
10444   Enc += "){";
10445 
10446   // We collect all encoded enumerations and order them alphanumerically.
10447   if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
10448     SmallVector<FieldEncoding, 16> FE;
10449     for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
10450          ++I) {
10451       SmallStringEnc EnumEnc;
10452       EnumEnc += "m(";
10453       EnumEnc += I->getName();
10454       EnumEnc += "){";
10455       I->getInitVal().toString(EnumEnc);
10456       EnumEnc += '}';
10457       FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
10458     }
10459     llvm::sort(FE);
10460     unsigned E = FE.size();
10461     for (unsigned I = 0; I != E; ++I) {
10462       if (I)
10463         Enc += ',';
10464       Enc += FE[I].str();
10465     }
10466   }
10467   Enc += '}';
10468   TSC.addIfComplete(ID, Enc.substr(Start), false);
10469   return true;
10470 }
10471 
10472 /// Appends type's qualifier to Enc.
10473 /// This is done prior to appending the type's encoding.
10474 static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
10475   // Qualifiers are emitted in alphabetical order.
10476   static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
10477   int Lookup = 0;
10478   if (QT.isConstQualified())
10479     Lookup += 1<<0;
10480   if (QT.isRestrictQualified())
10481     Lookup += 1<<1;
10482   if (QT.isVolatileQualified())
10483     Lookup += 1<<2;
10484   Enc += Table[Lookup];
10485 }
10486 
10487 /// Appends built-in types to Enc.
10488 static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
10489   const char *EncType;
10490   switch (BT->getKind()) {
10491     case BuiltinType::Void:
10492       EncType = "0";
10493       break;
10494     case BuiltinType::Bool:
10495       EncType = "b";
10496       break;
10497     case BuiltinType::Char_U:
10498       EncType = "uc";
10499       break;
10500     case BuiltinType::UChar:
10501       EncType = "uc";
10502       break;
10503     case BuiltinType::SChar:
10504       EncType = "sc";
10505       break;
10506     case BuiltinType::UShort:
10507       EncType = "us";
10508       break;
10509     case BuiltinType::Short:
10510       EncType = "ss";
10511       break;
10512     case BuiltinType::UInt:
10513       EncType = "ui";
10514       break;
10515     case BuiltinType::Int:
10516       EncType = "si";
10517       break;
10518     case BuiltinType::ULong:
10519       EncType = "ul";
10520       break;
10521     case BuiltinType::Long:
10522       EncType = "sl";
10523       break;
10524     case BuiltinType::ULongLong:
10525       EncType = "ull";
10526       break;
10527     case BuiltinType::LongLong:
10528       EncType = "sll";
10529       break;
10530     case BuiltinType::Float:
10531       EncType = "ft";
10532       break;
10533     case BuiltinType::Double:
10534       EncType = "d";
10535       break;
10536     case BuiltinType::LongDouble:
10537       EncType = "ld";
10538       break;
10539     default:
10540       return false;
10541   }
10542   Enc += EncType;
10543   return true;
10544 }
10545 
10546 /// Appends a pointer encoding to Enc before calling appendType for the pointee.
10547 static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
10548                               const CodeGen::CodeGenModule &CGM,
10549                               TypeStringCache &TSC) {
10550   Enc += "p(";
10551   if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
10552     return false;
10553   Enc += ')';
10554   return true;
10555 }
10556 
10557 /// Appends array encoding to Enc before calling appendType for the element.
10558 static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
10559                             const ArrayType *AT,
10560                             const CodeGen::CodeGenModule &CGM,
10561                             TypeStringCache &TSC, StringRef NoSizeEnc) {
10562   if (AT->getSizeModifier() != ArrayType::Normal)
10563     return false;
10564   Enc += "a(";
10565   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
10566     CAT->getSize().toStringUnsigned(Enc);
10567   else
10568     Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
10569   Enc += ':';
10570   // The Qualifiers should be attached to the type rather than the array.
10571   appendQualifier(Enc, QT);
10572   if (!appendType(Enc, AT->getElementType(), CGM, TSC))
10573     return false;
10574   Enc += ')';
10575   return true;
10576 }
10577 
10578 /// Appends a function encoding to Enc, calling appendType for the return type
10579 /// and the arguments.
10580 static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
10581                              const CodeGen::CodeGenModule &CGM,
10582                              TypeStringCache &TSC) {
10583   Enc += "f{";
10584   if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
10585     return false;
10586   Enc += "}(";
10587   if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
10588     // N.B. we are only interested in the adjusted param types.
10589     auto I = FPT->param_type_begin();
10590     auto E = FPT->param_type_end();
10591     if (I != E) {
10592       do {
10593         if (!appendType(Enc, *I, CGM, TSC))
10594           return false;
10595         ++I;
10596         if (I != E)
10597           Enc += ',';
10598       } while (I != E);
10599       if (FPT->isVariadic())
10600         Enc += ",va";
10601     } else {
10602       if (FPT->isVariadic())
10603         Enc += "va";
10604       else
10605         Enc += '0';
10606     }
10607   }
10608   Enc += ')';
10609   return true;
10610 }
10611 
10612 /// Handles the type's qualifier before dispatching a call to handle specific
10613 /// type encodings.
10614 static bool appendType(SmallStringEnc &Enc, QualType QType,
10615                        const CodeGen::CodeGenModule &CGM,
10616                        TypeStringCache &TSC) {
10617 
10618   QualType QT = QType.getCanonicalType();
10619 
10620   if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
10621     // The Qualifiers should be attached to the type rather than the array.
10622     // Thus we don't call appendQualifier() here.
10623     return appendArrayType(Enc, QT, AT, CGM, TSC, "");
10624 
10625   appendQualifier(Enc, QT);
10626 
10627   if (const BuiltinType *BT = QT->getAs<BuiltinType>())
10628     return appendBuiltinType(Enc, BT);
10629 
10630   if (const PointerType *PT = QT->getAs<PointerType>())
10631     return appendPointerType(Enc, PT, CGM, TSC);
10632 
10633   if (const EnumType *ET = QT->getAs<EnumType>())
10634     return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
10635 
10636   if (const RecordType *RT = QT->getAsStructureType())
10637     return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
10638 
10639   if (const RecordType *RT = QT->getAsUnionType())
10640     return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
10641 
10642   if (const FunctionType *FT = QT->getAs<FunctionType>())
10643     return appendFunctionType(Enc, FT, CGM, TSC);
10644 
10645   return false;
10646 }
10647 
10648 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
10649                           const CodeGen::CodeGenModule &CGM,
10650                           TypeStringCache &TSC) {
10651   if (!D)
10652     return false;
10653 
10654   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10655     if (FD->getLanguageLinkage() != CLanguageLinkage)
10656       return false;
10657     return appendType(Enc, FD->getType(), CGM, TSC);
10658   }
10659 
10660   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
10661     if (VD->getLanguageLinkage() != CLanguageLinkage)
10662       return false;
10663     QualType QT = VD->getType().getCanonicalType();
10664     if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
10665       // Global ArrayTypes are given a size of '*' if the size is unknown.
10666       // The Qualifiers should be attached to the type rather than the array.
10667       // Thus we don't call appendQualifier() here.
10668       return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
10669     }
10670     return appendType(Enc, QT, CGM, TSC);
10671   }
10672   return false;
10673 }
10674 
10675 //===----------------------------------------------------------------------===//
10676 // RISCV ABI Implementation
10677 //===----------------------------------------------------------------------===//
10678 
10679 namespace {
10680 class RISCVABIInfo : public DefaultABIInfo {
10681 private:
10682   // Size of the integer ('x') registers in bits.
10683   unsigned XLen;
10684   // Size of the floating point ('f') registers in bits. Note that the target
10685   // ISA might have a wider FLen than the selected ABI (e.g. an RV32IF target
10686   // with soft float ABI has FLen==0).
10687   unsigned FLen;
10688   static const int NumArgGPRs = 8;
10689   static const int NumArgFPRs = 8;
10690   bool detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
10691                                       llvm::Type *&Field1Ty,
10692                                       CharUnits &Field1Off,
10693                                       llvm::Type *&Field2Ty,
10694                                       CharUnits &Field2Off) const;
10695 
10696 public:
10697   RISCVABIInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, unsigned FLen)
10698       : DefaultABIInfo(CGT), XLen(XLen), FLen(FLen) {}
10699 
10700   // DefaultABIInfo's classifyReturnType and classifyArgumentType are
10701   // non-virtual, but computeInfo is virtual, so we overload it.
10702   void computeInfo(CGFunctionInfo &FI) const override;
10703 
10704   ABIArgInfo classifyArgumentType(QualType Ty, bool IsFixed, int &ArgGPRsLeft,
10705                                   int &ArgFPRsLeft) const;
10706   ABIArgInfo classifyReturnType(QualType RetTy) const;
10707 
10708   Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
10709                     QualType Ty) const override;
10710 
10711   ABIArgInfo extendType(QualType Ty) const;
10712 
10713   bool detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
10714                                 CharUnits &Field1Off, llvm::Type *&Field2Ty,
10715                                 CharUnits &Field2Off, int &NeededArgGPRs,
10716                                 int &NeededArgFPRs) const;
10717   ABIArgInfo coerceAndExpandFPCCEligibleStruct(llvm::Type *Field1Ty,
10718                                                CharUnits Field1Off,
10719                                                llvm::Type *Field2Ty,
10720                                                CharUnits Field2Off) const;
10721 };
10722 } // end anonymous namespace
10723 
10724 void RISCVABIInfo::computeInfo(CGFunctionInfo &FI) const {
10725   QualType RetTy = FI.getReturnType();
10726   if (!getCXXABI().classifyReturnType(FI))
10727     FI.getReturnInfo() = classifyReturnType(RetTy);
10728 
10729   // IsRetIndirect is true if classifyArgumentType indicated the value should
10730   // be passed indirect, or if the type size is a scalar greater than 2*XLen
10731   // and not a complex type with elements <= FLen. e.g. fp128 is passed direct
10732   // in LLVM IR, relying on the backend lowering code to rewrite the argument
10733   // list and pass indirectly on RV32.
10734   bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect;
10735   if (!IsRetIndirect && RetTy->isScalarType() &&
10736       getContext().getTypeSize(RetTy) > (2 * XLen)) {
10737     if (RetTy->isComplexType() && FLen) {
10738       QualType EltTy = RetTy->castAs<ComplexType>()->getElementType();
10739       IsRetIndirect = getContext().getTypeSize(EltTy) > FLen;
10740     } else {
10741       // This is a normal scalar > 2*XLen, such as fp128 on RV32.
10742       IsRetIndirect = true;
10743     }
10744   }
10745 
10746   // We must track the number of GPRs used in order to conform to the RISC-V
10747   // ABI, as integer scalars passed in registers should have signext/zeroext
10748   // when promoted, but are anyext if passed on the stack. As GPR usage is
10749   // different for variadic arguments, we must also track whether we are
10750   // examining a vararg or not.
10751   int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs;
10752   int ArgFPRsLeft = FLen ? NumArgFPRs : 0;
10753   int NumFixedArgs = FI.getNumRequiredArgs();
10754 
10755   int ArgNum = 0;
10756   for (auto &ArgInfo : FI.arguments()) {
10757     bool IsFixed = ArgNum < NumFixedArgs;
10758     ArgInfo.info =
10759         classifyArgumentType(ArgInfo.type, IsFixed, ArgGPRsLeft, ArgFPRsLeft);
10760     ArgNum++;
10761   }
10762 }
10763 
10764 // Returns true if the struct is a potential candidate for the floating point
10765 // calling convention. If this function returns true, the caller is
10766 // responsible for checking that if there is only a single field then that
10767 // field is a float.
10768 bool RISCVABIInfo::detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
10769                                                   llvm::Type *&Field1Ty,
10770                                                   CharUnits &Field1Off,
10771                                                   llvm::Type *&Field2Ty,
10772                                                   CharUnits &Field2Off) const {
10773   bool IsInt = Ty->isIntegralOrEnumerationType();
10774   bool IsFloat = Ty->isRealFloatingType();
10775 
10776   if (IsInt || IsFloat) {
10777     uint64_t Size = getContext().getTypeSize(Ty);
10778     if (IsInt && Size > XLen)
10779       return false;
10780     // Can't be eligible if larger than the FP registers. Half precision isn't
10781     // currently supported on RISC-V and the ABI hasn't been confirmed, so
10782     // default to the integer ABI in that case.
10783     if (IsFloat && (Size > FLen || Size < 32))
10784       return false;
10785     // Can't be eligible if an integer type was already found (int+int pairs
10786     // are not eligible).
10787     if (IsInt && Field1Ty && Field1Ty->isIntegerTy())
10788       return false;
10789     if (!Field1Ty) {
10790       Field1Ty = CGT.ConvertType(Ty);
10791       Field1Off = CurOff;
10792       return true;
10793     }
10794     if (!Field2Ty) {
10795       Field2Ty = CGT.ConvertType(Ty);
10796       Field2Off = CurOff;
10797       return true;
10798     }
10799     return false;
10800   }
10801 
10802   if (auto CTy = Ty->getAs<ComplexType>()) {
10803     if (Field1Ty)
10804       return false;
10805     QualType EltTy = CTy->getElementType();
10806     if (getContext().getTypeSize(EltTy) > FLen)
10807       return false;
10808     Field1Ty = CGT.ConvertType(EltTy);
10809     Field1Off = CurOff;
10810     Field2Ty = Field1Ty;
10811     Field2Off = Field1Off + getContext().getTypeSizeInChars(EltTy);
10812     return true;
10813   }
10814 
10815   if (const ConstantArrayType *ATy = getContext().getAsConstantArrayType(Ty)) {
10816     uint64_t ArraySize = ATy->getSize().getZExtValue();
10817     QualType EltTy = ATy->getElementType();
10818     CharUnits EltSize = getContext().getTypeSizeInChars(EltTy);
10819     for (uint64_t i = 0; i < ArraySize; ++i) {
10820       bool Ret = detectFPCCEligibleStructHelper(EltTy, CurOff, Field1Ty,
10821                                                 Field1Off, Field2Ty, Field2Off);
10822       if (!Ret)
10823         return false;
10824       CurOff += EltSize;
10825     }
10826     return true;
10827   }
10828 
10829   if (const auto *RTy = Ty->getAs<RecordType>()) {
10830     // Structures with either a non-trivial destructor or a non-trivial
10831     // copy constructor are not eligible for the FP calling convention.
10832     if (getRecordArgABI(Ty, CGT.getCXXABI()))
10833       return false;
10834     if (isEmptyRecord(getContext(), Ty, true))
10835       return true;
10836     const RecordDecl *RD = RTy->getDecl();
10837     // Unions aren't eligible unless they're empty (which is caught above).
10838     if (RD->isUnion())
10839       return false;
10840     int ZeroWidthBitFieldCount = 0;
10841     for (const FieldDecl *FD : RD->fields()) {
10842       const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
10843       uint64_t FieldOffInBits = Layout.getFieldOffset(FD->getFieldIndex());
10844       QualType QTy = FD->getType();
10845       if (FD->isBitField()) {
10846         unsigned BitWidth = FD->getBitWidthValue(getContext());
10847         // Allow a bitfield with a type greater than XLen as long as the
10848         // bitwidth is XLen or less.
10849         if (getContext().getTypeSize(QTy) > XLen && BitWidth <= XLen)
10850           QTy = getContext().getIntTypeForBitwidth(XLen, false);
10851         if (BitWidth == 0) {
10852           ZeroWidthBitFieldCount++;
10853           continue;
10854         }
10855       }
10856 
10857       bool Ret = detectFPCCEligibleStructHelper(
10858           QTy, CurOff + getContext().toCharUnitsFromBits(FieldOffInBits),
10859           Field1Ty, Field1Off, Field2Ty, Field2Off);
10860       if (!Ret)
10861         return false;
10862 
10863       // As a quirk of the ABI, zero-width bitfields aren't ignored for fp+fp
10864       // or int+fp structs, but are ignored for a struct with an fp field and
10865       // any number of zero-width bitfields.
10866       if (Field2Ty && ZeroWidthBitFieldCount > 0)
10867         return false;
10868     }
10869     return Field1Ty != nullptr;
10870   }
10871 
10872   return false;
10873 }
10874 
10875 // Determine if a struct is eligible for passing according to the floating
10876 // point calling convention (i.e., when flattened it contains a single fp
10877 // value, fp+fp, or int+fp of appropriate size). If so, NeededArgFPRs and
10878 // NeededArgGPRs are incremented appropriately.
10879 bool RISCVABIInfo::detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
10880                                             CharUnits &Field1Off,
10881                                             llvm::Type *&Field2Ty,
10882                                             CharUnits &Field2Off,
10883                                             int &NeededArgGPRs,
10884                                             int &NeededArgFPRs) const {
10885   Field1Ty = nullptr;
10886   Field2Ty = nullptr;
10887   NeededArgGPRs = 0;
10888   NeededArgFPRs = 0;
10889   bool IsCandidate = detectFPCCEligibleStructHelper(
10890       Ty, CharUnits::Zero(), Field1Ty, Field1Off, Field2Ty, Field2Off);
10891   // Not really a candidate if we have a single int but no float.
10892   if (Field1Ty && !Field2Ty && !Field1Ty->isFloatingPointTy())
10893     return false;
10894   if (!IsCandidate)
10895     return false;
10896   if (Field1Ty && Field1Ty->isFloatingPointTy())
10897     NeededArgFPRs++;
10898   else if (Field1Ty)
10899     NeededArgGPRs++;
10900   if (Field2Ty && Field2Ty->isFloatingPointTy())
10901     NeededArgFPRs++;
10902   else if (Field2Ty)
10903     NeededArgGPRs++;
10904   return true;
10905 }
10906 
10907 // Call getCoerceAndExpand for the two-element flattened struct described by
10908 // Field1Ty, Field1Off, Field2Ty, Field2Off. This method will create an
10909 // appropriate coerceToType and unpaddedCoerceToType.
10910 ABIArgInfo RISCVABIInfo::coerceAndExpandFPCCEligibleStruct(
10911     llvm::Type *Field1Ty, CharUnits Field1Off, llvm::Type *Field2Ty,
10912     CharUnits Field2Off) const {
10913   SmallVector<llvm::Type *, 3> CoerceElts;
10914   SmallVector<llvm::Type *, 2> UnpaddedCoerceElts;
10915   if (!Field1Off.isZero())
10916     CoerceElts.push_back(llvm::ArrayType::get(
10917         llvm::Type::getInt8Ty(getVMContext()), Field1Off.getQuantity()));
10918 
10919   CoerceElts.push_back(Field1Ty);
10920   UnpaddedCoerceElts.push_back(Field1Ty);
10921 
10922   if (!Field2Ty) {
10923     return ABIArgInfo::getCoerceAndExpand(
10924         llvm::StructType::get(getVMContext(), CoerceElts, !Field1Off.isZero()),
10925         UnpaddedCoerceElts[0]);
10926   }
10927 
10928   CharUnits Field2Align =
10929       CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(Field2Ty));
10930   CharUnits Field1End = Field1Off +
10931       CharUnits::fromQuantity(getDataLayout().getTypeStoreSize(Field1Ty));
10932   CharUnits Field2OffNoPadNoPack = Field1End.alignTo(Field2Align);
10933 
10934   CharUnits Padding = CharUnits::Zero();
10935   if (Field2Off > Field2OffNoPadNoPack)
10936     Padding = Field2Off - Field2OffNoPadNoPack;
10937   else if (Field2Off != Field2Align && Field2Off > Field1End)
10938     Padding = Field2Off - Field1End;
10939 
10940   bool IsPacked = !Field2Off.isMultipleOf(Field2Align);
10941 
10942   if (!Padding.isZero())
10943     CoerceElts.push_back(llvm::ArrayType::get(
10944         llvm::Type::getInt8Ty(getVMContext()), Padding.getQuantity()));
10945 
10946   CoerceElts.push_back(Field2Ty);
10947   UnpaddedCoerceElts.push_back(Field2Ty);
10948 
10949   auto CoerceToType =
10950       llvm::StructType::get(getVMContext(), CoerceElts, IsPacked);
10951   auto UnpaddedCoerceToType =
10952       llvm::StructType::get(getVMContext(), UnpaddedCoerceElts, IsPacked);
10953 
10954   return ABIArgInfo::getCoerceAndExpand(CoerceToType, UnpaddedCoerceToType);
10955 }
10956 
10957 ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, bool IsFixed,
10958                                               int &ArgGPRsLeft,
10959                                               int &ArgFPRsLeft) const {
10960   assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow");
10961   Ty = useFirstFieldIfTransparentUnion(Ty);
10962 
10963   // Structures with either a non-trivial destructor or a non-trivial
10964   // copy constructor are always passed indirectly.
10965   if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
10966     if (ArgGPRsLeft)
10967       ArgGPRsLeft -= 1;
10968     return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
10969                                            CGCXXABI::RAA_DirectInMemory);
10970   }
10971 
10972   // Ignore empty structs/unions.
10973   if (isEmptyRecord(getContext(), Ty, true))
10974     return ABIArgInfo::getIgnore();
10975 
10976   uint64_t Size = getContext().getTypeSize(Ty);
10977 
10978   // Pass floating point values via FPRs if possible.
10979   if (IsFixed && Ty->isFloatingType() && !Ty->isComplexType() &&
10980       FLen >= Size && ArgFPRsLeft) {
10981     ArgFPRsLeft--;
10982     return ABIArgInfo::getDirect();
10983   }
10984 
10985   // Complex types for the hard float ABI must be passed direct rather than
10986   // using CoerceAndExpand.
10987   if (IsFixed && Ty->isComplexType() && FLen && ArgFPRsLeft >= 2) {
10988     QualType EltTy = Ty->castAs<ComplexType>()->getElementType();
10989     if (getContext().getTypeSize(EltTy) <= FLen) {
10990       ArgFPRsLeft -= 2;
10991       return ABIArgInfo::getDirect();
10992     }
10993   }
10994 
10995   if (IsFixed && FLen && Ty->isStructureOrClassType()) {
10996     llvm::Type *Field1Ty = nullptr;
10997     llvm::Type *Field2Ty = nullptr;
10998     CharUnits Field1Off = CharUnits::Zero();
10999     CharUnits Field2Off = CharUnits::Zero();
11000     int NeededArgGPRs = 0;
11001     int NeededArgFPRs = 0;
11002     bool IsCandidate =
11003         detectFPCCEligibleStruct(Ty, Field1Ty, Field1Off, Field2Ty, Field2Off,
11004                                  NeededArgGPRs, NeededArgFPRs);
11005     if (IsCandidate && NeededArgGPRs <= ArgGPRsLeft &&
11006         NeededArgFPRs <= ArgFPRsLeft) {
11007       ArgGPRsLeft -= NeededArgGPRs;
11008       ArgFPRsLeft -= NeededArgFPRs;
11009       return coerceAndExpandFPCCEligibleStruct(Field1Ty, Field1Off, Field2Ty,
11010                                                Field2Off);
11011     }
11012   }
11013 
11014   uint64_t NeededAlign = getContext().getTypeAlign(Ty);
11015   bool MustUseStack = false;
11016   // Determine the number of GPRs needed to pass the current argument
11017   // according to the ABI. 2*XLen-aligned varargs are passed in "aligned"
11018   // register pairs, so may consume 3 registers.
11019   int NeededArgGPRs = 1;
11020   if (!IsFixed && NeededAlign == 2 * XLen)
11021     NeededArgGPRs = 2 + (ArgGPRsLeft % 2);
11022   else if (Size > XLen && Size <= 2 * XLen)
11023     NeededArgGPRs = 2;
11024 
11025   if (NeededArgGPRs > ArgGPRsLeft) {
11026     MustUseStack = true;
11027     NeededArgGPRs = ArgGPRsLeft;
11028   }
11029 
11030   ArgGPRsLeft -= NeededArgGPRs;
11031 
11032   if (!isAggregateTypeForABI(Ty) && !Ty->isVectorType()) {
11033     // Treat an enum type as its underlying type.
11034     if (const EnumType *EnumTy = Ty->getAs<EnumType>())
11035       Ty = EnumTy->getDecl()->getIntegerType();
11036 
11037     // All integral types are promoted to XLen width, unless passed on the
11038     // stack.
11039     if (Size < XLen && Ty->isIntegralOrEnumerationType() && !MustUseStack) {
11040       return extendType(Ty);
11041     }
11042 
11043     if (const auto *EIT = Ty->getAs<BitIntType>()) {
11044       if (EIT->getNumBits() < XLen && !MustUseStack)
11045         return extendType(Ty);
11046       if (EIT->getNumBits() > 128 ||
11047           (!getContext().getTargetInfo().hasInt128Type() &&
11048            EIT->getNumBits() > 64))
11049         return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
11050     }
11051 
11052     return ABIArgInfo::getDirect();
11053   }
11054 
11055   // Aggregates which are <= 2*XLen will be passed in registers if possible,
11056   // so coerce to integers.
11057   if (Size <= 2 * XLen) {
11058     unsigned Alignment = getContext().getTypeAlign(Ty);
11059 
11060     // Use a single XLen int if possible, 2*XLen if 2*XLen alignment is
11061     // required, and a 2-element XLen array if only XLen alignment is required.
11062     if (Size <= XLen) {
11063       return ABIArgInfo::getDirect(
11064           llvm::IntegerType::get(getVMContext(), XLen));
11065     } else if (Alignment == 2 * XLen) {
11066       return ABIArgInfo::getDirect(
11067           llvm::IntegerType::get(getVMContext(), 2 * XLen));
11068     } else {
11069       return ABIArgInfo::getDirect(llvm::ArrayType::get(
11070           llvm::IntegerType::get(getVMContext(), XLen), 2));
11071     }
11072   }
11073   return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
11074 }
11075 
11076 ABIArgInfo RISCVABIInfo::classifyReturnType(QualType RetTy) const {
11077   if (RetTy->isVoidType())
11078     return ABIArgInfo::getIgnore();
11079 
11080   int ArgGPRsLeft = 2;
11081   int ArgFPRsLeft = FLen ? 2 : 0;
11082 
11083   // The rules for return and argument types are the same, so defer to
11084   // classifyArgumentType.
11085   return classifyArgumentType(RetTy, /*IsFixed=*/true, ArgGPRsLeft,
11086                               ArgFPRsLeft);
11087 }
11088 
11089 Address RISCVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
11090                                 QualType Ty) const {
11091   CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8);
11092 
11093   // Empty records are ignored for parameter passing purposes.
11094   if (isEmptyRecord(getContext(), Ty, true)) {
11095     Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
11096     Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
11097     return Addr;
11098   }
11099 
11100   auto TInfo = getContext().getTypeInfoInChars(Ty);
11101 
11102   // Arguments bigger than 2*Xlen bytes are passed indirectly.
11103   bool IsIndirect = TInfo.Width > 2 * SlotSize;
11104 
11105   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TInfo,
11106                           SlotSize, /*AllowHigherAlign=*/true);
11107 }
11108 
11109 ABIArgInfo RISCVABIInfo::extendType(QualType Ty) const {
11110   int TySize = getContext().getTypeSize(Ty);
11111   // RV64 ABI requires unsigned 32 bit integers to be sign extended.
11112   if (XLen == 64 && Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
11113     return ABIArgInfo::getSignExtend(Ty);
11114   return ABIArgInfo::getExtend(Ty);
11115 }
11116 
11117 namespace {
11118 class RISCVTargetCodeGenInfo : public TargetCodeGenInfo {
11119 public:
11120   RISCVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen,
11121                          unsigned FLen)
11122       : TargetCodeGenInfo(std::make_unique<RISCVABIInfo>(CGT, XLen, FLen)) {}
11123 
11124   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
11125                            CodeGen::CodeGenModule &CGM) const override {
11126     const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
11127     if (!FD) return;
11128 
11129     const auto *Attr = FD->getAttr<RISCVInterruptAttr>();
11130     if (!Attr)
11131       return;
11132 
11133     const char *Kind;
11134     switch (Attr->getInterrupt()) {
11135     case RISCVInterruptAttr::user: Kind = "user"; break;
11136     case RISCVInterruptAttr::supervisor: Kind = "supervisor"; break;
11137     case RISCVInterruptAttr::machine: Kind = "machine"; break;
11138     }
11139 
11140     auto *Fn = cast<llvm::Function>(GV);
11141 
11142     Fn->addFnAttr("interrupt", Kind);
11143   }
11144 };
11145 } // namespace
11146 
11147 //===----------------------------------------------------------------------===//
11148 // VE ABI Implementation.
11149 //
11150 namespace {
11151 class VEABIInfo : public DefaultABIInfo {
11152 public:
11153   VEABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
11154 
11155 private:
11156   ABIArgInfo classifyReturnType(QualType RetTy) const;
11157   ABIArgInfo classifyArgumentType(QualType RetTy) const;
11158   void computeInfo(CGFunctionInfo &FI) const override;
11159 };
11160 } // end anonymous namespace
11161 
11162 ABIArgInfo VEABIInfo::classifyReturnType(QualType Ty) const {
11163   if (Ty->isAnyComplexType())
11164     return ABIArgInfo::getDirect();
11165   uint64_t Size = getContext().getTypeSize(Ty);
11166   if (Size < 64 && Ty->isIntegerType())
11167     return ABIArgInfo::getExtend(Ty);
11168   return DefaultABIInfo::classifyReturnType(Ty);
11169 }
11170 
11171 ABIArgInfo VEABIInfo::classifyArgumentType(QualType Ty) const {
11172   if (Ty->isAnyComplexType())
11173     return ABIArgInfo::getDirect();
11174   uint64_t Size = getContext().getTypeSize(Ty);
11175   if (Size < 64 && Ty->isIntegerType())
11176     return ABIArgInfo::getExtend(Ty);
11177   return DefaultABIInfo::classifyArgumentType(Ty);
11178 }
11179 
11180 void VEABIInfo::computeInfo(CGFunctionInfo &FI) const {
11181   FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
11182   for (auto &Arg : FI.arguments())
11183     Arg.info = classifyArgumentType(Arg.type);
11184 }
11185 
11186 namespace {
11187 class VETargetCodeGenInfo : public TargetCodeGenInfo {
11188 public:
11189   VETargetCodeGenInfo(CodeGenTypes &CGT)
11190       : TargetCodeGenInfo(std::make_unique<VEABIInfo>(CGT)) {}
11191   // VE ABI requires the arguments of variadic and prototype-less functions
11192   // are passed in both registers and memory.
11193   bool isNoProtoCallVariadic(const CallArgList &args,
11194                              const FunctionNoProtoType *fnType) const override {
11195     return true;
11196   }
11197 };
11198 } // end anonymous namespace
11199 
11200 //===----------------------------------------------------------------------===//
11201 // Driver code
11202 //===----------------------------------------------------------------------===//
11203 
11204 bool CodeGenModule::supportsCOMDAT() const {
11205   return getTriple().supportsCOMDAT();
11206 }
11207 
11208 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
11209   if (TheTargetCodeGenInfo)
11210     return *TheTargetCodeGenInfo;
11211 
11212   // Helper to set the unique_ptr while still keeping the return value.
11213   auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
11214     this->TheTargetCodeGenInfo.reset(P);
11215     return *P;
11216   };
11217 
11218   const llvm::Triple &Triple = getTarget().getTriple();
11219   switch (Triple.getArch()) {
11220   default:
11221     return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
11222 
11223   case llvm::Triple::le32:
11224     return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
11225   case llvm::Triple::m68k:
11226     return SetCGInfo(new M68kTargetCodeGenInfo(Types));
11227   case llvm::Triple::mips:
11228   case llvm::Triple::mipsel:
11229     if (Triple.getOS() == llvm::Triple::NaCl)
11230       return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
11231     return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
11232 
11233   case llvm::Triple::mips64:
11234   case llvm::Triple::mips64el:
11235     return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
11236 
11237   case llvm::Triple::avr:
11238     return SetCGInfo(new AVRTargetCodeGenInfo(Types));
11239 
11240   case llvm::Triple::aarch64:
11241   case llvm::Triple::aarch64_32:
11242   case llvm::Triple::aarch64_be: {
11243     AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
11244     if (getTarget().getABI() == "darwinpcs")
11245       Kind = AArch64ABIInfo::DarwinPCS;
11246     else if (Triple.isOSWindows())
11247       return SetCGInfo(
11248           new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64));
11249 
11250     return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
11251   }
11252 
11253   case llvm::Triple::wasm32:
11254   case llvm::Triple::wasm64: {
11255     WebAssemblyABIInfo::ABIKind Kind = WebAssemblyABIInfo::MVP;
11256     if (getTarget().getABI() == "experimental-mv")
11257       Kind = WebAssemblyABIInfo::ExperimentalMV;
11258     return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types, Kind));
11259   }
11260 
11261   case llvm::Triple::arm:
11262   case llvm::Triple::armeb:
11263   case llvm::Triple::thumb:
11264   case llvm::Triple::thumbeb: {
11265     if (Triple.getOS() == llvm::Triple::Win32) {
11266       return SetCGInfo(
11267           new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
11268     }
11269 
11270     ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
11271     StringRef ABIStr = getTarget().getABI();
11272     if (ABIStr == "apcs-gnu")
11273       Kind = ARMABIInfo::APCS;
11274     else if (ABIStr == "aapcs16")
11275       Kind = ARMABIInfo::AAPCS16_VFP;
11276     else if (CodeGenOpts.FloatABI == "hard" ||
11277              (CodeGenOpts.FloatABI != "soft" &&
11278               (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
11279                Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
11280                Triple.getEnvironment() == llvm::Triple::EABIHF)))
11281       Kind = ARMABIInfo::AAPCS_VFP;
11282 
11283     return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
11284   }
11285 
11286   case llvm::Triple::ppc: {
11287     if (Triple.isOSAIX())
11288       return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ false));
11289 
11290     bool IsSoftFloat =
11291         CodeGenOpts.FloatABI == "soft" || getTarget().hasFeature("spe");
11292     bool RetSmallStructInRegABI =
11293         PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
11294     return SetCGInfo(
11295         new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI));
11296   }
11297   case llvm::Triple::ppcle: {
11298     bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
11299     bool RetSmallStructInRegABI =
11300         PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
11301     return SetCGInfo(
11302         new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI));
11303   }
11304   case llvm::Triple::ppc64:
11305     if (Triple.isOSAIX())
11306       return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ true));
11307 
11308     if (Triple.isOSBinFormatELF()) {
11309       PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
11310       if (getTarget().getABI() == "elfv2")
11311         Kind = PPC64_SVR4_ABIInfo::ELFv2;
11312       bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
11313 
11314       return SetCGInfo(
11315           new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, IsSoftFloat));
11316     }
11317     return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
11318   case llvm::Triple::ppc64le: {
11319     assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
11320     PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
11321     if (getTarget().getABI() == "elfv1")
11322       Kind = PPC64_SVR4_ABIInfo::ELFv1;
11323     bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
11324 
11325     return SetCGInfo(
11326         new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, IsSoftFloat));
11327   }
11328 
11329   case llvm::Triple::nvptx:
11330   case llvm::Triple::nvptx64:
11331     return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
11332 
11333   case llvm::Triple::msp430:
11334     return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
11335 
11336   case llvm::Triple::riscv32:
11337   case llvm::Triple::riscv64: {
11338     StringRef ABIStr = getTarget().getABI();
11339     unsigned XLen = getTarget().getPointerWidth(0);
11340     unsigned ABIFLen = 0;
11341     if (ABIStr.endswith("f"))
11342       ABIFLen = 32;
11343     else if (ABIStr.endswith("d"))
11344       ABIFLen = 64;
11345     return SetCGInfo(new RISCVTargetCodeGenInfo(Types, XLen, ABIFLen));
11346   }
11347 
11348   case llvm::Triple::systemz: {
11349     bool SoftFloat = CodeGenOpts.FloatABI == "soft";
11350     bool HasVector = !SoftFloat && getTarget().getABI() == "vector";
11351     return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector, SoftFloat));
11352   }
11353 
11354   case llvm::Triple::tce:
11355   case llvm::Triple::tcele:
11356     return SetCGInfo(new TCETargetCodeGenInfo(Types));
11357 
11358   case llvm::Triple::x86: {
11359     bool IsDarwinVectorABI = Triple.isOSDarwin();
11360     bool RetSmallStructInRegABI =
11361         X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
11362     bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
11363 
11364     if (Triple.getOS() == llvm::Triple::Win32) {
11365       return SetCGInfo(new WinX86_32TargetCodeGenInfo(
11366           Types, IsDarwinVectorABI, RetSmallStructInRegABI,
11367           IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
11368     } else {
11369       return SetCGInfo(new X86_32TargetCodeGenInfo(
11370           Types, IsDarwinVectorABI, RetSmallStructInRegABI,
11371           IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
11372           CodeGenOpts.FloatABI == "soft"));
11373     }
11374   }
11375 
11376   case llvm::Triple::x86_64: {
11377     StringRef ABI = getTarget().getABI();
11378     X86AVXABILevel AVXLevel =
11379         (ABI == "avx512"
11380              ? X86AVXABILevel::AVX512
11381              : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
11382 
11383     switch (Triple.getOS()) {
11384     case llvm::Triple::Win32:
11385       return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
11386     default:
11387       return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
11388     }
11389   }
11390   case llvm::Triple::hexagon:
11391     return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
11392   case llvm::Triple::lanai:
11393     return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
11394   case llvm::Triple::r600:
11395     return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
11396   case llvm::Triple::amdgcn:
11397     return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
11398   case llvm::Triple::sparc:
11399     return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
11400   case llvm::Triple::sparcv9:
11401     return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
11402   case llvm::Triple::xcore:
11403     return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
11404   case llvm::Triple::arc:
11405     return SetCGInfo(new ARCTargetCodeGenInfo(Types));
11406   case llvm::Triple::spir:
11407   case llvm::Triple::spir64:
11408     return SetCGInfo(new CommonSPIRTargetCodeGenInfo(Types));
11409   case llvm::Triple::spirv32:
11410   case llvm::Triple::spirv64:
11411     return SetCGInfo(new SPIRVTargetCodeGenInfo(Types));
11412   case llvm::Triple::ve:
11413     return SetCGInfo(new VETargetCodeGenInfo(Types));
11414   }
11415 }
11416 
11417 /// Create an OpenCL kernel for an enqueued block.
11418 ///
11419 /// The kernel has the same function type as the block invoke function. Its
11420 /// name is the name of the block invoke function postfixed with "_kernel".
11421 /// It simply calls the block invoke function then returns.
11422 llvm::Function *
11423 TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF,
11424                                              llvm::Function *Invoke,
11425                                              llvm::Value *BlockLiteral) const {
11426   auto *InvokeFT = Invoke->getFunctionType();
11427   llvm::SmallVector<llvm::Type *, 2> ArgTys;
11428   for (auto &P : InvokeFT->params())
11429     ArgTys.push_back(P);
11430   auto &C = CGF.getLLVMContext();
11431   std::string Name = Invoke->getName().str() + "_kernel";
11432   auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
11433   auto *F = llvm::Function::Create(FT, llvm::GlobalValue::ExternalLinkage, Name,
11434                                    &CGF.CGM.getModule());
11435   auto IP = CGF.Builder.saveIP();
11436   auto *BB = llvm::BasicBlock::Create(C, "entry", F);
11437   auto &Builder = CGF.Builder;
11438   Builder.SetInsertPoint(BB);
11439   llvm::SmallVector<llvm::Value *, 2> Args;
11440   for (auto &A : F->args())
11441     Args.push_back(&A);
11442   llvm::CallInst *call = Builder.CreateCall(Invoke, Args);
11443   call->setCallingConv(Invoke->getCallingConv());
11444   Builder.CreateRetVoid();
11445   Builder.restoreIP(IP);
11446   return F;
11447 }
11448 
11449 /// Create an OpenCL kernel for an enqueued block.
11450 ///
11451 /// The type of the first argument (the block literal) is the struct type
11452 /// of the block literal instead of a pointer type. The first argument
11453 /// (block literal) is passed directly by value to the kernel. The kernel
11454 /// allocates the same type of struct on stack and stores the block literal
11455 /// to it and passes its pointer to the block invoke function. The kernel
11456 /// has "enqueued-block" function attribute and kernel argument metadata.
11457 llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel(
11458     CodeGenFunction &CGF, llvm::Function *Invoke,
11459     llvm::Value *BlockLiteral) const {
11460   auto &Builder = CGF.Builder;
11461   auto &C = CGF.getLLVMContext();
11462 
11463   auto *BlockTy = BlockLiteral->getType()->getPointerElementType();
11464   auto *InvokeFT = Invoke->getFunctionType();
11465   llvm::SmallVector<llvm::Type *, 2> ArgTys;
11466   llvm::SmallVector<llvm::Metadata *, 8> AddressQuals;
11467   llvm::SmallVector<llvm::Metadata *, 8> AccessQuals;
11468   llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames;
11469   llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames;
11470   llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals;
11471   llvm::SmallVector<llvm::Metadata *, 8> ArgNames;
11472 
11473   ArgTys.push_back(BlockTy);
11474   ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
11475   AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0)));
11476   ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
11477   ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
11478   AccessQuals.push_back(llvm::MDString::get(C, "none"));
11479   ArgNames.push_back(llvm::MDString::get(C, "block_literal"));
11480   for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) {
11481     ArgTys.push_back(InvokeFT->getParamType(I));
11482     ArgTypeNames.push_back(llvm::MDString::get(C, "void*"));
11483     AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3)));
11484     AccessQuals.push_back(llvm::MDString::get(C, "none"));
11485     ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*"));
11486     ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
11487     ArgNames.push_back(
11488         llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str()));
11489   }
11490   std::string Name = Invoke->getName().str() + "_kernel";
11491   auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
11492   auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
11493                                    &CGF.CGM.getModule());
11494   F->addFnAttr("enqueued-block");
11495   auto IP = CGF.Builder.saveIP();
11496   auto *BB = llvm::BasicBlock::Create(C, "entry", F);
11497   Builder.SetInsertPoint(BB);
11498   const auto BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlign(BlockTy);
11499   auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr);
11500   BlockPtr->setAlignment(BlockAlign);
11501   Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign);
11502   auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0));
11503   llvm::SmallVector<llvm::Value *, 2> Args;
11504   Args.push_back(Cast);
11505   for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I)
11506     Args.push_back(I);
11507   llvm::CallInst *call = Builder.CreateCall(Invoke, Args);
11508   call->setCallingConv(Invoke->getCallingConv());
11509   Builder.CreateRetVoid();
11510   Builder.restoreIP(IP);
11511 
11512   F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals));
11513   F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals));
11514   F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames));
11515   F->setMetadata("kernel_arg_base_type",
11516                  llvm::MDNode::get(C, ArgBaseTypeNames));
11517   F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals));
11518   if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
11519     F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames));
11520 
11521   return F;
11522 }
11523